From 0ebe6c6079f391b53765a580fa0869585f9adb61 Mon Sep 17 00:00:00 2001 From: igarri Date: Thu, 22 Apr 2021 13:19:39 +0100 Subject: [PATCH 001/811] Setup Table model and Table view --- .../AzToolsFramework/AssetBrowserTableModel.h | 36 ++ .../AssetBrowser/AssetBrowserTableModel.cpp | 37 ++ .../AssetBrowser/AssetBrowserTableModel.h | 36 ++ .../Entries/AssetBrowserEntry.cpp | 5 +- .../AssetBrowser/Entries/AssetBrowserEntry.h | 2 + .../Entries/FolderAssetBrowserEntry.cpp | 1 + .../Entries/RootAssetBrowserEntry.cpp | 3 + .../Views/AssetBrowserTableView.cpp | 65 +++ .../Views/AssetBrowserTableView.h | 56 +++ .../AssetBrowser/Views/EntryDelegate.cpp | 44 +-- .../aztoolsframework_files.cmake | 4 + .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 17 + .../AzAssetBrowser/AzAssetBrowserWindow.h | 3 + .../AzAssetBrowser/AzAssetBrowserWindow.ui | 369 ++++++++++-------- 14 files changed, 492 insertions(+), 186 deletions(-) create mode 100644 Code/Framework/AzToolsFramework/AssetBrowserTableModel.h create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h diff --git a/Code/Framework/AzToolsFramework/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AssetBrowserTableModel.h new file mode 100644 index 0000000000..4e65b3921c --- /dev/null +++ b/Code/Framework/AzToolsFramework/AssetBrowserTableModel.h @@ -0,0 +1,36 @@ +#pragma once +#if !defined(Q_MOC_RUN) +#include +#include +#include + +#include +#include +#include + +AZ_PUSH_DISABLE_WARNING( + 4251, "-Wunknown-warning-option") // 4251: class '...' needs to have dll-interface to be used by clients of class '...' +#include +#include +#include +#endif +AZ_POP_DISABLE_WARNING +namespace AzToolsFramework +{ + namespace AssetBrowser + { + class AssetBrowserTableModel + : public QSortFilterProxyModel + { + Q_OBJECT + public: + AZ_CLASS_ALLOCATOR(AssetBrowserTableModel, AZ::SystemAllocator, 0); + explicit AssetBrowserTableModel(QObject* parent = nullptr); + + QModelIndex mapToSource(const QModelIndex &proxyIndex) const override; + QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override; + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + }; + } +} diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp new file mode 100644 index 0000000000..a6e5cde6d8 --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -0,0 +1,37 @@ +#include "AssetBrowserTableModel.h" +namespace AzToolsFramework +{ + namespace AssetBrowser + { + AssetBrowserTableModel::AssetBrowserTableModel(QObject* parent /* = nullptr */) + : QSortFilterProxyModel(parent) + { + } + QModelIndex AssetBrowserTableModel::mapToSource(const QModelIndex& proxyIndex) const + { + AZ_UNUSED(proxyIndex); + return QModelIndex(); + } + QModelIndex AssetBrowserTableModel::mapFromSource(const QModelIndex& sourceIndex) const + { + AZ_UNUSED(sourceIndex); + return QModelIndex(); + } + QModelIndex AssetBrowserTableModel::index(int row, int column, const QModelIndex& parent) const + { + AZ_UNUSED(row); + AZ_UNUSED(column); + AZ_UNUSED(parent); + + return QModelIndex(); + } + QVariant AssetBrowserTableModel::data(const QModelIndex& index, int role) const + { + AZ_UNUSED(index); + AZ_UNUSED(role); + + return QVariant(); + } + } // namespace AssetBrowser +} // namespace AzToolsFramework +#include "AssetBrowser/moc_AssetBrowserTableModel.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h new file mode 100644 index 0000000000..4e65b3921c --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -0,0 +1,36 @@ +#pragma once +#if !defined(Q_MOC_RUN) +#include +#include +#include + +#include +#include +#include + +AZ_PUSH_DISABLE_WARNING( + 4251, "-Wunknown-warning-option") // 4251: class '...' needs to have dll-interface to be used by clients of class '...' +#include +#include +#include +#endif +AZ_POP_DISABLE_WARNING +namespace AzToolsFramework +{ + namespace AssetBrowser + { + class AssetBrowserTableModel + : public QSortFilterProxyModel + { + Q_OBJECT + public: + AZ_CLASS_ALLOCATOR(AssetBrowserTableModel, AZ::SystemAllocator, 0); + explicit AssetBrowserTableModel(QObject* parent = nullptr); + + QModelIndex mapToSource(const QModelIndex &proxyIndex) const override; + QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override; + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + }; + } +} diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp index 85d5eaecea..8ee8f44137 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp @@ -46,6 +46,7 @@ namespace AzToolsFramework const char* AssetBrowserEntry::m_columnNames[] = { "Name", + "Path", "Source ID", "Fingerprint", "Guid", @@ -128,6 +129,8 @@ namespace AzToolsFramework return QString::fromUtf8(m_name.c_str()); case Column::DisplayName: return m_displayName; + case Column::Path: + return m_displayPath; default: return QVariant(); } @@ -283,4 +286,4 @@ namespace AzToolsFramework } // namespace AssetBrowser } // namespace AzToolsFramework -#include "AssetBrowser/Entries/moc_AssetBrowserEntry.cpp" \ No newline at end of file +#include "AssetBrowser/Entries/moc_AssetBrowserEntry.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h index 6f0eceeeea..ac5470a136 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h @@ -68,6 +68,7 @@ namespace AzToolsFramework enum class Column { Name, + Path, SourceID, Fingerprint, Guid, @@ -135,6 +136,7 @@ namespace AzToolsFramework protected: AZStd::string m_name; QString m_displayName; + QString m_displayPath; AZStd::string m_relativePath; AZStd::string m_fullPath; AZStd::vector m_children; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp index 88b26ad5ee..0312edbc51 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp @@ -43,6 +43,7 @@ namespace AzToolsFramework void FolderAssetBrowserEntry::UpdateChildPaths(AssetBrowserEntry* child) const { child->m_relativePath = m_relativePath + AZ_CORRECT_DATABASE_SEPARATOR + child->m_name; + child->m_displayPath = QString::fromUtf8(child->m_relativePath.c_str()); child->m_fullPath = m_fullPath + AZ_CORRECT_DATABASE_SEPARATOR + child->m_name; AssetBrowserEntry::UpdateChildPaths(child); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp index ada961711a..2ee71c8719 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp @@ -292,6 +292,9 @@ namespace AzToolsFramework product->m_assetType = productWithUuidDatabaseEntry.second.m_assetType; product->m_assetType.ToString(product->m_assetTypeString); AZ::Data::AssetCatalogRequestBus::BroadcastResult(product->m_relativePath, &AZ::Data::AssetCatalogRequests::GetAssetPathById, assetId); + QString displayPath = QString::fromUtf8(product->m_relativePath.c_str()); + displayPath.remove(QString("/" + QString::fromUtf8(product->m_name.c_str()))); + product->m_displayPath = displayPath; EntryCache::GetInstance()->m_productAssetIdMap[assetId] = product; if (needsAdd) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp new file mode 100644 index 0000000000..ee86f372db --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -0,0 +1,65 @@ +#include "AssetBrowserTableView.h" + +#pragma optimize("", off) +namespace AzToolsFramework +{ + namespace AssetBrowser + { + AssetBrowserTableView::AssetBrowserTableView(QWidget* parent) + : QTableView(parent) + { + AssetBrowserViewRequestBus::Handler::BusConnect(); + AssetBrowserComponentNotificationBus::Handler::BusConnect(); + } + AssetBrowserTableView::~AssetBrowserTableView() + { + AssetBrowserViewRequestBus::Handler::BusDisconnect(); + AssetBrowserComponentNotificationBus::Handler::BusDisconnect(); + } + void AssetBrowserTableView::setModel(QAbstractItemModel* model) + { + //m_assetBrowserSortFilterProxyModel = qobject_cast(model); + //AZ_Assert(m_assetBrowserSortFilterProxyModel, "Expecting AssetBrowserTableFilterModel"); + //m_assetBrowserModel = qobject_cast(m_assetBrowserSortFilterProxyModel->sourceModel()); + QTableView::setModel(model); + } + void AssetBrowserTableView::SetName(const QString& name) + { + m_name = name; + bool isAssetBrowserComponentReady = false; + AssetBrowserComponentRequestBus::BroadcastResult(isAssetBrowserComponentReady, &AssetBrowserComponentRequests::AreEntriesReady); + if (isAssetBrowserComponentReady) + { + OnAssetBrowserComponentReady(); + } + } + AZStd::vector AssetBrowserTableView::GetSelectedAssets() const + { + return AZStd::vector(); + } + + void AssetBrowserTableView::SelectProduct(AZ::Data::AssetId assetID) + { + AZ_UNUSED(assetID); + } + + void AssetBrowserTableView::SelectFileAtPath(const AZStd::string& assetPath) + { + AZ_UNUSED(assetPath); + } + + void AssetBrowserTableView::ClearFilter() + { + } + + void AssetBrowserTableView::Update() + { + } + + //void AssetBrowserTableView::OnAssetBrowserComponentReady() + //{ + //} + } // namespace AssetBrowser +} // namespace AzToolsFramework +#pragma optimize("", on) +#include "AssetBrowser/Views/moc_AssetBrowserTableView.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h new file mode 100644 index 0000000000..04881aa782 --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -0,0 +1,56 @@ +#pragma once +#if !defined(Q_MOC_RUN) +#include +#include +#include + +#include +//#include + +#include +#include +#include +#endif + +namespace AzToolsFramework +{ + namespace AssetBrowser + { + class AssetBrowserEntry; + class AssetBrowserModel; + class AssetBrowserFilterModel; + class EntryDelegate; + + class AssetBrowserTableView + : public QTableView + , public AssetBrowserViewRequestBus::Handler + , public AssetBrowserComponentNotificationBus::Handler + { + Q_OBJECT + public: + explicit AssetBrowserTableView(QWidget* parent = nullptr); + ~AssetBrowserTableView() override; + + void setModel(QAbstractItemModel *model) override; + void SetName(const QString& name); + + AZStd::vector GetSelectedAssets() const; + + ////////////////////////////////////////////////////////////////////////// + // AssetBrowserViewRequestBus + virtual void SelectProduct(AZ::Data::AssetId assetID) override; + virtual void SelectFileAtPath(const AZStd::string& assetPath) override; + virtual void ClearFilter() override; + virtual void Update() override; + + ////////////////////////////////////////////////////////////////////////// + // AssetBrowserComponentNotificationBus + //void OnAssetBrowserComponentReady() override; + ////////////////////////////////////////////////////////////////////////// + private: + QString m_name; + + + }; + } // namespace AssetBrowser +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp index abc290a406..42e161cf37 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp @@ -74,34 +74,34 @@ namespace AzToolsFramework QPoint iconTopLeft(remainingRect.x(), remainingRect.y() + (remainingRect.height() / 2) - (m_iconSize / 2)); auto sourceEntry = azrtti_cast(entry); - - int thumbX = DrawThumbnail(painter, iconTopLeft, iconSize, entry->GetThumbnailKey()); - QPalette actualPalette(option.palette); - - if (sourceEntry) + if (index.column() == static_cast(AssetBrowserEntry::Column::Name)) { - if (m_showSourceControl) + int thumbX = DrawThumbnail(painter, iconTopLeft, iconSize, entry->GetThumbnailKey()); + if (sourceEntry) { - DrawThumbnail(painter, iconTopLeft, iconSize, sourceEntry->GetSourceControlThumbnailKey()); - } - // sources with no children should be greyed out. - if (sourceEntry->GetChildCount() == 0) - { - isEnabled = false; // draw in disabled style. - actualPalette.setCurrentColorGroup(QPalette::Disabled); + if (m_showSourceControl) + { + DrawThumbnail(painter, iconTopLeft, iconSize, sourceEntry->GetSourceControlThumbnailKey()); + } + // sources with no children should be greyed out. + if (sourceEntry->GetChildCount() == 0) + { + isEnabled = false; // draw in disabled style. + actualPalette.setCurrentColorGroup(QPalette::Disabled); + } } + + remainingRect.adjust(thumbX, 0, 0, 0); // bump it to the right by the size of the thumbnail + remainingRect.adjust(ENTRY_SPACING_LEFT_PIXELS, 0, 0, 0); // bump it to the right by the spacing. } + QString displayString = qvariant_cast(index.data(index.column())); - remainingRect.adjust(thumbX, 0, 0, 0); // bump it to the right by the size of the thumbnail - remainingRect.adjust(ENTRY_SPACING_LEFT_PIXELS, 0, 0, 0); // bump it to the right by the spacing. - - style->drawItemText(painter, - remainingRect, - option.displayAlignment, - actualPalette, - isEnabled, - entry->GetDisplayName(), + style->drawItemText( + painter, remainingRect, option.displayAlignment, actualPalette, isEnabled, + index.column() == static_cast(AssetBrowserEntry::Column::Name) + ? qvariant_cast(entry->data(static_cast(AssetBrowserEntry::Column::Name))) + : qvariant_cast(entry->data(static_cast(AssetBrowserEntry::Column::Path))), isSelected ? QPalette::HighlightedText : QPalette::Text); } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index 2939bb44ad..51ca1a3fdb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -545,6 +545,8 @@ set(FILES AssetBrowser/AssetBrowserEntry.h AssetBrowser/AssetBrowserFilterModel.cpp AssetBrowser/AssetBrowserFilterModel.h + AssetBrowser/AssetBrowserTableModel.cpp + AssetBrowser/AssetBrowserTableModel.h AssetBrowser/AssetBrowserModel.cpp AssetBrowser/AssetBrowserModel.h AssetBrowser/AssetEntryChange.h @@ -555,6 +557,8 @@ set(FILES AssetBrowser/EBusFindAssetTypeByName.h AssetBrowser/Views/AssetBrowserTreeView.cpp AssetBrowser/Views/AssetBrowserTreeView.h + AssetBrowser/Views/AssetBrowserTableView.cpp + AssetBrowser/Views/AssetBrowserTableView.h AssetBrowser/Views/EntryDelegate.cpp AssetBrowser/Views/EntryDelegate.h AssetBrowser/Views/AssetBrowserFolderWidget.cpp diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 0b23739bb8..733044746e 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include // AzQtComponents @@ -66,6 +67,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) : QWidget(parent) , m_ui(new Ui::AzAssetBrowserWindowClass()) , m_filterModel(new AzToolsFramework::AssetBrowser::AssetBrowserFilterModel(parent)) + , m_tableModel(new AzToolsFramework::AssetBrowser::AssetBrowserTableModel(parent)) { m_ui->setupUi(this); m_ui->m_searchWidget->Setup(true, true); @@ -76,7 +78,12 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_filterModel->setSourceModel(m_assetBrowserModel); m_filterModel->SetFilter(m_ui->m_searchWidget->GetFilter()); + m_tableModel->setSourceModel(m_filterModel.data()); + m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); + m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); + + m_ui->m_assetBrowserTableViewWidget->setVisible(false); connect(m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), &AssetBrowserFilterModel::filterUpdatedSlot); @@ -92,7 +99,11 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, &SearchWidget::ClearStringFilter); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, &SearchWidget::ClearTypeFilter); + m_ui->m_assetBrowserTreeViewWidget->SetName("AssetBrowserTreeView_main"); + m_ui->m_assetBrowserTableViewWidget->SetName("AssetBrowserTableView_main"); + + connect(m_ui->m_viewSwitcherCheckBox, &QCheckBox::stateChanged, this, &AzAssetBrowserWindow::SwitchDisplayView); } AzAssetBrowserWindow::~AzAssetBrowserWindow() @@ -220,4 +231,10 @@ void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& } +void AzAssetBrowserWindow::SwitchDisplayView(const int state) +{ + m_ui->m_assetBrowserTableViewWidget->setVisible(state); + m_ui->m_assetBrowserTreeViewWidget->setVisible(!state); +} + #include diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h index 263712dfe2..1a5604b98f 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h @@ -29,6 +29,7 @@ namespace AzToolsFramework namespace AssetBrowser { class AssetBrowserFilterModel; + class AssetBrowserTableModel; class AssetBrowserModel; } } @@ -53,6 +54,7 @@ private: QScopedPointer m_ui; QScopedPointer m_filterModel; + QScopedPointer m_tableModel; AzToolsFramework::AssetBrowser::AssetBrowserModel* m_assetBrowserModel; void UpdatePreview() const; @@ -60,6 +62,7 @@ private: private Q_SLOTS: void SelectionChangedSlot(const QItemSelection& selected, const QItemSelection& deselected) const; void DoubleClickedItem(const QModelIndex& element); + void SwitchDisplayView(const int state); }; extern const char* AZ_ASSET_BROWSER_PREVIEW_NAME; diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui index d6a6b4b8df..d9e42ef906 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui @@ -1,168 +1,211 @@ - AzAssetBrowserWindowClass - - - - 0 - 0 - 691 - 554 - - - - Asset Browser - - - - 0 - - - - - - 1 - 1 - - - - true - - - - - 0 - 0 - 671 - 534 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - - 0 - 0 - - - - + AzAssetBrowserWindowClass + + + + 0 + 0 + 691 + 554 + + + + Asset Browser + + + + 0 + + + + + + 1 + 1 + + + + true + + + + + 0 + 0 + 671 + 534 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + 0 + 0 + + + + + + + + Switch View + + + + + + + + + + 0 + 0 + + + + Qt::Horizontal + + + false + + + + + 0 + 0 + + + + vertical-align: top + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed + + + QAbstractItemView::DropOnly + + + QAbstractItemView::SingleSelection + + + QAbstractItemView::SelectRows + + + QAbstractItemView::ScrollPerPixel + + + false + + + true + + + + + + + + 1 + 0 + + + + QAbstractItemView::DragOnly + + + + + + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + + + + + + - - - - - - 0 - 0 - - - - Qt::Horizontal - - - false - - - - - 0 - 0 - - - - vertical-align: top - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 1 - 0 - - - - QAbstractItemView::DragOnly - - - - - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - - - - - - - - - AzToolsFramework::AssetBrowser::SearchWidget - QWidget -
AzToolsFramework/AssetBrowser/Search/SearchWidget.h
- 1 -
- - AzToolsFramework::AssetBrowser::AssetBrowserTreeView - QTreeView -
AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.h
-
- - AzToolsFramework::AssetBrowser::PreviewerFrame - QFrame -
AzToolsFramework/AssetBrowser/Previewer/PreviewerFrame.h
- 1 -
-
- - + + + AzToolsFramework::AssetBrowser::SearchWidget + QWidget +
AzToolsFramework/AssetBrowser/Search/SearchWidget.h
+ 1 +
+ + AzToolsFramework::AssetBrowser::AssetBrowserTreeView + QTreeView +
AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.h
+
+ + AzToolsFramework::AssetBrowser::PreviewerFrame + QFrame +
AzToolsFramework/AssetBrowser/Previewer/PreviewerFrame.h
+ 1 +
+ + AzToolsFramework::AssetBrowser::AssetBrowserTableView + QTableView +
AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h
+
+
+ +
From b7c2495911484fa0e22a57e77534c3fffdb678d0 Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 28 Apr 2021 09:38:43 +0100 Subject: [PATCH 002/811] Working base --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 2 + .../AssetBrowser/AssetBrowserFilterModel.h | 1 + .../AssetBrowser/AssetBrowserTableModel.cpp | 94 ++++++++++++++++--- .../AssetBrowser/AssetBrowserTableModel.h | 18 +++- .../Views/AssetBrowserTableView.cpp | 74 +++++++++++++-- .../Views/AssetBrowserTableView.h | 17 +++- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 4 + 7 files changed, 184 insertions(+), 26 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 9c60b6cd35..42498eb76e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -62,6 +62,7 @@ namespace AzToolsFramework invalidateFilter(); m_invalidateFilter = false; } + Q_EMIT entriesUpdated(); } bool AssetBrowserFilterModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const @@ -162,6 +163,7 @@ namespace AzToolsFramework { m_alreadyRecomputingFilters = false; FilterUpdatedSlotImmediate(); + //beginInsertRows() } ); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h index f9423b2534..6aa1a08e45 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h @@ -53,6 +53,7 @@ namespace AzToolsFramework Q_SIGNALS: void filterChanged(); + void entriesUpdated(); ////////////////////////////////////////////////////////////////////////// //QSortFilterProxyModel diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index a6e5cde6d8..e7a49b2d99 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -6,31 +6,97 @@ namespace AzToolsFramework AssetBrowserTableModel::AssetBrowserTableModel(QObject* parent /* = nullptr */) : QSortFilterProxyModel(parent) { + m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); + m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); } QModelIndex AssetBrowserTableModel::mapToSource(const QModelIndex& proxyIndex) const { - AZ_UNUSED(proxyIndex); - return QModelIndex(); + Q_ASSERT(!proxyIndex.isValid() || proxyIndex.model() == this); + if (!proxyIndex.isValid()) + { + return QModelIndex(); + } + return m_indexMap[proxyIndex.row()]; } QModelIndex AssetBrowserTableModel::mapFromSource(const QModelIndex& sourceIndex) const { - AZ_UNUSED(sourceIndex); - return QModelIndex(); + Q_ASSERT(!sourceIndex.isValid() || sourceIndex.model() == sourceModel()); + if (!sourceIndex.isValid()) + { + return QModelIndex(); + } + return createIndex(m_rowMap[sourceIndex], sourceIndex.column(), sourceIndex.internalPointer()); } - QModelIndex AssetBrowserTableModel::index(int row, int column, const QModelIndex& parent) const - { - AZ_UNUSED(row); - AZ_UNUSED(column); - AZ_UNUSED(parent); + //QModelIndex AssetBrowserTableModel::index(int row, int column, const QModelIndex& parent) const + //{ - return QModelIndex(); - } + // //return parent.isValid() ? QModelIndex() : createIndex(row, column , m_indexMap[row].internalPointer()); + // if (!parent.isValid()) + // { + // QModelIndex(); + // } + // return createIndex(row, column, m_indexMap[row].internalPointer()); + //} QVariant AssetBrowserTableModel::data(const QModelIndex& index, int role) const { - AZ_UNUSED(index); - AZ_UNUSED(role); + //AZ_UNUSED(role); + auto sourceIndex = mapToSource(index); + if (!sourceIndex.isValid()) + return QVariant(); - return QVariant(); + AssetBrowserEntry* entry = GetAssetEntry(sourceIndex); // static_cast(sourceIndex.internalPointer()); + if (entry == nullptr) + { + AZ_Assert(false, "ERROR - index internal pointer not pointing to an AssetEntry. Tree provided by the AssetBrowser invalid?"); + return Qt::PartiallyChecked; + } + + return sourceIndex.data(role); //return entry->data(index.column()); + //return QVariant::fromValue(entry); + + } + bool AssetBrowserTableModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const + { + AZ_UNUSED(source_row); + AZ_UNUSED(source_parent); + return true; + } + bool AssetBrowserTableModel::filterAcceptsColumn(int source_column, const QModelIndex&) const + { + return m_showColumn.find(source_column) != m_showColumn.end(); + } + int AssetBrowserTableModel::BuildMap(const QAbstractItemModel* model, const QModelIndex& parent, int row) + { + int rows = model ? model->rowCount(parent) : 0; + for (int i = 0; i < rows; ++i) + { + auto index = model->index(i, 0, parent); + + m_rowMap[index] = row; + m_indexMap[row] = index; + row = row + 1; + if (model->hasChildren(index)) + { + row = BuildMap(model, index, row); + } + } + return row; + } + AssetBrowserEntry* AssetBrowserTableModel::GetAssetEntry(QModelIndex index) const + { + if (index.isValid()) + { + return static_cast(index.internalPointer()); + } + else + { + AZ_Error("AssetBrowser", false, "Invalid Source Index provided to GetAssetEntry."); + return nullptr; + } + } + void AssetBrowserTableModel::UpdateMap() + { + BuildMap(sourceModel()); } } // namespace AssetBrowser } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index 4e65b3921c..ef87ad8512 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -29,8 +29,24 @@ namespace AzToolsFramework QModelIndex mapToSource(const QModelIndex &proxyIndex) const override; QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override; - QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; + //QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + + public Q_SLOTS: + void UpdateMap(); + + protected: + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; + bool filterAcceptsColumn(int source_column, const QModelIndex& /*source_parent*/) const override; + + private: + int BuildMap(const QAbstractItemModel* model, const QModelIndex& parent = QModelIndex(), int row = 0); + AssetBrowserEntry* GetAssetEntry(QModelIndex index) const; + + private: + AZStd::fixed_unordered_set(AssetBrowserEntry::Column::Count)> m_showColumn; + QMap m_indexMap; + QMap m_rowMap; }; } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index ee86f372db..927deb0039 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -1,5 +1,34 @@ -#include "AssetBrowserTableView.h" +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +AZ_PUSH_DISABLE_WARNING( + 4244 4251 4800, "-Wunknown-warning-option") // conversion from 'int' to 'float', possible loss of data, needs to have dll-interface to + // be used by clients of class 'QFlags::Int': forcing value to bool + // 'true' or 'false' (performance warning) +#include +#include +#include +#include +#include +#include +#include +AZ_POP_DISABLE_WARNING #pragma optimize("", off) namespace AzToolsFramework { @@ -7,7 +36,19 @@ namespace AzToolsFramework { AssetBrowserTableView::AssetBrowserTableView(QWidget* parent) : QTableView(parent) + , m_delegate(new EntryDelegate(this)) + { + setSortingEnabled(true); + setItemDelegate(m_delegate); + // header()->hide(); + setContextMenuPolicy(Qt::CustomContextMenu); + + setMouseTracking(true); + + connect(this, &QTableView::customContextMenuRequested, this, &AssetBrowserTableView::OnContextMenu); + //connect(m_scTimer, &QTimer::timeout, this, &AssetBrowserTreeView::OnUpdateSCThumbnailsList); + AssetBrowserViewRequestBus::Handler::BusConnect(); AssetBrowserComponentNotificationBus::Handler::BusConnect(); } @@ -18,9 +59,9 @@ namespace AzToolsFramework } void AssetBrowserTableView::setModel(QAbstractItemModel* model) { - //m_assetBrowserSortFilterProxyModel = qobject_cast(model); - //AZ_Assert(m_assetBrowserSortFilterProxyModel, "Expecting AssetBrowserTableFilterModel"); - //m_assetBrowserModel = qobject_cast(m_assetBrowserSortFilterProxyModel->sourceModel()); + m_sourceModel = qobject_cast(model); + AZ_Assert(m_sourceModel, "Expecting AssetBrowserTableModel"); + m_sourceFilterModel = qobject_cast(m_sourceModel->sourceModel()); QTableView::setModel(model); } void AssetBrowserTableView::SetName(const QString& name) @@ -54,11 +95,30 @@ namespace AzToolsFramework void AssetBrowserTableView::Update() { + update(); } - //void AssetBrowserTableView::OnAssetBrowserComponentReady() - //{ - //} + void AssetBrowserTableView::OnAssetBrowserComponentReady() + { + } + + void AssetBrowserTableView::OnContextMenu(const QPoint& point) + { + AZ_UNUSED(point); + + auto selectedAssets = GetSelectedAssets(); + if (selectedAssets.size() != 1) + { + return; + } + + QMenu menu(this); + AssetBrowserInteractionNotificationBus::Broadcast(&AssetBrowserInteractionNotificationBus::Events::AddContextMenuActions, this, &menu, selectedAssets); + if (!menu.isEmpty()) + { + menu.exec(QCursor::pos()); + } + } } // namespace AssetBrowser } // namespace AzToolsFramework #pragma optimize("", on) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h index 04881aa782..bec24cca9b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -5,7 +5,7 @@ #include #include -//#include +#include #include #include @@ -17,7 +17,7 @@ namespace AzToolsFramework namespace AssetBrowser { class AssetBrowserEntry; - class AssetBrowserModel; + class AssetBrowserTableModel; class AssetBrowserFilterModel; class EntryDelegate; @@ -45,11 +45,20 @@ namespace AzToolsFramework ////////////////////////////////////////////////////////////////////////// // AssetBrowserComponentNotificationBus - //void OnAssetBrowserComponentReady() override; + void OnAssetBrowserComponentReady() override; ////////////////////////////////////////////////////////////////////////// + + private Q_SLOTS: + void OnContextMenu(const QPoint& point); + + //! Get all visible source entries and place them in a queue to update their source control status + //void OnUpdateSCThumbnailsList(); + private: QString m_name; - + QPointer m_sourceFilterModel = nullptr; + QPointer m_sourceModel = nullptr; + EntryDelegate* m_delegate = nullptr; }; } // namespace AssetBrowser diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 733044746e..d67ee0d0ca 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -78,13 +78,17 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_filterModel->setSourceModel(m_assetBrowserModel); m_filterModel->SetFilter(m_ui->m_searchWidget->GetFilter()); + m_tableModel->setFilterRole(Qt::DisplayRole); m_tableModel->setSourceModel(m_filterModel.data()); + //m_tableModel->setSourceModel(m_assetBrowserModel); m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); m_ui->m_assetBrowserTableViewWidget->setVisible(false); + connect(m_filterModel.data(), &AssetBrowserFilterModel::entriesUpdated, m_tableModel.data(), &AssetBrowserTableModel::UpdateMap); + connect(m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), &AssetBrowserFilterModel::filterUpdatedSlot); connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, this, [this]() From 4630c82df0f5280414b01aa5cf884a06df1dd38c Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 28 Apr 2021 14:05:36 -0700 Subject: [PATCH 003/811] Preventing certain projects from showing up in the project's solution --- CMakeLists.txt | 62 +++++++++++++++++++++--------------------- cmake/CMakeFiles.cmake | 12 ++++---- 2 files changed, 38 insertions(+), 36 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ad5cd9f431..20c964ed06 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,50 +58,50 @@ include(cmake/CMakeFiles.cmake) include(cmake/Projects.cmake) if(NOT INSTALLED_ENGINE) + # Add the rest of the targets add_subdirectory(Code) add_subdirectory(Gems) -else() - ly_find_o3de_packages() -endif() + add_subdirectory(scripts) -set(enabled_platforms + # SPEC-1417 will investigate and fix this + if(NOT PAL_PLATFORM_NAME STREQUAL "Mac") + add_subdirectory(Tools/LyTestTools/tests/) + add_subdirectory(Tools/RemoteConsole/ly_remote_console/tests/) + endif() + + set(enabled_platforms ${PAL_PLATFORM_NAME} ${LY_PAL_TOOLS_ENABLED}) -foreach(restricted_platform ${PAL_RESTRICTED_PLATFORMS}) - if(restricted_platform IN_LIST enabled_platforms) - add_subdirectory(restricted/${restricted_platform}) - endif() -endforeach() + foreach(restricted_platform ${PAL_RESTRICTED_PLATFORMS}) + if(restricted_platform IN_LIST enabled_platforms) + add_subdirectory(restricted/${restricted_platform}) + endif() + endforeach() -add_subdirectory(scripts) + # Loop over the additional external subdirectories and invoke add_subdirectory on them + foreach(external_directory ${LY_EXTERNAL_SUBDIRS}) + # Hash the extenal_directory name and append it to the Binary Directory section of add_subdirectory + # This is to deal with potential situations where multiple external directories has the same last directory name + # For example if D:/Company1/RayTracingGem and F:/Company2/Path/RayTracingGem were both added as a subdirectory + file(REAL_PATH ${external_directory} full_directory_path) + string(SHA256 full_directory_hash ${full_directory_path}) + # Truncate the full_directory_hash down to 8 characters to avoid hitting the Windows 260 character path limit + # when the external subdirectory contains relative paths of significant length + string(SUBSTRING ${full_directory_hash} 0 8 full_directory_hash) + # Use the last directory as the suffix path to use for the Binary Directory + get_filename_component(directory_name ${external_directory} NAME) + add_subdirectory(${external_directory} ${CMAKE_BINARY_DIR}/${directory_name}-${full_directory_hash}) + endforeach() -# SPEC-1417 will investigate and fix this -if(NOT PAL_PLATFORM_NAME STREQUAL "Mac") - add_subdirectory(Tools/LyTestTools/tests/) - add_subdirectory(Tools/RemoteConsole/ly_remote_console/tests/) +else() + ly_find_o3de_packages() endif() ################################################################################ # Post-processing ################################################################################ - -# Loop over the additional external subdirectories and invoke add_subdirectory on them -foreach(external_directory ${LY_EXTERNAL_SUBDIRS}) - # Hash the extenal_directory name and append it to the Binary Directory section of add_subdirectory - # This is to deal with potential situations where multiple external directories has the same last directory name - # For example if D:/Company1/RayTracingGem and F:/Company2/Path/RayTracingGem were both added as a subdirectory - file(REAL_PATH ${external_directory} full_directory_path) - string(SHA256 full_directory_hash ${full_directory_path}) - # Truncate the full_directory_hash down to 8 characters to avoid hitting the Windows 260 character path limit - # when the external subdirectory contains relative paths of significant length - string(SUBSTRING ${full_directory_hash} 0 8 full_directory_hash) - # Use the last directory as the suffix path to use for the Binary Directory - get_filename_component(directory_name ${external_directory} NAME) - add_subdirectory(${external_directory} ${CMAKE_BINARY_DIR}/${directory_name}-${full_directory_hash}) -endforeach() - # The following steps have to be done after all targets are registered: # 1. generate a settings registry .setreg file for all ly_add_project_dependencies() and ly_add_target_dependencies() calls # to provide applications with the filenames of gem modules to load @@ -124,6 +124,6 @@ ly_test_impact_post_step() if(NOT INSTALLED_ENGINE) ly_setup_o3de_install() - # IMPORTANT: must be included last + # 7. CPack information (to be included after install) include(cmake/CPack.cmake) endif() diff --git a/cmake/CMakeFiles.cmake b/cmake/CMakeFiles.cmake index 952f9b5eb8..77c2eb75e1 100644 --- a/cmake/CMakeFiles.cmake +++ b/cmake/CMakeFiles.cmake @@ -9,8 +9,10 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -# Add all cmake files in a project so they can be handled from within the IDE -ly_include_cmake_file_list(cmake/cmake_files.cmake) -add_custom_target(CMakeFiles SOURCES ${ALLFILES}) -ly_source_groups_from_folders("${ALLFILES}") -unset(ALLFILES) \ No newline at end of file +if(NOT INSTALLED_ENGINE) + # Add all cmake files in a project so they can be handled from within the IDE + ly_include_cmake_file_list(cmake/cmake_files.cmake) + add_custom_target(CMakeFiles SOURCES ${ALLFILES}) + ly_source_groups_from_folders("${ALLFILES}") + unset(ALLFILES) +endif() \ No newline at end of file From 9681eb4a4d811933df309c18d32779f60fbfc321 Mon Sep 17 00:00:00 2001 From: pappeste Date: Fri, 30 Apr 2021 14:20:15 -0700 Subject: [PATCH 004/811] Improving projects shown in the IDE for projects building from installed sdk --- cmake/3rdParty.cmake | 9 ++++++--- cmake/Install.cmake | 12 ++++++++++-- cmake/LYPython.cmake | 9 +++++---- cmake/cmake_files.cmake | 1 + 4 files changed, 22 insertions(+), 9 deletions(-) diff --git a/cmake/3rdParty.cmake b/cmake/3rdParty.cmake index 7385f34e5a..eb11404237 100644 --- a/cmake/3rdParty.cmake +++ b/cmake/3rdParty.cmake @@ -313,6 +313,9 @@ list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/3rdParty) ly_get_absolute_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/3rdParty/Platform/${PAL_PLATFORM_NAME}) list(APPEND CMAKE_MODULE_PATH ${pal_dir}) -ly_include_cmake_file_list(cmake/3rdParty/cmake_files.cmake) -ly_get_absolute_pal_filename(pal_3rdparty_dir ${CMAKE_CURRENT_SOURCE_DIR}/cmake/3rdParty/Platform/${PAL_PLATFORM_NAME}) -ly_include_cmake_file_list(${pal_3rdparty_dir}/cmake_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake) +if(NOT INSTALLED_ENGINE) + # Add the 3rdParty cmake files to the IDE + ly_include_cmake_file_list(cmake/3rdParty/cmake_files.cmake) + ly_get_absolute_pal_filename(pal_3rdparty_dir ${CMAKE_CURRENT_SOURCE_DIR}/cmake/3rdParty/Platform/${PAL_PLATFORM_NAME}) + ly_include_cmake_file_list(${pal_3rdparty_dir}/cmake_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake) +endif() \ No newline at end of file diff --git a/cmake/Install.cmake b/cmake/Install.cmake index b56f5ced85..73a3273dfa 100644 --- a/cmake/Install.cmake +++ b/cmake/Install.cmake @@ -9,5 +9,13 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -ly_get_absolute_pal_filename(pal_dir ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Platform/${PAL_PLATFORM_NAME}) -include(${pal_dir}/Install_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) \ No newline at end of file +if(NOT INSTALLED_ENGINE) + ly_get_absolute_pal_filename(pal_dir ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Platform/${PAL_PLATFORM_NAME}) + include(${pal_dir}/Install_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) +else() + + # Provide empty implementation so ly_add_target continues working + function(ly_install_target ly_install_target_NAME) + endfunction() + +endif() \ No newline at end of file diff --git a/cmake/LYPython.cmake b/cmake/LYPython.cmake index ff5132097c..546d5f66db 100644 --- a/cmake/LYPython.cmake +++ b/cmake/LYPython.cmake @@ -265,10 +265,11 @@ if (NOT CMAKE_SCRIPT_MODE_FILE) # we also need to make sure any custom packages are installed. # this costs a moment of time though, so we'll only do it based on stamp files. - - ly_pip_install_local_package_editable(${LY_ROOT_FOLDER}/Tools/LyTestTools ly-test-tools) - ly_pip_install_local_package_editable(${LY_ROOT_FOLDER}/Tools/RemoteConsole/ly_remote_console ly-remote-console) - ly_pip_install_local_package_editable(${LY_ROOT_FOLDER}/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools editor-python-test-tools) + if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND NOT INSTALLED_ENGINE) + ly_pip_install_local_package_editable(${LY_ROOT_FOLDER}/Tools/LyTestTools ly-test-tools) + ly_pip_install_local_package_editable(${LY_ROOT_FOLDER}/Tools/RemoteConsole/ly_remote_console ly-remote-console) + ly_pip_install_local_package_editable(${LY_ROOT_FOLDER}/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools editor-python-test-tools) + endif() endif() endif() diff --git a/cmake/cmake_files.cmake b/cmake/cmake_files.cmake index 5045a42cbe..bd5976b494 100644 --- a/cmake/cmake_files.cmake +++ b/cmake/cmake_files.cmake @@ -12,6 +12,7 @@ set(FILES 3rdParty.cmake 3rdPartyPackages.cmake + CMakeFiles.cmake CommandExecution.cmake Configurations.cmake CPack.cmake From d046bae20babb0c876a52e61cd60956270777c1f Mon Sep 17 00:00:00 2001 From: pappeste Date: Fri, 30 Apr 2021 18:06:03 -0700 Subject: [PATCH 005/811] removing duplicate message --- cmake/Platform/Windows/Configurations_windows.cmake | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cmake/Platform/Windows/Configurations_windows.cmake b/cmake/Platform/Windows/Configurations_windows.cmake index 6ab376ed0b..9ef535e455 100644 --- a/cmake/Platform/Windows/Configurations_windows.cmake +++ b/cmake/Platform/Windows/Configurations_windows.cmake @@ -106,7 +106,7 @@ if(NOT CMAKE_GENERATOR MATCHES "Visual Studio") endforeach() if(NOT version VERSION_EQUAL CMAKE_SYSTEM_VERSION) - message(STATUS "Selecting Windows SDK version ${version} to target Windows ${CMAKE_SYSTEM_VERSION}.") + message(STATUS "Using Windows SDK version ${version} to target Windows ${CMAKE_SYSTEM_VERSION}") endif() ly_set(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION "${version}") @@ -116,4 +116,3 @@ endif() if(NOT CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION MATCHES "10.0") message(FATAL_ERROR "Unsupported version of Windows SDK ${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}, specify \"-DCMAKE_SYSTEM_VERSION=10.0\" when invoking cmake") endif() -message(STATUS "Using Windows target SDK ${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}") From a905f38cc4c2513ee018523cf86fc6e247d5043a Mon Sep 17 00:00:00 2001 From: pappeste Date: Fri, 30 Apr 2021 18:06:30 -0700 Subject: [PATCH 006/811] qt deploy --- cmake/Platform/Common/Install_common.cmake | 46 ++++++++++++++-------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index fb3a7b1b09..dac12d8a50 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -13,6 +13,10 @@ set(CMAKE_INSTALL_MESSAGE NEVER) # Simplify messages to reduce output noise ly_set(LY_DEFAULT_INSTALL_COMPONENT "Core") +file(RELATIVE_PATH runtime_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) +set(install_output_folder "${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$") + #! ly_install_target: registers the target to be installed by cmake install. # # \arg:NAME name of the target @@ -47,13 +51,11 @@ function(ly_install_target ly_install_target_NAME) if(target_runtime_output_directory) file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) endif() - file(RELATIVE_PATH runtime_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) get_target_property(target_library_output_directory ${ly_install_target_NAME} LIBRARY_OUTPUT_DIRECTORY) if(target_library_output_directory) file(RELATIVE_PATH target_library_output_subdirectory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${target_library_output_directory}) endif() - file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) install( TARGETS ${ly_install_target_NAME} @@ -85,6 +87,28 @@ function(ly_install_target ly_install_target_NAME) COMPONENT ${ly_install_target_COMPONENT} ) + get_target_property(target_type ${ly_install_target_NAME} TYPE) + set(runtime_dependencies_list SHARED MODULE EXECUTABLE APPLICATION) # Only have to deploy for dlls/exes + if(target_type IN_LIST runtime_dependencies_list) + get_property(has_qt_dependency GLOBAL PROPERTY LY_DETECT_QT_DEPENDENCY_${ly_install_target_NAME}) + if(has_qt_dependency) + # Qt deploy needs to be done after the binary is copied to the output, so we do a install(CODE) which effectively + # puts it as a postbuild step of the "install" target. Binaries are copied at that point. + if(NOT EXISTS ${WINDEPLOYQT_EXECUTABLE}) + message(FATAL_ERROR "Qt deploy executable not found: ${WINDEPLOYQT_EXECUTABLE}") + endif() + set(target_output "${install_output_folder}/${target_runtime_output_subdirectory}/$") + install(CODE +"execute_process(COMMAND \"${WINDEPLOYQT_EXECUTABLE}\" --verbose 0 --no-compiler-runtime \"${target_output}\" ERROR_VARIABLE deploy_error RESULT_VARIABLE deploy_result) +if (NOT \${deploy_result} EQUAL 0) + if(NOT deploy_result MATCHES \"does not seem to be a Qt executable\" ) + message(SEND_ERROR \"Deploying qt for ${target_output} returned \${result}: \${deploy_error}\") + endif() +endif() +") + endif() + endif() + endfunction() @@ -310,8 +334,8 @@ function(ly_setup_others) # Registry install(DIRECTORY - ${CMAKE_CURRENT_BINARY_DIR}/bin/$/Registry - DESTINATION ./bin/$ + ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/$/Registry + DESTINATION ./${runtime_output_directory}/${PAL_PLATFORM_NAME}/$ COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) install(DIRECTORY @@ -329,8 +353,7 @@ function(ly_setup_others) # Gem Source Assets and Registry # Find all gem directories relative to the CMake Source Dir - file( - GLOB_RECURSE + file(GLOB_RECURSE gems_assets_path LIST_DIRECTORIES TRUE RELATIVE "${CMAKE_SOURCE_DIR}/" @@ -350,17 +373,6 @@ function(ly_setup_others) endif() endforeach() - - # Qt Binaries - set(QT_BIN_DIRS bearer iconengines imageformats platforms styles translations) - foreach(qt_dir ${QT_BIN_DIRS}) - install(DIRECTORY - ${CMAKE_CURRENT_BINARY_DIR}/bin/$/${qt_dir} - DESTINATION ./bin/$ - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} - ) - endforeach() - # Templates install(DIRECTORY ${CMAKE_SOURCE_DIR}/Templates From ed17d01028d1a582df72e7149bf1a46b907430e1 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 3 May 2021 17:10:40 -0700 Subject: [PATCH 007/811] making the runtime_dependencies a function so we can reuse internal functions for the install --- CMakeLists.txt | 3 +- .../Common/RuntimeDependencies_common.cmake | 82 ++++++++-------- .../iOS/RuntimeDependencies_ios.cmake | 94 ++++++++++--------- 3 files changed, 94 insertions(+), 85 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2504bd625d..bd55e91e08 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -36,6 +36,7 @@ include(cmake/GeneralSettings.cmake) include(cmake/FileUtil.cmake) include(cmake/PAL.cmake) include(cmake/PALTools.cmake) +include(cmake/RuntimeDependencies.cmake) include(cmake/Install.cmake) include(cmake/Configurations.cmake) # Requires to be after PAL so we get platform variable definitions include(cmake/Dependencies.cmake) @@ -117,7 +118,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) endif() # 4. inject runtime dependencies to the targets. We need to do this after (1) since we are going to walk through # the dependencies -include(cmake/RuntimeDependencies.cmake) +ly_delayed_generate_runtime_dependencies() # 5. Perform test impact framework post steps once all of the targets have been enumerated ly_test_impact_post_step() # 6. Generate the O3DE find file and setup install locations for scripts, tools, assets etc., required by the engine diff --git a/cmake/Platform/Common/RuntimeDependencies_common.cmake b/cmake/Platform/Common/RuntimeDependencies_common.cmake index 6ac5215a01..859d1d21e3 100644 --- a/cmake/Platform/Common/RuntimeDependencies_common.cmake +++ b/cmake/Platform/Common/RuntimeDependencies_common.cmake @@ -10,7 +10,7 @@ # set(LY_COPY_PERMISSIONS "OWNER_READ OWNER_WRITE OWNER_EXECUTE") -set(LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS MODULE_LIBRARY SHARED_LIBRARY EXECUTABLE) +set(LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS MODULE_LIBRARY SHARED_LIBRARY EXECUTABLE APPLICATION) # There are several runtime dependencies to handle: # 1. Dependencies to 3rdparty libraries. This involves copying IMPORTED_LOCATION to the folder where the target is. @@ -183,7 +183,7 @@ function(ly_get_runtime_dependency_command ly_RUNTIME_COMMAND ly_TARGET) # To support platforms where the binaries end in different places, we are going to assume that all dependencies, # including the ones we are building, need to be copied over. However, we add a check to prevent copying something # over itself. This detection cannot happen now because the target we are copying for varies. - set(runtime_command "ly_copy(\"${source_file}\" \"$${target_directory}\")\n") + set(runtime_command "ly_copy(\"${source_file}\" \"@target_file_dir@${target_directory}\")\n") # Tentative optimization: this is an attempt to solve the first "if" at generation time, making the runtime_dependencies # file smaller and faster to run. In platforms where the built target and the dependencies targets end up in the same @@ -206,47 +206,51 @@ function(ly_get_runtime_dependency_command ly_RUNTIME_COMMAND ly_TARGET) endfunction() -get_property(additional_module_paths GLOBAL PROPERTY LY_ADDITIONAL_MODULE_PATH) -list(APPEND CMAKE_MODULE_PATH ${additional_module_paths}) +function(ly_delayed_generate_runtime_dependencies) -get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) -foreach(target IN LISTS all_targets) + get_property(additional_module_paths GLOBAL PROPERTY LY_ADDITIONAL_MODULE_PATH) + list(APPEND CMAKE_MODULE_PATH ${additional_module_paths}) - # Exclude targets that dont produce runtime outputs - get_target_property(target_type ${target} TYPE) - if(NOT target_type IN_LIST LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS) - continue() - endif() + get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) + foreach(target IN LISTS all_targets) - unset(runtime_dependencies) - set(runtime_commands " -function(ly_copy source_file target_directory) - get_filename_component(target_filename \"\${source_file}\" NAME) - if(NOT \"\${source_file}\" STREQUAL \"\${target_directory}/\${target_filename}\") - if(NOT EXISTS \"\${target_directory}\") - file(MAKE_DIRECTORY \"\${target_directory}\") + # Exclude targets that dont produce runtime outputs + get_target_property(target_type ${target} TYPE) + if(NOT target_type IN_LIST LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS) + continue() endif() - if(\"\${source_file}\" IS_NEWER_THAN \"\${target_directory}/\${target_filename}\") - file(LOCK \"\${target_directory}/\${target_filename}.lock\" GUARD FUNCTION TIMEOUT 30) - file(COPY \"\${source_file}\" DESTINATION \"\${target_directory}\" FILE_PERMISSIONS ${LY_COPY_PERMISSIONS}) - endif() - endif() -endfunction() -\n") - ly_get_runtime_dependencies(runtime_dependencies ${target}) - foreach(runtime_dependency ${runtime_dependencies}) - unset(runtime_command) - ly_get_runtime_dependency_command(runtime_command ${runtime_dependency}) - string(APPEND runtime_commands ${runtime_command}) + unset(runtime_dependencies) + set(runtime_commands " + function(ly_copy source_file target_directory) + get_filename_component(target_filename \"\${source_file}\" NAME) + if(NOT \"\${source_file}\" STREQUAL \"\${target_directory}/\${target_filename}\") + if(NOT EXISTS \"\${target_directory}\") + file(MAKE_DIRECTORY \"\${target_directory}\") + endif() + if(\"\${source_file}\" IS_NEWER_THAN \"\${target_directory}/\${target_filename}\") + file(LOCK \"\${target_directory}/\${target_filename}.lock\" GUARD FUNCTION TIMEOUT 30) + file(COPY \"\${source_file}\" DESTINATION \"\${target_directory}\" FILE_PERMISSIONS ${LY_COPY_PERMISSIONS}) + endif() + endif() + endfunction() + \n") + + ly_get_runtime_dependencies(runtime_dependencies ${target}) + foreach(runtime_dependency ${runtime_dependencies}) + unset(runtime_command) + ly_get_runtime_dependency_command(runtime_command ${runtime_dependency}) + string(APPEND runtime_commands ${runtime_command}) + endforeach() + + # Generate the output file + set(target_file_dir "$") + string(CONFIGURE "${runtime_commands}" generated_commands @ONLY) + file(GENERATE + OUTPUT ${CMAKE_BINARY_DIR}/runtime_dependencies/$/${target}.cmake + CONTENT "${generated_commands}" + ) + endforeach() - - # Generate the output file - string(CONFIGURE "${runtime_commands}" generated_commands @ONLY) - file(GENERATE - OUTPUT ${CMAKE_BINARY_DIR}/runtime_dependencies/$/${target}.cmake - CONTENT "${generated_commands}" - ) - -endforeach() +endfunction() diff --git a/cmake/Platform/iOS/RuntimeDependencies_ios.cmake b/cmake/Platform/iOS/RuntimeDependencies_ios.cmake index d558c6f12a..034ab750ff 100644 --- a/cmake/Platform/iOS/RuntimeDependencies_ios.cmake +++ b/cmake/Platform/iOS/RuntimeDependencies_ios.cmake @@ -118,57 +118,61 @@ function(ios_get_dependencies_recursive ios_DEPENDENCIES ly_TARGET) endfunction() -# For each (non-monolithic) game project, find runtime dependencies and tell XCode to embed/sign them -if(NOT LY_MONOLITHIC_GAME) +function(ly_delayed_generate_runtime_dependencies) - foreach(game_project ${LY_PROJECTS}) + # For each (non-monolithic) game project, find runtime dependencies and tell XCode to embed/sign them + if(NOT LY_MONOLITHIC_GAME) - # Recursively get all dependent frameworks for the game project. - unset(dependencies) - ios_get_dependencies_recursive(dependencies ${game_project}.GameLauncher) - if(dependencies) - set_target_properties(${game_project}.GameLauncher - PROPERTIES - XCODE_EMBED_FRAMEWORKS "${dependencies}" - XCODE_EMBED_FRAMEWORKS_CODE_SIGN_ON_COPY TRUE - XCODE_ATTRIBUTE_LD_RUNPATH_SEARCH_PATHS "@executable_path/Frameworks" - ) + foreach(game_project ${LY_PROJECTS}) + + # Recursively get all dependent frameworks for the game project. + unset(dependencies) + ios_get_dependencies_recursive(dependencies ${game_project}.GameLauncher) + if(dependencies) + set_target_properties(${game_project}.GameLauncher + PROPERTIES + XCODE_EMBED_FRAMEWORKS "${dependencies}" + XCODE_EMBED_FRAMEWORKS_CODE_SIGN_ON_COPY TRUE + XCODE_ATTRIBUTE_LD_RUNPATH_SEARCH_PATHS "@executable_path/Frameworks" + ) + endif() + + endforeach() + + endif() + + get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) + unset(test_runner_dependencies) + foreach(target IN LISTS all_targets) + # Exclude targets that dont produce runtime outputs + get_target_property(target_type ${target} TYPE) + if(NOT target_type IN_LIST LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS) + continue() endif() + + file(GENERATE + OUTPUT ${CMAKE_BINARY_DIR}/runtime_dependencies/$/${target}.cmake + CONTENT "" + ) + if(target_type IN_LIST IOS_FRAMEWORK_TARGET_TYPES) + list(APPEND test_runner_dependencies ${target}) + endif() endforeach() -endif() + if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) + add_dependencies("AzTestRunner" ${test_runner_dependencies}) + + # We still need to add indirect dependencies(eg. 3rdParty) + unset(all_dependencies) + ios_get_dependencies_recursive(all_dependencies AzTestRunner) -get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) -unset(test_runner_dependencies) -foreach(target IN LISTS all_targets) - # Exclude targets that dont produce runtime outputs - get_target_property(target_type ${target} TYPE) - if(NOT target_type IN_LIST LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS) - continue() + set_target_properties("AzTestRunner" + PROPERTIES + XCODE_EMBED_FRAMEWORKS "${all_dependencies}" + XCODE_EMBED_FRAMEWORKS_CODE_SIGN_ON_COPY TRUE + XCODE_ATTRIBUTE_LD_RUNPATH_SEARCH_PATHS "@executable_path/Frameworks" + ) endif() - - file(GENERATE - OUTPUT ${CMAKE_BINARY_DIR}/runtime_dependencies/$/${target}.cmake - CONTENT "" - ) - if(target_type IN_LIST IOS_FRAMEWORK_TARGET_TYPES) - list(APPEND test_runner_dependencies ${target}) - endif() -endforeach() - -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) - add_dependencies("AzTestRunner" ${test_runner_dependencies}) - - # We still need to add indirect dependencies(eg. 3rdParty) - unset(all_dependencies) - ios_get_dependencies_recursive(all_dependencies AzTestRunner) - - set_target_properties("AzTestRunner" - PROPERTIES - XCODE_EMBED_FRAMEWORKS "${all_dependencies}" - XCODE_EMBED_FRAMEWORKS_CODE_SIGN_ON_COPY TRUE - XCODE_ATTRIBUTE_LD_RUNPATH_SEARCH_PATHS "@executable_path/Frameworks" - ) -endif() \ No newline at end of file +endfunction() \ No newline at end of file From fd9bac8684a31b143921ad3b7415e08afbf430dc Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 3 May 2021 17:11:03 -0700 Subject: [PATCH 008/811] Unnecessary empty line --- Gems/ImageProcessing/Code/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/Gems/ImageProcessing/Code/CMakeLists.txt b/Gems/ImageProcessing/Code/CMakeLists.txt index a5cb6f6cb9..41d4b95179 100644 --- a/Gems/ImageProcessing/Code/CMakeLists.txt +++ b/Gems/ImageProcessing/Code/CMakeLists.txt @@ -81,7 +81,6 @@ ly_add_source_properties( ly_add_target( NAME ImageProcessing.Editor GEM_MODULE - NAMESPACE Gem AUTOMOC AUTORCC From 04032d37bc5254bb87b65dee7dd5f672c8d515af Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 3 May 2021 17:11:25 -0700 Subject: [PATCH 009/811] leftover for a parameter it never existed --- cmake/LYWrappers.cmake | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index f6a36afc89..47515ba663 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -333,10 +333,6 @@ function(ly_add_target) endif() if(NOT ly_add_target_IMPORTED) - if(NOT ly_add_target_INSTALL_COMPONENT) - set(ly_add_target_INSTALL_COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT}) - endif() - ly_install_target( ${ly_add_target_NAME} NAMESPACE ${ly_add_target_NAMESPACE} @@ -344,7 +340,7 @@ function(ly_add_target) BUILD_DEPENDENCIES ${ly_add_target_BUILD_DEPENDENCIES} RUNTIME_DEPENDENCIES ${ly_add_target_RUNTIME_DEPENDENCIES} COMPILE_DEFINITIONS ${ly_add_target_COMPILE_DEFINITIONS} - COMPONENT ${ly_add_target_INSTALL_COMPONENT} + COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) endif() From 5c68647b6b4bfebea1742cc66d1ce4b016f72394 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 3 May 2021 17:16:03 -0700 Subject: [PATCH 010/811] fixing qt deploy and adding install of runtime dependencies --- cmake/Platform/Common/Install_common.cmake | 91 ++++++++++++++++------ 1 file changed, 69 insertions(+), 22 deletions(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index dac12d8a50..a2fa54b503 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -17,6 +17,7 @@ file(RELATIVE_PATH runtime_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_RUNTIME_ file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) set(install_output_folder "${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$") + #! ly_install_target: registers the target to be installed by cmake install. # # \arg:NAME name of the target @@ -87,28 +88,6 @@ function(ly_install_target ly_install_target_NAME) COMPONENT ${ly_install_target_COMPONENT} ) - get_target_property(target_type ${ly_install_target_NAME} TYPE) - set(runtime_dependencies_list SHARED MODULE EXECUTABLE APPLICATION) # Only have to deploy for dlls/exes - if(target_type IN_LIST runtime_dependencies_list) - get_property(has_qt_dependency GLOBAL PROPERTY LY_DETECT_QT_DEPENDENCY_${ly_install_target_NAME}) - if(has_qt_dependency) - # Qt deploy needs to be done after the binary is copied to the output, so we do a install(CODE) which effectively - # puts it as a postbuild step of the "install" target. Binaries are copied at that point. - if(NOT EXISTS ${WINDEPLOYQT_EXECUTABLE}) - message(FATAL_ERROR "Qt deploy executable not found: ${WINDEPLOYQT_EXECUTABLE}") - endif() - set(target_output "${install_output_folder}/${target_runtime_output_subdirectory}/$") - install(CODE -"execute_process(COMMAND \"${WINDEPLOYQT_EXECUTABLE}\" --verbose 0 --no-compiler-runtime \"${target_output}\" ERROR_VARIABLE deploy_error RESULT_VARIABLE deploy_result) -if (NOT \${deploy_result} EQUAL 0) - if(NOT deploy_result MATCHES \"does not seem to be a Qt executable\" ) - message(SEND_ERROR \"Deploying qt for ${target_output} returned \${result}: \${deploy_error}\") - endif() -endif() -") - endif() - endif() - endfunction() @@ -235,6 +214,7 @@ function(ly_setup_o3de_install) ly_setup_cmake_install() ly_setup_target_generator() + ly_setup_runtime_dependencies() ly_setup_others() endfunction() @@ -306,6 +286,73 @@ function(ly_setup_cmake_install) endfunction() +#! ly_setup_runtime_dependencies: install runtime dependencies +function(ly_setup_runtime_dependencies) + + # Common functions used by the bellow code + install(CODE +"function(ly_deploy_qt_install target_output) + execute_process(COMMAND \"${WINDEPLOYQT_EXECUTABLE}\" --verbose 0 --no-compiler-runtime \"\${target_output}\" ERROR_VARIABLE deploy_error RESULT_VARIABLE deploy_result) + if (NOT \${deploy_result} EQUAL 0) + if(NOT deploy_error MATCHES \"does not seem to be a Qt executable\" ) + message(SEND_ERROR \"Deploying qt for \${target_output} returned \${deploy_result}: \${deploy_error}\") + endif() + endif() +endfunction() + +function(ly_copy source_file target_directory) + file(COPY \"\${source_file}\" DESTINATION \"\${target_directory}\" FILE_PERMISSIONS ${LY_COPY_PERMISSIONS}) +endfunction()" + COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + ) + + unset(runtime_commands) + get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) + foreach(target IN LISTS all_targets) + + # Exclude targets that dont produce runtime outputs + get_target_property(target_type ${target} TYPE) + if(NOT target_type IN_LIST LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS) + continue() + endif() + + get_target_property(target_runtime_output_directory ${target} RUNTIME_OUTPUT_DIRECTORY) + if(target_runtime_output_directory) + file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) + endif() + + # Qt + get_property(has_qt_dependency GLOBAL PROPERTY LY_DETECT_QT_DEPENDENCY_${target}) + if(has_qt_dependency) + # Qt deploy needs to be done after the binary is copied to the output, so we do a install(CODE) which effectively + # puts it as a postbuild step of the "install" target. Binaries are copied at that point. + if(NOT EXISTS ${WINDEPLOYQT_EXECUTABLE}) + message(FATAL_ERROR "Qt deploy executable not found: ${WINDEPLOYQT_EXECUTABLE}") + endif() + set(target_output "${install_output_folder}/${target_runtime_output_subdirectory}/$") + list(APPEND runtime_commands "ly_deploy_qt_install(\"${target_output}\")\n") + endif() + + # runtime dependencies that need to be copied to the output + set(target_file_dir "${install_output_folder}/${target_runtime_output_subdirectory}") + ly_get_runtime_dependencies(runtime_dependencies ${target}) + foreach(runtime_dependency ${runtime_dependencies}) + unset(runtime_command) + ly_get_runtime_dependency_command(runtime_command ${runtime_dependency}) + string(CONFIGURE "${runtime_command}" runtime_command @ONLY) + list(APPEND runtime_commands ${runtime_command}) + endforeach() + + endforeach() + + list(REMOVE_DUPLICATES runtime_commands) + list(JOIN runtime_commands " " runtime_commands_str) # the spaces are just to see the right identation in the cmake_install.cmake file + install(CODE "${runtime_commands_str}" + COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + ) + +endfunction() + #! ly_setup_others: install directories required by the engine function(ly_setup_others) From d1416d53e08d4645aaae0fe8024e975bfda49c07 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 3 May 2021 18:16:08 -0700 Subject: [PATCH 011/811] adding a file for ImageProcessing --- cmake/Platform/Common/Install_common.cmake | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index a2fa54b503..0686b27fe7 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -420,6 +420,13 @@ function(ly_setup_others) endif() endforeach() + # Additional files needed by gems + install(FILES + ${CMAKE_SOURCE_DIR}/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings + DESTINATION Gems/ImageProcessing/Code/Source + COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + ) + # Templates install(DIRECTORY ${CMAKE_SOURCE_DIR}/Templates From b0732dd494231d2b600ee382fae2e776296b8434 Mon Sep 17 00:00:00 2001 From: pappeste Date: Tue, 4 May 2021 13:52:19 -0700 Subject: [PATCH 012/811] Changing find files to add_subdirectory to be able to have SettingsRegistry.cmake finding the path to the gems --- cmake/LYWrappers.cmake | 12 +++-- cmake/Platform/Common/Install_common.cmake | 45 ++++++++++--------- cmake/SettingsRegistry.cmake | 9 ++-- cmake/{ => install}/Findo3de.cmake.in | 0 .../TargetCMakeLists.txt.in} | 6 +-- 5 files changed, 35 insertions(+), 37 deletions(-) rename cmake/{ => install}/Findo3de.cmake.in (100%) rename cmake/{FindTarget.cmake.in => install/TargetCMakeLists.txt.in} (82%) diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index 47515ba663..62509582a1 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -52,7 +52,6 @@ define_property(TARGET PROPERTY GEM_MODULE # \arg:HEADERONLY (bool) defines this target to be a header only library. A ${NAME}_HEADERS project will be created for the IDE # \arg:EXECUTABLE (bool) defines this target to be an executable # \arg:APPLICATION (bool) defines this target to be an application (executable that is not a console) -# \arg:UNKNOWN (bool) defines this target to be unknown. This is used when importing installed targets from Find files # \arg:IMPORTED (bool) defines this target to be imported. # \arg:NAMESPACE namespace declaration for this target. It will be used for IDE and dependencies # \arg:OUTPUT_NAME (optional) overrides the name of the output target. If not specified, the name will be used. @@ -76,7 +75,7 @@ define_property(TARGET PROPERTY GEM_MODULE # \arg:AUTOGEN_RULES a set of AutoGeneration rules to be passed to the AzAutoGen expansion system function(ly_add_target) - set(options STATIC SHARED MODULE GEM_MODULE HEADERONLY EXECUTABLE APPLICATION UNKNOWN IMPORTED AUTOMOC AUTOUIC AUTORCC NO_UNITY) + set(options STATIC SHARED MODULE GEM_MODULE HEADERONLY EXECUTABLE APPLICATION IMPORTED AUTOMOC AUTOUIC AUTORCC NO_UNITY) set(oneValueArgs NAME NAMESPACE OUTPUT_SUBDIRECTORY OUTPUT_NAME) set(multiValueArgs FILES_CMAKE GENERATED_FILES INCLUDE_DIRECTORIES COMPILE_DEFINITIONS BUILD_DEPENDENCIES RUNTIME_DEPENDENCIES PLATFORM_INCLUDE_FILES TARGET_PROPERTIES AUTOGEN_RULES) @@ -128,12 +127,12 @@ function(ly_add_target) set(linking_options APPLICATION) set(linking_count "${linking_count}1") endif() - if(ly_add_target_UNKNOWN) - set(linking_options UNKNOWN) + if(ly_add_target_IMPORTED) + set(linking_options UNKNOWN IMPORTED GLOBAL) set(linking_count "${linking_count}1") endif() if(NOT ("${linking_count}" STREQUAL "1")) - message(FATAL_ERROR "More than one of the following options [STATIC | SHARED | MODULE | HEADERONLY | EXECUTABLE | APPLICATION | UNKNOWN] was specified and they are mutually exclusive") + message(FATAL_ERROR "More than one of the following options [STATIC | SHARED | MODULE | HEADERONLY | EXECUTABLE | APPLICATION | IMPORTED] was specified and they are mutually exclusive") endif() if(ly_add_target_NAMESPACE) @@ -159,10 +158,9 @@ function(ly_add_target) ${linking_options} ${ALLFILES} ${ly_add_target_GENERATED_FILES} ) - elseif(ly_add_target_UNKNOWN) + elseif(ly_add_target_IMPORTED) add_library(${ly_add_target_NAME} ${linking_options} - IMPORTED ) else() add_library(${ly_add_target_NAME} diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index edbcdc473b..e9726fb949 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -11,7 +11,7 @@ set(CMAKE_INSTALL_MESSAGE NEVER) # Simplify messages to reduce output noise -ly_set(LY_DEFAULT_INSTALL_COMPONENT "Core") +ly_set(LY_DEFAULT_INSTALL_COMPONENT Core) file(RELATIVE_PATH runtime_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) @@ -74,20 +74,9 @@ function(ly_install_target ly_install_target_NAME) COMPONENT ${ly_install_target_COMPONENT} ) - ly_generate_target_find_file( - NAME ${ly_install_target_NAME} - ${ARGN} - ) + ly_generate_target_find_file(NAME ${ly_install_target_NAME} ${ARGN}) ly_generate_target_config_file(${ly_install_target_NAME}) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${ly_install_target_NAME}_$.cmake" - DESTINATION cmake_autogen/${ly_install_target_NAME} - COMPONENT ${ly_install_target_COMPONENT} - ) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/Find${ly_install_target_NAME}.cmake" - DESTINATION cmake - COMPONENT ${ly_install_target_COMPONENT} - ) - + endfunction() @@ -129,16 +118,21 @@ function(ly_generate_target_find_file) # Includes need additional processing to add the install root foreach(include ${include_directories_interface_props}) - set(installed_include_prefix "\${LY_ROOT_FOLDER}/include/") file(RELATIVE_PATH relative_path ${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/${include}) - list(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "include/${relative_path}") + string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${relative_path}\n") endforeach() - string(REPLACE ";" "\n" INCLUDE_DIRECTORIES_PLACEHOLDER "${INCLUDE_DIRECTORIES_PLACEHOLDER}") string(REPLACE ";" "\n" BUILD_DEPENDENCIES_PLACEHOLDER "${BUILD_DEPENDENCIES_PLACEHOLDER}") string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") - configure_file(${LY_ROOT_FOLDER}/cmake/FindTarget.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/Find${ly_generate_target_find_file_NAME}.cmake @ONLY) + # Since a CMakeLists could contain multiple targets, we generate it in a folder per target + configure_file(${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/install/${ly_generate_target_find_file_NAME}/CMakeLists.txt @ONLY) + get_target_property(target_source_dir ${ly_generate_target_find_file_NAME} SOURCE_DIR) + file(RELATIVE_PATH target_source_dir_relative ${CMAKE_SOURCE_DIR} ${target_source_dir}) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${ly_generate_target_find_file_NAME}/CMakeLists.txt" + DESTINATION ${target_source_dir_relative}/${ly_generate_target_find_file_NAME} + COMPONENT ${ly_install_target_COMPONENT} + ) endfunction() @@ -183,7 +177,13 @@ endif() ") endif() - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${NAME}_$.cmake" CONTENT "${target_file_contents}") + file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME}/${NAME}_$.cmake" CONTENT "${target_file_contents}") + get_target_property(target_source_dir ${NAME} SOURCE_DIR) + file(RELATIVE_PATH target_source_dir_relative ${CMAKE_SOURCE_DIR} ${target_source_dir}) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME}_$.cmake" + DESTINATION ${target_source_dir_relative}/${NAME} + COMPONENT ${ly_install_target_COMPONENT} + ) endfunction() @@ -254,11 +254,12 @@ function(ly_setup_cmake_install) get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) unset(FIND_PACKAGES_PLACEHOLDER) foreach(target IN LISTS all_targets) - string(APPEND FIND_PACKAGES_PLACEHOLDER " find_package(${target})\n") + get_target_property(target_source_dir ${target} SOURCE_DIR) + file(RELATIVE_PATH target_source_dir_relative ${CMAKE_SOURCE_DIR} ${target_source_dir}) + string(APPEND FIND_PACKAGES_PLACEHOLDER " add_subdirectory(${target_source_dir_relative}/${target})\n") endforeach() - configure_file(${LY_ROOT_FOLDER}/cmake/Findo3de.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/Findo3de.cmake @ONLY) - + configure_file(${LY_ROOT_FOLDER}/cmake/install/Findo3de.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/Findo3de.cmake @ONLY) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/cmake/Findo3de.cmake" DESTINATION cmake COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index fd5985a5a1..1bc2b2344e 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -126,15 +126,16 @@ function(ly_delayed_generate_settings_registry) get_property(gem_relative_source_dir TARGET ${gem_target} PROPERTY SOURCE_DIR) if(gem_relative_source_dir) # Most gems CMakeLists.txt files reside in the /Code/ so remove "Code/" from the path - if(gem_relative_source_dir MATCHES ".*/Code$") + while(gem_relative_source_dir MATCHES ".*/Code$") get_filename_component(gem_relative_source_dir ${gem_relative_source_dir} DIRECTORY) - endif() + endwhile() file(TO_CMAKE_PATH ${LY_ROOT_FOLDER} ly_root_folder_cmake) file(RELATIVE_PATH gem_relative_source_dir ${ly_root_folder_cmake} ${gem_relative_source_dir}) endif() - # Strip target namespace from gem targets before configuring them into the json template - ly_strip_target_namespace(TARGET ${gem_target} OUTPUT_VARIABLE stripped_gem_target) + message("gem_target: ${gem_target}, gem_relative_source_dir: ${gem_relative_source_dir}") + # Strip target namespace from gem targets before configuring them into the json template + ly_strip_target_namespace(TARGET ${gem_target} OUTPUT_VARIABLE stripped_gem_target) string(CONFIGURE ${gem_module_template} gem_module_json @ONLY) list(APPEND target_gem_dependencies_names ${gem_module_json}) endforeach() diff --git a/cmake/Findo3de.cmake.in b/cmake/install/Findo3de.cmake.in similarity index 100% rename from cmake/Findo3de.cmake.in rename to cmake/install/Findo3de.cmake.in diff --git a/cmake/FindTarget.cmake.in b/cmake/install/TargetCMakeLists.txt.in similarity index 82% rename from cmake/FindTarget.cmake.in rename to cmake/install/TargetCMakeLists.txt.in index 8ad9822dae..16263ecf30 100644 --- a/cmake/FindTarget.cmake.in +++ b/cmake/install/TargetCMakeLists.txt.in @@ -11,10 +11,8 @@ # Generated by O3DE -include(FindPackageHandleStandardArgs) - ly_add_target( - NAME @NAME_PLACEHOLDER@ UNKNOWN IMPORTED + NAME @NAME_PLACEHOLDER@ IMPORTED @NAMESPACE_PLACEHOLDER@ COMPILE_DEFINITIONS INTERFACE @@ -30,5 +28,5 @@ ly_add_target( ) foreach(config @CMAKE_CONFIGURATION_TYPES@) - include("${LY_ROOT_FOLDER}/cmake_autogen/@NAME_PLACEHOLDER@/@NAME_PLACEHOLDER@_${config}.cmake" OPTIONAL) + include("@NAME_PLACEHOLDER@_${config}.cmake" OPTIONAL) endforeach() From 84381e4c3a65986e0d83f8839e5a8eba0be984fb Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 5 May 2021 12:07:23 -0700 Subject: [PATCH 013/811] making the settings registry compute the path based on the gems.json file --- cmake/SettingsRegistry.cmake | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index 1bc2b2344e..af6ef42e31 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -125,15 +125,14 @@ function(ly_delayed_generate_settings_registry) endif() get_property(gem_relative_source_dir TARGET ${gem_target} PROPERTY SOURCE_DIR) if(gem_relative_source_dir) - # Most gems CMakeLists.txt files reside in the /Code/ so remove "Code/" from the path - while(gem_relative_source_dir MATCHES ".*/Code$") + # Most gems SOURCE dir is nested in the path, we need to find the path to the gem.json file + while(NOT EXISTS ${gem_relative_source_dir}/gem.json) get_filename_component(gem_relative_source_dir ${gem_relative_source_dir} DIRECTORY) endwhile() file(TO_CMAKE_PATH ${LY_ROOT_FOLDER} ly_root_folder_cmake) file(RELATIVE_PATH gem_relative_source_dir ${ly_root_folder_cmake} ${gem_relative_source_dir}) endif() - message("gem_target: ${gem_target}, gem_relative_source_dir: ${gem_relative_source_dir}") # Strip target namespace from gem targets before configuring them into the json template ly_strip_target_namespace(TARGET ${gem_target} OUTPUT_VARIABLE stripped_gem_target) string(CONFIGURE ${gem_module_template} gem_module_json @ONLY) From 7c9837dfd4fb1e55c20c00d88fb0c9ed5587d5c9 Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 5 May 2021 12:07:45 -0700 Subject: [PATCH 014/811] installing the gems.json files --- cmake/Platform/Common/Install_common.cmake | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index e9726fb949..dbffcc8d12 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -439,6 +439,21 @@ function(ly_setup_others) endif() endforeach() + # gem.json files + file(GLOB_RECURSE + gems_json_path + LIST_DIRECTORIES FALSE + RELATIVE "${CMAKE_SOURCE_DIR}" + "Gems/*/gem.json" + ) + foreach(gem_json_path ${gems_json_path}) + get_filename_component(gem_relative_path ${gem_json_path} DIRECTORY) + install(FILES ${gem_json_path} + DESTINATION ${gem_relative_path} + COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + ) + endforeach() + # Additional files needed by gems install(FILES ${CMAKE_SOURCE_DIR}/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings From 412bf6777239da2a30378a481b47a5c07d8e4572 Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 5 May 2021 12:08:55 -0700 Subject: [PATCH 015/811] changing the default prefix (install path) to be /install to workaround the "build/*" filter in the AP This is also better since we support installing different configuraitons/platforms in the same prefix --- .gitignore | 1 + cmake/OutputDirectory.cmake | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index c3af907e97..c396847560 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ __pycache__ AssetProcessorTemp/** [Bb]uild/** [Cc]ache/ +install/ Editor/EditorEventLog.xml Editor/EditorLayout.xml **/*egg-info/** diff --git a/cmake/OutputDirectory.cmake b/cmake/OutputDirectory.cmake index 9055802d39..5fe5c7a957 100644 --- a/cmake/OutputDirectory.cmake +++ b/cmake/OutputDirectory.cmake @@ -13,4 +13,8 @@ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib CACHE PATH "Build directory for static libraries and import libraries") set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin CACHE PATH "Build directory for shared libraries") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin CACHE PATH "Build directory for executables") -set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/install CACHE PATH "Installation prefix") + +# We install outside of the binary dir because our install support muliple platforms to +# be installed together. We also have an exclusion rule in the AP that filters out the +# "build" folder which is a common binary dir +set(CMAKE_INSTALL_PREFIX ${CMAKE_SOURCE_DIR}/install CACHE PATH "Installation prefix") From 76ffff8bb5f3f7eb3d3239a3d1852622cfc0367a Mon Sep 17 00:00:00 2001 From: nggieber Date: Wed, 5 May 2021 12:29:06 -0700 Subject: [PATCH 016/811] Moved Qt files into to renamed 'S'ource --- .../Tools/ProjectManager/{source/Qt => Source}/EngineSettings.cpp | 0 Code/Tools/ProjectManager/{source/Qt => Source}/EngineSettings.h | 0 Code/Tools/ProjectManager/{source/Qt => Source}/EngineSettings.ui | 0 Code/Tools/ProjectManager/{source/Qt => Source}/FirstTimeUse.cpp | 0 Code/Tools/ProjectManager/{source/Qt => Source}/FirstTimeUse.h | 0 Code/Tools/ProjectManager/{source/Qt => Source}/FirstTimeUse.ui | 0 Code/Tools/ProjectManager/{source/Qt => Source}/GemCatalog.cpp | 0 Code/Tools/ProjectManager/{source/Qt => Source}/GemCatalog.h | 0 Code/Tools/ProjectManager/{source/Qt => Source}/GemCatalog.ui | 0 .../ProjectManager/{source/Qt => Source}/NewProjectSettings.cpp | 0 .../ProjectManager/{source/Qt => Source}/NewProjectSettings.h | 0 .../ProjectManager/{source/Qt => Source}/NewProjectSettings.ui | 0 .../ProjectManager/{source/Qt => Source}/ProjectManagerWindow.cpp | 0 .../ProjectManager/{source/Qt => Source}/ProjectManagerWindow.h | 0 .../ProjectManager/{source/Qt => Source}/ProjectManagerWindow.ui | 0 .../ProjectManager/{source/Qt => Source}/ProjectSettings.cpp | 0 Code/Tools/ProjectManager/{source/Qt => Source}/ProjectSettings.h | 0 .../Tools/ProjectManager/{source/Qt => Source}/ProjectSettings.ui | 0 Code/Tools/ProjectManager/{source/Qt => Source}/ProjectsHome.cpp | 0 Code/Tools/ProjectManager/{source/Qt => Source}/ProjectsHome.h | 0 Code/Tools/ProjectManager/{source/Qt => Source}/ProjectsHome.ui | 0 Code/Tools/ProjectManager/{source => Source}/ScreenDefs.h | 0 Code/Tools/ProjectManager/{source => Source}/ScreenFactory.cpp | 0 Code/Tools/ProjectManager/{source => Source}/ScreenFactory.h | 0 Code/Tools/ProjectManager/{source/Qt => Source}/ScreenWidget.h | 0 Code/Tools/ProjectManager/{source => Source}/main.cpp | 0 26 files changed, 0 insertions(+), 0 deletions(-) rename Code/Tools/ProjectManager/{source/Qt => Source}/EngineSettings.cpp (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/EngineSettings.h (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/EngineSettings.ui (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/FirstTimeUse.cpp (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/FirstTimeUse.h (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/FirstTimeUse.ui (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/GemCatalog.cpp (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/GemCatalog.h (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/GemCatalog.ui (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/NewProjectSettings.cpp (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/NewProjectSettings.h (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/NewProjectSettings.ui (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/ProjectManagerWindow.cpp (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/ProjectManagerWindow.h (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/ProjectManagerWindow.ui (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/ProjectSettings.cpp (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/ProjectSettings.h (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/ProjectSettings.ui (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/ProjectsHome.cpp (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/ProjectsHome.h (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/ProjectsHome.ui (100%) rename Code/Tools/ProjectManager/{source => Source}/ScreenDefs.h (100%) rename Code/Tools/ProjectManager/{source => Source}/ScreenFactory.cpp (100%) rename Code/Tools/ProjectManager/{source => Source}/ScreenFactory.h (100%) rename Code/Tools/ProjectManager/{source/Qt => Source}/ScreenWidget.h (100%) rename Code/Tools/ProjectManager/{source => Source}/main.cpp (100%) diff --git a/Code/Tools/ProjectManager/source/Qt/EngineSettings.cpp b/Code/Tools/ProjectManager/Source/EngineSettings.cpp similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/EngineSettings.cpp rename to Code/Tools/ProjectManager/Source/EngineSettings.cpp diff --git a/Code/Tools/ProjectManager/source/Qt/EngineSettings.h b/Code/Tools/ProjectManager/Source/EngineSettings.h similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/EngineSettings.h rename to Code/Tools/ProjectManager/Source/EngineSettings.h diff --git a/Code/Tools/ProjectManager/source/Qt/EngineSettings.ui b/Code/Tools/ProjectManager/Source/EngineSettings.ui similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/EngineSettings.ui rename to Code/Tools/ProjectManager/Source/EngineSettings.ui diff --git a/Code/Tools/ProjectManager/source/Qt/FirstTimeUse.cpp b/Code/Tools/ProjectManager/Source/FirstTimeUse.cpp similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/FirstTimeUse.cpp rename to Code/Tools/ProjectManager/Source/FirstTimeUse.cpp diff --git a/Code/Tools/ProjectManager/source/Qt/FirstTimeUse.h b/Code/Tools/ProjectManager/Source/FirstTimeUse.h similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/FirstTimeUse.h rename to Code/Tools/ProjectManager/Source/FirstTimeUse.h diff --git a/Code/Tools/ProjectManager/source/Qt/FirstTimeUse.ui b/Code/Tools/ProjectManager/Source/FirstTimeUse.ui similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/FirstTimeUse.ui rename to Code/Tools/ProjectManager/Source/FirstTimeUse.ui diff --git a/Code/Tools/ProjectManager/source/Qt/GemCatalog.cpp b/Code/Tools/ProjectManager/Source/GemCatalog.cpp similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/GemCatalog.cpp rename to Code/Tools/ProjectManager/Source/GemCatalog.cpp diff --git a/Code/Tools/ProjectManager/source/Qt/GemCatalog.h b/Code/Tools/ProjectManager/Source/GemCatalog.h similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/GemCatalog.h rename to Code/Tools/ProjectManager/Source/GemCatalog.h diff --git a/Code/Tools/ProjectManager/source/Qt/GemCatalog.ui b/Code/Tools/ProjectManager/Source/GemCatalog.ui similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/GemCatalog.ui rename to Code/Tools/ProjectManager/Source/GemCatalog.ui diff --git a/Code/Tools/ProjectManager/source/Qt/NewProjectSettings.cpp b/Code/Tools/ProjectManager/Source/NewProjectSettings.cpp similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/NewProjectSettings.cpp rename to Code/Tools/ProjectManager/Source/NewProjectSettings.cpp diff --git a/Code/Tools/ProjectManager/source/Qt/NewProjectSettings.h b/Code/Tools/ProjectManager/Source/NewProjectSettings.h similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/NewProjectSettings.h rename to Code/Tools/ProjectManager/Source/NewProjectSettings.h diff --git a/Code/Tools/ProjectManager/source/Qt/NewProjectSettings.ui b/Code/Tools/ProjectManager/Source/NewProjectSettings.ui similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/NewProjectSettings.ui rename to Code/Tools/ProjectManager/Source/NewProjectSettings.ui diff --git a/Code/Tools/ProjectManager/source/Qt/ProjectManagerWindow.cpp b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/ProjectManagerWindow.cpp rename to Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp diff --git a/Code/Tools/ProjectManager/source/Qt/ProjectManagerWindow.h b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/ProjectManagerWindow.h rename to Code/Tools/ProjectManager/Source/ProjectManagerWindow.h diff --git a/Code/Tools/ProjectManager/source/Qt/ProjectManagerWindow.ui b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.ui similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/ProjectManagerWindow.ui rename to Code/Tools/ProjectManager/Source/ProjectManagerWindow.ui diff --git a/Code/Tools/ProjectManager/source/Qt/ProjectSettings.cpp b/Code/Tools/ProjectManager/Source/ProjectSettings.cpp similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/ProjectSettings.cpp rename to Code/Tools/ProjectManager/Source/ProjectSettings.cpp diff --git a/Code/Tools/ProjectManager/source/Qt/ProjectSettings.h b/Code/Tools/ProjectManager/Source/ProjectSettings.h similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/ProjectSettings.h rename to Code/Tools/ProjectManager/Source/ProjectSettings.h diff --git a/Code/Tools/ProjectManager/source/Qt/ProjectSettings.ui b/Code/Tools/ProjectManager/Source/ProjectSettings.ui similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/ProjectSettings.ui rename to Code/Tools/ProjectManager/Source/ProjectSettings.ui diff --git a/Code/Tools/ProjectManager/source/Qt/ProjectsHome.cpp b/Code/Tools/ProjectManager/Source/ProjectsHome.cpp similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/ProjectsHome.cpp rename to Code/Tools/ProjectManager/Source/ProjectsHome.cpp diff --git a/Code/Tools/ProjectManager/source/Qt/ProjectsHome.h b/Code/Tools/ProjectManager/Source/ProjectsHome.h similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/ProjectsHome.h rename to Code/Tools/ProjectManager/Source/ProjectsHome.h diff --git a/Code/Tools/ProjectManager/source/Qt/ProjectsHome.ui b/Code/Tools/ProjectManager/Source/ProjectsHome.ui similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/ProjectsHome.ui rename to Code/Tools/ProjectManager/Source/ProjectsHome.ui diff --git a/Code/Tools/ProjectManager/source/ScreenDefs.h b/Code/Tools/ProjectManager/Source/ScreenDefs.h similarity index 100% rename from Code/Tools/ProjectManager/source/ScreenDefs.h rename to Code/Tools/ProjectManager/Source/ScreenDefs.h diff --git a/Code/Tools/ProjectManager/source/ScreenFactory.cpp b/Code/Tools/ProjectManager/Source/ScreenFactory.cpp similarity index 100% rename from Code/Tools/ProjectManager/source/ScreenFactory.cpp rename to Code/Tools/ProjectManager/Source/ScreenFactory.cpp diff --git a/Code/Tools/ProjectManager/source/ScreenFactory.h b/Code/Tools/ProjectManager/Source/ScreenFactory.h similarity index 100% rename from Code/Tools/ProjectManager/source/ScreenFactory.h rename to Code/Tools/ProjectManager/Source/ScreenFactory.h diff --git a/Code/Tools/ProjectManager/source/Qt/ScreenWidget.h b/Code/Tools/ProjectManager/Source/ScreenWidget.h similarity index 100% rename from Code/Tools/ProjectManager/source/Qt/ScreenWidget.h rename to Code/Tools/ProjectManager/Source/ScreenWidget.h diff --git a/Code/Tools/ProjectManager/source/main.cpp b/Code/Tools/ProjectManager/Source/main.cpp similarity index 100% rename from Code/Tools/ProjectManager/source/main.cpp rename to Code/Tools/ProjectManager/Source/main.cpp From 625aa14aa8eac6699accbd38e11afe9133c9279f Mon Sep 17 00:00:00 2001 From: nggieber Date: Wed, 5 May 2021 12:31:17 -0700 Subject: [PATCH 017/811] Updated files after moving all Qt folder into Source --- Code/Tools/ProjectManager/CMakeLists.txt | 2 +- .../ProjectManager/Source/EngineSettings.cpp | 4 +- .../ProjectManager/Source/EngineSettings.h | 2 +- .../ProjectManager/Source/FirstTimeUse.cpp | 4 +- .../ProjectManager/Source/FirstTimeUse.h | 2 +- .../ProjectManager/Source/GemCatalog.cpp | 4 +- Code/Tools/ProjectManager/Source/GemCatalog.h | 2 +- .../Source/NewProjectSettings.cpp | 4 +- .../Source/NewProjectSettings.h | 2 +- .../Source/ProjectManagerWindow.cpp | 4 +- .../ProjectManager/Source/ProjectSettings.cpp | 4 +- .../ProjectManager/Source/ProjectSettings.h | 2 +- .../ProjectManager/Source/ProjectsHome.cpp | 4 +- .../ProjectManager/Source/ProjectsHome.h | 2 +- .../ProjectManager/Source/ScreenFactory.cpp | 12 ++--- .../ProjectManager/Source/ScreenFactory.h | 2 +- .../ProjectManager/Source/ScreenWidget.h | 2 +- Code/Tools/ProjectManager/Source/main.cpp | 2 +- .../project_manager_files.cmake | 44 +++++++++---------- 19 files changed, 52 insertions(+), 52 deletions(-) diff --git a/Code/Tools/ProjectManager/CMakeLists.txt b/Code/Tools/ProjectManager/CMakeLists.txt index 0961acd354..e4354bac32 100644 --- a/Code/Tools/ProjectManager/CMakeLists.txt +++ b/Code/Tools/ProjectManager/CMakeLists.txt @@ -27,7 +27,7 @@ ly_add_target( PUBLIC . PRIVATE - source + Source BUILD_DEPENDENCIES PRIVATE diff --git a/Code/Tools/ProjectManager/Source/EngineSettings.cpp b/Code/Tools/ProjectManager/Source/EngineSettings.cpp index 03040781f7..bc359637e4 100644 --- a/Code/Tools/ProjectManager/Source/EngineSettings.cpp +++ b/Code/Tools/ProjectManager/Source/EngineSettings.cpp @@ -10,9 +10,9 @@ * */ -#include +#include -#include +#include namespace O3DE::ProjectManager { diff --git a/Code/Tools/ProjectManager/Source/EngineSettings.h b/Code/Tools/ProjectManager/Source/EngineSettings.h index 5f2aa5310a..f90f760798 100644 --- a/Code/Tools/ProjectManager/Source/EngineSettings.h +++ b/Code/Tools/ProjectManager/Source/EngineSettings.h @@ -12,7 +12,7 @@ #pragma once #if !defined(Q_MOC_RUN) -#include +#include #endif namespace Ui diff --git a/Code/Tools/ProjectManager/Source/FirstTimeUse.cpp b/Code/Tools/ProjectManager/Source/FirstTimeUse.cpp index 9ba4eba2a6..5f5dcd5087 100644 --- a/Code/Tools/ProjectManager/Source/FirstTimeUse.cpp +++ b/Code/Tools/ProjectManager/Source/FirstTimeUse.cpp @@ -10,9 +10,9 @@ * */ -#include +#include -#include +#include namespace O3DE::ProjectManager { diff --git a/Code/Tools/ProjectManager/Source/FirstTimeUse.h b/Code/Tools/ProjectManager/Source/FirstTimeUse.h index 677ca398fa..708513d493 100644 --- a/Code/Tools/ProjectManager/Source/FirstTimeUse.h +++ b/Code/Tools/ProjectManager/Source/FirstTimeUse.h @@ -12,7 +12,7 @@ #pragma once #if !defined(Q_MOC_RUN) -#include +#include #endif namespace Ui diff --git a/Code/Tools/ProjectManager/Source/GemCatalog.cpp b/Code/Tools/ProjectManager/Source/GemCatalog.cpp index 6377eb5c8d..9d89740816 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog.cpp @@ -10,9 +10,9 @@ * */ -#include +#include -#include +#include namespace O3DE::ProjectManager { diff --git a/Code/Tools/ProjectManager/Source/GemCatalog.h b/Code/Tools/ProjectManager/Source/GemCatalog.h index aee7b3a988..e45d865e58 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog.h @@ -12,7 +12,7 @@ #pragma once #if !defined(Q_MOC_RUN) -#include +#include #endif namespace Ui diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettings.cpp b/Code/Tools/ProjectManager/Source/NewProjectSettings.cpp index 7289c73329..2ebe54e682 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettings.cpp +++ b/Code/Tools/ProjectManager/Source/NewProjectSettings.cpp @@ -10,9 +10,9 @@ * */ -#include +#include -#include +#include namespace O3DE::ProjectManager { diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettings.h b/Code/Tools/ProjectManager/Source/NewProjectSettings.h index 5790772a0c..f5fa91a9b9 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettings.h +++ b/Code/Tools/ProjectManager/Source/NewProjectSettings.h @@ -12,7 +12,7 @@ #pragma once #if !defined(Q_MOC_RUN) -#include +#include #endif namespace Ui diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp index b37f73a0c5..12980fc836 100644 --- a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include #include @@ -18,7 +18,7 @@ #include -#include +#include namespace O3DE::ProjectManager { diff --git a/Code/Tools/ProjectManager/Source/ProjectSettings.cpp b/Code/Tools/ProjectManager/Source/ProjectSettings.cpp index 56b27f5fe3..bc653f9c5b 100644 --- a/Code/Tools/ProjectManager/Source/ProjectSettings.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectSettings.cpp @@ -10,9 +10,9 @@ * */ -#include +#include -#include +#include namespace O3DE::ProjectManager { diff --git a/Code/Tools/ProjectManager/Source/ProjectSettings.h b/Code/Tools/ProjectManager/Source/ProjectSettings.h index c9356db9bf..e7781d3a2a 100644 --- a/Code/Tools/ProjectManager/Source/ProjectSettings.h +++ b/Code/Tools/ProjectManager/Source/ProjectSettings.h @@ -12,7 +12,7 @@ #pragma once #if !defined(Q_MOC_RUN) -#include +#include #endif namespace Ui diff --git a/Code/Tools/ProjectManager/Source/ProjectsHome.cpp b/Code/Tools/ProjectManager/Source/ProjectsHome.cpp index ef85d71950..1a451f3d10 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsHome.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectsHome.cpp @@ -10,9 +10,9 @@ * */ -#include +#include -#include +#include namespace O3DE::ProjectManager { diff --git a/Code/Tools/ProjectManager/Source/ProjectsHome.h b/Code/Tools/ProjectManager/Source/ProjectsHome.h index b5a062f2dd..4cc2918a38 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsHome.h +++ b/Code/Tools/ProjectManager/Source/ProjectsHome.h @@ -12,7 +12,7 @@ #pragma once #if !defined(Q_MOC_RUN) -#include +#include #endif namespace Ui diff --git a/Code/Tools/ProjectManager/Source/ScreenFactory.cpp b/Code/Tools/ProjectManager/Source/ScreenFactory.cpp index e29994d162..b07816e69e 100644 --- a/Code/Tools/ProjectManager/Source/ScreenFactory.cpp +++ b/Code/Tools/ProjectManager/Source/ScreenFactory.cpp @@ -11,12 +11,12 @@ */ #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include namespace O3DE::ProjectManager { diff --git a/Code/Tools/ProjectManager/Source/ScreenFactory.h b/Code/Tools/ProjectManager/Source/ScreenFactory.h index addc868dfa..ea68534a08 100644 --- a/Code/Tools/ProjectManager/Source/ScreenFactory.h +++ b/Code/Tools/ProjectManager/Source/ScreenFactory.h @@ -13,7 +13,7 @@ #include -#include +#include #include diff --git a/Code/Tools/ProjectManager/Source/ScreenWidget.h b/Code/Tools/ProjectManager/Source/ScreenWidget.h index 0cec4bed03..b4c4fd190c 100644 --- a/Code/Tools/ProjectManager/Source/ScreenWidget.h +++ b/Code/Tools/ProjectManager/Source/ScreenWidget.h @@ -12,7 +12,7 @@ #pragma once #if !defined(Q_MOC_RUN) -#include +#include #include #endif diff --git a/Code/Tools/ProjectManager/Source/main.cpp b/Code/Tools/ProjectManager/Source/main.cpp index 7ae977818b..149da79491 100644 --- a/Code/Tools/ProjectManager/Source/main.cpp +++ b/Code/Tools/ProjectManager/Source/main.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include #include diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index 0616b28e1e..2a7656c8c4 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -15,26 +15,26 @@ set(FILES source/ScreenDefs.h source/ScreenFactory.h source/ScreenFactory.cpp - source/Qt/ScreenWidget.h - source/Qt/FirstTimeUse.h - source/Qt/FirstTimeUse.cpp - source/Qt/FirstTimeUse.ui - source/Qt/ProjectManagerWindow.h - source/Qt/ProjectManagerWindow.cpp - source/Qt/ProjectManagerWindow.ui - source/Qt/NewProjectSettings.h - source/Qt/NewProjectSettings.cpp - source/Qt/NewProjectSettings.ui - source/Qt/GemCatalog.h - source/Qt/GemCatalog.cpp - source/Qt/GemCatalog.ui - source/Qt/ProjectsHome.h - source/Qt/ProjectsHome.cpp - source/Qt/ProjectsHome.ui - source/Qt/ProjectSettings.h - source/Qt/ProjectSettings.cpp - source/Qt/ProjectSettings.ui - source/Qt/EngineSettings.h - source/Qt/EngineSettings.cpp - source/Qt/EngineSettings.ui + source/ScreenWidget.h + source/FirstTimeUse.h + source/FirstTimeUse.cpp + source/FirstTimeUse.ui + source/ProjectManagerWindow.h + source/ProjectManagerWindow.cpp + source/ProjectManagerWindow.ui + source/NewProjectSettings.h + source/NewProjectSettings.cpp + source/NewProjectSettings.ui + source/GemCatalog.h + source/GemCatalog.cpp + source/GemCatalog.ui + source/ProjectsHome.h + source/ProjectsHome.cpp + source/ProjectsHome.ui + source/ProjectSettings.h + source/ProjectSettings.cpp + source/ProjectSettings.ui + source/EngineSettings.h + source/EngineSettings.cpp + source/EngineSettings.ui ) \ No newline at end of file From d27aa0f5846c82cd5f1b56f90087c2628c772f88 Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 5 May 2021 12:31:34 -0700 Subject: [PATCH 018/811] replaced ly_add_dependencies with ly_add_target_files so settingsregistry is happy --- cmake/Platform/Common/Install_common.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index dbffcc8d12..f351b074a0 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -157,7 +157,7 @@ function(ly_generate_target_config_file NAME) string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\"") elseif(target_type STREQUAL SHARED_LIBRARY) string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"") - string(APPEND target_file_contents "ly_add_dependencies(${NAME} \"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\")\n") + string(APPEND target_file_contents "ly_add_target_files(TARGET ${NAME} FILES \"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\")\n") else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"") endif() From 2044832bb1634b77cc25112bf5ad146146b26340 Mon Sep 17 00:00:00 2001 From: nggieber Date: Wed, 5 May 2021 12:41:05 -0700 Subject: [PATCH 019/811] Updated Source capitalization in cmake files list --- .../project_manager_files.cmake | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index 2a7656c8c4..698027ea15 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -11,30 +11,30 @@ set(FILES project_manager.qrc - source/main.cpp - source/ScreenDefs.h - source/ScreenFactory.h - source/ScreenFactory.cpp - source/ScreenWidget.h - source/FirstTimeUse.h - source/FirstTimeUse.cpp - source/FirstTimeUse.ui - source/ProjectManagerWindow.h - source/ProjectManagerWindow.cpp - source/ProjectManagerWindow.ui - source/NewProjectSettings.h - source/NewProjectSettings.cpp - source/NewProjectSettings.ui - source/GemCatalog.h - source/GemCatalog.cpp - source/GemCatalog.ui - source/ProjectsHome.h - source/ProjectsHome.cpp - source/ProjectsHome.ui - source/ProjectSettings.h - source/ProjectSettings.cpp - source/ProjectSettings.ui - source/EngineSettings.h - source/EngineSettings.cpp - source/EngineSettings.ui + Source/main.cpp + Source/ScreenDefs.h + Source/ScreenFactory.h + Source/ScreenFactory.cpp + Source/ScreenWidget.h + Source/FirstTimeUse.h + Source/FirstTimeUse.cpp + Source/FirstTimeUse.ui + Source/ProjectManagerWindow.h + Source/ProjectManagerWindow.cpp + Source/ProjectManagerWindow.ui + Source/NewProjectSettings.h + Source/NewProjectSettings.cpp + Source/NewProjectSettings.ui + Source/GemCatalog.h + Source/GemCatalog.cpp + Source/GemCatalog.ui + Source/ProjectsHome.h + Source/ProjectsHome.cpp + Source/ProjectsHome.ui + Source/ProjectSettings.h + Source/ProjectSettings.cpp + Source/ProjectSettings.ui + Source/EngineSettings.h + Source/EngineSettings.cpp + Source/EngineSettings.ui ) \ No newline at end of file From 5b98227a773177b68999bd25fcff0b4ea2522385 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 5 May 2021 14:58:31 -0500 Subject: [PATCH 020/811] Adding newline to the end of project_manager_files.cmake --- Code/Tools/ProjectManager/project_manager_files.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index 698027ea15..333180ea78 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -37,4 +37,4 @@ set(FILES Source/EngineSettings.h Source/EngineSettings.cpp Source/EngineSettings.ui -) \ No newline at end of file +) From f6187f510a10d8f05bb884a261b3ae4c7b759e46 Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 5 May 2021 16:21:25 -0700 Subject: [PATCH 021/811] config file going to the wrong place --- cmake/Platform/Common/Install_common.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index f351b074a0..f6e2488126 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -180,7 +180,7 @@ endif() file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME}/${NAME}_$.cmake" CONTENT "${target_file_contents}") get_target_property(target_source_dir ${NAME} SOURCE_DIR) file(RELATIVE_PATH target_source_dir_relative ${CMAKE_SOURCE_DIR} ${target_source_dir}) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME}_$.cmake" + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME}/${NAME}_$.cmake" DESTINATION ${target_source_dir_relative}/${NAME} COMPONENT ${ly_install_target_COMPONENT} ) From e63c36019470966c54f5dda17b5b3eac79f85a6e Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 5 May 2021 16:21:41 -0700 Subject: [PATCH 022/811] small unrelated fix --- Code/Tools/ProjectManager/CMakeLists.txt | 3 --- 1 file changed, 3 deletions(-) diff --git a/Code/Tools/ProjectManager/CMakeLists.txt b/Code/Tools/ProjectManager/CMakeLists.txt index e4354bac32..2f0603a705 100644 --- a/Code/Tools/ProjectManager/CMakeLists.txt +++ b/Code/Tools/ProjectManager/CMakeLists.txt @@ -24,11 +24,8 @@ ly_add_target( project_manager_files.cmake Platform/${PAL_PLATFORM_NAME}/PAL_${PAL_PLATFORM_NAME_LOWERCASE}.cmake INCLUDE_DIRECTORIES - PUBLIC - . PRIVATE Source - BUILD_DEPENDENCIES PRIVATE 3rdParty::Qt::Core From 9fe893830c6a4201c6ef5e6e4e244e853e9aa211 Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 5 May 2021 16:22:13 -0700 Subject: [PATCH 023/811] sine fixes to AP model handling, still getting some sporadic asserts in debug --- Code/Framework/AzCore/AzCore/IO/Path/Path.h | 6 ++++ Code/Framework/AzCore/AzCore/IO/Path/Path.inl | 5 +++ .../native/ui/ProductAssetTreeModel.cpp | 29 ++++++++------- .../native/ui/SourceAssetTreeModel.cpp | 36 +++++++++---------- 4 files changed, 45 insertions(+), 31 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.h b/Code/Framework/AzCore/AzCore/IO/Path/Path.h index 61294cd637..6c1b519224 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.h +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.h @@ -95,6 +95,12 @@ namespace AZ::IO constexpr int Compare(AZStd::string_view pathString) const noexcept; constexpr int Compare(const value_type* pathString) const noexcept; + // Extension for fixed strings + //! extension: fixed string types with MaxPathLength capacity + //! Returns a new instance of an AZStd::fixed_string with capacity of MaxPathLength + //! made from the internal string + constexpr AZStd::fixed_string FixedMaxPathString() const noexcept; + // decomposition //! Given a windows path of "C:\O3DE\foo\bar\name.txt" and a posix path of //! "/O3DE/foo/bar/name.txt" diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.inl b/Code/Framework/AzCore/AzCore/IO/Path/Path.inl index 1e42fc9df7..05a92c5247 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.inl +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.inl @@ -915,6 +915,11 @@ namespace AZ::IO return compare_string_view(path); } + constexpr AZStd::fixed_string PathView::FixedMaxPathString() const noexcept + { + return AZStd::fixed_string(m_path.begin(), m_path.end()); + } + // decomposition constexpr auto PathView::RootName() const -> PathView { diff --git a/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp b/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp index 5efef8166c..68ba64ea1a 100644 --- a/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp +++ b/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp @@ -14,6 +14,7 @@ #include "ProductAssetTreeItemData.h" #include +#include #include namespace AssetProcessor @@ -159,31 +160,33 @@ namespace AssetProcessor return; } + AZ::IO::Path productNamePath(product.m_productName, AZ::IO::PosixPathSeparator); - AZStd::vector tokens; - AzFramework::StringFunc::Tokenize(product.m_productName.c_str(), tokens, AZ_CORRECT_DATABASE_SEPARATOR, false, true); - - if (tokens.empty()) + if (productNamePath.empty()) { AZ_Warning("AssetProcessor", false, "Product id %d has an invalid name: %s", product.m_productID, product.m_productName.c_str()); return; } AssetTreeItem* parentItem = m_root.get(); - AZStd::string fullFolderName; - for (int i = 0; i < tokens.size() - 1; ++i) + AZ::IO::Path currentFullFolderPath; + const AZ::IO::PathView filename = productNamePath.Filename(); + const AZ::IO::PathView fullPathWithoutFilename = productNamePath.RemoveFilename(); + AZStd::fixed_string currentPath; + for (auto pathIt = fullPathWithoutFilename.begin(); pathIt != fullPathWithoutFilename.end(); ++pathIt) { - AzFramework::StringFunc::AssetDatabasePath::Join(fullFolderName.c_str(), tokens[i].c_str(), fullFolderName); - AssetTreeItem* nextParent = parentItem->GetChildFolder(tokens[i].c_str()); + currentPath = pathIt->FixedMaxPathString(); + currentFullFolderPath /= currentPath; + AssetTreeItem* nextParent = parentItem->GetChildFolder(currentPath.c_str()); if (!nextParent) { if (!modelIsResetting) { - QModelIndex parentIndex = parentItem == m_root.get() ? QModelIndex() : createIndex(parentItem->GetRow(), 0, parentItem); + QModelIndex parentIndex = createIndex(parentItem->GetRow(), 0, parentItem); beginInsertRows(parentIndex, parentItem->getChildCount(), parentItem->getChildCount()); } - nextParent = parentItem->CreateChild(ProductAssetTreeItemData::MakeShared(nullptr, fullFolderName, tokens[i].c_str(), true, AZ::Uuid::CreateNull())); - m_productToTreeItem[fullFolderName] = nextParent; + nextParent = parentItem->CreateChild(ProductAssetTreeItemData::MakeShared(nullptr, currentFullFolderPath.Native(), currentPath.c_str(), true, AZ::Uuid::CreateNull())); + m_productToTreeItem[currentFullFolderPath.Native()] = nextParent; // m_productIdToTreeItem is not used for folders, folders don't have product IDs. if (!modelIsResetting) @@ -205,12 +208,12 @@ namespace AssetProcessor if (!modelIsResetting) { - QModelIndex parentIndex = parentItem == m_root.get() ? QModelIndex() : createIndex(parentItem->GetRow(), 0, parentItem); + QModelIndex parentIndex = createIndex(parentItem->GetRow(), 0, parentItem); beginInsertRows(parentIndex, parentItem->getChildCount(), parentItem->getChildCount()); } AZStd::shared_ptr productItemData = - ProductAssetTreeItemData::MakeShared(&product, product.m_productName, tokens[tokens.size() - 1].c_str(), false, sourceId); + ProductAssetTreeItemData::MakeShared(&product, product.m_productName, AZStd::fixed_string(filename.Native()).c_str(), false, sourceId); m_productToTreeItem[product.m_productName] = parentItem->CreateChild(productItemData); m_productIdToTreeItem[product.m_productID] = m_productToTreeItem[product.m_productName]; diff --git a/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp b/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp index dda0a58837..69e60f6733 100644 --- a/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp +++ b/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp @@ -63,8 +63,7 @@ namespace AssetProcessor } - auto fullPath = AZ::IO::Path(scanFolder.m_scanFolder) / source.m_sourceName; - + AZ::IO::Path fullPath = AZ::IO::Path(scanFolder.m_scanFolder, AZ::IO::PosixPathSeparator) / source.m_sourceName; // It's common for Open 3D Engine game projects and scan folders to be in a subfolder // of the engine install. To improve readability of the source files, strip out @@ -78,34 +77,35 @@ namespace AssetProcessor AzFramework::StringFunc::Replace(fullPath.Native(), m_assetRoot.absolutePath().toUtf8(), ""); } - - AZStd::vector tokens; - AzFramework::StringFunc::Tokenize(fullPath.c_str(), tokens, AZ_CORRECT_DATABASE_SEPARATOR, false, true); - - if (tokens.empty()) + if (fullPath.empty()) { - AZ_Warning("AssetProcessor", false, "Source id %s has an invalid name: %s", - source.m_sourceGuid.ToString().c_str(), source.m_sourceName.c_str()); + AZ_Warning( + "AssetProcessor", false, "Source id %s has an invalid name: %s", source.m_sourceGuid.ToString().c_str(), + source.m_sourceName.c_str()); return; } QModelIndex newIndicesStart; AssetTreeItem* parentItem = m_root.get(); - AZStd::string fullFolderName; - for (int i = 0; i < tokens.size() - 1; ++i) + AZ::IO::Path currentFullFolderPath; + const AZ::IO::PathView filename = fullPath.Filename(); + const AZ::IO::PathView fullPathWithoutFilename = fullPath.RemoveFilename(); + AZStd::fixed_string currentPath; + for (auto pathIt = fullPathWithoutFilename.begin(); pathIt != fullPathWithoutFilename.end(); ++pathIt) { - AzFramework::StringFunc::AssetDatabasePath::Join(fullFolderName.c_str(), tokens[i].c_str(), fullFolderName); - AssetTreeItem* nextParent = parentItem->GetChildFolder(tokens[i].c_str()); + currentPath = pathIt->FixedMaxPathString(); + currentFullFolderPath /= currentPath; + AssetTreeItem* nextParent = parentItem->GetChildFolder(currentPath.c_str()); if (!nextParent) { if (!modelIsResetting) { - QModelIndex parentIndex = parentItem == m_root.get() ? QModelIndex() : createIndex(parentItem->GetRow(), 0, parentItem); + QModelIndex parentIndex = createIndex(parentItem->GetRow(), 0, parentItem); beginInsertRows(parentIndex, parentItem->getChildCount(), parentItem->getChildCount()); } - nextParent = parentItem->CreateChild(SourceAssetTreeItemData::MakeShared(nullptr, nullptr, fullFolderName, tokens[i].c_str(), true)); - m_sourceToTreeItem[fullFolderName] = nextParent; + nextParent = parentItem->CreateChild(SourceAssetTreeItemData::MakeShared(nullptr, nullptr, currentFullFolderPath.Native(), currentPath.c_str(), true)); + m_sourceToTreeItem[currentFullFolderPath.Native()] = nextParent; // Folders don't have source IDs, don't add to m_sourceIdToTreeItem if (!modelIsResetting) { @@ -117,12 +117,12 @@ namespace AssetProcessor if (!modelIsResetting) { - QModelIndex parentIndex = parentItem == m_root.get() ? QModelIndex() : createIndex(parentItem->GetRow(), 0, parentItem); + QModelIndex parentIndex = createIndex(parentItem->GetRow(), 0, parentItem); beginInsertRows(parentIndex, parentItem->getChildCount(), parentItem->getChildCount()); } m_sourceToTreeItem[source.m_sourceName] = - parentItem->CreateChild(SourceAssetTreeItemData::MakeShared(&source, &scanFolder, source.m_sourceName, tokens[tokens.size() - 1].c_str(), false)); + parentItem->CreateChild(SourceAssetTreeItemData::MakeShared(&source, &scanFolder, source.m_sourceName, AZStd::fixed_string(filename.Native()).c_str(), false)); m_sourceIdToTreeItem[source.m_sourceID] = m_sourceToTreeItem[source.m_sourceName]; if (!modelIsResetting) { From 68f19644e7af2dbaedf5b4bad536f0758c041a53 Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 5 May 2021 16:42:50 -0700 Subject: [PATCH 024/811] typo --- cmake/Platform/Common/Install_common.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index f6e2488126..3c372462a2 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -157,7 +157,7 @@ function(ly_generate_target_config_file NAME) string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\"") elseif(target_type STREQUAL SHARED_LIBRARY) string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"") - string(APPEND target_file_contents "ly_add_target_files(TARGET ${NAME} FILES \"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\")\n") + string(APPEND target_file_contents "ly_add_target_files(TARGETS ${NAME} FILES \"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\")\n") else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"") endif() From bddbe43240169c0e927329677982618acdf7afe5 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 6 May 2021 13:55:34 -0700 Subject: [PATCH 025/811] adding all the config folder for ImageProcessingAtom --- cmake/Platform/Common/Install_common.cmake | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 3c372462a2..cef3251899 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -455,11 +455,11 @@ function(ly_setup_others) endforeach() # Additional files needed by gems - install(FILES - ${CMAKE_SOURCE_DIR}/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings - DESTINATION Gems/ImageProcessing/Code/Source + install(DIRECTORY + ${CMAKE_SOURCE_DIR}/Gems/Atom/Asset/ImageProcessingAtom/Config + DESTINATION Gems/Atom/Asset/ImageProcessingAtom COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} - ) + ) # Templates install(DIRECTORY From 2eb494f7c13764f4bdf60cf7ebac855bb2668c27 Mon Sep 17 00:00:00 2001 From: mbalfour Date: Fri, 7 May 2021 14:23:01 -0500 Subject: [PATCH 026/811] Changed the level loading code to always set the default mission name now. the mission system recently got redcoded, so nothing else was setting this name. --- Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp index d31f122d9b..8818dfa0d9 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp @@ -108,10 +108,11 @@ bool CLevelInfo::ReadInfo() AzFramework::ApplicationRequests::Bus::BroadcastResult( usePrefabSystemForLevels, &AzFramework::ApplicationRequests::IsPrefabSystemForLevelsEnabled); + // Set up a default game type for legacy code. + m_defaultGameTypeName = "Mission0"; + if (usePrefabSystemForLevels) { - // Set up a default game type for legacy code. - m_defaultGameTypeName = "Mission0"; return true; } From 7441685508759e37237d0ea4a963f16b830be86b Mon Sep 17 00:00:00 2001 From: pappeste Date: Fri, 7 May 2021 13:22:22 -0700 Subject: [PATCH 027/811] changing how we refer to this path --- cmake/Packaging.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index 4f6565edc7..a4d7da5730 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -13,7 +13,7 @@ if(NOT PAL_TRAIT_BUILD_CPACK_SUPPORTED) return() endif() -ly_get_absolute_pal_filename(pal_dir ${CMAKE_SOURCE_DIR}/cmake/Platform/${PAL_HOST_PLATFORM_NAME}) +ly_get_absolute_pal_filename(pal_dir ${LY_ROOT_FOLDER}/cmake/Platform/${PAL_HOST_PLATFORM_NAME}) include(${pal_dir}/Packaging_${PAL_HOST_PLATFORM_NAME_LOWERCASE}.cmake) # if we get here and the generator hasn't been set, then a non fatal error occurred disabling packaging support From 2625e983b80b7d14638dcb97f7ab8e32f35e788b Mon Sep 17 00:00:00 2001 From: pappeste Date: Fri, 7 May 2021 13:22:54 -0700 Subject: [PATCH 028/811] fixing errors that had wrong condition --- Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp index 4b6e210522..b5829bb9da 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp @@ -38,8 +38,8 @@ namespace LegacyLevelSystem //------------------------------------------------------------------------ static void LoadLevel(const AZ::ConsoleCommandContainer& arguments) { - AZ_Error("SpawnableLevelSystem", arguments.empty(), "LoadLevel requires a level file name to be provided."); - AZ_Error("SpawnableLevelSystem", arguments.size() > 1, "LoadLevel requires a single level file name to be provided."); + AZ_Error("SpawnableLevelSystem", !arguments.empty(), "LoadLevel requires a level file name to be provided."); + AZ_Error("SpawnableLevelSystem", arguments.size() == 1, "LoadLevel requires a single level file name to be provided."); if (!arguments.empty() && gEnv->pSystem && gEnv->pSystem->GetILevelSystem() && !gEnv->IsEditor()) { From bedecebdcc9206d9a34277935f9295705c0ff530 Mon Sep 17 00:00:00 2001 From: phistere Date: Fri, 7 May 2021 20:05:05 -0500 Subject: [PATCH 029/811] Configures and installs an engine.json generated from a template. Fixes HEADERONLY targets for install. Fixes locating .ico resource file. Fix infinite loop in CMake configure on new projects. --- .../Windows/launcher_project_windows.cmake | 5 +++++ cmake/LYWrappers.cmake | 2 +- cmake/Platform/Common/Install_common.cmake | 16 ++++++++++++++-- cmake/SettingsRegistry.cmake | 10 +++++++--- cmake/Version.cmake | 3 ++- cmake/install/TargetCMakeLists.txt.in | 2 +- cmake/install/engine.json.in | 7 +++++++ engine.json | 3 ++- 8 files changed, 39 insertions(+), 9 deletions(-) create mode 100644 cmake/install/engine.json.in diff --git a/Code/LauncherUnified/Platform/Windows/launcher_project_windows.cmake b/Code/LauncherUnified/Platform/Windows/launcher_project_windows.cmake index bcef59ec5a..35c89caf15 100644 --- a/Code/LauncherUnified/Platform/Windows/launcher_project_windows.cmake +++ b/Code/LauncherUnified/Platform/Windows/launcher_project_windows.cmake @@ -10,6 +10,11 @@ # set(ICON_FILE ${project_real_path}/Gem/Resources/GameSDK.ico) +if(NOT EXISTS ${ICON_FILE}) + # Try another project-relative path + set(ICON_FILE ${project_real_path}/Resources/GameSDK.ico) +endif() + if(NOT EXISTS ${ICON_FILE}) # Try the common LauncherUnified icon instead set(ICON_FILE Resources/GameSDK.ico) diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index 62509582a1..73586b624f 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -85,7 +85,7 @@ function(ly_add_target) if(NOT ly_add_target_NAME) message(FATAL_ERROR "You must provide a name for the target") endif() - if(NOT ly_add_target_IMPORTED) + if(NOT ly_add_target_IMPORTED AND NOT ly_add_target_HEADERONLY) if(NOT ly_add_target_FILES_CMAKE) message(FATAL_ERROR "You must provide a list of _files.cmake files for the target") endif() diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index cef3251899..141f229506 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -104,6 +104,13 @@ function(ly_generate_target_find_file) unset(INCLUDE_DIRECTORIES_PLACEHOLDER) set(RUNTIME_DEPENDENCIES_PLACEHOLDER ${ly_generate_target_find_file_RUNTIME_DEPENDENCIES}) + set(TARGET_TYPE_PLACEHOLDER "IMPORTED") + #set(TARGET_TYPE_PLACEHOLDER) + get_target_property(target_type ${NAME_PLACEHOLDER} TYPE) + if(target_type STREQUAL INTERFACE_LIBRARY) + set(TARGET_TYPE_PLACEHOLDER "HEADERONLY") + endif() + # These targets will be imported. We will expose PUBLIC and INTERFACE properties as INTERFACE properties since # only INTERFACE properties can be exposed on imported targets ly_strip_private_properties(COMPILE_DEFINITIONS_PLACEHOLDER ${ly_generate_target_find_file_COMPILE_DEFINITIONS}) @@ -225,13 +232,17 @@ function(ly_setup_cmake_install) install(DIRECTORY "${CMAKE_SOURCE_DIR}/cmake" DESTINATION . COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + PATTERN "__pycache__" EXCLUDE REGEX "Findo3de.cmake" EXCLUDE REGEX "Platform\/.*\/BuiltInPackages_.*\.cmake" EXCLUDE ) + + configure_file(${CMAKE_SOURCE_DIR}/cmake/install/engine.json.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/engine.json @ONLY) + install( FILES "${CMAKE_SOURCE_DIR}/CMakeLists.txt" - "${CMAKE_SOURCE_DIR}/engine.json" + "${CMAKE_CURRENT_BINARY_DIR}/cmake/engine.json" DESTINATION . COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) @@ -369,6 +380,7 @@ function(ly_setup_others) install(DIRECTORY "${CMAKE_SOURCE_DIR}/${dir}" DESTINATION ${install_path} COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + PATTERN "__pycache__" EXCLUDE ) endforeach() @@ -450,7 +462,7 @@ function(ly_setup_others) get_filename_component(gem_relative_path ${gem_json_path} DIRECTORY) install(FILES ${gem_json_path} DESTINATION ${gem_relative_path} - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) endforeach() diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index af6ef42e31..31ce36c516 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -125,9 +125,13 @@ function(ly_delayed_generate_settings_registry) endif() get_property(gem_relative_source_dir TARGET ${gem_target} PROPERTY SOURCE_DIR) if(gem_relative_source_dir) - # Most gems SOURCE dir is nested in the path, we need to find the path to the gem.json file - while(NOT EXISTS ${gem_relative_source_dir}/gem.json) - get_filename_component(gem_relative_source_dir ${gem_relative_source_dir} DIRECTORY) + # Most gems SOURCE dir is nested in the path, we need to find the path to the gem.json or project.json file + while(NOT EXISTS ${gem_relative_source_dir}/gem.json AND NOT EXISTS ${gem_relative_source_dir}/project.json) + get_filename_component(parent_dir ${gem_relative_source_dir} DIRECTORY) + if (${parent_dir} STREQUAL ${gem_relative_source_dir}) + message(FATAL_ERROR "Did not find gem.json or project.json while processing target ${gem_target}!") + endif() + set(gem_relative_source_dir ${parent_dir}) endwhile() file(TO_CMAKE_PATH ${LY_ROOT_FOLDER} ly_root_folder_cmake) file(RELATIVE_PATH gem_relative_source_dir ${ly_root_folder_cmake} ${gem_relative_source_dir}) diff --git a/cmake/Version.cmake b/cmake/Version.cmake index 08d79d4ce6..1d484fb059 100644 --- a/cmake/Version.cmake +++ b/cmake/Version.cmake @@ -12,4 +12,5 @@ string(TIMESTAMP current_year "%Y") set(LY_VERSION_COPYRIGHT_YEAR ${current_year} CACHE STRING "Open 3D Engine's copyright year") set(LY_VERSION_STRING "0.0.0.0" CACHE STRING "Open 3D Engine's version") -set(LY_VERSION_BUILD_NUMBER 0 CACHE STRING "Open 3D Engine's build number") \ No newline at end of file +set(LY_VERSION_BUILD_NUMBER 0 CACHE STRING "Open 3D Engine's build number") +set(LY_VERSION_ENGINE_NAME "o3de" CACHE STRING "Open 3D Engine's engine name") diff --git a/cmake/install/TargetCMakeLists.txt.in b/cmake/install/TargetCMakeLists.txt.in index 16263ecf30..1c2f181368 100644 --- a/cmake/install/TargetCMakeLists.txt.in +++ b/cmake/install/TargetCMakeLists.txt.in @@ -12,7 +12,7 @@ # Generated by O3DE ly_add_target( - NAME @NAME_PLACEHOLDER@ IMPORTED + NAME @NAME_PLACEHOLDER@ @TARGET_TYPE_PLACEHOLDER@ @NAMESPACE_PLACEHOLDER@ COMPILE_DEFINITIONS INTERFACE diff --git a/cmake/install/engine.json.in b/cmake/install/engine.json.in new file mode 100644 index 0000000000..9899b169ed --- /dev/null +++ b/cmake/install/engine.json.in @@ -0,0 +1,7 @@ +{ + "engine_name": "@LY_VERSION_ENGINE_NAME@", + "FileVersion": 1, + "O3DEVersion": "@LY_VERSION_STRING@", + "O3DECopyrightYear": @LY_VERSION_COPYRIGHT_YEAR@, + "O3DEBuildNumber": @LY_VERSION_BUILD_NUMBER@ +} diff --git a/engine.json b/engine.json index 5091605f4c..f933886c44 100644 --- a/engine.json +++ b/engine.json @@ -2,5 +2,6 @@ "engine_name": "o3de", "FileVersion": 1, "O3DEVersion": "0.0.0.0", - "O3DECopyrightYear": 2021 + "O3DECopyrightYear": 2021, + "O3DEBuildNumber": 0 } From 92c74a1aaa8dab978cea802e7af3a49114f27ebe Mon Sep 17 00:00:00 2001 From: phistere Date: Fri, 7 May 2021 20:06:12 -0500 Subject: [PATCH 030/811] Fixing minor spacing, spelling, and print formatting. --- .../AzCore/AzCore/Component/ComponentApplication.cpp | 2 +- Code/Framework/AzCore/AzCore/Module/ModuleManager.cpp | 2 +- Code/LauncherUnified/Launcher.cpp | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index d0f277a6b8..6ba985d032 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -1215,7 +1215,7 @@ namespace AZ // So auto load is turned off if option "AutoLoad" key is bool that is false if (valueName == "AutoLoad" && !value) { - // Strip off the AutoLoead entry from the path + // Strip off the AutoLoad entry from the path auto autoLoadKey = AZ::StringFunc::TokenizeLast(path, "/"); if (!autoLoadKey) { diff --git a/Code/Framework/AzCore/AzCore/Module/ModuleManager.cpp b/Code/Framework/AzCore/AzCore/Module/ModuleManager.cpp index fe41050b00..0ce3ee5d8d 100644 --- a/Code/Framework/AzCore/AzCore/Module/ModuleManager.cpp +++ b/Code/Framework/AzCore/AzCore/Module/ModuleManager.cpp @@ -512,7 +512,7 @@ namespace AZ // Load DLLs specified in the application descriptor for (const auto& moduleDescriptor : modules) { - // For each module that is loaded, attempt to set the module's folder as a path for dependent module resolution + // For each module that is loaded, attempt to set the module's folder as a path for dependent module resolution moduleSearchPathHelper.SetModuleSearchPath(moduleDescriptor); LoadModuleOutcome result = LoadDynamicModule(moduleDescriptor.m_dynamicLibraryPath.c_str(), lastStepToPerform, maintainReferences); diff --git a/Code/LauncherUnified/Launcher.cpp b/Code/LauncherUnified/Launcher.cpp index 033169ac6d..26962dfe03 100644 --- a/Code/LauncherUnified/Launcher.cpp +++ b/Code/LauncherUnified/Launcher.cpp @@ -488,8 +488,8 @@ namespace O3DELauncher const AZStd::string_view buildTargetName = GetBuildTargetName(); AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddBuildSystemTargetSpecialization(*settingsRegistry, buildTargetName); - AZ_TracePrintf("Launcher", R"(Running project "%.*s.)" "\n" - R"(The project name value has been successfully set in the Settings Registry at key "%s/project_name)" + AZ_TracePrintf("Launcher", R"(Running project "%.*s")" "\n" + R"(The project name has been successfully set in the Settings Registry at key "%s/project_name")" R"( for Launcher target "%.*s")" "\n", aznumeric_cast(launcherProjectName.size()), launcherProjectName.data(), AZ::SettingsRegistryMergeUtils::ProjectSettingsRootKey, From 65550d3f1c3ec5d011485a8d9fdbe973b6789710 Mon Sep 17 00:00:00 2001 From: igarri Date: Mon, 10 May 2021 10:39:01 +0100 Subject: [PATCH 031/811] Entries updating on the table view --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 4 +- .../AssetBrowser/AssetBrowserModel.cpp | 3 +- .../AssetBrowser/AssetBrowserTableModel.cpp | 264 ++++++++++++++++-- .../AssetBrowser/AssetBrowserTableModel.h | 79 +++++- .../Views/AssetBrowserTableView.cpp | 48 +++- .../Views/AssetBrowserTableView.h | 22 +- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 27 +- .../AzAssetBrowser/AzAssetBrowserWindow.h | 2 + 8 files changed, 395 insertions(+), 54 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 42498eb76e..5e9203cc29 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -31,7 +31,8 @@ namespace AzToolsFramework AssetBrowserFilterModel::AssetBrowserFilterModel(QObject* parent) : QSortFilterProxyModel(parent) { - m_showColumn.insert(AssetBrowserModel::m_column); + m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); + m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); m_collator.setNumericMode(true); AssetBrowserComponentNotificationBus::Handler::BusConnect(); } @@ -163,7 +164,6 @@ namespace AzToolsFramework { m_alreadyRecomputingFilters = false; FilterUpdatedSlotImmediate(); - //beginInsertRows() } ); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp index d7c0164435..1101e11f3a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp @@ -144,7 +144,8 @@ namespace AzToolsFramework if (parent.isValid()) { if ((parent.column() != static_cast(AssetBrowserEntry::Column::DisplayName)) && - (parent.column() != static_cast(AssetBrowserEntry::Column::Name))) + (parent.column() != static_cast(AssetBrowserEntry::Column::Name)) && + (parent.column() != static_cast(AssetBrowserEntry::Column::Path))) { return 0; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index e7a49b2d99..7480d17d47 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -1,4 +1,16 @@ -#include "AssetBrowserTableModel.h" +#include +#include +#include +#include +AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") + +#include +#include + +#include +#include +#include +AZ_POP_DISABLE_WARNING namespace AzToolsFramework { namespace AssetBrowser @@ -6,9 +18,24 @@ namespace AzToolsFramework AssetBrowserTableModel::AssetBrowserTableModel(QObject* parent /* = nullptr */) : QSortFilterProxyModel(parent) { - m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); - m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); + sort(0); + setDynamicSortFilter(false); + setRecursiveFilteringEnabled(true); + AssetBrowserComponentNotificationBus::Handler::BusConnect(); } + AssetBrowserTableModel::~AssetBrowserTableModel() + { + AssetBrowserComponentNotificationBus::Handler::BusDisconnect(); + } + void AssetBrowserTableModel::OnAssetBrowserComponentReady() + { + BuildMap(sourceModel()); + } + void AssetBrowserTableModel::setSourceModel(QAbstractItemModel* sourceModel) + { + QSortFilterProxyModel::setSourceModel(sourceModel); + } + QModelIndex AssetBrowserTableModel::mapToSource(const QModelIndex& proxyIndex) const { Q_ASSERT(!proxyIndex.isValid() || proxyIndex.model() == this); @@ -18,6 +45,11 @@ namespace AzToolsFramework } return m_indexMap[proxyIndex.row()]; } + QModelIndex AssetBrowserTableModel::parent(const QModelIndex& child) const + { + AZ_UNUSED(child); + return QModelIndex(); + } QModelIndex AssetBrowserTableModel::mapFromSource(const QModelIndex& sourceIndex) const { Q_ASSERT(!sourceIndex.isValid() || sourceIndex.model() == sourceModel()); @@ -27,16 +59,14 @@ namespace AzToolsFramework } return createIndex(m_rowMap[sourceIndex], sourceIndex.column(), sourceIndex.internalPointer()); } - //QModelIndex AssetBrowserTableModel::index(int row, int column, const QModelIndex& parent) const - //{ - // //return parent.isValid() ? QModelIndex() : createIndex(row, column , m_indexMap[row].internalPointer()); - // if (!parent.isValid()) - // { - // QModelIndex(); - // } - // return createIndex(row, column, m_indexMap[row].internalPointer()); - //} + QModelIndex AssetBrowserTableModel::index(int row, int column, const QModelIndex& parent) const + { + /*AZ_UNUSED(row); + AZ_UNUSED(column);*/ + return parent.isValid() ? QModelIndex() : createIndex(row, column, m_indexMap[row].internalPointer()); + } + QVariant AssetBrowserTableModel::data(const QModelIndex& index, int role) const { //AZ_UNUSED(role); @@ -47,34 +77,67 @@ namespace AzToolsFramework AssetBrowserEntry* entry = GetAssetEntry(sourceIndex); // static_cast(sourceIndex.internalPointer()); if (entry == nullptr) { - AZ_Assert(false, "ERROR - index internal pointer not pointing to an AssetEntry. Tree provided by the AssetBrowser invalid?"); + AZ_Assert( + false, "ERROR - index internal pointer not pointing to an AssetEntry. Tree provided by the AssetBrowser invalid?"); return Qt::PartiallyChecked; } - return sourceIndex.data(role); //return entry->data(index.column()); + return sourceIndex.data(role); // return entry->data(index.column()); //return QVariant::fromValue(entry); + //AZ_UNUSED(role); + //if (index.isValid()) + //{ + // ////if (role == AssetBrowserModel::EntryRole) + // //{ + // QModelIndex modelIndex = mapFromSource(index); + // auto assetEntry = static_cast(index.internalPointer()); + // return QVariant::fromValue(assetEntry); + //} + //return QVariant(); // AzToolsFramework::AssetBrowser::AssetBrowserModel::data(index, role); } - bool AssetBrowserTableModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const + + + int AssetBrowserTableModel::rowCount(const QModelIndex& parent) const { - AZ_UNUSED(source_row); - AZ_UNUSED(source_parent); - return true; - } - bool AssetBrowserTableModel::filterAcceptsColumn(int source_column, const QModelIndex&) const - { - return m_showColumn.find(source_column) != m_showColumn.end(); + return !parent.isValid() ? m_rowMap.size() : 0; } + int AssetBrowserTableModel::BuildMap(const QAbstractItemModel* model, const QModelIndex& parent, int row) { + //int rows = model ? model->rowCount(parent) : 0; + //for (int i = 0; i < rows; ++i) + //{ + // auto index = model->index(i, 0, parent); + // //if (!model->hasChildren(index)) + // //{ + // beginInsertRows(parent, row, row); + // m_rowMap[index] = row; + // m_indexMap[row] = index; + // endInsertRows(); + // Q_EMIT dataChanged(parent, parent); + // row = row + 1; + // //} + // if (model->hasChildren(index)) + // { + // row = BuildMap(model, index, row); + // } + //} + //return row; int rows = model ? model->rowCount(parent) : 0; for (int i = 0; i < rows; ++i) { auto index = model->index(i, 0, parent); + if (model->hasChildren(index) == false) + { + beginInsertRows(parent, row, row); + m_rowMap[index] = row; + m_indexMap[row] = index; + endInsertRows(); + Q_EMIT dataChanged(parent, parent); + row = row + 1; + } - m_rowMap[index] = row; - m_indexMap[row] = index; - row = row + 1; if (model->hasChildren(index)) { row = BuildMap(model, index, row); @@ -96,8 +159,159 @@ namespace AzToolsFramework } void AssetBrowserTableModel::UpdateMap() { + m_indexMap.clear(); + m_rowMap.clear(); BuildMap(sourceModel()); } + + //---------------------------------------AssetBrowserTableFilterModel-------------------------------------------- + AssetBrowserTableFilterModel::AssetBrowserTableFilterModel(QObject* parent) + : QSortFilterProxyModel(parent) + { + m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); + m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); + AssetBrowserComponentNotificationBus::Handler::BusConnect(); + } + + AssetBrowserTableFilterModel::~AssetBrowserTableFilterModel() + { + AssetBrowserComponentNotificationBus::Handler::BusDisconnect(); + } + + void AssetBrowserTableFilterModel::setSourceModel(QAbstractItemModel* sourceModel) + { + QSortFilterProxyModel::setSourceModel(sourceModel); + } + + void AssetBrowserTableFilterModel::SetFilter(FilterConstType filter) + { + connect(filter.data(), &AssetBrowserEntryFilter::updatedSignal, this, &AssetBrowserTableFilterModel::filterUpdatedSlot); + m_filter = filter; + m_invalidateFilter = true; + // asset browser entries are not guaranteed to have populated when the filter is set, delay filtering until they are + bool isAssetBrowserComponentReady = false; + AssetBrowserComponentRequestBus::BroadcastResult(isAssetBrowserComponentReady, &AssetBrowserComponentRequests::AreEntriesReady); + if (isAssetBrowserComponentReady) + { + OnAssetBrowserComponentReady(); + } + } + + void AssetBrowserTableFilterModel::FilterUpdatedSlotImmediate() + { + auto compFilter = qobject_cast>(m_filter); + if (compFilter) + { + auto& subFilters = compFilter->GetSubFilters(); + auto it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { + auto assetTypeFilter = qobject_cast>(filter); + return !assetTypeFilter.isNull(); + }); + if (it != subFilters.end()) + { + m_assetTypeFilter = qobject_cast>(*it); + } + it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { + auto stringFilter = qobject_cast>(filter); + return !stringFilter.isNull(); + }); + if (it != subFilters.end()) + { + m_stringFilter = qobject_cast>(*it); + } + } + invalidateFilter(); + Q_EMIT filterChanged(); + } + + void AssetBrowserTableFilterModel::OnAssetBrowserComponentReady() + { + if (m_invalidateFilter) + { + invalidateFilter(); + m_invalidateFilter = false; + } + Q_EMIT entriesUpdated(); + } + + bool AssetBrowserTableFilterModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const + { + AZ_UNUSED(source_row); + AZ_UNUSED(source_parent); + QModelIndex idx = sourceModel()->index(source_row, 0, source_parent); + if (!idx.isValid()) + { + return false; + } + // no filter present, every entry is visible + if (!m_filter) + { + return true; + } + + //// the entry is the internal pointer of the index + //auto entry = static_cast(idx.internalPointer()); + + //if (entry) + //{ + // // root should return true even if its not displayed in the treeview + // if (entry && entry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Root) + // { + // return true; + // } + // return m_filter->Match(entry); + //} + return true; + } + + bool AssetBrowserTableFilterModel::filterAcceptsColumn(int source_column, const QModelIndex&) const + { + return m_showColumn.find(source_column) != m_showColumn.end(); + } + + bool AssetBrowserTableFilterModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const + { + if (source_left.column() == source_right.column()) + { + QVariant leftData = sourceModel()->data(source_left, AssetBrowserModel::Roles::EntryRole); + QVariant rightData = sourceModel()->data(source_right, AssetBrowserModel::Roles::EntryRole); + if (leftData.canConvert() && rightData.canConvert()) + { + auto leftEntry = qvariant_cast(leftData); + auto rightEntry = qvariant_cast(rightData); + + // folders should always come first + if (azrtti_istypeof(leftEntry) && + azrtti_istypeof(rightEntry)) + { + return false; + } + if (azrtti_istypeof(leftEntry) && + azrtti_istypeof(rightEntry)) + { + return true; + } + + // if both entries are of same type, sort alphabetically + return m_collator.compare(leftEntry->GetDisplayName(), rightEntry->GetDisplayName()) > 0; + } + } + return QSortFilterProxyModel::lessThan(source_left, source_right); + } + + void AssetBrowserTableFilterModel::filterUpdatedSlot() + { + if (!m_alreadyRecomputingFilters) + { + m_alreadyRecomputingFilters = true; + // de-bounce it, since we may get many filter updates all at once. + QTimer::singleShot(0, this, [this]() { + m_alreadyRecomputingFilters = false; + FilterUpdatedSlotImmediate(); + }); + } + } + } // namespace AssetBrowser } // namespace AzToolsFramework #include "AssetBrowser/moc_AssetBrowserTableModel.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index ef87ad8512..8ffd1a469e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -21,32 +21,87 @@ namespace AzToolsFramework { class AssetBrowserTableModel : public QSortFilterProxyModel + , public AssetBrowserComponentNotificationBus::Handler { Q_OBJECT + public: AZ_CLASS_ALLOCATOR(AssetBrowserTableModel, AZ::SystemAllocator, 0); explicit AssetBrowserTableModel(QObject* parent = nullptr); - - QModelIndex mapToSource(const QModelIndex &proxyIndex) const override; - QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override; - //QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; + ~AssetBrowserTableModel(); + //////////////////////////////////////////////////////////////////// + // AssetBrowserComponentNotificationBus + //////////////////////////////////////////////////////////////////// + void OnAssetBrowserComponentReady() override; + void setSourceModel(QAbstractItemModel* sourceModel) override; + //////////////////////////////////////////////////////////////////// + // QSortFilterProxyModel + QModelIndex mapToSource(const QModelIndex& proxyIndex) const override; + QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override; + QModelIndex parent(const QModelIndex& child) const override; + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; public Q_SLOTS: void UpdateMap(); - protected: - bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; - bool filterAcceptsColumn(int source_column, const QModelIndex& /*source_parent*/) const override; + int rowCount(const QModelIndex& parent = QModelIndex()) const override; + //QVariant headerData(int section, Qt::Orientation orientation, int role /* = Qt::DisplayRole */) const override; + //////////////////////////////////////////////////////////////////// private: - int BuildMap(const QAbstractItemModel* model, const QModelIndex& parent = QModelIndex(), int row = 0); AssetBrowserEntry* GetAssetEntry(QModelIndex index) const; - + int BuildMap(const QAbstractItemModel* model, const QModelIndex& parent = QModelIndex(), int row = 0); private: - AZStd::fixed_unordered_set(AssetBrowserEntry::Column::Count)> m_showColumn; QMap m_indexMap; QMap m_rowMap; }; - } -} + + class AssetBrowserTableFilterModel + : public QSortFilterProxyModel + , public AssetBrowserComponentNotificationBus::Handler + { + Q_OBJECT + public: + explicit AssetBrowserTableFilterModel(QObject* parent = nullptr); + ~AssetBrowserTableFilterModel(); + + void setSourceModel(QAbstractItemModel* sourceModel) override; + // asset type filtering + void SetFilter(FilterConstType filter); + void FilterUpdatedSlotImmediate(); + + ////////////////////////////////////////////////////////////////////////// + // AssetBrowserComponentNotificationBus + ////////////////////////////////////////////////////////////////////////// + void OnAssetBrowserComponentReady() override; + + Q_SIGNALS: + void filterChanged(); + void entriesUpdated(); + + ////////////////////////////////////////////////////////////////////////// + // QSortFilterProxyModel + protected: + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; + bool filterAcceptsColumn(int source_column, const QModelIndex& /*source_parent*/) const override; + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + ////////////////////////////////////////////////////////////////////////// + + public Q_SLOTS: + void filterUpdatedSlot(); + + private: + AZStd::fixed_unordered_set(AssetBrowserEntry::Column::Count)> m_showColumn; + bool m_alreadyRecomputingFilters = false; + // asset source name match filter + FilterConstType m_filter; + AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // 4251: class '...' needs to have dll-interface to be used by clients of class '...' + QWeakPointer m_stringFilter; + QWeakPointer m_assetTypeFilter; + QCollator m_collator; // cache the collator as its somewhat expensive to constantly create and destroy one. + AZ_POP_DISABLE_WARNING + bool m_invalidateFilter = false; + }; + } // namespace AssetBrowser +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index 927deb0039..aa35d99894 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -41,13 +41,13 @@ namespace AzToolsFramework { setSortingEnabled(true); setItemDelegate(m_delegate); - // header()->hide(); + //header()->hide(); setContextMenuPolicy(Qt::CustomContextMenu); setMouseTracking(true); connect(this, &QTableView::customContextMenuRequested, this, &AssetBrowserTableView::OnContextMenu); - //connect(m_scTimer, &QTimer::timeout, this, &AssetBrowserTreeView::OnUpdateSCThumbnailsList); + connect(m_scTimer, &QTimer::timeout, this, &AssetBrowserTableView::OnUpdateSCThumbnailsList); AssetBrowserViewRequestBus::Handler::BusConnect(); AssetBrowserComponentNotificationBus::Handler::BusConnect(); @@ -59,9 +59,9 @@ namespace AzToolsFramework } void AssetBrowserTableView::setModel(QAbstractItemModel* model) { - m_sourceModel = qobject_cast(model); - AZ_Assert(m_sourceModel, "Expecting AssetBrowserTableModel"); - m_sourceFilterModel = qobject_cast(m_sourceModel->sourceModel()); + m_filterModel = qobject_cast(model); + AZ_Assert(m_filterModel, "Expecting AssetBrowserTableModel"); + m_sourceModel = qobject_cast(m_filterModel->sourceModel()); QTableView::setModel(model); } void AssetBrowserTableView::SetName(const QString& name) @@ -76,9 +76,40 @@ namespace AzToolsFramework } AZStd::vector AssetBrowserTableView::GetSelectedAssets() const { - return AZStd::vector(); - } + QModelIndexList sourceIndexes{}; + //for (const auto& index : selectedIndexes()) + //{ + // sourceIndexes.push_back(m_sourceModel->mapToSource(index)); + //} + AZStd::vector entries; + //AssetBrowserModel::SourceIndexesToAssetDatabaseEntries(sourceIndexes, entries); + return entries; + } + void AssetBrowserTableView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) + { + AZ_UNUSED(selected); + AZ_UNUSED(deselected); + } + void AssetBrowserTableView::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) + { + // if selected entry is being removed, clear selection so not to select (and attempt to preview) other entries potentially + // marked for deletion + if (selectionModel() && selectionModel()->selectedIndexes().size() == 1) + { + QModelIndex selectedIndex = selectionModel()->selectedIndexes().first(); + QModelIndex parentSelectedIndex = selectedIndex.parent(); + if (parentSelectedIndex == parent && selectedIndex.row() >= start && selectedIndex.row() <= end) + { + selectionModel()->clear(); + } + } + QTableView::rowsAboutToBeRemoved(parent, start, end); + } + void AssetBrowserTableView::OnUpdateSCThumbnailsList() + { + + } void AssetBrowserTableView::SelectProduct(AZ::Data::AssetId assetID) { AZ_UNUSED(assetID); @@ -91,6 +122,9 @@ namespace AzToolsFramework void AssetBrowserTableView::ClearFilter() { + emit ClearStringFilter(); + emit ClearTypeFilter(); + m_sourceModel->FilterUpdatedSlotImmediate(); } void AssetBrowserTableView::Update() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h index bec24cca9b..aef7353334 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -48,18 +48,32 @@ namespace AzToolsFramework void OnAssetBrowserComponentReady() override; ////////////////////////////////////////////////////////////////////////// - private Q_SLOTS: - void OnContextMenu(const QPoint& point); + + Q_SIGNALS: + void selectionChangedSignal(const QItemSelection& selected, const QItemSelection& deselected); + void ClearStringFilter(); + void ClearTypeFilter(); + + protected Q_SLOTS: + void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) override; + void rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) override; //! Get all visible source entries and place them in a queue to update their source control status //void OnUpdateSCThumbnailsList(); private: QString m_name; - QPointer m_sourceFilterModel = nullptr; - QPointer m_sourceModel = nullptr; + QPointer m_filterModel = nullptr; + QPointer m_sourceModel = nullptr; EntryDelegate* m_delegate = nullptr; + QTimer* m_scTimer = nullptr; + const int m_scUpdateInterval = 100; + + private Q_SLOTS: + void OnContextMenu(const QPoint& point); + //! Get all visible source entries and place them in a queue to update their source control status + void OnUpdateSCThumbnailsList(); }; } // namespace AssetBrowser } // namespace AzToolsFramework diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index d67ee0d0ca..fb850f4f26 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -68,6 +68,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) , m_ui(new Ui::AzAssetBrowserWindowClass()) , m_filterModel(new AzToolsFramework::AssetBrowser::AssetBrowserFilterModel(parent)) , m_tableModel(new AzToolsFramework::AssetBrowser::AssetBrowserTableModel(parent)) + , m_tableFilterModel(new AzToolsFramework::AssetBrowser::AssetBrowserTableFilterModel(parent)) { m_ui->setupUi(this); m_ui->m_searchWidget->Setup(true, true); @@ -82,12 +83,18 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_tableModel->setSourceModel(m_filterModel.data()); //m_tableModel->setSourceModel(m_assetBrowserModel); - m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); - m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); + m_tableFilterModel->setSourceModel(m_tableModel.data()); + m_tableFilterModel->SetFilter(m_ui->m_searchWidget->GetFilter()); + + m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); + m_ui->m_assetBrowserTreeViewWidget->hideColumn(static_cast(AssetBrowserEntry::Column::Path)); + + //m_ui->m_assetBrowserTableViewWidget->setModel(m_tableFilterModel.data()); + m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); m_ui->m_assetBrowserTableViewWidget->setVisible(false); - connect(m_filterModel.data(), &AssetBrowserFilterModel::entriesUpdated, m_tableModel.data(), &AssetBrowserTableModel::UpdateMap); + //connect(m_filterModel.data(), &AssetBrowserFilterModel::entriesUpdated, m_tableModel.data(), &AssetBrowserTableModel::UpdateMap); connect(m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), &AssetBrowserFilterModel::filterUpdatedSlot); @@ -97,6 +104,17 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) const bool selectFirstFilteredIndex = false; m_ui->m_assetBrowserTreeViewWidget->UpdateAfterFilter(hasFilter, selectFirstFilteredIndex); }); + + //connect( m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_tableFilterModel.data(), + // &AssetBrowserTableFilterModel::filterUpdatedSlot); + //connect(m_tableFilterModel.data(), &AssetBrowserTableFilterModel::filterChanged, this, [this]() { + // const bool hasFilter = !m_ui->m_searchWidget->GetFilterString().isEmpty(); + // const bool selectFirstFilteredIndex = false; + // m_ui->m_assetBrowserTableViewWidget->UpdateAfterFilter(hasFilter, selectFirstFilteredIndex); + //}); + + connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, m_tableModel.data(), &AssetBrowserTableModel::UpdateMap); + connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); connect(m_ui->m_assetBrowserTreeViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); @@ -104,6 +122,9 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, &SearchWidget::ClearStringFilter); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, &SearchWidget::ClearTypeFilter); + connect(m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::ClearStringFilter, m_ui->m_searchWidget, &SearchWidget::ClearStringFilter); + connect(m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::ClearTypeFilter, m_ui->m_searchWidget, &SearchWidget::ClearTypeFilter); + m_ui->m_assetBrowserTreeViewWidget->SetName("AssetBrowserTreeView_main"); m_ui->m_assetBrowserTableViewWidget->SetName("AssetBrowserTableView_main"); diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h index 1a5604b98f..a8a8474ef8 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h @@ -31,6 +31,7 @@ namespace AzToolsFramework class AssetBrowserFilterModel; class AssetBrowserTableModel; class AssetBrowserModel; + class AssetBrowserTableFilterModel; } } @@ -55,6 +56,7 @@ private: QScopedPointer m_ui; QScopedPointer m_filterModel; QScopedPointer m_tableModel; + QScopedPointer m_tableFilterModel; AzToolsFramework::AssetBrowser::AssetBrowserModel* m_assetBrowserModel; void UpdatePreview() const; From 6e15e87e41d610391facaeb210bc0d5b484c1d1c Mon Sep 17 00:00:00 2001 From: igarri Date: Mon, 10 May 2021 15:52:35 +0100 Subject: [PATCH 032/811] Asset Browser Table view filtering --- .../AssetBrowser/AssetBrowserFilterModel.h | 2 +- .../AssetBrowser/AssetBrowserTableModel.cpp | 302 ++++++++++-------- .../AssetBrowser/AssetBrowserTableModel.h | 87 ++--- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 6 +- .../AzAssetBrowser/AzAssetBrowserWindow.h | 2 +- 5 files changed, 217 insertions(+), 182 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h index 6aa1a08e45..3fff43859f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h @@ -45,7 +45,7 @@ namespace AzToolsFramework //asset type filtering void SetFilter(FilterConstType filter); void FilterUpdatedSlotImmediate(); - + const FilterConstType& GetFilter() const { return m_filter; } ////////////////////////////////////////////////////////////////////////// // AssetBrowserComponentNotificationBus ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 7480d17d47..b75d3e9400 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -5,7 +5,7 @@ AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") #include -#include +#include #include #include @@ -29,10 +29,12 @@ namespace AzToolsFramework } void AssetBrowserTableModel::OnAssetBrowserComponentReady() { - BuildMap(sourceModel()); + //BuildMap(sourceModel()); } void AssetBrowserTableModel::setSourceModel(QAbstractItemModel* sourceModel) { + m_filterModel = qobject_cast(sourceModel); + AZ_Assert(m_filterModel, "Expecting AssetBrowserFilterModel"); QSortFilterProxyModel::setSourceModel(sourceModel); } @@ -60,6 +62,18 @@ namespace AzToolsFramework return createIndex(m_rowMap[sourceIndex], sourceIndex.column(), sourceIndex.internalPointer()); } + bool AssetBrowserTableModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const + { + AZ_UNUSED(source_row); + AZ_UNUSED(source_parent); + // no filter present, every entry is not visible + if (!m_filterModel->GetFilter()) + { + return false; + } + return true; + } + QModelIndex AssetBrowserTableModel::index(int row, int column, const QModelIndex& parent) const { /*AZ_UNUSED(row); @@ -159,158 +173,172 @@ namespace AzToolsFramework } void AssetBrowserTableModel::UpdateMap() { - m_indexMap.clear(); - m_rowMap.clear(); + //m_indexMap.clear(); + //m_rowMap.clear(); + + if (m_indexMap.size() > 0) + { + //beginRemoveRows(m_indexMap.first().parent(), m_indexMap.first().row(), m_indexMap.last().row()); + for (const auto& key : m_indexMap.keys()) + { + beginRemoveRows(m_indexMap[key], m_indexMap[key].row(), m_indexMap[key].row()); + m_rowMap.remove(m_indexMap[key]); + m_indexMap.remove(key); + endRemoveRows(); + } + //endRemoveRows(); + } + BuildMap(sourceModel()); } //---------------------------------------AssetBrowserTableFilterModel-------------------------------------------- - AssetBrowserTableFilterModel::AssetBrowserTableFilterModel(QObject* parent) - : QSortFilterProxyModel(parent) - { - m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); - m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); - AssetBrowserComponentNotificationBus::Handler::BusConnect(); - } + //AssetBrowserTableFilterModel::AssetBrowserTableFilterModel(QObject* parent) + // : QSortFilterProxyModel(parent) + //{ + // m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); + // m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); + // AssetBrowserComponentNotificationBus::Handler::BusConnect(); + //} - AssetBrowserTableFilterModel::~AssetBrowserTableFilterModel() - { - AssetBrowserComponentNotificationBus::Handler::BusDisconnect(); - } + //AssetBrowserTableFilterModel::~AssetBrowserTableFilterModel() + //{ + // AssetBrowserComponentNotificationBus::Handler::BusDisconnect(); + //} - void AssetBrowserTableFilterModel::setSourceModel(QAbstractItemModel* sourceModel) - { - QSortFilterProxyModel::setSourceModel(sourceModel); - } + //void AssetBrowserTableFilterModel::setSourceModel(QAbstractItemModel* sourceModel) + //{ + // QSortFilterProxyModel::setSourceModel(sourceModel); + //} - void AssetBrowserTableFilterModel::SetFilter(FilterConstType filter) - { - connect(filter.data(), &AssetBrowserEntryFilter::updatedSignal, this, &AssetBrowserTableFilterModel::filterUpdatedSlot); - m_filter = filter; - m_invalidateFilter = true; - // asset browser entries are not guaranteed to have populated when the filter is set, delay filtering until they are - bool isAssetBrowserComponentReady = false; - AssetBrowserComponentRequestBus::BroadcastResult(isAssetBrowserComponentReady, &AssetBrowserComponentRequests::AreEntriesReady); - if (isAssetBrowserComponentReady) - { - OnAssetBrowserComponentReady(); - } - } + //void AssetBrowserTableFilterModel::SetFilter(FilterConstType filter) + //{ + // connect(filter.data(), &AssetBrowserEntryFilter::updatedSignal, this, &AssetBrowserTableFilterModel::filterUpdatedSlot); + // m_filter = filter; + // m_invalidateFilter = true; + // // asset browser entries are not guaranteed to have populated when the filter is set, delay filtering until they are + // bool isAssetBrowserComponentReady = false; + // AssetBrowserComponentRequestBus::BroadcastResult(isAssetBrowserComponentReady, &AssetBrowserComponentRequests::AreEntriesReady); + // if (isAssetBrowserComponentReady) + // { + // OnAssetBrowserComponentReady(); + // } + //} - void AssetBrowserTableFilterModel::FilterUpdatedSlotImmediate() - { - auto compFilter = qobject_cast>(m_filter); - if (compFilter) - { - auto& subFilters = compFilter->GetSubFilters(); - auto it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { - auto assetTypeFilter = qobject_cast>(filter); - return !assetTypeFilter.isNull(); - }); - if (it != subFilters.end()) - { - m_assetTypeFilter = qobject_cast>(*it); - } - it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { - auto stringFilter = qobject_cast>(filter); - return !stringFilter.isNull(); - }); - if (it != subFilters.end()) - { - m_stringFilter = qobject_cast>(*it); - } - } - invalidateFilter(); - Q_EMIT filterChanged(); - } + //void AssetBrowserTableFilterModel::FilterUpdatedSlotImmediate() + //{ + // auto compFilter = qobject_cast>(m_filter); + // if (compFilter) + // { + // auto& subFilters = compFilter->GetSubFilters(); + // auto it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { + // auto assetTypeFilter = qobject_cast>(filter); + // return !assetTypeFilter.isNull(); + // }); + // if (it != subFilters.end()) + // { + // m_assetTypeFilter = qobject_cast>(*it); + // } + // it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { + // auto stringFilter = qobject_cast>(filter); + // return !stringFilter.isNull(); + // }); + // if (it != subFilters.end()) + // { + // m_stringFilter = qobject_cast>(*it); + // } + // } + // invalidateFilter(); + // Q_EMIT filterChanged(); + //} - void AssetBrowserTableFilterModel::OnAssetBrowserComponentReady() - { - if (m_invalidateFilter) - { - invalidateFilter(); - m_invalidateFilter = false; - } - Q_EMIT entriesUpdated(); - } + //void AssetBrowserTableFilterModel::OnAssetBrowserComponentReady() + //{ + // if (m_invalidateFilter) + // { + // invalidateFilter(); + // m_invalidateFilter = false; + // } + // Q_EMIT entriesUpdated(); + //} - bool AssetBrowserTableFilterModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const - { - AZ_UNUSED(source_row); - AZ_UNUSED(source_parent); - QModelIndex idx = sourceModel()->index(source_row, 0, source_parent); - if (!idx.isValid()) - { - return false; - } - // no filter present, every entry is visible - if (!m_filter) - { - return true; - } + //bool AssetBrowserTableFilterModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const + //{ + // AZ_UNUSED(source_row); + // AZ_UNUSED(source_parent); + // QModelIndex idx = sourceModel()->index(source_row, 0, source_parent); + // if (!idx.isValid()) + // { + // return false; + // } + // // no filter present, every entry is visible + // if (!m_filter) + // { + // return true; + // } - //// the entry is the internal pointer of the index - //auto entry = static_cast(idx.internalPointer()); + // //// the entry is the internal pointer of the index + // //auto entry = static_cast(idx.internalPointer()); - //if (entry) - //{ - // // root should return true even if its not displayed in the treeview - // if (entry && entry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Root) - // { - // return true; - // } - // return m_filter->Match(entry); - //} - return true; - } + // //if (entry) + // //{ + // // // root should return true even if its not displayed in the treeview + // // if (entry && entry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Root) + // // { + // // return true; + // // } + // // return m_filter->Match(entry); + // //} + // return true; + //} - bool AssetBrowserTableFilterModel::filterAcceptsColumn(int source_column, const QModelIndex&) const - { - return m_showColumn.find(source_column) != m_showColumn.end(); - } + //bool AssetBrowserTableFilterModel::filterAcceptsColumn(int source_column, const QModelIndex&) const + //{ + // return m_showColumn.find(source_column) != m_showColumn.end(); + //} - bool AssetBrowserTableFilterModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const - { - if (source_left.column() == source_right.column()) - { - QVariant leftData = sourceModel()->data(source_left, AssetBrowserModel::Roles::EntryRole); - QVariant rightData = sourceModel()->data(source_right, AssetBrowserModel::Roles::EntryRole); - if (leftData.canConvert() && rightData.canConvert()) - { - auto leftEntry = qvariant_cast(leftData); - auto rightEntry = qvariant_cast(rightData); + //bool AssetBrowserTableFilterModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const + //{ + // if (source_left.column() == source_right.column()) + // { + // QVariant leftData = sourceModel()->data(source_left, AssetBrowserModel::Roles::EntryRole); + // QVariant rightData = sourceModel()->data(source_right, AssetBrowserModel::Roles::EntryRole); + // if (leftData.canConvert() && rightData.canConvert()) + // { + // auto leftEntry = qvariant_cast(leftData); + // auto rightEntry = qvariant_cast(rightData); - // folders should always come first - if (azrtti_istypeof(leftEntry) && - azrtti_istypeof(rightEntry)) - { - return false; - } - if (azrtti_istypeof(leftEntry) && - azrtti_istypeof(rightEntry)) - { - return true; - } + // // folders should always come first + // if (azrtti_istypeof(leftEntry) && + // azrtti_istypeof(rightEntry)) + // { + // return false; + // } + // if (azrtti_istypeof(leftEntry) && + // azrtti_istypeof(rightEntry)) + // { + // return true; + // } - // if both entries are of same type, sort alphabetically - return m_collator.compare(leftEntry->GetDisplayName(), rightEntry->GetDisplayName()) > 0; - } - } - return QSortFilterProxyModel::lessThan(source_left, source_right); - } + // // if both entries are of same type, sort alphabetically + // return m_collator.compare(leftEntry->GetDisplayName(), rightEntry->GetDisplayName()) > 0; + // } + // } + // return QSortFilterProxyModel::lessThan(source_left, source_right); + //} - void AssetBrowserTableFilterModel::filterUpdatedSlot() - { - if (!m_alreadyRecomputingFilters) - { - m_alreadyRecomputingFilters = true; - // de-bounce it, since we may get many filter updates all at once. - QTimer::singleShot(0, this, [this]() { - m_alreadyRecomputingFilters = false; - FilterUpdatedSlotImmediate(); - }); - } - } + //void AssetBrowserTableFilterModel::filterUpdatedSlot() + //{ + // if (!m_alreadyRecomputingFilters) + // { + // m_alreadyRecomputingFilters = true; + // // de-bounce it, since we may get many filter updates all at once. + // QTimer::singleShot(0, this, [this]() { + // m_alreadyRecomputingFilters = false; + // FilterUpdatedSlotImmediate(); + // }); + // } + //} } // namespace AssetBrowser } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index 8ffd1a469e..34cf8432ff 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -7,6 +7,8 @@ #include #include #include +//#include +#include AZ_PUSH_DISABLE_WARNING( 4251, "-Wunknown-warning-option") // 4251: class '...' needs to have dll-interface to be used by clients of class '...' @@ -19,6 +21,9 @@ namespace AzToolsFramework { namespace AssetBrowser { + class AssetBrowserFilterModel; + + class AssetBrowserTableModel : public QSortFilterProxyModel , public AssetBrowserComponentNotificationBus::Handler @@ -38,6 +43,7 @@ namespace AzToolsFramework // QSortFilterProxyModel QModelIndex mapToSource(const QModelIndex& proxyIndex) const override; QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override; + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; QModelIndex parent(const QModelIndex& child) const override; QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; @@ -53,55 +59,56 @@ namespace AzToolsFramework AssetBrowserEntry* GetAssetEntry(QModelIndex index) const; int BuildMap(const QAbstractItemModel* model, const QModelIndex& parent = QModelIndex(), int row = 0); private: + QPointer m_filterModel; QMap m_indexMap; QMap m_rowMap; }; - class AssetBrowserTableFilterModel - : public QSortFilterProxyModel - , public AssetBrowserComponentNotificationBus::Handler - { - Q_OBJECT - public: - explicit AssetBrowserTableFilterModel(QObject* parent = nullptr); - ~AssetBrowserTableFilterModel(); + //class AssetBrowserTableFilterModel + // : public QSortFilterProxyModel + // , public AssetBrowserComponentNotificationBus::Handler + //{ + // Q_OBJECT + //public: + // explicit AssetBrowserTableFilterModel(QObject* parent = nullptr); + // ~AssetBrowserTableFilterModel(); - void setSourceModel(QAbstractItemModel* sourceModel) override; - // asset type filtering - void SetFilter(FilterConstType filter); - void FilterUpdatedSlotImmediate(); + // void setSourceModel(QAbstractItemModel* sourceModel) override; + // // asset type filtering + // void SetFilter(FilterConstType filter); + // void FilterUpdatedSlotImmediate(); - ////////////////////////////////////////////////////////////////////////// - // AssetBrowserComponentNotificationBus - ////////////////////////////////////////////////////////////////////////// - void OnAssetBrowserComponentReady() override; + // ////////////////////////////////////////////////////////////////////////// + // // AssetBrowserComponentNotificationBus + // ////////////////////////////////////////////////////////////////////////// + // void OnAssetBrowserComponentReady() override; - Q_SIGNALS: - void filterChanged(); - void entriesUpdated(); + //Q_SIGNALS: + // void filterChanged(); + // void entriesUpdated(); - ////////////////////////////////////////////////////////////////////////// - // QSortFilterProxyModel - protected: - bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; - bool filterAcceptsColumn(int source_column, const QModelIndex& /*source_parent*/) const override; - bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; - ////////////////////////////////////////////////////////////////////////// + // ////////////////////////////////////////////////////////////////////////// + // // QSortFilterProxyModel + //protected: + // bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; + // bool filterAcceptsColumn(int source_column, const QModelIndex& /*source_parent*/) const override; + // bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + // ////////////////////////////////////////////////////////////////////////// - public Q_SLOTS: - void filterUpdatedSlot(); + //public Q_SLOTS: + // void filterUpdatedSlot(); - private: - AZStd::fixed_unordered_set(AssetBrowserEntry::Column::Count)> m_showColumn; - bool m_alreadyRecomputingFilters = false; - // asset source name match filter - FilterConstType m_filter; - AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // 4251: class '...' needs to have dll-interface to be used by clients of class '...' - QWeakPointer m_stringFilter; - QWeakPointer m_assetTypeFilter; - QCollator m_collator; // cache the collator as its somewhat expensive to constantly create and destroy one. - AZ_POP_DISABLE_WARNING - bool m_invalidateFilter = false; - }; + //private: + // AZStd::fixed_unordered_set(AssetBrowserEntry::Column::Count)> m_showColumn; + // bool m_alreadyRecomputingFilters = false; + // // asset source name match filter + // FilterConstType m_filter; + // AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // 4251: class '...' needs to have dll-interface to be used by clients of class '...' + // QWeakPointer m_stringFilter; + // QWeakPointer m_assetTypeFilter; + // QCollator m_collator; // cache the collator as its somewhat expensive to constantly create and destroy one. + // AZ_POP_DISABLE_WARNING + // bool m_invalidateFilter = false; + //}; } // namespace AssetBrowser } // namespace AzToolsFramework diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index fb850f4f26..dd4b3b0cad 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -68,7 +68,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) , m_ui(new Ui::AzAssetBrowserWindowClass()) , m_filterModel(new AzToolsFramework::AssetBrowser::AssetBrowserFilterModel(parent)) , m_tableModel(new AzToolsFramework::AssetBrowser::AssetBrowserTableModel(parent)) - , m_tableFilterModel(new AzToolsFramework::AssetBrowser::AssetBrowserTableFilterModel(parent)) + /*, m_tableFilterModel(new AzToolsFramework::AssetBrowser::AssetBrowserTableFilterModel(parent))*/ { m_ui->setupUi(this); m_ui->m_searchWidget->Setup(true, true); @@ -83,8 +83,8 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_tableModel->setSourceModel(m_filterModel.data()); //m_tableModel->setSourceModel(m_assetBrowserModel); - m_tableFilterModel->setSourceModel(m_tableModel.data()); - m_tableFilterModel->SetFilter(m_ui->m_searchWidget->GetFilter()); + //m_tableFilterModel->setSourceModel(m_tableModel.data()); + //m_tableFilterModel->SetFilter(m_ui->m_searchWidget->GetFilter()); m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h index a8a8474ef8..801af3e2a8 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h @@ -56,7 +56,7 @@ private: QScopedPointer m_ui; QScopedPointer m_filterModel; QScopedPointer m_tableModel; - QScopedPointer m_tableFilterModel; + //QScopedPointer m_tableFilterModel; AzToolsFramework::AssetBrowser::AssetBrowserModel* m_assetBrowserModel; void UpdatePreview() const; From ac7024cc06d4c43a121ee6b28e480ca8bcd08e45 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 10 May 2021 11:19:35 -0700 Subject: [PATCH 033/811] Making install to be completely a post-processing step. We need this so all dependencies are declared and ready when we generate the target files --- cmake/Install.cmake | 6 - cmake/LYWrappers.cmake | 83 +++---- cmake/LyAutoGen.cmake | 2 +- cmake/Platform/Common/Install_common.cmake | 229 ++++++++---------- .../Common/RuntimeDependencies_common.cmake | 29 ++- cmake/Platform/Mac/Install_mac.cmake | 6 - cmake/Platform/iOS/Install_ios.cmake | 6 - .../iOS/RuntimeDependencies_ios.cmake | 6 +- .../LYTestImpactFramework.cmake | 5 +- cmake/install/TargetCMakeLists.txt.in | 4 +- 10 files changed, 165 insertions(+), 211 deletions(-) diff --git a/cmake/Install.cmake b/cmake/Install.cmake index 73a3273dfa..205277f0e5 100644 --- a/cmake/Install.cmake +++ b/cmake/Install.cmake @@ -12,10 +12,4 @@ if(NOT INSTALLED_ENGINE) ly_get_absolute_pal_filename(pal_dir ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Platform/${PAL_PLATFORM_NAME}) include(${pal_dir}/Install_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) -else() - - # Provide empty implementation so ly_add_target continues working - function(ly_install_target ly_install_target_NAME) - endfunction() - endif() \ No newline at end of file diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index 62509582a1..8640b460de 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -202,7 +202,7 @@ function(ly_add_target) endif() if (ly_add_target_INCLUDE_DIRECTORIES) - ly_target_include_directories(${ly_add_target_NAME} + target_include_directories(${ly_add_target_NAME} ${ly_add_target_INCLUDE_DIRECTORIES} ) endif() @@ -299,7 +299,7 @@ function(ly_add_target) endif() # Store the target so we can walk through all of them in LocationDependencies.cmake - set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGETS ${ly_add_target_NAME}) + set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGETS ${interface_name}) set(runtime_dependencies_list SHARED MODULE EXECUTABLE APPLICATION) if(linking_options IN_LIST runtime_dependencies_list) @@ -330,18 +330,6 @@ function(ly_add_target) ) endif() - if(NOT ly_add_target_IMPORTED) - ly_install_target( - ${ly_add_target_NAME} - NAMESPACE ${ly_add_target_NAMESPACE} - INCLUDE_DIRECTORIES ${ly_add_target_INCLUDE_DIRECTORIES} - BUILD_DEPENDENCIES ${ly_add_target_BUILD_DEPENDENCIES} - RUNTIME_DEPENDENCIES ${ly_add_target_RUNTIME_DEPENDENCIES} - COMPILE_DEFINITIONS ${ly_add_target_COMPILE_DEFINITIONS} - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} - ) - endif() - endfunction() #! ly_target_link_libraries: wraps target_link_libraries handling also MODULE linkage. @@ -401,7 +389,7 @@ function(ly_delayed_target_link_libraries) endif() if(item_type STREQUAL MODULE_LIBRARY) - ly_target_include_directories(${target} ${visibility} $) + target_include_directories(${target} ${visibility} $) target_link_libraries(${target} ${visibility} $) target_compile_definitions(${target} ${visibility} $) target_compile_options(${target} ${visibility} $) @@ -502,7 +490,7 @@ endfunction() # Looks at the the following variables within the platform include file to set the equivalent target properties # LY_FILES_CMAKE -> extract list of files -> target_sources # LY_FILES -> target_source -# LY_INCLUDE_DIRECTORIES -> ly_target_include_directories +# LY_INCLUDE_DIRECTORIES -> target_include_directories # LY_COMPILE_DEFINITIONS -> target_compile_definitions # LY_COMPILE_OPTIONS -> target_compile_options # LY_LINK_OPTIONS -> target_link_options @@ -528,7 +516,11 @@ macro(ly_configure_target_platform_properties) message(FATAL_ERROR "The supplied PLATFORM_INCLUDE_FILE(${platform_include_file}) cannot be included.\ Parsing of target will halt") endif() - target_sources(${ly_add_target_NAME} PRIVATE ${platform_include_file}) + if(ly_add_target_HEADERONLY) + target_sources(${ly_add_target_NAME} INTERFACE ${platform_include_file}) + else() + target_sources(${ly_add_target_NAME} PRIVATE ${platform_include_file}) + endif() ly_source_groups_from_folders("${platform_include_file}") if(LY_FILES_CMAKE) @@ -544,7 +536,7 @@ macro(ly_configure_target_platform_properties) target_sources(${ly_add_target_NAME} PRIVATE ${LY_FILES}) endif() if (LY_INCLUDE_DIRECTORIES) - ly_target_include_directories(${ly_add_target_NAME} ${LY_INCLUDE_DIRECTORIES}) + target_include_directories(${ly_add_target_NAME} ${LY_INCLUDE_DIRECTORIES}) endif() if(LY_COMPILE_DEFINITIONS) target_compile_definitions(${ly_add_target_NAME} ${LY_COMPILE_DEFINITIONS}) @@ -647,42 +639,6 @@ function(ly_add_source_properties) endfunction() -function(ly_target_include_directories TARGET) - - # Add the includes to the build and install interface - set(reserved_keywords PRIVATE PUBLIC INTERFACE) - unset(last_keyword) - foreach(include ${ARGN}) - if(${include} IN_LIST reserved_keywords) - list(APPEND adapted_includes ${include}) - elseif(IS_ABSOLUTE ${include}) - list(APPEND adapted_includes - $ - ) - else() - string(GENEX_STRIP ${include} include_genex_expr) - if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions - # We will be installing the includes using the same directory structure used in our source tree. - # The INSTALL_INTERFACE path tells CMake the location of the includes relative to the install prefix. - # When the target is imported into an external project, cmake will find these includes at /include/ - # where is the location of the lumberyard install on disk. - file(REAL_PATH ${include} include_real) - file(RELATIVE_PATH install_dir ${CMAKE_SOURCE_DIR} ${include_real}) - list(APPEND adapted_includes - $ - $ - ) - else() - list(APPEND adapted_includes - ${include} - ) - endif() - endif() - endforeach() - target_include_directories(${TARGET} ${adapted_includes}) - -endfunction() - #! ly_project_add_subdirectory: calls add_subdirectory() if the project name is in the project list # @@ -713,3 +669,22 @@ function(ly_project_add_subdirectory project_name) endif() endif() endfunction() + +# given a target name, returns the "real" name of the target if its an alias. +# this function recursively de-aliases +function(ly_de_alias_target target_name output_variable_name) + # its not okay to call get_target_property on a non-existant target + if (NOT TARGET ${target_name}) + message(FATAL_ERROR "ly_de_alias_target called on non-existant target: ${target_name}") + endif() + + while(target_name) + set(de_aliased_target_name ${target_name}) + get_target_property(target_name ${target_name} ALIASED_TARGET) + endwhile() + + if(NOT de_aliased_target_name) + message(FATAL_ERROR "Empty de_aliased for ${target_name}") + endif() + set(${output_variable_name} ${de_aliased_target_name} PARENT_SCOPE) +endfunction() \ No newline at end of file diff --git a/cmake/LyAutoGen.cmake b/cmake/LyAutoGen.cmake index 16a8a8de55..aa0e7f8d5a 100644 --- a/cmake/LyAutoGen.cmake +++ b/cmake/LyAutoGen.cmake @@ -26,7 +26,7 @@ function(ly_add_autogen) if(ly_add_autogen_AUTOGEN_RULES) set(AZCG_INPUTFILES ${ly_add_autogen_ALLFILES}) list(FILTER AZCG_INPUTFILES INCLUDE REGEX ".*\.(xml|json|jinja)$") - ly_target_include_directories(${ly_add_autogen_NAME} PUBLIC "${CMAKE_CURRENT_BINARY_DIR}/Azcg/Generated") + target_include_directories(${ly_add_autogen_NAME} PUBLIC "${CMAKE_CURRENT_BINARY_DIR}/Azcg/Generated") execute_process( COMMAND ${LY_PYTHON_CMD} "${LY_ROOT_FOLDER}/Code/Framework/AzAutoGen/AzAutoGen.py" "${CMAKE_BINARY_DIR}/Azcg/TemplateCache/" "${CMAKE_CURRENT_BINARY_DIR}/Azcg/Generated/" "${CMAKE_CURRENT_SOURCE_DIR}" "${AZCG_INPUTFILES}" "${ly_add_autogen_AUTOGEN_RULES}" "-n" OUTPUT_VARIABLE AUTOGEN_OUTPUTS diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index cef3251899..99ff0bbbe2 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -17,49 +17,61 @@ file(RELATIVE_PATH runtime_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_RUNTIME_ file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) set(install_output_folder "${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$") +#! ly_setup_targets: setups all targets +function(ly_setup_targets) + get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) + foreach(target IN LISTS all_targets) + ly_setup_target(${target}) + endforeach() +endfunction() -#! ly_install_target: registers the target to be installed by cmake install. -# -# \arg:NAME name of the target -# \arg:COMPONENT the grouping string of the target used for splitting up the install -# into smaller packages. -# All other parameters are forwarded to ly_generate_target_find_file -function(ly_install_target ly_install_target_NAME) +#! ly_setup_target: setups the target to be installed by cmake install. +function(ly_setup_target ALIAS_TARGET_NAME) - set(options) - set(oneValueArgs NAMESPACE COMPONENT) - set(multiValueArgs INCLUDE_DIRECTORIES BUILD_DEPENDENCIES RUNTIME_DEPENDENCIES COMPILE_DEFINITIONS) - - cmake_parse_arguments(ly_install_target "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + unset(TARGET_NAME) + ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) + + get_target_property(absolute_target_source_dir ${TARGET_NAME} SOURCE_DIR) + file(RELATIVE_PATH target_source_dir ${CMAKE_SOURCE_DIR} ${absolute_target_source_dir}) # All include directories marked PUBLIC or INTERFACE will be installed set(include_location "include") - get_target_property(include_directories ${ly_install_target_NAME} INTERFACE_INCLUDE_DIRECTORIES) - + get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) if (include_directories) - set_target_properties(${ly_install_target_NAME} PROPERTIES PUBLIC_HEADER "${include_directories}") - # The include directories are specified relative to the CMakeLists.txt file that adds the target. - # We need to install the includes relative to our source tree root because that's where INSTALL_INTERFACE - # will point CMake when it looks for headers - file(RELATIVE_PATH relative_path ${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}) - string(APPEND include_location "/${relative_path}") + unset(public_headers) + foreach(include_directory ${include_directories}) + string(GENEX_STRIP ${include_directory} include_genex_expr) + if(include_genex_expr STREQUAL include_directory) # only for cases where there are no generation expressions + unset(current_public_headers) + # We install all header types for the time being until we clean up certain libraries that contain all sorts + # of files in the public include directories (e.g. CryCommon) + file(GLOB_RECURSE current_public_headers + LIST_DIRECTORIES false + ${include_directory}/*.h + ${include_directory}/*.hpp + ${include_directory}/*.inl + ) + list(APPEND public_headers ${current_public_headers}) + endif() + endforeach() + set_target_properties(${TARGET_NAME} PROPERTIES PUBLIC_HEADER "${public_headers}") endif() # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target file(RELATIVE_PATH archive_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) - get_target_property(target_runtime_output_directory ${ly_install_target_NAME} RUNTIME_OUTPUT_DIRECTORY) + get_target_property(target_runtime_output_directory ${TARGET_NAME} RUNTIME_OUTPUT_DIRECTORY) if(target_runtime_output_directory) file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) endif() - get_target_property(target_library_output_directory ${ly_install_target_NAME} LIBRARY_OUTPUT_DIRECTORY) + get_target_property(target_library_output_directory ${TARGET_NAME} LIBRARY_OUTPUT_DIRECTORY) if(target_library_output_directory) file(RELATIVE_PATH target_library_output_subdirectory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${target_library_output_directory}) endif() install( - TARGETS ${ly_install_target_NAME} + TARGETS ${TARGET_NAME} ARCHIVE DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ COMPONENT ${ly_install_target_COMPONENT} @@ -70,81 +82,78 @@ function(ly_install_target ly_install_target_NAME) DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} COMPONENT ${ly_install_target_COMPONENT} PUBLIC_HEADER - DESTINATION ${include_location} + # The include directories are specified relative to the CMakeLists.txt file that adds the target. + # We need to install the includes relative to our source tree root + DESTINATION ${include_location}/${target_source_dir} COMPONENT ${ly_install_target_COMPONENT} ) - ly_generate_target_find_file(NAME ${ly_install_target_NAME} ${ARGN}) - ly_generate_target_config_file(${ly_install_target_NAME}) - -endfunction() - - -#! ly_generate_target_find_file: generates the Find${target}.cmake file which is used when importing installed packages. -# -# \arg:NAME name of the target -# \arg:NAMESPACE namespace declaration for this target. It will be used for IDE and dependencies -# \arg:INCLUDE_DIRECTORIES paths to the include directories -# \arg:BUILD_DEPENDENCIES list of interfaces this target depends on (could be a compilation dependency -# if the dependency is only exposing an include path, or could be a linking -# dependency is exposing a lib) -# \arg:RUNTIME_DEPENDENCIES list of dependencies this target depends on at runtime -# \arg:COMPILE_DEFINITIONS list of compilation definitions this target will use to compile -function(ly_generate_target_find_file) - - set(options) - set(oneValueArgs NAME NAMESPACE) - set(multiValueArgs INCLUDE_DIRECTORIES COMPILE_DEFINITIONS BUILD_DEPENDENCIES RUNTIME_DEPENDENCIES) - cmake_parse_arguments(ly_generate_target_find_file "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) - - set(NAME_PLACEHOLDER ${ly_generate_target_find_file_NAME}) - unset(NAMESPACE_PLACEHOLDER) - unset(COMPILE_DEFINITIONS_PLACEHOLDER) - unset(include_directories_interface_props) - unset(INCLUDE_DIRECTORIES_PLACEHOLDER) - set(RUNTIME_DEPENDENCIES_PLACEHOLDER ${ly_generate_target_find_file_RUNTIME_DEPENDENCIES}) - - # These targets will be imported. We will expose PUBLIC and INTERFACE properties as INTERFACE properties since - # only INTERFACE properties can be exposed on imported targets - ly_strip_private_properties(COMPILE_DEFINITIONS_PLACEHOLDER ${ly_generate_target_find_file_COMPILE_DEFINITIONS}) - ly_strip_private_properties(include_directories_interface_props ${ly_generate_target_find_file_INCLUDE_DIRECTORIES}) - ly_strip_private_properties(BUILD_DEPENDENCIES_PLACEHOLDER ${ly_generate_target_find_file_BUILD_DEPENDENCIES}) - - if(ly_generate_target_find_file_NAMESPACE) - set(NAMESPACE_PLACEHOLDER "NAMESPACE ${ly_generate_target_find_file_NAMESPACE}") + # CMakeLists.txt file + string(REGEX MATCH "(.*)::(.*)$" match ${ALIAS_TARGET_NAME}) + if(match) + set(NAMESPACE_PLACEHOLDER "NAMESPACE ${CMAKE_MATCH_1}") + set(NAME_PLACEHOLDER ${CMAKE_MATCH_2}) + else() + set(NAMESPACE_PLACEHOLDER "") + set(NAME_PLACEHOLDER ${TARGET_NAME}) endif() - string(REPLACE ";" "\n" COMPILE_DEFINITIONS_PLACEHOLDER "${COMPILE_DEFINITIONS_PLACEHOLDER}") + get_target_property(COMPILE_DEFINITIONS_PLACEHOLDER ${TARGET_NAME} INTERFACE_COMPILE_DEFINITIONS) + if(COMPILE_DEFINITIONS_PLACEHOLDER) + string(REPLACE ";" "\n" COMPILE_DEFINITIONS_PLACEHOLDER "${COMPILE_DEFINITIONS_PLACEHOLDER}") + else() + unset(COMPILE_DEFINITIONS_PLACEHOLDER) + endif() # Includes need additional processing to add the install root - foreach(include ${include_directories_interface_props}) - file(RELATIVE_PATH relative_path ${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/${include}) - string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${relative_path}\n") - endforeach() + get_target_property(include_directories_interface_props ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) + unset(INCLUDE_DIRECTORIES_PLACEHOLDER) + if(include_directories_interface_props) + foreach(include ${include_directories_interface_props}) + string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}\n") + endforeach() + endif() - string(REPLACE ";" "\n" BUILD_DEPENDENCIES_PLACEHOLDER "${BUILD_DEPENDENCIES_PLACEHOLDER}") - string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") + get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) + if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found + string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") + else() + unset(RUNTIME_DEPENDENCIES_PLACEHOLDER) + endif() - # Since a CMakeLists could contain multiple targets, we generate it in a folder per target - configure_file(${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/install/${ly_generate_target_find_file_NAME}/CMakeLists.txt @ONLY) - get_target_property(target_source_dir ${ly_generate_target_find_file_NAME} SOURCE_DIR) - file(RELATIVE_PATH target_source_dir_relative ${CMAKE_SOURCE_DIR} ${target_source_dir}) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${ly_generate_target_find_file_NAME}/CMakeLists.txt" - DESTINATION ${target_source_dir_relative}/${ly_generate_target_find_file_NAME} + get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES) + unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) + if(inteface_build_dependencies_props) + foreach(build_dependency ${inteface_build_dependencies_props}) + # Skip wrapping produced when targets are not created in the same directory + if(NOT ${build_dependency} MATCHES "^::@") + string(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}\n") + endif() + endforeach() + endif() + + # We also need to declare teh private link libraries since we will use that to generate the runtime dependencies + get_target_property(private_build_dependencies_props ${TARGET_NAME} LINK_LIBRARIES) + unset(PRIVATE_BUILD_DEPENDENCIES_PLACEHOLDER) + if(private_build_dependencies_props) + foreach(build_dependency ${private_build_dependencies_props}) + # Skip wrapping produced when targets are not created in the same directory + if(NOT ${build_dependency} MATCHES "^::@") + string(APPEND PRIVATE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}\n") + endif() + endforeach() + endif() + + # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target + configure_file(${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/CMakeLists.txt @ONLY) + + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/CMakeLists.txt" + DESTINATION ${target_source_dir}/${NAME_PLACEHOLDER} COMPONENT ${ly_install_target_COMPONENT} ) -endfunction() - - -#! ly_generate_target_config_file: generates the ${target}_$.cmake files for a target -# -# The generated file will set the location of the target binary per configuration -# These per config files will be included by the target's find file to set the location of the binary/ -# \arg:NAME name of the target -function(ly_generate_target_config_file NAME) - - get_target_property(target_type ${NAME} TYPE) + # Config file + get_target_property(target_type ${TARGET_NAME} TYPE) set(target_file_contents "# Generated by O3DE install\n\n") if(NOT target_type STREQUAL INTERFACE_LIBRARY) @@ -152,66 +161,43 @@ function(ly_generate_target_config_file NAME) unset(target_location) set(runtime_types EXECUTABLE APPLICATION) if(target_type IN_LIST runtime_types) - string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$\"") + string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$\"") elseif(target_type STREQUAL MODULE_LIBRARY) - string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\"") + string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\"") elseif(target_type STREQUAL SHARED_LIBRARY) - string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"") - string(APPEND target_file_contents "ly_add_target_files(TARGETS ${NAME} FILES \"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\")\n") + string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"") + string(APPEND target_file_contents "target_link_libraries(${TARGET_NAME} INTERFACE \"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\")\n") else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY - string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"") + string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"") endif() string(APPEND target_file_contents "set(target_location ${target_location}) -set_target_properties(${NAME} +set_target_properties(${TARGET_NAME} PROPERTIES $<$:IMPORTED_LOCATION \"\${target_location}\"> IMPORTED_LOCATION_$> \"\${target_location}\" ) if(EXISTS \"\${target_location}\") - set(${NAME}_$_FOUND TRUE) + set(${NAME_PLACEHOLDER}_$_FOUND TRUE) else() - set(${NAME}_$_FOUND FALSE) + set(${NAME_PLACEHOLDER}_$_FOUND FALSE) endif() ") endif() - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME}/${NAME}_$.cmake" CONTENT "${target_file_contents}") - get_target_property(target_source_dir ${NAME} SOURCE_DIR) - file(RELATIVE_PATH target_source_dir_relative ${CMAKE_SOURCE_DIR} ${target_source_dir}) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME}/${NAME}_$.cmake" - DESTINATION ${target_source_dir_relative}/${NAME} + file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/${NAME_PLACEHOLDER}_$.cmake" + DESTINATION ${target_source_dir}/${NAME_PLACEHOLDER} COMPONENT ${ly_install_target_COMPONENT} ) endfunction() - -#! ly_strip_private_properties: strips private properties since we're exporting an interface target -# -# \arg:INTERFACE_PROPERTIES list of interface properties to be returned -function(ly_strip_private_properties INTERFACE_PROPERTIES) - set(reserved_keywords PRIVATE PUBLIC INTERFACE) - unset(last_keyword) - unset(stripped_props) - foreach(prop ${ARGN}) - if(${prop} IN_LIST reserved_keywords) - set(last_keyword ${prop}) - else() - if (NOT last_keyword STREQUAL "PRIVATE") - list(APPEND stripped_props ${prop}) - endif() - endif() - endforeach() - - set(${INTERFACE_PROPERTIES} ${stripped_props} PARENT_SCOPE) -endfunction() - - #! ly_setup_o3de_install: orchestrates the installation of the different parts. This is the entry point from the root CMakeLists.txt function(ly_setup_o3de_install) + ly_setup_targets() ly_setup_cmake_install() ly_setup_target_generator() ly_setup_runtime_dependencies() @@ -479,7 +465,6 @@ function(ly_setup_others) endfunction() - #! ly_setup_target_generator: install source files needed for project launcher generation function(ly_setup_target_generator) diff --git a/cmake/Platform/Common/RuntimeDependencies_common.cmake b/cmake/Platform/Common/RuntimeDependencies_common.cmake index 859d1d21e3..333bbaaae2 100644 --- a/cmake/Platform/Common/RuntimeDependencies_common.cmake +++ b/cmake/Platform/Common/RuntimeDependencies_common.cmake @@ -212,7 +212,10 @@ function(ly_delayed_generate_runtime_dependencies) list(APPEND CMAKE_MODULE_PATH ${additional_module_paths}) get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) - foreach(target IN LISTS all_targets) + foreach(aliased_target IN LISTS all_targets) + + unset(target) + ly_de_alias_target(${aliased_target} target) # Exclude targets that dont produce runtime outputs get_target_property(target_type ${target} TYPE) @@ -222,18 +225,18 @@ function(ly_delayed_generate_runtime_dependencies) unset(runtime_dependencies) set(runtime_commands " - function(ly_copy source_file target_directory) - get_filename_component(target_filename \"\${source_file}\" NAME) - if(NOT \"\${source_file}\" STREQUAL \"\${target_directory}/\${target_filename}\") - if(NOT EXISTS \"\${target_directory}\") - file(MAKE_DIRECTORY \"\${target_directory}\") - endif() - if(\"\${source_file}\" IS_NEWER_THAN \"\${target_directory}/\${target_filename}\") - file(LOCK \"\${target_directory}/\${target_filename}.lock\" GUARD FUNCTION TIMEOUT 30) - file(COPY \"\${source_file}\" DESTINATION \"\${target_directory}\" FILE_PERMISSIONS ${LY_COPY_PERMISSIONS}) - endif() - endif() - endfunction() +function(ly_copy source_file target_directory) + get_filename_component(target_filename \"\${source_file}\" NAME) + if(NOT \"\${source_file}\" STREQUAL \"\${target_directory}/\${target_filename}\") + if(NOT EXISTS \"\${target_directory}\") + file(MAKE_DIRECTORY \"\${target_directory}\") + endif() + if(\"\${source_file}\" IS_NEWER_THAN \"\${target_directory}/\${target_filename}\") + file(LOCK \"\${target_directory}/\${target_filename}.lock\" GUARD FUNCTION TIMEOUT 30) + file(COPY \"\${source_file}\" DESTINATION \"\${target_directory}\" FILE_PERMISSIONS ${LY_COPY_PERMISSIONS}) + endif() + endif() +endfunction() \n") ly_get_runtime_dependencies(runtime_dependencies ${target}) diff --git a/cmake/Platform/Mac/Install_mac.cmake b/cmake/Platform/Mac/Install_mac.cmake index 8c96c199de..5c7959bf77 100644 --- a/cmake/Platform/Mac/Install_mac.cmake +++ b/cmake/Platform/Mac/Install_mac.cmake @@ -11,11 +11,5 @@ # Empty implementations for untested platforms to fix build errors. -function(ly_install_target ly_install_target_NAME) - -endfunction() - - function(ly_setup_o3de_install) - endfunction() \ No newline at end of file diff --git a/cmake/Platform/iOS/Install_ios.cmake b/cmake/Platform/iOS/Install_ios.cmake index 8c96c199de..5c7959bf77 100644 --- a/cmake/Platform/iOS/Install_ios.cmake +++ b/cmake/Platform/iOS/Install_ios.cmake @@ -11,11 +11,5 @@ # Empty implementations for untested platforms to fix build errors. -function(ly_install_target ly_install_target_NAME) - -endfunction() - - function(ly_setup_o3de_install) - endfunction() \ No newline at end of file diff --git a/cmake/Platform/iOS/RuntimeDependencies_ios.cmake b/cmake/Platform/iOS/RuntimeDependencies_ios.cmake index 034ab750ff..a2a6d30593 100644 --- a/cmake/Platform/iOS/RuntimeDependencies_ios.cmake +++ b/cmake/Platform/iOS/RuntimeDependencies_ios.cmake @@ -143,7 +143,11 @@ function(ly_delayed_generate_runtime_dependencies) get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) unset(test_runner_dependencies) - foreach(target IN LISTS all_targets) + foreach(aliased_target IN LISTS all_targets) + + unset(target) + ly_de_alias_target(${aliased_target} target) + # Exclude targets that dont produce runtime outputs get_target_property(target_type ${target} TYPE) if(NOT target_type IN_LIST LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS) diff --git a/cmake/TestImpactFramework/LYTestImpactFramework.cmake b/cmake/TestImpactFramework/LYTestImpactFramework.cmake index c10c5bf637..d46b16bca5 100644 --- a/cmake/TestImpactFramework/LYTestImpactFramework.cmake +++ b/cmake/TestImpactFramework/LYTestImpactFramework.cmake @@ -204,7 +204,10 @@ function(ly_test_impact_export_source_target_mappings MAPPING_TEMPLATE_FILE) get_property(LY_ALL_TARGETS GLOBAL PROPERTY LY_ALL_TARGETS) # Walk the build targets - foreach(target ${LY_ALL_TARGETS}) + foreach(aliased_target ${LY_ALL_TARGETS}) + + unset(target) + ly_de_alias_target(${aliased_target} target) message(TRACE "Exporting static source file mappings for ${target}") # Target name and path relative to root diff --git a/cmake/install/TargetCMakeLists.txt.in b/cmake/install/TargetCMakeLists.txt.in index 16263ecf30..5542184b89 100644 --- a/cmake/install/TargetCMakeLists.txt.in +++ b/cmake/install/TargetCMakeLists.txt.in @@ -22,7 +22,9 @@ ly_add_target( @INCLUDE_DIRECTORIES_PLACEHOLDER@ BUILD_DEPENDENCIES INTERFACE -@BUILD_DEPENDENCIES_PLACEHOLDER@ +@INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER@ + PRIVATE +@PRIVATE_BUILD_DEPENDENCIES_PLACEHOLDER@ RUNTIME_DEPENDENCIES @RUNTIME_DEPENDENCIES_PLACEHOLDER@ ) From 12cea5d0299a728b472effd9cd5bba49520c36e2 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 10 May 2021 13:58:22 -0700 Subject: [PATCH 034/811] Fixing headers and interface build dependencies --- cmake/Platform/Common/Install_common.cmake | 48 +++++++++++----------- cmake/install/TargetCMakeLists.txt.in | 2 - 2 files changed, 23 insertions(+), 27 deletions(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index e8ad598277..b8d8dcea18 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -34,7 +34,10 @@ function(ly_setup_target ALIAS_TARGET_NAME) get_target_property(absolute_target_source_dir ${TARGET_NAME} SOURCE_DIR) file(RELATIVE_PATH target_source_dir ${LY_ROOT_FOLDER} ${absolute_target_source_dir}) - # All include directories marked PUBLIC or INTERFACE will be installed + # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that + # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the + # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. + # Instead, we install them with install(DIRECTORY) set(include_location "include") get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) if (include_directories) @@ -43,18 +46,16 @@ function(ly_setup_target ALIAS_TARGET_NAME) string(GENEX_STRIP ${include_directory} include_genex_expr) if(include_genex_expr STREQUAL include_directory) # only for cases where there are no generation expressions unset(current_public_headers) - # We install all header types for the time being until we clean up certain libraries that contain all sorts - # of files in the public include directories (e.g. CryCommon) - file(GLOB_RECURSE current_public_headers - LIST_DIRECTORIES false - ${include_directory}/*.h - ${include_directory}/*.hpp - ${include_directory}/*.inl + install(DIRECTORY ${include_directory} + DESTINATION ${include_location}/${target_source_dir} + COMPONENT ${ly_install_target_COMPONENT} + FILES_MATCHING + PATTERN *.h + PATTERN *.hpp + PATTERN *.inl ) - list(APPEND public_headers ${current_public_headers}) endif() endforeach() - set_target_properties(${TARGET_NAME} PROPERTIES PUBLIC_HEADER "${public_headers}") endif() # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target @@ -81,11 +82,6 @@ function(ly_setup_target ALIAS_TARGET_NAME) RUNTIME DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} COMPONENT ${ly_install_target_COMPONENT} - PUBLIC_HEADER - # The include directories are specified relative to the CMakeLists.txt file that adds the target. - # We need to install the includes relative to our source tree root - DESTINATION ${include_location}/${target_source_dir} - COMPONENT ${ly_install_target_COMPONENT} ) # CMakeLists.txt file @@ -112,11 +108,13 @@ function(ly_setup_target ALIAS_TARGET_NAME) endif() # Includes need additional processing to add the install root - get_target_property(include_directories_interface_props ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) - unset(INCLUDE_DIRECTORIES_PLACEHOLDER) - if(include_directories_interface_props) - foreach(include ${include_directories_interface_props}) - string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}\n") + if(include_directories) + foreach(include ${include_directories}) + string(GENEX_STRIP ${include} include_genex_expr) + if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions + file(RELATIVE_PATH relative_include ${absolute_target_source_dir} ${include}) + string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}/${relative_include}\n") + endif() endforeach() endif() @@ -137,15 +135,13 @@ function(ly_setup_target ALIAS_TARGET_NAME) endif() endforeach() endif() - - # We also need to declare teh private link libraries since we will use that to generate the runtime dependencies + # We also need to pass the private link libraries since we will use that to generate the runtime dependencies get_target_property(private_build_dependencies_props ${TARGET_NAME} LINK_LIBRARIES) - unset(PRIVATE_BUILD_DEPENDENCIES_PLACEHOLDER) if(private_build_dependencies_props) foreach(build_dependency ${private_build_dependencies_props}) # Skip wrapping produced when targets are not created in the same directory if(NOT ${build_dependency} MATCHES "^::@") - string(APPEND PRIVATE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}\n") + string(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}\n") endif() endforeach() endif() @@ -247,7 +243,9 @@ function(ly_setup_cmake_install) # targets that are pre-built get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) unset(FIND_PACKAGES_PLACEHOLDER) - foreach(target IN LISTS all_targets) + foreach(alias_target IN LISTS all_targets) + unset(TARGET_NAME) + ly_de_alias_target(${alias_target} target) get_target_property(target_source_dir ${target} SOURCE_DIR) file(RELATIVE_PATH target_source_dir_relative ${LY_ROOT_FOLDER} ${target_source_dir}) string(APPEND FIND_PACKAGES_PLACEHOLDER " add_subdirectory(${target_source_dir_relative}/${target})\n") diff --git a/cmake/install/TargetCMakeLists.txt.in b/cmake/install/TargetCMakeLists.txt.in index 784448aeb0..ae3ca91d5b 100644 --- a/cmake/install/TargetCMakeLists.txt.in +++ b/cmake/install/TargetCMakeLists.txt.in @@ -23,8 +23,6 @@ ly_add_target( BUILD_DEPENDENCIES INTERFACE @INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER@ - PRIVATE -@PRIVATE_BUILD_DEPENDENCIES_PLACEHOLDER@ RUNTIME_DEPENDENCIES @RUNTIME_DEPENDENCIES_PLACEHOLDER@ ) From 89fc1483fe572020efbf3f3cfe99cf3d82fc05cd Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 10 May 2021 14:52:26 -0700 Subject: [PATCH 035/811] removing unused var --- Code/Sandbox/Editor/EditorViewportWidget.cpp | 4 ---- Code/Sandbox/Editor/RenderViewport.cpp | 4 ---- 2 files changed, 8 deletions(-) diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 3803867870..23f080a777 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -656,9 +656,6 @@ CBaseObject* EditorViewportWidget::GetCameraObject() const ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) { - static ICVar* outputToHMD = gEnv->pConsole->GetCVar("output_to_hmd"); - AZ_Assert(outputToHMD, "cvar output_to_hmd is undeclared"); - switch (event) { case eNotify_OnBeginGameMode: @@ -680,7 +677,6 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (deviceInfo) { // Note: This may also need to adjust the viewport size - outputToHMD->Set(1); SetActiveWindow(); SetFocus(); SetSelected(true); diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index 49064b5bc5..32b6a5c811 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -1259,9 +1259,6 @@ CBaseObject* CRenderViewport::GetCameraObject() const ////////////////////////////////////////////////////////////////////////// void CRenderViewport::OnEditorNotifyEvent(EEditorNotifyEvent event) { - static ICVar* outputToHMD = gEnv->pConsole->GetCVar("output_to_hmd"); - AZ_Assert(outputToHMD, "cvar output_to_hmd is undeclared"); - switch (event) { case eNotify_OnBeginGameMode: @@ -1282,7 +1279,6 @@ void CRenderViewport::OnEditorNotifyEvent(EEditorNotifyEvent event) if (deviceInfo) { - outputToHMD->Set(1); m_previousContext = SetCurrentContext(deviceInfo->renderWidth, deviceInfo->renderHeight); if (m_renderer->GetIStereoRenderer()) { From 65e0bd270e1081df256dae6f7029337ee1f673b0 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 10 May 2021 14:55:03 -0700 Subject: [PATCH 036/811] Fixing runtime dependencies (including qt deploy). Running AP/Editor again --- AutomatedTesting/EngineFinder.cmake | 4 +++- cmake/Platform/Common/Install_common.cmake | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/AutomatedTesting/EngineFinder.cmake b/AutomatedTesting/EngineFinder.cmake index 1fdcef2b56..9ff8ce4d66 100644 --- a/AutomatedTesting/EngineFinder.cmake +++ b/AutomatedTesting/EngineFinder.cmake @@ -45,6 +45,8 @@ if(EXISTS ${manifest_path}) if(${json_error}) message(FATAL_ERROR "Unable to read engines[${engine_path_index}] '${manifest_path}', error: ${json_error}") endif() - list(APPEND CMAKE_MODULE_PATH "${engine_path}/cmake") + if(engine_path) + list(APPEND CMAKE_MODULE_PATH "${engine_path}/cmake") + endif() endforeach() endif() diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index b8d8dcea18..338244c05f 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -244,7 +244,6 @@ function(ly_setup_cmake_install) get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) unset(FIND_PACKAGES_PLACEHOLDER) foreach(alias_target IN LISTS all_targets) - unset(TARGET_NAME) ly_de_alias_target(${alias_target} target) get_target_property(target_source_dir ${target} SOURCE_DIR) file(RELATIVE_PATH target_source_dir_relative ${LY_ROOT_FOLDER} ${target_source_dir}) @@ -301,7 +300,8 @@ endfunction()" unset(runtime_commands) get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) - foreach(target IN LISTS all_targets) + foreach(alias_target IN LISTS all_targets) + ly_de_alias_target(${alias_target} target) # Exclude targets that dont produce runtime outputs get_target_property(target_type ${target} TYPE) From c5b6878e91777b91e604b024440fcf82283033af Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 10 May 2021 14:55:24 -0700 Subject: [PATCH 037/811] removing more mentions to a gone cvar --- Code/Sandbox/Editor/EditorViewportWidget.cpp | 4 ---- Code/Sandbox/Editor/RenderViewport.cpp | 4 ---- 2 files changed, 8 deletions(-) diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 23f080a777..e3c7280a26 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -696,10 +696,6 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (GetIEditor()->GetViewManager()->GetGameViewport() == this) { SetCurrentCursor(STD_CURSOR_DEFAULT); - if (gSettings.bEnableGameModeVR) - { - outputToHMD->Set(0); - } m_bInRotateMode = false; m_bInMoveMode = false; m_bInOrbitMode = false; diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index 32b6a5c811..c10ba41203 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -1309,10 +1309,6 @@ void CRenderViewport::OnEditorNotifyEvent(EEditorNotifyEvent event) // 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."); } - if (gSettings.bEnableGameModeVR) - { - outputToHMD->Set(0); - } RestorePreviousContext(m_previousContext); m_bInRotateMode = false; m_bInMoveMode = false; From 03bde5c24467ccc14c4b7f63e16cd02423cd000c Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 10 May 2021 15:05:17 -0700 Subject: [PATCH 038/811] getting CMakeTestbed to build again --- CMakeLists.txt | 4 +--- cmake/install/engine.json.in | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c5185127d8..78667a7161 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,14 +34,12 @@ if(NOT PROJECT_NAME) LANGUAGES C CXX VERSION ${LY_VERSION_STRING} ) - - # o3de manifest - include(cmake/o3de_manifest.cmake) endif() ################################################################################ # Resolve this engines name and restricted path ################################################################################ +include(cmake/o3de_manifest.cmake) o3de_engine_name(${o3de_engine_json} o3de_engine_name) o3de_restricted_path(${o3de_engine_json} o3de_engine_restricted_path) message(STATUS "O3DE Engine Name: ${o3de_engine_name}") diff --git a/cmake/install/engine.json.in b/cmake/install/engine.json.in index 9899b169ed..04ee6348d3 100644 --- a/cmake/install/engine.json.in +++ b/cmake/install/engine.json.in @@ -1,5 +1,6 @@ { "engine_name": "@LY_VERSION_ENGINE_NAME@", + "restricted": "@LY_VERSION_ENGINE_NAME@", "FileVersion": 1, "O3DEVersion": "@LY_VERSION_STRING@", "O3DECopyrightYear": @LY_VERSION_COPYRIGHT_YEAR@, From c2a1365279930d3d7a2833b009078867e93e0de8 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 10 May 2021 15:05:38 -0700 Subject: [PATCH 039/811] removing debugging messages --- cmake/o3de_manifest.cmake | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/cmake/o3de_manifest.cmake b/cmake/o3de_manifest.cmake index 1585ec2d2f..632f064659 100644 --- a/cmake/o3de_manifest.cmake +++ b/cmake/o3de_manifest.cmake @@ -24,7 +24,6 @@ endif() # Optionally delete the home directory if(O3DE_DELETE_HOME_PATH) - message(STATUS "O3DE_DELETE_HOME_PATH=${O3DE_DELETE_HOME_PATH}") if(EXISTS ${home_directory}/.o3de) message(STATUS "Deleting ${home_directory}/.o3de") file(REMOVE_RECURSE ${home_directory}/.o3de) @@ -53,11 +52,7 @@ endif() # -DO3DE_REGISTER_RESTRICTED_PATHS=C:\this\engine\Restricted;C:\ThisGame\Restricted;C:\ThisGem\Restricted ######################################################################################################################## if(O3DE_REGISTER_ENGINE_PATH) - message(STATUS "O3DE_REGISTER_ENGINE_PATH=${O3DE_REGISTER_ENGINE_PATH}") - if(O3DE_REGISTER_THIS_ENGINE) - message(STATUS "O3DE_REGISTER_THIS_ENGINE=${O3DE_REGISTER_THIS_ENGINE}") - message(STATUS "register --this-engine") if(CMAKE_HOST_WIN32) execute_process( COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --this-engine --override-home-folder ${home_directory} @@ -77,7 +72,6 @@ if(O3DE_REGISTER_ENGINE_PATH) endif() if(O3DE_REGISTER_RESTRICTED_PATHS) - message(STATUS "O3DE_REGISTER_RESTRICTED_PATHS=${O3DE_REGISTER_RESTRICTED_PATHS}") foreach(restricted_path ${O3DE_REGISTER_RESTRICTED_PATHS}) if(CMAKE_HOST_WIN32) execute_process( @@ -99,7 +93,6 @@ if(O3DE_REGISTER_ENGINE_PATH) endif() if(O3DE_REGISTER_PROJECT_PATHS) - message(STATUS "O3DE_REGISTER_PROJECT_PATHS=${O3DE_REGISTER_PROJECT_PATHS}") foreach(project_path ${O3DE_REGISTER_PROJECT_PATHS}) if(CMAKE_HOST_WIN32) execute_process( @@ -121,7 +114,6 @@ if(O3DE_REGISTER_ENGINE_PATH) endif() if(O3DE_REGISTER_GEM_PATHS) - message(STATUS "O3DE_REGISTER_GEM_PATHS=${O3DE_REGISTER_GEM_PATHS}") foreach(gem_path ${O3DE_REGISTER_GEM_PATHS}) if(CMAKE_HOST_WIN32) execute_process( @@ -143,7 +135,6 @@ if(O3DE_REGISTER_ENGINE_PATH) endif() if(O3DE_REGISTER_TEMPLATE_PATHS) - message(STATUS "O3DE_REGISTER_TEMPLATE_PATHS=${O3DE_REGISTER_TEMPLATE_PATHS}") foreach(template_path ${O3DE_REGISTER_TEMPLATE_PATHS}) if(CMAKE_HOST_WIN32) execute_process( @@ -165,7 +156,6 @@ if(O3DE_REGISTER_ENGINE_PATH) endif() if(O3DE_REGISTER_REPO_URIS) - message(STATUS "O3DE_REGISTER_REPO_URIS=${O3DE_REGISTER_REPO_URIS}") foreach(repo_uri ${O3DE_REGISTER_REPO_URIS}) if(CMAKE_HOST_WIN32) execute_process( @@ -201,7 +191,6 @@ file(READ ${o3de_manifest_json_path} manifest_json_data) # o3de manifest name ################################################################################ string(JSON o3de_manifest_name ERROR_VARIABLE json_error GET ${manifest_json_data} o3de_manifest_name) -message(STATUS "o3de_manifest_name: ${o3de_manifest_name}") if(json_error) message(FATAL_ERROR "Unable to read repo_name from '${o3de_manifest_json_path}', error: ${json_error}") endif() @@ -218,7 +207,6 @@ endif() # o3de default engines folder ################################################################################ string(JSON o3de_default_engines_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_engines_folder) -message(STATUS "default_engines_folder: ${o3de_default_engines_folder}") if(json_error) message(FATAL_ERROR "Unable to read default_engines_folder from '${o3de_manifest_json_path}', error: ${json_error}") endif() @@ -227,7 +215,6 @@ endif() # o3de default projects folder ################################################################################ string(JSON o3de_default_projects_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_projects_folder) -message(STATUS "default_projects_folder: ${o3de_default_projects_folder}") if(json_error) message(FATAL_ERROR "Unable to read default_projects_folder from '${o3de_manifest_json_path}', error: ${json_error}") endif() @@ -236,7 +223,6 @@ endif() # o3de default gems folder ################################################################################ string(JSON o3de_default_gems_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_gems_folder) -message(STATUS "default_gems_folder: ${o3de_default_gems_folder}") if(json_error) message(FATAL_ERROR "Unable to read default_gems_folder from '${o3de_manifest_json_path}', error: ${json_error}") endif() @@ -245,7 +231,6 @@ endif() # o3de default templates folder ################################################################################ string(JSON o3de_default_templates_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_templates_folder) -message(STATUS "default_templates_folder: ${o3de_default_templates_folder}") if(json_error) message(FATAL_ERROR "Unable to read default_templates_folder from '${o3de_manifest_json_path}', error: ${json_error}") endif() @@ -254,7 +239,6 @@ endif() # o3de default restricted folder ################################################################################ string(JSON o3de_default_restricted_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_restricted_folder) -message(STATUS "default_restricted_folder: ${o3de_default_restricted_folder}") if(json_error) message(FATAL_ERROR "Unable to read default_restricted_folder from '${o3de_manifest_json_path}', error: ${json_error}") endif() From f222590d77b743eb37840cb71910e1c0eceba7d5 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 10 May 2021 16:02:07 -0700 Subject: [PATCH 040/811] fixing debug --- cmake/install/TargetCMakeLists.txt.in | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cmake/install/TargetCMakeLists.txt.in b/cmake/install/TargetCMakeLists.txt.in index ae3ca91d5b..dd6fddcc9b 100644 --- a/cmake/install/TargetCMakeLists.txt.in +++ b/cmake/install/TargetCMakeLists.txt.in @@ -27,6 +27,7 @@ ly_add_target( @RUNTIME_DEPENDENCIES_PLACEHOLDER@ ) -foreach(config @CMAKE_CONFIGURATION_TYPES@) +set(configs @CMAKE_CONFIGURATION_TYPES@) +foreach(config ${configs}) include("@NAME_PLACEHOLDER@_${config}.cmake" OPTIONAL) endforeach() From 232f81b4ea36229d8ff4d0c2d36f4c0ddd361da9 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 10 May 2021 16:02:21 -0700 Subject: [PATCH 041/811] wrong trait --- Gems/AtomLyIntegration/AtomFont/Code/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/AtomLyIntegration/AtomFont/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomFont/Code/CMakeLists.txt index 1066cc33e8..d3b8c8cde7 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomFont/Code/CMakeLists.txt @@ -12,7 +12,7 @@ ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) ly_add_target( - NAME AtomFont ${PAL_TRAIT_MONOLITHIC_DRIVEN_LIBRARY_TYPE} + NAME AtomFont ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} NAMESPACE Gem FILES_CMAKE atomfont_files.cmake From b3ae71a5d8442e44b5bd32d1b74ce9277e372a3f Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 10 May 2021 16:03:00 -0700 Subject: [PATCH 042/811] misc fixes --- cmake/Platform/Common/Install_common.cmake | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 338244c05f..0642e24690 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -131,7 +131,7 @@ function(ly_setup_target ALIAS_TARGET_NAME) foreach(build_dependency ${inteface_build_dependencies_props}) # Skip wrapping produced when targets are not created in the same directory if(NOT ${build_dependency} MATCHES "^::@") - string(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}\n") + list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") endif() endforeach() endif() @@ -141,10 +141,12 @@ function(ly_setup_target ALIAS_TARGET_NAME) foreach(build_dependency ${private_build_dependencies_props}) # Skip wrapping produced when targets are not created in the same directory if(NOT ${build_dependency} MATCHES "^::@") - string(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}\n") + list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") endif() endforeach() endif() + list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) + string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}") # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target configure_file(${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/CMakeLists.txt @ONLY) From 083849b444dfefe68fbd2defe369302a9743d482 Mon Sep 17 00:00:00 2001 From: pappeste Date: Tue, 11 May 2021 14:41:28 -0700 Subject: [PATCH 043/811] Fixing initialization of LyShin and removing a macro and ISystemEventListner that were not doing anything --- Code/CryEngine/CryCommon/CryMemoryManager.h | 4 -- Code/CryEngine/CrySystem/DllMain.cpp | 1 - Code/CryEngine/CrySystem/SystemInit.cpp | 5 --- Code/CryEngine/CrySystem/XML/XmlUtils.cpp | 1 - .../Code/Source/LyShineSystemComponent.cpp | 44 ++++++++----------- .../Code/Source/LyShineSystemComponent.h | 6 +++ .../Code/Source/MaestroSystemComponent.cpp | 1 - 7 files changed, 25 insertions(+), 37 deletions(-) diff --git a/Code/CryEngine/CryCommon/CryMemoryManager.h b/Code/CryEngine/CryCommon/CryMemoryManager.h index b3f8ba7c8e..e900b16761 100644 --- a/Code/CryEngine/CryCommon/CryMemoryManager.h +++ b/Code/CryEngine/CryCommon/CryMemoryManager.h @@ -50,10 +50,6 @@ #include // memalign #endif // defined(APPLE) -#ifndef STLALLOCATOR_CLEANUP -#define STLALLOCATOR_CLEANUP -#endif - #define _CRY_DEFAULT_MALLOC_ALIGNMENT 4 #if CRYMEMORYMANAGER_H_TRAIT_INCLUDE_MALLOC_H diff --git a/Code/CryEngine/CrySystem/DllMain.cpp b/Code/CryEngine/CrySystem/DllMain.cpp index aba39fb9fb..7e9047854d 100644 --- a/Code/CryEngine/CrySystem/DllMain.cpp +++ b/Code/CryEngine/CrySystem/DllMain.cpp @@ -90,7 +90,6 @@ public: case ESYSTEM_EVENT_LEVEL_POST_UNLOAD: { CryCleanup(); - STLALLOCATOR_CLEANUP; gEnv->pSystem->SetThreadState(ESubsys_Physics, true); break; } diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 83ef4fcd2b..93fa75ec3b 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -1393,11 +1393,6 @@ bool CSystem::InitShine([[maybe_unused]] const SSystemInitParams& initParams) EBUS_EVENT(UiSystemBus, InitializeSystem); - if (!m_env.pLyShine) - { - AZ_Error(AZ_TRACE_SYSTEM_WINDOW, false, "LYShine System did not initialize correctly. Please check that the LyShine gem is enabled for this project in ProjectConfigurator."); - return false; - } return true; } diff --git a/Code/CryEngine/CrySystem/XML/XmlUtils.cpp b/Code/CryEngine/CrySystem/XML/XmlUtils.cpp index de5a14ecd7..d4feec04f2 100644 --- a/Code/CryEngine/CrySystem/XML/XmlUtils.cpp +++ b/Code/CryEngine/CrySystem/XML/XmlUtils.cpp @@ -272,7 +272,6 @@ void CXmlUtils::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_PTR wpar case ESYSTEM_EVENT_LEVEL_POST_UNLOAD: case ESYSTEM_EVENT_LEVEL_LOAD_END: g_pCXmlNode_PoolAlloc->FreeMemoryIfEmpty(); - STLALLOCATOR_CLEANUP; break; } } diff --git a/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp b/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp index 8e8079e18e..902752a03c 100644 --- a/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp +++ b/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp @@ -56,26 +56,6 @@ #include "UiDynamicScrollBoxComponent.h" #include "UiNavigationSettings.h" -//////////////////////////////////////////////////////////////////////////////////////////////////// -struct CSystemEventListener_UI - : public ISystemEventListener -{ -public: - virtual void OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) - { - switch (event) - { - case ESYSTEM_EVENT_LEVEL_POST_UNLOAD: - { - STLALLOCATOR_CLEANUP; - break; - } - } - } -}; -static CSystemEventListener_UI g_system_event_listener_ui; - - namespace LyShine { const AZStd::list* LyShineSystemComponent::m_componentDescriptors = nullptr; @@ -228,11 +208,6 @@ namespace LyShine //////////////////////////////////////////////////////////////////////////////////////////////////// void LyShineSystemComponent::InitializeSystem() { - // Not sure if this is still required - gEnv->pSystem->GetISystemEventDispatcher()->RegisterListener(&g_system_event_listener_ui); - - m_pLyShine = new CLyShine(gEnv->pSystem); - gEnv->pLyShine = m_pLyShine; BroadcastCursorImagePathname(); } @@ -397,6 +372,25 @@ namespace LyShine } } + /////////////////////////////////////////////////////////////////////////////////////////////// + void LyShineSystemComponent::OnCrySystemInitialized(ISystem& system, [[maybe_unused]] const SSystemInitParams& startupParams) + { +#if !defined(AZ_MONOLITHIC_BUILD) + // When module is linked dynamically, we must set our gEnv pointer. + // When module is linked statically, we'll share the application's gEnv pointer. + gEnv = system.GetGlobalEnvironment(); +#endif + m_pLyShine = new CLyShine(gEnv->pSystem); + gEnv->pLyShine = m_pLyShine; + } + + void LyShineSystemComponent::OnCrySystemShutdown([[maybe_unused]] ISystem& system) + { + gEnv->pLyShine = nullptr; + delete m_pLyShine; + m_pLyShine = nullptr; + } + //////////////////////////////////////////////////////////////////////////////////////////////////// void LyShineSystemComponent::BroadcastCursorImagePathname() { diff --git a/Gems/LyShine/Code/Source/LyShineSystemComponent.h b/Gems/LyShine/Code/Source/LyShineSystemComponent.h index 5f45f22823..f65dc75463 100644 --- a/Gems/LyShine/Code/Source/LyShineSystemComponent.h +++ b/Gems/LyShine/Code/Source/LyShineSystemComponent.h @@ -38,6 +38,7 @@ namespace LyShine , protected UiSystemToolsBus::Handler , protected LyShineAllocatorScope , protected UiFrameworkBus::Handler + , protected CrySystemEventBus::Handler { public: AZ_COMPONENT(LyShineSystemComponent, lyShineSystemComponentUuid); @@ -89,6 +90,11 @@ namespace LyShine void HandleEditorOnlyEntities(const EntityList& exportSliceEntities, const EntityIdSet& editorOnlyEntityIds) override; //////////////////////////////////////////////////////////////////////// + // CrySystemEventBus /////////////////////////////////////////////////////// + void OnCrySystemInitialized(ISystem& system, const SSystemInitParams&) override; + virtual void OnCrySystemShutdown(ISystem&) override; + //////////////////////////////////////////////////////////////////////////// + void BroadcastCursorImagePathname(); protected: // data diff --git a/Gems/Maestro/Code/Source/MaestroSystemComponent.cpp b/Gems/Maestro/Code/Source/MaestroSystemComponent.cpp index cd0dfb02b3..dff51d3cc7 100644 --- a/Gems/Maestro/Code/Source/MaestroSystemComponent.cpp +++ b/Gems/Maestro/Code/Source/MaestroSystemComponent.cpp @@ -112,7 +112,6 @@ namespace Maestro { case ESYSTEM_EVENT_LEVEL_POST_UNLOAD: { - STLALLOCATOR_CLEANUP; CLightAnimWrapper::ReconstructCache(); break; } From 671f26bed4f722c8e81dbfb6930455946ab4f50b Mon Sep 17 00:00:00 2001 From: pappeste Date: Tue, 11 May 2021 19:06:07 -0700 Subject: [PATCH 044/811] fixing debug configuration and how we declare IMPORTED targets (instead of UNKNOW we use the actual type) --- cmake/LYWrappers.cmake | 26 +++++------ cmake/Platform/Common/Install_common.cmake | 46 +++++++++++-------- .../Common/RuntimeDependencies_common.cmake | 8 +++- cmake/install/TargetCMakeLists.txt.in | 2 +- 4 files changed, 46 insertions(+), 36 deletions(-) diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index fcf205238c..bddd1a6c66 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -87,8 +87,8 @@ function(ly_add_target) endif() if(NOT ly_add_target_IMPORTED AND NOT ly_add_target_HEADERONLY) if(NOT ly_add_target_FILES_CMAKE) - message(FATAL_ERROR "You must provide a list of _files.cmake files for the target") - endif() + message(FATAL_ERROR "You must provide a list of _files.cmake files for the target") + endif() endif() # If the GEM_MODULE tag is passed set the normal MODULE argument @@ -114,11 +114,10 @@ function(ly_add_target) set(linking_options ${PAL_LINKOPTION_MODULE}) set(linking_count "${linking_count}1") endif() - if(ly_add_target_HEADERONLY) set(linking_options INTERFACE) set(linking_count "${linking_count}1") - endif() + endif() if(ly_add_target_EXECUTABLE) set(linking_options EXECUTABLE) set(linking_count "${linking_count}1") @@ -127,12 +126,11 @@ function(ly_add_target) set(linking_options APPLICATION) set(linking_count "${linking_count}1") endif() - if(ly_add_target_IMPORTED) - set(linking_options UNKNOWN IMPORTED GLOBAL) - set(linking_count "${linking_count}1") - endif() if(NOT ("${linking_count}" STREQUAL "1")) - message(FATAL_ERROR "More than one of the following options [STATIC | SHARED | MODULE | HEADERONLY | EXECUTABLE | APPLICATION | IMPORTED] was specified and they are mutually exclusive") + message(FATAL_ERROR "More than one of the following options [STATIC | SHARED | MODULE | HEADERONLY | EXECUTABLE | APPLICATION ] was specified and they are mutually exclusive") + endif() + if(ly_add_target_IMPORTED) + list(APPEND linking_options IMPORTED GLOBAL) endif() if(ly_add_target_NAMESPACE) @@ -147,21 +145,23 @@ function(ly_add_target) ${ALLFILES} ${ly_add_target_GENERATED_FILES} ) ly_apply_platform_properties(${ly_add_target_NAME}) + if(ly_add_target_IMPORTED) + set_target_properties(${ly_add_target_NAME} PROPERTIES LINKER_LANGUAGE CXX) + endif() elseif(ly_add_target_APPLICATION) add_executable(${ly_add_target_NAME} ${PAL_EXECUTABLE_APPLICATION_FLAG} ${ALLFILES} ${ly_add_target_GENERATED_FILES} ) ly_apply_platform_properties(${ly_add_target_NAME}) + if(ly_add_target_IMPORTED) + set_target_properties(${ly_add_target_NAME} PROPERTIES LINKER_LANGUAGE CXX) + endif() elseif(ly_add_target_HEADERONLY) add_library(${ly_add_target_NAME} ${linking_options} ${ALLFILES} ${ly_add_target_GENERATED_FILES} ) - elseif(ly_add_target_IMPORTED) - add_library(${ly_add_target_NAME} - ${linking_options} - ) else() add_library(${ly_add_target_NAME} ${linking_options} diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 0642e24690..64fc973701 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -94,10 +94,17 @@ function(ly_setup_target ALIAS_TARGET_NAME) set(NAME_PLACEHOLDER ${TARGET_NAME}) endif() - set(TARGET_TYPE_PLACEHOLDER "IMPORTED") + set(TARGET_TYPE_PLACEHOLDER "") get_target_property(target_type ${NAME_PLACEHOLDER} TYPE) - if(target_type STREQUAL INTERFACE_LIBRARY) - set(TARGET_TYPE_PLACEHOLDER "HEADERONLY") + # Remove the _LIBRARY since we dont need to pass that to ly_add_targets + string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type}) + # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead + string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER}) + if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE") + get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE) + if(gem_module) + set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE") + endif() endif() get_target_property(COMPILE_DEFINITIONS_PLACEHOLDER ${TARGET_NAME} INTERFACE_COMPILE_DEFINITIONS) @@ -155,7 +162,7 @@ function(ly_setup_target ALIAS_TARGET_NAME) DESTINATION ${target_source_dir}/${NAME_PLACEHOLDER} COMPONENT ${ly_install_target_COMPONENT} ) - + # Config file set(target_file_contents "# Generated by O3DE install\n\n") if(NOT target_type STREQUAL INTERFACE_LIBRARY) @@ -163,29 +170,28 @@ function(ly_setup_target ALIAS_TARGET_NAME) unset(target_location) set(runtime_types EXECUTABLE APPLICATION) if(target_type IN_LIST runtime_types) - string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$\"") + set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$") elseif(target_type STREQUAL MODULE_LIBRARY) - string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\"") + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") elseif(target_type STREQUAL SHARED_LIBRARY) - string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"") - string(APPEND target_file_contents "target_link_libraries(${TARGET_NAME} INTERFACE \"\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$\")\n") + string(APPEND target_file_contents "set_property(TARGET ${TARGET_NAME} PROPERTY IMPORTED_IMPLIB_$ \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\")\n") + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY - string(APPEND target_location "\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"") + set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") endif() - string(APPEND target_file_contents -"set(target_location ${target_location}) -set_target_properties(${TARGET_NAME} - PROPERTIES - $<$:IMPORTED_LOCATION \"\${target_location}\"> - IMPORTED_LOCATION_$> \"\${target_location}\" + if(target_location) + string(APPEND target_file_contents +"set_property(TARGET ${TARGET_NAME} + APPEND_STRING PROPERTY IMPORTED_LOCATION + $<$$:${target_location}$ +) +set_property(TARGET ${TARGET_NAME} + PROPERTY IMPORTED_LOCATION_$> + ${target_location} ) -if(EXISTS \"\${target_location}\") - set(${NAME_PLACEHOLDER}_$_FOUND TRUE) -else() - set(${NAME_PLACEHOLDER}_$_FOUND FALSE) -endif() ") + endif() endif() file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") diff --git a/cmake/Platform/Common/RuntimeDependencies_common.cmake b/cmake/Platform/Common/RuntimeDependencies_common.cmake index 333bbaaae2..d9d0fe4c7f 100644 --- a/cmake/Platform/Common/RuntimeDependencies_common.cmake +++ b/cmake/Platform/Common/RuntimeDependencies_common.cmake @@ -61,7 +61,7 @@ function(ly_get_runtime_dependencies ly_RUNTIME_DEPENDENCIES ly_TARGET) if(dependencies) list(APPEND link_dependencies ${dependencies}) endif() - if(NOT target_type MATCHES "INTERFACE") + if(NOT target_type STREQUAL "INTERFACE_LIBRARY") unset(dependencies) get_target_property(dependencies ${ly_TARGET} LINK_LIBRARIES) if(dependencies) @@ -105,11 +105,15 @@ function(ly_get_runtime_dependencies ly_RUNTIME_DEPENDENCIES ly_TARGET) set(skip_imported TRUE) endif() endif() + if(target_type MATCHES "(INTERFACE_LIBRARY|STATIC_LIBRARY)") + # No need to copy these dependencies since the outputs are not used at runtime + set(skip_imported TRUE) + endif() if(NOT skip_imported) # Add imported locations - if(target_type MATCHES "INTERFACE") + if(target_type STREQUAL "INTERFACE_LIBRARY") set(imported_property INTERFACE_IMPORTED_LOCATION) else() set(imported_property IMPORTED_LOCATION) diff --git a/cmake/install/TargetCMakeLists.txt.in b/cmake/install/TargetCMakeLists.txt.in index dd6fddcc9b..b2c8b9b6f6 100644 --- a/cmake/install/TargetCMakeLists.txt.in +++ b/cmake/install/TargetCMakeLists.txt.in @@ -12,7 +12,7 @@ # Generated by O3DE ly_add_target( - NAME @NAME_PLACEHOLDER@ @TARGET_TYPE_PLACEHOLDER@ + NAME @NAME_PLACEHOLDER@ IMPORTED @TARGET_TYPE_PLACEHOLDER@ @NAMESPACE_PLACEHOLDER@ COMPILE_DEFINITIONS INTERFACE From 1c990b2ef6b206c254e810d0301365c0a411ab88 Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 12 May 2021 11:03:02 +0100 Subject: [PATCH 045/811] Filter Sorting Working --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 3 +- .../AssetBrowser/AssetBrowserFilterModel.h | 1 - .../AssetBrowser/AssetBrowserTableModel.cpp | 234 ++---------------- .../AssetBrowser/AssetBrowserTableModel.h | 60 +---- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 20 +- 5 files changed, 33 insertions(+), 285 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 5e9203cc29..34f8b97b5a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -32,7 +32,7 @@ namespace AzToolsFramework : QSortFilterProxyModel(parent) { m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); - m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); + //m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); m_collator.setNumericMode(true); AssetBrowserComponentNotificationBus::Handler::BusConnect(); } @@ -63,7 +63,6 @@ namespace AzToolsFramework invalidateFilter(); m_invalidateFilter = false; } - Q_EMIT entriesUpdated(); } bool AssetBrowserFilterModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h index 3fff43859f..6cccc53eb6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h @@ -53,7 +53,6 @@ namespace AzToolsFramework Q_SIGNALS: void filterChanged(); - void entriesUpdated(); ////////////////////////////////////////////////////////////////////////// //QSortFilterProxyModel diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index b75d3e9400..ce9e97520a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -7,9 +7,7 @@ AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") #include #include -#include #include -#include AZ_POP_DISABLE_WARNING namespace AzToolsFramework { @@ -18,18 +16,7 @@ namespace AzToolsFramework AssetBrowserTableModel::AssetBrowserTableModel(QObject* parent /* = nullptr */) : QSortFilterProxyModel(parent) { - sort(0); setDynamicSortFilter(false); - setRecursiveFilteringEnabled(true); - AssetBrowserComponentNotificationBus::Handler::BusConnect(); - } - AssetBrowserTableModel::~AssetBrowserTableModel() - { - AssetBrowserComponentNotificationBus::Handler::BusDisconnect(); - } - void AssetBrowserTableModel::OnAssetBrowserComponentReady() - { - //BuildMap(sourceModel()); } void AssetBrowserTableModel::setSourceModel(QAbstractItemModel* sourceModel) { @@ -69,86 +56,68 @@ namespace AzToolsFramework // no filter present, every entry is not visible if (!m_filterModel->GetFilter()) { - return false; + return true; } return true; } QModelIndex AssetBrowserTableModel::index(int row, int column, const QModelIndex& parent) const { - /*AZ_UNUSED(row); - AZ_UNUSED(column);*/ return parent.isValid() ? QModelIndex() : createIndex(row, column, m_indexMap[row].internalPointer()); } QVariant AssetBrowserTableModel::data(const QModelIndex& index, int role) const { - //AZ_UNUSED(role); auto sourceIndex = mapToSource(index); if (!sourceIndex.isValid()) return QVariant(); - AssetBrowserEntry* entry = GetAssetEntry(sourceIndex); // static_cast(sourceIndex.internalPointer()); + AssetBrowserEntry* entry = GetAssetEntry(sourceIndex); if (entry == nullptr) { - AZ_Assert( - false, "ERROR - index internal pointer not pointing to an AssetEntry. Tree provided by the AssetBrowser invalid?"); + AZ_Assert(false, "ERROR - index internal pointer not pointing to an AssetEntry. Tree provided by the AssetBrowser invalid?"); return Qt::PartiallyChecked; } - return sourceIndex.data(role); // return entry->data(index.column()); - //return QVariant::fromValue(entry); - //AZ_UNUSED(role); - //if (index.isValid()) - //{ - // ////if (role == AssetBrowserModel::EntryRole) - // //{ - // QModelIndex modelIndex = mapFromSource(index); - // auto assetEntry = static_cast(index.internalPointer()); - // return QVariant::fromValue(assetEntry); - //} - //return QVariant(); // AzToolsFramework::AssetBrowser::AssetBrowserModel::data(index, role); - + return sourceIndex.data(role); } - int AssetBrowserTableModel::rowCount(const QModelIndex& parent) const { return !parent.isValid() ? m_rowMap.size() : 0; } + QVariant AssetBrowserTableModel::headerData(int section, Qt::Orientation orientation, int role) const + { + if (role == Qt::DisplayRole && orientation == Qt::Horizontal) + { + switch (section) + { + case static_cast(AssetBrowserEntry::Column::Name): + return QString("Name"); + case static_cast(AssetBrowserEntry::Column::Path): + return QString("Path"); + default: + return QString::number(section); + } + } + return QSortFilterProxyModel::headerData(section, orientation, role); // QVariant(); + } + int AssetBrowserTableModel::BuildMap(const QAbstractItemModel* model, const QModelIndex& parent, int row) { - //int rows = model ? model->rowCount(parent) : 0; - //for (int i = 0; i < rows; ++i) - //{ - // auto index = model->index(i, 0, parent); - // //if (!model->hasChildren(index)) - // //{ - // beginInsertRows(parent, row, row); - // m_rowMap[index] = row; - // m_indexMap[row] = index; - // endInsertRows(); - // Q_EMIT dataChanged(parent, parent); - // row = row + 1; - // //} - // if (model->hasChildren(index)) - // { - // row = BuildMap(model, index, row); - // } - //} - //return row; int rows = model ? model->rowCount(parent) : 0; for (int i = 0; i < rows; ++i) { - auto index = model->index(i, 0, parent); + QModelIndex index = model->index(i, 0, parent); if (model->hasChildren(index) == false) { beginInsertRows(parent, row, row); m_rowMap[index] = row; m_indexMap[row] = index; endInsertRows(); - Q_EMIT dataChanged(parent, parent); + + Q_EMIT dataChanged(index, index); row = row + 1; } @@ -173,12 +142,12 @@ namespace AzToolsFramework } void AssetBrowserTableModel::UpdateMap() { + //Not properly clears the indexes. //m_indexMap.clear(); //m_rowMap.clear(); - + emit layoutAboutToBeChanged(); if (m_indexMap.size() > 0) { - //beginRemoveRows(m_indexMap.first().parent(), m_indexMap.first().row(), m_indexMap.last().row()); for (const auto& key : m_indexMap.keys()) { beginRemoveRows(m_indexMap[key], m_indexMap[key].row(), m_indexMap[key].row()); @@ -186,160 +155,11 @@ namespace AzToolsFramework m_indexMap.remove(key); endRemoveRows(); } - //endRemoveRows(); } BuildMap(sourceModel()); + sort(0); } - - //---------------------------------------AssetBrowserTableFilterModel-------------------------------------------- - //AssetBrowserTableFilterModel::AssetBrowserTableFilterModel(QObject* parent) - // : QSortFilterProxyModel(parent) - //{ - // m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); - // m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); - // AssetBrowserComponentNotificationBus::Handler::BusConnect(); - //} - - //AssetBrowserTableFilterModel::~AssetBrowserTableFilterModel() - //{ - // AssetBrowserComponentNotificationBus::Handler::BusDisconnect(); - //} - - //void AssetBrowserTableFilterModel::setSourceModel(QAbstractItemModel* sourceModel) - //{ - // QSortFilterProxyModel::setSourceModel(sourceModel); - //} - - //void AssetBrowserTableFilterModel::SetFilter(FilterConstType filter) - //{ - // connect(filter.data(), &AssetBrowserEntryFilter::updatedSignal, this, &AssetBrowserTableFilterModel::filterUpdatedSlot); - // m_filter = filter; - // m_invalidateFilter = true; - // // asset browser entries are not guaranteed to have populated when the filter is set, delay filtering until they are - // bool isAssetBrowserComponentReady = false; - // AssetBrowserComponentRequestBus::BroadcastResult(isAssetBrowserComponentReady, &AssetBrowserComponentRequests::AreEntriesReady); - // if (isAssetBrowserComponentReady) - // { - // OnAssetBrowserComponentReady(); - // } - //} - - //void AssetBrowserTableFilterModel::FilterUpdatedSlotImmediate() - //{ - // auto compFilter = qobject_cast>(m_filter); - // if (compFilter) - // { - // auto& subFilters = compFilter->GetSubFilters(); - // auto it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { - // auto assetTypeFilter = qobject_cast>(filter); - // return !assetTypeFilter.isNull(); - // }); - // if (it != subFilters.end()) - // { - // m_assetTypeFilter = qobject_cast>(*it); - // } - // it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { - // auto stringFilter = qobject_cast>(filter); - // return !stringFilter.isNull(); - // }); - // if (it != subFilters.end()) - // { - // m_stringFilter = qobject_cast>(*it); - // } - // } - // invalidateFilter(); - // Q_EMIT filterChanged(); - //} - - //void AssetBrowserTableFilterModel::OnAssetBrowserComponentReady() - //{ - // if (m_invalidateFilter) - // { - // invalidateFilter(); - // m_invalidateFilter = false; - // } - // Q_EMIT entriesUpdated(); - //} - - //bool AssetBrowserTableFilterModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const - //{ - // AZ_UNUSED(source_row); - // AZ_UNUSED(source_parent); - // QModelIndex idx = sourceModel()->index(source_row, 0, source_parent); - // if (!idx.isValid()) - // { - // return false; - // } - // // no filter present, every entry is visible - // if (!m_filter) - // { - // return true; - // } - - // //// the entry is the internal pointer of the index - // //auto entry = static_cast(idx.internalPointer()); - - // //if (entry) - // //{ - // // // root should return true even if its not displayed in the treeview - // // if (entry && entry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Root) - // // { - // // return true; - // // } - // // return m_filter->Match(entry); - // //} - // return true; - //} - - //bool AssetBrowserTableFilterModel::filterAcceptsColumn(int source_column, const QModelIndex&) const - //{ - // return m_showColumn.find(source_column) != m_showColumn.end(); - //} - - //bool AssetBrowserTableFilterModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const - //{ - // if (source_left.column() == source_right.column()) - // { - // QVariant leftData = sourceModel()->data(source_left, AssetBrowserModel::Roles::EntryRole); - // QVariant rightData = sourceModel()->data(source_right, AssetBrowserModel::Roles::EntryRole); - // if (leftData.canConvert() && rightData.canConvert()) - // { - // auto leftEntry = qvariant_cast(leftData); - // auto rightEntry = qvariant_cast(rightData); - - // // folders should always come first - // if (azrtti_istypeof(leftEntry) && - // azrtti_istypeof(rightEntry)) - // { - // return false; - // } - // if (azrtti_istypeof(leftEntry) && - // azrtti_istypeof(rightEntry)) - // { - // return true; - // } - - // // if both entries are of same type, sort alphabetically - // return m_collator.compare(leftEntry->GetDisplayName(), rightEntry->GetDisplayName()) > 0; - // } - // } - // return QSortFilterProxyModel::lessThan(source_left, source_right); - //} - - //void AssetBrowserTableFilterModel::filterUpdatedSlot() - //{ - // if (!m_alreadyRecomputingFilters) - // { - // m_alreadyRecomputingFilters = true; - // // de-bounce it, since we may get many filter updates all at once. - // QTimer::singleShot(0, this, [this]() { - // m_alreadyRecomputingFilters = false; - // FilterUpdatedSlotImmediate(); - // }); - // } - //} - } // namespace AssetBrowser } // namespace AzToolsFramework #include "AssetBrowser/moc_AssetBrowserTableModel.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index 34cf8432ff..69b8ead7c5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -1,9 +1,6 @@ #pragma once #if !defined(Q_MOC_RUN) -#include #include -#include - #include #include #include @@ -26,21 +23,15 @@ namespace AzToolsFramework class AssetBrowserTableModel : public QSortFilterProxyModel - , public AssetBrowserComponentNotificationBus::Handler { Q_OBJECT public: AZ_CLASS_ALLOCATOR(AssetBrowserTableModel, AZ::SystemAllocator, 0); explicit AssetBrowserTableModel(QObject* parent = nullptr); - ~AssetBrowserTableModel(); - //////////////////////////////////////////////////////////////////// - // AssetBrowserComponentNotificationBus - //////////////////////////////////////////////////////////////////// - void OnAssetBrowserComponentReady() override; - void setSourceModel(QAbstractItemModel* sourceModel) override; //////////////////////////////////////////////////////////////////// // QSortFilterProxyModel + void setSourceModel(QAbstractItemModel* sourceModel) override; QModelIndex mapToSource(const QModelIndex& proxyIndex) const override; QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override; bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; @@ -52,7 +43,7 @@ namespace AzToolsFramework void UpdateMap(); protected: int rowCount(const QModelIndex& parent = QModelIndex()) const override; - //QVariant headerData(int section, Qt::Orientation orientation, int role /* = Qt::DisplayRole */) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role /* = Qt::DisplayRole */) const override; //////////////////////////////////////////////////////////////////// private: @@ -63,52 +54,5 @@ namespace AzToolsFramework QMap m_indexMap; QMap m_rowMap; }; - - //class AssetBrowserTableFilterModel - // : public QSortFilterProxyModel - // , public AssetBrowserComponentNotificationBus::Handler - //{ - // Q_OBJECT - //public: - // explicit AssetBrowserTableFilterModel(QObject* parent = nullptr); - // ~AssetBrowserTableFilterModel(); - - // void setSourceModel(QAbstractItemModel* sourceModel) override; - // // asset type filtering - // void SetFilter(FilterConstType filter); - // void FilterUpdatedSlotImmediate(); - - // ////////////////////////////////////////////////////////////////////////// - // // AssetBrowserComponentNotificationBus - // ////////////////////////////////////////////////////////////////////////// - // void OnAssetBrowserComponentReady() override; - - //Q_SIGNALS: - // void filterChanged(); - // void entriesUpdated(); - - // ////////////////////////////////////////////////////////////////////////// - // // QSortFilterProxyModel - //protected: - // bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; - // bool filterAcceptsColumn(int source_column, const QModelIndex& /*source_parent*/) const override; - // bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; - // ////////////////////////////////////////////////////////////////////////// - - //public Q_SLOTS: - // void filterUpdatedSlot(); - - //private: - // AZStd::fixed_unordered_set(AssetBrowserEntry::Column::Count)> m_showColumn; - // bool m_alreadyRecomputingFilters = false; - // // asset source name match filter - // FilterConstType m_filter; - // AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // 4251: class '...' needs to have dll-interface to be used by clients of class '...' - // QWeakPointer m_stringFilter; - // QWeakPointer m_assetTypeFilter; - // QCollator m_collator; // cache the collator as its somewhat expensive to constantly create and destroy one. - // AZ_POP_DISABLE_WARNING - // bool m_invalidateFilter = false; - //}; } // namespace AssetBrowser } // namespace AzToolsFramework diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index dd4b3b0cad..554c62a251 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -68,7 +68,6 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) , m_ui(new Ui::AzAssetBrowserWindowClass()) , m_filterModel(new AzToolsFramework::AssetBrowser::AssetBrowserFilterModel(parent)) , m_tableModel(new AzToolsFramework::AssetBrowser::AssetBrowserTableModel(parent)) - /*, m_tableFilterModel(new AzToolsFramework::AssetBrowser::AssetBrowserTableFilterModel(parent))*/ { m_ui->setupUi(this); m_ui->m_searchWidget->Setup(true, true); @@ -81,21 +80,13 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_tableModel->setFilterRole(Qt::DisplayRole); m_tableModel->setSourceModel(m_filterModel.data()); - //m_tableModel->setSourceModel(m_assetBrowserModel); - - //m_tableFilterModel->setSourceModel(m_tableModel.data()); - //m_tableFilterModel->SetFilter(m_ui->m_searchWidget->GetFilter()); - m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); m_ui->m_assetBrowserTreeViewWidget->hideColumn(static_cast(AssetBrowserEntry::Column::Path)); - //m_ui->m_assetBrowserTableViewWidget->setModel(m_tableFilterModel.data()); m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); m_ui->m_assetBrowserTableViewWidget->setVisible(false); - //connect(m_filterModel.data(), &AssetBrowserFilterModel::entriesUpdated, m_tableModel.data(), &AssetBrowserTableModel::UpdateMap); - connect(m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), &AssetBrowserFilterModel::filterUpdatedSlot); connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, this, [this]() @@ -105,20 +96,15 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->m_assetBrowserTreeViewWidget->UpdateAfterFilter(hasFilter, selectFirstFilteredIndex); }); - //connect( m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_tableFilterModel.data(), - // &AssetBrowserTableFilterModel::filterUpdatedSlot); - //connect(m_tableFilterModel.data(), &AssetBrowserTableFilterModel::filterChanged, this, [this]() { - // const bool hasFilter = !m_ui->m_searchWidget->GetFilterString().isEmpty(); - // const bool selectFirstFilteredIndex = false; - // m_ui->m_assetBrowserTableViewWidget->UpdateAfterFilter(hasFilter, selectFirstFilteredIndex); - //}); - connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, m_tableModel.data(), &AssetBrowserTableModel::UpdateMap); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); connect(m_ui->m_assetBrowserTreeViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); + connect(m_ui->m_assetBrowserTableViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); + + connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, &SearchWidget::ClearStringFilter); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, &SearchWidget::ClearTypeFilter); From 80684b383b66b762dbc3e4537afb536c033a2caa Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 12 May 2021 11:42:39 +0100 Subject: [PATCH 046/811] Code cleanup --- .../AssetBrowser/AssetBrowserTableModel.cpp | 121 ++++++++---------- .../AssetBrowser/AssetBrowserTableModel.h | 22 +--- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 2 +- 3 files changed, 61 insertions(+), 84 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index ce9e97520a..724e7a54d9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -1,14 +1,8 @@ -#include -#include -#include -#include -AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") #include #include +#include -#include -AZ_POP_DISABLE_WARNING namespace AzToolsFramework { namespace AssetBrowser @@ -34,11 +28,6 @@ namespace AzToolsFramework } return m_indexMap[proxyIndex.row()]; } - QModelIndex AssetBrowserTableModel::parent(const QModelIndex& child) const - { - AZ_UNUSED(child); - return QModelIndex(); - } QModelIndex AssetBrowserTableModel::mapFromSource(const QModelIndex& sourceIndex) const { Q_ASSERT(!sourceIndex.isValid() || sourceIndex.model() == sourceModel()); @@ -49,44 +38,6 @@ namespace AzToolsFramework return createIndex(m_rowMap[sourceIndex], sourceIndex.column(), sourceIndex.internalPointer()); } - bool AssetBrowserTableModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const - { - AZ_UNUSED(source_row); - AZ_UNUSED(source_parent); - // no filter present, every entry is not visible - if (!m_filterModel->GetFilter()) - { - return true; - } - return true; - } - - QModelIndex AssetBrowserTableModel::index(int row, int column, const QModelIndex& parent) const - { - return parent.isValid() ? QModelIndex() : createIndex(row, column, m_indexMap[row].internalPointer()); - } - - QVariant AssetBrowserTableModel::data(const QModelIndex& index, int role) const - { - auto sourceIndex = mapToSource(index); - if (!sourceIndex.isValid()) - return QVariant(); - - AssetBrowserEntry* entry = GetAssetEntry(sourceIndex); - if (entry == nullptr) - { - AZ_Assert(false, "ERROR - index internal pointer not pointing to an AssetEntry. Tree provided by the AssetBrowser invalid?"); - return Qt::PartiallyChecked; - } - - return sourceIndex.data(role); - } - - int AssetBrowserTableModel::rowCount(const QModelIndex& parent) const - { - return !parent.isValid() ? m_rowMap.size() : 0; - } - QVariant AssetBrowserTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) @@ -104,7 +55,50 @@ namespace AzToolsFramework return QSortFilterProxyModel::headerData(section, orientation, role); // QVariant(); } - int AssetBrowserTableModel::BuildMap(const QAbstractItemModel* model, const QModelIndex& parent, int row) + QVariant AssetBrowserTableModel::data(const QModelIndex& index, int role) const + { + auto sourceIndex = mapToSource(index); + if (!sourceIndex.isValid()) + return QVariant(); + + AssetBrowserEntry* entry = GetAssetEntry(sourceIndex); + if (entry == nullptr) + { + AZ_Assert(false, "ERROR - index internal pointer not pointing to an AssetEntry. Tree provided by the AssetBrowser invalid?"); + return Qt::PartiallyChecked; + } + + return sourceIndex.data(role); + } + + QModelIndex AssetBrowserTableModel::index(int row, int column, const QModelIndex& parent) const + { + return parent.isValid() ? QModelIndex() : createIndex(row, column, m_indexMap[row].internalPointer()); + } + + QModelIndex AssetBrowserTableModel::parent(const QModelIndex& child) const + { + AZ_UNUSED(child); + return QModelIndex(); + } + bool AssetBrowserTableModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const + { + AZ_UNUSED(source_row); + AZ_UNUSED(source_parent); + // no filter present, every entry is not visible + if (!m_filterModel->GetFilter()) + { + return true; + } + return true; + } + + int AssetBrowserTableModel::rowCount(const QModelIndex& parent) const + { + return !parent.isValid() ? m_rowMap.size() : 0; + } + + int AssetBrowserTableModel::BuildTableModelMap(const QAbstractItemModel* model, const QModelIndex& parent /*= QModelIndex()*/, int row /*= 0*/) { int rows = model ? model->rowCount(parent) : 0; for (int i = 0; i < rows; ++i) @@ -123,7 +117,7 @@ namespace AzToolsFramework if (model->hasChildren(index)) { - row = BuildMap(model, index, row); + row = BuildTableModelMap(model, index, row); } } return row; @@ -140,25 +134,18 @@ namespace AzToolsFramework return nullptr; } } - void AssetBrowserTableModel::UpdateMap() - { - //Not properly clears the indexes. - //m_indexMap.clear(); - //m_rowMap.clear(); + void AssetBrowserTableModel::UpdateTableModelMaps() +{ emit layoutAboutToBeChanged(); if (m_indexMap.size() > 0) { - for (const auto& key : m_indexMap.keys()) - { - beginRemoveRows(m_indexMap[key], m_indexMap[key].row(), m_indexMap[key].row()); - m_rowMap.remove(m_indexMap[key]); - m_indexMap.remove(key); - endRemoveRows(); - } + beginRemoveRows(m_indexMap.first(), m_indexMap.first().row(), m_indexMap.last().row()); + m_rowMap.clear(); + m_indexMap.clear(); + endRemoveRows(); } - - BuildMap(sourceModel()); - sort(0); + BuildTableModelMap(sourceModel()); + emit layoutChanged(); } } // namespace AssetBrowser } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index 69b8ead7c5..51976c3482 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -1,25 +1,16 @@ #pragma once #if !defined(Q_MOC_RUN) -#include #include -#include -#include -//#include -#include - -AZ_PUSH_DISABLE_WARNING( - 4251, "-Wunknown-warning-option") // 4251: class '...' needs to have dll-interface to be used by clients of class '...' -#include -#include #include +#include #endif -AZ_POP_DISABLE_WARNING + namespace AzToolsFramework { namespace AssetBrowser { class AssetBrowserFilterModel; - + class AssetBrowserEntry; class AssetBrowserTableModel : public QSortFilterProxyModel @@ -34,21 +25,20 @@ namespace AzToolsFramework void setSourceModel(QAbstractItemModel* sourceModel) override; QModelIndex mapToSource(const QModelIndex& proxyIndex) const override; QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override; - bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; QModelIndex parent(const QModelIndex& child) const override; QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - public Q_SLOTS: - void UpdateMap(); + void UpdateTableModelMaps(); protected: + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; int rowCount(const QModelIndex& parent = QModelIndex()) const override; QVariant headerData(int section, Qt::Orientation orientation, int role /* = Qt::DisplayRole */) const override; //////////////////////////////////////////////////////////////////// private: AssetBrowserEntry* GetAssetEntry(QModelIndex index) const; - int BuildMap(const QAbstractItemModel* model, const QModelIndex& parent = QModelIndex(), int row = 0); + int BuildTableModelMap(const QAbstractItemModel* model, const QModelIndex& parent = QModelIndex(), int row = 0); private: QPointer m_filterModel; QMap m_indexMap; diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 554c62a251..f415e0a135 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -96,7 +96,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->m_assetBrowserTreeViewWidget->UpdateAfterFilter(hasFilter, selectFirstFilteredIndex); }); - connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, m_tableModel.data(), &AssetBrowserTableModel::UpdateMap); + connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, m_tableModel.data(), &AssetBrowserTableModel::UpdateTableModelMaps); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); From c1e21185b43e7892973dc1055ae19d1b9099b5e1 Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 12 May 2021 12:20:23 +0100 Subject: [PATCH 047/811] Selecting correct indexes from Asset Browser Model --- .../Views/AssetBrowserTableView.cpp | 22 +++++------ .../Views/AssetBrowserTableView.h | 7 +--- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 39 ++++++++++++++++++- .../AzAssetBrowser/AzAssetBrowserWindow.h | 2 +- 4 files changed, 52 insertions(+), 18 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index aa35d99894..0a6aeed374 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -47,7 +47,7 @@ namespace AzToolsFramework setMouseTracking(true); connect(this, &QTableView::customContextMenuRequested, this, &AssetBrowserTableView::OnContextMenu); - connect(m_scTimer, &QTimer::timeout, this, &AssetBrowserTableView::OnUpdateSCThumbnailsList); + //connect(m_scTimer, &QTimer::timeout, this, &AssetBrowserTableView::OnUpdateSCThumbnailsList); AssetBrowserViewRequestBus::Handler::BusConnect(); AssetBrowserComponentNotificationBus::Handler::BusConnect(); @@ -59,9 +59,9 @@ namespace AzToolsFramework } void AssetBrowserTableView::setModel(QAbstractItemModel* model) { - m_filterModel = qobject_cast(model); - AZ_Assert(m_filterModel, "Expecting AssetBrowserTableModel"); - m_sourceModel = qobject_cast(m_filterModel->sourceModel()); + m_tableModel = qobject_cast(model); + AZ_Assert(m_tableModel, "Expecting AssetBrowserTableModel"); + m_sourceFilterModel = qobject_cast(m_tableModel->sourceModel()); QTableView::setModel(model); } void AssetBrowserTableView::SetName(const QString& name) @@ -76,14 +76,14 @@ namespace AzToolsFramework } AZStd::vector AssetBrowserTableView::GetSelectedAssets() const { - QModelIndexList sourceIndexes{}; - //for (const auto& index : selectedIndexes()) - //{ - // sourceIndexes.push_back(m_sourceModel->mapToSource(index)); - //} + QModelIndexList sourceIndexes; + for (const auto& index : selectedIndexes()) + { + sourceIndexes.push_back(m_sourceFilterModel->mapToSource(m_tableModel->mapToSource(index))); + } AZStd::vector entries; - //AssetBrowserModel::SourceIndexesToAssetDatabaseEntries(sourceIndexes, entries); + AssetBrowserModel::SourceIndexesToAssetDatabaseEntries(sourceIndexes, entries); return entries; } void AssetBrowserTableView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) @@ -124,7 +124,7 @@ namespace AzToolsFramework { emit ClearStringFilter(); emit ClearTypeFilter(); - m_sourceModel->FilterUpdatedSlotImmediate(); + m_sourceFilterModel->FilterUpdatedSlotImmediate(); } void AssetBrowserTableView::Update() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h index aef7353334..d1bab70104 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -63,13 +63,10 @@ namespace AzToolsFramework private: QString m_name; - QPointer m_filterModel = nullptr; - QPointer m_sourceModel = nullptr; + QPointer m_tableModel = nullptr; + QPointer m_sourceFilterModel = nullptr; EntryDelegate* m_delegate = nullptr; - QTimer* m_scTimer = nullptr; - const int m_scUpdateInterval = 100; - private Q_SLOTS: void OnContextMenu(const QPoint& point); //! Get all visible source entries and place them in a queue to update their source control status diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index f415e0a135..b59190d9a9 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -102,7 +102,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) this, &AzAssetBrowserWindow::SelectionChangedSlot); connect(m_ui->m_assetBrowserTreeViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); - connect(m_ui->m_assetBrowserTableViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); + connect(m_ui->m_assetBrowserTableViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItemTableModel); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, &SearchWidget::ClearStringFilter); @@ -242,6 +242,43 @@ void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& } +void AzAssetBrowserWindow::DoubleClickedItemTableModel([[maybe_unused]] const QModelIndex& element) +{ + using namespace AzToolsFramework; + using namespace AzToolsFramework::AssetBrowser; + // assumption: Double clicking an item selects it before telling us we double clicked it. + auto selectedAssets = m_ui->m_assetBrowserTableViewWidget->GetSelectedAssets(); + for (const AssetBrowserEntry* entry : selectedAssets) + { + AZ::Data::AssetId assetIdToOpen; + AZStd::string fullFilePath; + + if (const ProductAssetBrowserEntry* productEntry = azrtti_cast(entry)) + { + assetIdToOpen = productEntry->GetAssetId(); + fullFilePath = entry->GetFullPath(); + } + else if (const SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry)) + { + // manufacture an empty AssetID with the source's UUID + assetIdToOpen = AZ::Data::AssetId(sourceEntry->GetSourceUuid(), 0); + fullFilePath = entry->GetFullPath(); + } + + bool handledBySomeone = false; + if (assetIdToOpen.IsValid()) + { + AssetBrowserInteractionNotificationBus::Broadcast( + &AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); + } + + if (!handledBySomeone && !fullFilePath.empty()) + { + AzAssetBrowserRequestHandler::OpenWithOS(fullFilePath); + } + } +} + void AzAssetBrowserWindow::SwitchDisplayView(const int state) { m_ui->m_assetBrowserTableViewWidget->setVisible(state); diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h index 801af3e2a8..86d81ad873 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h @@ -56,7 +56,6 @@ private: QScopedPointer m_ui; QScopedPointer m_filterModel; QScopedPointer m_tableModel; - //QScopedPointer m_tableFilterModel; AzToolsFramework::AssetBrowser::AssetBrowserModel* m_assetBrowserModel; void UpdatePreview() const; @@ -64,6 +63,7 @@ private: private Q_SLOTS: void SelectionChangedSlot(const QItemSelection& selected, const QItemSelection& deselected) const; void DoubleClickedItem(const QModelIndex& element); + void DoubleClickedItemTableModel(const QModelIndex& element); void SwitchDisplayView(const int state); }; From d6868df735033804d51c52949bfcc87d1d6cbeb6 Mon Sep 17 00:00:00 2001 From: igarri Date: Thu, 13 May 2021 12:29:16 +0100 Subject: [PATCH 048/811] Expanding TableView Columns --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 2 +- .../AssetBrowser/AssetBrowserTableModel.cpp | 1 - .../AssetBrowser/Views/AssetBrowserTableView.cpp | 15 ++++----------- .../AssetBrowser/Views/AssetBrowserTableView.h | 5 ----- 4 files changed, 5 insertions(+), 18 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 34f8b97b5a..ee3aa04e27 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -32,7 +32,7 @@ namespace AzToolsFramework : QSortFilterProxyModel(parent) { m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); - //m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); + m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); m_collator.setNumericMode(true); AssetBrowserComponentNotificationBus::Handler::BusConnect(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 724e7a54d9..13b298cdec 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -1,4 +1,3 @@ - #include #include #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index 0a6aeed374..40e0b9db5e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -1,7 +1,5 @@ #include -#include -#include #include #include @@ -14,8 +12,6 @@ #include #include #include -#include -#include AZ_PUSH_DISABLE_WARNING( 4244 4251 4800, "-Wunknown-warning-option") // conversion from 'int' to 'float', possible loss of data, needs to have dll-interface to @@ -37,17 +33,16 @@ namespace AzToolsFramework AssetBrowserTableView::AssetBrowserTableView(QWidget* parent) : QTableView(parent) , m_delegate(new EntryDelegate(this)) - { setSortingEnabled(true); setItemDelegate(m_delegate); - //header()->hide(); + verticalHeader()->hide(); setContextMenuPolicy(Qt::CustomContextMenu); setMouseTracking(true); + setSortingEnabled(false); connect(this, &QTableView::customContextMenuRequested, this, &AssetBrowserTableView::OnContextMenu); - //connect(m_scTimer, &QTimer::timeout, this, &AssetBrowserTableView::OnUpdateSCThumbnailsList); AssetBrowserViewRequestBus::Handler::BusConnect(); AssetBrowserComponentNotificationBus::Handler::BusConnect(); @@ -63,6 +58,8 @@ namespace AzToolsFramework AZ_Assert(m_tableModel, "Expecting AssetBrowserTableModel"); m_sourceFilterModel = qobject_cast(m_tableModel->sourceModel()); QTableView::setModel(model); + horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch); + horizontalHeader()->setSectionResizeMode(1,QHeaderView::ResizeMode::Stretch); } void AssetBrowserTableView::SetName(const QString& name) { @@ -105,10 +102,6 @@ namespace AzToolsFramework } } QTableView::rowsAboutToBeRemoved(parent, start, end); - } - void AssetBrowserTableView::OnUpdateSCThumbnailsList() - { - } void AssetBrowserTableView::SelectProduct(AZ::Data::AssetId assetID) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h index d1bab70104..531e962297 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -58,9 +58,6 @@ namespace AzToolsFramework void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) override; void rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) override; - //! Get all visible source entries and place them in a queue to update their source control status - //void OnUpdateSCThumbnailsList(); - private: QString m_name; QPointer m_tableModel = nullptr; @@ -69,8 +66,6 @@ namespace AzToolsFramework private Q_SLOTS: void OnContextMenu(const QPoint& point); - //! Get all visible source entries and place them in a queue to update their source control status - void OnUpdateSCThumbnailsList(); }; } // namespace AssetBrowser } // namespace AzToolsFramework From d7ca3f273bb656f0b162eeeede07ba87cafca22f Mon Sep 17 00:00:00 2001 From: igarri Date: Thu, 13 May 2021 13:25:03 +0100 Subject: [PATCH 049/811] croll to top on view when the filter updates --- .../AssetBrowser/AssetBrowserTableModel.cpp | 1 + .../AssetBrowser/Views/AssetBrowserTableView.cpp | 9 +++++++++ .../AssetBrowser/Views/AssetBrowserTableView.h | 1 + 3 files changed, 11 insertions(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 13b298cdec..7991eb35d8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -145,6 +145,7 @@ namespace AzToolsFramework } BuildTableModelMap(sourceModel()); emit layoutChanged(); + } } // namespace AssetBrowser } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index 40e0b9db5e..83a0f2ce9f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -58,6 +58,8 @@ namespace AzToolsFramework AZ_Assert(m_tableModel, "Expecting AssetBrowserTableModel"); m_sourceFilterModel = qobject_cast(m_tableModel->sourceModel()); QTableView::setModel(model); + connect(m_tableModel, &AssetBrowserTableModel::layoutChanged, this, &AssetBrowserTableView::layoutChangedSlot); + horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch); horizontalHeader()->setSectionResizeMode(1,QHeaderView::ResizeMode::Stretch); } @@ -103,6 +105,13 @@ namespace AzToolsFramework } QTableView::rowsAboutToBeRemoved(parent, start, end); } + void AssetBrowserTableView::layoutChangedSlot(const QList& parents, QAbstractItemModel::LayoutChangeHint hint) + { + AZ_UNUSED(parents); + AZ_UNUSED(hint); + + scrollToTop(); + } void AssetBrowserTableView::SelectProduct(AZ::Data::AssetId assetID) { AZ_UNUSED(assetID); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h index 531e962297..b39d48c391 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -57,6 +57,7 @@ namespace AzToolsFramework protected Q_SLOTS: void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) override; void rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) override; + void layoutChangedSlot(const QList &parents = QList(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint); private: QString m_name; From 33240c9f90fad3cf4c4e30ef1fcda909a0acad7b Mon Sep 17 00:00:00 2001 From: igarri Date: Thu, 13 May 2021 16:08:14 +0100 Subject: [PATCH 050/811] Selecting assets from tableview --- .../AssetBrowser/AssetBrowserTableModel.cpp | 13 +------------ .../AssetBrowser/AssetBrowserTableModel.h | 2 -- .../AssetBrowser/Views/AssetBrowserTableView.cpp | 12 ++++++++---- .../AssetBrowser/Views/AssetBrowserTreeView.cpp | 5 ++++- 4 files changed, 13 insertions(+), 19 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 7991eb35d8..bebdf44c9a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -27,15 +27,6 @@ namespace AzToolsFramework } return m_indexMap[proxyIndex.row()]; } - QModelIndex AssetBrowserTableModel::mapFromSource(const QModelIndex& sourceIndex) const - { - Q_ASSERT(!sourceIndex.isValid() || sourceIndex.model() == sourceModel()); - if (!sourceIndex.isValid()) - { - return QModelIndex(); - } - return createIndex(m_rowMap[sourceIndex], sourceIndex.column(), sourceIndex.internalPointer()); - } QVariant AssetBrowserTableModel::headerData(int section, Qt::Orientation orientation, int role) const { @@ -94,7 +85,7 @@ namespace AzToolsFramework int AssetBrowserTableModel::rowCount(const QModelIndex& parent) const { - return !parent.isValid() ? m_rowMap.size() : 0; + return !parent.isValid() ? m_indexMap.size() : 0; } int AssetBrowserTableModel::BuildTableModelMap(const QAbstractItemModel* model, const QModelIndex& parent /*= QModelIndex()*/, int row /*= 0*/) @@ -106,7 +97,6 @@ namespace AzToolsFramework if (model->hasChildren(index) == false) { beginInsertRows(parent, row, row); - m_rowMap[index] = row; m_indexMap[row] = index; endInsertRows(); @@ -139,7 +129,6 @@ namespace AzToolsFramework if (m_indexMap.size() > 0) { beginRemoveRows(m_indexMap.first(), m_indexMap.first().row(), m_indexMap.last().row()); - m_rowMap.clear(); m_indexMap.clear(); endRemoveRows(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index 51976c3482..432300194b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -24,7 +24,6 @@ namespace AzToolsFramework // QSortFilterProxyModel void setSourceModel(QAbstractItemModel* sourceModel) override; QModelIndex mapToSource(const QModelIndex& proxyIndex) const override; - QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override; QModelIndex parent(const QModelIndex& child) const override; QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; @@ -42,7 +41,6 @@ namespace AzToolsFramework private: QPointer m_filterModel; QMap m_indexMap; - QMap m_rowMap; }; } // namespace AssetBrowser } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index 83a0f2ce9f..cb4a989043 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -41,6 +41,7 @@ namespace AzToolsFramework setMouseTracking(true); setSortingEnabled(false); + setSelectionMode(QAbstractItemView::SingleSelection); connect(this, &QTableView::customContextMenuRequested, this, &AssetBrowserTableView::OnContextMenu); @@ -61,7 +62,7 @@ namespace AzToolsFramework connect(m_tableModel, &AssetBrowserTableModel::layoutChanged, this, &AssetBrowserTableView::layoutChangedSlot); horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch); - horizontalHeader()->setSectionResizeMode(1,QHeaderView::ResizeMode::Stretch); + horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeMode::Stretch); } void AssetBrowserTableView::SetName(const QString& name) { @@ -78,7 +79,10 @@ namespace AzToolsFramework QModelIndexList sourceIndexes; for (const auto& index : selectedIndexes()) { - sourceIndexes.push_back(m_sourceFilterModel->mapToSource(m_tableModel->mapToSource(index))); + if (index.column() == 0) + { + sourceIndexes.push_back(m_sourceFilterModel->mapToSource(m_tableModel->mapToSource(index))); + } } AZStd::vector entries; @@ -87,8 +91,8 @@ namespace AzToolsFramework } void AssetBrowserTableView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { - AZ_UNUSED(selected); - AZ_UNUSED(deselected); + QTableView::selectionChanged(selected, deselected); + Q_EMIT selectionChangedSignal(selected, deselected); } void AssetBrowserTableView::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp index eeee433835..f2a5cc1a3a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp @@ -101,7 +101,10 @@ namespace AzToolsFramework QModelIndexList sourceIndexes; for (const auto& index : selectedIndexes()) { - sourceIndexes.push_back(m_assetBrowserSortFilterProxyModel->mapToSource(index)); + if (index.column() == 0) + { + sourceIndexes.push_back(m_assetBrowserSortFilterProxyModel->mapToSource(index)); + } } AZStd::vector entries; From 99c2c3b07be18aa95d0381e7eca5c8d80a004215 Mon Sep 17 00:00:00 2001 From: phistere Date: Thu, 13 May 2021 19:04:20 -0500 Subject: [PATCH 051/811] Updates the settings registry visitor that walks through 'engines' from the manifest --- .../Settings/SettingsRegistryMergeUtils.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp index 56dfbdcb71..10a830bcc6 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp @@ -88,6 +88,35 @@ namespace AZ::Internal m_enginePaths.emplace_back(EngineInfo{AZ::IO::FixedMaxPath{value}.LexicallyNormal(), {}}); } + AZ::SettingsRegistryInterface::VisitResponse Traverse( + [[maybe_unused]] AZStd::string_view path, AZStd::string_view valueName, + AZ::SettingsRegistryInterface::VisitAction action, AZ::SettingsRegistryInterface::Type type) override + { + auto response = AZ::SettingsRegistryInterface::VisitResponse::Continue; + if (action == AZ::SettingsRegistryInterface::VisitAction::Begin) + { + if (type == AZ::SettingsRegistryInterface::Type::Array) + { + if (valueName.compare("engines") != 0) + { + response = AZ::SettingsRegistryInterface::VisitResponse::Skip; + } + } + } + else if (action == AZ::SettingsRegistryInterface::VisitAction::Value) + { + if (type == AZ::SettingsRegistryInterface::Type::String) + { + if (valueName.compare("path") != 0) + { + response = AZ::SettingsRegistryInterface::VisitResponse::Skip; + } + } + } + + return response; + } + AZStd::vector m_enginePaths{}; }; From cff9fea535c91a08ce4d444c2a79823d53f2f75c Mon Sep 17 00:00:00 2001 From: igarri Date: Fri, 14 May 2021 13:09:14 +0100 Subject: [PATCH 052/811] Switching views with filters --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 6 ++++++ .../AssetBrowser/AssetBrowserFilterModel.h | 2 +- .../AzToolsFramework/AssetBrowser/Search/Filter.cpp | 5 +++++ .../AzToolsFramework/AssetBrowser/Search/Filter.h | 2 +- .../AssetBrowser/Views/AssetBrowserTreeView.cpp | 2 ++ .../Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp | 9 +++++++-- .../Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h | 2 +- 7 files changed, 23 insertions(+), 5 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index ee3aa04e27..b4728633d3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -130,6 +130,9 @@ namespace AzToolsFramework if (compFilter) { auto& subFilters = compFilter->GetSubFilters(); + //bool bNoFilters = false; + + auto it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { auto assetTypeFilter = qobject_cast >(filter); @@ -147,8 +150,11 @@ namespace AzToolsFramework if (it != subFilters.end()) { m_stringFilter = qobject_cast >(*it); + emit switchFilterView(m_stringFilter.toStrongRef()->IsEmpty()); } } + + invalidateFilter(); Q_EMIT filterChanged(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h index 6cccc53eb6..71689354d1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h @@ -52,8 +52,8 @@ namespace AzToolsFramework void OnAssetBrowserComponentReady() override; Q_SIGNALS: + void switchFilterView(int); void filterChanged(); - ////////////////////////////////////////////////////////////////////////// //QSortFilterProxyModel protected: diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp index ceda5f8e19..86315613ad 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp @@ -233,6 +233,11 @@ namespace AzToolsFramework Q_EMIT updatedSignal(); } + bool StringFilter::IsEmpty() const + { + return m_filterString.isEmpty(); + } + QString StringFilter::GetNameInternal() const { return m_filterString; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h index b67b699862..6d19fb3b47 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h @@ -110,7 +110,7 @@ namespace AzToolsFramework ~StringFilter() override = default; void SetFilterString(const QString& filterString); - + bool IsEmpty() const; protected: QString GetNameInternal() const override; bool MatchInternal(const AssetBrowserEntry* entry) const override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp index f2a5cc1a3a..e29607698d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp @@ -52,6 +52,7 @@ namespace AzToolsFramework setSortingEnabled(true); setItemDelegate(m_delegate); header()->hide(); + setContextMenuPolicy(Qt::CustomContextMenu); setMouseTracking(true); @@ -174,6 +175,7 @@ namespace AzToolsFramework void AssetBrowserTreeView::OnAssetBrowserComponentReady() { + hideColumn(static_cast(AssetBrowserEntry::Column::Path)); if (!m_name.isEmpty()) { auto crc = AZ::Crc32(m_name.toUtf8().data()); diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index b59190d9a9..d1bbbb1f9d 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -82,7 +82,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_tableModel->setSourceModel(m_filterModel.data()); m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); - m_ui->m_assetBrowserTreeViewWidget->hideColumn(static_cast(AssetBrowserEntry::Column::Path)); + //m_ui->m_assetBrowserTreeViewWidget->hideColumn(static_cast(AssetBrowserEntry::Column::Path)); m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); m_ui->m_assetBrowserTableViewWidget->setVisible(false); @@ -97,9 +97,14 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) }); connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, m_tableModel.data(), &AssetBrowserTableModel::UpdateTableModelMaps); + connect(m_filterModel.data(), &AssetBrowserFilterModel::switchFilterView, this, &AzAssetBrowserWindow::SwitchDisplayView); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); + + connect(m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::selectionChangedSignal, + this, &AzAssetBrowserWindow::SelectionChangedSlot); + connect(m_ui->m_assetBrowserTreeViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); connect(m_ui->m_assetBrowserTableViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItemTableModel); @@ -279,7 +284,7 @@ void AzAssetBrowserWindow::DoubleClickedItemTableModel([[maybe_unused]] const QM } } -void AzAssetBrowserWindow::SwitchDisplayView(const int state) +void AzAssetBrowserWindow::SwitchDisplayView(bool state) { m_ui->m_assetBrowserTableViewWidget->setVisible(state); m_ui->m_assetBrowserTreeViewWidget->setVisible(!state); diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h index 86d81ad873..8c32a913ba 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h @@ -64,7 +64,7 @@ private Q_SLOTS: void SelectionChangedSlot(const QItemSelection& selected, const QItemSelection& deselected) const; void DoubleClickedItem(const QModelIndex& element); void DoubleClickedItemTableModel(const QModelIndex& element); - void SwitchDisplayView(const int state); + void SwitchDisplayView(bool state); }; extern const char* AZ_ASSET_BROWSER_PREVIEW_NAME; From 74fda49ca4e99348da42c41da774ea32d04eab69 Mon Sep 17 00:00:00 2001 From: phistere Date: Sun, 16 May 2021 11:39:49 -0500 Subject: [PATCH 053/811] Fixes paths to AssetProcessor when being run from SDK. --- .../AzFramework/Asset/AssetSystemComponentHelper_Linux.cpp | 3 ++- .../Mac/AzFramework/Asset/AssetSystemComponentHelper_Mac.cpp | 3 ++- .../AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzFramework/Platform/Linux/AzFramework/Asset/AssetSystemComponentHelper_Linux.cpp b/Code/Framework/AzFramework/Platform/Linux/AzFramework/Asset/AssetSystemComponentHelper_Linux.cpp index 1ae3945bd6..d501271f59 100644 --- a/Code/Framework/AzFramework/Platform/Linux/AzFramework/Asset/AssetSystemComponentHelper_Linux.cpp +++ b/Code/Framework/AzFramework/Platform/Linux/AzFramework/Asset/AssetSystemComponentHelper_Linux.cpp @@ -35,7 +35,8 @@ namespace AzFramework::AssetSystem::Platform if (!AZ::IO::SystemFile::Exists(assetProcessorPath.c_str())) { // Check for existence of one under a "bin" directory, i.e. engineRoot is an SDK structure. - assetProcessorPath = AZ::IO::FixedMaxPath{engineRoot} / "bin" / AZ_BUILD_CONFIGURATION_TYPE / "AssetProcessor"; + assetProcessorPath = + AZ::IO::FixedMaxPath{engineRoot} / "bin" / AZ_TRAIT_OS_PLATFORM_NAME / AZ_BUILD_CONFIGURATION_TYPE / "AssetProcessor"; if (!AZ::IO::SystemFile::Exists(assetProcessorPath.c_str())) { diff --git a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Asset/AssetSystemComponentHelper_Mac.cpp b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Asset/AssetSystemComponentHelper_Mac.cpp index 6f1f860932..890b6b32c3 100644 --- a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Asset/AssetSystemComponentHelper_Mac.cpp +++ b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Asset/AssetSystemComponentHelper_Mac.cpp @@ -34,7 +34,8 @@ namespace AzFramework::AssetSystem::Platform if (!AZ::IO::SystemFile::Exists(assetProcessorPath.c_str())) { // Check for existence of one under a "bin" directory, i.e. engineRoot is an SDK structure. - assetProcessorPath = AZ::IO::FixedMaxPath{engineRoot} / "bin" / AZ_BUILD_CONFIGURATION_TYPE / "AssetProcessor.app"; + assetProcessorPath = + AZ::IO::FixedMaxPath{engineRoot} / "bin" / AZ_TRAIT_OS_PLATFORM_NAME / AZ_BUILD_CONFIGURATION_TYPE / "AssetProcessor.app"; if (!AZ::IO::SystemFile::Exists(assetProcessorPath.c_str())) { diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp index b716778cf4..b0debfd3b0 100644 --- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp +++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp @@ -71,7 +71,8 @@ namespace AzFramework::AssetSystem::Platform if (!AZ::IO::SystemFile::Exists(assetProcessorPath.c_str())) { // Check for existence of one under a "bin" directory, i.e. engineRoot is an SDK structure. - assetProcessorPath = AZ::IO::FixedMaxPath{engineRoot} / "bin" / AZ_BUILD_CONFIGURATION_TYPE / "AssetProcessor.exe"; + assetProcessorPath = + AZ::IO::FixedMaxPath{engineRoot} / "bin" / AZ_TRAIT_OS_PLATFORM_NAME / AZ_BUILD_CONFIGURATION_TYPE / "AssetProcessor.exe"; if (!AZ::IO::SystemFile::Exists(assetProcessorPath.c_str())) { From b9c9811d3566a008feb330ef79d82b501bcd2ac3 Mon Sep 17 00:00:00 2001 From: igarri Date: Mon, 17 May 2021 14:06:01 +0100 Subject: [PATCH 054/811] Fixing qobject_cast to the StringFilter --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 33 ++++++++++++++----- .../AssetBrowser/AssetBrowserFilterModel.h | 2 +- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 2 +- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index b4728633d3..9ee00a96ae 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -130,9 +130,7 @@ namespace AzToolsFramework if (compFilter) { auto& subFilters = compFilter->GetSubFilters(); - //bool bNoFilters = false; - auto it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { auto assetTypeFilter = qobject_cast >(filter); @@ -142,21 +140,38 @@ namespace AzToolsFramework { m_assetTypeFilter = qobject_cast >(*it); } - it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool + + it = AZStd::find_if(subFilters.begin(), subFilters.end(), [](FilterConstType filter) -> bool { - auto stringFilter = qobject_cast >(filter); - return !stringFilter.isNull(); + auto stringCompositeFilter = qobject_cast >(filter); + bool isStringFilter = false; + if (stringCompositeFilter) + { + auto& subFilters = stringCompositeFilter->GetSubFilters(); + auto it = AZStd::find_if(subFilters.begin(), subFilters.end(), [](FilterConstType filt) -> bool + { + auto strFilter = qobject_cast>(filt); + return !strFilter.isNull(); + }); + if (it != subFilters.end()) + { + isStringFilter = true; + } + } + + return isStringFilter; }); if (it != subFilters.end()) { - m_stringFilter = qobject_cast >(*it); - emit switchFilterView(m_stringFilter.toStrongRef()->IsEmpty()); + auto compStringFilter = qobject_cast>(*it); + m_stringFilter = qobject_cast>(compStringFilter->GetSubFilters()[0]); } + } - - invalidateFilter(); Q_EMIT filterChanged(); + emit stringFilterPopulated(!m_stringFilter.isNull()); + } void AssetBrowserFilterModel::filterUpdatedSlot() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h index 71689354d1..7a6faf9f18 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h @@ -52,7 +52,7 @@ namespace AzToolsFramework void OnAssetBrowserComponentReady() override; Q_SIGNALS: - void switchFilterView(int); + void stringFilterPopulated(bool); void filterChanged(); ////////////////////////////////////////////////////////////////////////// //QSortFilterProxyModel diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index d1bbbb1f9d..047d4d4dc2 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -97,7 +97,6 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) }); connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, m_tableModel.data(), &AssetBrowserTableModel::UpdateTableModelMaps); - connect(m_filterModel.data(), &AssetBrowserFilterModel::switchFilterView, this, &AzAssetBrowserWindow::SwitchDisplayView); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); @@ -119,6 +118,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->m_assetBrowserTreeViewWidget->SetName("AssetBrowserTreeView_main"); m_ui->m_assetBrowserTableViewWidget->SetName("AssetBrowserTableView_main"); + connect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); connect(m_ui->m_viewSwitcherCheckBox, &QCheckBox::stateChanged, this, &AzAssetBrowserWindow::SwitchDisplayView); } From 10ca002ced59314ac7e4bc01365a2fb7f4682ebe Mon Sep 17 00:00:00 2001 From: igarri Date: Mon, 17 May 2021 14:25:43 +0100 Subject: [PATCH 055/811] Checkbox to select view --- .../Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp | 13 ++++++++++++- .../Editor/AzAssetBrowser/AzAssetBrowserWindow.h | 1 + 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 047d4d4dc2..8c01f6841c 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -119,7 +119,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->m_assetBrowserTableViewWidget->SetName("AssetBrowserTableView_main"); connect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); - connect(m_ui->m_viewSwitcherCheckBox, &QCheckBox::stateChanged, this, &AzAssetBrowserWindow::SwitchDisplayView); + connect(m_ui->m_viewSwitcherCheckBox, &QCheckBox::stateChanged, this, &AzAssetBrowserWindow::LockToDefaultView); } AzAssetBrowserWindow::~AzAssetBrowserWindow() @@ -290,4 +290,15 @@ void AzAssetBrowserWindow::SwitchDisplayView(bool state) m_ui->m_assetBrowserTreeViewWidget->setVisible(!state); } +void AzAssetBrowserWindow::LockToDefaultView(bool state) +{ + using namespace AzToolsFramework; + using namespace AzToolsFramework::AssetBrowser; + SwitchDisplayView(!state); + if (state == true) + disconnect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); + else + connect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); +} + #include diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h index 8c32a913ba..1174335995 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.h @@ -65,6 +65,7 @@ private Q_SLOTS: void DoubleClickedItem(const QModelIndex& element); void DoubleClickedItemTableModel(const QModelIndex& element); void SwitchDisplayView(bool state); + void LockToDefaultView(bool state); }; extern const char* AZ_ASSET_BROWSER_PREVIEW_NAME; From 61ac423ebdc0c9865a95710d94f7f21c1c9ce463 Mon Sep 17 00:00:00 2001 From: igarri Date: Mon, 17 May 2021 16:04:43 +0100 Subject: [PATCH 056/811] Deleted unused files --- .../AzToolsFramework/AssetBrowserTableModel.h | 36 ------------------- 1 file changed, 36 deletions(-) delete mode 100644 Code/Framework/AzToolsFramework/AssetBrowserTableModel.h diff --git a/Code/Framework/AzToolsFramework/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AssetBrowserTableModel.h deleted file mode 100644 index 4e65b3921c..0000000000 --- a/Code/Framework/AzToolsFramework/AssetBrowserTableModel.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once -#if !defined(Q_MOC_RUN) -#include -#include -#include - -#include -#include -#include - -AZ_PUSH_DISABLE_WARNING( - 4251, "-Wunknown-warning-option") // 4251: class '...' needs to have dll-interface to be used by clients of class '...' -#include -#include -#include -#endif -AZ_POP_DISABLE_WARNING -namespace AzToolsFramework -{ - namespace AssetBrowser - { - class AssetBrowserTableModel - : public QSortFilterProxyModel - { - Q_OBJECT - public: - AZ_CLASS_ALLOCATOR(AssetBrowserTableModel, AZ::SystemAllocator, 0); - explicit AssetBrowserTableModel(QObject* parent = nullptr); - - QModelIndex mapToSource(const QModelIndex &proxyIndex) const override; - QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override; - QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; - QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - }; - } -} From f30b1f2c75977a32a69732815ed32962e46ee2d4 Mon Sep 17 00:00:00 2001 From: phistere Date: Mon, 17 May 2021 11:41:10 -0500 Subject: [PATCH 057/811] Work in Progress: template changes, getting external projects w/ SDK to work --- .../DefaultProject/Template/CMakeLists.txt | 155 ++++++++++++------ .../Template/EngineFinder.cmake | 64 ++++++++ Templates/DefaultProject/template.json | 6 + 3 files changed, 176 insertions(+), 49 deletions(-) create mode 100644 Templates/DefaultProject/Template/EngineFinder.cmake diff --git a/Templates/DefaultProject/Template/CMakeLists.txt b/Templates/DefaultProject/Template/CMakeLists.txt index ad0a4c869d..c92607a789 100644 --- a/Templates/DefaultProject/Template/CMakeLists.txt +++ b/Templates/DefaultProject/Template/CMakeLists.txt @@ -23,64 +23,121 @@ function(add_vs_debugger_arguments) endforeach() endfunction() -set(o3de_project_path ${CMAKE_CURRENT_LIST_DIR}) -set(o3de_project_json ${o3de_project_path}/project.json) - if(NOT PROJECT_NAME) cmake_minimum_required(VERSION 3.19) project(${Name} LANGUAGES C CXX VERSION 1.0.0.0 ) + include(EngineFinder.cmake OPTIONAL) + find_package(o3de REQUIRED) + o3de_initialize() + add_vs_debugger_arguments() +else() + # Add the project_name to global LY_PROJECTS_TARGET_NAME property + file(READ "${CMAKE_CURRENT_LIST_DIR}/project.json" project_json) - # set this project as the only project - set(LY_PROJECTS ${CMAKE_CURRENT_LIST_DIR}) - - # o3de manifest - include(o3de_manifest.cmake) - - ################################################################################ - # Set the engine_path and resolve this engines restricted path if it has one - ################################################################################ - o3de_engine_path(${o3de_project_json} o3de_engine_path) - o3de_project_name(${o3de_project_json} o3de_project_name) - o3de_restricted_path(${o3de_project_json} o3de_project_restricted_path) - message(STATUS "O3DE Project Name: ${o3de_project_name}") - message(STATUS "O3DE Project Path: ${o3de_project_path}") - if(o3de_project_restricted_path) - message(STATUS "O3DE Project Restricted Path: ${o3de_project_restricted_path}") + string(JSON project_target_name ERROR_VARIABLE json_error GET ${project_json} "project_name") + if(json_error) + message(FATAL_ERROR "Unable to read key 'project_name' from 'project.json'") endif() - # add the engines cmake folder to the CMAKE_MODULE_PATH - list(APPEND CMAKE_MODULE_PATH "${o3de_engine_path}/cmake") - - # add subdirectory on the engine path for this project - add_subdirectory(${o3de_engine_path} o3de) - - # add this --project-path arguments to visual studio debugger - add_vs_debugger_arguments() - -else() - ###################################################### - # the engine is calling add sub_directory() on us - ###################################################### - o3de_project_name(${o3de_project_json} o3de_project_name) - o3de_restricted_path(${o3de_project_json} o3de_project_restricted_path) - - # Currently we are in the folder: ${CMAKE_CURRENT_LIST_DIR} - # Get the platform specific folder ${pal_dir} for the folder: ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} - # Note: ly_get_list_relative_pal_filename will take care of the details for us, as this may be a restricted platform - # in which case it will see if that platform is present here or in the restricted folder. - # i.e. It could here: TestDP/Platform/ or - # //TestDP - ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} ${o3de_project_restricted_path} ${o3de_project_path} ${o3de_project_name}) - - # Now that we have the platform abstraction layer (PAL) folder for this folder, thats where we will find the - # project cmake for this platform. - include(${pal_dir}/${PAL_PLATFORM_NAME_LOWERCASE}_project.cmake) - - # Add the project_name to global LY_PROJECTS_TARGET_NAME property - set_property(GLOBAL APPEND PROPERTY LY_PROJECTS_TARGET_NAME ${o3de_project_name}) + set_property(GLOBAL APPEND PROPERTY LY_PROJECTS_TARGET_NAME ${project_target_name}) add_subdirectory(Code) endif() + + + +# #! Adds the --project-path argument to the VS IDE debugger command arguments +# function(add_vs_debugger_arguments) +# # Inject the project root into the --project-path argument into the Visual Studio Debugger arguments by defaults +# list(APPEND app_targets ${Name}.GameLauncher ${Name}.ServerLauncher) +# list(APPEND app_targets AssetBuilder AssetProcessor AssetProcessorBatch Editor) +# foreach(app_target IN LISTS app_targets) +# if (TARGET ${app_target}) +# set_property(TARGET ${app_target} APPEND PROPERTY VS_DEBUGGER_COMMAND_ARGUMENTS "--project-path=\"${CMAKE_CURRENT_LIST_DIR}\"") +# endif() +# endforeach() +# endfunction() + +# set(o3de_project_path ${CMAKE_CURRENT_LIST_DIR}) +# set(o3de_project_json ${o3de_project_path}/project.json) + +# if(NOT PROJECT_NAME) +# cmake_minimum_required(VERSION 3.19) +# project(${Name} +# LANGUAGES C CXX +# VERSION 1.0.0.0 +# ) + +# # set this project as the only project +# set(LY_PROJECTS ${CMAKE_CURRENT_LIST_DIR}) + +# # o3de manifest +# include(o3de_manifest.cmake) + +# ################################################################################ +# # Set the engine_path and resolve this engines restricted path if it has one +# ################################################################################ +# o3de_engine_path(${o3de_project_json} o3de_engine_path) +# o3de_project_name(${o3de_project_json} o3de_project_name) +# o3de_restricted_path(${o3de_project_json} o3de_project_restricted_path) +# message(STATUS "O3DE Project Name: ${o3de_project_name}") +# message(STATUS "O3DE Project Path: ${o3de_project_path}") +# if(o3de_project_restricted_path) +# message(STATUS "O3DE Project Restricted Path: ${o3de_project_restricted_path}") +# endif() + +# # add the engines cmake folder to the CMAKE_MODULE_PATH +# list(APPEND CMAKE_MODULE_PATH "${o3de_engine_path}/cmake") + +# # add subdirectory on the engine path for this project +# #add_subdirectory(${o3de_engine_path} o3de) +# find_package(o3de REQUIRED) +# o3de_initialize() + +# # add this --project-path arguments to visual studio debugger +# add_vs_debugger_arguments() + +# else() +# ###################################################### +# # the engine is calling add sub_directory() on us +# ###################################################### +# o3de_project_name(${o3de_project_json} o3de_project_name) +# o3de_restricted_path(${o3de_project_json} o3de_project_restricted_path) + +# # Currently we are in the folder: ${CMAKE_CURRENT_LIST_DIR} +# # Get the platform specific folder ${pal_dir} for the folder: ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} +# # Note: ly_get_list_relative_pal_filename will take care of the details for us, as this may be a restricted platform +# # in which case it will see if that platform is present here or in the restricted folder. +# # i.e. It could here: TestDP/Platform/ or +# # //TestDP +# ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} ${o3de_project_restricted_path} ${o3de_project_path} ${o3de_project_name}) + +# # Now that we have the platform abstraction layer (PAL) folder for this folder, thats where we will find the +# # project cmake for this platform. +# include(${pal_dir}/${PAL_PLATFORM_NAME_LOWERCASE}_project.cmake) + +# # Add the project_name to global LY_PROJECTS_TARGET_NAME property +# set_property(GLOBAL APPEND PROPERTY LY_PROJECTS_TARGET_NAME ${o3de_project_name}) + +# add_subdirectory(Code) +# endif() + + + + + + + + + + + + + + + + + diff --git a/Templates/DefaultProject/Template/EngineFinder.cmake b/Templates/DefaultProject/Template/EngineFinder.cmake new file mode 100644 index 0000000000..5f791f5e3d --- /dev/null +++ b/Templates/DefaultProject/Template/EngineFinder.cmake @@ -0,0 +1,64 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +# This file is copied during engine registration. Edits to this file will be lost next +# time a registration happens. + +include_guard() + +# Read the engine name from the project_json file +file(READ ${CMAKE_CURRENT_LIST_DIR}/project.json project_json) +string(JSON LY_ENGINE_NAME_TO_USE ERROR_VARIABLE json_error GET ${project_json} engine) +if(json_error) + message(FATAL_ERROR "Unable to read key 'engine' from 'project.json', error: ${json_error}") +endif() + +# Read the list of paths from ~.o3de/o3de_manifest.json +if($ENV{USERPROFILE} AND EXISTS $ENV{USERPROFILE}) + set(manifest_path $ENV{USERPROFILE}/.o3de/o3de_manifest.json) # Windows +else() + set(manifest_path $ENV{HOME}/.o3de/o3de_manifest.json) # Unix +endif() + +if(EXISTS ${manifest_path}) + file(READ ${manifest_path} manifest_json) + + string(JSON engine_paths_count ERROR_VARIABLE json_error LENGTH ${manifest_json} engine_paths) + if(json_error) + message(FATAL_ERROR "Unable to read key 'engine_paths' from '${manifest_path}', error: ${json_error}") + endif() + + string(JSON engine_paths_type ERROR_VARIABLE json_error TYPE ${manifest_json} engine_paths) + if(json_error OR NOT ${engine_paths_type} STREQUAL "OBJECT") + message(FATAL_ERROR "Type of 'engine_paths' in '${manifest_path}' is not a JSON Object, error: ${json_error}") + endif() + + math(EXPR engine_paths_count "${engine_paths_count}-1") + foreach(engine_path_index RANGE ${engine_paths_count}) + string(JSON engine_name ERROR_VARIABLE json_error MEMBER ${manifest_json} engine_paths ${engine_path_index}) + if(json_error) + message(FATAL_ERROR "Unable to read 'engine_paths/${engine_path_index}' from '${manifest_path}', error: ${json_error}") + endif() + + if(LY_ENGINE_NAME_TO_USE STREQUAL engine_name) + string(JSON engine_path ERROR_VARIABLE json_error GET ${manifest_json} engine_paths ${engine_name}) + if(json_error) + message(FATAL_ERROR "Unable to read value from 'engine_paths/${engine_name}', error: ${json_error}") + endif() + + if(engine_path) + list(APPEND CMAKE_MODULE_PATH "${engine_path}/cmake") + break() + endif() + endif() + endforeach() +else() + message(FATAL_ERROR "Engine registration is required before configuring a project. Please register an engine by running 'scripts/o3de register --this-engine'") +endif() diff --git a/Templates/DefaultProject/template.json b/Templates/DefaultProject/template.json index 56278a6b04..e823b6df19 100644 --- a/Templates/DefaultProject/template.json +++ b/Templates/DefaultProject/template.json @@ -24,6 +24,12 @@ "isTemplated": true, "isOptional": false }, + { + "file": "EngineFinder.cmake", + "origin": "EngineFinder.cmake", + "isTemplated": false, + "isOptional": false + }, { "file": "Code/${NameLower}_files.cmake", "origin": "Code/${NameLower}_files.cmake", From d4a0eb3a246e2afcc10e9322638e3a420ef32bca Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Mon, 17 May 2021 13:03:37 -0500 Subject: [PATCH 058/811] Moving o3de registration scripts to the scripts/o3de folder --- {cmake/Tools => scripts/o3de}/engine_template.py | 0 {cmake/Tools => scripts/o3de}/global_project.py | 0 {cmake/Tools => scripts/o3de}/registration.py | 0 {cmake/Tools => scripts/o3de}/unit_test_add_remove_gem.py | 0 {cmake/Tools => scripts/o3de}/unit_test_current_project.py | 0 {cmake/Tools => scripts/o3de}/unit_test_engine_template.py | 0 {cmake/Tools => scripts/o3de}/unit_test_utils.py | 0 {cmake/Tools => scripts/o3de}/utils.py | 0 8 files changed, 0 insertions(+), 0 deletions(-) rename {cmake/Tools => scripts/o3de}/engine_template.py (100%) rename {cmake/Tools => scripts/o3de}/global_project.py (100%) rename {cmake/Tools => scripts/o3de}/registration.py (100%) rename {cmake/Tools => scripts/o3de}/unit_test_add_remove_gem.py (100%) rename {cmake/Tools => scripts/o3de}/unit_test_current_project.py (100%) rename {cmake/Tools => scripts/o3de}/unit_test_engine_template.py (100%) rename {cmake/Tools => scripts/o3de}/unit_test_utils.py (100%) rename {cmake/Tools => scripts/o3de}/utils.py (100%) diff --git a/cmake/Tools/engine_template.py b/scripts/o3de/engine_template.py similarity index 100% rename from cmake/Tools/engine_template.py rename to scripts/o3de/engine_template.py diff --git a/cmake/Tools/global_project.py b/scripts/o3de/global_project.py similarity index 100% rename from cmake/Tools/global_project.py rename to scripts/o3de/global_project.py diff --git a/cmake/Tools/registration.py b/scripts/o3de/registration.py similarity index 100% rename from cmake/Tools/registration.py rename to scripts/o3de/registration.py diff --git a/cmake/Tools/unit_test_add_remove_gem.py b/scripts/o3de/unit_test_add_remove_gem.py similarity index 100% rename from cmake/Tools/unit_test_add_remove_gem.py rename to scripts/o3de/unit_test_add_remove_gem.py diff --git a/cmake/Tools/unit_test_current_project.py b/scripts/o3de/unit_test_current_project.py similarity index 100% rename from cmake/Tools/unit_test_current_project.py rename to scripts/o3de/unit_test_current_project.py diff --git a/cmake/Tools/unit_test_engine_template.py b/scripts/o3de/unit_test_engine_template.py similarity index 100% rename from cmake/Tools/unit_test_engine_template.py rename to scripts/o3de/unit_test_engine_template.py diff --git a/cmake/Tools/unit_test_utils.py b/scripts/o3de/unit_test_utils.py similarity index 100% rename from cmake/Tools/unit_test_utils.py rename to scripts/o3de/unit_test_utils.py diff --git a/cmake/Tools/utils.py b/scripts/o3de/utils.py similarity index 100% rename from cmake/Tools/utils.py rename to scripts/o3de/utils.py From 4c2933b38d36dca8e2e0a2d412114a1bd1ab0d92 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Mon, 17 May 2021 18:44:32 -0400 Subject: [PATCH 059/811] Adding gems metadata query --- cmake/Tools/registration.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/cmake/Tools/registration.py b/cmake/Tools/registration.py index 184d2cdb31..70fbc5ba90 100755 --- a/cmake/Tools/registration.py +++ b/cmake/Tools/registration.py @@ -2216,6 +2216,19 @@ def get_gem_data(gem_name: str = None, return None +def get_gems_metadata(): + gem_list = get_gems() + get_engine_gems() + gem_data_dict = {} + for gem in gem_list: + json_path = os.path.join(gem, 'gem.json') + if (os.path.exists(json_path)): + with open(json_path, 'r') as gem_json: + parsed_meta_data = json.loads(gem_json.read()) + gem_data_dict[str(parsed_meta_data['gem_name'])] = parsed_meta_data + else: + logger.error(f'Gem json {gem_json} is not present.') + json_result = json.dumps(gem_data_dict, indent = 4) + return json_result def get_template_data(template_name: str = None, template_path: str or pathlib.Path = None, ) -> dict or None: @@ -2410,6 +2423,12 @@ def print_downloadables(verbose: int) -> None: print_templates_data(downloadable_data['templates']) print_restricted_data(downloadable_data['templates']) +def print_gems_metadata(verbose: int) -> None: + gems_data = get_gems_metadata() + print(gems_data) + if verbose > 0: + gem_list = get_gems() + get_engine_gems() + print(gem_list) def download_engine(engine_name: str, dest_path: str) -> int: @@ -3833,7 +3852,6 @@ def _run_register_show(args: argparse) -> int: if args.this_engine: print_this_engine(args.verbose) return 0 - elif args.engines: print_engines(args.verbose) return 0 @@ -3897,6 +3915,9 @@ def _run_register_show(args: argparse) -> int: elif args.downloadable_templates: print_downloadable_templates(args.verbose) return 0 + elif args.gems_data: + print_gems_metadata(args.verbose) + return 0 else: register_show(args.verbose) return 0 @@ -4168,6 +4189,9 @@ def add_args(parser, subparsers) -> None: group.add_argument('-dt', '--downloadable-templates', action='store_true', required=False, default=False, help='Combine all repos templates into a single list of resources.') + group.add_argument('-gd', '--gems-data', action='store_true', required=False, + default=False, + help='Returns a json formatted string of meta data for all local and engine gems.') register_show_subparser.add_argument('-v', '--verbose', action='count', required=False, default=0, From 1c2b8f91118f744314dc4f34ed33fc66245eea7c Mon Sep 17 00:00:00 2001 From: igarri Date: Tue, 18 May 2021 13:33:21 +0100 Subject: [PATCH 060/811] Adding AZ_CVAR for the new feature --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 10 +++- .../AssetBrowser/Search/Filter.cpp | 5 -- .../AssetBrowser/Search/Filter.h | 1 - .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 51 ++++++++++++------- 4 files changed, 43 insertions(+), 24 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 9ee00a96ae..5b820c4d06 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -12,6 +12,7 @@ #include #include #include +#include AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") #include @@ -22,6 +23,10 @@ AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") #include AZ_POP_DISABLE_WARNING +AZ_CVAR( + bool, ed_useNewAssetBrowserTableView, false, nullptr, AZ::ConsoleFunctorFlags::Null, + "Use the new AssetBrowser TableView for searching assets."); + namespace AzToolsFramework { namespace AssetBrowser @@ -32,7 +37,10 @@ namespace AzToolsFramework : QSortFilterProxyModel(parent) { m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); - m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); + if (ed_useNewAssetBrowserTableView) + { + m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); + } m_collator.setNumericMode(true); AssetBrowserComponentNotificationBus::Handler::BusConnect(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp index 86315613ad..ceda5f8e19 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp @@ -233,11 +233,6 @@ namespace AzToolsFramework Q_EMIT updatedSignal(); } - bool StringFilter::IsEmpty() const - { - return m_filterString.isEmpty(); - } - QString StringFilter::GetNameInternal() const { return m_filterString; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h index 6d19fb3b47..135dd00925 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h @@ -110,7 +110,6 @@ namespace AzToolsFramework ~StringFilter() override = default; void SetFilterString(const QString& filterString); - bool IsEmpty() const; protected: QString GetNameInternal() const override; bool MatchInternal(const AssetBrowserEntry* entry) const override; diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 8c01f6841c..c4a79a9394 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -20,6 +20,7 @@ #include #include #include +#include // AzQtComponents #include @@ -32,6 +33,9 @@ AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING +AZ_CVAR( + bool, ed_useNewAssetBrowserTableView, false, nullptr, AZ::ConsoleFunctorFlags::Null, + "Use the new AssetBrowser TableView for searching assets."); class ListenerForShowAssetEditorEvent : public QObject @@ -78,15 +82,40 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_filterModel->setSourceModel(m_assetBrowserModel); m_filterModel->SetFilter(m_ui->m_searchWidget->GetFilter()); - m_tableModel->setFilterRole(Qt::DisplayRole); - m_tableModel->setSourceModel(m_filterModel.data()); + m_ui->m_viewSwitcherCheckBox->setVisible(false); + m_ui->m_assetBrowserTableViewWidget->setVisible(false); + if (ed_useNewAssetBrowserTableView) + { + m_ui->m_viewSwitcherCheckBox->setVisible(true); + m_tableModel->setFilterRole(Qt::DisplayRole); + m_tableModel->setSourceModel(m_filterModel.data()); + m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); + connect( + m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, m_tableModel.data(), + &AssetBrowserTableModel::UpdateTableModelMaps); + connect( + m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::selectionChangedSignal, this, + &AzAssetBrowserWindow::SelectionChangedSlot); + connect( + m_ui->m_assetBrowserTableViewWidget, &QAbstractItemView::doubleClicked, this, + &AzAssetBrowserWindow::DoubleClickedItemTableModel); + connect( + m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::ClearStringFilter, m_ui->m_searchWidget, + &SearchWidget::ClearStringFilter); + connect( + m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::ClearTypeFilter, m_ui->m_searchWidget, + &SearchWidget::ClearTypeFilter); + + m_ui->m_assetBrowserTableViewWidget->SetName("AssetBrowserTableView_main"); + + connect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); + connect(m_ui->m_viewSwitcherCheckBox, &QCheckBox::stateChanged, this, &AzAssetBrowserWindow::LockToDefaultView); + + } m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); //m_ui->m_assetBrowserTreeViewWidget->hideColumn(static_cast(AssetBrowserEntry::Column::Path)); - m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); - m_ui->m_assetBrowserTableViewWidget->setVisible(false); - connect(m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), &AssetBrowserFilterModel::filterUpdatedSlot); connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, this, [this]() @@ -96,30 +125,18 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->m_assetBrowserTreeViewWidget->UpdateAfterFilter(hasFilter, selectFirstFilteredIndex); }); - connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, m_tableModel.data(), &AssetBrowserTableModel::UpdateTableModelMaps); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); - connect(m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::selectionChangedSignal, - this, &AzAssetBrowserWindow::SelectionChangedSlot); - connect(m_ui->m_assetBrowserTreeViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); - connect(m_ui->m_assetBrowserTableViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItemTableModel); - connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, &SearchWidget::ClearStringFilter); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, &SearchWidget::ClearTypeFilter); - connect(m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::ClearStringFilter, m_ui->m_searchWidget, &SearchWidget::ClearStringFilter); - connect(m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::ClearTypeFilter, m_ui->m_searchWidget, &SearchWidget::ClearTypeFilter); m_ui->m_assetBrowserTreeViewWidget->SetName("AssetBrowserTreeView_main"); - m_ui->m_assetBrowserTableViewWidget->SetName("AssetBrowserTableView_main"); - - connect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); - connect(m_ui->m_viewSwitcherCheckBox, &QCheckBox::stateChanged, this, &AzAssetBrowserWindow::LockToDefaultView); } AzAssetBrowserWindow::~AzAssetBrowserWindow() From f49e4b33337b47b6939f1df90c99696fd0e5efd5 Mon Sep 17 00:00:00 2001 From: igarri Date: Tue, 18 May 2021 15:26:05 +0100 Subject: [PATCH 061/811] modified code from feedback --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 33 +++++++++++-------- .../AssetBrowser/AssetBrowserModel.cpp | 10 +++--- .../AssetBrowser/AssetBrowserModel.h | 2 -- .../Views/AssetBrowserTreeView.cpp | 1 + .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 5 ++- 5 files changed, 26 insertions(+), 25 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 5b820c4d06..77e5523ee3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -23,9 +23,7 @@ AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") #include AZ_POP_DISABLE_WARNING -AZ_CVAR( - bool, ed_useNewAssetBrowserTableView, false, nullptr, AZ::ConsoleFunctorFlags::Null, - "Use the new AssetBrowser TableView for searching assets."); +AZ_CVAR_EXTERNED(bool, ed_useNewAssetBrowserTableView); namespace AzToolsFramework { @@ -36,10 +34,10 @@ namespace AzToolsFramework AssetBrowserFilterModel::AssetBrowserFilterModel(QObject* parent) : QSortFilterProxyModel(parent) { - m_showColumn.insert(static_cast(AssetBrowserEntry::Column::DisplayName)); + m_showColumn.insert(aznumeric_cast(AssetBrowserEntry::Column::DisplayName)); if (ed_useNewAssetBrowserTableView) { - m_showColumn.insert(static_cast(AssetBrowserEntry::Column::Path)); + m_showColumn.insert(aznumeric_cast(AssetBrowserEntry::Column::Path)); } m_collator.setNumericMode(true); AssetBrowserComponentNotificationBus::Handler::BusConnect(); @@ -149,19 +147,23 @@ namespace AzToolsFramework m_assetTypeFilter = qobject_cast >(*it); } - it = AZStd::find_if(subFilters.begin(), subFilters.end(), [](FilterConstType filter) -> bool + auto compStringFilterIter = AZStd::find_if(subFilters.begin(), subFilters.end(), [](FilterConstType filter) -> bool { + //The real StringFilter is really a CompositeFilter with just one StringFilter in its subfilter list + //To know if it is actually a StringFilter we have to get that subfilter and check if it is a Stringfilter. auto stringCompositeFilter = qobject_cast >(filter); bool isStringFilter = false; if (stringCompositeFilter) { - auto& subFilters = stringCompositeFilter->GetSubFilters(); - auto it = AZStd::find_if(subFilters.begin(), subFilters.end(), [](FilterConstType filt) -> bool - { + const auto& stringSubfilters = stringCompositeFilter->GetSubFilters(); + auto canBeCasted = [](FilterConstType filt) -> bool { auto strFilter = qobject_cast>(filt); return !strFilter.isNull(); - }); - if (it != subFilters.end()) + }; + auto stringSubfliterConstIter = AZStd::find_if(stringSubfilters.begin(), stringSubfilters.end(), canBeCasted); + + //A Composite StringFilter will only have just one subfilter and nothing more. + if (stringSubfliterConstIter != stringSubfilters.end() && stringSubfilters.size() == 1) { isStringFilter = true; } @@ -169,10 +171,13 @@ namespace AzToolsFramework return isStringFilter; }); - if (it != subFilters.end()) + if (compStringFilterIter != subFilters.end()) { - auto compStringFilter = qobject_cast>(*it); - m_stringFilter = qobject_cast>(compStringFilter->GetSubFilters()[0]); + auto compStringFilter = qobject_cast>(*compStringFilterIter); + if (compStringFilter->GetSubFilters().size() > 0 && compStringFilter->GetSubFilters()[0]) + { + m_stringFilter = qobject_cast>(compStringFilter->GetSubFilters()[0]); + } } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp index 1101e11f3a..a5cfad09ba 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp @@ -27,8 +27,6 @@ namespace AzToolsFramework { namespace AssetBrowser { - const int AssetBrowserModel::m_column = static_cast(AssetBrowserEntry::Column::DisplayName); - AssetBrowserModel::AssetBrowserModel(QObject* parent) : QAbstractItemModel(parent) , m_rootEntry(nullptr) @@ -143,9 +141,9 @@ namespace AzToolsFramework if (parent.isValid()) { - if ((parent.column() != static_cast(AssetBrowserEntry::Column::DisplayName)) && - (parent.column() != static_cast(AssetBrowserEntry::Column::Name)) && - (parent.column() != static_cast(AssetBrowserEntry::Column::Path))) + if ((parent.column() != aznumeric_cast(AssetBrowserEntry::Column::DisplayName)) && + (parent.column() != aznumeric_cast(AssetBrowserEntry::Column::Name)) && + (parent.column() != aznumeric_cast(AssetBrowserEntry::Column::Path))) { return 0; } @@ -394,7 +392,7 @@ namespace AzToolsFramework } int row = entry->row(); - index = createIndex(row, m_column, entry); + index = createIndex(row, aznumeric_cast(AssetBrowserEntry::Column::DisplayName), entry); return true; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.h index 9e60c44dae..3c4cae5588 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.h @@ -91,8 +91,6 @@ namespace AzToolsFramework static void SourceIndexesToAssetIds(const QModelIndexList& indexes, AZStd::vector& assetIds); static void SourceIndexesToAssetDatabaseEntries(const QModelIndexList& indexes, AZStd::vector& entries); - const static int m_column; - private: AZStd::shared_ptr m_rootEntry; bool m_loaded; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp index e29607698d..660c04ccd4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp @@ -102,6 +102,7 @@ namespace AzToolsFramework QModelIndexList sourceIndexes; for (const auto& index : selectedIndexes()) { + //If we check for more than one column then the model will try to select the same entry several times. if (index.column() == 0) { sourceIndexes.push_back(m_assetBrowserSortFilterProxyModel->mapToSource(index)); diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index c4a79a9394..412dc61465 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -114,7 +114,6 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) } m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); - //m_ui->m_assetBrowserTreeViewWidget->hideColumn(static_cast(AssetBrowserEntry::Column::Path)); connect(m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), &AssetBrowserFilterModel::filterUpdatedSlot); @@ -232,7 +231,7 @@ void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& using namespace AzToolsFramework; using namespace AzToolsFramework::AssetBrowser; // assumption: Double clicking an item selects it before telling us we double clicked it. - auto selectedAssets = m_ui->m_assetBrowserTreeViewWidget->GetSelectedAssets(); + const auto& selectedAssets = m_ui->m_assetBrowserTreeViewWidget->GetSelectedAssets(); for (const AssetBrowserEntry* entry : selectedAssets) { AZ::Data::AssetId assetIdToOpen; @@ -269,7 +268,7 @@ void AzAssetBrowserWindow::DoubleClickedItemTableModel([[maybe_unused]] const QM using namespace AzToolsFramework; using namespace AzToolsFramework::AssetBrowser; // assumption: Double clicking an item selects it before telling us we double clicked it. - auto selectedAssets = m_ui->m_assetBrowserTableViewWidget->GetSelectedAssets(); + const auto& selectedAssets = m_ui->m_assetBrowserTableViewWidget->GetSelectedAssets(); for (const AssetBrowserEntry* entry : selectedAssets) { AZ::Data::AssetId assetIdToOpen; From ec784b005ffdd39288097ed17f44612cf00b32a4 Mon Sep 17 00:00:00 2001 From: igarri Date: Tue, 18 May 2021 15:49:35 +0100 Subject: [PATCH 062/811] More Corrections --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 2 +- .../AssetBrowser/AssetBrowserTableModel.cpp | 44 ++++++++++--------- .../AssetBrowser/AssetBrowserTableModel.h | 13 +++++- .../Views/AssetBrowserTableView.cpp | 28 +++++++----- .../Views/AssetBrowserTableView.h | 11 +++++ 5 files changed, 64 insertions(+), 34 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 77e5523ee3..12b0256c5d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -174,7 +174,7 @@ namespace AzToolsFramework if (compStringFilterIter != subFilters.end()) { auto compStringFilter = qobject_cast>(*compStringFilterIter); - if (compStringFilter->GetSubFilters().size() > 0 && compStringFilter->GetSubFilters()[0]) + if (!compStringFilter->GetSubFilters().isEmpty() && compStringFilter->GetSubFilters()[0]) { m_stringFilter = qobject_cast>(compStringFilter->GetSubFilters()[0]); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index bebdf44c9a..b9bfe1bea6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -1,3 +1,14 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include #include #include @@ -32,24 +43,27 @@ namespace AzToolsFramework { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { - switch (section) + auto columnRole = aznumeric_cast(role); + switch (columnRole) { - case static_cast(AssetBrowserEntry::Column::Name): + case AssetBrowserEntry::Column::Name: return QString("Name"); - case static_cast(AssetBrowserEntry::Column::Path): + case AssetBrowserEntry::Column::Path: return QString("Path"); default: return QString::number(section); } } - return QSortFilterProxyModel::headerData(section, orientation, role); // QVariant(); + return QSortFilterProxyModel::headerData(section, orientation, role); } QVariant AssetBrowserTableModel::data(const QModelIndex& index, int role) const { auto sourceIndex = mapToSource(index); if (!sourceIndex.isValid()) + { return QVariant(); + } AssetBrowserEntry* entry = GetAssetEntry(sourceIndex); if (entry == nullptr) @@ -66,22 +80,10 @@ namespace AzToolsFramework return parent.isValid() ? QModelIndex() : createIndex(row, column, m_indexMap[row].internalPointer()); } - QModelIndex AssetBrowserTableModel::parent(const QModelIndex& child) const + QModelIndex AssetBrowserTableModel::parent([[maybe_unused]] const QModelIndex& child) const { - AZ_UNUSED(child); return QModelIndex(); } - bool AssetBrowserTableModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const - { - AZ_UNUSED(source_row); - AZ_UNUSED(source_parent); - // no filter present, every entry is not visible - if (!m_filterModel->GetFilter()) - { - return true; - } - return true; - } int AssetBrowserTableModel::rowCount(const QModelIndex& parent) const { @@ -94,14 +96,14 @@ namespace AzToolsFramework for (int i = 0; i < rows; ++i) { QModelIndex index = model->index(i, 0, parent); - if (model->hasChildren(index) == false) + if (!model->hasChildren(index)) { beginInsertRows(parent, row, row); m_indexMap[row] = index; endInsertRows(); Q_EMIT dataChanged(index, index); - row = row + 1; + ++row; } if (model->hasChildren(index)) @@ -124,9 +126,9 @@ namespace AzToolsFramework } } void AssetBrowserTableModel::UpdateTableModelMaps() -{ + { emit layoutAboutToBeChanged(); - if (m_indexMap.size() > 0) + if (!m_indexMap.isEmpty()) { beginRemoveRows(m_indexMap.first(), m_indexMap.first().row(), m_indexMap.last().row()); m_indexMap.clear(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index 432300194b..b0497213a0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -1,4 +1,16 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once + #if !defined(Q_MOC_RUN) #include #include @@ -30,7 +42,6 @@ namespace AzToolsFramework public Q_SLOTS: void UpdateTableModelMaps(); protected: - bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; int rowCount(const QModelIndex& parent = QModelIndex()) const override; QVariant headerData(int section, Qt::Orientation orientation, int role /* = Qt::DisplayRole */) const override; //////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index cb4a989043..df3b0b8644 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -1,3 +1,15 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + #include #include @@ -109,21 +121,16 @@ namespace AzToolsFramework } QTableView::rowsAboutToBeRemoved(parent, start, end); } - void AssetBrowserTableView::layoutChangedSlot(const QList& parents, QAbstractItemModel::LayoutChangeHint hint) + void AssetBrowserTableView::layoutChangedSlot([[maybe_unused]] const QList& parents,[[maybe_unused]] QAbstractItemModel::LayoutChangeHint hint) { - AZ_UNUSED(parents); - AZ_UNUSED(hint); - scrollToTop(); } - void AssetBrowserTableView::SelectProduct(AZ::Data::AssetId assetID) + void AssetBrowserTableView::SelectProduct([[maybe_unused]] AZ::Data::AssetId assetID) { - AZ_UNUSED(assetID); } - void AssetBrowserTableView::SelectFileAtPath(const AZStd::string& assetPath) + void AssetBrowserTableView::SelectFileAtPath([[maybe_unused]] const AZStd::string& assetPath) { - AZ_UNUSED(assetPath); } void AssetBrowserTableView::ClearFilter() @@ -142,11 +149,10 @@ namespace AzToolsFramework { } - void AssetBrowserTableView::OnContextMenu(const QPoint& point) + void AssetBrowserTableView::OnContextMenu([[maybe_unused]] const QPoint& point) { - AZ_UNUSED(point); - auto selectedAssets = GetSelectedAssets(); + const auto& selectedAssets = GetSelectedAssets(); if (selectedAssets.size() != 1) { return; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h index b39d48c391..482a072373 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -1,3 +1,14 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once #if !defined(Q_MOC_RUN) #include From 680a8e6fbd80466015161cf7d24aba4c56f83773 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 18 May 2021 21:43:13 -0500 Subject: [PATCH 063/811] Moving the o3de UnitTest files to script/o3de/test folder to help with file organization --- scripts/o3de/{ => test}/unit_test_add_remove_gem.py | 0 scripts/o3de/{ => test}/unit_test_current_project.py | 0 scripts/o3de/{ => test}/unit_test_engine_template.py | 0 scripts/o3de/{ => test}/unit_test_utils.py | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename scripts/o3de/{ => test}/unit_test_add_remove_gem.py (100%) rename scripts/o3de/{ => test}/unit_test_current_project.py (100%) rename scripts/o3de/{ => test}/unit_test_engine_template.py (100%) rename scripts/o3de/{ => test}/unit_test_utils.py (100%) diff --git a/scripts/o3de/unit_test_add_remove_gem.py b/scripts/o3de/test/unit_test_add_remove_gem.py similarity index 100% rename from scripts/o3de/unit_test_add_remove_gem.py rename to scripts/o3de/test/unit_test_add_remove_gem.py diff --git a/scripts/o3de/unit_test_current_project.py b/scripts/o3de/test/unit_test_current_project.py similarity index 100% rename from scripts/o3de/unit_test_current_project.py rename to scripts/o3de/test/unit_test_current_project.py diff --git a/scripts/o3de/unit_test_engine_template.py b/scripts/o3de/test/unit_test_engine_template.py similarity index 100% rename from scripts/o3de/unit_test_engine_template.py rename to scripts/o3de/test/unit_test_engine_template.py diff --git a/scripts/o3de/unit_test_utils.py b/scripts/o3de/test/unit_test_utils.py similarity index 100% rename from scripts/o3de/unit_test_utils.py rename to scripts/o3de/test/unit_test_utils.py From f34661491774ed36587047bbd91ebd46da8ed32b Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 18 May 2021 21:47:03 -0500 Subject: [PATCH 064/811] Adding __init__.py scripts to allow the name of o3de to be structured as a package --- scripts/o3de/__init__.py | 10 ++++++++++ scripts/o3de/test/__init__.py | 10 ++++++++++ 2 files changed, 20 insertions(+) create mode 100644 scripts/o3de/__init__.py create mode 100644 scripts/o3de/test/__init__.py diff --git a/scripts/o3de/__init__.py b/scripts/o3de/__init__.py new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/scripts/o3de/__init__.py @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/scripts/o3de/test/__init__.py b/scripts/o3de/test/__init__.py new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/scripts/o3de/test/__init__.py @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# From 548219d1174a9598d554844e4aff5f8b52bdbbb9 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 18 May 2021 22:19:09 -0500 Subject: [PATCH 065/811] Updated the registration.py script register_engine_path function to add a key, value mapping of engine name to engine path in the o3de_manifest.json file Added a pytest to validate the new engine_name -> engine_path functionality and registered those test with CTest. Fixed miscellaneous issues in the registration.py around incorrect return values for get_*_data functions where some of the returns values were integers where the return value should have been None --- scripts/CMakeLists.txt | 1 + scripts/o3de/CMakeLists.txt | 12 ++ scripts/o3de/registration.py | 172 +++++++++++++------- scripts/o3de/test/CMakeLists.txt | 22 +++ scripts/o3de/test/unit_test_registration.py | 66 ++++++++ 5 files changed, 212 insertions(+), 61 deletions(-) create mode 100644 scripts/o3de/CMakeLists.txt create mode 100644 scripts/o3de/test/CMakeLists.txt create mode 100644 scripts/o3de/test/unit_test_registration.py diff --git a/scripts/CMakeLists.txt b/scripts/CMakeLists.txt index d2843a9013..d3c9640665 100644 --- a/scripts/CMakeLists.txt +++ b/scripts/CMakeLists.txt @@ -11,5 +11,6 @@ add_subdirectory(detect_file_changes) add_subdirectory(commit_validation) +add_subdirectory(o3de) add_subdirectory(project_manager) add_subdirectory(ctest) diff --git a/scripts/o3de/CMakeLists.txt b/scripts/o3de/CMakeLists.txt new file mode 100644 index 0000000000..0744845784 --- /dev/null +++ b/scripts/o3de/CMakeLists.txt @@ -0,0 +1,12 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +add_subdirectory(test) diff --git a/scripts/o3de/registration.py b/scripts/o3de/registration.py index 184d2cdb31..eb7224c8ea 100755 --- a/scripts/o3de/registration.py +++ b/scripts/o3de/registration.py @@ -128,7 +128,7 @@ def get_o3de_logs_folder() -> pathlib.Path: return restricted_folder -def register_shipped_engine_o3de_objects() -> int: +def register_shipped_engine_o3de_objects(force: bool = False) -> int: engine_path = get_this_engine_path() ret_val = 0 @@ -137,7 +137,7 @@ def register_shipped_engine_o3de_objects() -> int: starting_engines_directories = [ ] for engines_directory in sorted(starting_engines_directories, reverse=True): - error_code = register_all_engines_in_folder(engines_path=engines_directory) + error_code = register_all_engines_in_folder(engines_path=engines_directory, force=force) if error_code: ret_val = error_code @@ -145,7 +145,7 @@ def register_shipped_engine_o3de_objects() -> int: starting_engines = [ ] for engine_path in sorted(starting_engines): - error_code = register(engine_path=engine_path) + error_code = register(engine_path=engine_path, force=force) if error_code: ret_val = error_code @@ -162,7 +162,7 @@ def register_shipped_engine_o3de_objects() -> int: f'{engine_path}/AutomatedTesting' ] for project_path in sorted(starting_projects, reverse=True): - error_code = register(engine_path=engine_path, project_path=project_path) + error_code = register(engine_path=engine_path, project_path=project_path, force=force) if error_code: ret_val = error_code @@ -179,7 +179,7 @@ def register_shipped_engine_o3de_objects() -> int: starting_gems = [ ] for gem_path in sorted(starting_gems, reverse=True): - error_code = register(engine_path=engine_path, gem_path=gem_path) + error_code = register(engine_path=engine_path, gem_path=gem_path, force=force) if error_code: ret_val = error_code @@ -196,7 +196,7 @@ def register_shipped_engine_o3de_objects() -> int: starting_templates = [ ] for template_path in sorted(starting_templates, reverse=True): - error_code = register(engine_path=engine_path, template_path=template_path) + error_code = register(engine_path=engine_path, template_path=template_path, force=force) if error_code: ret_val = error_code @@ -212,7 +212,7 @@ def register_shipped_engine_o3de_objects() -> int: starting_restricted = [ ] for restricted_path in sorted(starting_restricted, reverse=True): - error_code = register(engine_path=engine_path, restricted_path=restricted_path) + error_code = register(engine_path=engine_path, restricted_path=restricted_path, force=force) if error_code: ret_val = error_code @@ -228,12 +228,12 @@ def register_shipped_engine_o3de_objects() -> int: starting_repos = [ ] for repo_uri in sorted(starting_repos, reverse=True): - error_code = register(repo_uri=repo_uri) + error_code = register(repo_uri=repo_uri, force=force) if error_code: ret_val = error_code # register anything in the users default folders globally - error_code = register_all_engines_in_folder(get_registered(default_folder='engines')) + error_code = register_all_engines_in_folder(get_registered(default_folder='engines'), force=force) if error_code: ret_val = error_code error_code = register_all_projects_in_folder(get_registered(default_folder='projects')) @@ -266,7 +266,7 @@ def register_shipped_engine_o3de_objects() -> int: gem_path = pathlib.Path(gem_path).resolve() gem_cmake_lists_txt = gem_path / 'CMakeLists.txt' if gem_cmake_lists_txt.is_file(): - add_gem_to_cmake(engine_path=engine_path, gem_path=gem_path, supress_errors=True) # don't care about errors + add_gem_to_cmake(engine_path=engine_path, gem_path=gem_path, suppress_errors=True) # don't care about errors return ret_val @@ -344,7 +344,8 @@ def register_all_in_folder(folder_path: str or pathlib.Path, def register_all_engines_in_folder(engines_path: str or pathlib.Path, - remove: bool = False) -> int: + remove: bool = False, + force: bool = False) -> int: if not engines_path: logger.error(f'Engines path cannot be empty.') return 1 @@ -360,10 +361,10 @@ def register_all_engines_in_folder(engines_path: str or pathlib.Path, for root, dirs, files in os.walk(engines_path): for name in files: if name == 'engine.json': - engines_set.add(name) + engines_set.add(root) for engine in sorted(engines_set, reverse=True): - error_code = register(engine_path=engine, remove=remove) + error_code = register(engine_path=engine, remove=remove, force=force) if error_code: ret_val = error_code @@ -602,21 +603,65 @@ def save_o3de_manifest(json_data: dict) -> None: logger.error(f'Manifest json failed to save: {str(e)}') +def remove_engine_name_to_path(json_data: dict, + engine_path: pathlib.Path) -> int: + """ + Remove the engine at the specified path if it exist in the o3de manifest + :param json_data in-memory json view of the o3de_manifest.json data + :param engine_path path to engine to remove from the manifest data + + returns 0 to indicate no issues has occurred with removal + """ + if engine_path.is_dir() and valid_o3de_engine_json(engine_path): + engine_json_data = get_engine_data(engine_path=engine_path) + if 'engine_name' in engine_json_data and 'engines_path' in json_data: + engine_name = engine_json_data['engine_name'] + try: + del json_data['engines_path'][engine_name] + except KeyError: + # Attempting to remove a non-existent engine_name is fine + pass + return 0 + + +def add_engine_name_to_path(json_data: dict, engine_path: pathlib.Path, force: bool): + # Add an engine path JSON object which maps the "engine_name" -> "engine_path" + engine_json_data = get_engine_data(engine_path=engine_path) + if not engine_json_data: + logger.error(f'Unable to retrieve json data from engine.json at path {engine_path.as_posix()}') + return 1 + engines_path_json = json_data.setdefault('engines_path', {}) + if 'engine_name' not in engine_json_data: + logger.error(f'engine.json at path {engine_path.as_posix()} is missing "engine_name" key') + return 1 + + engine_name = engine_json_data['engine_name'] + if not force and engine_name in engines_path_json and \ + pathlib.PurePath(engines_path_json[engine_name]) != engine_path: + logger.error( + f'Attempting to register existing engine "{engine_name}" with a new path of {engine_path.as_posix()}.' + f' The current path is {pathlib.Path(engines_path_json[engine_name]).as_posix()}.' + f' To force registration of a new engine path, specify the -f/--force option.') + return 1 + engines_path_json[engine_name] = engine_path.as_posix() + return 0 + def register_engine_path(json_data: dict, engine_path: str or pathlib.Path, - remove: bool = False) -> int: + remove: bool = False, + force: bool = False) -> int: if not engine_path: logger.error(f'Engine path cannot be empty.') return 1 engine_path = pathlib.Path(engine_path).resolve() - for engine_object in json_data['engines']: + for engine_object in json_data.get('engines', {}): engine_object_path = pathlib.Path(engine_object['path']).resolve() if engine_object_path == engine_path: json_data['engines'].remove(engine_object) if remove: - return 0 + return remove_engine_name_to_path(json_data, engine_path) if not engine_path.is_dir(): logger.error(f'Engine path {engine_path} does not exist.') @@ -635,9 +680,9 @@ def register_engine_path(json_data: dict, engine_object.update({'restricted': []}) engine_object.update({'external_subdirectories': []}) - json_data['engines'].insert(0, engine_object) + json_data.setdefault('engines', []).insert(0, engine_object) - return 0 + return add_engine_name_to_path(json_data, engine_path, force) def register_gem_path(json_data: dict, @@ -1234,7 +1279,8 @@ def register(engine_path: str or pathlib.Path = None, default_gems_folder: str or pathlib.Path = None, default_templates_folder: str or pathlib.Path = None, default_restricted_folder: str or pathlib.Path = None, - remove: bool = False + remove: bool = False, + force: bool = False ) -> int: """ Adds/Updates entries to the .o3de/o3de_manifest.json @@ -1251,6 +1297,7 @@ def register(engine_path: str or pathlib.Path = None, :param default_templates_folder: default templates folder :param default_restricted_folder: default restricted code folder :param remove: add/remove the entries + :param force: force update of the engine_path for specified "engine_name" from the engine.json file :return: 0 for success or non 0 failure code """ @@ -1312,7 +1359,7 @@ def register(engine_path: str or pathlib.Path = None, if not engine_path: logger.error(f'Engine path cannot be empty.') return 1 - result = register_engine_path(json_data, engine_path, remove) + result = register_engine_path(json_data, engine_path, remove, force) if not result: save_o3de_manifest(json_data) @@ -2122,23 +2169,23 @@ def get_engine_data(engine_name: str = None, engine_path: str or pathlib.Path = None, ) -> dict or None: if not engine_name and not engine_path: logger.error('Must specify either a Engine name or Engine Path.') - return 1 + return None if engine_name and not engine_path: engine_path = get_registered(engine_name=engine_name) if not engine_path: logger.error(f'Engine Path {engine_path} has not been registered.') - return 1 + return None engine_path = pathlib.Path(engine_path).resolve() engine_json = engine_path / 'engine.json' if not engine_json.is_file(): logger.error(f'Engine json {engine_json} is not present.') - return 1 + return None if not valid_o3de_engine_json(engine_json): logger.error(f'Engine json {engine_json} is not valid.') - return 1 + return None with engine_json.open('r') as f: try: @@ -2155,23 +2202,23 @@ def get_project_data(project_name: str = None, project_path: str or pathlib.Path = None, ) -> dict or None: if not project_name and not project_path: logger.error('Must specify either a Project name or Project Path.') - return 1 + return None if project_name and not project_path: project_path = get_registered(project_name=project_name) if not project_path: logger.error(f'Project Path {project_path} has not been registered.') - return 1 + return None project_path = pathlib.Path(project_path).resolve() project_json = project_path / 'project.json' if not project_json.is_file(): logger.error(f'Project json {project_json} is not present.') - return 1 + return None if not valid_o3de_project_json(project_json): logger.error(f'Project json {project_json} is not valid.') - return 1 + return None with project_json.open('r') as f: try: @@ -2188,23 +2235,23 @@ def get_gem_data(gem_name: str = None, gem_path: str or pathlib.Path = None, ) -> dict or None: if not gem_name and not gem_path: logger.error('Must specify either a Gem name or Gem Path.') - return 1 + return None if gem_name and not gem_path: gem_path = get_registered(gem_name=gem_name) if not gem_path: logger.error(f'Gem Path {gem_path} has not been registered.') - return 1 + return None gem_path = pathlib.Path(gem_path).resolve() gem_json = gem_path / 'gem.json' if not gem_json.is_file(): logger.error(f'Gem json {gem_json} is not present.') - return 1 + return None if not valid_o3de_gem_json(gem_json): logger.error(f'Gem json {gem_json} is not valid.') - return 1 + return None with gem_json.open('r') as f: try: @@ -2221,23 +2268,23 @@ def get_template_data(template_name: str = None, template_path: str or pathlib.Path = None, ) -> dict or None: if not template_name and not template_path: logger.error('Must specify either a Template name or Template Path.') - return 1 + return None if template_name and not template_path: template_path = get_registered(template_name=template_name) if not template_path: logger.error(f'Template Path {template_path} has not been registered.') - return 1 + return None template_path = pathlib.Path(template_path).resolve() template_json = template_path / 'template.json' if not template_json.is_file(): logger.error(f'Template json {template_json} is not present.') - return 1 + return None if not valid_o3de_template_json(template_json): logger.error(f'Template json {template_json} is not valid.') - return 1 + return None with template_json.open('r') as f: try: @@ -2254,23 +2301,23 @@ def get_restricted_data(restricted_name: str = None, restricted_path: str or pathlib.Path = None, ) -> dict or None: if not restricted_name and not restricted_path: logger.error('Must specify either a Restricted name or Restricted Path.') - return 1 + return None if restricted_name and not restricted_path: restricted_path = get_registered(restricted_name=restricted_name) if not restricted_path: logger.error(f'Restricted Path {restricted_path} has not been registered.') - return 1 + return None restricted_path = pathlib.Path(restricted_path).resolve() restricted_json = restricted_path / 'restricted.json' if not restricted_json.is_file(): logger.error(f'Restricted json {restricted_json} is not present.') - return 1 + return None if not valid_o3de_restricted_json(restricted_json): logger.error(f'Restricted json {restricted_json} is not valid.') - return 1 + return None with restricted_json.open('r') as f: try: @@ -3259,30 +3306,30 @@ def get_gem_targets(gem_name: str = None, def add_external_subdirectory(external_subdir: str or pathlib.Path, engine_path: str or pathlib.Path = None, - supress_errors: bool = False) -> int: + suppress_errors: bool = False) -> int: """ add external subdirectory to a cmake :param external_subdir: external subdirectory to add to cmake :param engine_path: optional engine path, defaults to this engine - :param supress_errors: optional silence errors + :param suppress_errors: optional silence errors :return: 0 for success or non 0 failure code """ external_subdir = pathlib.Path(external_subdir).resolve() if not external_subdir.is_dir(): - if not supress_errors: + if not suppress_errors: logger.error(f'Add External Subdirectory Failed: {external_subdir} does not exist.') return 1 external_subdir_cmake = external_subdir / 'CMakeLists.txt' if not external_subdir_cmake.is_file(): - if not supress_errors: + if not suppress_errors: logger.error(f'Add External Subdirectory Failed: {external_subdir} does not contain a CMakeLists.txt.') return 1 json_data = load_o3de_manifest() engine_object = find_engine_data(json_data, engine_path) if not engine_object: - if not supress_errors: + if not suppress_errors: logger.error(f'Add External Subdirectory Failed: {engine_path} not registered.') return 1 @@ -3290,7 +3337,7 @@ def add_external_subdirectory(external_subdir: str or pathlib.Path, engine_object['external_subdirectories'].remove(external_subdir.as_posix()) def parse_cmake_file(cmake: str or pathlib.Path, - files: set()): + files: set): cmake_path = pathlib.Path(cmake).resolve() cmake_file = cmake_path if cmake_path.is_dir(): @@ -3335,7 +3382,7 @@ def add_external_subdirectory(external_subdir: str or pathlib.Path, if external_subdir in cmake_files: save_o3de_manifest(json_data) - if not supress_errors: + if not suppress_errors: logger.error(f'External subdirectory {external_subdir.as_posix()} already included by add_subdirectory().') return 1 @@ -3374,18 +3421,18 @@ def add_gem_to_cmake(gem_name: str = None, gem_path: str or pathlib.Path = None, engine_name: str = None, engine_path: str or pathlib.Path = None, - supress_errors: bool = False) -> int: + suppress_errors: bool = False) -> int: """ add a gem to a cmake as an external subdirectory for an engine :param gem_name: name of the gem to add to cmake :param gem_path: the path of the gem to add to cmake :param engine_name: name of the engine to add to cmake :param engine_path: the path of the engine to add external subdirectory to, default to this engine - :param supress_errors: optional silence errors + :param suppress_errors: optional silence errors :return: 0 for success or non 0 failure code """ if not gem_name and not gem_path: - if not supress_errors: + if not suppress_errors: logger.error('Must specify either a Gem name or Gem Path.') return 1 @@ -3393,18 +3440,18 @@ def add_gem_to_cmake(gem_name: str = None, gem_path = get_registered(gem_name=gem_name) if not gem_path: - if not supress_errors: + if not suppress_errors: logger.error(f'Gem Path {gem_path} has not been registered.') return 1 gem_path = pathlib.Path(gem_path).resolve() gem_json = gem_path / 'gem.json' if not gem_json.is_file(): - if not supress_errors: + if not suppress_errors: logger.error(f'Gem json {gem_json} is not present.') return 1 if not valid_o3de_gem_json(gem_json): - if not supress_errors: + if not suppress_errors: logger.error(f'Gem json {gem_json} is not valid.') return 1 @@ -3415,21 +3462,21 @@ def add_gem_to_cmake(gem_name: str = None, engine_path = get_registered(engine_name=engine_name) if not engine_path: - if not supress_errors: + if not suppress_errors: logger.error(f'Engine Path {engine_path} has not been registered.') return 1 engine_json = engine_path / 'engine.json' if not engine_json.is_file(): - if not supress_errors: + if not suppress_errors: logger.error(f'Engine json {engine_json} is not present.') return 1 if not valid_o3de_engine_json(engine_json): - if not supress_errors: + if not suppress_errors: logger.error(f'Engine json {engine_json} is not valid.') return 1 - return add_external_subdirectory(external_subdir=gem_path, engine_path=engine_path, supress_errors=supress_errors) + return add_external_subdirectory(external_subdir=gem_path, engine_path=engine_path, suppress_errors=suppress_errors) def remove_gem_from_cmake(gem_name: str = None, @@ -3930,13 +3977,13 @@ def _run_register(args: argparse) -> int: remove_invalid_o3de_objects() return refresh_repos() elif args.this_engine: - ret_val = register(engine_path=get_this_engine_path()) - error_code = register_shipped_engine_o3de_objects() + ret_val = register(engine_path=get_this_engine_path(), force=args.force) + error_code = register_shipped_engine_o3de_objects(force=args.force) if error_code: ret_val = error_code return ret_val elif args.all_engines_path: - return register_all_engines_in_folder(args.all_engines_path, args.remove) + return register_all_engines_in_folder(args.all_engines_path, args.remove, args.force) elif args.all_projects_path: return register_all_projects_in_folder(args.all_projects_path, args.remove) elif args.all_gems_path: @@ -3959,7 +4006,8 @@ def _run_register(args: argparse) -> int: default_gems_folder=args.default_gems_folder, default_templates_folder=args.default_templates_folder, default_restricted_folder=args.default_restricted_folder, - remove=args.remove) + remove=args.remove, + force=args.force) def _run_add_external_subdirectory(args: argparse) -> int: @@ -4096,6 +4144,8 @@ def add_args(parser, subparsers) -> None: register_subparser.add_argument('-r', '--remove', action='store_true', required=False, default=False, help='Remove entry.') + register_subparser.add_argument('-f', '--force', action='store_true', default=False, + help='For the update of the registration field being modified.') register_subparser.set_defaults(func=_run_register) # show diff --git a/scripts/o3de/test/CMakeLists.txt b/scripts/o3de/test/CMakeLists.txt new file mode 100644 index 0000000000..29410e3523 --- /dev/null +++ b/scripts/o3de/test/CMakeLists.txt @@ -0,0 +1,22 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +if(NOT PAL_TRAIT_BUILD_TESTS_SUPPORTED) + return() +endif() + +# Add a test to test out the o3de package `o3de.py register` command +ly_add_pytest( + NAME o3de_register + PATH ${CMAKE_CURRENT_LIST_DIR}/unit_test_registration.py + TEST_SUITE smoke + EXCLUDE_TEST_RUN_TARGET_FROM_IDE +) diff --git a/scripts/o3de/test/unit_test_registration.py b/scripts/o3de/test/unit_test_registration.py new file mode 100644 index 0000000000..31a2dcb2f0 --- /dev/null +++ b/scripts/o3de/test/unit_test_registration.py @@ -0,0 +1,66 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +import argparse +import json +import logging +import pytest +import pathlib +from unittest.mock import patch + +from .. import registration + +string_manifest_data = '{}' + +@pytest.mark.parametrize( + "engine_path, engine_name, force, expected_result", [ + pytest.param(pathlib.PurePath('D:/o3de/o3de'), "o3de", False, 0), + # Same engine_name and path should result in valid registration + pytest.param(pathlib.PurePath('D:/o3de/o3de'), "o3de", False, 0), + # Same engine_name and but different path should fail + pytest.param(pathlib.PurePath('D:/o3de/engine-path'), "o3de", False, 1), + # New engine_name should result in valid registration + pytest.param(pathlib.PurePath('D:/o3de/engine-path'), "o3de-other", False, 0), + # Same engine_name and but different path with --force should result in valid registration + pytest.param(pathlib.PurePath('F:/Open3DEngine'), "o3de", True, 0), + ] +) +def test_register_engine_path(engine_path, engine_name, force, expected_result): + parser = argparse.ArgumentParser() + subparser = parser.add_subparsers(help='sub-command help') + + # Register the registration script subparsers with the current argument parser + registration.add_args(parser, subparser) + arg_list = ['register', '--engine-path', str(engine_path)] + if force: + arg_list += ['--force'] + args = parser.parse_args(arg_list) + + def load_manifest_from_string() -> dict: + try: + manifest_json = json.loads(string_manifest_data) + except json.JSONDecodeError as err: + logging.error("Error decoding Json from Manifest file") + else: + return manifest_json + def save_manifest_to_string(manifest_json: dict) -> None: + global string_manifest_data + string_manifest_data = json.dumps(manifest_json) + + engine_json_data = {'engine_name': engine_name} + with patch('o3de.registration.load_o3de_manifest', side_effect=load_manifest_from_string) as load_manifest_mock, \ + patch('o3de.registration.save_o3de_manifest', side_effect=save_manifest_to_string) as save_manifest_mock, \ + patch('o3de.registration.get_engine_data', return_value=engine_json_data) as engine_paths_mock, \ + patch('o3de.registration.valid_o3de_engine_json', return_value=True) as valid_engine_mock, \ + patch('pathlib.Path.is_dir', return_value=True) as pathlib_is_dir_mock: + result = registration._run_register(args) + assert result == expected_result + From 5d42b64ff979d36e2617287ab39712b3d6116fba Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 18 May 2021 23:05:55 -0500 Subject: [PATCH 066/811] Moving the o3de test scripts to the tests subfolder of the package --- scripts/o3de/{test => tests}/CMakeLists.txt | 0 scripts/o3de/{test => tests}/__init__.py | 0 scripts/o3de/{test => tests}/unit_test_add_remove_gem.py | 0 scripts/o3de/{test => tests}/unit_test_current_project.py | 0 scripts/o3de/{test => tests}/unit_test_registration.py | 0 scripts/o3de/{test => tests}/unit_test_utils.py | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename scripts/o3de/{test => tests}/CMakeLists.txt (100%) rename scripts/o3de/{test => tests}/__init__.py (100%) rename scripts/o3de/{test => tests}/unit_test_add_remove_gem.py (100%) rename scripts/o3de/{test => tests}/unit_test_current_project.py (100%) rename scripts/o3de/{test => tests}/unit_test_registration.py (100%) rename scripts/o3de/{test => tests}/unit_test_utils.py (100%) diff --git a/scripts/o3de/test/CMakeLists.txt b/scripts/o3de/tests/CMakeLists.txt similarity index 100% rename from scripts/o3de/test/CMakeLists.txt rename to scripts/o3de/tests/CMakeLists.txt diff --git a/scripts/o3de/test/__init__.py b/scripts/o3de/tests/__init__.py similarity index 100% rename from scripts/o3de/test/__init__.py rename to scripts/o3de/tests/__init__.py diff --git a/scripts/o3de/test/unit_test_add_remove_gem.py b/scripts/o3de/tests/unit_test_add_remove_gem.py similarity index 100% rename from scripts/o3de/test/unit_test_add_remove_gem.py rename to scripts/o3de/tests/unit_test_add_remove_gem.py diff --git a/scripts/o3de/test/unit_test_current_project.py b/scripts/o3de/tests/unit_test_current_project.py similarity index 100% rename from scripts/o3de/test/unit_test_current_project.py rename to scripts/o3de/tests/unit_test_current_project.py diff --git a/scripts/o3de/test/unit_test_registration.py b/scripts/o3de/tests/unit_test_registration.py similarity index 100% rename from scripts/o3de/test/unit_test_registration.py rename to scripts/o3de/tests/unit_test_registration.py diff --git a/scripts/o3de/test/unit_test_utils.py b/scripts/o3de/tests/unit_test_utils.py similarity index 100% rename from scripts/o3de/test/unit_test_utils.py rename to scripts/o3de/tests/unit_test_utils.py From 6fc1257f7344b57199e3e1e1a69675e2d07ebd5f Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 18 May 2021 23:13:25 -0500 Subject: [PATCH 067/811] Moving the o3de python scripts to be underneath another o3de folder to allow `import o3de` to succeed. The path is now scripts/o3de/o3de --- scripts/o3de/{ => o3de}/__init__.py | 0 scripts/o3de/{ => o3de}/engine_template.py | 0 scripts/o3de/{ => o3de}/global_project.py | 0 scripts/o3de/{ => o3de}/registration.py | 0 scripts/o3de/{ => o3de}/utils.py | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename scripts/o3de/{ => o3de}/__init__.py (100%) rename scripts/o3de/{ => o3de}/engine_template.py (100%) rename scripts/o3de/{ => o3de}/global_project.py (100%) rename scripts/o3de/{ => o3de}/registration.py (100%) rename scripts/o3de/{ => o3de}/utils.py (100%) diff --git a/scripts/o3de/__init__.py b/scripts/o3de/o3de/__init__.py similarity index 100% rename from scripts/o3de/__init__.py rename to scripts/o3de/o3de/__init__.py diff --git a/scripts/o3de/engine_template.py b/scripts/o3de/o3de/engine_template.py similarity index 100% rename from scripts/o3de/engine_template.py rename to scripts/o3de/o3de/engine_template.py diff --git a/scripts/o3de/global_project.py b/scripts/o3de/o3de/global_project.py similarity index 100% rename from scripts/o3de/global_project.py rename to scripts/o3de/o3de/global_project.py diff --git a/scripts/o3de/registration.py b/scripts/o3de/o3de/registration.py similarity index 100% rename from scripts/o3de/registration.py rename to scripts/o3de/o3de/registration.py diff --git a/scripts/o3de/utils.py b/scripts/o3de/o3de/utils.py similarity index 100% rename from scripts/o3de/utils.py rename to scripts/o3de/o3de/utils.py From ec7f4c3fdcde2a46f90532494757a835c340455b Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 18 May 2021 23:15:50 -0500 Subject: [PATCH 068/811] Moving the engine template unit test files into the o3de/tests folder --- scripts/o3de/{test => tests}/unit_test_engine_template.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename scripts/o3de/{test => tests}/unit_test_engine_template.py (100%) diff --git a/scripts/o3de/test/unit_test_engine_template.py b/scripts/o3de/tests/unit_test_engine_template.py similarity index 100% rename from scripts/o3de/test/unit_test_engine_template.py rename to scripts/o3de/tests/unit_test_engine_template.py From 703c268e40107de3abac5bf8c4b2fe520f0cc0da Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 18 May 2021 23:48:35 -0500 Subject: [PATCH 069/811] Adding a setup.py and a README to the scripts/o3de folder so it can be linked as a package into the engine python runtime when python is installed via python/get_python.bat --- scripts/o3de/README.txt | 41 ++++++++++++++++++++++++++++++++++++++++ scripts/o3de/setup.py | 42 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 scripts/o3de/README.txt create mode 100644 scripts/o3de/setup.py diff --git a/scripts/o3de/README.txt b/scripts/o3de/README.txt new file mode 100644 index 0000000000..51bbf78cbd --- /dev/null +++ b/scripts/o3de/README.txt @@ -0,0 +1,41 @@ +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +INTRODUCTION +------------ + +o3de is a package of scripts containing functionality to register engine, projects, gems, +templates and download repositories with the o3de manifests +It also contains functionality for creating new projects, gems and templates as well +as querying existing gems and templates + + +REQUIREMENTS +------------ + + * Python 3.7.10 (64-bit) + +INSTALL +----------- +It is recommended to set up these these tools with O3DE's CMake build commands. +Assuming CMake is already setup on your operating system, below are some sample build commands: + cd /path/to/od3e/ + cmake -B windows_vs2019 -S . -G"Visual Studio 16" -DLY_3RDPARTY_PATH="%LY_3RDPARTY_PATH%" + +To manually install the project in development mode using your own installed Python interpreter: + cd /path/to/od3e/o3de + /path/to/your/python -m pip install -e . + + +UNINSTALLATION +-------------- + +The preferred way to uninstall the project is: + /path/to/your/python -m pip uninstall o3de diff --git a/scripts/o3de/setup.py b/scripts/o3de/setup.py new file mode 100644 index 0000000000..595f477c45 --- /dev/null +++ b/scripts/o3de/setup.py @@ -0,0 +1,42 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" +import os +import platform + +from setuptools import setup, find_packages +from setuptools.command.develop import develop +from setuptools.command.build_py import build_py + +PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__)) + +PYTHON_64 = platform.architecture()[0] == '64bit' + + +if __name__ == '__main__': + if not PYTHON_64: + raise RuntimeError("32-bit Python is not a supported platform.") + + with open(os.path.join(PACKAGE_ROOT, 'README.txt')) as f: + long_description = f.read() + + setup( + name="o3de", + version="1.0.0", + description='O3DE editor Python bindings test tools', + long_description=long_description, + packages=find_packages(where='o3de', exclude=['tests']), + install_requires=[ + ], + tests_require=[ + ], + entry_points={ + }, + ) From c6b0e3562e3f35b2bb0eb21c77e365453da0bdc7 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 19 May 2021 00:52:28 -0500 Subject: [PATCH 070/811] Updating the python import paths for the o3de scripts to use the new package o3de package location --- .../ProjectManager/Source/PythonBindings.cpp | 70 +++++++++---------- scripts/o3de.py | 23 +++--- scripts/o3de/CMakeLists.txt | 2 +- scripts/o3de/o3de/engine_template.py | 9 +-- scripts/o3de/o3de/global_project.py | 6 +- scripts/o3de/o3de/registration.py | 4 +- scripts/project_manager/projects.py | 5 +- 7 files changed, 63 insertions(+), 56 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index cc5348fd22..bc154ea059 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -53,7 +53,7 @@ namespace Platform #define Py_To_String(obj) obj.cast().c_str() #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string -namespace O3DE::ProjectManager +namespace O3DE::ProjectManager { PythonBindings::PythonBindings(const AZ::IO::PathView& enginePath) : m_enginePath(enginePath) @@ -112,7 +112,7 @@ namespace O3DE::ProjectManager AZ_Warning("ProjectManagerWindow", result != -1, "Append to sys path failed"); // import required modules - m_registration = pybind11::module::import("cmake.Tools.registration"); + m_registration = pybind11::module::import("o3de.registration"); return result == 0 && !PyErr_Occurred(); } catch ([[maybe_unused]] const std::exception& e) @@ -153,22 +153,22 @@ namespace O3DE::ProjectManager } } - AZ::Outcome PythonBindings::GetEngineInfo() + AZ::Outcome PythonBindings::GetEngineInfo() { return AZ::Failure(); } - bool PythonBindings::SetEngineInfo([[maybe_unused]] const EngineInfo& engineInfo) + bool PythonBindings::SetEngineInfo([[maybe_unused]] const EngineInfo& engineInfo) { return false; } - AZ::Outcome PythonBindings::GetGem(const QString& path) + AZ::Outcome PythonBindings::GetGem(const QString& path) { GemInfo gemInfo = GemInfoFromPath(pybind11::str(path.toStdString())); if (gemInfo.IsValid()) { - return AZ::Success(AZStd::move(gemInfo)); + return AZ::Success(AZStd::move(gemInfo)); } else { @@ -176,18 +176,18 @@ namespace O3DE::ProjectManager } } - AZ::Outcome> PythonBindings::GetGems() + AZ::Outcome> PythonBindings::GetGems() { QVector gems; bool result = ExecuteWithLock([&] { - // external gems + // external gems for (auto path : m_registration.attr("get_gems")()) { gems.push_back(GemInfoFromPath(path)); } - // gems from the engine + // gems from the engine for (auto path : m_registration.attr("get_engine_gems")()) { gems.push_back(GemInfoFromPath(path)); @@ -200,21 +200,21 @@ namespace O3DE::ProjectManager } else { - return AZ::Success(AZStd::move(gems)); + return AZ::Success(AZStd::move(gems)); } } - AZ::Outcome PythonBindings::CreateProject([[maybe_unused]] const ProjectTemplateInfo& projectTemplate,[[maybe_unused]] const ProjectInfo& projectInfo) + AZ::Outcome PythonBindings::CreateProject([[maybe_unused]] const ProjectTemplateInfo& projectTemplate,[[maybe_unused]] const ProjectInfo& projectInfo) { return AZ::Failure(); } - AZ::Outcome PythonBindings::GetProject(const QString& path) + AZ::Outcome PythonBindings::GetProject(const QString& path) { ProjectInfo projectInfo = ProjectInfoFromPath(pybind11::str(path.toStdString())); if (projectInfo.IsValid()) { - return AZ::Success(AZStd::move(projectInfo)); + return AZ::Success(AZStd::move(projectInfo)); } else { @@ -225,7 +225,7 @@ namespace O3DE::ProjectManager GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path) { GemInfo gemInfo; - gemInfo.m_path = Py_To_String(path); + gemInfo.m_path = Py_To_String(path); auto data = m_registration.attr("get_gem_data")(pybind11::none(), path); if (pybind11::isinstance(data)) @@ -233,13 +233,13 @@ namespace O3DE::ProjectManager try { // required - gemInfo.m_name = Py_To_String(data["Name"]); - gemInfo.m_uuid = AZ::Uuid(Py_To_String(data["Uuid"])); + gemInfo.m_name = Py_To_String(data["Name"]); + gemInfo.m_uuid = AZ::Uuid(Py_To_String(data["Uuid"])); // optional - gemInfo.m_displayName = Py_To_String_Optional(data, "DisplayName", gemInfo.m_name); - gemInfo.m_summary = Py_To_String_Optional(data, "Summary", ""); - gemInfo.m_version = Py_To_String_Optional(data, "Version", ""); + gemInfo.m_displayName = Py_To_String_Optional(data, "DisplayName", gemInfo.m_name); + gemInfo.m_summary = Py_To_String_Optional(data, "Summary", ""); + gemInfo.m_version = Py_To_String_Optional(data, "Version", ""); if (data.contains("Dependencies")) { @@ -268,7 +268,7 @@ namespace O3DE::ProjectManager ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path) { ProjectInfo projectInfo; - projectInfo.m_path = Py_To_String(path); + projectInfo.m_path = Py_To_String(path); auto projectData = m_registration.attr("get_project_data")(pybind11::none(), path); if (pybind11::isinstance(projectData)) @@ -276,9 +276,9 @@ namespace O3DE::ProjectManager try { // required fields - projectInfo.m_productName = Py_To_String(projectData["product_name"]); - projectInfo.m_projectName = Py_To_String(projectData["project_name"]); - projectInfo.m_projectId = AZ::Uuid(Py_To_String(projectData["project_id"])); + projectInfo.m_productName = Py_To_String(projectData["product_name"]); + projectInfo.m_projectName = Py_To_String(projectData["project_name"]); + projectInfo.m_projectId = AZ::Uuid(Py_To_String(projectData["project_id"])); } catch ([[maybe_unused]] const std::exception& e) { @@ -289,18 +289,18 @@ namespace O3DE::ProjectManager return projectInfo; } - AZ::Outcome> PythonBindings::GetProjects() + AZ::Outcome> PythonBindings::GetProjects() { QVector projects; bool result = ExecuteWithLock([&] { - // external projects + // external projects for (auto path : m_registration.attr("get_projects")()) { projects.push_back(ProjectInfoFromPath(path)); } - // projects from the engine + // projects from the engine for (auto path : m_registration.attr("get_engine_projects")()) { projects.push_back(ProjectInfoFromPath(path)); @@ -313,11 +313,11 @@ namespace O3DE::ProjectManager } else { - return AZ::Success(AZStd::move(projects)); + return AZ::Success(AZStd::move(projects)); } } - bool PythonBindings::UpdateProject([[maybe_unused]] const ProjectInfo& projectInfo) + bool PythonBindings::UpdateProject([[maybe_unused]] const ProjectInfo& projectInfo) { return false; } @@ -325,7 +325,7 @@ namespace O3DE::ProjectManager ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path) { ProjectTemplateInfo templateInfo; - templateInfo.m_path = Py_To_String(path); + templateInfo.m_path = Py_To_String(path); auto data = m_registration.attr("get_template_data")(pybind11::none(), path); if (pybind11::isinstance(data)) @@ -333,10 +333,10 @@ namespace O3DE::ProjectManager try { // required - templateInfo.m_displayName = Py_To_String(data["display_name"]); - templateInfo.m_name = Py_To_String(data["template_name"]); - templateInfo.m_summary = Py_To_String(data["summary"]); - + templateInfo.m_displayName = Py_To_String(data["display_name"]); + templateInfo.m_name = Py_To_String(data["template_name"]); + templateInfo.m_summary = Py_To_String(data["summary"]); + // optional if (data.contains("canonical_tags")) { @@ -362,7 +362,7 @@ namespace O3DE::ProjectManager return templateInfo; } - AZ::Outcome> PythonBindings::GetProjectTemplates() + AZ::Outcome> PythonBindings::GetProjectTemplates() { QVector templates; @@ -379,7 +379,7 @@ namespace O3DE::ProjectManager } else { - return AZ::Success(AZStd::move(templates)); + return AZ::Success(AZStd::move(templates)); } } } diff --git a/scripts/o3de.py b/scripts/o3de.py index dbb9c53e4b..7bc1c4a9fb 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -10,17 +10,24 @@ # import argparse +import pathlib import sys -import os -# Resolve the common python module -ROOT_DEV_PATH = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) -if ROOT_DEV_PATH not in sys.path: - sys.path.append(ROOT_DEV_PATH) +# As o3de.py shares the same name as the o3de package attempting to use a regular +# from o3de import line tries to import from the current o3de.py script and not the package +# So the current script directory is removed from the sys.path temporary +SCRIPT_DIR_REMOVED = False +SCRIPT_DIR = pathlib.Path(__file__).parent.resolve() +if str(SCRIPT_DIR) in sys.path: + SCRIPT_DIR_REMOVED = True + sys.path.remove(str(SCRIPT_DIR)) -from cmake.Tools import engine_template -from cmake.Tools import global_project -from cmake.Tools import registration +from o3de import engine_template +from o3de import global_project +from o3de import registration + +if SCRIPT_DIR_REMOVED: + sys.path.insert(0, str(SCRIPT_DIR)) def add_args(parser, subparsers) -> None: diff --git a/scripts/o3de/CMakeLists.txt b/scripts/o3de/CMakeLists.txt index 0744845784..9819c1cd6e 100644 --- a/scripts/o3de/CMakeLists.txt +++ b/scripts/o3de/CMakeLists.txt @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -add_subdirectory(test) +add_subdirectory(tests) diff --git a/scripts/o3de/o3de/engine_template.py b/scripts/o3de/o3de/engine_template.py index eefb8c5541..23acab33d4 100755 --- a/scripts/o3de/o3de/engine_template.py +++ b/scripts/o3de/o3de/engine_template.py @@ -20,8 +20,8 @@ import json import uuid import re -from cmake.Tools import utils -import cmake.Tools.registration as registration + +from o3de import utils, registration logger = logging.getLogger() logging.basicConfig() @@ -2423,7 +2423,7 @@ if __name__ == "__main__": the_parser = argparse.ArgumentParser() # add subparsers - the_subparsers = the_parser.add_subparsers(help='sub-command help') + the_subparsers = the_parser.add_subparsers(help='sub-command help', dest='command', required=True) # add args to the parser add_args(the_parser, the_subparsers) @@ -2432,7 +2432,8 @@ if __name__ == "__main__": the_args = the_parser.parse_args() # run - ret = the_args.func(the_args) + + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 # return sys.exit(ret) diff --git a/scripts/o3de/o3de/global_project.py b/scripts/o3de/o3de/global_project.py index 1d84d9dcfb..da1b5dfa80 100644 --- a/scripts/o3de/o3de/global_project.py +++ b/scripts/o3de/o3de/global_project.py @@ -16,7 +16,7 @@ import sys import re import pathlib import json -import cmake.Tools.registration as registration +from o3de import registration logger = logging.getLogger() logging.basicConfig() @@ -153,7 +153,7 @@ if __name__ == "__main__": the_parser = argparse.ArgumentParser() # add subparsers - the_subparsers = the_parser.add_subparsers(help='sub-command help') + the_subparsers = the_parser.add_subparsers(help='sub-command help', dest='command', required=True) # add args to the parser add_args(the_parser, the_subparsers) @@ -162,7 +162,7 @@ if __name__ == "__main__": the_args = the_parser.parse_args() # run - ret = the_args.func(the_args) + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 # return sys.exit(ret) diff --git a/scripts/o3de/o3de/registration.py b/scripts/o3de/o3de/registration.py index eb7224c8ea..a4afecd740 100755 --- a/scripts/o3de/o3de/registration.py +++ b/scripts/o3de/o3de/registration.py @@ -4416,7 +4416,7 @@ if __name__ == "__main__": the_parser = argparse.ArgumentParser() # add subparsers - the_subparsers = the_parser.add_subparsers(help='sub-command help') + the_subparsers = the_parser.add_subparsers(help='sub-command help', dest='command', required=True) # add args to the parser add_args(the_parser, the_subparsers) @@ -4425,7 +4425,7 @@ if __name__ == "__main__": the_args = the_parser.parse_args() # run - ret = the_args.func(the_args) + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 # return sys.exit(ret) diff --git a/scripts/project_manager/projects.py b/scripts/project_manager/projects.py index 51db7a6440..e50c8d8a2d 100755 --- a/scripts/project_manager/projects.py +++ b/scripts/project_manager/projects.py @@ -29,12 +29,11 @@ executable_path = '' logger = logging.getLogger() logger.setLevel(logging.INFO) -from cmake.Tools import engine_template -from cmake.Tools import registration +from o3de import engine_template, registration o3de_folder = registration.get_o3de_folder() o3de_logs_folder = registration.get_o3de_logs_folder() -project_manager_log_file_path = o3de_log_folder / "project_manager.log" +project_manager_log_file_path = o3de_logs_folder / "project_manager.log" log_file_handler = RotatingFileHandler(filename=project_manager_log_file_path, maxBytes=1024 * 1024, backupCount=1) formatter = logging.Formatter('%(asctime)s | %(levelname)s : %(message)s') log_file_handler.setFormatter(formatter) From f3d264292654eba10a2693fa195cc4b1d0a6103f Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 19 May 2021 00:54:31 -0500 Subject: [PATCH 071/811] Added an installation of the scripts/o3de folder as a local package for the o3de python that is installed through cmake --- cmake/LYPython.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cmake/LYPython.cmake b/cmake/LYPython.cmake index 546d5f66db..a7c18e4dbe 100644 --- a/cmake/LYPython.cmake +++ b/cmake/LYPython.cmake @@ -270,6 +270,8 @@ if (NOT CMAKE_SCRIPT_MODE_FILE) ly_pip_install_local_package_editable(${LY_ROOT_FOLDER}/Tools/RemoteConsole/ly_remote_console ly-remote-console) ly_pip_install_local_package_editable(${LY_ROOT_FOLDER}/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools editor-python-test-tools) endif() + + ly_pip_install_local_package_editable(${LY_ROOT_FOLDER}/scripts/o3de o3de) endif() endif() From 0b50b6cc63842c7537ff43609a039e39295f1a5d Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 19 May 2021 12:04:40 +0100 Subject: [PATCH 072/811] Fixed code Style and minor issues from feedback --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 1 - .../AssetBrowser/AssetBrowserTableModel.cpp | 13 ++++++++----- .../AssetBrowser/Views/AssetBrowserTableView.cpp | 8 ++++++++ .../AssetBrowser/Views/EntryDelegate.cpp | 6 +++--- .../Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp | 4 ++++ 5 files changed, 23 insertions(+), 9 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 12b0256c5d..c5723832c7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -184,7 +184,6 @@ namespace AzToolsFramework invalidateFilter(); Q_EMIT filterChanged(); emit stringFilterPopulated(!m_stringFilter.isNull()); - } void AssetBrowserFilterModel::filterUpdatedSlot() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index b9bfe1bea6..6d9803dfd4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -22,10 +22,11 @@ namespace AzToolsFramework { setDynamicSortFilter(false); } + void AssetBrowserTableModel::setSourceModel(QAbstractItemModel* sourceModel) { m_filterModel = qobject_cast(sourceModel); - AZ_Assert(m_filterModel, "Expecting AssetBrowserFilterModel"); + AZ_Assert(m_filterModel, "Error in AssetBrowserTableModel initialization, class expects source model to be an AssetBrowserFilterModel."); QSortFilterProxyModel::setSourceModel(sourceModel); } @@ -47,9 +48,9 @@ namespace AzToolsFramework switch (columnRole) { case AssetBrowserEntry::Column::Name: - return QString("Name"); + return tr("Name"); case AssetBrowserEntry::Column::Path: - return QString("Path"); + return tr("Path"); default: return QString::number(section); } @@ -68,8 +69,8 @@ namespace AzToolsFramework AssetBrowserEntry* entry = GetAssetEntry(sourceIndex); if (entry == nullptr) { - AZ_Assert(false, "ERROR - index internal pointer not pointing to an AssetEntry. Tree provided by the AssetBrowser invalid?"); - return Qt::PartiallyChecked; + AZ_Assert(false, "AssetBrowserTableModel - QModelIndex does not reference an AssetEntry. Source model is not valid."); + return QVariant(); } return sourceIndex.data(role); @@ -113,6 +114,7 @@ namespace AzToolsFramework } return row; } + AssetBrowserEntry* AssetBrowserTableModel::GetAssetEntry(QModelIndex index) const { if (index.isValid()) @@ -125,6 +127,7 @@ namespace AzToolsFramework return nullptr; } } + void AssetBrowserTableModel::UpdateTableModelMaps() { emit layoutAboutToBeChanged(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index df3b0b8644..f7128cb504 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -60,11 +60,13 @@ namespace AzToolsFramework AssetBrowserViewRequestBus::Handler::BusConnect(); AssetBrowserComponentNotificationBus::Handler::BusConnect(); } + AssetBrowserTableView::~AssetBrowserTableView() { AssetBrowserViewRequestBus::Handler::BusDisconnect(); AssetBrowserComponentNotificationBus::Handler::BusDisconnect(); } + void AssetBrowserTableView::setModel(QAbstractItemModel* model) { m_tableModel = qobject_cast(model); @@ -76,6 +78,7 @@ namespace AzToolsFramework horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch); horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeMode::Stretch); } + void AssetBrowserTableView::SetName(const QString& name) { m_name = name; @@ -86,6 +89,7 @@ namespace AzToolsFramework OnAssetBrowserComponentReady(); } } + AZStd::vector AssetBrowserTableView::GetSelectedAssets() const { QModelIndexList sourceIndexes; @@ -101,11 +105,13 @@ namespace AzToolsFramework AssetBrowserModel::SourceIndexesToAssetDatabaseEntries(sourceIndexes, entries); return entries; } + void AssetBrowserTableView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { QTableView::selectionChanged(selected, deselected); Q_EMIT selectionChangedSignal(selected, deselected); } + void AssetBrowserTableView::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) { // if selected entry is being removed, clear selection so not to select (and attempt to preview) other entries potentially @@ -121,10 +127,12 @@ namespace AzToolsFramework } QTableView::rowsAboutToBeRemoved(parent, start, end); } + void AssetBrowserTableView::layoutChangedSlot([[maybe_unused]] const QList& parents,[[maybe_unused]] QAbstractItemModel::LayoutChangeHint hint) { scrollToTop(); } + void AssetBrowserTableView::SelectProduct([[maybe_unused]] AZ::Data::AssetId assetID) { } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp index b968f0480a..dff8a170c7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp @@ -99,9 +99,9 @@ namespace AzToolsFramework style->drawItemText( painter, remainingRect, option.displayAlignment, actualPalette, isEnabled, - index.column() == static_cast(AssetBrowserEntry::Column::Name) - ? qvariant_cast(entry->data(static_cast(AssetBrowserEntry::Column::Name))) - : qvariant_cast(entry->data(static_cast(AssetBrowserEntry::Column::Path))), + index.column() == aznumeric_cast(AssetBrowserEntry::Column::Name) + ? qvariant_cast(entry->data(aznumeric_cast(AssetBrowserEntry::Column::Name))) + : qvariant_cast(entry->data(aznumeric_cast(AssetBrowserEntry::Column::Path))), isSelected ? QPalette::HighlightedText : QPalette::Text); } } diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 412dc61465..35734042a0 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -312,9 +312,13 @@ void AzAssetBrowserWindow::LockToDefaultView(bool state) using namespace AzToolsFramework::AssetBrowser; SwitchDisplayView(!state); if (state == true) + { disconnect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); + } else + { connect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); + } } #include From f972edee010845160615370f66391cbe3c552448 Mon Sep 17 00:00:00 2001 From: phistere Date: Wed, 19 May 2021 10:49:17 -0500 Subject: [PATCH 073/811] Fixes an issue with RUNTIME_DEPENDENCIES including too many targets during install --- CMakeLists.txt | 2 +- cmake/LYWrappers.cmake | 7 +++++++ cmake/Platform/Common/Install_common.cmake | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 78667a7161..50670c0b85 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -124,7 +124,7 @@ endif() # The following steps have to be done after all targets are registered: # 1. generate a settings registry .setreg file for all ly_add_project_dependencies() and ly_add_target_dependencies() calls # to provide applications with the filenames of gem modules to load -# This must be done before ly_delayed_target_link_libraries() as that inserts BUILD_DEPENDENCIE as MANUALLY_ADDED_DEPENDENCIES +# This must be done before ly_delayed_target_link_libraries() as that inserts BUILD_DEPENDENCIES as MANUALLY_ADDED_DEPENDENCIES # if the build dependency is a MODULE_LIBRARY. That would cause a false load dependency to be generated ly_delayed_generate_settings_registry() # 2. link targets where the dependency was yet not declared, we need to have the declaration so we do different diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index bddd1a6c66..2ad80851b9 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -372,9 +372,16 @@ function(ly_delayed_target_link_libraries) list(APPEND CMAKE_MODULE_PATH ${additional_module_paths}) get_property(delayed_targets GLOBAL PROPERTY LY_DELAYED_LINK_TARGETS) + foreach(target ${delayed_targets}) get_property(delayed_link GLOBAL PROPERTY LY_DELAYED_LINK_${target}) + + # Cache off the original MANUALLY_ADDED_DEPENDENCIES that were associated with the target + # via previous ly_add_dependencies() calls either explicitly or through RUNTIME_DEPENDENCIES + get_target_property(target_orig_manually_added_dependencies ${target} MANUALLY_ADDED_DEPENDENCIES) + set_property(TARGET ${target} PROPERTY LY_ORIGINAL_MANUALLY_ADDED_DEPENDENCIES ${target_orig_manually_added_dependencies}) + if(delayed_link) cmake_parse_arguments(ly_delayed_target_link_libraries "" "" "${visibilities}" ${delayed_link}) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 64fc973701..b501e3db03 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -125,7 +125,7 @@ function(ly_setup_target ALIAS_TARGET_NAME) endforeach() endif() - get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) + get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} LY_ORIGINAL_MANUALLY_ADDED_DEPENDENCIES) if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") else() From 5f82d8e3ebcee713b0921144d0dfc93222e9da30 Mon Sep 17 00:00:00 2001 From: phistere Date: Wed, 19 May 2021 11:49:18 -0500 Subject: [PATCH 074/811] Updates EngineFinder.cmake to correct the key that it's looking for --- .../Template/EngineFinder.cmake | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Templates/DefaultProject/Template/EngineFinder.cmake b/Templates/DefaultProject/Template/EngineFinder.cmake index 5f791f5e3d..7dfddf2c5f 100644 --- a/Templates/DefaultProject/Template/EngineFinder.cmake +++ b/Templates/DefaultProject/Template/EngineFinder.cmake @@ -30,27 +30,27 @@ endif() if(EXISTS ${manifest_path}) file(READ ${manifest_path} manifest_json) - string(JSON engine_paths_count ERROR_VARIABLE json_error LENGTH ${manifest_json} engine_paths) + string(JSON engines_path_count ERROR_VARIABLE json_error LENGTH ${manifest_json} engines_path) if(json_error) - message(FATAL_ERROR "Unable to read key 'engine_paths' from '${manifest_path}', error: ${json_error}") + message(FATAL_ERROR "Unable to read key 'engines_path' from '${manifest_path}', error: ${json_error}") endif() - string(JSON engine_paths_type ERROR_VARIABLE json_error TYPE ${manifest_json} engine_paths) - if(json_error OR NOT ${engine_paths_type} STREQUAL "OBJECT") - message(FATAL_ERROR "Type of 'engine_paths' in '${manifest_path}' is not a JSON Object, error: ${json_error}") + string(JSON engines_path_type ERROR_VARIABLE json_error TYPE ${manifest_json} engines_path) + if(json_error OR NOT ${engines_path_type} STREQUAL "OBJECT") + message(FATAL_ERROR "Type of 'engines_path' in '${manifest_path}' is not a JSON Object, error: ${json_error}") endif() - math(EXPR engine_paths_count "${engine_paths_count}-1") - foreach(engine_path_index RANGE ${engine_paths_count}) - string(JSON engine_name ERROR_VARIABLE json_error MEMBER ${manifest_json} engine_paths ${engine_path_index}) + math(EXPR engines_path_count "${engines_path_count}-1") + foreach(engine_path_index RANGE ${engines_path_count}) + string(JSON engine_name ERROR_VARIABLE json_error MEMBER ${manifest_json} engines_path ${engine_path_index}) if(json_error) - message(FATAL_ERROR "Unable to read 'engine_paths/${engine_path_index}' from '${manifest_path}', error: ${json_error}") + message(FATAL_ERROR "Unable to read 'engines_path/${engine_path_index}' from '${manifest_path}', error: ${json_error}") endif() if(LY_ENGINE_NAME_TO_USE STREQUAL engine_name) - string(JSON engine_path ERROR_VARIABLE json_error GET ${manifest_json} engine_paths ${engine_name}) + string(JSON engine_path ERROR_VARIABLE json_error GET ${manifest_json} engines_path ${engine_name}) if(json_error) - message(FATAL_ERROR "Unable to read value from 'engine_paths/${engine_name}', error: ${json_error}") + message(FATAL_ERROR "Unable to read value from 'engines_path/${engine_name}', error: ${json_error}") endif() if(engine_path) From b5b9f7b7e9480ae5157b3a2b196ae8e38a237343 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 19 May 2021 12:14:47 -0500 Subject: [PATCH 075/811] Removing leftover ScriptCanvasDiagnosticLibrary files --- .../Code/Source/precompiled.cpp | 13 ------ .../Code/Source/precompiled.h | 28 ------------ .../ScriptCanvasDiagnosticLibraryTest.cpp | 44 ------------------- 3 files changed, 85 deletions(-) delete mode 100644 Gems/ScriptCanvasDiagnosticLibrary/Code/Source/precompiled.cpp delete mode 100644 Gems/ScriptCanvasDiagnosticLibrary/Code/Source/precompiled.h delete mode 100644 Gems/ScriptCanvasDiagnosticLibrary/Code/Tests/ScriptCanvasDiagnosticLibraryTest.cpp diff --git a/Gems/ScriptCanvasDiagnosticLibrary/Code/Source/precompiled.cpp b/Gems/ScriptCanvasDiagnosticLibrary/Code/Source/precompiled.cpp deleted file mode 100644 index 6fdd7bdc45..0000000000 --- a/Gems/ScriptCanvasDiagnosticLibrary/Code/Source/precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "precompiled.h" diff --git a/Gems/ScriptCanvasDiagnosticLibrary/Code/Source/precompiled.h b/Gems/ScriptCanvasDiagnosticLibrary/Code/Source/precompiled.h deleted file mode 100644 index 01688d8dc7..0000000000 --- a/Gems/ScriptCanvasDiagnosticLibrary/Code/Source/precompiled.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include -#include - -#if !defined(SCRIPTCANVASDIAGNOSTICSLIBRARY_EDITOR) - -#include - -#else - -#endif diff --git a/Gems/ScriptCanvasDiagnosticLibrary/Code/Tests/ScriptCanvasDiagnosticLibraryTest.cpp b/Gems/ScriptCanvasDiagnosticLibrary/Code/Tests/ScriptCanvasDiagnosticLibraryTest.cpp deleted file mode 100644 index 4052b9dee4..0000000000 --- a/Gems/ScriptCanvasDiagnosticLibrary/Code/Tests/ScriptCanvasDiagnosticLibraryTest.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "precompiled.h" - -#include - -class ScriptCanvasDiagnosticLibraryTest - : public ::testing::Test -{ -protected: - static void SetUpTestCase() - { - } - - static void TearDownTestCase() - { - } - - void SetUp() override - { - } - - void TearDown() override - { - } - -}; - -TEST_F(ScriptCanvasDiagnosticLibraryTest, Sanity_Pass) -{ - EXPECT_TRUE(true); -} - - -AZ_UNIT_TEST_HOOK(); From 0ba2900fdd2c6021f4f580f026b7fcff459a728a Mon Sep 17 00:00:00 2001 From: phistere Date: Wed, 19 May 2021 12:27:02 -0500 Subject: [PATCH 076/811] Fixes and issue with o3de scripts assuming the wrong directory as the engine directory --- scripts/o3de/o3de/registration.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/o3de/o3de/registration.py b/scripts/o3de/o3de/registration.py index a4afecd740..6a165cbea5 100755 --- a/scripts/o3de/o3de/registration.py +++ b/scripts/o3de/o3de/registration.py @@ -55,7 +55,7 @@ def backup_folder(folder: str or pathlib.Path) -> None: def get_this_engine_path() -> pathlib.Path: - return pathlib.Path(os.path.realpath(__file__)).parents[2].resolve() + return pathlib.Path(os.path.realpath(__file__)).parents[3].resolve() override_home_folder = None @@ -123,9 +123,9 @@ def get_o3de_restricted_folder() -> pathlib.Path: def get_o3de_logs_folder() -> pathlib.Path: - restricted_folder = get_o3de_folder() / 'Logs' - restricted_folder.mkdir(parents=True, exist_ok=True) - return restricted_folder + logs_folder = get_o3de_folder() / 'Logs' + logs_folder.mkdir(parents=True, exist_ok=True) + return logs_folder def register_shipped_engine_o3de_objects(force: bool = False) -> int: From cef7eacd241ce7a654d7b752094c5386e4f38d5d Mon Sep 17 00:00:00 2001 From: phistere Date: Wed, 19 May 2021 13:25:51 -0500 Subject: [PATCH 077/811] Fixes install of scripts to include o3de folder --- cmake/Platform/Common/Install_common.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index b501e3db03..ebe31a4cfa 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -385,6 +385,7 @@ function(ly_setup_others) install(DIRECTORY ${LY_ROOT_FOLDER}/scripts/bundler ${LY_ROOT_FOLDER}/scripts/project_manager + ${LY_ROOT_FOLDER}/scripts/o3de DESTINATION ./scripts COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} PATTERN "__pycache__" EXCLUDE From 4ca30afa9ee19615b2680e9c74b7e62c8f8750b5 Mon Sep 17 00:00:00 2001 From: phistere Date: Wed, 19 May 2021 14:24:31 -0500 Subject: [PATCH 078/811] Updates pip install flags for consistency and installs the o3de module --- cmake/LYPython.cmake | 2 +- python/get_python.bat | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/cmake/LYPython.cmake b/cmake/LYPython.cmake index a7c18e4dbe..238889d829 100644 --- a/cmake/LYPython.cmake +++ b/cmake/LYPython.cmake @@ -81,7 +81,7 @@ function(update_pip_requirements requirements_file_path unique_name) set(ENV{PYTHONNOUSERSITE} 1) execute_process(COMMAND - ${LY_PYTHON_CMD} -m pip install --no-deps -r "${requirements_file_path}" --disable-pip-version-check --no-warn-script-location + ${LY_PYTHON_CMD} -m pip install -r "${requirements_file_path}" --disable-pip-version-check --no-warn-script-location WORKING_DIRECTORY ${Python_BINFOLDER} RESULT_VARIABLE PIP_RESULT OUTPUT_VARIABLE PIP_OUT diff --git a/python/get_python.bat b/python/get_python.bat index e9f18441b5..e11c4ab92f 100644 --- a/python/get_python.bat +++ b/python/get_python.bat @@ -25,7 +25,8 @@ call python.cmd --version > NUL IF !ERRORLEVEL!==0 ( echo get_python.bat: Python is already installed: call python.cmd --version - call "%CMD_DIR%\pip.cmd" install -r "%CMD_DIR%/requirements.txt" --quiet --disable-pip-version-check + call "%CMD_DIR%\pip.cmd" install -r "%CMD_DIR%/requirements.txt" --quiet --disable-pip-version-check --no-warn-script-location + call "%CMD_DIR%\pip.cmd" install -e "%CMD_DIR%/../scripts/o3de" --quiet --disable-pip-version-check --no-warn-script-location --no-deps exit /B 0 ) @@ -65,6 +66,7 @@ if ERRORLEVEL 1 ( ) echo calling PIP to install requirements... -call "%CMD_DIR%\pip.cmd" install -r "%CMD_DIR%/requirements.txt" --disable-pip-version-check +call "%CMD_DIR%\pip.cmd" install -r "%CMD_DIR%/requirements.txt" --disable-pip-version-check --no-warn-script-location +call "%CMD_DIR%\pip.cmd" install -e "%CMD_DIR%/../scripts/o3de" --disable-pip-version-check --no-warn-script-location --no-deps exit /B %ERRORLEVEL% From 7a25a17fae641fef241d3fecf80d6ea6cdd8fb5d Mon Sep 17 00:00:00 2001 From: phistere Date: Thu, 20 May 2021 09:13:01 -0500 Subject: [PATCH 079/811] Fixes a few issues when using an engine name different from the default --- .../Template/EngineFinder.cmake | 5 ++- cmake/install/engine.json.in | 2 +- scripts/o3de/o3de/engine_template.py | 43 +++++++++++++++++-- 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/Templates/DefaultProject/Template/EngineFinder.cmake b/Templates/DefaultProject/Template/EngineFinder.cmake index 7dfddf2c5f..a7dbf671fd 100644 --- a/Templates/DefaultProject/Template/EngineFinder.cmake +++ b/Templates/DefaultProject/Template/EngineFinder.cmake @@ -20,13 +20,14 @@ if(json_error) message(FATAL_ERROR "Unable to read key 'engine' from 'project.json', error: ${json_error}") endif() -# Read the list of paths from ~.o3de/o3de_manifest.json -if($ENV{USERPROFILE} AND EXISTS $ENV{USERPROFILE}) +if(DEFINED ENV{USERPROFILE} AND EXISTS $ENV{USERPROFILE}) set(manifest_path $ENV{USERPROFILE}/.o3de/o3de_manifest.json) # Windows else() set(manifest_path $ENV{HOME}/.o3de/o3de_manifest.json) # Unix endif() +# Read the ~/.o3de/o3de_manifest.json file and look through the 'engines_path' object. +# Find a key that matches LY_ENGINE_NAME_TO_USE and use that as the engine path. if(EXISTS ${manifest_path}) file(READ ${manifest_path} manifest_json) diff --git a/cmake/install/engine.json.in b/cmake/install/engine.json.in index 04ee6348d3..4a8579d864 100644 --- a/cmake/install/engine.json.in +++ b/cmake/install/engine.json.in @@ -1,6 +1,6 @@ { "engine_name": "@LY_VERSION_ENGINE_NAME@", - "restricted": "@LY_VERSION_ENGINE_NAME@", + "restricted": "o3de", "FileVersion": 1, "O3DEVersion": "@LY_VERSION_STRING@", "O3DECopyrightYear": @LY_VERSION_COPYRIGHT_YEAR@, diff --git a/scripts/o3de/o3de/engine_template.py b/scripts/o3de/o3de/engine_template.py index 23acab33d4..ad7ec55e1f 100755 --- a/scripts/o3de/o3de/engine_template.py +++ b/scripts/o3de/o3de/engine_template.py @@ -1652,10 +1652,45 @@ def create_project(project_path: str, d.write('# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n') d.write('# {END_LICENSE}\n') - # copy the o3de_manifest.cmake into the project root - engine_path = registration.get_this_engine_path() - o3de_manifest_cmake = f'{engine_path}/cmake/o3de_manifest.cmake' - shutil.copy(o3de_manifest_cmake, project_path) + # set the "engine" element of the project.json + engine_json = f'{registration.get_this_engine_path()}/engine.json' + if not registration.valid_o3de_engine_json(engine_json): + logger.error(f"Engine json {engine_json} is not valid.") + return 1 + + with open(engine_json) as s: + try: + engine_json_data = json.load(s) + except Exception as e: + logger.error(f"Failed to read engine json {engine_json}: {str(e)}") + return 1 + + try: + engine_name = engine_json_data['engine_name'] + except Exception as e: + logger.error(f"Engine json {engine_json} engine_name not found.") + return 1 + + project_json = f"{project_path}/project.json".replace('//', '/') + if not registration.valid_o3de_project_json(project_json): + logger.error(f'Project json {project_json} is not valid.') + return 1 + + with open(project_json, 'r') as s: + try: + project_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to load project json {project_json}.') + return 1 + + project_json_data.update({"engine": engine_name}) + os.unlink(project_json) + with open(project_json, 'w') as s: + try: + s.write(json.dumps(project_json_data, indent=4)) + except Exception as e: + logger.error(f'Failed to write project json {project_json}.') + return 1 return 0 From 0f4e00e48f940eab016cf3f01be27821c0236f1e Mon Sep 17 00:00:00 2001 From: phistere Date: Thu, 20 May 2021 10:38:44 -0500 Subject: [PATCH 080/811] Updating the Gems selctions for the DefaultProject template --- .../Template/Code/runtime_dependencies.cmake | 10 ---------- .../Template/Code/tool_dependencies.cmake | 15 --------------- 2 files changed, 25 deletions(-) diff --git a/Templates/DefaultProject/Template/Code/runtime_dependencies.cmake b/Templates/DefaultProject/Template/Code/runtime_dependencies.cmake index ce8df8152d..f55677a9b6 100644 --- a/Templates/DefaultProject/Template/Code/runtime_dependencies.cmake +++ b/Templates/DefaultProject/Template/Code/runtime_dependencies.cmake @@ -18,19 +18,9 @@ set(GEM_DEPENDENCIES Gem::LyShine Gem::Camera Gem::CameraFramework - Gem::Atom_RHI.Private Gem::EMotionFX - Gem::Atom_RPI.Private - Gem::Atom_Feature_Common Gem::ImGui - Gem::Atom_Bootstrap - Gem::Atom_Component_DebugCamera - Gem::AtomImGuiTools - Gem::AtomLyIntegration_CommonFeatures - Gem::EMotionFX_Atom - Gem::ImguiAtom Gem::Atom_AtomBridge Gem::GradientSignal - Gem::AtomFont Gem::WhiteBox ) diff --git a/Templates/DefaultProject/Template/Code/tool_dependencies.cmake b/Templates/DefaultProject/Template/Code/tool_dependencies.cmake index 010d45bd0f..c6a782c17e 100644 --- a/Templates/DefaultProject/Template/Code/tool_dependencies.cmake +++ b/Templates/DefaultProject/Template/Code/tool_dependencies.cmake @@ -20,24 +20,9 @@ set(GEM_DEPENDENCIES Gem::EditorPythonBindings.Editor Gem::Camera.Editor Gem::CameraFramework - Gem::Atom_RHI.Private Gem::EMotionFX.Editor - Gem::Atom_RPI.Builders - Gem::Atom_RPI.Editor - Gem::Atom_Feature_Common.Builders - Gem::Atom_Feature_Common.Editor Gem::ImGui.Editor - Gem::Atom_Bootstrap - Gem::Atom_Asset_Shader.Builders - Gem::Atom_Component_DebugCamera - Gem::AtomImGuiTools - Gem::AtomLyIntegration_CommonFeatures.Editor - Gem::EMotionFX_Atom.Editor - Gem::ImageProcessingAtom.Editor Gem::Atom_AtomBridge.Editor - Gem::ImguiAtom - Gem::AtomFont - Gem::AtomToolsFramework.Editor Gem::GradientSignal.Editor Gem::WhiteBox.Editor ) From a4243f4be37473003b4f896712185dedc8caa286 Mon Sep 17 00:00:00 2001 From: phistere Date: Thu, 20 May 2021 10:42:06 -0500 Subject: [PATCH 081/811] Temporarily fixes an issue with some Gems where asset paths aren't properly generated for asset processor --- cmake/SettingsRegistry.cmake | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index 31ce36c516..dcfbd8a1f0 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -124,12 +124,13 @@ function(ly_delayed_generate_settings_registry) message(FATAL_ERROR "Dependency ${gem_target} from ${target} does not exist") endif() get_property(gem_relative_source_dir TARGET ${gem_target} PROPERTY SOURCE_DIR) + if(gem_relative_source_dir) - # Most gems SOURCE dir is nested in the path, we need to find the path to the gem.json or project.json file - while(NOT EXISTS ${gem_relative_source_dir}/gem.json AND NOT EXISTS ${gem_relative_source_dir}/project.json) + # Most gems SOURCE dir is nested in the path, we need to find the path where an 'Assets' or 'Code' folder resides + while(NOT EXISTS ${gem_relative_source_dir}/Assets AND NOT EXISTS ${gem_relative_source_dir}/Code) get_filename_component(parent_dir ${gem_relative_source_dir} DIRECTORY) if (${parent_dir} STREQUAL ${gem_relative_source_dir}) - message(FATAL_ERROR "Did not find gem.json or project.json while processing target ${gem_target}!") + message(FATAL_ERROR "Did not find a Gem source dir while processing target ${gem_target}!") endif() set(gem_relative_source_dir ${parent_dir}) endwhile() From c9d5d7fb779b4354ffd70a3acca9d5f07a0c645f Mon Sep 17 00:00:00 2001 From: Nicholas Lawson <70027408+lawsonamzn@users.noreply.github.com> Date: Tue, 27 Apr 2021 17:09:57 -0700 Subject: [PATCH 082/811] The new gem registration and usage system Merge from mainline (Rebase) --- AutomatedTesting/Gem/Code/CMakeLists.txt | 20 ++ AutomatedTesting/Gem/Code/enabled_gems.cmake | 57 +++++ .../Gem/Code/runtime_dependencies.cmake | 51 ----- .../Gem/Code/tool_dependencies.cmake | 63 ------ CMakeLists.txt | 21 +- Gems/AWSClientAuth/Code/CMakeLists.txt | 4 + Gems/AWSCore/Code/CMakeLists.txt | 9 + Gems/AWSMetrics/Code/CMakeLists.txt | 4 + Gems/Achievements/Code/CMakeLists.txt | 3 + Gems/AssetMemoryAnalyzer/Code/CMakeLists.txt | 5 + Gems/AssetValidation/Code/CMakeLists.txt | 5 + Gems/AudioEngineWwise/Code/CMakeLists.txt | 7 + Gems/AudioSystem/Code/CMakeLists.txt | 25 +-- .../Code/CMakeLists.txt | 4 + Gems/Blast/Code/CMakeLists.txt | 8 + Gems/Camera/Code/CMakeLists.txt | 7 + Gems/CameraFramework/Code/CMakeLists.txt | 6 + Gems/CertificateManager/Code/CMakeLists.txt | 4 + Gems/CrashReporting/Code/CMakeLists.txt | 5 + Gems/CustomAssetExample/Code/CMakeLists.txt | 9 + Gems/DebugDraw/Code/CMakeLists.txt | 8 + Gems/EMotionFX/Code/CMakeLists.txt | 9 + Gems/EditorPythonBindings/Code/CMakeLists.txt | 4 + Gems/ExpressionEvaluation/Code/CMakeLists.txt | 6 + Gems/FastNoise/Code/CMakeLists.txt | 10 + Gems/GameState/Code/CMakeLists.txt | 4 + Gems/GameStateSamples/Code/CMakeLists.txt | 4 + Gems/Gestures/Code/CMakeLists.txt | 6 + Gems/GradientSignal/Code/CMakeLists.txt | 9 + Gems/GraphCanvas/Code/CMakeLists.txt | 6 + Gems/GraphModel/Code/CMakeLists.txt | 5 + Gems/HttpRequestor/Code/CMakeLists.txt | 6 + Gems/ImGui/Code/CMakeLists.txt | 9 + Gems/InAppPurchases/Code/CMakeLists.txt | 5 + Gems/LandscapeCanvas/Code/CMakeLists.txt | 5 + Gems/LmbrCentral/Code/CMakeLists.txt | 9 + Gems/LocalUser/Code/CMakeLists.txt | 3 + Gems/LyShine/Code/CMakeLists.txt | 7 + Gems/LyShineExamples/Code/CMakeLists.txt | 7 + Gems/Maestro/Code/CMakeLists.txt | 8 + Gems/MessagePopup/Code/CMakeLists.txt | 4 + Gems/Metastream/Code/CMakeLists.txt | 5 + Gems/Microphone/Code/CMakeLists.txt | 4 + Gems/Multiplayer/Code/CMakeLists.txt | 53 +++-- .../Code/CMakeLists.txt | 5 + Gems/NvCloth/Code/CMakeLists.txt | 8 + Gems/PhysX/Code/CMakeLists.txt | 8 + Gems/PhysXDebug/Code/CMakeLists.txt | 7 + Gems/Prefab/PrefabBuilder/CMakeLists.txt | 18 +- Gems/Presence/Code/CMakeLists.txt | 3 + Gems/PythonAssetBuilder/Code/CMakeLists.txt | 5 + Gems/QtForPython/Code/CMakeLists.txt | 6 + Gems/RADTelemetry/Code/CMakeLists.txt | 5 + Gems/SaveData/Code/CMakeLists.txt | 3 + Gems/SceneLoggingExample/Code/CMakeLists.txt | 4 + Gems/SceneProcessing/Code/CMakeLists.txt | 4 + Gems/ScriptCanvas/Code/CMakeLists.txt | 18 ++ .../ScriptCanvasDeveloper/Code/CMakeLists.txt | 9 + Gems/ScriptCanvasPhysics/Code/CMakeLists.txt | 6 + Gems/ScriptCanvasTesting/Code/CMakeLists.txt | 3 + Gems/ScriptEvents/Code/CMakeLists.txt | 9 + .../ScriptedEntityTweener/Code/CMakeLists.txt | 6 + Gems/SliceFavorites/Code/CMakeLists.txt | 3 + Gems/StartingPointCamera/Code/CMakeLists.txt | 6 + Gems/StartingPointInput/Code/CMakeLists.txt | 9 + .../StartingPointMovement/Code/CMakeLists.txt | 6 + Gems/SurfaceData/Code/CMakeLists.txt | 7 + Gems/TestAssetBuilder/Code/CMakeLists.txt | 3 + Gems/TextureAtlas/Code/CMakeLists.txt | 6 + Gems/TickBusOrderViewer/Code/CMakeLists.txt | 6 + Gems/Twitch/Code/CMakeLists.txt | 6 + Gems/Vegetation/Code/CMakeLists.txt | 8 + .../Code/CMakeLists.txt | 5 + Gems/VirtualGamepad/Code/CMakeLists.txt | 5 + Gems/WhiteBox/Code/CMakeLists.txt | 10 + cmake/Gems.cmake | 196 ++++++++++++++++++ cmake/LYWrappers.cmake | 17 ++ cmake/SettingsRegistry.cmake | 19 +- 78 files changed, 784 insertions(+), 168 deletions(-) create mode 100644 AutomatedTesting/Gem/Code/enabled_gems.cmake delete mode 100644 AutomatedTesting/Gem/Code/runtime_dependencies.cmake delete mode 100644 AutomatedTesting/Gem/Code/tool_dependencies.cmake create mode 100644 cmake/Gems.cmake diff --git a/AutomatedTesting/Gem/Code/CMakeLists.txt b/AutomatedTesting/Gem/Code/CMakeLists.txt index 2bcc304bde..e81156c3aa 100644 --- a/AutomatedTesting/Gem/Code/CMakeLists.txt +++ b/AutomatedTesting/Gem/Code/CMakeLists.txt @@ -31,6 +31,26 @@ ly_add_target( ################################################################################ # Gem dependencies ################################################################################ + +# The GameLauncher uses "Client" gem variants: +ly_enable_gems(PROJECT_NAME AutomatedTesting GEM_FILE enabled_gems.cmake + TARGETS AutomatedTesting.GameLauncher + VARIANTS Clients) + +# The Editor uses Tools gem variants: +ly_enable_gems( + PROJECT_NAME AutomatedTesting GEM_FILE enabled_gems.cmake + TARGETS Editor + VARIANTS Tools) + +# The pipeline tools use Builders gem variants: +ly_enable_gems( + PROJECT_NAME AutomatedTesting GEM_FILE enabled_gems.cmake + TARGETS AssetBuilder AssetProcessor AssetProcessorBatch + VARIANTS Builders) + +# old system (remove when all gems are ported to the new system above) + ly_add_project_dependencies( PROJECT_NAME AutomatedTesting diff --git a/AutomatedTesting/Gem/Code/enabled_gems.cmake b/AutomatedTesting/Gem/Code/enabled_gems.cmake new file mode 100644 index 0000000000..32fdd11415 --- /dev/null +++ b/AutomatedTesting/Gem/Code/enabled_gems.cmake @@ -0,0 +1,57 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(ENABLED_GEMS + ImGui + ScriptEvents + ExpressionEvaluation + Gestures + CertificateManager + DebugDraw + SceneProcessing + GraphCanvas + InAppPurchases + AutomatedTesting + EditorPythonBindings + PythonAssetBuilder + Metastream + AudioSystem + Camera + EMotionFX + PhysX + CameraFramework + StartingPointMovement + StartingPointCamera + ScriptCanvas + ScriptCanvasPhysics + ScriptCanvasTesting + LyShineExamples + StartingPointInput + PhysXDebug + WhiteBox + FastNoise + SurfaceData + GradientSignal + Vegetation + GraphModel + LandscapeCanvas + NvCloth + Blast + Maestro + TextureAtlas + LmbrCentral + LyShine + HttpRequestor + Atom_AtomBridge + AWSCore + AWSClientAuth + AWSMetrics + ) diff --git a/AutomatedTesting/Gem/Code/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/runtime_dependencies.cmake deleted file mode 100644 index 33c2bf8d5f..0000000000 --- a/AutomatedTesting/Gem/Code/runtime_dependencies.cmake +++ /dev/null @@ -1,51 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the License). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an AS IS BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -# Extracted from Game -set(GEM_DEPENDENCIES - Gem::Maestro - Gem::TextureAtlas - Gem::LmbrCentral - Gem::LyShine - Gem::HttpRequestor - Gem::ScriptEvents - Gem::ExpressionEvaluation - Gem::Gestures - Gem::CertificateManager - Gem::DebugDraw - Gem::AudioSystem - Gem::InAppPurchases - Gem::AutomatedTesting - Gem::Metastream - Gem::Camera - Gem::EMotionFX - Gem::PhysX - Gem::CameraFramework - Gem::StartingPointMovement - Gem::StartingPointCamera - Gem::ScriptCanvas - Gem::ImGui - Gem::LyShineExamples - Gem::StartingPointInput - Gem::ScriptCanvasPhysics - Gem::PhysXDebug - Gem::WhiteBox - Gem::FastNoise - Gem::SurfaceData - Gem::GradientSignal - Gem::Vegetation - Gem::Atom_AtomBridge - Gem::NvCloth - Gem::Blast - Gem::AWSCore - Gem::AWSClientAuth - Gem::AWSMetrics -) diff --git a/AutomatedTesting/Gem/Code/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/tool_dependencies.cmake deleted file mode 100644 index c8eccab947..0000000000 --- a/AutomatedTesting/Gem/Code/tool_dependencies.cmake +++ /dev/null @@ -1,63 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the License). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an AS IS BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -# Extracted from Editor.xml -set(GEM_DEPENDENCIES - Gem::Maestro.Editor - Gem::TextureAtlas - Gem::LmbrCentral.Editor - Gem::LyShine.Editor - Gem::HttpRequestor - Gem::ScriptEvents.Editor - Gem::ExpressionEvaluation - Gem::Gestures - Gem::CertificateManager - Gem::DebugDraw.Editor - Gem::SceneProcessing.Editor - Gem::GraphCanvas.Editor - Gem::InAppPurchases - Gem::AutomatedTesting - Gem::EditorPythonBindings.Editor - Gem::PythonAssetBuilder.Editor - Gem::Metastream - Gem::AudioSystem.Editor - Gem::Camera.Editor - Gem::EMotionFX.Editor - Gem::PhysX.Editor - Gem::CameraFramework - Gem::StartingPointMovement - Gem::StartingPointCamera - Gem::ScriptCanvas.Editor - Gem::ScriptEvents.Editor - Gem::ImGui.Editor - Gem::LyShineExamples - Gem::StartingPointInput.Editor - Gem::ScriptCanvasPhysics - Gem::ScriptCanvasTesting.Editor - Gem::PhysXDebug.Editor - Gem::WhiteBox.Editor - Gem::FastNoise.Editor - Gem::SurfaceData.Editor - Gem::GradientSignal.Editor - Gem::Vegetation.Editor - Gem::GraphModel.Editor - Gem::LandscapeCanvas.Editor - Gem::EMotionFX.Editor - Gem::ImGui.Editor - Gem::Atom_RHI.Private - Gem::Atom_Feature_Common.Editor - Gem::Atom_AtomBridge.Editor - Gem::NvCloth.Editor - Gem::Blast.Editor - Gem::AWSCore.Editor - Gem::AWSClientAuth - Gem::AWSMetrics -) diff --git a/CMakeLists.txt b/CMakeLists.txt index 63177e9d60..34a54d214d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -67,6 +67,7 @@ include(cmake/Deployment.cmake) include(cmake/3rdParty.cmake) include(cmake/LYPython.cmake) include(cmake/LYWrappers.cmake) +include(cmake/Gems.cmake) include(cmake/UnitTest.cmake) include(cmake/LYTestWrappers.cmake) include(cmake/Monolithic.cmake) @@ -128,24 +129,32 @@ foreach(external_directory ${LY_EXTERNAL_SUBDIRS}) endforeach() # The following steps have to be done after all targets are registered: -# 1. generate a settings registry .setreg file for all ly_add_project_dependencies() and ly_add_target_dependencies() calls +# 1. Add any dependencies registered via ly_enable_gems +ly_enable_gems_delayed() + +# 2. generate a settings registry .setreg file for all ly_add_project_dependencies() and ly_add_target_dependencies() calls # to provide applications with the filenames of gem modules to load # This must be done before ly_delayed_target_link_libraries() as that inserts BUILD_DEPENDENCIES as MANUALLY_ADDED_DEPENDENCIES # if the build dependency is a MODULE_LIBRARY. That would cause a false load dependency to be generated ly_delayed_generate_settings_registry() -# 2. link targets where the dependency was yet not declared, we need to have the declaration so we do different + +# 3. link targets where the dependency was yet not declared, we need to have the declaration so we do different # linking logic depending on the type of target ly_delayed_target_link_libraries() -# 3. generate a registry file for unit testing for platforms that support unit testing + +# 4. generate a registry file for unit testing for platforms that support unit testing if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_delayed_generate_unit_test_module_registry() endif() -# 4. inject runtime dependencies to the targets. We need to do this after (1) since we are going to walk through + +# 5. inject runtime dependencies to the targets. We need to do this after (1) since we are going to walk through # the dependencies include(cmake/RuntimeDependencies.cmake) -# 5. Perform test impact framework post steps once all of the targets have been enumerated + +# 6. Perform test impact framework post steps once all of the targets have been enumerated ly_test_impact_post_step() -# 6. Generate the O3DE find file and setup install locations for scripts, tools, assets etc., required by the engine + +# 7. Generate the O3DE find file and setup install locations for scripts, tools, assets etc., required by the engine if(NOT INSTALLED_ENGINE) ly_setup_o3de_install() diff --git a/Gems/AWSClientAuth/Code/CMakeLists.txt b/Gems/AWSClientAuth/Code/CMakeLists.txt index e9f2a4ed84..a1f6f0ca59 100644 --- a/Gems/AWSClientAuth/Code/CMakeLists.txt +++ b/Gems/AWSClientAuth/Code/CMakeLists.txt @@ -51,6 +51,10 @@ ly_add_target( Gem::AWSClientAuth.Static ) +# servers and clients use the above module. +ly_create_alias(NAME AWSClientAuth.Servers NAMESPACE Gem TARGETS Gem::AWSClientAuth) +ly_create_alias(NAME AWSClientAuth.Clients NAMESPACE Gem TARGETS Gem::AWSClientAuth) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/AWSCore/Code/CMakeLists.txt b/Gems/AWSCore/Code/CMakeLists.txt index a58b02d1d4..46046c0791 100644 --- a/Gems/AWSCore/Code/CMakeLists.txt +++ b/Gems/AWSCore/Code/CMakeLists.txt @@ -45,6 +45,10 @@ ly_add_target( Gem::AWSCore.Static ) +# clients and servers will use the above Gem::AWSCore module. +ly_create_alias(NAME AWSCore.Servers NAMESPACE Gem TARGETS Gem::AWSCore) +ly_create_alias(NAME AWSCore.Clients NAMESPACE Gem TARGETS Gem::AWSCore) + if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME AWSCore.Editor.Static STATIC @@ -99,6 +103,11 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Gem::AWSCore.Editor.Static ) ly_add_dependencies(AWSCore.Editor AWSCore.ResourceMappingTool) + + # Builders and Tools (such as the Editor use AWSCore.Editor) use the .Editor module above. + ly_create_alias(NAME AWSCore.Tools NAMESPACE Gem TARGETS Gem::AWSCore.Editor) + ly_create_alias(NAME AWSCore.Builders NAMESPACE Gem TARGETS Gem::AWSCore.Editor) + endif() ################################################################################ diff --git a/Gems/AWSMetrics/Code/CMakeLists.txt b/Gems/AWSMetrics/Code/CMakeLists.txt index ffa9ac0408..413baf28ed 100644 --- a/Gems/AWSMetrics/Code/CMakeLists.txt +++ b/Gems/AWSMetrics/Code/CMakeLists.txt @@ -44,6 +44,10 @@ ly_add_target( Gem::AWSMetrics.Static ) +# Servers and Clients use the above metrics module +ly_create_alias(NAME AWSMetrics.Servers NAMESPACE Gem TARGETS Gem::AWSMetrics) +ly_create_alias(NAME AWSMetrics.Clients NAMESPACE Gem TARGETS Gem::AWSMetrics) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/Achievements/Code/CMakeLists.txt b/Gems/Achievements/Code/CMakeLists.txt index b49409bd5e..4b2aa07dab 100644 --- a/Gems/Achievements/Code/CMakeLists.txt +++ b/Gems/Achievements/Code/CMakeLists.txt @@ -44,3 +44,6 @@ ly_add_target( PRIVATE Gem::Achievements.Static ) + +# we'll load the above "Gem::Achievements" module in clients only. +ly_create_alias(NAME Achievements.Clients NAMESPACE Gem TARGETS Gem::Achievements) diff --git a/Gems/AssetMemoryAnalyzer/Code/CMakeLists.txt b/Gems/AssetMemoryAnalyzer/Code/CMakeLists.txt index df97feaa3f..bdf76eca60 100644 --- a/Gems/AssetMemoryAnalyzer/Code/CMakeLists.txt +++ b/Gems/AssetMemoryAnalyzer/Code/CMakeLists.txt @@ -43,6 +43,10 @@ ly_add_target( Gem::ImGui ) +# AssetMemoryAnalyzer is available in clients and servers. +ly_create_alias(NAME AssetMemoryAnalyzer.Clients NAMESPACE Gem TARGETS Gem::AssetMemoryAnalyzer) +ly_create_alias(NAME AssetMemoryAnalyzer.Servers NAMESPACE Gem TARGETS Gem::AssetMemoryAnalyzer) + ################################################################################ # Tests ################################################################################ @@ -65,3 +69,4 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) NAME Gem::AssetMemoryAnalyzer.Tests ) endif() + diff --git a/Gems/AssetValidation/Code/CMakeLists.txt b/Gems/AssetValidation/Code/CMakeLists.txt index 983ddd9e9d..f62baf57f5 100644 --- a/Gems/AssetValidation/Code/CMakeLists.txt +++ b/Gems/AssetValidation/Code/CMakeLists.txt @@ -65,3 +65,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) NAME Gem::AssetValidation.Tests ) endif() + +# AssetValidation should be active in all clients plus tools +ly_create_alias(NAME AssetValidation.Clients NAMESPACE Gem TARGETS Gem::AssetValidation) +ly_create_alias(NAME AssetValidation.Tools NAMESPACE Gem TARGETS Gem::AssetValidation) + diff --git a/Gems/AudioEngineWwise/Code/CMakeLists.txt b/Gems/AudioEngineWwise/Code/CMakeLists.txt index 5ea6a6d461..41b8c8298e 100644 --- a/Gems/AudioEngineWwise/Code/CMakeLists.txt +++ b/Gems/AudioEngineWwise/Code/CMakeLists.txt @@ -93,6 +93,9 @@ ly_add_target( Gem::AudioEngineWwise.Static ) +# we'll load the above "Gem::AudioEngineWwise" module in clients. +ly_create_alias(NAME AudioEngineWwise.Clients NAMESPACE Gem TARGETS Gem::AudioEngineWwise) + ################################################################################ # Tests ################################################################################ @@ -230,6 +233,10 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Gem::AudioSystem.Editor ) + # by default, we'll load the above "Gem::AudioEngineWwise.Editor" module in builders and tools. + ly_create_alias(NAME AudioEngineWwise.Builders NAMESPACE Gem TARGETS Gem::AudioEngineWwise.Editor) + ly_create_alias(NAME AudioEngineWwise.Tools NAMESPACE Gem TARGETS Gem::AudioEngineWwise.Editor) + if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_target( NAME AudioEngineWwise.Editor.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} diff --git a/Gems/AudioSystem/Code/CMakeLists.txt b/Gems/AudioSystem/Code/CMakeLists.txt index 8a6f2c417e..dfb80a15d5 100644 --- a/Gems/AudioSystem/Code/CMakeLists.txt +++ b/Gems/AudioSystem/Code/CMakeLists.txt @@ -61,22 +61,8 @@ ly_add_target( Gem::AudioSystem.Static ) -################################################################################ -# Server -################################################################################ -if (PAL_TRAIT_BUILD_SERVER_SUPPORTED) - # Stub gem for server. Audio system is client only - ly_add_target( - NAME AudioSystem.Server GEM_MODULE - - NAMESPACE Gem - FILES_CMAKE - audiosystem_stub_files.cmake - BUILD_DEPENDENCIES - PRIVATE - AZ::AzCore - ) -endif () +# AudioSystem should use the above target on clients. +ly_create_alias(NAME AudioSystem.Clients NAMESPACE Gem TARGETS Gem::AudioSystem) ################################################################################ # Tests @@ -230,6 +216,10 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Gem::AudioSystem.Editor.Static ) + # use the above "Editor" target in tools and builders: + ly_create_alias(NAME AssetMemoryAnalyzer.Tools NAMESPACE Gem TARGETS Gem::AudioSystem.Editor) + ly_create_alias(NAME AssetMemoryAnalyzer.Builders NAMESPACE Gem TARGETS Gem::AudioSystem.Editor) + if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_target( NAME AudioSystem.Editor.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} @@ -253,3 +243,6 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) ) endif() endif () + + + diff --git a/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt b/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt index 551f76da02..6215ae7697 100644 --- a/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt +++ b/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt @@ -42,3 +42,7 @@ ly_add_target( RUNTIME_DEPENDENCIES Gem::LmbrCentral ) + +# servers and clients use the above module. +ly_create_alias(NAME AutomatedLauncherTesting.Servers NAMESPACE Gem TARGETS Gem::AutomatedLauncherTesting) +ly_create_alias(NAME AutomatedLauncherTesting.Clients NAMESPACE Gem TARGETS Gem::AutomatedLauncherTesting) diff --git a/Gems/Blast/Code/CMakeLists.txt b/Gems/Blast/Code/CMakeLists.txt index 6c90357364..143e3af095 100644 --- a/Gems/Blast/Code/CMakeLists.txt +++ b/Gems/Blast/Code/CMakeLists.txt @@ -59,6 +59,11 @@ ly_add_target( Gem::PhysX ) +# clients and servers use the above Gem module. +ly_create_alias(NAME Blast.Servers NAMESPACE Gem TARGETS Gem::Blast) +ly_create_alias(NAME Blast.Clients NAMESPACE Gem TARGETS Gem::Blast) + + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( @@ -110,6 +115,9 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::PhysX.Editor ) + # tools and builders use the above module. + ly_create_alias(NAME Blast.Tools NAMESPACE Gem TARGETS Gem::Blast.Editor) + ly_create_alias(NAME Blast.Builders NAMESPACE Gem TARGETS Gem::Blast.Editor) endif() ################################################################################ diff --git a/Gems/Camera/Code/CMakeLists.txt b/Gems/Camera/Code/CMakeLists.txt index 950ff451ff..703424416b 100644 --- a/Gems/Camera/Code/CMakeLists.txt +++ b/Gems/Camera/Code/CMakeLists.txt @@ -39,6 +39,10 @@ ly_add_target( Gem::Camera.Static ) +# clients and servers use the above module: +ly_create_alias(NAME Camera.Clients NAMESPACE Gem TARGETS Gem::Camera) +ly_create_alias(NAME Camera.Servers NAMESPACE Gem TARGETS Gem::Camera) + if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( @@ -62,4 +66,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Gem::Camera.Static ) + # tools and builders use the above module. + ly_create_alias(NAME Camera.Tools NAMESPACE Gem TARGETS Gem::Camera.Editor) + ly_create_alias(NAME Camera.Builders NAMESPACE Gem TARGETS Gem::Camera.Editor) endif() diff --git a/Gems/CameraFramework/Code/CMakeLists.txt b/Gems/CameraFramework/Code/CMakeLists.txt index 1ec9dc0ad9..6b0d084e28 100644 --- a/Gems/CameraFramework/Code/CMakeLists.txt +++ b/Gems/CameraFramework/Code/CMakeLists.txt @@ -38,3 +38,9 @@ ly_add_target( PRIVATE Gem::CameraFramework.Static ) + +# Every kind of application uses the above target module. +ly_create_alias(NAME CameraFramework.Clients NAMESPACE Gem TARGETS Gem::CameraFramework) +ly_create_alias(NAME CameraFramework.Servers NAMESPACE Gem TARGETS Gem::CameraFramework) +ly_create_alias(NAME CameraFramework.Tools NAMESPACE Gem TARGETS Gem::CameraFramework) +ly_create_alias(NAME CameraFramework.Builders NAMESPACE Gem TARGETS Gem::CameraFramework) diff --git a/Gems/CertificateManager/Code/CMakeLists.txt b/Gems/CertificateManager/Code/CMakeLists.txt index 93e78bb86a..2307ebed40 100644 --- a/Gems/CertificateManager/Code/CMakeLists.txt +++ b/Gems/CertificateManager/Code/CMakeLists.txt @@ -41,3 +41,7 @@ ly_add_target( PRIVATE Gem::CertificateManager.Static ) + +# we'll load the above "Gem::CertificateManager" module in Clients and Servers +ly_create_alias(NAME CertificateManager.Clients NAMESPACE Gem TARGETS Gem::CertificateManager) +ly_create_alias(NAME CertificateManager.Servers NAMESPACE Gem TARGETS Gem::CertificateManager) diff --git a/Gems/CrashReporting/Code/CMakeLists.txt b/Gems/CrashReporting/Code/CMakeLists.txt index d52600ea9b..2d77d563d9 100644 --- a/Gems/CrashReporting/Code/CMakeLists.txt +++ b/Gems/CrashReporting/Code/CMakeLists.txt @@ -33,6 +33,11 @@ ly_add_target( AZ::CrashHandler ) +# Load the "Gem::CrashReporting" module in Clients and Servers +ly_create_alias(NAME CrashReporting.Clients NAMESPACE Gem TARGETS Gem::CrashReporting) +ly_create_alias(NAME CrashReporting.Servers NAMESPACE Gem TARGETS Gem::CrashReporting) + + ly_add_target( NAME CrashReporting.Uploader APPLICATION NAMESPACE AZ diff --git a/Gems/CustomAssetExample/Code/CMakeLists.txt b/Gems/CustomAssetExample/Code/CMakeLists.txt index 661b1950ce..3debe27919 100644 --- a/Gems/CustomAssetExample/Code/CMakeLists.txt +++ b/Gems/CustomAssetExample/Code/CMakeLists.txt @@ -22,6 +22,10 @@ ly_add_target( AZ::AzCore ) +# clients and servers use the above module. +ly_create_alias(NAME CustomAssetExample.Clients NAMESPACE Gem TARGETS CustomAssetExample) +ly_create_alias(NAME CustomAssetExample.Servers NAMESPACE Gem TARGETS CustomAssetExample) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME CustomAssetExample.Editor GEM_MODULE @@ -37,4 +41,9 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AzCore AZ::AssetBuilderSDK ) + + # other tools use the above tools module: + ly_create_alias(NAME CustomAssetExample.Builders NAMESPACE Gem TARGETS CustomAssetExample.Editor) + ly_create_alias(NAME CustomAssetExample.Tools NAMESPACE Gem TARGETS CustomAssetExample.Editor) + endif() diff --git a/Gems/DebugDraw/Code/CMakeLists.txt b/Gems/DebugDraw/Code/CMakeLists.txt index 5759cdaff2..44a1c15d7d 100644 --- a/Gems/DebugDraw/Code/CMakeLists.txt +++ b/Gems/DebugDraw/Code/CMakeLists.txt @@ -39,6 +39,9 @@ ly_add_target( Gem::DebugDraw.Static ) +# servers do not need debug draw components, only clients +ly_create_alias(NAME DebugDraw.Clients NAMESPACE Gem TARGETS DebugDraw) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME DebugDraw.Editor GEM_MODULE @@ -56,4 +59,9 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::DebugDraw.Static AZ::AzToolsFramework ) + + # builders and tools use DebugDraw.Editor + ly_create_alias(NAME DebugDraw.Builders NAMESPACE Gem TARGETS DebugDraw.Editor) + ly_create_alias(NAME DebugDraw.Tools NAMESPACE Gem TARGETS DebugDraw.Editor) + endif() diff --git a/Gems/EMotionFX/Code/CMakeLists.txt b/Gems/EMotionFX/Code/CMakeLists.txt index b90902a948..1bfc45babc 100644 --- a/Gems/EMotionFX/Code/CMakeLists.txt +++ b/Gems/EMotionFX/Code/CMakeLists.txt @@ -67,6 +67,10 @@ ly_add_target( Gem::LmbrCentral ) +# Clients and servers use the above EMotionFX module +ly_create_alias(NAME EMotionFX.Clients NAMESPACE Gem TARGETS EMotionFX) +ly_create_alias(NAME EMotionFX.Servers NAMESPACE Gem TARGETS EMotionFX) + if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( @@ -129,6 +133,11 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor ) + + # builders and tools use the above EMotionFX.Editor module + ly_create_alias(NAME EMotionFX.Builders NAMESPACE Gem TARGETS EMotionFX.Editor) + ly_create_alias(NAME EMotionFX.Tools NAMESPACE Gem TARGETS EMotionFX.Editor) + endif() ################################################################################ diff --git a/Gems/EditorPythonBindings/Code/CMakeLists.txt b/Gems/EditorPythonBindings/Code/CMakeLists.txt index 3a34a8491d..a8d4382b45 100644 --- a/Gems/EditorPythonBindings/Code/CMakeLists.txt +++ b/Gems/EditorPythonBindings/Code/CMakeLists.txt @@ -64,6 +64,10 @@ ly_add_target( Gem::EditorPythonBindings.Static ) +# builders and tools use EditorPythonBindings.Editor +ly_create_alias(NAME EditorPythonBindings.Builders NAMESPACE Gem TARGETS EditorPythonBindings.Editor) +ly_create_alias(NAME EditorPythonBindings.Tools NAMESPACE Gem TARGETS EditorPythonBindings.Editor) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/ExpressionEvaluation/Code/CMakeLists.txt b/Gems/ExpressionEvaluation/Code/CMakeLists.txt index 563e3f3341..456129f05d 100644 --- a/Gems/ExpressionEvaluation/Code/CMakeLists.txt +++ b/Gems/ExpressionEvaluation/Code/CMakeLists.txt @@ -41,6 +41,12 @@ ly_add_target( Gem::ExpressionEvaluation.Static ) +# all types of applications use the above module +ly_create_alias(NAME ExpressionEvaluation.Clients NAMESPACE Gem TARGETS ExpressionEvaluation) +ly_create_alias(NAME ExpressionEvaluation.Servers NAMESPACE Gem TARGETS ExpressionEvaluation) +ly_create_alias(NAME ExpressionEvaluation.Builders NAMESPACE Gem TARGETS ExpressionEvaluation) +ly_create_alias(NAME ExpressionEvaluation.Tools NAMESPACE Gem TARGETS ExpressionEvaluation) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/FastNoise/Code/CMakeLists.txt b/Gems/FastNoise/Code/CMakeLists.txt index a49126303a..ac1343844d 100644 --- a/Gems/FastNoise/Code/CMakeLists.txt +++ b/Gems/FastNoise/Code/CMakeLists.txt @@ -42,6 +42,10 @@ ly_add_target( Gem::GradientSignal ) +# Clients and Servers use the above module +ly_create_alias(NAME FastNoise.Clients NAMESPACE Gem TARGETS FastNoise) +ly_create_alias(NAME FastNoise.Servers NAMESPACE Gem TARGETS FastNoise) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME FastNoise.Editor.Static STATIC @@ -81,6 +85,12 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::LmbrCentral.Editor Gem::SurfaceData.Editor ) + + # builders and tools load the above tool module. + ly_create_alias(NAME FastNoise.Builders NAMESPACE Gem TARGETS FastNoise.Editor) + ly_create_alias(NAME FastNoise.Tools NAMESPACE Gem TARGETS FastNoise.Editor) + + endif() ################################################################################ diff --git a/Gems/GameState/Code/CMakeLists.txt b/Gems/GameState/Code/CMakeLists.txt index d57cf8feed..828dfcbb35 100644 --- a/Gems/GameState/Code/CMakeLists.txt +++ b/Gems/GameState/Code/CMakeLists.txt @@ -40,6 +40,10 @@ ly_add_target( Gem::GameState.Static ) +# Clients and Servers use the above module. There is no editor or tools module required. +ly_create_alias(NAME GameState.Clients NAMESPACE Gem TARGETS GameState) +ly_create_alias(NAME GameState.Servers NAMESPACE Gem TARGETS GameState) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/GameStateSamples/Code/CMakeLists.txt b/Gems/GameStateSamples/Code/CMakeLists.txt index e3ebc25016..2199a6689b 100644 --- a/Gems/GameStateSamples/Code/CMakeLists.txt +++ b/Gems/GameStateSamples/Code/CMakeLists.txt @@ -45,3 +45,7 @@ ly_add_target( Gem::LmbrCentral Gem::GameStateSamples.Headers ) + +# Clients and Servers use the above module. There is no editor or tools module required. +ly_create_alias(NAME GameStateSamples.Clients NAMESPACE Gem TARGETS GameStateSamples) +ly_create_alias(NAME GameStateSamples.Servers NAMESPACE Gem TARGETS GameStateSamples) diff --git a/Gems/Gestures/Code/CMakeLists.txt b/Gems/Gestures/Code/CMakeLists.txt index 677886c0ed..8c4ec5ad55 100644 --- a/Gems/Gestures/Code/CMakeLists.txt +++ b/Gems/Gestures/Code/CMakeLists.txt @@ -43,6 +43,12 @@ ly_add_target( Gem::Gestures.Static ) +# All types of applications use the same module. +ly_create_alias(NAME Gestures.Clients NAMESPACE Gem TARGETS Gestures) +ly_create_alias(NAME Gestures.Servers NAMESPACE Gem TARGETS Gestures) +ly_create_alias(NAME Gestures.Builders NAMESPACE Gem TARGETS Gestures) +ly_create_alias(NAME Gestures.Tools NAMESPACE Gem TARGETS Gestures) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/GradientSignal/Code/CMakeLists.txt b/Gems/GradientSignal/Code/CMakeLists.txt index 7b8c9813e6..ed56797c7e 100644 --- a/Gems/GradientSignal/Code/CMakeLists.txt +++ b/Gems/GradientSignal/Code/CMakeLists.txt @@ -47,6 +47,10 @@ ly_add_target( Gem::SurfaceData ) +# Load the "Gem::GradientSignal" module in Clients and Servers +ly_create_alias(NAME GradientSignal.Clients NAMESPACE Gem TARGETS Gem::GradientSignal) +ly_create_alias(NAME GradientSignal.Servers NAMESPACE Gem TARGETS Gem::GradientSignal) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( @@ -92,6 +96,11 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::SurfaceData.Editor ) + # Load the "Gem::GradientSignal.Editor" module in Builders and Tools + ly_create_alias(NAME GradientSignal.Builders NAMESPACE Gem TARGETS Gem::GradientSignal.Editor) + ly_create_alias(NAME GradientSignal.Tools NAMESPACE Gem TARGETS Gem::GradientSignal.Editor) + + endif() ################################################################################ diff --git a/Gems/GraphCanvas/Code/CMakeLists.txt b/Gems/GraphCanvas/Code/CMakeLists.txt index 683b0e4bdf..537588957e 100644 --- a/Gems/GraphCanvas/Code/CMakeLists.txt +++ b/Gems/GraphCanvas/Code/CMakeLists.txt @@ -75,4 +75,10 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) 3rdParty::Qt::Xml AZ::AzQtComponents ) + + # Load the "Gem::GraphCanvas" module in Builders and Tools + ly_create_alias(NAME GraphCanvas.Builders NAMESPACE Gem TARGETS Gem::GraphCanvas.Editor) + ly_create_alias(NAME GraphCanvas.Tools NAMESPACE Gem TARGETS Gem::GraphCanvas.Editor) + + endif () diff --git a/Gems/GraphModel/Code/CMakeLists.txt b/Gems/GraphModel/Code/CMakeLists.txt index 2c4fc57252..86141140ee 100644 --- a/Gems/GraphModel/Code/CMakeLists.txt +++ b/Gems/GraphModel/Code/CMakeLists.txt @@ -52,6 +52,11 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) RUNTIME_DEPENDENCIES Gem::GraphCanvas.Editor ) + + # Load the "Gem::GraphModel" module in Builders and Tools + ly_create_alias(NAME GraphModel.Builders NAMESPACE Gem TARGETS Gem::GraphModel.Editor) + ly_create_alias(NAME GraphModel.Tools NAMESPACE Gem TARGETS Gem::GraphModel.Editor) + endif() ################################################################################ diff --git a/Gems/HttpRequestor/Code/CMakeLists.txt b/Gems/HttpRequestor/Code/CMakeLists.txt index 71181f9ff4..bfbc4305b0 100644 --- a/Gems/HttpRequestor/Code/CMakeLists.txt +++ b/Gems/HttpRequestor/Code/CMakeLists.txt @@ -48,6 +48,12 @@ ly_add_target( Gem::HttpRequestor.Static ) +# Load the "Gem::HttpRequestor" module in all types of applicatons. +ly_create_alias(NAME HttpRequestor.Clients NAMESPACE Gem TARGETS Gem::HttpRequestor) +ly_create_alias(NAME HttpRequestor.Servers NAMESPACE Gem TARGETS Gem::HttpRequestor) +ly_create_alias(NAME HttpRequestor.Builders NAMESPACE Gem TARGETS Gem::HttpRequestor) +ly_create_alias(NAME HttpRequestor.Tools NAMESPACE Gem TARGETS Gem::HttpRequestor) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/ImGui/Code/CMakeLists.txt b/Gems/ImGui/Code/CMakeLists.txt index 2f7d6c6ce7..c3a324b61c 100644 --- a/Gems/ImGui/Code/CMakeLists.txt +++ b/Gems/ImGui/Code/CMakeLists.txt @@ -90,6 +90,10 @@ ly_add_target( Gem::LmbrCentral ) +# Load the above "Gem::ImGui" module in Clients and Servers: +ly_create_alias(NAME ImGui.Clients NAMESPACE Gem TARGETS Gem::ImGui) +ly_create_alias(NAME ImGui.Servers NAMESPACE Gem TARGETS Gem::ImGui) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME ImGui.Editor GEM_MODULE @@ -113,4 +117,9 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor ) + + # Load the above "Gem::ImGui.Editor" module in only tools and builders. + ly_create_alias(NAME ImGui.Builders NAMESPACE Gem TARGETS Gem::ImGui.Editor) + ly_create_alias(NAME ImGui.Tools NAMESPACE Gem TARGETS Gem::ImGui.Editor) + endif() diff --git a/Gems/InAppPurchases/Code/CMakeLists.txt b/Gems/InAppPurchases/Code/CMakeLists.txt index 61f9839841..889b651838 100644 --- a/Gems/InAppPurchases/Code/CMakeLists.txt +++ b/Gems/InAppPurchases/Code/CMakeLists.txt @@ -43,3 +43,8 @@ ly_add_target( PRIVATE Gem::InAppPurchases.Static ) +# Load the above "Gem::InAppPurchases" module in all app types +ly_create_alias(NAME InAppPurchases.Clients NAMESPACE Gem TARGETS Gem::InAppPurchases) +ly_create_alias(NAME InAppPurchases.Servers NAMESPACE Gem TARGETS Gem::InAppPurchases) +ly_create_alias(NAME InAppPurchases.Builders NAMESPACE Gem TARGETS Gem::InAppPurchases) +ly_create_alias(NAME InAppPurchases.Tools NAMESPACE Gem TARGETS Gem::InAppPurchases) diff --git a/Gems/LandscapeCanvas/Code/CMakeLists.txt b/Gems/LandscapeCanvas/Code/CMakeLists.txt index e8e2fce689..f74445b89e 100644 --- a/Gems/LandscapeCanvas/Code/CMakeLists.txt +++ b/Gems/LandscapeCanvas/Code/CMakeLists.txt @@ -72,6 +72,11 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::SurfaceData.Editor Gem::Vegetation.Editor ) + + # by default, load the above "Gem::LandscapeCanvas.Editor" module in dev applications + ly_create_alias(NAME LandscapeCanvas.Builders NAMESPACE Gem TARGETS Gem::LandscapeCanvas.Editor) + ly_create_alias(NAME LandscapeCanvas.Tools NAMESPACE Gem TARGETS Gem::LandscapeCanvas.Editor) + endif() ################################################################################ diff --git a/Gems/LmbrCentral/Code/CMakeLists.txt b/Gems/LmbrCentral/Code/CMakeLists.txt index c1fbd744e6..4d03d30923 100644 --- a/Gems/LmbrCentral/Code/CMakeLists.txt +++ b/Gems/LmbrCentral/Code/CMakeLists.txt @@ -48,6 +48,11 @@ ly_add_target( Gem::LmbrCentral.Static ) +# by default, load the above "Gem::LmbrCentral" module in Client and Server +ly_create_alias(NAME LmbrCentral.Clients NAMESPACE Gem TARGETS Gem::LmbrCentral) +ly_create_alias(NAME LmbrCentral.Servers NAMESPACE Gem TARGETS Gem::LmbrCentral) + + if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME LmbrCentral.Editor.Static STATIC @@ -102,6 +107,10 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) FILES ${QT_LRELEASE_EXECUTABLE} ) + # by default, load the above "Gem::LmbrCentral.Editor" module in dev tools + ly_create_alias(NAME LmbrCentral.Builders NAMESPACE Gem TARGETS Gem::LmbrCentral.Editor) + ly_create_alias(NAME LmbrCentral.Tools NAMESPACE Gem TARGETS Gem::LmbrCentral.Editor) + endif() ################################################################################ diff --git a/Gems/LocalUser/Code/CMakeLists.txt b/Gems/LocalUser/Code/CMakeLists.txt index 6198d88e15..3f2b513282 100644 --- a/Gems/LocalUser/Code/CMakeLists.txt +++ b/Gems/LocalUser/Code/CMakeLists.txt @@ -43,6 +43,9 @@ ly_add_target( Gem::LocalUser.Static ) +# by default, load the above "Gem::LocalUser" module in client applications +ly_create_alias(NAME LocalUser.Clients NAMESPACE Gem TARGETS Gem::LocalUser) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/LyShine/Code/CMakeLists.txt b/Gems/LyShine/Code/CMakeLists.txt index 732bd1cfd4..9baad008dd 100644 --- a/Gems/LyShine/Code/CMakeLists.txt +++ b/Gems/LyShine/Code/CMakeLists.txt @@ -56,6 +56,9 @@ ly_add_target( Gem::TextureAtlas ) +# by default, load the above "Gem::LyShine" module in Client applications: +ly_create_alias(NAME LyShine.Clients NAMESPACE Gem TARGETS Gem::LyShine) + if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME LyShine.Editor.Static STATIC @@ -123,6 +126,10 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Gem::LmbrCentral.Editor Gem::TextureAtlas ) + + # by default, load the above "Gem::LyShine.Editor" module in dev tools: + ly_create_alias(NAME LyShine.Builders NAMESPACE Gem TARGETS Gem::LyShine.Editor) + ly_create_alias(NAME LyShine.Tools NAMESPACE Gem TARGETS Gem::LyShine.Editor) endif() ################################################################################ diff --git a/Gems/LyShineExamples/Code/CMakeLists.txt b/Gems/LyShineExamples/Code/CMakeLists.txt index 372bfa948b..1eea884f78 100644 --- a/Gems/LyShineExamples/Code/CMakeLists.txt +++ b/Gems/LyShineExamples/Code/CMakeLists.txt @@ -40,3 +40,10 @@ ly_add_target( PRIVATE Gem::LyShineExamples.Static ) + +# if enabled, LyShineExamples is used by all kinds of applications +ly_create_alias(NAME LyShineExamples.Builders NAMESPACE Gem TARGETS Gem::LyShineExamples) +ly_create_alias(NAME LyShineExamples.Tools NAMESPACE Gem TARGETS Gem::LyShineExamples) +ly_create_alias(NAME LyShineExamples.Clients NAMESPACE Gem TARGETS Gem::LyShineExamples) +ly_create_alias(NAME LyShineExamples.Servers NAMESPACE Gem TARGETS Gem::LyShineExamples) + diff --git a/Gems/Maestro/Code/CMakeLists.txt b/Gems/Maestro/Code/CMakeLists.txt index fe58ba03a6..f554094cf2 100644 --- a/Gems/Maestro/Code/CMakeLists.txt +++ b/Gems/Maestro/Code/CMakeLists.txt @@ -44,6 +44,10 @@ ly_add_target( Gem::LmbrCentral ) +# if enabled, "Maestro" module is used for Clients and Servers: +ly_create_alias(NAME Maestro.Clients NAMESPACE Gem TARGETS Gem::Maestro) +ly_create_alias(NAME Maestro.Servers NAMESPACE Gem TARGETS Gem::Maestro) + if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME Maestro.Editor GEM_MODULE @@ -73,6 +77,10 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor ) + # the .Editor variant is used in dev tools: + ly_create_alias(NAME Maestro.Tools NAMESPACE Gem TARGETS Gem::Maestro.Editor) + ly_create_alias(NAME Maestro.Builders NAMESPACE Gem TARGETS Gem::Maestro.Editor) + endif() ################################################################################ diff --git a/Gems/MessagePopup/Code/CMakeLists.txt b/Gems/MessagePopup/Code/CMakeLists.txt index 2d0ad1ebcc..fa89b61f21 100644 --- a/Gems/MessagePopup/Code/CMakeLists.txt +++ b/Gems/MessagePopup/Code/CMakeLists.txt @@ -38,3 +38,7 @@ ly_add_target( PRIVATE Gem::MessagePopup.Static ) + +# MessagePopup is used only in client applications +ly_create_alias(NAME MessagePopup.Clients NAMESPACE Gem TARGETS Gem::MessagePopup) + diff --git a/Gems/Metastream/Code/CMakeLists.txt b/Gems/Metastream/Code/CMakeLists.txt index 326c21c5a9..95f7746b91 100644 --- a/Gems/Metastream/Code/CMakeLists.txt +++ b/Gems/Metastream/Code/CMakeLists.txt @@ -50,6 +50,11 @@ ly_add_target( Legacy::CryCommon ) +# The above "Metastream" target is used by all types of applications, including dev tools. +ly_create_alias(NAME Metastream.Clients NAMESPACE Gem TARGETS Gem::Metastream) +ly_create_alias(NAME Metastream.Servers NAMESPACE Gem TARGETS Gem::Metastream) +ly_create_alias(NAME Metastream.Builders NAMESPACE Gem TARGETS Gem::Metastream) +ly_create_alias(NAME Metastream.Tools NAMESPACE Gem TARGETS Gem::Metastream) ################################################################################ # Tests diff --git a/Gems/Microphone/Code/CMakeLists.txt b/Gems/Microphone/Code/CMakeLists.txt index 942899735c..17d492d786 100644 --- a/Gems/Microphone/Code/CMakeLists.txt +++ b/Gems/Microphone/Code/CMakeLists.txt @@ -46,3 +46,7 @@ ly_add_target( RUNTIME_DEPENDENCIES Gem::AudioSystem ) + +# The above "Microphone" target is used by all interactive applications +ly_create_alias(NAME Microphone.Clients NAMESPACE Gem TARGETS Gem::Microphone) +ly_create_alias(NAME Microphone.Tools NAMESPACE Gem TARGETS Gem::Microphone) diff --git a/Gems/Multiplayer/Code/CMakeLists.txt b/Gems/Multiplayer/Code/CMakeLists.txt index 019f341d0c..84a1cf7546 100644 --- a/Gems/Multiplayer/Code/CMakeLists.txt +++ b/Gems/Multiplayer/Code/CMakeLists.txt @@ -58,6 +58,33 @@ ly_add_target( Gem::CertificateManager ) +ly_add_target( + NAME Multiplayer.Debug ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} + NAMESPACE Gem + FILES_CMAKE + multiplayer_debug_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Source + . + PUBLIC + Include + BUILD_DEPENDENCIES + PRIVATE + AZ::AzCore + AZ::AtomCore + AZ::AzFramework + AZ::AzNetworking + Gem::Atom_Feature_Common.Static + Gem::Multiplayer.Static + Gem::ImGui.Static +) + +# The above "Multiplayer" target is used by clients and servers +# the debug is only used on Clients +ly_create_alias(NAME Multiplayer.Clients NAMESPACE Gem TARGETS Gem::Multiplayer Gem::Multiplayer.Debug) +ly_create_alias(NAME Multiplayer.Servers NAMESPACE Gem TARGETS Gem::Multiplayer) + if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME Multiplayer.Tools.Static STATIC @@ -124,6 +151,10 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Gem::Multiplayer.Tools ) + # use the Multiplayer.Editor module in tools and builders. Tools also get the visual debug view + ly_create_alias(NAME Multiplayer.Tools NAMESPACE Gem TARGETS Gem::Multiplayer.Editor Gem::Multiplayer.Debug Gem::Multiplayer.PrefabProcessor) + ly_create_alias(NAME Multiplayer.Builders NAMESPACE Gem TARGETS Gem::Multiplayer.Editor Gem::Multiplayer.PrefabProcessor) + endif() if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) @@ -173,25 +204,3 @@ if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) endif() endif() - -ly_add_target( - NAME Multiplayer.Debug ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} - NAMESPACE Gem - FILES_CMAKE - multiplayer_debug_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Source - . - PUBLIC - Include - BUILD_DEPENDENCIES - PRIVATE - AZ::AzCore - AZ::AtomCore - AZ::AzFramework - AZ::AzNetworking - Gem::Atom_Feature_Common.Static - Gem::Multiplayer.Static - Gem::ImGui.Static -) diff --git a/Gems/MultiplayerCompression/Code/CMakeLists.txt b/Gems/MultiplayerCompression/Code/CMakeLists.txt index 58ce546543..acc7978e88 100644 --- a/Gems/MultiplayerCompression/Code/CMakeLists.txt +++ b/Gems/MultiplayerCompression/Code/CMakeLists.txt @@ -39,6 +39,11 @@ ly_add_target( Gem::MultiplayerCompression.Static ) +# use the MultiplayerCompression module everywhere except builders: +ly_create_alias(NAME MultiplayerCompression.Clients NAMESPACE Gem TARGETS Gem::MultiplayerCompression) +ly_create_alias(NAME MultiplayerCompression.Tools NAMESPACE Gem TARGETS Gem::MultiplayerCompression) +ly_create_alias(NAME MultiplayerCompression.Servers NAMESPACE Gem TARGETS Gem::MultiplayerCompression) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/NvCloth/Code/CMakeLists.txt b/Gems/NvCloth/Code/CMakeLists.txt index 0f019a985f..d7eaf80b16 100644 --- a/Gems/NvCloth/Code/CMakeLists.txt +++ b/Gems/NvCloth/Code/CMakeLists.txt @@ -56,6 +56,10 @@ ly_add_target( Gem::AtomLyIntegration_CommonFeatures ) +# use the NvCloth module in clients and servers: +ly_create_alias(NAME NvCloth.Clients NAMESPACE Gem TARGETS Gem::NvCloth) +ly_create_alias(NAME NvCloth.Servers NAMESPACE Gem TARGETS Gem::NvCloth) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME NvCloth.Editor.Static STATIC @@ -97,6 +101,10 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) RUNTIME_DEPENDENCIES Gem::AtomLyIntegration_CommonFeatures.Editor ) + + # use the NvCloth.Editor module in dev tools: + ly_create_alias(NAME NvCloth.Builders NAMESPACE Gem TARGETS Gem::NvCloth.Editor) + ly_create_alias(NAME NvCloth.Tools NAMESPACE Gem TARGETS Gem::NvCloth.Editor) endif() ################################################################################ diff --git a/Gems/PhysX/Code/CMakeLists.txt b/Gems/PhysX/Code/CMakeLists.txt index b4c7b580a6..7f6fe61be7 100644 --- a/Gems/PhysX/Code/CMakeLists.txt +++ b/Gems/PhysX/Code/CMakeLists.txt @@ -70,6 +70,10 @@ ly_add_target( Gem::LmbrCentral ) +# use the PhysX module in clients and servers: +ly_create_alias(NAME PhysX.Clients NAMESPACE Gem TARGETS Gem::PhysX) +ly_create_alias(NAME PhysX.Servers NAMESPACE Gem TARGETS Gem::PhysX) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_associate_package(PACKAGE_NAME poly2tri-0.3.3-rev2-multiplatform TARGETS poly2tri PACKAGE_HASH 04092d06716f59b936b61906eaf3647db23b685d81d8b66131eb53e0aeaa1a38) @@ -136,6 +140,10 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::LmbrCentral.Editor ) + # use the PhysX.Editor module in dev tools: + ly_create_alias(NAME PhysX.Builders NAMESPACE Gem TARGETS Gem::PhysX.Editor) + ly_create_alias(NAME PhysX.Tools NAMESPACE Gem TARGETS Gem::PhysX.Editor) + endif() ################################################################################ diff --git a/Gems/PhysXDebug/Code/CMakeLists.txt b/Gems/PhysXDebug/Code/CMakeLists.txt index f198f6f26e..55d8044757 100644 --- a/Gems/PhysXDebug/Code/CMakeLists.txt +++ b/Gems/PhysXDebug/Code/CMakeLists.txt @@ -44,6 +44,9 @@ ly_add_target( Gem::PhysX Gem::ImGui ) +# use the PhysXDebug module in Clients and Servers: +ly_create_alias(NAME PhysXDebug.Clients NAMESPACE Gem TARGETS Gem::PhysXDebug) +ly_create_alias(NAME PhysXDebug.Servers NAMESPACE Gem TARGETS Gem::PhysXDebug) if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( @@ -73,4 +76,8 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::PhysX.Editor Gem::ImGui.Editor ) + # use the PhysXDebug.Editor module in dev tools: + ly_create_alias(NAME PhysXDebug.Builders NAMESPACE Gem TARGETS Gem::PhysXDebug.Editor) + ly_create_alias(NAME PhysXDebug.Tools NAMESPACE Gem TARGETS Gem::PhysXDebug.Editor) + endif() diff --git a/Gems/Prefab/PrefabBuilder/CMakeLists.txt b/Gems/Prefab/PrefabBuilder/CMakeLists.txt index 22b89287ca..dbd3c2281b 100644 --- a/Gems/Prefab/PrefabBuilder/CMakeLists.txt +++ b/Gems/Prefab/PrefabBuilder/CMakeLists.txt @@ -38,14 +38,16 @@ ly_add_target( Gem::PrefabBuilder.Static ) -ly_add_target_dependencies( - TARGETS - AssetBuilder - AssetProcessor - AssetProcessorBatch - DEPENDENT_TARGETS - Gem::PrefabBuilder -) +# the prefab builder only needs to be active in builders +# use the PrefabBuilder module in Clients and Servers: +ly_create_alias(NAME PrefabBuilder.Builders NAMESPACE Gem TARGETS Gem::PrefabBuilder) + +# we automatically add this gem, if it is present, to all our known set of builder applications: +ly_enable_gems(GEMS PrefabBuilder VARIANTS Builders TARGETS AssetProcessor AssetProcessorBatch AssetBuilder) + +# if you have a custom builder application in your project, then use ly_enable_gems() to +# add it to that application for your project, like this to make YOUR_TARGET_NAME load it automatically +# ly_enable_gems(PROJECT (YOUR_PROJECT_NAME) GEMS PrefabBuilder VARIANTS Builders TARGETS (YOUR_TARGET_NAME) ) if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_target( diff --git a/Gems/Presence/Code/CMakeLists.txt b/Gems/Presence/Code/CMakeLists.txt index 07780fc8eb..b9db324996 100644 --- a/Gems/Presence/Code/CMakeLists.txt +++ b/Gems/Presence/Code/CMakeLists.txt @@ -44,3 +44,6 @@ ly_add_target( AZ::AzFramework Gem::Presence.Headers ) + +# we activate the presence gem (if enabled) only on client applications such as the launcher: +ly_create_alias(NAME Presence.Clients NAMESPACE Gem TARGETS Gem::Presence) diff --git a/Gems/PythonAssetBuilder/Code/CMakeLists.txt b/Gems/PythonAssetBuilder/Code/CMakeLists.txt index 60af675bc6..4af266f56d 100644 --- a/Gems/PythonAssetBuilder/Code/CMakeLists.txt +++ b/Gems/PythonAssetBuilder/Code/CMakeLists.txt @@ -69,6 +69,11 @@ ly_add_target( Gem::EditorPythonBindings.Editor ) +# the above target is used in both builders like AssetProcessor and Tools like the Editor +# but is not used in clients or servers +ly_create_alias(NAME PythonAssetBuilder.Tools NAMESPACE Gem TARGETS Gem::PythonAssetBuilder.Editor) +ly_create_alias(NAME PythonAssetBuilder.Builders NAMESPACE Gem TARGETS Gem::PythonAssetBuilder.Editor) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/QtForPython/Code/CMakeLists.txt b/Gems/QtForPython/Code/CMakeLists.txt index 74c660043f..c11d93634e 100644 --- a/Gems/QtForPython/Code/CMakeLists.txt +++ b/Gems/QtForPython/Code/CMakeLists.txt @@ -55,3 +55,9 @@ ly_add_target( RUNTIME_DEPENDENCIES Gem::EditorPythonBindings.Editor ) + +# the above target is used in both builders like AssetProcessor and Tools like the Editor +# but is not used in clients or servers +ly_create_alias(NAME QtForPython.Tools NAMESPACE Gem TARGETS Gem::QtForPython.Editor) +ly_create_alias(NAME QtForPython.Builders NAMESPACE Gem TARGETS Gem::QtForPython.Editor) + diff --git a/Gems/RADTelemetry/Code/CMakeLists.txt b/Gems/RADTelemetry/Code/CMakeLists.txt index 78a5561b7c..8b3cc70570 100644 --- a/Gems/RADTelemetry/Code/CMakeLists.txt +++ b/Gems/RADTelemetry/Code/CMakeLists.txt @@ -42,3 +42,8 @@ ly_add_target( PRIVATE Gem::RADTelemetry.Static ) + +# the RADTelemetry module above can be used in all kinds of applications, but we don't enable it in asset builders +ly_create_alias(NAME RADTelemetry.Clients NAMESPACE Gem TARGETS Gem::RADTelemetry) +ly_create_alias(NAME RADTelemetry.Tools NAMESPACE Gem TARGETS Gem::RADTelemetry) +ly_create_alias(NAME RADTelemetry.Servers NAMESPACE Gem TARGETS Gem::RADTelemetry) diff --git a/Gems/SaveData/Code/CMakeLists.txt b/Gems/SaveData/Code/CMakeLists.txt index 46c6e91f58..d9dc62ef03 100644 --- a/Gems/SaveData/Code/CMakeLists.txt +++ b/Gems/SaveData/Code/CMakeLists.txt @@ -46,6 +46,9 @@ ly_add_target( Gem::SaveData.Static ) +# the SaveData module above is only used in Clients by default. +ly_create_alias(NAME SaveData.Clients NAMESPACE Gem TARGETS Gem::SaveData) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/SceneLoggingExample/Code/CMakeLists.txt b/Gems/SceneLoggingExample/Code/CMakeLists.txt index 8cd012c4c2..6370420928 100644 --- a/Gems/SceneLoggingExample/Code/CMakeLists.txt +++ b/Gems/SceneLoggingExample/Code/CMakeLists.txt @@ -40,3 +40,7 @@ ly_add_target( PRIVATE Gem::SceneLoggingExample.Static ) + +# the SceneLoggingExample module above is only used in Builders and Tools by default. +ly_create_alias(NAME SceneLoggingExample.Builders NAMESPACE Gem TARGETS Gem::SceneLoggingExample) +ly_create_alias(NAME SceneLoggingExample.Tools NAMESPACE Gem TARGETS Gem::SceneLoggingExample) diff --git a/Gems/SceneProcessing/Code/CMakeLists.txt b/Gems/SceneProcessing/Code/CMakeLists.txt index 67124a74d5..32c0331f4a 100644 --- a/Gems/SceneProcessing/Code/CMakeLists.txt +++ b/Gems/SceneProcessing/Code/CMakeLists.txt @@ -66,6 +66,10 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) AZ::SceneCore AZ::SceneData ) + # the SceneProcessing.Editor module above is only used in Builders and Tools. + ly_create_alias(NAME SceneProcessing.Builders NAMESPACE Gem TARGETS Gem::SceneProcessing.Editor) + ly_create_alias(NAME SceneProcessing.Tools NAMESPACE Gem TARGETS Gem::SceneProcessing.Editor) + endif() ################################################################################ diff --git a/Gems/ScriptCanvas/Code/CMakeLists.txt b/Gems/ScriptCanvas/Code/CMakeLists.txt index 32efa74520..5c9022182b 100644 --- a/Gems/ScriptCanvas/Code/CMakeLists.txt +++ b/Gems/ScriptCanvas/Code/CMakeLists.txt @@ -49,6 +49,14 @@ ly_add_target( Gem::ScriptEvents.Static ) +# the script canvas debugger is an optional gem module +# To Enable it: ly_enable_gems( ... TARGETS xxxyyzzz GEMS ScriptCanvasDebugger ...) +# in any particular target. +ly_create_alias(NAME ScriptCanvasDebugger.Builders NAMESPACE Gem TARGETS Gem::ScriptCanvasDebugger) +ly_create_alias(NAME ScriptCanvasDebugger.Tools NAMESPACE Gem TARGETS Gem::ScriptCanvasDebugger) +ly_create_alias(NAME ScriptCanvasDebugger.Clients NAMESPACE Gem TARGETS Gem::ScriptCanvasDebugger) +ly_create_alias(NAME ScriptCanvasDebugger.Servers NAMESPACE Gem TARGETS Gem::ScriptCanvasDebugger) + ly_add_target( NAME ScriptCanvas.Static STATIC NAMESPACE Gem @@ -109,6 +117,10 @@ ly_add_target( Gem::ExpressionEvaluation ) +# the "ScriptCanvas" target is active in Clients and Servers +ly_create_alias(NAME ScriptCanvas.Clients NAMESPACE Gem TARGETS Gem::ScriptCanvas) +ly_create_alias(NAME ScriptCanvas.Servers NAMESPACE Gem TARGETS Gem::ScriptCanvas) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME ScriptCanvasEditor STATIC @@ -204,6 +216,12 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::ScriptEvents.Editor Gem::ExpressionEvaluation ) + + # the "ScriptCanvas.Editor" target is active in all dev tools: + ly_create_alias(NAME ScriptCanvas.Builders NAMESPACE Gem TARGETS Gem::ScriptCanvas.Editor) + ly_create_alias(NAME ScriptCanvas.Tools NAMESPACE Gem TARGETS Gem::ScriptCanvas.Editor) + + endif() ################################################################################ diff --git a/Gems/ScriptCanvasDeveloper/Code/CMakeLists.txt b/Gems/ScriptCanvasDeveloper/Code/CMakeLists.txt index d9ce9004d3..1bdbdff12d 100644 --- a/Gems/ScriptCanvasDeveloper/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasDeveloper/Code/CMakeLists.txt @@ -54,6 +54,11 @@ ly_add_target( Gem::ScriptCanvas ) +# By default, the above module is the Client/Server module +ly_create_alias(NAME ScriptCanvasDeveloper.Clients NAMESPACE Gem TARGETS Gem::ScriptCanvasDeveloper) +ly_create_alias(NAME ScriptCanvasDeveloper.Servers NAMESPACE Gem TARGETS Gem::ScriptCanvasDeveloper) + + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME ScriptCanvasDeveloper.Editor GEM_MODULE @@ -82,4 +87,8 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) RUNTIME_DEPENDENCIES Gem::ScriptCanvas.Editor ) + # By Default the above module is the dev tools module + ly_create_alias(NAME ScriptCanvasDeveloper.Builders NAMESPACE Gem TARGETS Gem::ScriptCanvasDeveloper.Editor) + ly_create_alias(NAME ScriptCanvasDeveloper.Tools NAMESPACE Gem TARGETS Gem::ScriptCanvasDeveloper.Editor) + endif() diff --git a/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt b/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt index 23ee6937c7..0c0560e063 100644 --- a/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt @@ -38,6 +38,12 @@ ly_add_target( Gem::ScriptCanvasPhysics.Static ) +# By default, the above module is used by all application types +ly_create_alias(NAME ScriptCanvasPhysics.Clients NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics) +ly_create_alias(NAME ScriptCanvasPhysics.Servers NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics) +ly_create_alias(NAME ScriptCanvasPhysics.Tools NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics) +ly_create_alias(NAME ScriptCanvasPhysics.Builders NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/ScriptCanvasTesting/Code/CMakeLists.txt b/Gems/ScriptCanvasTesting/Code/CMakeLists.txt index 639ef114fc..e3bdbf02e2 100644 --- a/Gems/ScriptCanvasTesting/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasTesting/Code/CMakeLists.txt @@ -73,6 +73,9 @@ ly_add_target( Gem::ScriptCanvas.Editor ) +# By default, the above module is used only in tools: +ly_create_alias(NAME ScriptCanvasTesting.Tools NAMESPACE Gem TARGETS Gem::ScriptCanvasTesting.Editor) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/ScriptEvents/Code/CMakeLists.txt b/Gems/ScriptEvents/Code/CMakeLists.txt index 12f8cfd7b6..6f75e35d71 100644 --- a/Gems/ScriptEvents/Code/CMakeLists.txt +++ b/Gems/ScriptEvents/Code/CMakeLists.txt @@ -40,6 +40,11 @@ ly_add_target( Gem::ScriptEvents.Static ) +# the above module is for use in clients and servers +ly_create_alias(NAME ScriptEvents.Clients NAMESPACE Gem TARGETS Gem::ScriptEvents) +ly_create_alias(NAME ScriptEvents.Servers NAMESPACE Gem TARGETS Gem::ScriptEvents) + + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME ScriptEvents.Editor GEM_MODULE @@ -61,6 +66,10 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AssetBuilderSDK Gem::ScriptEvents.Static ) + + # the above module is for use in dev tools. + ly_create_alias(NAME ScriptEvents.Tools NAMESPACE Gem TARGETS Gem::ScriptEvents.Editor) + ly_create_alias(NAME ScriptEvents.Builders NAMESPACE Gem TARGETS Gem::ScriptEvents.Editor) endif() ################################################################################ diff --git a/Gems/ScriptedEntityTweener/Code/CMakeLists.txt b/Gems/ScriptedEntityTweener/Code/CMakeLists.txt index c5062c84b7..2488057f8c 100644 --- a/Gems/ScriptedEntityTweener/Code/CMakeLists.txt +++ b/Gems/ScriptedEntityTweener/Code/CMakeLists.txt @@ -40,3 +40,9 @@ ly_add_target( AZ::AzCore Legacy::CryCommon ) + +# the above module is for use in all application types: +ly_create_alias(NAME ScriptedEntityTweener.Tools NAMESPACE Gem TARGETS Gem::ScriptedEntityTweener) +ly_create_alias(NAME ScriptedEntityTweener.Clients NAMESPACE Gem TARGETS Gem::ScriptedEntityTweener) +ly_create_alias(NAME ScriptedEntityTweener.Builders NAMESPACE Gem TARGETS Gem::ScriptedEntityTweener) +ly_create_alias(NAME ScriptedEntityTweener.Servers NAMESPACE Gem TARGETS Gem::ScriptedEntityTweener) \ No newline at end of file diff --git a/Gems/SliceFavorites/Code/CMakeLists.txt b/Gems/SliceFavorites/Code/CMakeLists.txt index 4ad89ad6c3..35349c777c 100644 --- a/Gems/SliceFavorites/Code/CMakeLists.txt +++ b/Gems/SliceFavorites/Code/CMakeLists.txt @@ -51,3 +51,6 @@ ly_add_target( 3rdParty::Qt::Core Gem::SliceFavorites.Editor.Static ) + +# the above module is for use in Tools only (no need to load it in builders) +ly_create_alias(NAME SliceFavorites.Tools NAMESPACE Gem TARGETS Gem::SliceFavorites.Editor) \ No newline at end of file diff --git a/Gems/StartingPointCamera/Code/CMakeLists.txt b/Gems/StartingPointCamera/Code/CMakeLists.txt index d6dd1a7038..7bc57476a5 100644 --- a/Gems/StartingPointCamera/Code/CMakeLists.txt +++ b/Gems/StartingPointCamera/Code/CMakeLists.txt @@ -48,3 +48,9 @@ ly_add_target( RUNTIME_DEPENDENCIES Gem::CameraFramework ) + +# the above module is for use in all kinds of applications +ly_create_alias(NAME StartingPointCamera.Servers NAMESPACE Gem TARGETS Gem::StartingPointCamera) +ly_create_alias(NAME StartingPointCamera.Clients NAMESPACE Gem TARGETS Gem::StartingPointCamera) +ly_create_alias(NAME StartingPointCamera.Builders NAMESPACE Gem TARGETS Gem::StartingPointCamera) +ly_create_alias(NAME StartingPointCamera.Tools NAMESPACE Gem TARGETS Gem::StartingPointCamera) diff --git a/Gems/StartingPointInput/Code/CMakeLists.txt b/Gems/StartingPointInput/Code/CMakeLists.txt index 1372a79a78..c6e7fdcb52 100644 --- a/Gems/StartingPointInput/Code/CMakeLists.txt +++ b/Gems/StartingPointInput/Code/CMakeLists.txt @@ -56,6 +56,10 @@ ly_add_source_properties( VALUES ${LY_PAL_TOOLS_DEFINES} ) +# the above module is for use in clients and servers +ly_create_alias(NAME StartingPointInput.Servers NAMESPACE Gem TARGETS Gem::StartingPointInput) +ly_create_alias(NAME StartingPointInput.Clients NAMESPACE Gem TARGETS Gem::StartingPointInput) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME StartingPointInput.Editor GEM_MODULE @@ -74,6 +78,11 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AzFramework Gem::StartingPointInput.Static ) + + # by default, activate the ab ove module in builders and tools: + ly_create_alias(NAME StartingPointInput.Builders NAMESPACE Gem TARGETS Gem::StartingPointInput.Editor) + ly_create_alias(NAME StartingPointInput.Tools NAMESPACE Gem TARGETS Gem::StartingPointInput.Editor) + endif() ################################################################################ diff --git a/Gems/StartingPointMovement/Code/CMakeLists.txt b/Gems/StartingPointMovement/Code/CMakeLists.txt index d6434ccf78..417dfe01ee 100644 --- a/Gems/StartingPointMovement/Code/CMakeLists.txt +++ b/Gems/StartingPointMovement/Code/CMakeLists.txt @@ -40,3 +40,9 @@ ly_add_target( AZ::AzCore AZ::AzFramework ) + +# the above module is for use in all application types (there is no tool specialization) +ly_create_alias(NAME StartingPointMovement.Servers NAMESPACE Gem TARGETS Gem::StartingPointMovement) +ly_create_alias(NAME StartingPointMovement.Clients NAMESPACE Gem TARGETS Gem::StartingPointMovement) +ly_create_alias(NAME StartingPointMovement.Builders NAMESPACE Gem TARGETS Gem::StartingPointMovement) +ly_create_alias(NAME StartingPointMovement.Tools NAMESPACE Gem TARGETS Gem::StartingPointMovement) \ No newline at end of file diff --git a/Gems/SurfaceData/Code/CMakeLists.txt b/Gems/SurfaceData/Code/CMakeLists.txt index de1aa51938..cdc1bbc4f3 100644 --- a/Gems/SurfaceData/Code/CMakeLists.txt +++ b/Gems/SurfaceData/Code/CMakeLists.txt @@ -46,6 +46,10 @@ ly_add_target( Gem::LmbrCentral ) +# the above module is for use in all client/server types +ly_create_alias(NAME SurfaceData.Servers NAMESPACE Gem TARGETS Gem::SurfaceData) +ly_create_alias(NAME SurfaceData.Clients NAMESPACE Gem TARGETS Gem::SurfaceData) + if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( @@ -70,6 +74,9 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor ) + # the above module is for use in dev tool situations + ly_create_alias(NAME SurfaceData.Builders NAMESPACE Gem TARGETS Gem::SurfaceData.Editor) + ly_create_alias(NAME SurfaceData.Tools NAMESPACE Gem TARGETS Gem::SurfaceData.Editor) endif() diff --git a/Gems/TestAssetBuilder/Code/CMakeLists.txt b/Gems/TestAssetBuilder/Code/CMakeLists.txt index dbd2907033..ebd34140aa 100644 --- a/Gems/TestAssetBuilder/Code/CMakeLists.txt +++ b/Gems/TestAssetBuilder/Code/CMakeLists.txt @@ -40,3 +40,6 @@ ly_add_target( PRIVATE Gem::TestAssetBuilder.Static ) + +# the above module is for use in builders only +ly_create_alias(NAME TestAssetBuilder.Builders NAMESPACE Gem TARGETS Gem::TestAssetBuilder.Editor) diff --git a/Gems/TextureAtlas/Code/CMakeLists.txt b/Gems/TextureAtlas/Code/CMakeLists.txt index b7072321dc..8f96ed6593 100644 --- a/Gems/TextureAtlas/Code/CMakeLists.txt +++ b/Gems/TextureAtlas/Code/CMakeLists.txt @@ -22,3 +22,9 @@ ly_add_target( Legacy::CryCommon AZ::AzFramework ) + +# the above module is for use in all application types (there is no tool specialization) +ly_create_alias(NAME TextureAtlas.Servers NAMESPACE Gem TARGETS Gem::TextureAtlas) +ly_create_alias(NAME TextureAtlas.Clients NAMESPACE Gem TARGETS Gem::TextureAtlas) +ly_create_alias(NAME TextureAtlas.Builders NAMESPACE Gem TARGETS Gem::TextureAtlas) +ly_create_alias(NAME TextureAtlas.Tools NAMESPACE Gem TARGETS Gem::TextureAtlas) diff --git a/Gems/TickBusOrderViewer/Code/CMakeLists.txt b/Gems/TickBusOrderViewer/Code/CMakeLists.txt index 3f56a0d554..551c62c64c 100644 --- a/Gems/TickBusOrderViewer/Code/CMakeLists.txt +++ b/Gems/TickBusOrderViewer/Code/CMakeLists.txt @@ -38,3 +38,9 @@ ly_add_target( PRIVATE Gem::TickBusOrderViewer.Static ) + + +# the above module is for use in all application types except builders +ly_create_alias(NAME TickBusOrderViewer.Servers NAMESPACE Gem TARGETS Gem::TickBusOrderViewer) +ly_create_alias(NAME TickBusOrderViewer.Clients NAMESPACE Gem TARGETS Gem::TickBusOrderViewer) +ly_create_alias(NAME TickBusOrderViewer.Tools NAMESPACE Gem TARGETS Gem::TickBusOrderViewer) diff --git a/Gems/Twitch/Code/CMakeLists.txt b/Gems/Twitch/Code/CMakeLists.txt index 14d7a41532..7369f5c7bf 100644 --- a/Gems/Twitch/Code/CMakeLists.txt +++ b/Gems/Twitch/Code/CMakeLists.txt @@ -47,3 +47,9 @@ ly_add_target( RUNTIME_DEPENDENCIES Gem::HttpRequestor ) + +# the above module is for use in all application types except builders +ly_create_alias(NAME Twitch.Servers NAMESPACE Gem TARGETS Gem::Twitch) +ly_create_alias(NAME Twitch.Clients NAMESPACE Gem TARGETS Gem::Twitch) +ly_create_alias(NAME Twitch.Tools NAMESPACE Gem TARGETS Gem::Twitch) + diff --git a/Gems/Vegetation/Code/CMakeLists.txt b/Gems/Vegetation/Code/CMakeLists.txt index c4a003bb4a..3e1cc36e77 100644 --- a/Gems/Vegetation/Code/CMakeLists.txt +++ b/Gems/Vegetation/Code/CMakeLists.txt @@ -51,6 +51,10 @@ ly_add_target( Gem::SurfaceData ) +# the above module is for use in clients and server type applications +ly_create_alias(NAME Vegetation.Servers NAMESPACE Gem TARGETS Gem::Vegetation) +ly_create_alias(NAME Vegetation.Clients NAMESPACE Gem TARGETS Gem::Vegetation) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME Vegetation.Editor GEM_MODULE @@ -75,6 +79,10 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::GradientSignal.Editor Gem::SurfaceData.Editor ) + # the above module is for use in dev tools + ly_create_alias(NAME Vegetation.Builders NAMESPACE Gem TARGETS Gem::Vegetation.Editor) + ly_create_alias(NAME Vegetation.Tools NAMESPACE Gem TARGETS Gem::Vegetation.Editor) + endif() ################################################################################ diff --git a/Gems/VideoPlaybackFramework/Code/CMakeLists.txt b/Gems/VideoPlaybackFramework/Code/CMakeLists.txt index 297f4cfaac..b29fe53216 100644 --- a/Gems/VideoPlaybackFramework/Code/CMakeLists.txt +++ b/Gems/VideoPlaybackFramework/Code/CMakeLists.txt @@ -42,6 +42,11 @@ ly_add_target( Gem::VideoPlaybackFramework.Static ) +# the video playback framework makes sense in everything but servers: +ly_create_alias(NAME VideoPlaybackFramework.Clients NAMESPACE Gem TARGETS Gem::VideoPlaybackFramework) +ly_create_alias(NAME VideoPlaybackFramework.Tools NAMESPACE Gem TARGETS Gem::VideoPlaybackFramework) +ly_create_alias(NAME VideoPlaybackFramework.Builders NAMESPACE Gem TARGETS Gem::VideoPlaybackFramework) + ################################################################################ # Tests ################################################################################ diff --git a/Gems/VirtualGamepad/Code/CMakeLists.txt b/Gems/VirtualGamepad/Code/CMakeLists.txt index 99a33db70b..4311796b57 100644 --- a/Gems/VirtualGamepad/Code/CMakeLists.txt +++ b/Gems/VirtualGamepad/Code/CMakeLists.txt @@ -40,3 +40,8 @@ ly_add_target( PRIVATE Gem::VirtualGamepad.Static ) + +# the virtual gamepad is needed everywhere except servers: +ly_create_alias(NAME VirtualGamepad.Clients NAMESPACE Gem TARGETS Gem::VirtualGamepad) +ly_create_alias(NAME VirtualGamepad.Tools NAMESPACE Gem TARGETS Gem::VirtualGamepad) +ly_create_alias(NAME VirtualGamepad.Builders NAMESPACE Gem TARGETS Gem::VirtualGamepad) diff --git a/Gems/WhiteBox/Code/CMakeLists.txt b/Gems/WhiteBox/Code/CMakeLists.txt index a15a4e150c..5985ff26a3 100644 --- a/Gems/WhiteBox/Code/CMakeLists.txt +++ b/Gems/WhiteBox/Code/CMakeLists.txt @@ -86,6 +86,10 @@ ly_add_target( Gem::WhiteBox.Static ) +# use the above WhiteBox module in runtimes: +ly_create_alias(NAME WhiteBox.Clients NAMESPACE Gem TARGETS Gem::WhiteBox) +ly_create_alias(NAME WhiteBox.Servers NAMESPACE Gem TARGETS Gem::WhiteBox) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME WhiteBox.Editor.Static STATIC @@ -129,6 +133,12 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) PRIVATE Gem::WhiteBox.Editor.Static ) + + # use the above WhiteBox.Editor module in dev tools: + ly_create_alias(NAME WhiteBox.Tools NAMESPACE Gem TARGETS Gem::WhiteBox.Editor) + ly_create_alias(NAME WhiteBox.Builders NAMESPACE Gem TARGETS Gem::WhiteBox.Editor) + + endif() ################################################################################ diff --git a/cmake/Gems.cmake b/cmake/Gems.cmake new file mode 100644 index 0000000000..3e9ce97329 --- /dev/null +++ b/cmake/Gems.cmake @@ -0,0 +1,196 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +# This file contains utility wrappers for dealing with the Gems system. + +# ly_create_alias +# given an alias to create, and a list of one or more targets, +# this creates an alias that depends on all of the given targets. +function(ly_create_alias) + set(options) + set(oneValueArgs NAME NAMESPACE) + set(multiValueArgs TARGETS) + + cmake_parse_arguments(ly_create_alias "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + + if (NOT ly_create_alias_NAME) + message(FATAL_ERROR "Provide the name of the alias to create using the NAME keyword") + endif() + + if (NOT ly_create_alias_NAMESPACE) + message(FATAL_ERROR "Provide the namespace of the alias to create using the NAMESPACE keyword") + endif() + + if (NOT ly_create_alias_TARGETS) + message(FATAL_ERROR "Provide the name of the targets the alias be associated with, using the TARGETS keyword") + endif() + + if(TARGET ${ly_create_alias_NAMESPACE}::${ly_create_alias_NAME}) + message(FATAL_ERROR "Target already exists, cannot create an alias for it: ${ly_create_alias_NAMESPACE}::${ly_create_alias_NAME}\n" + "Make sure the target wasn't copy and pasted here or elsewhere.") + endif() + + # easy version - if its juts one target, we can directly get the target, and make both aliases, + # the namespaced and non namespaced one, point at it. + list(LENGTH ly_create_alias_TARGETS number_of_targets) + if (number_of_targets EQUAL 1) + ly_de_alias_target(${ly_create_alias_TARGETS} de_aliased_target_name) + add_library(${ly_create_alias_NAMESPACE}::${ly_create_alias_NAME} ALIAS ${de_aliased_target_name}) + if (NOT TARGET ${ly_create_alias_NAME}) + add_library(${ly_create_alias_NAME} ALIAS ${de_aliased_target_name}) + endif() + return() + endif() + + # more complex version - one alias to multiple targets. To actually achieve this + # we have to create an interface library with those dependencies, then we have to create an alias to that target. + # by convention we create one without a namespace then alias the namespaced one. + + if(TARGET ${ly_create_alias_NAME}) + message(FATAL_ERROR "Internal alias target already exists, cannot create an alias for it: ${ly_create_alias_NAME}\n" + "This could be a copy-paste error, where some part of the ly_create_alias call was changed but the other") + endif() + + add_library(${ly_create_alias_NAME} INTERFACE IMPORTED) + set_target_properties(${ly_create_alias_NAME} PROPERTIES GEM_MODULE TRUE) + + foreach(target_name ${ly_create_alias_TARGETS}) + ly_de_alias_target(${target_name} de_aliased_target_name) + if(NOT de_aliased_target_name) + message(FATAL_ERROR "Target not found in ly_create_alias call: ${target_name} - check your spelling of the target name") + endif() + list(APPEND final_targets ${de_aliased_target_name}) + endforeach() + + ly_parse_third_party_dependencies("${final_targets}") + ly_add_dependencies(${ly_create_alias_NAME} ${final_targets}) + + # now add the final alias: + add_library(${ly_create_alias_NAMESPACE}::${ly_create_alias_NAME} ALIAS ${ly_create_alias_NAME}) +endfunction() + +# ly_enable_gems +# this function makes sure that the given gems, or gems listed in the variable ENABLED_GEMS +# in the GEM_FILE name, are set as runtime dependencies (and thus loaded) for the given targets +# in the context of the given project. +# note that it can't do this immediately, so it saves the data for later processing. +# Note: If you don't supply a project name, it will apply it across the board to all projects. +# this is useful in the case of "ly_add_gems being called for so called 'mandatory gems' inside the engine. +function(ly_enable_gems) + set(options) + set(oneValueArgs PROJECT_NAME GEM_FILE) + set(multiValueArgs GEMS TARGETS VARIANTS) + + cmake_parse_arguments(ly_enable_gems "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + + if (NOT ly_enable_gems_TARGETS) + message(FATAL_ERROR "You must provide the targets to add gems to using the TARGETS keyword") + endif() + + + if (NOT ly_enable_gems_PROJECT_NAME) + message(VERBOSE "Note: ly_enable_gems called with no PROJECT_NAME name, applying to all projects: \n" + " - VARIANTS ${ly_enable_gems_VARIANTS} \n" + " - GEMS ${ly_enable_gems_GEMS} \n" + " - TARGETS ${ly_enable_gems_TARGETS} \n" + " - GEM_FILE ${ly_enable_gems_GEM_FILE}") + set(ly_enable_gems_PROJECT_NAME "__NOPROJECT__") # so that the token is not blank + endif() + + if (NOT ly_enable_gems_VARIANTS) + message(FATAL_ERROR "You must provide at least 1 variant of the gem modules (Editor, Server, Client, Builder) to " + "add to your targets, using the VARIANTS keyword") + endif() + + if ((NOT ly_enable_gems_GEMS AND NOT ly_enable_gems_GEM_FILE) OR (ly_enable_gems_GEMS AND ly_enable_gems_GEM_FILE)) + message(FATAL_ERROR "Provide exactly one of either GEM_FILE (filename) or GEMS (list of gems) keywords.") + endif() + + if (ly_enable_gems_GEM_FILE) + set(store_temp ${ENABLED_GEMS}) + include(${ly_enable_gems_GEM_FILE} RESULT_VARIABLE was_able_to_load_the_file) + if(NOT was_able_to_load_the_file) + message(FATAL_ERROR "could not load the GEM_FILE ${ly_enable_gems_GEM_FILE}") + endif() + if(NOT ENABLED_GEMS) + message(FATAL_ERROR "GEM_FILE ${ly_enable_gems_GEM_FILE} did not set the value of ENABLED_GEMS.\n" + "Gem Files should contain set(ENABLED_GEMS ... )") + endif() + set(ly_enable_gems_GEMS ${ENABLED_GEMS}) + set(ENABLED_GEMS ${store_temp}) # restore value of ENABLED_GEMS just in case... + endif() + + # all the actual work has to be done later. + foreach(target_name ${ly_enable_gems_TARGETS}) + foreach(variant_name ${ly_enable_gems_VARIANTS}) + set_property(GLOBAL APPEND PROPERTY LY_DELAYED_ENABLE_GEMS "${ly_enable_gems_PROJECT_NAME},${target_name},${variant_name}") + set_property(GLOBAL APPEND PROPERTY LY_DELAYED_ENABLE_GEMS_"${ly_enable_gems_PROJECT_NAME},${target_name},${variant_name}" ${ly_enable_gems_GEMS}) + endforeach() + endforeach() +endfunction() + +# call this before runtime dependencies are used to add any relevant targets +# saved by the above function +function(ly_enable_gems_delayed) + get_property(ly_delayed_enable_gems GLOBAL PROPERTY LY_DELAYED_ENABLE_GEMS) + foreach(project_target_variant ${ly_delayed_enable_gems}) + # we expect a colon seperated list of + # PROJECT_NAME,target_name,variant_name + string(REPLACE "," ";" project_target_variant_list "${project_target_variant}") + list(LENGTH project_target_variant_list project_target_variant_length) + if(project_target_variant_length EQUAL 0) + continue() + endif() + + if(NOT project_target_variant_length EQUAL 3) + message(FATAL_ERROR "Invalid specificaiton of gems, expected 'project','target','variant' and got ${project_target_variant}") + endif() + + list(POP_BACK project_target_variant_list variant) + list(POP_BACK project_target_variant_list target) + list(POP_BACK project_target_variant_list project) + + get_property(gem_dependencies GLOBAL PROPERTY LY_DELAYED_ENABLE_GEMS_"${project_target_variant}") + if (NOT gem_dependencies) + continue() + endif() + + if(${project} STREQUAL "__NOPROJECT__") + # special case, apply to all + unset(PREFIX_CLAUSE) + else() + set(PREFIX_CLAUSE "PREFIX;${project}") + endif() + + if (NOT TARGET ${target}) + message(FATAL_ERROR "ly_enable_gems specified TARGET '${target}' but no such target was found.") + endif() + + # apply the list of gem targets. Adding a gem really just means adding the appropriate dependency. + foreach(gem_name ${gem_dependencies}) + + if (TARGET Gem::${gem_name}.${variant}) + ly_add_target_dependencies( + ${PREFIX_CLAUSE} + TARGETS ${target} + DEPENDENT_TARGETS Gem::${gem_name}.${variant} + ) + elseif(${variant} STREQUAL "Client" AND TARGET Gem::${gem_name}) + # Client can also be 'empty' for backward compatibility + ly_add_target_dependencies( + ${PREFIX_CLAUSE} + TARGETS ${target} + DEPENDENT_TARGETS Gem::${gem_name} + ) + endif() + endforeach() + endforeach() +endfunction() \ No newline at end of file diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index f6a36afc89..b4641e0ff5 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -719,3 +719,20 @@ function(ly_project_add_subdirectory project_name) endif() endif() endfunction() + +# given a target name, returns the "real" name of the target if its an alias. +# this function recursively de-aliases +function(ly_de_alias_target target_name output_variable_name) + # its not okay to call get_target_property on a non-existant target + if (NOT TARGET ${target_name}) + message(FATAL_ERROR "ly_de_alias_target called on non-existant target: ${target_name}") + endif() + + while(target_name) + set(de_aliased_target_name ${target_name}) + + get_target_property(target_name ${target_name} ALIASED_TARGET) + endwhile() + + set(${output_variable_name} ${de_aliased_target_name} PARENT_SCOPE) +endfunction() diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index fd5985a5a1..b89a810f10 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -67,6 +67,7 @@ function(ly_get_gem_load_dependencies ly_GEM_LOAD_DEPENDENCIES ly_TARGET) # Skip wrapping produced when targets are not created in the same directory if(NOT ${load_dependency} MATCHES "^::@") get_property(dependency_type TARGET ${load_dependency} PROPERTY TYPE) + get_property(is_gem_target TARGET ${load_dependency} PROPERTY GEM_MODULE SET) # If the dependency is a "gem module" then add it as a load dependencies # and recurse into its manually added dependencies @@ -91,12 +92,10 @@ endfunction() # This can be used for example to determine which list of gems to load with an application function(ly_delayed_generate_settings_registry) get_property(ly_delayed_load_targets GLOBAL PROPERTY LY_DELAYED_LOAD_DEPENDENCIES) - foreach(prefix_target ${ly_delayed_load_targets}) string(REPLACE "," ";" prefix_target_list "${prefix_target}") list(LENGTH prefix_target_list prefix_target_length) if(prefix_target_length EQUAL 0) - message(SEND_ERROR "Delayed load target is missing target name") continue() endif() @@ -116,6 +115,14 @@ function(ly_delayed_generate_settings_registry) endforeach() list(REMOVE_DUPLICATES all_gem_dependencies) + # de-namespace them + foreach(gem_target ${all_gem_dependencies}) + ly_strip_target_namespace(TARGET ${gem_target} OUTPUT_VARIABLE stripped_gem_target) + list(APPEND new_gem_dependencies ${stripped_gem_target}) + endforeach() + set(all_gem_dependencies ${new_gem_dependencies}) + list(REMOVE_DUPLICATES all_gem_dependencies) + unset(target_gem_dependencies_names) foreach(gem_target ${all_gem_dependencies}) unset(gem_relative_source_dir) @@ -123,6 +130,14 @@ function(ly_delayed_generate_settings_registry) if (NOT TARGET ${gem_target}) message(FATAL_ERROR "Dependency ${gem_target} from ${target} does not exist") endif() + + get_target_property(target_type ${gem_target} TYPE) + if (target_type STREQUAL "INTERFACE_LIBRARY") + # don't use interface libraries here, we only want ones which produce actual binaries. + # we have still already recursed into their dependencies - they'll show up later. + continue() + endif() + get_property(gem_relative_source_dir TARGET ${gem_target} PROPERTY SOURCE_DIR) if(gem_relative_source_dir) # Most gems CMakeLists.txt files reside in the /Code/ so remove "Code/" from the path From 6a7a86062e4335a90c702111ae1837134a145da9 Mon Sep 17 00:00:00 2001 From: lawsonamzn <70027408+lawsonamzn@users.noreply.github.com> Date: Thu, 13 May 2021 14:00:05 -0700 Subject: [PATCH 083/811] Updates AutomatedTesting project and adds atom support --- AutomatedTesting/Gem/Code/CMakeLists.txt | 61 +++++++------------ .../AtomBridge/Code/CMakeLists.txt | 9 +++ Gems/AudioSystem/Code/CMakeLists.txt | 4 +- Gems/Multiplayer/Code/CMakeLists.txt | 1 - 4 files changed, 34 insertions(+), 41 deletions(-) diff --git a/AutomatedTesting/Gem/Code/CMakeLists.txt b/AutomatedTesting/Gem/Code/CMakeLists.txt index e81156c3aa..9315bf8397 100644 --- a/AutomatedTesting/Gem/Code/CMakeLists.txt +++ b/AutomatedTesting/Gem/Code/CMakeLists.txt @@ -32,46 +32,31 @@ ly_add_target( # Gem dependencies ################################################################################ -# The GameLauncher uses "Client" gem variants: +# The GameLauncher uses "Clients" gem variants: ly_enable_gems(PROJECT_NAME AutomatedTesting GEM_FILE enabled_gems.cmake TARGETS AutomatedTesting.GameLauncher VARIANTS Clients) -# The Editor uses Tools gem variants: -ly_enable_gems( - PROJECT_NAME AutomatedTesting GEM_FILE enabled_gems.cmake - TARGETS Editor - VARIANTS Tools) - -# The pipeline tools use Builders gem variants: -ly_enable_gems( - PROJECT_NAME AutomatedTesting GEM_FILE enabled_gems.cmake - TARGETS AssetBuilder AssetProcessor AssetProcessorBatch - VARIANTS Builders) - -# old system (remove when all gems are ported to the new system above) - -ly_add_project_dependencies( - PROJECT_NAME - AutomatedTesting - TARGETS - AutomatedTesting.GameLauncher - DEPENDENCIES_FILES - runtime_dependencies.cmake - ${pal_dir}/runtime_dependencies.cmake -) - -if(PAL_TRAIT_BUILD_HOST_TOOLS) - ly_add_project_dependencies( - PROJECT_NAME - AutomatedTesting - TARGETS - AssetBuilder - AssetProcessor - AssetProcessorBatch - Editor - DEPENDENCIES_FILES - tool_dependencies.cmake - ${pal_dir}/tool_dependencies.cmake - ) +# If we build a server, then apply the gems to the server +if(PAL_TRAIT_BUILD_SERVER_SUPPORTED) + # if we're making a server, then add the "Server" gem variants to it: + ly_enable_gems(PROJECT_NAME AutomatedTesting GEM_FILE enabled_gems.cmake + TARGETS AutomatedTesting.ServerLauncher + VARIANTS Servers) + + set_property(GLOBAL APPEND PROPERTY LY_LAUNCHER_SERVER_PROJECTS AutomatedTesting) +endif() + +if (PAL_TRAIT_BUILD_HOST_TOOLS) + # The Editor uses "Tools" gem variants: + ly_enable_gems( + PROJECT_NAME AutomatedTesting GEM_FILE enabled_gems.cmake + TARGETS Editor + VARIANTS Tools) + + # The pipeline tools use "Builders" gem variants: + ly_enable_gems( + PROJECT_NAME AutomatedTesting GEM_FILE enabled_gems.cmake + TARGETS AssetBuilder AssetProcessor AssetProcessorBatch + VARIANTS Builders) endif() diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt index c431746b40..85d84a5dc0 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt @@ -66,6 +66,10 @@ ly_add_target( Gem::AtomViewportDisplayInfo ) +# Any 'runtime-like' applications should use Gem::Atom_AtomBridge: +ly_create_alias(NAME Atom_AtomBridge.Clients NAMESPACE Gem TARGETS Gem::Atom_AtomBridge) +ly_create_alias(NAME Atom_AtomBridge.Servers NAMESPACE Gem TARGETS Gem::Atom_AtomBridge) + if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME Atom_AtomBridge.Editor ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} @@ -107,4 +111,9 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::AtomToolsFramework.Editor Gem::AtomViewportDisplayInfo ) + + + # Any 'tool' and 'builder' type applications should use Gem::Atom_AtomBridge.Editor: + ly_create_alias(NAME Atom_AtomBridge.Builders NAMESPACE Gem TARGETS Gem::Atom_AtomBridge.Editor) + ly_create_alias(NAME Atom_AtomBridge.Tools NAMESPACE Gem TARGETS Gem::Atom_AtomBridge.Editor) endif() diff --git a/Gems/AudioSystem/Code/CMakeLists.txt b/Gems/AudioSystem/Code/CMakeLists.txt index dfb80a15d5..a0a8328147 100644 --- a/Gems/AudioSystem/Code/CMakeLists.txt +++ b/Gems/AudioSystem/Code/CMakeLists.txt @@ -217,8 +217,8 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) ) # use the above "Editor" target in tools and builders: - ly_create_alias(NAME AssetMemoryAnalyzer.Tools NAMESPACE Gem TARGETS Gem::AudioSystem.Editor) - ly_create_alias(NAME AssetMemoryAnalyzer.Builders NAMESPACE Gem TARGETS Gem::AudioSystem.Editor) + ly_create_alias(NAME AudioSystem.Tools NAMESPACE Gem TARGETS Gem::AudioSystem.Editor) + ly_create_alias(NAME AudioSystem.Builders NAMESPACE Gem TARGETS Gem::AudioSystem.Editor) if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_target( diff --git a/Gems/Multiplayer/Code/CMakeLists.txt b/Gems/Multiplayer/Code/CMakeLists.txt index 84a1cf7546..800670ff92 100644 --- a/Gems/Multiplayer/Code/CMakeLists.txt +++ b/Gems/Multiplayer/Code/CMakeLists.txt @@ -154,7 +154,6 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) # use the Multiplayer.Editor module in tools and builders. Tools also get the visual debug view ly_create_alias(NAME Multiplayer.Tools NAMESPACE Gem TARGETS Gem::Multiplayer.Editor Gem::Multiplayer.Debug Gem::Multiplayer.PrefabProcessor) ly_create_alias(NAME Multiplayer.Builders NAMESPACE Gem TARGETS Gem::Multiplayer.Editor Gem::Multiplayer.PrefabProcessor) - endif() if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) From 4ef357e57e2d8faf3b22d478eb3f3ef6a96f6410 Mon Sep 17 00:00:00 2001 From: lawsonamzn <70027408+lawsonamzn@users.noreply.github.com> Date: Thu, 13 May 2021 15:04:40 -0700 Subject: [PATCH 084/811] Updates the templates to use the new system Also updates the Gems.cmake file to handle namespaces being used. --- .../DefaultGem/Template/Code/CMakeLists.txt | 14 +++ .../Template/Code/${NameLower}_files.cmake | 4 +- .../Template/Code/CMakeLists.txt | 52 +++++---- .../Android/${NameLower}_android_files.cmake | 3 - .../android_runtime_dependencies.cmake | 14 --- .../Android/android_server_dependencies.cmake | 13 --- .../Android/android_tool_dependencies.cmake | 14 --- .../Linux/${NameLower}_linux_files.cmake | 3 - .../Linux/linux_runtime_dependencies.cmake | 15 --- .../Linux/linux_server_dependencies.cmake | 13 --- .../Linux/linux_tool_dependencies.cmake | 14 --- .../Platform/Mac/${NameLower}_mac_files.cmake | 3 - .../Mac/mac_runtime_dependencies.cmake | 15 --- .../Mac/mac_server_dependencies.cmake | 13 --- .../Platform/Mac/mac_tool_dependencies.cmake | 18 --- .../Windows/${NameLower}_windows_files.cmake | 3 - .../windows_runtime_dependencies.cmake | 16 --- .../Windows/windows_server_dependencies.cmake | 13 --- .../Windows/windows_tool_dependencies.cmake | 19 ---- .../Platform/iOS/${NameLower}_ios_files.cmake | 3 - .../iOS/ios_runtime_dependencies.cmake | 14 --- .../iOS/ios_server_dependencies.cmake | 13 --- .../Platform/iOS/ios_tool_dependencies.cmake | 14 --- ..._dependencies.cmake => enabled_gems.cmake} | 18 ++- .../Template/Code/runtime_dependencies.cmake | 36 ------ .../Template/Code/tool_dependencies.cmake | 43 ------- Templates/DefaultProject/template.json | 106 +----------------- cmake/Gems.cmake | 24 ++-- 28 files changed, 76 insertions(+), 454 deletions(-) delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Android/android_runtime_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Android/android_server_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Android/android_tool_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Linux/linux_runtime_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Linux/linux_server_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Linux/linux_tool_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Mac/mac_runtime_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Mac/mac_server_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Mac/mac_tool_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Windows/windows_runtime_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Windows/windows_server_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/Windows/windows_tool_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/iOS/ios_runtime_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/iOS/ios_server_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/Platform/iOS/ios_tool_dependencies.cmake rename Templates/DefaultProject/Template/Code/{server_dependencies.cmake => enabled_gems.cmake} (70%) delete mode 100644 Templates/DefaultProject/Template/Code/runtime_dependencies.cmake delete mode 100644 Templates/DefaultProject/Template/Code/tool_dependencies.cmake diff --git a/Templates/DefaultGem/Template/Code/CMakeLists.txt b/Templates/DefaultGem/Template/Code/CMakeLists.txt index 3511f8ff83..b0e52dd79f 100644 --- a/Templates/DefaultGem/Template/Code/CMakeLists.txt +++ b/Templates/DefaultGem/Template/Code/CMakeLists.txt @@ -59,6 +59,12 @@ ly_add_target( Gem::${Name}.Static ) +# By default, we will specify that the above target ${Name} would be used by +# Client and Server type targets when this gem is enabled. If you don't want it +# active in Clients or Servers by default, delete one of both of the following lines: +ly_create_alias(NAME ${Name}.Clients NAMESPACE Gem TARGETS Gem::${Name}) +ly_create_alias(NAME ${Name}.Servers NAMESPACE Gem TARGETS Gem::${Name}) + # If we are on a host platform, we want to add the host tools targets like the ${Name}.Editor target which # will also depend on ${Name}.Static if(PAL_TRAIT_BUILD_HOST_TOOLS) @@ -94,6 +100,14 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) PUBLIC Gem::${Name}.Editor.Static ) + + # By default, we will specify that the above target ${Name} would be used by + # Tool and Builder type targets when this gem is enabled. If you don't want it + # active in Tools or Builders by default, delete one of both of the following lines: + ly_create_alias(NAME ${Name}.Tools NAMESPACE Gem TARGETS Gem::${Name}.Editor) + ly_create_alias(NAME ${Name}.Builders NAMESPACE Gem TARGETS Gem::${Name}.Editor) + + endif() ################################################################################ diff --git a/Templates/DefaultProject/Template/Code/${NameLower}_files.cmake b/Templates/DefaultProject/Template/Code/${NameLower}_files.cmake index 459e33f547..f77348395b 100644 --- a/Templates/DefaultProject/Template/Code/${NameLower}_files.cmake +++ b/Templates/DefaultProject/Template/Code/${NameLower}_files.cmake @@ -13,7 +13,5 @@ set(FILES Include/${Name}/${Name}Bus.h Source/${Name}SystemComponent.cpp Source/${Name}SystemComponent.h - runtime_dependencies.cmake - tool_dependencies.cmake - server_dependencies.cmake + enabled_gems.cmake ) diff --git a/Templates/DefaultProject/Template/Code/CMakeLists.txt b/Templates/DefaultProject/Template/Code/CMakeLists.txt index 38999c031c..b116fb2044 100644 --- a/Templates/DefaultProject/Template/Code/CMakeLists.txt +++ b/Templates/DefaultProject/Template/Code/CMakeLists.txt @@ -64,41 +64,47 @@ ly_add_target( ################################################################################ # Gem dependencies ################################################################################ -ly_add_project_dependencies( - PROJECT_NAME - ${Name} + +# The GameLauncher uses "Clients" gem variants: +ly_enable_gems( + PROJECT_NAME ${Name} GEM_FILE enabled_gems.cmake TARGETS ${Name}.GameLauncher - DEPENDENCIES_FILES - runtime_dependencies.cmake - ${pal_dir}/${PAL_PLATFORM_NAME_LOWERCASE}_runtime_dependencies.cmake -) + VARIANTS + Clients) if(PAL_TRAIT_BUILD_HOST_TOOLS) - ly_add_project_dependencies( - PROJECT_NAME - ${Name} + + # the builder type applications use the "Builders" variants of the enabled gems. + ly_enable_gems( + PROJECT_NAME ${Name} GEM_FILE enabled_gems.cmake TARGETS AssetBuilder AssetProcessor AssetProcessorBatch + VARIANTS + Builders) + + # the Editor applications use the "Tools" variants of the enabled gems. + ly_enable_gems( + PROJECT_NAME ${Name} GEM_FILE enabled_gems.cmake + TARGETS Editor - DEPENDENCIES_FILES - tool_dependencies.cmake - ${pal_dir}/${PAL_PLATFORM_NAME_LOWERCASE}_tool_dependencies.cmake - ) + VARIANTS + Tools) endif() if(PAL_TRAIT_BUILD_SERVER_SUPPORTED) - ly_add_project_dependencies( - PROJECT_NAME - ${Name} + # this property causes it to actually make a ServerLauncher. + # if you don't want a Server application, you can remove this and the + # following ly_enable_gems lines. + set_property(GLOBAL APPEND PROPERTY LY_LAUNCHER_SERVER_PROJECTS ${Name}) + + # The ServerLauncher uses the "Servers" variants of enabled gems: + ly_enable_gems( + PROJECT_NAME ${Name} GEM_FILE enabled_gems.cmake TARGETS ${Name}.ServerLauncher - DEPENDENCIES_FILES - server_dependencies.cmake - ${pal_dir}/${PAL_PLATFORM_NAME_LOWERCASE}_server_dependencies.cmake - ) - set_property(GLOBAL APPEND PROPERTY LY_LAUNCHER_SERVER_PROJECTS ${Name}) - + VARIANTS + Servers) endif() diff --git a/Templates/DefaultProject/Template/Code/Platform/Android/${NameLower}_android_files.cmake b/Templates/DefaultProject/Template/Code/Platform/Android/${NameLower}_android_files.cmake index b774cd944f..78fd98ba6c 100644 --- a/Templates/DefaultProject/Template/Code/Platform/Android/${NameLower}_android_files.cmake +++ b/Templates/DefaultProject/Template/Code/Platform/Android/${NameLower}_android_files.cmake @@ -11,7 +11,4 @@ set(FILES PAL_android.cmake - android_runtime_dependencies.cmake - android_tool_dependencies.cmake - android_server_dependencies.cmake ) diff --git a/Templates/DefaultProject/Template/Code/Platform/Android/android_runtime_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Android/android_runtime_dependencies.cmake deleted file mode 100644 index a1ebd6e455..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Android/android_runtime_dependencies.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::Atom_RHI_Vulkan.Private -) diff --git a/Templates/DefaultProject/Template/Code/Platform/Android/android_server_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Android/android_server_dependencies.cmake deleted file mode 100644 index fe28e294e9..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Android/android_server_dependencies.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES -) diff --git a/Templates/DefaultProject/Template/Code/Platform/Android/android_tool_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Android/android_tool_dependencies.cmake deleted file mode 100644 index 14e6f1aa4c..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Android/android_tool_dependencies.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES -) - diff --git a/Templates/DefaultProject/Template/Code/Platform/Linux/${NameLower}_linux_files.cmake b/Templates/DefaultProject/Template/Code/Platform/Linux/${NameLower}_linux_files.cmake index 58fc59d265..ee0b06efc4 100644 --- a/Templates/DefaultProject/Template/Code/Platform/Linux/${NameLower}_linux_files.cmake +++ b/Templates/DefaultProject/Template/Code/Platform/Linux/${NameLower}_linux_files.cmake @@ -11,7 +11,4 @@ set(FILES PAL_linux.cmake - linux_runtime_dependencies.cmake - linux_tool_dependencies.cmake - linux_server_dependencies.cmake ) diff --git a/Templates/DefaultProject/Template/Code/Platform/Linux/linux_runtime_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Linux/linux_runtime_dependencies.cmake deleted file mode 100644 index a54c22de8c..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Linux/linux_runtime_dependencies.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::Atom_RHI_Vulkan.Private - Gem::Atom_RHI_Vulkan.Builders -) diff --git a/Templates/DefaultProject/Template/Code/Platform/Linux/linux_server_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Linux/linux_server_dependencies.cmake deleted file mode 100644 index fe28e294e9..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Linux/linux_server_dependencies.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES -) diff --git a/Templates/DefaultProject/Template/Code/Platform/Linux/linux_tool_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Linux/linux_tool_dependencies.cmake deleted file mode 100644 index a1ebd6e455..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Linux/linux_tool_dependencies.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::Atom_RHI_Vulkan.Private -) diff --git a/Templates/DefaultProject/Template/Code/Platform/Mac/${NameLower}_mac_files.cmake b/Templates/DefaultProject/Template/Code/Platform/Mac/${NameLower}_mac_files.cmake index 7eb776e3a6..e14e028c88 100644 --- a/Templates/DefaultProject/Template/Code/Platform/Mac/${NameLower}_mac_files.cmake +++ b/Templates/DefaultProject/Template/Code/Platform/Mac/${NameLower}_mac_files.cmake @@ -12,7 +12,4 @@ set(FILES ../../../Resources/Platform/Mac/Info.plist PAL_mac.cmake - mac_runtime_dependencies.cmake - mac_tool_dependencies.cmake - mac_server_dependencies.cmake ) diff --git a/Templates/DefaultProject/Template/Code/Platform/Mac/mac_runtime_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Mac/mac_runtime_dependencies.cmake deleted file mode 100644 index 2821493346..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Mac/mac_runtime_dependencies.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::Atom_RHI_Metal.Private - Gem::Atom_RHI_Null.Private -) diff --git a/Templates/DefaultProject/Template/Code/Platform/Mac/mac_server_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Mac/mac_server_dependencies.cmake deleted file mode 100644 index fe28e294e9..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Mac/mac_server_dependencies.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES -) diff --git a/Templates/DefaultProject/Template/Code/Platform/Mac/mac_tool_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Mac/mac_tool_dependencies.cmake deleted file mode 100644 index adf5485ed4..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Mac/mac_tool_dependencies.cmake +++ /dev/null @@ -1,18 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::Atom_RHI_Metal.Private - Gem::Atom_RHI_Metal.Builders - Gem::Atom_RHI_Vulkan.Builders - Gem::Atom_RHI_DX12.Builders - Gem::Atom_RHI_Null.Builders -) diff --git a/Templates/DefaultProject/Template/Code/Platform/Windows/${NameLower}_windows_files.cmake b/Templates/DefaultProject/Template/Code/Platform/Windows/${NameLower}_windows_files.cmake index 8fee85a163..b6eb718a05 100644 --- a/Templates/DefaultProject/Template/Code/Platform/Windows/${NameLower}_windows_files.cmake +++ b/Templates/DefaultProject/Template/Code/Platform/Windows/${NameLower}_windows_files.cmake @@ -11,7 +11,4 @@ set(FILES PAL_windows.cmake - windows_runtime_dependencies.cmake - windows_tool_dependencies.cmake - windows_server_dependencies.cmake ) diff --git a/Templates/DefaultProject/Template/Code/Platform/Windows/windows_runtime_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Windows/windows_runtime_dependencies.cmake deleted file mode 100644 index 514a61aa57..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Windows/windows_runtime_dependencies.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::Atom_RHI_Vulkan.Private - Gem::Atom_RHI_DX12.Private - Gem::Atom_RHI_Null.Private -) diff --git a/Templates/DefaultProject/Template/Code/Platform/Windows/windows_server_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Windows/windows_server_dependencies.cmake deleted file mode 100644 index fe28e294e9..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Windows/windows_server_dependencies.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES -) diff --git a/Templates/DefaultProject/Template/Code/Platform/Windows/windows_tool_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/Windows/windows_tool_dependencies.cmake deleted file mode 100644 index b7f4b82126..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/Windows/windows_tool_dependencies.cmake +++ /dev/null @@ -1,19 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::Atom_RHI_Vulkan.Private - Gem::Atom_RHI_Vulkan.Builders - Gem::Atom_RHI_DX12.Private - Gem::Atom_RHI_DX12.Builders - Gem::Atom_RHI_Null.Private - Gem::Atom_RHI_Null.Builders -) diff --git a/Templates/DefaultProject/Template/Code/Platform/iOS/${NameLower}_ios_files.cmake b/Templates/DefaultProject/Template/Code/Platform/iOS/${NameLower}_ios_files.cmake index 41a6d13884..44f15538c8 100644 --- a/Templates/DefaultProject/Template/Code/Platform/iOS/${NameLower}_ios_files.cmake +++ b/Templates/DefaultProject/Template/Code/Platform/iOS/${NameLower}_ios_files.cmake @@ -12,7 +12,4 @@ set(FILES ../Resources/Platform/iOS/Info.plist PAL_ios.cmake - ios_runtime_dependencies.cmake - ios_tool_dependencies.cmake - ios_server_dependencies.cmake ) diff --git a/Templates/DefaultProject/Template/Code/Platform/iOS/ios_runtime_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/iOS/ios_runtime_dependencies.cmake deleted file mode 100644 index e49929c6e1..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/iOS/ios_runtime_dependencies.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::Atom_RHI_Metal.Private -) diff --git a/Templates/DefaultProject/Template/Code/Platform/iOS/ios_server_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/iOS/ios_server_dependencies.cmake deleted file mode 100644 index fe28e294e9..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/iOS/ios_server_dependencies.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES -) diff --git a/Templates/DefaultProject/Template/Code/Platform/iOS/ios_tool_dependencies.cmake b/Templates/DefaultProject/Template/Code/Platform/iOS/ios_tool_dependencies.cmake deleted file mode 100644 index 14e6f1aa4c..0000000000 --- a/Templates/DefaultProject/Template/Code/Platform/iOS/ios_tool_dependencies.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES -) - diff --git a/Templates/DefaultProject/Template/Code/server_dependencies.cmake b/Templates/DefaultProject/Template/Code/enabled_gems.cmake similarity index 70% rename from Templates/DefaultProject/Template/Code/server_dependencies.cmake rename to Templates/DefaultProject/Template/Code/enabled_gems.cmake index 3982bbb166..dfb7d93233 100644 --- a/Templates/DefaultProject/Template/Code/server_dependencies.cmake +++ b/Templates/DefaultProject/Template/Code/enabled_gems.cmake @@ -9,8 +9,20 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # {END_LICENSE} -set(GEM_DEPENDENCIES +set(ENABLED_GEMS Project::${Name} - Gem::Maestro - Gem::LmbrCentral + Atom_AtomBridge + Camera + CameraFramework + EditorPythonBindings + EMotionFX + GradientSignal + ImGui + LmbrCentral + LyShine + Maestro + NvCloth + SceneProcessing + TextureAtlas + WhiteBox ) diff --git a/Templates/DefaultProject/Template/Code/runtime_dependencies.cmake b/Templates/DefaultProject/Template/Code/runtime_dependencies.cmake deleted file mode 100644 index ce8df8152d..0000000000 --- a/Templates/DefaultProject/Template/Code/runtime_dependencies.cmake +++ /dev/null @@ -1,36 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Project::${Name} - Gem::Maestro - Gem::TextureAtlas - Gem::LmbrCentral - Gem::NvCloth - Gem::LyShine - Gem::Camera - Gem::CameraFramework - Gem::Atom_RHI.Private - Gem::EMotionFX - Gem::Atom_RPI.Private - Gem::Atom_Feature_Common - Gem::ImGui - Gem::Atom_Bootstrap - Gem::Atom_Component_DebugCamera - Gem::AtomImGuiTools - Gem::AtomLyIntegration_CommonFeatures - Gem::EMotionFX_Atom - Gem::ImguiAtom - Gem::Atom_AtomBridge - Gem::GradientSignal - Gem::AtomFont - Gem::WhiteBox -) diff --git a/Templates/DefaultProject/Template/Code/tool_dependencies.cmake b/Templates/DefaultProject/Template/Code/tool_dependencies.cmake deleted file mode 100644 index 010d45bd0f..0000000000 --- a/Templates/DefaultProject/Template/Code/tool_dependencies.cmake +++ /dev/null @@ -1,43 +0,0 @@ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Project::${Name} - Gem::Maestro.Editor - Gem::TextureAtlas - Gem::LmbrCentral.Editor - Gem::NvCloth.Editor - Gem::LyShine.Editor - Gem::SceneProcessing.Editor - Gem::EditorPythonBindings.Editor - Gem::Camera.Editor - Gem::CameraFramework - Gem::Atom_RHI.Private - Gem::EMotionFX.Editor - Gem::Atom_RPI.Builders - Gem::Atom_RPI.Editor - Gem::Atom_Feature_Common.Builders - Gem::Atom_Feature_Common.Editor - Gem::ImGui.Editor - Gem::Atom_Bootstrap - Gem::Atom_Asset_Shader.Builders - Gem::Atom_Component_DebugCamera - Gem::AtomImGuiTools - Gem::AtomLyIntegration_CommonFeatures.Editor - Gem::EMotionFX_Atom.Editor - Gem::ImageProcessingAtom.Editor - Gem::Atom_AtomBridge.Editor - Gem::ImguiAtom - Gem::AtomFont - Gem::AtomToolsFramework.Editor - Gem::GradientSignal.Editor - Gem::WhiteBox.Editor -) diff --git a/Templates/DefaultProject/template.json b/Templates/DefaultProject/template.json index 56278a6b04..7add7e34f7 100644 --- a/Templates/DefaultProject/template.json +++ b/Templates/DefaultProject/template.json @@ -66,24 +66,6 @@ "isTemplated": true, "isOptional": false }, - { - "file": "Code/Platform/Android/android_runtime_dependencies.cmake", - "origin": "Code/Platform/Android/android_runtime_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/Platform/Android/android_server_dependencies.cmake", - "origin": "Code/Platform/Android/android_server_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/Platform/Android/android_tool_dependencies.cmake", - "origin": "Code/Platform/Android/android_tool_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, { "file": "Code/Platform/Linux/${NameLower}_linux_files.cmake", "origin": "Code/Platform/Linux/${NameLower}_linux_files.cmake", @@ -102,24 +84,6 @@ "isTemplated": true, "isOptional": false }, - { - "file": "Code/Platform/Linux/linux_runtime_dependencies.cmake", - "origin": "Code/Platform/Linux/linux_runtime_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/Platform/Linux/linux_server_dependencies.cmake", - "origin": "Code/Platform/Linux/linux_server_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/Platform/Linux/linux_tool_dependencies.cmake", - "origin": "Code/Platform/Linux/linux_tool_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, { "file": "Code/Platform/Mac/${NameLower}_mac_files.cmake", "origin": "Code/Platform/Mac/${NameLower}_mac_files.cmake", @@ -138,24 +102,6 @@ "isTemplated": true, "isOptional": false }, - { - "file": "Code/Platform/Mac/mac_runtime_dependencies.cmake", - "origin": "Code/Platform/Mac/mac_runtime_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/Platform/Mac/mac_server_dependencies.cmake", - "origin": "Code/Platform/Mac/mac_server_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/Platform/Mac/mac_tool_dependencies.cmake", - "origin": "Code/Platform/Mac/mac_tool_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, { "file": "Code/Platform/Windows/${NameLower}_shared_windows_files.cmake", "origin": "Code/Platform/Windows/${NameLower}_shared_windows_files.cmake", @@ -174,24 +120,6 @@ "isTemplated": true, "isOptional": false }, - { - "file": "Code/Platform/Windows/windows_runtime_dependencies.cmake", - "origin": "Code/Platform/Windows/windows_runtime_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/Platform/Windows/windows_server_dependencies.cmake", - "origin": "Code/Platform/Windows/windows_server_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/Platform/Windows/windows_tool_dependencies.cmake", - "origin": "Code/Platform/Windows/windows_tool_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, { "file": "Code/Platform/iOS/${NameLower}_ios_files.cmake", "origin": "Code/Platform/iOS/${NameLower}_ios_files.cmake", @@ -210,24 +138,6 @@ "isTemplated": true, "isOptional": false }, - { - "file": "Code/Platform/iOS/ios_runtime_dependencies.cmake", - "origin": "Code/Platform/iOS/ios_runtime_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/Platform/iOS/ios_server_dependencies.cmake", - "origin": "Code/Platform/iOS/ios_server_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/Platform/iOS/ios_tool_dependencies.cmake", - "origin": "Code/Platform/iOS/ios_tool_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, { "file": "Code/Source/${Name}Module.cpp", "origin": "Code/Source/${Name}Module.cpp", @@ -247,20 +157,8 @@ "isOptional": false }, { - "file": "Code/runtime_dependencies.cmake", - "origin": "Code/runtime_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/server_dependencies.cmake", - "origin": "Code/server_dependencies.cmake", - "isTemplated": true, - "isOptional": false - }, - { - "file": "Code/tool_dependencies.cmake", - "origin": "Code/tool_dependencies.cmake", + "file": "Code/enabled_gems.cmake", + "origin": "Code/enabled_gems.cmake", "isTemplated": true, "isOptional": false }, diff --git a/cmake/Gems.cmake b/cmake/Gems.cmake index 3e9ce97329..caa5b74c93 100644 --- a/cmake/Gems.cmake +++ b/cmake/Gems.cmake @@ -84,6 +84,7 @@ endfunction() # note that it can't do this immediately, so it saves the data for later processing. # Note: If you don't supply a project name, it will apply it across the board to all projects. # this is useful in the case of "ly_add_gems being called for so called 'mandatory gems' inside the engine. +# if you specify a gem name with a namespace, it will be used, otherwise it will assume Gem:: function(ly_enable_gems) set(options) set(oneValueArgs PROJECT_NAME GEM_FILE) @@ -176,19 +177,24 @@ function(ly_enable_gems_delayed) # apply the list of gem targets. Adding a gem really just means adding the appropriate dependency. foreach(gem_name ${gem_dependencies}) + # the gem name may already have a namespace. If it does, we use that one + ly_strip_target_namespace(TARGET ${gem_name} OUTPUT_VARIABLE unaliased_gem_name) + if (${unaliased_gem_name} STREQUAL ${gem_name}) + # if stripping a namespace had no effect, it had no namespace + # and we supply the default Gem:: namespace. + set(gem_name_with_namespace Gem::${gem_name}) + else() + # if stripping the namespace had an effect then we use the original + # with the namespace, instead of assuming Gem:: + set(gem_name_with_namespace ${gem_name}) + endif() - if (TARGET Gem::${gem_name}.${variant}) + # if the target exists, add it. + if (TARGET ${gem_name_with_namespace}.${variant}) ly_add_target_dependencies( ${PREFIX_CLAUSE} TARGETS ${target} - DEPENDENT_TARGETS Gem::${gem_name}.${variant} - ) - elseif(${variant} STREQUAL "Client" AND TARGET Gem::${gem_name}) - # Client can also be 'empty' for backward compatibility - ly_add_target_dependencies( - ${PREFIX_CLAUSE} - TARGETS ${target} - DEPENDENT_TARGETS Gem::${gem_name} + DEPENDENT_TARGETS ${gem_name_with_namespace}.${variant} ) endif() endforeach() From e886dba77e1a91f11005529c9295ec7e7e7d3ac7 Mon Sep 17 00:00:00 2001 From: lawsonamzn <70027408+lawsonamzn@users.noreply.github.com> Date: Thu, 20 May 2021 15:27:54 -0700 Subject: [PATCH 085/811] Update Multiplayer gem to conform to the new standard The multiplayer gem had a naming conflict in it - a module was called "Tools". --- Gems/Multiplayer/Code/CMakeLists.txt | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Gems/Multiplayer/Code/CMakeLists.txt b/Gems/Multiplayer/Code/CMakeLists.txt index 800670ff92..430fe5ca4b 100644 --- a/Gems/Multiplayer/Code/CMakeLists.txt +++ b/Gems/Multiplayer/Code/CMakeLists.txt @@ -80,14 +80,13 @@ ly_add_target( Gem::ImGui.Static ) -# The above "Multiplayer" target is used by clients and servers -# the debug is only used on Clients +# The "Multiplayer" target is used by clients and servers, Debug is used only on clients. ly_create_alias(NAME Multiplayer.Clients NAMESPACE Gem TARGETS Gem::Multiplayer Gem::Multiplayer.Debug) ly_create_alias(NAME Multiplayer.Servers NAMESPACE Gem TARGETS Gem::Multiplayer) if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( - NAME Multiplayer.Tools.Static STATIC + NAME Multiplayer.Builders.Static STATIC NAMESPACE Gem FILES_CMAKE multiplayer_tools_files.cmake @@ -107,10 +106,12 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Gem::Multiplayer.Static ) + # by naming this target Multiplayer.Builders it ensures that it is loaded + # in any pipeline tools (Like Asset Processor, AssetBuilder, etc) ly_add_target( - NAME Multiplayer.Tools MODULE + NAME Multiplayer.Builders GEM_MODULE NAMESPACE Gem - OUTPUT_NAME Gem.Multiplayer.Tools + OUTPUT_NAME Gem.Multiplayer.Builders FILES_CMAKE multiplayer_tools_files.cmake INCLUDE_DIRECTORIES @@ -121,7 +122,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Include BUILD_DEPENDENCIES PRIVATE - Gem::Multiplayer.Tools.Static + Gem::Multiplayer.Builders.Static ) ly_add_target( @@ -148,12 +149,11 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AzNetworking AZ::AzToolsFramework Gem::Multiplayer.Static - Gem::Multiplayer.Tools + Gem::Multiplayer.Builders ) - # use the Multiplayer.Editor module in tools and builders. Tools also get the visual debug view - ly_create_alias(NAME Multiplayer.Tools NAMESPACE Gem TARGETS Gem::Multiplayer.Editor Gem::Multiplayer.Debug Gem::Multiplayer.PrefabProcessor) - ly_create_alias(NAME Multiplayer.Builders NAMESPACE Gem TARGETS Gem::Multiplayer.Editor Gem::Multiplayer.PrefabProcessor) + # use the Multiplayer.Editor module in tools like the Editor: Such tools also get the visual debug view: + ly_create_alias(NAME Multiplayer.Tools NAMESPACE Gem TARGETS Gem::Multiplayer.Editor Gem::Multiplayer.Debug) endif() if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) @@ -181,7 +181,7 @@ if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( - NAME Multiplayer.Tools.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAME Multiplayer.Builders.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} NAMESPACE Gem FILES_CMAKE multiplayer_tools_tests_files.cmake @@ -195,10 +195,10 @@ if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest AZ::AzTestShared AZ::AzToolsFrameworkTestCommon - Gem::Multiplayer.Tools.Static + Gem::Multiplayer.Builders.Static ) ly_add_googletest( - NAME Gem::Multiplayer.Tools.Tests + NAME Gem::Multiplayer.Builders.Tests ) endif() From a9bc8e943d13caa3c05107126b32b6cc086def34 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 21 May 2021 01:58:54 -0500 Subject: [PATCH 086/811] Refactored the o3de registration.py script into several files which each contains the implementation of a subparser command. Updated the register command to be not register engine gems, templates, projects and external subdirectories to the o3de_manifest Updated the register-show command to be able to read the engine's gems, templates, projects and external subdirectories from the engine.json file --- scripts/o3de.py | 2 +- .../o3de/o3de/add_external_subdirectory.py | 140 + scripts/o3de/o3de/add_gem_cmake.py | 114 + scripts/o3de/o3de/add_gem_project.py | 311 ++ scripts/o3de/o3de/cmake.py | 234 + scripts/o3de/o3de/download.py | 598 +++ scripts/o3de/o3de/engine_template.py | 178 +- scripts/o3de/o3de/get_registration.py | 62 + scripts/o3de/o3de/global_project.py | 12 +- scripts/o3de/o3de/manifest.py | 600 +++ scripts/o3de/o3de/print_registration.py | 456 ++ scripts/o3de/o3de/register.py | 1066 ++++ scripts/o3de/o3de/registration.py | 4383 +---------------- .../o3de/o3de/remove_external_subdirectory.py | 73 + scripts/o3de/o3de/remove_gem_cmake.py | 89 + scripts/o3de/o3de/remove_gem_project.py | 270 + scripts/o3de/o3de/repo.py | 291 ++ scripts/o3de/o3de/sha256.py | 82 + scripts/o3de/o3de/utils.py | 25 + scripts/o3de/o3de/validation.py | 103 + .../o3de/tests/unit_test_add_remove_gem.py | 4 +- scripts/o3de/tests/unit_test_registration.py | 14 +- 22 files changed, 4641 insertions(+), 4466 deletions(-) create mode 100644 scripts/o3de/o3de/add_external_subdirectory.py create mode 100644 scripts/o3de/o3de/add_gem_cmake.py create mode 100644 scripts/o3de/o3de/add_gem_project.py create mode 100644 scripts/o3de/o3de/cmake.py create mode 100644 scripts/o3de/o3de/download.py create mode 100644 scripts/o3de/o3de/get_registration.py create mode 100644 scripts/o3de/o3de/manifest.py create mode 100644 scripts/o3de/o3de/print_registration.py create mode 100644 scripts/o3de/o3de/register.py create mode 100644 scripts/o3de/o3de/remove_external_subdirectory.py create mode 100644 scripts/o3de/o3de/remove_gem_cmake.py create mode 100644 scripts/o3de/o3de/remove_gem_project.py create mode 100644 scripts/o3de/o3de/repo.py create mode 100644 scripts/o3de/o3de/sha256.py create mode 100644 scripts/o3de/o3de/validation.py diff --git a/scripts/o3de.py b/scripts/o3de.py index 7bc1c4a9fb..d3b877620f 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -18,7 +18,7 @@ import sys # So the current script directory is removed from the sys.path temporary SCRIPT_DIR_REMOVED = False SCRIPT_DIR = pathlib.Path(__file__).parent.resolve() -if str(SCRIPT_DIR) in sys.path: +while str(SCRIPT_DIR) in sys.path: SCRIPT_DIR_REMOVED = True sys.path.remove(str(SCRIPT_DIR)) diff --git a/scripts/o3de/o3de/add_external_subdirectory.py b/scripts/o3de/o3de/add_external_subdirectory.py new file mode 100644 index 0000000000..15dc5163c5 --- /dev/null +++ b/scripts/o3de/o3de/add_external_subdirectory.py @@ -0,0 +1,140 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +Contains command to add a gem to a project's cmake scripts +""" + +import argparse +import logging +import pathlib + +from o3de import manifest + +logger = logging.getLogger() +logging.basicConfig() + +def add_external_subdirectory(external_subdir: str or pathlib.Path, + engine_path: str or pathlib.Path = None, + suppress_errors: bool = False) -> int: + """ + add external subdirectory to a cmake + :param external_subdir: external subdirectory to add to cmake + :param engine_path: optional engine path, defaults to this engine + :param suppress_errors: optional silence errors + :return: 0 for success or non 0 failure code + """ + external_subdir = pathlib.Path(external_subdir).resolve() + if not external_subdir.is_dir(): + if not suppress_errors: + logger.error(f'Add External Subdirectory Failed: {external_subdir} does not exist.') + return 1 + + external_subdir_cmake = external_subdir / 'CMakeLists.txt' + if not external_subdir_cmake.is_file(): + if not suppress_errors: + logger.error(f'Add External Subdirectory Failed: {external_subdir} does not contain a CMakeLists.txt.') + return 1 + + json_data = manifest.load_o3de_manifest() + engine_object = manifest.find_engine_data(json_data, engine_path) + if not engine_object: + if not suppress_errors: + logger.error(f'Add External Subdirectory Failed: {engine_path} not registered.') + return 1 + + while external_subdir.as_posix() in engine_object['external_subdirectories']: + engine_object['external_subdirectories'].remove(external_subdir.as_posix()) + + def parse_cmake_file(cmake: str or pathlib.Path, + files: set): + cmake_path = pathlib.Path(cmake).resolve() + cmake_file = cmake_path + if cmake_path.is_dir(): + files.add(cmake_path) + cmake_file = cmake_path / 'CMakeLists.txt' + elif cmake_path.is_file(): + cmake_path = cmake_path.parent + else: + return + + with cmake_file.open('r') as s: + lines = s.readlines() + for line in lines: + line = line.strip() + start = line.find('include(') + if start == 0: + end = line.find(')', start) + if end > start + len('include('): + try: + include_cmake_file = pathlib.Path(engine_path / line[start + len('include('): end]).resolve() + except Exception as e: + pass + else: + parse_cmake_file(include_cmake_file, files) + else: + start = line.find('add_subdirectory(') + if start == 0: + end = line.find(')', start) + if end > start + len('add_subdirectory('): + try: + include_cmake_file = pathlib.Path( + cmake_path / line[start + len('add_subdirectory('): end]).resolve() + except Exception as e: + pass + else: + parse_cmake_file(include_cmake_file, files) + + cmake_files = set() + parse_cmake_file(engine_path, cmake_files) + for external in engine_object["external_subdirectories"]: + parse_cmake_file(external, cmake_files) + + if external_subdir in cmake_files: + manifest.save_o3de_manifest(json_data) + if not suppress_errors: + logger.error(f'External subdirectory {external_subdir.as_posix()} already included by add_subdirectory().') + return 1 + + engine_object['external_subdirectories'].insert(0, external_subdir.as_posix()) + engine_object['external_subdirectories'] = sorted(engine_object['external_subdirectories']) + + manifest.save_o3de_manifest(json_data) + + return 0 + + +def _run_add_external_subdirectory(args: argparse) -> int: + if args.override_home_folder: + manifest.override_home_folder = args.override_home_folder + + return add_external_subdirectory(args.external_subdirectory) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + add_external_subdirectory_subparser = subparsers.add_parser('add-external-subdirectory') + add_external_subdirectory_subparser.add_argument('external_subdirectory', metavar='external_subdirectory', type=str, + help='add an external subdirectory to cmake') + + add_external_subdirectory_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + add_external_subdirectory_subparser.set_defaults(func=_run_add_external_subdirectory) + diff --git a/scripts/o3de/o3de/add_gem_cmake.py b/scripts/o3de/o3de/add_gem_cmake.py new file mode 100644 index 0000000000..fa2d2f4bb3 --- /dev/null +++ b/scripts/o3de/o3de/add_gem_cmake.py @@ -0,0 +1,114 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +Contains command to add a gem to a project's cmake scripts +""" + +import argparse +import logging +import pathlib + +from o3de import add_external_subdirectory, manifest, validation + +logger = logging.getLogger() +logging.basicConfig() + +def add_gem_to_cmake(gem_name: str = None, + gem_path: str or pathlib.Path = None, + engine_name: str = None, + engine_path: str or pathlib.Path = None, + suppress_errors: bool = False) -> int: + """ + add a gem to a cmake as an external subdirectory for an engine + :param gem_name: name of the gem to add to cmake + :param gem_path: the path of the gem to add to cmake + :param engine_name: name of the engine to add to cmake + :param engine_path: the path of the engine to add external subdirectory to, default to this engine + :param suppress_errors: optional silence errors + :return: 0 for success or non 0 failure code + """ + if not gem_name and not gem_path: + if not suppress_errors: + logger.error('Must specify either a Gem name or Gem Path.') + return 1 + + if gem_name and not gem_path: + gem_path = manifest.get_registered(gem_name=gem_name) + + if not gem_path: + if not suppress_errors: + logger.error(f'Gem Path {gem_path} has not been registered.') + return 1 + + gem_path = pathlib.Path(gem_path).resolve() + gem_json = gem_path / 'gem.json' + if not gem_json.is_file(): + if not suppress_errors: + logger.error(f'Gem json {gem_json} is not present.') + return 1 + if not validation.valid_o3de_gem_json(gem_json): + if not suppress_errors: + logger.error(f'Gem json {gem_json} is not valid.') + return 1 + + if not engine_name and not engine_path: + engine_path = manifest.get_this_engine_path() + + if engine_name and not engine_path: + engine_path = manifest.get_registered(engine_name=engine_name) + + if not engine_path: + if not suppress_errors: + logger.error(f'Engine Path {engine_path} has not been registered.') + return 1 + + engine_json = engine_path / 'engine.json' + if not engine_json.is_file(): + if not suppress_errors: + logger.error(f'Engine json {engine_json} is not present.') + return 1 + if not validation.valid_o3de_engine_json(engine_json): + if not suppress_errors: + logger.error(f'Engine json {engine_json} is not valid.') + return 1 + + return add_external_subdirectory.add_external_subdirectory(external_subdir=gem_path, engine_path=engine_path, suppress_errors=suppress_errors) + + +def _run_add_gem_to_cmake(args: argparse) -> int: + if args.override_home_folder: + manifest.override_home_folder = args.override_home_folder + + return add_gem_to_cmake(gem_name=args.gem_name, gem_path=args.gem_path) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + add_gem_to_cmake_subparser = subparsers.add_parser('add-gem-to-cmake') + group = add_gem_to_cmake_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-gp', '--gem-path', type=str, required=False, + help='The path to the gem.') + group.add_argument('-gn', '--gem-name', type=str, required=False, + help='The name of the gem.') + + add_gem_to_cmake_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + add_gem_to_cmake_subparser.set_defaults(func=_run_add_gem_to_cmake) diff --git a/scripts/o3de/o3de/add_gem_project.py b/scripts/o3de/o3de/add_gem_project.py new file mode 100644 index 0000000000..933fd019bb --- /dev/null +++ b/scripts/o3de/o3de/add_gem_project.py @@ -0,0 +1,311 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +Contains command to add a gem to a project's cmake scripts +""" + +import argparse +import json +import logging +import os +import pathlib + +from o3de import add_gem_cmake, cmake, manifest, validation + +logger = logging.getLogger() +logging.basicConfig() + +def add_gem_dependency(cmake_file: str or pathlib.Path, + gem_target: str) -> int: + """ + adds a gem dependency to a cmake file + :param cmake_file: path to the cmake file + :param gem_target: name of the cmake target + :return: 0 for success or non 0 failure code + """ + if not os.path.isfile(cmake_file): + logger.error(f'Failed to locate cmake file {cmake_file}') + return 1 + + # on a line by basis, see if there already is Gem::{gem_name} + # find the first occurrence of a gem, copy its formatting and replace + # the gem name with the new one and append it + # if the gem is already present fail + t_data = [] + added = False + with open(cmake_file, 'r') as s: + for line in s: + if f'Gem::{gem_target}' in line: + logger.warning(f'{gem_target} is already a gem dependency.') + return 0 + if not added and r'Gem::' in line: + new_gem = ' ' * line.find(r'Gem::') + f'Gem::{gem_target}\n' + t_data.append(new_gem) + added = True + t_data.append(line) + + # if we didn't add it the set gem dependencies could be empty so + # add a new gem, if empty the correct format is 1 tab=4spaces + if not added: + index = 0 + for line in t_data: + index = index + 1 + if r'set(GEM_DEPENDENCIES' in line: + t_data.insert(index, f' Gem::{gem_target}\n') + added = True + break + + # if we didn't add it then it's not here, add a whole new one + if not added: + t_data.append('\n') + t_data.append('set(GEM_DEPENDENCIES\n') + t_data.append(f' Gem::{gem_target}\n') + t_data.append(')\n') + + # write the cmake + os.unlink(cmake_file) + with open(cmake_file, 'w') as s: + s.writelines(t_data) + + return 0 + + +def add_gem_to_project(gem_name: str = None, + gem_path: str or pathlib.Path = None, + gem_target: str = None, + project_name: str = None, + project_path: str or pathlib.Path = None, + dependencies_file: str or pathlib.Path = None, + runtime_dependency: bool = False, + tool_dependency: bool = False, + server_dependency: bool = False, + platforms: str = 'Common', + add_to_cmake: bool = True) -> int: + """ + add a gem to a project + :param gem_name: name of the gem to add + :param gem_path: path to the gem to add + :param gem_target: the name of the cmake gem module + :param project_name: name of to the project to add the gem to + :param project_path: path to the project to add the gem to + :param dependencies_file: if this dependency goes/is in a specific file + :param runtime_dependency: bool to specify this is a runtime gem for the game + :param tool_dependency: bool to specify this is a tool gem for the editor + :param server_dependency: bool to specify this is a server gem for the server + :param platforms: str to specify common or which specific platforms + :param add_to_cmake: bool to specify that this gem should be added to cmake + :return: 0 for success or non 0 failure code + """ + # we need either a project name or path + if not project_name and not project_path: + logger.error(f'Must either specify a Project path or Project Name.') + return 1 + + # if project name resolve it into a path + if project_name and not project_path: + project_path = manifest.get_registered(project_name=project_name) + project_path = pathlib.Path(project_path).resolve() + if not project_path.is_dir(): + logger.error(f'Project path {project_path} is not a folder.') + return 1 + + # get the engine name this project is associated with + # and resolve that engines path + project_json = project_path / 'project.json' + if not validation.valid_o3de_project_json(project_json): + logger.error(f'Project json {project_json} is not valid.') + return 1 + with project_json.open('r') as s: + try: + project_json_data = json.load(s) + except Exception as e: + logger.error(f'Error loading Project json {project_json}: {str(e)}') + return 1 + else: + try: + engine_name = project_json_data['engine'] + except Exception as e: + logger.error(f'Project json {project_json} "engine" not found: {str(e)}') + return 1 + else: + engine_path = manifest.get_registered(engine_name=engine_name) + if not engine_path: + logger.error(f'Engine {engine_name} is not registered.') + return 1 + + # we need either a gem name or path + if not gem_name and not gem_path: + logger.error(f'Must either specify a Gem path or Gem Name.') + return 1 + + # if gem name resolve it into a path + if gem_name and not gem_path: + gem_path = manifest.get_registered(gem_name=gem_name) + gem_path = pathlib.Path(gem_path).resolve() + # make sure this gem already exists if we're adding. We can always remove a gem. + if not gem_path.is_dir(): + logger.error(f'Gem Path {gem_path} does not exist.') + return 1 + + # if add to cmake, make sure the gem.json exists and valid before we proceed + if add_to_cmake: + gem_json = gem_path / 'gem.json' + if not gem_json.is_file(): + logger.error(f'Gem json {gem_json} is not present.') + return 1 + if not validation.valid_o3de_gem_json(gem_json): + logger.error(f'Gem json {gem_json} is not valid.') + return 1 + + # find all available modules in this gem_path + modules = cmake.get_gem_targets(gem_path=gem_path) + if len(modules) == 0: + logger.error(f'No gem modules found under {gem_path}.') + return 1 + + # if the gem has no modules and the user has specified a target fail + if gem_target and not modules: + logger.error(f'Gem has no targets, but gem target {gem_target} was specified.') + return 1 + + # if the gem target is not in the modules + if gem_target not in modules: + logger.error(f'Gem target not in gem modules: {modules}') + return 1 + + if gem_target: + # if the user has not specified either we will assume they meant the most common which is runtime + if not runtime_dependency and not tool_dependency and not server_dependency and not dependencies_file: + logger.warning("Dependency type not specified: Assuming '--runtime-dependency'") + runtime_dependency = True + + ret_val = 0 + + # if the user has specified the dependencies file then ignore the runtime_dependency and tool_dependency flags + if dependencies_file: + dependencies_file = pathlib.Path(dependencies_file).resolve() + # make sure this is a project has a dependencies_file + if not dependencies_file.is_file(): + logger.error(f'Dependencies file {dependencies_file} is not present.') + return 1 + # add the dependency + ret_val = add_gem_dependency(dependencies_file, gem_target) + + else: + if ',' in platforms: + platforms = platforms.split(',') + else: + platforms = [platforms] + for platform in platforms: + if runtime_dependency: + # make sure this is a project has a runtime_dependencies.cmake file + project_runtime_dependencies_file = pathlib.Path( + cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', + platform=platform)).resolve() + if not project_runtime_dependencies_file.is_file(): + logger.error(f'Runtime dependencies file {project_runtime_dependencies_file} is not present.') + return 1 + # add the dependency + ret_val = add_gem_dependency(project_runtime_dependencies_file, gem_target) + + if (ret_val == 0) and tool_dependency: + # make sure this is a project has a tool_dependencies.cmake file + project_tool_dependencies_file = pathlib.Path( + cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', + platform=platform)).resolve() + if not project_tool_dependencies_file.is_file(): + logger.error(f'Tool dependencies file {project_tool_dependencies_file} is not present.') + return 1 + # add the dependency + ret_val = add_gem_dependency(project_tool_dependencies_file, gem_target) + + if (ret_val == 0) and server_dependency: + # make sure this is a project has a tool_dependencies.cmake file + project_server_dependencies_file = pathlib.Path( + cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='server', + platform=platform)).resolve() + if not project_server_dependencies_file.is_file(): + logger.error(f'Server dependencies file {project_server_dependencies_file} is not present.') + return 1 + # add the dependency + ret_val = add_gem_dependency(project_server_dependencies_file, gem_target) + + if not ret_val and add_to_cmake: + ret_val = add_gem_cmake.add_gem_to_cmake(gem_path=gem_path, engine_path=engine_path) + + return ret_val + + +def _run_add_gem_to_project(args: argparse) -> int: + if args.override_home_folder: + manifest.override_home_folder = args.override_home_folder + + return add_gem_to_project(args.gem_name, + args.gem_path, + args.gem_target, + args.project_name, + args.project_path, + args.dependencies_file, + args.runtime_dependency, + args.tool_dependency, + args.server_dependency, + args.platforms, + args.add_to_cmake) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + add_gem_subparser = subparsers.add_parser('add-gem-to-project') + group = add_gem_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-pp', '--project-path', type=str, required=False, + help='The path to the project.') + group.add_argument('-pn', '--project-name', type=str, required=False, + help='The name of the project.') + group = add_gem_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-gp', '--gem-path', type=str, required=False, + help='The path to the gem.') + group.add_argument('-gn', '--gem-name', type=str, required=False, + help='The name of the gem.') + add_gem_subparser.add_argument('-gt', '--gem-target', type=str, required=False, + help='The cmake target name to add. If not specified it will assume gem_name') + add_gem_subparser.add_argument('-df', '--dependencies-file', type=str, required=False, + help='The cmake dependencies file in which the gem dependencies are specified.' + 'If not specified it will assume ') + add_gem_subparser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be added as a runtime dependency') + add_gem_subparser.add_argument('-td', '--tool-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be added as a tool dependency') + add_gem_subparser.add_argument('-sd', '--server-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be added as a server dependency') + add_gem_subparser.add_argument('-pl', '--platforms', type=str, required=False, + default='Common', + help='Optional list of platforms this gem should be added to.' + ' Ex. --platforms Mac,Windows,Linux') + add_gem_subparser.add_argument('-a', '--add-to-cmake', type=bool, required=False, + default=True, + help='Automatically call add-gem-to-cmake.') + + add_gem_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + add_gem_subparser.set_defaults(func=_run_add_gem_to_project) diff --git a/scripts/o3de/o3de/cmake.py b/scripts/o3de/o3de/cmake.py new file mode 100644 index 0000000000..b5b28cbb7e --- /dev/null +++ b/scripts/o3de/o3de/cmake.py @@ -0,0 +1,234 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +This file contains methods for introspecting data from cmake scripts +""" + +import logging +import os +import pathlib + +from o3de import manifest + +logger = logging.getLogger() +logging.basicConfig() + +def get_project_runtime_gem_targets(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) + + +def get_project_tool_gem_targets(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) + + +def get_project_server_gem_targets(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) + + +def get_project_gem_targets(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + runtime_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) + tool_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) + server_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) + return runtime_gems.union(tool_gems.union(server_gems)) + + +def get_gem_targets_from_cmake_file(cmake_file: str or pathlib.Path) -> set: + """ + Gets a list of declared gem targets dependencies of a cmake file + :param cmake_file: path to the cmake file + :return: set of gem targets found + """ + cmake_file = pathlib.Path(cmake_file).resolve() + + if not cmake_file.is_file(): + logger.error(f'Failed to locate cmake file {cmake_file}') + return set() + + gem_target_set = set() + with cmake_file.open('r') as s: + for line in s: + gem_name = line.split('Gem::') + if len(gem_name) > 1: + # Only take the name as everything leading up to the first '.' if found + # Gem naming conventions will have GemName.Editor, GemName.Server, and GemName + # as different targets of the GemName Gem + gem_target_set.add(gem_name[1].replace('\n', '')) + return gem_target_set + + +def get_project_runtime_gem_names(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) + + +def get_project_tool_gem_names(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) + + +def get_project_server_gem_names(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) + + +def get_project_gem_names(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + runtime_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) + tool_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) + server_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) + return runtime_gem_names.union(tool_gem_names.union(server_gem_names)) + + +def get_gem_names_from_cmake_file(cmake_file: str or pathlib.Path) -> set: + """ + Gets a list of declared gem dependencies of a cmake file + :param cmake_file: path to the cmake file + :return: set of gems found + """ + cmake_file = pathlib.Path(cmake_file).resolve() + + if not cmake_file.is_file(): + logger.error(f'Failed to locate cmake file {cmake_file}') + return set() + + gem_set = set() + with cmake_file.open('r') as s: + for line in s: + gem_name = line.split('Gem::') + if len(gem_name) > 1: + # Only take the name as everything leading up to the first '.' if found + # Gem naming conventions will have GemName.Editor, GemName.Server, and GemName + # as different targets of the GemName Gem + gem_set.add(gem_name[1].split('.')[0].replace('\n', '')) + return gem_set + + +def get_project_runtime_gem_paths(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + gem_names = get_project_runtime_gem_names(project_path, platform) + gem_paths = set() + for gem_name in gem_names: + gem_paths.add(manifest.get_registered(gem_name=gem_name)) + return gem_paths + + +def get_project_tool_gem_paths(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + gem_names = get_project_tool_gem_names(project_path, platform) + gem_paths = set() + for gem_name in gem_names: + gem_paths.add(manifest.get_registered(gem_name=gem_name)) + return gem_paths + + +def get_project_server_gem_paths(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + gem_names = get_project_server_gem_names(project_path, platform) + gem_paths = set() + for gem_name in gem_names: + gem_paths.add(manifest.get_registered(gem_name=gem_name)) + return gem_paths + + +def get_project_gem_paths(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + gem_names = get_project_gem_names(project_path, platform) + gem_paths = set() + for gem_name in gem_names: + gem_paths.add(manifest.get_registered(gem_name=gem_name)) + return gem_paths + + +def get_dependencies_cmake_file(project_name: str = None, + project_path: str or pathlib.Path = None, + dependency_type: str = 'runtime', + platform: str = 'Common') -> str or None: + """ + get the standard cmake file name for a particular type of dependency + :param gem_name: name of the gem, resolves gem_path + :param gem_path: path of the gem + :return: list of gem targets + """ + if not project_name and not project_path: + logger.error(f'Must supply either a Project Name or Project Path.') + return None + + if project_name and not project_path: + project_path = manifest.get_registered(project_name=project_name) + + project_path = pathlib.Path(project_path).resolve() + + if platform == 'Common': + dependencies_file = f'{dependency_type}_dependencies.cmake' + dependencies_file_path = project_path / 'Gem/Code' / dependencies_file + if dependencies_file_path.is_file(): + return dependencies_file_path + return project_path / 'Code' / dependencies_file + else: + dependencies_file = f'{platform.lower()}_{dependency_type}_dependencies.cmake' + dependencies_file_path = project_path / 'Gem/Code/Platform' / platform / dependencies_file + if dependencies_file_path.is_file(): + return dependencies_file_path + return project_path / 'Code/Platform' / platform / dependencies_file + + +def get_all_gem_targets() -> list: + modules = [] + for gem_path in manifest.get_all_gems(): + this_gems_targets = get_gem_targets(gem_path=gem_path) + modules.extend(this_gems_targets) + return modules + + +def get_gem_targets(gem_name: str = None, + gem_path: str or pathlib.Path = None) -> list: + """ + Finds gem targets in a gem + :param gem_name: name of the gem, resolves gem_path + :param gem_path: path of the gem + :return: list of gem targets + """ + if not gem_name and not gem_path: + return [] + + if gem_name and not gem_path: + gem_path = manifest.get_registered(gem_name=gem_name) + + if not gem_path: + return [] + + gem_path = pathlib.Path(gem_path).resolve() + gem_json = gem_path / 'gem.json' + if not validation.valid_o3de_gem_json(gem_json): + return [] + + module_identifiers = [ + 'MODULE', + 'GEM_MODULE', + '${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE}' + ] + modules = [] + for root, dirs, files in os.walk(gem_path): + for file in files: + if file == 'CMakeLists.txt': + with open(os.path.join(root, file), 'r') as s: + for line in s: + trimmed = line.lstrip() + if trimmed.startswith('NAME '): + trimmed = trimmed.rstrip(' \n') + split_trimmed = trimmed.split(' ') + if len(split_trimmed) == 3 and split_trimmed[2] in module_identifiers: + modules.append(split_trimmed[1]) + return modules diff --git a/scripts/o3de/o3de/download.py b/scripts/o3de/o3de/download.py new file mode 100644 index 0000000000..218463f98b --- /dev/null +++ b/scripts/o3de/o3de/download.py @@ -0,0 +1,598 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +This file contains functions for querying paths from ~/.o3de directory +""" + +import argparse +import hashlib +import json +import logging +import pathlib +import shutil +import urllib.parse +import urllib.request + +from o3de import manifest, utils, validation + +logger = logging.getLogger() +logging.basicConfig() + +def download_engine(engine_name: str, + dest_path: str) -> int: + if not dest_path: + dest_path = manifest.get_registered(default_folder='engines') + if not dest_path: + logger.error(f'Destination path not cannot be empty.') + return 1 + + dest_path = pathlib.Path(dest_path).resolve() + dest_path.mkdir(exist_ok=True) + + download_path = manifest.get_o3de_download_folder() / 'engines' / engine_name + download_path.mkdir(exist_ok=True) + download_zip_path = download_path / 'engine.zip' + + downloadable_engine_data = get_downloadable(engine_name=engine_name) + if not downloadable_engine_data: + logger.error(f'Downloadable engine {engine_name} not found.') + return 1 + + origin = downloadable_engine_data['origin'] + url = f'{origin}/project.zip' + parsed_uri = urllib.parse.urlparse(url) + + if download_zip_path.is_file(): + logger.warn(f'Project already downloaded to {download_zip_path}.') + elif parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(url) as s: + with download_zip_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_zip_path) + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"Engine zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + # if the engine.json has a sha256 check it against a sha256 of the zip + try: + sha256A = downloadable_engine_data['sha256'] + except Exception as e: + logger.warn(f'SECURITY WARNING: The advertised engine you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised engine!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded engine.zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the engine.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + dest_engine_folder = dest_path / engine_name + if dest_engine_folder.is_dir(): + utils.backup_folder(dest_engine_folder) + with zipfile.ZipFile(download_zip_path, 'r') as project_zip: + try: + project_zip.extractall(dest_path) + except Exception as e: + logger.error(f'UnZip exception:{str(e)}') + shutil.rmtree(dest_path) + return 1 + + unzipped_engine_json = dest_engine_folder / 'engine.json' + if not unzipped_engine_json.is_file(): + logger.error(f'Engine json {unzipped_engine_json} is missing.') + return 1 + + if not validation.valid_o3de_engine_json(unzipped_engine_json): + logger.error(f'Engine json {unzipped_engine_json} is invalid.') + return 1 + + # remove the sha256 if present in the advertised downloadable engine.json + # then compare it to the engine.json in the zip, they should now be identical + try: + del downloadable_engine_data['sha256'] + except Exception as e: + pass + + sha256A = hashlib.sha256(json.dumps(downloadable_engine_data, indent=4).encode('utf8')).hexdigest() + with unzipped_engine_json.open('r') as s: + try: + unzipped_engine_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to read engine json {unzipped_engine_json}. Unable to confirm this' + f' is the same template that was advertised.') + return 1 + sha256B = hashlib.sha256(json.dumps(unzipped_engine_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded engine.json does not match' + f' the advertised engine.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def download_project(project_name: str, + dest_path: str or pathlib.Path) -> int: + if not dest_path: + dest_path = manifest.get_registered(default_folder='projects') + if not dest_path: + logger.error(f'Destination path not specified and not default projects path.') + return 1 + + dest_path = pathlib.Path(dest_path).resolve() + dest_path.mkdir(exist_ok=True, parents=True) + + download_path = manifest.get_o3de_download_folder() / 'projects' / project_name + download_path.mkdir(exist_ok=True, parents=True) + download_zip_path = download_path / 'project.zip' + + downloadable_project_data = get_downloadable(project_name=project_name) + if not downloadable_project_data: + logger.error(f'Downloadable project {project_name} not found.') + return 1 + + origin = downloadable_project_data['origin'] + url = f'{origin}/project.zip' + parsed_uri = urllib.parse.urlparse(url) + + if download_zip_path.is_file(): + logger.warn(f'Project already downloaded to {download_zip_path}.') + elif parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(url) as s: + with download_zip_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_zip_path) + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"Project zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + # if the project.json has a sha256 check it against a sha256 of the zip + try: + sha256A = downloadable_project_data['sha256'] + except Exception as e: + logger.warn(f'SECURITY WARNING: The advertised project you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised project!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded project.zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the project.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + dest_project_folder = dest_path / project_name + if dest_project_folder.is_dir(): + utils.backup_folder(dest_project_folder) + with zipfile.ZipFile(download_zip_path, 'r') as project_zip: + try: + project_zip.extractall(dest_project_folder) + except Exception as e: + logger.error(f'UnZip exception:{str(e)}') + shutil.rmtree(dest_path) + return 1 + + unzipped_project_json = dest_project_folder / 'project.json' + if not unzipped_project_json.is_file(): + logger.error(f'Project json {unzipped_project_json} is missing.') + return 1 + + if not validation.valid_o3de_project_json(unzipped_project_json): + logger.error(f'Project json {unzipped_project_json} is invalid.') + return 1 + + # remove the sha256 if present in the advertised downloadable project.json + # then compare it to the project.json in the zip, they should now be identical + try: + del downloadable_project_data['sha256'] + except Exception as e: + pass + + sha256A = hashlib.sha256(json.dumps(downloadable_project_data, indent=4).encode('utf8')).hexdigest() + with unzipped_project_json.open('r') as s: + try: + unzipped_project_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to read Project json {unzipped_project_json}. Unable to confirm this' + f' is the same project that was advertised.') + return 1 + sha256B = hashlib.sha256(json.dumps(unzipped_project_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded project.json does not match' + f' the advertised project.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def download_gem(gem_name: str, + dest_path: str or pathlib.Path) -> int: + if not dest_path: + dest_path = manifest.get_registered(default_folder='gems') + if not dest_path: + logger.error(f'Destination path not cannot be empty.') + return 1 + + dest_path = pathlib.Path(dest_path).resolve() + dest_path.mkdir(exist_ok=True, parents=True) + + download_path = manifest.get_o3de_download_folder() / 'gems' / gem_name + download_path.mkdir(exist_ok=True, parents=True) + download_zip_path = download_path / 'gem.zip' + + downloadable_gem_data = get_downloadable(gem_name=gem_name) + if not downloadable_gem_data: + logger.error(f'Downloadable gem {gem_name} not found.') + return 1 + + origin = downloadable_gem_data['origin'] + url = f'{origin}/gem.zip' + parsed_uri = urllib.parse.urlparse(url) + + if download_zip_path.is_file(): + logger.warn(f'Project already downloaded to {download_zip_path}.') + elif parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(url) as s: + with download_zip_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_zip_path) + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"Gem zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + # if the gem.json has a sha256 check it against a sha256 of the zip + try: + sha256A = downloadable_gem_data['sha256'] + except Exception as e: + logger.warn(f'SECURITY WARNING: The advertised gem you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised gem!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded gem.zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the gem.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + dest_gem_folder = dest_path / gem_name + if dest_gem_folder.is_dir(): + utils.backup_folder(dest_gem_folder) + with zipfile.ZipFile(download_zip_path, 'r') as gem_zip: + try: + gem_zip.extractall(dest_path) + except Exception as e: + logger.error(f'UnZip exception:{str(e)}') + shutil.rmtree(dest_path) + return 1 + + unzipped_gem_json = dest_gem_folder / 'gem.json' + if not unzipped_gem_json.is_file(): + logger.error(f'Engine json {unzipped_gem_json} is missing.') + return 1 + + if not validation.valid_o3de_engine_json(unzipped_gem_json): + logger.error(f'Engine json {unzipped_gem_json} is invalid.') + return 1 + + # remove the sha256 if present in the advertised downloadable gem.json + # then compare it to the gem.json in the zip, they should now be identical + try: + del downloadable_gem_data['sha256'] + except Exception as e: + pass + + sha256A = hashlib.sha256(json.dumps(downloadable_gem_data, indent=4).encode('utf8')).hexdigest() + with unzipped_gem_json.open('r') as s: + try: + unzipped_gem_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to read gem json {unzipped_gem_json}. Unable to confirm this' + f' is the same gem that was advertised.') + return 1 + sha256B = hashlib.sha256(json.dumps(unzipped_gem_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded gem.json does not match' + f' the advertised gem.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def download_template(template_name: str, + dest_path: str or pathlib.Path) -> int: + if not dest_path: + dest_path = manifest.get_registered(default_folder='templates') + if not dest_path: + logger.error(f'Destination path not cannot be empty.') + return 1 + + dest_path = pathlib.Path(dest_path).resolve() + dest_path.mkdir(exist_ok=True, parents=True) + + download_path = manifest.get_o3de_download_folder() / 'templates' / template_name + download_path.mkdir(exist_ok=True, parents=True) + download_zip_path = download_path / 'template.zip' + + downloadable_template_data = get_downloadable(template_name=template_name) + if not downloadable_template_data: + logger.error(f'Downloadable template {template_name} not found.') + return 1 + + origin = downloadable_template_data['origin'] + url = f'{origin}/project.zip' + parsed_uri = urllib.parse.urlparse(url) + + result = 0 + + if download_zip_path.is_file(): + logger.warn(f'Project already downloaded to {download_zip_path}.') + elif parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(url) as s: + with download_zip_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_zip_path) + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"Template zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + # if the template.json has a sha256 check it against a sha256 of the zip + try: + sha256A = downloadable_template_data['sha256'] + except Exception as e: + logger.warn(f'SECURITY WARNING: The advertised template you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised template!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded template.zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the template.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + dest_template_folder = dest_path / template_name + if dest_template_folder.is_dir(): + utils.backup_folder(dest_template_folder) + with zipfile.ZipFile(download_zip_path, 'r') as project_zip: + try: + project_zip.extractall(dest_path) + except Exception as e: + logger.error(f'UnZip exception:{str(e)}') + shutil.rmtree(dest_path) + return 1 + + unzipped_template_json = dest_template_folder / 'template.json' + if not unzipped_template_json.is_file(): + logger.error(f'Template json {unzipped_template_json} is missing.') + return 1 + + if not validation.valid_o3de_engine_json(unzipped_template_json): + logger.error(f'Template json {unzipped_template_json} is invalid.') + return 1 + + # remove the sha256 if present in the advertised downloadable template.json + # then compare it to the template.json in the zip, they should now be identical + try: + del downloadable_template_data['sha256'] + except Exception as e: + pass + + sha256A = hashlib.sha256(json.dumps(downloadable_template_data, indent=4).encode('utf8')).hexdigest() + with unzipped_template_json.open('r') as s: + try: + unzipped_template_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to read Template json {unzipped_template_json}. Unable to confirm this' + f' is the same template that was advertised.') + return 1 + sha256B = hashlib.sha256(json.dumps(unzipped_template_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded template.json does not match' + f' the advertised template.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def download_restricted(restricted_name: str, + dest_path: str or pathlib.Path) -> int: + if not dest_path: + dest_path = manifest.get_registered(default_folder='restricted') + if not dest_path: + logger.error(f'Destination path not cannot be empty.') + return 1 + + dest_path = pathlib.Path(dest_path).resolve() + dest_path.mkdir(exist_ok=True, parents=True) + + download_path = manifest.get_o3de_download_folder() / 'restricted' / restricted_name + download_path.mkdir(exist_ok=True, parents=True) + download_zip_path = download_path / 'restricted.zip' + + downloadable_restricted_data = get_downloadable(restricted_name=restricted_name) + if not downloadable_restricted_data: + logger.error(f'Downloadable Restricted {restricted_name} not found.') + return 1 + + origin = downloadable_restricted_data['origin'] + url = f'{origin}/restricted.zip' + parsed_uri = urllib.parse.urlparse(url) + + if download_zip_path.is_file(): + logger.warn(f'Restricted already downloaded to {download_zip_path}.') + elif parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(url) as s: + with download_zip_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_zip_path) + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"Restricted zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + # if the restricted.json has a sha256 check it against a sha256 of the zip + try: + sha256A = downloadable_restricted_data['sha256'] + except Exception as e: + logger.warn(f'SECURITY WARNING: The advertised restricted you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised restricted!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded restricted.zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the restricted.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + dest_restricted_folder = dest_path / restricted_name + if dest_restricted_folder.is_dir(): + utils.backup_folder(dest_restricted_folder) + with zipfile.ZipFile(download_zip_path, 'r') as project_zip: + try: + project_zip.extractall(dest_path) + except Exception as e: + logger.error(f'UnZip exception:{str(e)}') + shutil.rmtree(dest_path) + return 1 + + unzipped_restricted_json = dest_restricted_folder / 'restricted.json' + if not unzipped_restricted_json.is_file(): + logger.error(f'Restricted json {unzipped_restricted_json} is missing.') + return 1 + + if not validation.valid_o3de_engine_json(unzipped_restricted_json): + logger.error(f'Restricted json {unzipped_restricted_json} is invalid.') + return 1 + + # remove the sha256 if present in the advertised downloadable restricted.json + # then compare it to the restricted.json in the zip, they should now be identical + try: + del downloadable_restricted_data['sha256'] + except Exception as e: + pass + + sha256A = hashlib.sha256(json.dumps(downloadable_restricted_data, indent=4).encode('utf8')).hexdigest() + with unzipped_restricted_json.open('r') as s: + try: + unzipped_restricted_json_data = json.load(s) + except Exception as e: + logger.error( + f'Failed to read Restricted json {unzipped_restricted_json}. Unable to confirm this' + f' is the same restricted that was advertised.') + return 1 + sha256B = hashlib.sha256( + json.dumps(unzipped_restricted_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded restricted.json does not match' + f' the advertised restricted.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def _run_download(args: argparse) -> int: + if args.override_home_folder: + manifest.override_home_folder = args.override_home_folder + + if args.engine_name: + return download_engine(args.engine_name, + args.dest_path) + elif args.project_name: + return download_project(args.project_name, + args.dest_path) + elif args.gem_nanme: + return download_gem(args.gem_name, + args.dest_path) + elif args.template_name: + return download_template(args.template_name, + args.dest_path) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + download_subparser = subparsers.add_parser('download') + group = download_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-e', '--engine-name', type=str, required=False, + help='Downloadable engine name.') + group.add_argument('-p', '--project-name', type=str, required=False, + help='Downloadable project name.') + group.add_argument('-g', '--gem-name', type=str, required=False, + help='Downloadable gem name.') + group.add_argument('-t', '--template-name', type=str, required=False, + help='Downloadable template name.') + download_subparser.add_argument('-dp', '--dest-path', type=str, required=False, + default=None, + help='Optional destination folder to download into.' + ' i.e. download --project-name "StarterGame" --dest-path "C:/projects"' + ' will result in C:/projects/StarterGame' + ' If blank will download to default object type folder') + + download_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + download_subparser.set_defaults(func=_run_download) + diff --git a/scripts/o3de/o3de/engine_template.py b/scripts/o3de/o3de/engine_template.py index 23acab33d4..ec390be480 100755 --- a/scripts/o3de/o3de/engine_template.py +++ b/scripts/o3de/o3de/engine_template.py @@ -21,7 +21,7 @@ import uuid import re -from o3de import utils, registration +from o3de import manifest, validation, utils logger = logging.getLogger() logging.basicConfig() @@ -321,7 +321,7 @@ def _instantiate_template(template_json_data: dict, platform_json = f'{template_restricted_platform_path_rel}/{template_file_name}'.replace('//', '/') if os.path.isfile(platform_json): - if not registration.valid_o3de_template_json(platform_json): + if not validation.valid_o3de_template_json(platform_json): logger.error(f'Template json {platform_json} is invalid.') return 1 @@ -403,7 +403,7 @@ def create_template(source_path: str, template_path = source_name template_path = template_path.replace('\\', '/') if not os.path.isabs(template_path): - default_templates_folder = registration.get_registered(default_folder='templates') + default_templates_folder = manifest.get_registered(default_folder='templates') template_path = f'{default_templates_folder}/{template_path}' logger.info(f'Template path not a full path. Using default templates folder {template_path}') if os.path.isdir(template_path): @@ -419,14 +419,14 @@ def create_template(source_path: str, return 1 if source_restricted_name and not source_restricted_path: - source_restricted_path = registration.get_registered(restricted_name=source_restricted_name) + source_restricted_path = manifest.get_registered(restricted_name=source_restricted_name) # source_restricted_path if source_restricted_path: source_restricted_path = source_restricted_path.replace('\\', '/') if not os.path.isabs(source_restricted_path): - engine_json = f'{registration.get_this_engine_path()}/engine.json' - if not registration.valid_o3de_engine_json(engine_json): + engine_json = f'{manifest.get_this_engine_path()}/engine.json' + if not validation.valid_o3de_engine_json(engine_json): logger.error(f"Engine json {engine_json} is not valid.") return 1 with open(engine_json) as s: @@ -436,11 +436,11 @@ def create_template(source_path: str, logger.error(f"Failed to read engine json {engine_json}: {str(e)}") return 1 try: - engine_restricted = engine_json_data['restricted'] + engine_restricted = engine_json_data['restricted_name'] except Exception as e: logger.error(f"Engine json {engine_json} restricted not found.") return 1 - engine_restricted_folder = registration.get_registered(restricted_name=engine_restricted) + engine_restricted_folder = manifest.get_registered(restricted_name=engine_restricted) new_source_restricted_path = f'{engine_restricted_folder}/{source_restricted_path}' logger.info(f'Source restricted path {source_restricted_path} not a full path. We must assume this engines' f' restricted folder {new_source_restricted_path}') @@ -449,7 +449,7 @@ def create_template(source_path: str, return 1 if template_restricted_name and not template_restricted_path: - template_restricted_path = registration.get_registered(restricted_name=template_restricted_name) + template_restricted_path = manifest.get_registered(restricted_name=template_restricted_name) if not template_restricted_name: template_restricted_name = template_name @@ -458,7 +458,7 @@ def create_template(source_path: str, if template_restricted_path: template_restricted_path = template_restricted_path.replace('\\', '/') if not os.path.isabs(template_restricted_path): - default_templates_restricted_folder = registration.get_registered(restricted_name='templates') + default_templates_restricted_folder = manifest.get_registered(restricted_name='templates') new_template_restricted_path = f'{default_templates_restricted_folder}/{template_restricted_path}' logger.info(f'Template restricted path {template_restricted_path} not a full path. We must assume the' f' default templates restricted folder {new_template_restricted_path}') @@ -466,10 +466,10 @@ def create_template(source_path: str, if os.path.isdir(template_restricted_path): # see if this is already a restricted path, if it is get the "restricted_name" from the restricted json - # so we can set "restricted" to it for this template + # so we can set "restricted_name" to it for this template restricted_json = f'{template_restricted_path}/restricted.json' if os.path.isfile(restricted_json): - if not registration.valid_o3de_restricted_json(restricted_json): + if not validation.valid_o3de_restricted_json(restricted_json): logger.error(f'{restricted_json} is not valid.') return 1 with open(restricted_json, 'r') as s: @@ -928,7 +928,7 @@ def create_template(source_path: str, json_data.update({'user_tags': [f"{template_name}"]}) json_data.update({'icon_path': "preview.png"}) if template_restricted_path: - json_data.update({'restricted': template_restricted_name}) + json_data.update({'restricted_name': template_restricted_name}) if template_restricted_platform_relative_path != '': json_data.update({'template_restricted_platform_relative_path': template_restricted_platform_relative_path}) json_data.update({'copyFiles': copy_files}) @@ -1048,7 +1048,7 @@ def create_from_template(destination_path: str, return 1 if template_name: - template_path = registration.get_registered(template_name=template_name) + template_path = manifest.get_registered(template_name=template_name) if not os.path.isdir(template_path): logger.error(f'Could not find the template {template_name}=>{template_path}') @@ -1059,7 +1059,7 @@ def create_from_template(destination_path: str, # the template.json should be in the template_path, make sure it's there a nd valid template_json = f'{template_path}/template.json' - if not registration.valid_o3de_template_json(template_json): + if not validation.valid_o3de_template_json(template_json): logger.error(f'Template json {template_path} is invalid.') return 1 @@ -1082,57 +1082,57 @@ def create_from_template(destination_path: str, # see if the template itself specifies a restricted name if not template_restricted_name and not template_restricted_path: try: - template_json_restricted_name = template_json_data['restricted'] + template_json_restricted_name = template_json_data['restricted_name'] except Exception as e: - # the template json doesn't have a 'restricted' element warn and use it - logger.info(f'The template does not specify a "restricted".') + # the template json doesn't have a 'restricted_name' element warn and use it + logger.info(f'The template does not specify a "restricted_name".') else: template_restricted_name = template_json_restricted_name # if no restricted name or path we continue on as if there is no template restricted files. if template_restricted_name or template_restricted_path: # If the user specified a --template-restricted-name we need to check that against the templates - # 'restricted' if it has one and see if they match. If they match then we don't have a problem. + # 'restricted_name' if it has one and see if they match. If they match then we don't have a problem. # If they don't then we error out. If supplied but not present in the template we warn and use it. # If not supplied we set what's in the template. If not supplied and not in the template we continue # on as if there is no template restricted files. if template_restricted_name: # The user specified a --template-restricted-name try: - template_json_restricted_name = template_json_data['restricted'] + template_json_restricted_name = template_json_data['restricted_name'] except Exception as e: - # the template json doesn't have a 'restricted' element warn and use it - logger.info(f'The template does not specify a "restricted".' + # the template json doesn't have a 'restricted_name' element warn and use it + logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_name}') else: if template_json_restricted_name != template_restricted_name: logger.error( f'The supplied --template-restricted-name {template_restricted_name} does not match the' - f' templates "restricted". Either the the --template-restricted-name is incorrect or the' - f' templates "restricted" is wrong. Note that since this template specifies "restricted" as' + f' templates "restricted_name". Either the the --template-restricted-name is incorrect or the' + f' templates "restricted_name" is wrong. Note that since this template specifies "restricted_name" as' f' {template_json_restricted_name}, --template-restricted-name need not be supplied.') - template_restricted_path = registration.get_registered(restricted_name=template_restricted_name) + template_restricted_path = manifest.get_registered(restricted_name=template_restricted_name) else: # The user has supplied the --template-restricted-path, see if that matches the template specifies. # If it does then we do not have a problem. If it doesn't match then error out. If not specified # in the template then warn and use the --template-restricted-path template_restricted_path = template_restricted_path.replace('\\', '/') try: - template_json_restricted_name = template_json_data['restricted'] + template_json_restricted_name = template_json_data['restricted_name'] except Exception as e: - # the template json doesn't have a 'restricted' element warn and use it - logger.info(f'The template does not specify a "restricted".' + # the template json doesn't have a 'restricted_name' element warn and use it + logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_path}') else: - template_json_restricted_path = registration.get_registered( + template_json_restricted_path = manifest.get_registered( restricted_name=template_json_restricted_name) if template_json_restricted_path != template_restricted_path: logger.error( f'The supplied --template-restricted-path {template_restricted_path} does not match the' - f' templates "restricted" {template_restricted_name} => {template_json_restricted_path}.' + f' templates "restricted_name" {template_restricted_name} => {template_json_restricted_path}.' f' Either the the supplied --template-restricted-path is incorrect or the templates' - f' "restricted" is wrong. Note that since this template specifies "restricted" as' + f' "restricted_name" is wrong. Note that since this template specifies "restricted_name" as' f' {template_json_restricted_name} --template-restricted-path need not be supplied' f' and {template_json_restricted_path} will be used.') return 1 @@ -1203,19 +1203,19 @@ def create_from_template(destination_path: str, # destination restricted name if destination_restricted_name: - destination_restricted_path = registration.get_registered(restricted_name=destination_restricted_name) + destination_restricted_path = manifest.get_registered(restricted_name=destination_restricted_name) # destination restricted path elif destination_restricted_path: destination_restricted_path = destination_restricted_path.replace('\\', '/') if os.path.isabs(destination_restricted_path): - restricted_default_path = registration.get_registered(default='restricted') + restricted_default_path = manifest.get_registered(default='restricted') new_destination_restricted_path = f'{restricted_default_path}/{destination_restricted_path}' logger.info(f'{destination_restricted_path} is not a full path, making it relative' f' to default restricted path = {new_destination_restricted_path}') destination_restricted_path = new_destination_restricted_path elif template_restricted_path: - restricted_default_path = registration.get_registered(default='restricted') + restricted_default_path = manifest.get_registered(default='restricted') logger.info(f'--destination-restricted-path is not specified, using default restricted path / destination name' f' = {restricted_default_path}') destination_restricted_path = restricted_default_path @@ -1337,7 +1337,7 @@ def create_project(project_path: str, template_name = 'DefaultProject' if template_name and not template_path: - template_path = registration.get_registered(template_name=template_name) + template_path = manifest.get_registered(template_name=template_name) if not os.path.isdir(template_path): logger.error(f'Could not find the template {template_name}=>{template_path}') @@ -1348,7 +1348,7 @@ def create_project(project_path: str, # the template.json should be in the template_path, make sure it's there and valid template_json = f'{template_path}/template.json' - if not registration.valid_o3de_template_json(template_json): + if not validation.valid_o3de_template_json(template_json): logger.error(f'Template json {template_path} is not valid.') return 1 @@ -1371,57 +1371,57 @@ def create_project(project_path: str, # see if the template itself specifies a restricted name if not template_restricted_name and not template_restricted_path: try: - template_json_restricted_name = template_json_data['restricted'] + template_json_restricted_name = template_json_data['restricted_name'] except Exception as e: - # the template json doesn't have a 'restricted' element warn and use it - logger.info(f'The template does not specify a "restricted".') + # the template json doesn't have a 'restricted_name' element warn and use it + logger.info(f'The template does not specify a "restricted_name".') else: template_restricted_name = template_json_restricted_name # if no restricted name or path we continue on as if there is no template restricted files. if template_restricted_name or template_restricted_path: # If the user specified a --template-restricted-name we need to check that against the templates - # 'restricted' if it has one and see if they match. If they match then we don't have a problem. + # 'restricted_name' if it has one and see if they match. If they match then we don't have a problem. # If they don't then we error out. If supplied but not present in the template we warn and use it. # If not supplied we set what's in the template. If not supplied and not in the template we continue # on as if there is no template restricted files. if template_restricted_name and not template_restricted_path: # The user specified a --template-restricted-name try: - template_json_restricted_name = template_json_data['restricted'] + template_json_restricted_name = template_json_data['restricted_name'] except Exception as e: - # the template json doesn't have a 'restricted' element warn and use it - logger.info(f'The template does not specify a "restricted".' + # the template json doesn't have a 'restricted_name' element warn and use it + logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_name}') else: if template_json_restricted_name != template_restricted_name: logger.error( f'The supplied --template-restricted-name {template_restricted_name} does not match the' - f' templates "restricted". Either the the --template-restricted-name is incorrect or the' - f' templates "restricted" is wrong. Note that since this template specifies "restricted" as' + f' templates "restricted_name". Either the the --template-restricted-name is incorrect or the' + f' templates "restricted_name" is wrong. Note that since this template specifies "restricted_name" as' f' {template_json_restricted_name}, --template-restricted-name need not be supplied.') - template_restricted_path = registration.get_registered(restricted_name=template_restricted_name) + template_restricted_path = manifest.get_registered(restricted_name=template_restricted_name) else: # The user has supplied the --template-restricted-path, see if that matches the template specifies. # If it does then we do not have a problem. If it doesn't match then error out. If not specified # in the template then warn and use the --template-restricted-path template_restricted_path = template_restricted_path.replace('\\', '/') try: - template_json_restricted_name = template_json_data['restricted'] + template_json_restricted_name = template_json_data['restricted_name'] except Exception as e: - # the template json doesn't have a 'restricted' element warn and use it - logger.info(f'The template does not specify a "restricted".' + # the template json doesn't have a 'restricted_name' element warn and use it + logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_path}') else: - template_json_restricted_path = registration.get_registered( + template_json_restricted_path = manifest.get_registered( restricted_name=template_json_restricted_name) if template_json_restricted_path != template_restricted_path: logger.error( f'The supplied --template-restricted-path {template_restricted_path} does not match the' - f' templates "restricted" {template_restricted_name} => {template_json_restricted_path}.' + f' templates "restricted_name" {template_restricted_name} => {template_json_restricted_path}.' f' Either the the supplied --template-restricted-path is incorrect or the templates' - f' "restricted" is wrong. Note that since this template specifies "restricted" as' + f' "restricted_name" is wrong. Note that since this template specifies "restricted_name" as' f' {template_json_restricted_name} --template-restricted-path need not be supplied' f' and {template_json_restricted_path} will be used.') return 1 @@ -1475,7 +1475,7 @@ def create_project(project_path: str, return 1 project_path = project_path.replace('\\', '/') if not os.path.isabs(project_path): - default_projects_folder = registration.get_registered(default_folder='projects') + default_projects_folder = manifest.get_registered(default_folder='projects') new_project_path = f'{default_projects_folder}/{project_path}' logger.info(f'Project Path {project_path} is not a full path, we must assume its relative' f' to default projects path = {new_project_path}') @@ -1496,19 +1496,19 @@ def create_project(project_path: str, # project restricted name if project_restricted_name and not project_restricted_path: - project_restricted_path = registration.get_registered(restricted_name=project_restricted_name) + project_restricted_path = manifest.get_registered(restricted_name=project_restricted_name) # project restricted path elif project_restricted_path: project_restricted_path = project_restricted_path.replace('\\', '/') if not os.path.isabs(project_restricted_path): - default_projects_restricted_folder = registration.get_registered(restricted_name='projects') + default_projects_restricted_folder = manifest.get_registered(restricted_name='projects') new_project_restricted_path = f'{default_projects_restricted_folder}/{project_restricted_path}' logger.info(f'Project restricted path {project_restricted_path} is not a full path, we must assume its' f' relative to default projects restricted path = {new_project_restricted_path}') project_restricted_path = new_project_restricted_path elif template_restricted_path: - project_restricted_default_path = registration.get_registered(restricted_name='projects') + project_restricted_default_path = manifest.get_registered(restricted_name='projects') logger.info(f'--project-restricted-path is not specified, using default project restricted path / project name' f' = {project_restricted_default_path}') project_restricted_path = project_restricted_default_path @@ -1585,7 +1585,7 @@ def create_project(project_path: str, # read the restricted_name from the projects restricted.json restricted_json = f"{project_restricted_path}/restricted.json".replace('//', '/') if os.path.isfile(restricted_json): - if not registration.valid_o3de_restricted_json(restricted_json): + if not validation.valid_o3de_restricted_json(restricted_json): logger.error(f'Restricted json {restricted_json} is not valid.') return 1 else: @@ -1607,9 +1607,9 @@ def create_project(project_path: str, logger.error(f'Failed to read "restricted_name" from restricted json {restricted_json}.') return 1 - # set the "restricted": "restricted_name" element of the project.json + # set the "restricted_name": "restricted_name" element of the project.json project_json = f"{project_path}/project.json".replace('//', '/') - if not registration.valid_o3de_project_json(project_json): + if not validation.valid_o3de_project_json(project_json): logger.error(f'Project json {project_json} is not valid.') return 1 @@ -1620,7 +1620,7 @@ def create_project(project_path: str, logger.error(f'Failed to load project json {project_json}.') return 1 - project_json_data.update({"restricted": restricted_name}) + project_json_data.update({"restricted_name": restricted_name}) os.unlink(project_json) with open(project_json, 'w') as s: try: @@ -1653,7 +1653,7 @@ def create_project(project_path: str, d.write('# {END_LICENSE}\n') # copy the o3de_manifest.cmake into the project root - engine_path = registration.get_this_engine_path() + engine_path = manifest.get_this_engine_path() o3de_manifest_cmake = f'{engine_path}/cmake/o3de_manifest.cmake' shutil.copy(o3de_manifest_cmake, project_path) @@ -1718,7 +1718,7 @@ def create_gem(gem_path: str, template_name = 'DefaultGem' if template_name and not template_path: - template_path = registration.get_registered(template_name=template_name) + template_path = manifest.get_registered(template_name=template_name) if not os.path.isdir(template_path): logger.error(f'Could not find the template {template_name}=>{template_path}') @@ -1729,7 +1729,7 @@ def create_gem(gem_path: str, # the template.json should be in the template_path, make sure it's there and valid template_json = f'{template_path}/template.json' - if not registration.valid_o3de_template_json(template_json): + if not validation.valid_o3de_template_json(template_json): logger.error(f'Template json {template_path} is not valid.') return 1 @@ -1752,56 +1752,56 @@ def create_gem(gem_path: str, # see if the template itself specifies a restricted name if not template_restricted_name and not template_restricted_path: try: - template_json_restricted_name = template_json_data['restricted'] + template_json_restricted_name = template_json_data['restricted_name'] except Exception as e: - # the template json doesn't have a 'restricted' element warn and use it - logger.info(f'The template does not specify a "restricted".') + # the template json doesn't have a 'restricted_name' element warn and use it + logger.info(f'The template does not specify a "restricted_name".') else: template_restricted_name = template_json_restricted_name # if no restricted name or path we continue on as if there is no template restricted files. if template_restricted_name or template_restricted_path: - # if the user specified a --template-restricted-name we need to check that against the templates 'restricted' + # if the user specified a --template-restricted-name we need to check that against the templates 'restricted_name' # if it has one and see if they match. If they match then we don't have a problem. If they don't then we error # out. If supplied but not present in the template we warn and use it. If not supplied we set what's in the # template. If not supplied and not in the template we continue on as if there is no template restricted files. if template_restricted_name and not template_restricted_path: # The user specified a --template-restricted-name try: - template_json_restricted_name = template_json_data['restricted'] + template_json_restricted_name = template_json_data['restricted_name'] except Exception as e: - # the template json doesn't have a 'restricted' element warn and use it - logger.info(f'The template does not specify a "restricted".' + # the template json doesn't have a 'restricted_name' element warn and use it + logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_name}') else: if template_json_restricted_name != template_restricted_name: logger.error( f'The supplied --template-restricted-name {template_restricted_name} does not match the' - f' templates "restricted". Either the the --template-restricted-name is incorrect or the' - f' templates "restricted" is wrong. Note that since this template specifies "restricted" as' + f' templates "restricted_name". Either the the --template-restricted-name is incorrect or the' + f' templates "restricted_name" is wrong. Note that since this template specifies "restricted_name" as' f' {template_json_restricted_name}, --template-restricted-name need not be supplied.') - template_restricted_path = registration.get_registered(restricted_name=template_restricted_name) + template_restricted_path = manifest.get_registered(restricted_name=template_restricted_name) else: # The user has supplied the --template-restricted-path, see if that matches the template specifies. # If it does then we do not have a problem. If it doesn't match then error out. If not specified # in the template then warn and use the --template-restricted-path template_restricted_path = template_restricted_path.replace('\\', '/') try: - template_json_restricted_name = template_json_data['restricted'] + template_json_restricted_name = template_json_data['restricted_name'] except Exception as e: - # the template json doesn't have a 'restricted' element warn and use it - logger.info(f'The template does not specify a "restricted".' + # the template json doesn't have a 'restricted_name' element warn and use it + logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_path}') else: - template_json_restricted_path = registration.get_registered( + template_json_restricted_path = manifest.get_registered( restricted_name=template_json_restricted_name) if template_json_restricted_path != template_restricted_path: logger.error( f'The supplied --template-restricted-path {template_restricted_path} does not match the' - f' templates "restricted" {template_restricted_name} => {template_json_restricted_path}.' + f' templates "restricted_name" {template_restricted_name} => {template_json_restricted_path}.' f' Either the the supplied --template-restricted-path is incorrect or the templates' - f' "restricted" is wrong. Note that since this template specifies "restricted" as' + f' "restricted_name" is wrong. Note that since this template specifies "restricted_name" as' f' {template_json_restricted_name} --template-restricted-path need not be supplied' f' and {template_json_restricted_path} will be used.') return 1 @@ -1854,7 +1854,7 @@ def create_gem(gem_path: str, return 1 gem_path = gem_path.replace('\\', '/') if not os.path.isabs(gem_path): - default_gems_folder = registration.get_registered(default_folder='gems') + default_gems_folder = manifest.get_registered(default_folder='gems') new_gem_path = f'{default_gems_folder}/{gem_path}' logger.info(f'Gem Path {gem_path} is not a full path, we must assume its relative' f' to default gems path = {new_gem_path}') @@ -1875,19 +1875,19 @@ def create_gem(gem_path: str, # gem restricted name if gem_restricted_name and not gem_restricted_path: - gem_restricted_path = registration.get_registered(restricted_name=gem_restricted_name) + gem_restricted_path = manifest.get_registered(restricted_name=gem_restricted_name) # gem restricted path elif gem_restricted_path: gem_restricted_path = gem_restricted_path.replace('\\', '/') if not os.path.isabs(gem_restricted_path): - default_gems_restricted_folder = registration.get_registered(restricted_name='gems') + default_gems_restricted_folder = manifest.get_registered(restricted_name='gems') new_gem_restricted_path = f'{default_gems_restricted_folder}/{gem_restricted_path}' logger.info(f'Gem restricted path {gem_restricted_path} is not a full path, we must assume its' f' relative to default gems restricted path = {new_gem_restricted_path}') gem_restricted_path = new_gem_restricted_path elif template_restricted_path: - gem_restricted_default_path = registration.get_registered(restricted_name='gems') + gem_restricted_default_path = manifest.get_registered(restricted_name='gems') logger.info(f'--gem-restricted-path is not specified, using default gem restricted path / gem name' f' = {gem_restricted_default_path}') gem_restricted_path = gem_restricted_default_path @@ -1964,7 +1964,7 @@ def create_gem(gem_path: str, # read the restricted_name from the gems restricted.json restricted_json = f"{gem_restricted_path}/restricted.json".replace('//', '/') if os.path.isfile(restricted_json): - if not registration.valid_o3de_restricted_json(restricted_json): + if not validation.valid_o3de_restricted_json(restricted_json): logger.error(f'Restricted json {restricted_json} is not valid.') return 1 else: @@ -1986,9 +1986,9 @@ def create_gem(gem_path: str, logger.error(f'Failed to read "restricted_name" from restricted json {restricted_json}.') return 1 - # set the "restricted": "restricted_name" element of the gem.json + # set the "restricted_name": "restricted_name" element of the gem.json gem_json = f"{gem_path}/gem.json".replace('//', '/') - if not registration.valid_o3de_gem_json(gem_json): + if not validation.valid_o3de_gem_json(gem_json): logger.error(f'Gem json {gem_json} is not valid.') return 1 @@ -1999,7 +1999,7 @@ def create_gem(gem_path: str, logger.error(f'Failed to load gem json {gem_json}.') return 1 - gem_json_data.update({"restricted": restricted_name}) + gem_json_data.update({"restricted_name": restricted_name}) os.unlink(gem_json) with open(gem_json, 'w') as s: try: @@ -2116,7 +2116,7 @@ def add_args(parser, subparsers) -> None: create_template_subparser.add_argument('-tp', '--template-path', type=str, required=False, help='The path to the template to create, can be absolute or relative' ' to default templates path') - group = create_template_subparser.add_mutually_exclusive_group(required=True) + group = create_template_subparser.add_mutually_exclusive_group(required=False) group.add_argument('-srp', '--source-restricted-path', type=str, required=False, default=None, help='The path to the source restricted folder.') @@ -2125,7 +2125,7 @@ def add_args(parser, subparsers) -> None: help='The name of the source restricted folder. If supplied this will resolve' ' the --source-restricted-path.') - group = create_template_subparser.add_mutually_exclusive_group(required=True) + group = create_template_subparser.add_mutually_exclusive_group(required=False) group.add_argument('-trp', '--template-restricted-path', type=str, required=False, default=None, help='The path to the templates restricted folder.') diff --git a/scripts/o3de/o3de/get_registration.py b/scripts/o3de/o3de/get_registration.py new file mode 100644 index 0000000000..c38d4d1cfb --- /dev/null +++ b/scripts/o3de/o3de/get_registration.py @@ -0,0 +1,62 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +import argparse +import pathlib + +from o3de import manifest + +def _run_get_registered(args: argparse) -> str or pathlib.Path: + if args.override_home_folder: + manifest.override_home_folder = args.override_home_folder + + return manifest.get_registered(args.engine_name, + args.project_name, + args.gem_name, + args.template_name, + args.default_folder, + args.repo_name, + args.restricted_name) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + get_registered_subparser = subparsers.add_parser('get-registered') + group = get_registered_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-en', '--engine-name', type=str, required=False, + help='Engine name.') + group.add_argument('-pn', '--project-name', type=str, required=False, + help='Project name.') + group.add_argument('-gn', '--gem-name', type=str, required=False, + help='Gem name.') + group.add_argument('-tn', '--template-name', type=str, required=False, + help='Template name.') + group.add_argument('-df', '--default-folder', type=str, required=False, + choices=['engines', 'projects', 'gems', 'templates', 'restricted'], + help='The default folders for o3de.') + group.add_argument('-rn', '--repo-name', type=str, required=False, + help='Repo name.') + group.add_argument('-rsn', '--restricted-name', type=str, required=False, + help='Restricted name.') + + get_registered_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + get_registered_subparser.set_defaults(func=_run_get_registered) diff --git a/scripts/o3de/o3de/global_project.py b/scripts/o3de/o3de/global_project.py index da1b5dfa80..1a17e3b79e 100644 --- a/scripts/o3de/o3de/global_project.py +++ b/scripts/o3de/o3de/global_project.py @@ -16,7 +16,7 @@ import sys import re import pathlib import json -from o3de import registration +from o3de import manifest logger = logging.getLogger() logging.basicConfig() @@ -39,7 +39,7 @@ def set_global_project(project_name: str or None, return 1 if project_name and not project_path: - project_path = registration.get_registered(project_name=project_name) + project_path = manifest.get_registered(project_name=project_name) if not project_path: logger.error(f'Project Path {project_path} has not been registered.') @@ -47,7 +47,7 @@ def set_global_project(project_name: str or None, project_path = pathlib.Path(project_path).resolve() - bootstrap_setreg_file = registration.get_o3de_registry_folder() / 'bootstrap.setreg' + bootstrap_setreg_file = manifest.get_o3de_registry_folder() / 'bootstrap.setreg' if bootstrap_setreg_file.is_file(): with bootstrap_setreg_file.open('r') as f: try: @@ -80,7 +80,7 @@ def get_global_project() -> pathlib.Path or None: get what the current project set is :return: project_path or None on failure """ - bootstrap_setreg_file = registration.get_o3de_registry_folder() / 'bootstrap.setreg' + bootstrap_setreg_file = manifest.get_o3de_registry_folder() / 'bootstrap.setreg' if not bootstrap_setreg_file.is_file(): logger.error(f'Bootstrap.setreg file {bootstrap_setreg_file} does not exist.') return None @@ -101,7 +101,7 @@ def get_global_project() -> pathlib.Path or None: def _run_get_global_project(args: argparse) -> int: if args.override_home_folder: - registration.override_home_folder = args.override_home_folder + manifest.override_home_folder = args.override_home_folder project_path = get_global_project() if project_path: @@ -112,7 +112,7 @@ def _run_get_global_project(args: argparse) -> int: def _run_set_global_project(args: argparse) -> int: if args.override_home_folder: - registration.override_home_folder = args.override_home_folder + manifest.override_home_folder = args.override_home_folder return set_global_project(args.project_name, args.project_path) diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py new file mode 100644 index 0000000000..b3aac6d1f3 --- /dev/null +++ b/scripts/o3de/o3de/manifest.py @@ -0,0 +1,600 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +This file contains functions for querying paths from ~/.o3de directory +""" + +import json +import logging +import os +import pathlib + +from o3de import validation + +logger = logging.getLogger() +logging.basicConfig() + +# Directory methods +override_home_folder = None + + +def get_this_engine_path() -> pathlib.Path: + return pathlib.Path(os.path.realpath(__file__)).parents[3].resolve() + + +def get_home_folder() -> pathlib.Path: + if override_home_folder: + return pathlib.Path(override_home_folder).resolve() + else: + return pathlib.Path(os.path.expanduser("~")).resolve() + + +def get_o3de_folder() -> pathlib.Path: + o3de_folder = get_home_folder() / '.o3de' + o3de_folder.mkdir(parents=True, exist_ok=True) + return o3de_folder + + +def get_o3de_registry_folder() -> pathlib.Path: + registry_folder = get_o3de_folder() / 'Registry' + registry_folder.mkdir(parents=True, exist_ok=True) + return registry_folder + + +def get_o3de_cache_folder() -> pathlib.Path: + cache_folder = get_o3de_folder() / 'Cache' + cache_folder.mkdir(parents=True, exist_ok=True) + return cache_folder + + +def get_o3de_download_folder() -> pathlib.Path: + download_folder = get_o3de_folder() / 'Download' + download_folder.mkdir(parents=True, exist_ok=True) + return download_folder + + +def get_o3de_engines_folder() -> pathlib.Path: + engines_folder = get_o3de_folder() / 'Engines' + engines_folder.mkdir(parents=True, exist_ok=True) + return engines_folder + + +def get_o3de_projects_folder() -> pathlib.Path: + projects_folder = get_o3de_folder() / 'Projects' + projects_folder.mkdir(parents=True, exist_ok=True) + return projects_folder + + +def get_o3de_gems_folder() -> pathlib.Path: + gems_folder = get_o3de_folder() / 'Gems' + gems_folder.mkdir(parents=True, exist_ok=True) + return gems_folder + + +def get_o3de_templates_folder() -> pathlib.Path: + templates_folder = get_o3de_folder() / 'Templates' + templates_folder.mkdir(parents=True, exist_ok=True) + return templates_folder + + +def get_o3de_restricted_folder() -> pathlib.Path: + restricted_folder = get_o3de_folder() / 'Restricted' + restricted_folder.mkdir(parents=True, exist_ok=True) + return restricted_folder + + +def get_o3de_logs_folder() -> pathlib.Path: + logs_folder = get_o3de_folder() / 'Logs' + logs_folder.mkdir(parents=True, exist_ok=True) + return logs_folder + + +# o3de manifest file methods +def get_o3de_manifest() -> pathlib.Path: + manifest_path = get_o3de_folder() / 'o3de_manifest.json' + if not manifest_path.is_file(): + username = os.path.split(get_home_folder())[-1] + + o3de_folder = get_o3de_folder() + default_registry_folder = get_o3de_registry_folder() + default_cache_folder = get_o3de_cache_folder() + default_downloads_folder = get_o3de_download_folder() + default_logs_folder = get_o3de_logs_folder() + default_engines_folder = get_o3de_engines_folder() + default_projects_folder = get_o3de_projects_folder() + default_gems_folder = get_o3de_gems_folder() + default_templates_folder = get_o3de_templates_folder() + default_restricted_folder = get_o3de_restricted_folder() + + default_projects_restricted_folder = default_projects_folder / 'Restricted' + default_projects_restricted_folder.mkdir(parents=True, exist_ok=True) + default_gems_restricted_folder = default_gems_folder / 'Restricted' + default_gems_restricted_folder.mkdir(parents=True, exist_ok=True) + default_templates_restricted_folder = default_templates_folder / 'Restricted' + default_templates_restricted_folder.mkdir(parents=True, exist_ok=True) + + json_data = {} + json_data.update({'o3de_manifest_name': f'{username}'}) + json_data.update({'origin': o3de_folder.as_posix()}) + json_data.update({'default_engines_folder': default_engines_folder.as_posix()}) + json_data.update({'default_projects_folder': default_projects_folder.as_posix()}) + json_data.update({'default_gems_folder': default_gems_folder.as_posix()}) + json_data.update({'default_templates_folder': default_templates_folder.as_posix()}) + json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) + + json_data.update({'projects': []}) + json_data.update({'gems': []}) + json_data.update({'templates': []}) + json_data.update({'restricted': []}) + json_data.update({'repos': []}) + json_data.update({'engines': []}) + + default_restricted_folder_json = default_restricted_folder / 'restricted.json' + if not default_restricted_folder_json.is_file(): + with default_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'o3de'}) + s.write(json.dumps(restricted_json_data, indent=4)) + json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) + + default_projects_restricted_folder_json = default_projects_restricted_folder / 'restricted.json' + if not default_projects_restricted_folder_json.is_file(): + with default_projects_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'projects'}) + s.write(json.dumps(restricted_json_data, indent=4)) + + default_gems_restricted_folder_json = default_gems_restricted_folder / 'restricted.json' + if not default_gems_restricted_folder_json.is_file(): + with default_gems_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'gems'}) + s.write(json.dumps(restricted_json_data, indent=4)) + + default_templates_restricted_folder_json = default_templates_restricted_folder / 'restricted.json' + if not default_templates_restricted_folder_json.is_file(): + with default_templates_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'templates'}) + s.write(json.dumps(restricted_json_data, indent=4)) + + with manifest_path.open('w') as s: + s.write(json.dumps(json_data, indent=4)) + + return manifest_path + + +def load_o3de_manifest() -> dict: + with get_o3de_manifest().open('r') as f: + try: + json_data = json.load(f) + except Exception as e: + logger.error(f'Manifest json failed to load: {str(e)}') + return {} + else: + return json_data + + +def save_o3de_manifest(json_data: dict) -> None: + with get_o3de_manifest().open('w') as s: + try: + s.write(json.dumps(json_data, indent=4)) + except Exception as e: + logger.error(f'Manifest json failed to save: {str(e)}') + + +# Data query methods +def get_this_engine() -> dict: + json_data = load_o3de_manifest() + engine_data = find_engine_data(json_data) + return engine_data + + +def get_engines() -> dict: + json_data = load_o3de_manifest() + return json_data['engines'] + + +def get_projects() -> dict: + json_data = load_o3de_manifest() + return json_data['projects'] + + +def get_gems() -> dict: + json_data = load_o3de_manifest() + return json_data['gems'] + + +def get_templates() -> dict: + json_data = load_o3de_manifest() + return json_data['templates'] + + +def get_restricted() -> dict: + json_data = load_o3de_manifest() + return json_data['restricted'] + + +def get_repos() -> dict: + json_data = load_o3de_manifest() + return json_data['repos'] + + +def get_engine_projects() -> list: + engine_path = get_this_engine_path() + engine_object = get_engine_json_data(engine_path=engine_path) + return list(map(lambda rel_path: (pathlib.Path(engine_path) / rel_path).as_posix(), + engine_object['projects'])) if 'projects' in engine_object else [] + + +def get_engine_gems() -> list: + def is_gem_subdirectory(subdir): + return (pathlib.Path(subdir) / 'gem.json').exists() + + external_subdirs = get_engine_external_subdirectories() + return list(filter(is_gem_subdirectory, external_subdirs)) if external_subdirs else [] + + +def get_engine_templates() -> list: + engine_path = get_this_engine_path() + engine_object = get_engine_json_data(engine_path=engine_path) + return list(map(lambda rel_path: (pathlib.Path(engine_path) / rel_path).as_posix(), + engine_object['templates'])) + + +def get_engine_restricted() -> list: + engine_path = get_this_engine_path() + engine_object = get_engine_json_data(engine_path=engine_path) + return list(map(lambda rel_path: (pathlib.Path(engine_path) / rel_path).as_posix(), + engine_object['restricted'])) if 'restricted' in engine_object else [] + + +def get_engine_external_subdirectories() -> list: + engine_path = get_this_engine_path() + engine_object = get_engine_json_data(engine_path=engine_path) + return list(map(lambda rel_path: (pathlib.Path(engine_path) / rel_path).as_posix(), + engine_object['external_subdirectories'])) if 'external_subdirectories' in engine_object else [] + + +def get_all_projects() -> list: + engine_projects = get_engine_projects() + projects_data = get_projects() + projects_data.extend(engine_projects) + return projects_data + + +def get_all_gems() -> list: + engine_gems = get_engine_gems() + gems_data = get_gems() + gems_data.extend(engine_gems) + return gems_data + + +def get_all_templates() -> list: + engine_templates = get_engine_templates() + templates_data = get_templates() + templates_data.extend(engine_templates) + return templates_data + + +def get_all_restricted() -> list: + engine_restricted = get_engine_restricted() + restricted_data = get_restricted() + restricted_data.extend(engine_restricted) + return restricted_data + + +def find_engine_data(json_data: dict, + engine_path: str or pathlib.Path = None) -> dict or None: + if not engine_path: + engine_path = get_this_engine_path() + engine_path = pathlib.Path(engine_path).resolve() + + for engine_object in json_data['engines']: + engine_object_path = pathlib.Path(engine_object['path']).resolve() + if engine_path == engine_object_path: + return engine_object + + return None + + +def get_engine_json_data(engine_name: str = None, + engine_path: str or pathlib.Path = None) -> dict or None: + if not engine_name and not engine_path: + logger.error('Must specify either a Engine name or Engine Path.') + return None + + if engine_name and not engine_path: + engine_path = get_registered(engine_name=engine_name) + + if not engine_path: + logger.error(f'Engine Path {engine_path} has not been registered.') + return None + + engine_path = pathlib.Path(engine_path).resolve() + engine_json = engine_path / 'engine.json' + if not engine_json.is_file(): + logger.error(f'Engine json {engine_json} is not present.') + return None + if not validation.valid_o3de_engine_json(engine_json): + logger.error(f'Engine json {engine_json} is not valid.') + return None + + with engine_json.open('r') as f: + try: + engine_json_data = json.load(f) + except Exception as e: + logger.warn(f'{engine_json} failed to load: {str(e)}') + else: + return engine_json_data + + return None + + +def get_project_json_data(project_name: str = None, + project_path: str or pathlib.Path = None) -> dict or None: + if not project_name and not project_path: + logger.error('Must specify either a Project name or Project Path.') + return None + + if project_name and not project_path: + project_path = get_registered(project_name=project_name) + + if not project_path: + logger.error(f'Project Path {project_path} has not been registered.') + return None + + project_path = pathlib.Path(project_path).resolve() + project_json = project_path / 'project.json' + if not project_json.is_file(): + logger.error(f'Project json {project_json} is not present.') + return None + if not validation.valid_o3de_project_json(project_json): + logger.error(f'Project json {project_json} is not valid.') + return None + + with project_json.open('r') as f: + try: + project_json_data = json.load(f) + except Exception as e: + logger.warn(f'{project_json} failed to load: {str(e)}') + else: + return project_json_data + + return None + + +def get_gem_json_data(gem_name: str = None, + gem_path: str or pathlib.Path = None) -> dict or None: + if not gem_name and not gem_path: + logger.error('Must specify either a Gem name or Gem Path.') + return None + + if gem_name and not gem_path: + gem_path = get_registered(gem_name=gem_name) + + if not gem_path: + logger.error(f'Gem Path {gem_path} has not been registered.') + return None + + gem_path = pathlib.Path(gem_path).resolve() + gem_json = gem_path / 'gem.json' + if not gem_json.is_file(): + logger.error(f'Gem json {gem_json} is not present.') + return None + if not validation.valid_o3de_gem_json(gem_json): + logger.error(f'Gem json {gem_json} is not valid.') + return None + + with gem_json.open('r') as f: + try: + gem_json_data = json.load(f) + except Exception as e: + logger.warn(f'{gem_json} failed to load: {str(e)}') + else: + return gem_json_data + + return None + + +def get_template_json_data(template_name: str = None, + template_path: str or pathlib.Path = None) -> dict or None: + if not template_name and not template_path: + logger.error('Must specify either a Template name or Template Path.') + return None + + if template_name and not template_path: + template_path = get_registered(template_name=template_name) + + if not template_path: + logger.error(f'Template Path {template_path} has not been registered.') + return None + + template_path = pathlib.Path(template_path).resolve() + template_json = template_path / 'template.json' + if not template_json.is_file(): + logger.error(f'Template json {template_json} is not present.') + return None + if not validation.valid_o3de_template_json(template_json): + logger.error(f'Template json {template_json} is not valid.') + return None + + with template_json.open('r') as f: + try: + template_json_data = json.load(f) + except Exception as e: + logger.warn(f'{template_json} failed to load: {str(e)}') + else: + return template_json_data + + return None + + +def get_restricted_data(restricted_name: str = None, + restricted_path: str or pathlib.Path = None) -> dict or None: + if not restricted_name and not restricted_path: + logger.error('Must specify either a Restricted name or Restricted Path.') + return None + + if restricted_name and not restricted_path: + restricted_path = get_registered(restricted_name=restricted_name) + + if not restricted_path: + logger.error(f'Restricted Path {restricted_path} has not been registered.') + return None + + restricted_path = pathlib.Path(restricted_path).resolve() + restricted_json = restricted_path / 'restricted.json' + if not restricted_json.is_file(): + logger.error(f'Restricted json {restricted_json} is not present.') + return None + if not validation.valid_o3de_restricted_json(restricted_json): + logger.error(f'Restricted json {restricted_json} is not valid.') + return None + + with restricted_json.open('r') as f: + try: + restricted_json_data = json.load(f) + except Exception as e: + logger.warn(f'{restricted_json} failed to load: {str(e)}') + else: + return restricted_json_data + + return None + + +def get_registered(engine_name: str = None, + project_name: str = None, + gem_name: str = None, + template_name: str = None, + default_folder: str = None, + repo_name: str = None, + restricted_name: str = None) -> pathlib.Path or None: + json_data = load_o3de_manifest() + + # check global first then this engine + if isinstance(engine_name, str): + for engine in json_data['engines']: + engine_path = pathlib.Path(engine['path']).resolve() + engine_json = engine_path / 'engine.json' + with engine_json.open('r') as f: + try: + engine_json_data = json.load(f) + except Exception as e: + logger.warn(f'{engine_json} failed to load: {str(e)}') + else: + this_engines_name = engine_json_data['engine_name'] + if this_engines_name == engine_name: + return engine_path + + elif isinstance(project_name, str): + engine_object = find_engine_data(json_data) + projects = json_data['projects'].copy() + projects.extend(engine_object['projects']) + for project_path in projects: + project_path = pathlib.Path(project_path).resolve() + project_json = project_path / 'project.json' + with project_json.open('r') as f: + try: + project_json_data = json.load(f) + except Exception as e: + logger.warn(f'{project_json} failed to load: {str(e)}') + else: + this_projects_name = project_json_data['project_name'] + if this_projects_name == project_name: + return project_path + + elif isinstance(gem_name, str): + engine_object = find_engine_data(json_data) + gems = json_data['gems'].copy() + gems.extend(engine_object['gems']) + for gem_path in gems: + gem_path = pathlib.Path(gem_path).resolve() + gem_json = gem_path / 'gem.json' + with gem_json.open('r') as f: + try: + gem_json_data = json.load(f) + except Exception as e: + logger.warn(f'{gem_json} failed to load: {str(e)}') + else: + this_gems_name = gem_json_data['gem_name'] + if this_gems_name == gem_name: + return gem_path + + elif isinstance(template_name, str): + engine_object = find_engine_data(json_data) + templates = json_data['templates'].copy() + templates.extend(engine_object['templates']) + for template_path in templates: + template_path = pathlib.Path(template_path).resolve() + template_json = template_path / 'template.json' + with template_json.open('r') as f: + try: + template_json_data = json.load(f) + except Exception as e: + logger.warn(f'{template_path} failed to load: {str(e)}') + else: + this_templates_name = template_json_data['template_name'] + if this_templates_name == template_name: + return template_path + + elif isinstance(restricted_name, str): + engine_object = find_engine_data(json_data) + restricted = json_data['restricted'].copy() + restricted.extend(engine_object['restricted']) + for restricted_path in restricted: + restricted_path = pathlib.Path(restricted_path).resolve() + restricted_json = restricted_path / 'restricted.json' + with restricted_json.open('r') as f: + try: + restricted_json_data = json.load(f) + except Exception as e: + logger.warn(f'{restricted_json} failed to load: {str(e)}') + else: + this_restricted_name = restricted_json_data['restricted_name'] + if this_restricted_name == restricted_name: + return restricted_path + + elif isinstance(default_folder, str): + if default_folder == 'engines': + default_engines_folder = pathlib.Path(json_data['default_engines_folder']).resolve() + return default_engines_folder + elif default_folder == 'projects': + default_projects_folder = pathlib.Path(json_data['default_projects_folder']).resolve() + return default_projects_folder + elif default_folder == 'gems': + default_gems_folder = pathlib.Path(json_data['default_gems_folder']).resolve() + return default_gems_folder + elif default_folder == 'templates': + default_templates_folder = pathlib.Path(json_data['default_templates_folder']).resolve() + return default_templates_folder + elif default_folder == 'restricted': + default_restricted_folder = pathlib.Path(json_data['default_restricted_folder']).resolve() + return default_restricted_folder + + elif isinstance(repo_name, str): + cache_folder = get_o3de_cache_folder() + for repo_uri in json_data['repos']: + repo_uri = pathlib.Path(repo_uri).resolve() + repo_sha256 = hashlib.sha256(repo_uri.encode()) + cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') + if cache_file.is_file(): + repo = pathlib.Path(cache_file).resolve() + with repo.open('r') as f: + try: + repo_json_data = json.load(f) + except Exception as e: + logger.warn(f'{cache_file} failed to load: {str(e)}') + else: + this_repos_name = repo_json_data['repo_name'] + if this_repos_name == repo_name: + return repo_uri + return None diff --git a/scripts/o3de/o3de/print_registration.py b/scripts/o3de/o3de/print_registration.py new file mode 100644 index 0000000000..7900fad7e4 --- /dev/null +++ b/scripts/o3de/o3de/print_registration.py @@ -0,0 +1,456 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +import argparse +import json +import hashlib +import logging +import urllib.parse + +from o3de import manifest, validation + +logger = logging.getLogger() +logging.basicConfig() + +def print_this_engine(verbose: int) -> None: + engine_data = manifest.get_this_engine() + print(json.dumps(engine_data, indent=4)) + if verbose > 0: + print_engines_data(engine_data) + + +def print_engines(verbose: int) -> None: + engines_data = manifest.get_engines() + print(json.dumps(engines_data, indent=4)) + if verbose > 0: + print_engines_data(engines_data) + + +def print_projects(verbose: int) -> None: + projects_data = manifest.get_projects() + print(json.dumps(projects_data, indent=4)) + if verbose > 0: + print_projects_data(projects_data) + + +def print_gems(verbose: int) -> None: + gems_data = manifest.get_gems() + print(json.dumps(gems_data, indent=4)) + if verbose > 0: + print_gems_data(gems_data) + + +def print_templates(verbose: int) -> None: + templates_data = manifest.get_templates() + print(json.dumps(templates_data, indent=4)) + if verbose > 0: + print_templates_data(templates_data) + + +def print_restricted(verbose: int) -> None: + restricted_data = manifest.get_restricted() + print(json.dumps(restricted_data, indent=4)) + if verbose > 0: + print_restricted_data(restricted_data) + +def print_engine_projects(verbose: int) -> None: + engine_projects_data = manifest.get_engine_projects() + print(json.dumps(engine_projects_data, indent=4)) + if verbose > 0: + print_projects_data(engine_projects_data) + + +def print_engine_gems(verbose: int) -> None: + engine_gems_data = manifest.get_engine_gems() + print(json.dumps(engine_gems_data, indent=4)) + if verbose > 0: + print_gems_data(engine_gems_data) + + +def print_engine_templates(verbose: int) -> None: + engine_templates_data = manifest.get_engine_templates() + print(json.dumps(engine_templates_data, indent=4)) + if verbose > 0: + print_templates_data(engine_templates_data) + + +def print_engine_restricted(verbose: int) -> None: + engine_restricted_data = manifest.get_engine_restricted() + print(json.dumps(engine_restricted_data, indent=4)) + if verbose > 0: + print_restricted_data(engine_restricted_data) + + +def print_engine_external_subdirectories(verbose: int) -> None: + external_subdirs_data = manifest.get_engine_external_subdirectories() + print(json.dumps(external_subdirs_data, indent=4)) + + +def print_all_projects(verbose: int) -> None: + all_projects_data = manifest.get_all_projects() + print(json.dumps(all_projects_data, indent=4)) + if verbose > 0: + print_projects_data(all_projects_data) + + +def print_all_gems(verbose: int) -> None: + all_gems_data = manifest.get_all_gems() + print(json.dumps(all_gems_data, indent=4)) + if verbose > 0: + print_gems_data(all_gems_data) + + +def print_all_templates(verbose: int) -> None: + all_templates_data = manifest.get_all_templates() + print(json.dumps(all_templates_data, indent=4)) + if verbose > 0: + print_templates_data(all_templates_data) + + +def print_all_restricted(verbose: int) -> None: + all_restricted_data = manifest.get_all_restricted() + print(json.dumps(all_restricted_data, indent=4)) + if verbose > 0: + print_restricted_data(all_restricted_data) + + +def print_engines_data(engines_data: dict) -> None: + print('\n') + print("Engines================================================") + for engine_object in engines_data: + # if it's not local it should be in the cache + engine_uri = engine_object['path'] + parsed_uri = urllib.parse.urlparse(engine_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + repo_sha256 = hashlib.sha256(engine_uri.encode()) + cache_folder = manifest.get_o3de_cache_folder() + engine = cache_folder / str(repo_sha256.hexdigest() + '.json') + print(f'{engine_uri}/engine.json cached as:') + else: + engine_json = pathlib.Path(engine_uri).resolve() / 'engine.json' + + with engine_json.open('r') as f: + try: + engine_json_data = json.load(f) + except Exception as e: + logger.warn(f'{engine_json} failed to load: {str(e)}') + else: + print(engine_json) + print(json.dumps(engine_json_data, indent=4)) + print('\n') + + +def print_projects_data(projects_data: dict) -> None: + print('\n') + print("Projects================================================") + for project_uri in projects_data: + # if it's not local it should be in the cache + parsed_uri = urllib.parse.urlparse(project_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + repo_sha256 = hashlib.sha256(project_uri.encode()) + cache_folder = manifest.get_o3de_cache_folder() + project_json = cache_folder / str(repo_sha256.hexdigest() + '.json') + else: + project_json = pathlib.Path(project_uri).resolve() / 'project.json' + + with project_json.open('r') as f: + try: + project_json_data = json.load(f) + except Exception as e: + logger.warn(f'{project_json} failed to load: {str(e)}') + else: + print(project_json) + print(json.dumps(project_json_data, indent=4)) + print('\n') + + +def print_gems_data(gems_data: dict) -> None: + print('\n') + print("Gems================================================") + for gem_uri in gems_data: + # if it's not local it should be in the cache + parsed_uri = urllib.parse.urlparse(gem_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + repo_sha256 = hashlib.sha256(gem_uri.encode()) + cache_folder = manifest.get_o3de_cache_folder() + gem_json = cache_folder / str(repo_sha256.hexdigest() + '.json') + else: + gem_json = pathlib.Path(gem_uri).resolve() / 'gem.json' + + with gem_json.open('r') as f: + try: + gem_json_data = json.load(f) + except Exception as e: + logger.warn(f'{gem_json} failed to load: {str(e)}') + else: + print(gem_json) + print(json.dumps(gem_json_data, indent=4)) + print('\n') + + +def print_templates_data(templates_data: dict) -> None: + print('\n') + print("Templates================================================") + for template_uri in templates_data: + # if it's not local it should be in the cache + parsed_uri = urllib.parse.urlparse(template_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + repo_sha256 = hashlib.sha256(template_uri.encode()) + cache_folder = manifest.get_o3de_cache_folder() + template_json = cache_folder / str(repo_sha256.hexdigest() + '.json') + else: + template_json = pathlib.Path(template_uri).resolve() / 'template.json' + + with template_json.open('r') as f: + try: + template_json_data = json.load(f) + except Exception as e: + logger.warn(f'{template_json} failed to load: {str(e)}') + else: + print(template_json) + print(json.dumps(template_json_data, indent=4)) + print('\n') + + +def print_repos_data(repos_data: dict) -> None: + print('\n') + print("Repos================================================") + cache_folder = manifest.get_o3de_cache_folder() + for repo_uri in repos_data: + repo_sha256 = hashlib.sha256(repo_uri.encode()) + cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') + if validation.valid_o3de_repo_json(cache_file): + with cache_file.open('r') as s: + try: + repo_json_data = json.load(s) + except Exception as e: + logger.warn(f'{cache_file} failed to load: {str(e)}') + else: + print(f'{repo_uri}/repo.json cached as:') + print(cache_file) + print(json.dumps(repo_json_data, indent=4)) + print('\n') + + +def print_restricted_data(restricted_data: dict) -> None: + print('\n') + print("Restricted================================================") + for restricted_path in restricted_data: + restricted_json = pathlib.Path(restricted_path).resolve() / 'restricted.json' + with restricted_json.open('r') as f: + try: + restricted_json_data = json.load(f) + except Exception as e: + logger.warn(f'{restricted_json} failed to load: {str(e)}') + else: + print(restricted_json) + print(json.dumps(restricted_json_data, indent=4)) + print('\n') + + +def register_show_repos(verbose: int) -> None: + repos_data = get_repos() + print(json.dumps(repos_data, indent=4)) + if verbose > 0: + print_repos_data(repos_data) + + +def register_show(verbose: int) -> None: + json_data = manifest.load_o3de_manifest() + print(f"{manifest.get_o3de_manifest()}:") + print(json.dumps(json_data, indent=4)) + + if verbose > 0: + print_engines_data(manifest.get_engines()) + print_projects_data(manifest.get_all_projects()) + print_gems_data(manifest.get_gems()) + print_templates_data(manifest.get_all_templates()) + print_restricted_data(manifest.get_all_restricted()) + print_repos_data(manifest.get_repos()) + + +def _run_register_show(args: argparse) -> int: + if args.override_home_folder: + manifest.override_home_folder = args.override_home_folder + + if args.this_engine: + print_this_engine(args.verbose) + return 0 + + elif args.engines: + print_engines(args.verbose) + return 0 + elif args.projects: + print_projects(args.verbose) + return 0 + elif args.gems: + print_gems(args.verbose) + return 0 + elif args.templates: + print_templates(args.verbose) + return 0 + elif args.repos: + register_show_repos(args.verbose) + return 0 + elif args.restricted: + print_restricted(args.verbose) + return 0 + + elif args.engine_projects: + print_engine_projects(args.verbose) + return 0 + elif args.engine_gems: + print_engine_gems(args.verbose) + return 0 + elif args.engine_templates: + print_engine_templates(args.verbose) + return 0 + elif args.engine_restricted: + print_engine_restricted(args.verbose) + return 0 + elif args.engine_external_subdirectories: + print_engine_external_subdirectories(args.verbose) + return 0 + + elif args.all_projects: + print_all_projects(args.verbose) + return 0 + elif args.all_gems: + print_all_gems(args.verbose) + return 0 + elif args.all_templates: + print_all_templates(args.verbose) + return 0 + elif args.all_restricted: + print_all_restricted(args.verbose) + return 0 + + elif args.downloadables: + print_downloadables(args.verbose) + return 0 + if args.downloadable_engines: + print_downloadable_engines(args.verbose) + return 0 + elif args.downloadable_projects: + print_downloadable_projects(args.verbose) + return 0 + elif args.downloadable_gems: + print_downloadable_gems(args.verbose) + return 0 + elif args.downloadable_templates: + print_downloadable_templates(args.verbose) + return 0 + else: + register_show(args.verbose) + return 0 + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + register_show_subparser = subparsers.add_parser('register-show') + group = register_show_subparser.add_mutually_exclusive_group(required=False) + group.add_argument('-te', '--this-engine', action='store_true', required=False, + default=False, + help='Just the local engines.') + + group.add_argument('-e', '--engines', action='store_true', required=False, + default=False, + help='Just the local engines.') + group.add_argument('-p', '--projects', action='store_true', required=False, + default=False, + help='Just the local projects.') + group.add_argument('-g', '--gems', action='store_true', required=False, + default=False, + help='Just the local gems.') + group.add_argument('-t', '--templates', action='store_true', required=False, + default=False, + help='Just the local templates.') + group.add_argument('-r', '--repos', action='store_true', required=False, + default=False, + help='Just the local repos. Ignores repos.') + group.add_argument('-rs', '--restricted', action='store_true', required=False, + default=False, + help='The local restricted folders.') + + group.add_argument('-ep', '--engine-projects', action='store_true', required=False, + default=False, + help='Just the local projects. Ignores repos.') + group.add_argument('-eg', '--engine-gems', action='store_true', required=False, + default=False, + help='Just the local gems. Ignores repos') + group.add_argument('-et', '--engine-templates', action='store_true', required=False, + default=False, + help='Just the local templates. Ignores repos.') + group.add_argument('-ers', '--engine-restricted', action='store_true', required=False, + default=False, + help='The restricted folders.') + group.add_argument('-x', '--engine-external-subdirectories', action='store_true', required=False, + default=False, + help='The external subdirectories.') + + group.add_argument('-ap', '--all-projects', action='store_true', required=False, + default=False, + help='Just the local projects. Ignores repos.') + group.add_argument('-ag', '--all-gems', action='store_true', required=False, + default=False, + help='Just the local gems. Ignores repos') + group.add_argument('-at', '--all-templates', action='store_true', required=False, + default=False, + help='Just the local templates. Ignores repos.') + group.add_argument('-ars', '--all-restricted', action='store_true', required=False, + default=False, + help='The restricted folders.') + + group.add_argument('-d', '--downloadables', action='store_true', required=False, + default=False, + help='Combine all repos into a single list of resources.') + group.add_argument('-de', '--downloadable-engines', action='store_true', required=False, + default=False, + help='Combine all repos engines into a single list of resources.') + group.add_argument('-dp', '--downloadable-projects', action='store_true', required=False, + default=False, + help='Combine all repos projects into a single list of resources.') + group.add_argument('-dg', '--downloadable-gems', action='store_true', required=False, + default=False, + help='Combine all repos gems into a single list of resources.') + group.add_argument('-dt', '--downloadable-templates', action='store_true', required=False, + default=False, + help='Combine all repos templates into a single list of resources.') + + register_show_subparser.add_argument('-v', '--verbose', action='count', required=False, + default=0, + help='How verbose do you want the output to be.') + + register_show_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + register_show_subparser.set_defaults(func=_run_register_show) \ No newline at end of file diff --git a/scripts/o3de/o3de/register.py b/scripts/o3de/o3de/register.py new file mode 100644 index 0000000000..e96d057e9c --- /dev/null +++ b/scripts/o3de/o3de/register.py @@ -0,0 +1,1066 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +This file contains all the code that has to do with registering engines, projects, gems and templates +""" + +import argparse +import hashlib +import logging +import json +import os +import pathlib +import shutil +import urllib.parse +import urllib.request + +from o3de import add_gem_cmake, get_registration, manifest, remove_external_subdirectory, repo, utils, validation + +logger = logging.getLogger() +logging.basicConfig() + + +def register_shipped_engine_o3de_objects(force: bool = False) -> int: + engine_path = manifest.get_this_engine_path() + + ret_val = 0 + + # register anything in the users default folders globally + error_code = register_all_engines_in_folder(manifest.get_registered(default_folder='engines'), force=force) + if error_code: + ret_val = error_code + error_code = register_all_projects_in_folder(manifest.get_registered(default_folder='projects')) + if error_code: + ret_val = error_code + error_code = register_all_gems_in_folder(manifest.get_registered(default_folder='gems')) + if error_code: + ret_val = error_code + error_code = register_all_templates_in_folder(manifest.get_registered(default_folder='templates')) + if error_code: + ret_val = error_code + error_code = register_all_restricted_in_folder(manifest.get_registered(default_folder='restricted')) + if error_code: + ret_val = error_code + error_code = register_all_restricted_in_folder(manifest.get_registered(default_folder='projects')) + if error_code: + ret_val = error_code + error_code = register_all_restricted_in_folder(manifest.get_registered(default_folder='gems')) + if error_code: + ret_val = error_code + error_code = register_all_restricted_in_folder(manifest.get_registered(default_folder='templates')) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_in_folder(folder_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None, + exclude: list = None) -> int: + if not folder_path: + logger.error(f'Folder path cannot be empty.') + return 1 + + folder_path = pathlib.Path(folder_path).resolve() + if not folder_path.is_dir(): + logger.error(f'Folder path is not dir.') + return 1 + + engines_set = set() + projects_set = set() + gems_set = set() + templates_set = set() + restricted_set = set() + repo_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(folder_path): + if root in exclude: + continue + + for name in files: + if name == 'engine.json': + engines_set.add(root) + elif name == 'project.json': + projects_set.add(root) + elif name == 'gem.json': + gems_set.add(root) + elif name == 'template.json': + templates_set.add(root) + elif name == 'restricted.json': + restricted_set.add(root) + elif name == 'repo.json': + repo_set.add(root) + + for engine in sorted(engines_set, reverse=True): + error_code = register(engine_path=engine, remove=remove) + if error_code: + ret_val = error_code + + for project in sorted(projects_set, reverse=True): + error_code = register(engine_path=engine_path, project_path=project, remove=remove) + if error_code: + ret_val = error_code + + for gem in sorted(gems_set, reverse=True): + error_code = register(engine_path=engine_path, gem_path=gem, remove=remove) + if error_code: + ret_val = error_code + + for template in sorted(templates_set, reverse=True): + error_code = register(engine_path=engine_path, template_path=template, remove=remove) + if error_code: + ret_val = error_code + + for restricted in sorted(restricted_set, reverse=True): + error_code = register(engine_path=engine_path, restricted_path=restricted, remove=remove) + if error_code: + ret_val = error_code + + for repo in sorted(repo_set, reverse=True): + error_code = register(engine_path=engine_path, repo_uri=repo, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_engines_in_folder(engines_path: str or pathlib.Path, + remove: bool = False, + force: bool = False) -> int: + if not engines_path: + logger.error(f'Engines path cannot be empty.') + return 1 + + engines_path = pathlib.Path(engines_path).resolve() + if not engines_path.is_dir(): + logger.error(f'Engines path is not dir.') + return 1 + + engines_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(engines_path): + for name in files: + if name == 'engine.json': + engines_set.add(root) + + for engine in sorted(engines_set, reverse=True): + error_code = register(engine_path=engine, remove=remove, force=force) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_projects_in_folder(projects_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not projects_path: + logger.error(f'Projects path cannot be empty.') + return 1 + + projects_path = pathlib.Path(projects_path).resolve() + if not projects_path.is_dir(): + logger.error(f'Projects path is not dir.') + return 1 + + projects_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(projects_path): + for name in files: + if name == 'project.json': + projects_set.add(root) + + for project in sorted(projects_set, reverse=True): + error_code = register(engine_path=engine_path, project_path=project, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_gems_in_folder(gems_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not gems_path: + logger.error(f'Gems path cannot be empty.') + return 1 + + gems_path = pathlib.Path(gems_path).resolve() + if not gems_path.is_dir(): + logger.error(f'Gems path is not dir.') + return 1 + + gems_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(gems_path): + for name in files: + if name == 'gem.json': + gems_set.add(root) + + for gem in sorted(gems_set, reverse=True): + error_code = register(engine_path=engine_path, gem_path=gem, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_templates_in_folder(templates_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not templates_path: + logger.error(f'Templates path cannot be empty.') + return 1 + + templates_path = pathlib.Path(templates_path).resolve() + if not templates_path.is_dir(): + logger.error(f'Templates path is not dir.') + return 1 + + templates_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(templates_path): + for name in files: + if name == 'template.json': + templates_set.add(root) + + for template in sorted(templates_set, reverse=True): + error_code = register(engine_path=engine_path, template_path=template, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_restricted_in_folder(restricted_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not restricted_path: + logger.error(f'Restricted path cannot be empty.') + return 1 + + restricted_path = pathlib.Path(restricted_path).resolve() + if not restricted_path.is_dir(): + logger.error(f'Restricted path is not dir.') + return 1 + + restricted_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(restricted_path): + for name in files: + if name == 'restricted.json': + restricted_set.add(root) + + for restricted in sorted(restricted_set, reverse=True): + error_code = register(engine_path=engine_path, restricted_path=restricted, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_repos_in_folder(repos_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not repos_path: + logger.error(f'Repos path cannot be empty.') + return 1 + + repos_path = pathlib.Path(repos_path).resolve() + if not repos_path.is_dir(): + logger.error(f'Repos path is not dir.') + return 1 + + repo_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(repos_path): + for name in files: + if name == 'repo.json': + repo_set.add(root) + + for repo in sorted(repo_set, reverse=True): + error_code = register(engine_path=engine_path, repo_uri=repo, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def remove_engine_name_to_path(json_data: dict, + engine_path: pathlib.Path) -> int: + """ + Remove the engine at the specified path if it exist in the o3de manifest + :param json_data in-memory json view of the o3de_manifest.json data + :param engine_path path to engine to remove from the manifest data + + returns 0 to indicate no issues has occurred with removal + """ + if engine_path.is_dir() and validation.valid_o3de_engine_json(engine_path): + engine_json_data = manifest.get_engine_json_data(engine_path=engine_path) + if 'engine_name' in engine_json_data and 'engines_path' in json_data: + engine_name = engine_json_data['engine_name'] + try: + del json_data['engines_path'][engine_name] + except KeyError: + # Attempting to remove a non-existent engine_name is fine + pass + return 0 + + +def add_engine_name_to_path(json_data: dict, engine_path: pathlib.Path, force: bool): + # Add an engine path JSON object which maps the "engine_name" -> "engine_path" + engine_json_data = manifest.get_engine_json_data(engine_path=engine_path) + if not engine_json_data: + logger.error(f'Unable to retrieve json data from engine.json at path {engine_path.as_posix()}') + return 1 + engines_path_json = json_data.setdefault('engines_path', {}) + if 'engine_name' not in engine_json_data: + logger.error(f'engine.json at path {engine_path.as_posix()} is missing "engine_name" key') + return 1 + + engine_name = engine_json_data['engine_name'] + if not force and engine_name in engines_path_json and \ + pathlib.PurePath(engines_path_json[engine_name]) != engine_path: + logger.error( + f'Attempting to register existing engine "{engine_name}" with a new path of {engine_path.as_posix()}.' + f' The current path is {pathlib.Path(engines_path_json[engine_name]).as_posix()}.' + f' To force registration of a new engine path, specify the -f/--force option.') + return 1 + engines_path_json[engine_name] = engine_path.as_posix() + return 0 + + +def register_engine_path(json_data: dict, + engine_path: str or pathlib.Path, + remove: bool = False, + force: bool = False) -> int: + if not engine_path: + logger.error(f'Engine path cannot be empty.') + return 1 + engine_path = pathlib.Path(engine_path).resolve() + + for engine_object in json_data.get('engines', {}): + engine_object_path = pathlib.Path(engine_object['path']).resolve() + if engine_object_path == engine_path: + json_data['engines'].remove(engine_object) + + if remove: + return remove_engine_name_to_path(json_data, engine_path) + + if not engine_path.is_dir(): + logger.error(f'Engine path {engine_path} does not exist.') + return 1 + + engine_json = engine_path / 'engine.json' + if not validation.valid_o3de_engine_json(engine_json): + logger.error(f'Engine json {engine_json} is not valid.') + return 1 + + engine_object = {} + engine_object.update({'path': engine_path.as_posix()}) + engine_object.update({'restricted': []}) + + json_data.setdefault('engines', []).insert(0, engine_object) + + return add_engine_name_to_path(json_data, engine_path, force) + + +def register_gem_path(json_data: dict, + gem_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not gem_path: + logger.error(f'Gem path cannot be empty.') + return 1 + gem_path = pathlib.Path(gem_path).resolve() + + if engine_path: + engine_data = manifest.find_engine_data(json_data, engine_path) + if not engine_data: + logger.error(f'Engine path {engine_path} is not registered.') + return 1 + + while gem_path in engine_data['gems']: + engine_data['gems'].remove(gem_path) + + while gem_path.as_posix() in engine_data['gems']: + engine_data['gems'].remove(gem_path.as_posix()) + + if remove: + logger.warn(f'Removing Gem path {gem_path}.') + return 0 + else: + while gem_path in json_data['gems']: + json_data['gems'].remove(gem_path) + + while gem_path.as_posix() in json_data['gems']: + json_data['gems'].remove(gem_path.as_posix()) + + if remove: + logger.warn(f'Removing Gem path {gem_path}.') + return 0 + + if not gem_path.is_dir(): + logger.error(f'Gem path {gem_path} does not exist.') + return 1 + + gem_json = gem_path / 'gem.json' + if not validation.valid_o3de_gem_json(gem_json): + logger.error(f'Gem json {gem_json} is not valid.') + return 1 + + if engine_path: + engine_data['gems'].insert(0, gem_path.as_posix()) + else: + json_data['gems'].insert(0, gem_path.as_posix()) + + return 0 + + +def register_project_path(json_data: dict, + project_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not project_path: + logger.error(f'Project path cannot be empty.') + return 1 + project_path = pathlib.Path(project_path).resolve() + + if engine_path: + engine_data = manifest.find_engine_data(json_data, engine_path) + if not engine_data: + logger.error(f'Engine path {engine_path} is not registered.') + return 1 + + while project_path in engine_data['projects']: + engine_data['projects'].remove(project_path) + + while project_path.as_posix() in engine_data['projects']: + engine_data['projects'].remove(project_path.as_posix()) + + if remove: + logger.warn(f'Engine {engine_path} removing Project path {project_path}.') + return 0 + else: + while project_path in json_data['projects']: + json_data['projects'].remove(project_path) + + while project_path.as_posix() in json_data['projects']: + json_data['projects'].remove(project_path.as_posix()) + + if remove: + logger.warn(f'Removing Project path {project_path}.') + return 0 + + if not project_path.is_dir(): + logger.error(f'Project path {project_path} does not exist.') + return 1 + + project_json = project_path / 'project.json' + if not validation.valid_o3de_project_json(project_json): + logger.error(f'Project json {project_json} is not valid.') + return 1 + + if engine_path: + engine_data['projects'].insert(0, project_path.as_posix()) + else: + json_data['projects'].insert(0, project_path.as_posix()) + + # registering a project has the additional step of setting the project.json 'engine' field + this_engine_json = manifest.get_this_engine_path() / 'engine.json' + with this_engine_json.open('r') as f: + try: + this_engine_json = json.load(f) + except Exception as e: + logger.error(f'Engine json failed to load: {str(e)}') + return 1 + with project_json.open('r') as f: + try: + project_json_data = json.load(f) + except Exception as e: + logger.error(f'Project json failed to load: {str(e)}') + return 1 + + update_project_json = False + try: + update_project_json = project_json_data['engine'] != this_engine_json['engine_name'] + except Exception as e: + update_project_json = True + + if update_project_json: + project_json_data['engine'] = this_engine_json['engine_name'] + utils.backup_file(project_json) + with project_json.open('w') as s: + try: + s.write(json.dumps(project_json_data, indent=4)) + except Exception as e: + logger.error(f'Project json failed to save: {str(e)}') + return 1 + + return 0 + + +def register_template_path(json_data: dict, + template_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not template_path: + logger.error(f'Template path cannot be empty.') + return 1 + template_path = pathlib.Path(template_path).resolve() + + if engine_path: + engine_data = manifest.find_engine_data(json_data, engine_path) + if not engine_data: + logger.error(f'Engine path {engine_path} is not registered.') + return 1 + + while template_path in engine_data['templates']: + engine_data['templates'].remove(template_path) + + while template_path.as_posix() in engine_data['templates']: + engine_data['templates'].remove(template_path.as_posix()) + + if remove: + logger.warn(f'Engine {engine_path} removing Template path {template_path}.') + return 0 + else: + while template_path in json_data['templates']: + json_data['templates'].remove(template_path) + + while template_path.as_posix() in json_data['templates']: + json_data['templates'].remove(template_path.as_posix()) + + if remove: + logger.warn(f'Removing Template path {template_path}.') + return 0 + + if not template_path.is_dir(): + logger.error(f'Template path {template_path} does not exist.') + return 1 + + template_json = template_path / 'template.json' + if not validation.valid_o3de_template_json(template_json): + logger.error(f'Template json {template_json} is not valid.') + return 1 + + if engine_path: + engine_data['templates'].insert(0, template_path.as_posix()) + else: + json_data['templates'].insert(0, template_path.as_posix()) + + return 0 + + +def register_restricted_path(json_data: dict, + restricted_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not restricted_path: + logger.error(f'Restricted path cannot be empty.') + return 1 + restricted_path = pathlib.Path(restricted_path).resolve() + + if engine_path: + engine_data = manifest.find_engine_data(json_data, engine_path) + if not engine_data: + logger.error(f'Engine path {engine_path} is not registered.') + return 1 + + while restricted_path in engine_data['restricted']: + engine_data['restricted'].remove(restricted_path) + + while restricted_path.as_posix() in engine_data['restricted']: + engine_data['restricted'].remove(restricted_path.as_posix()) + + if remove: + logger.warn(f'Engine {engine_path} removing Restricted path {restricted_path}.') + return 0 + else: + while restricted_path in json_data['restricted']: + json_data['restricted'].remove(restricted_path) + + while restricted_path.as_posix() in json_data['restricted']: + json_data['restricted'].remove(restricted_path.as_posix()) + + if remove: + logger.warn(f'Removing Restricted path {restricted_path}.') + return 0 + + if not restricted_path.is_dir(): + logger.error(f'Restricted path {restricted_path} does not exist.') + return 1 + + restricted_json = restricted_path / 'restricted.json' + if not validation.valid_o3de_restricted_json(restricted_json): + logger.error(f'Restricted json {restricted_json} is not valid.') + return 1 + + if engine_path: + engine_data['restricted'].insert(0, restricted_path.as_posix()) + else: + json_data['restricted'].insert(0, restricted_path.as_posix()) + + return 0 + + +def register_repo(json_data: dict, + repo_uri: str or pathlib.Path, + remove: bool = False) -> int: + if not repo_uri: + logger.error(f'Repo URI cannot be empty.') + return 1 + + url = f'{repo_uri}/repo.json' + parsed_uri = urllib.parse.urlparse(url) + + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + while repo_uri in json_data['repos']: + json_data['repos'].remove(repo_uri) + else: + repo_uri = pathlib.Path(repo_uri).resolve() + while repo_uri.as_posix() in json_data['repos']: + json_data['repos'].remove(repo_uri.as_posix()) + + if remove: + logger.warn(f'Removing repo uri {repo_uri}.') + return 0 + + repo_sha256 = hashlib.sha256(url.encode()) + cache_file = manifest.get_o3de_cache_folder() / str(repo_sha256.hexdigest() + '.json') + + result = 0 + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + if not cache_file.is_file(): + with urllib.request.urlopen(url) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + json_data['repos'].insert(0, repo_uri) + else: + if not cache_file.is_file(): + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, origin_file) + json_data['repos'].insert(0, repo_uri.as_posix()) + + repo_set = set() + result = repo.process_add_o3de_repo(cache_file, repo_set) + + return result + + +def register_default_engines_folder(json_data: dict, + default_engines_folder: str or pathlib.Path, + remove: bool = False) -> int: + if remove: + default_engines_folder = manifest.get_o3de_engines_folder() + + # make sure the path exists + default_engines_folder = pathlib.Path(default_engines_folder).resolve() + if not default_engines_folder.is_dir(): + logger.error(f'Default engines folder {default_engines_folder} does not exist.') + return 1 + + default_engines_folder = default_engines_folder.as_posix() + json_data['default_engines_folder'] = default_engines_folder + + return 0 + + +def register_default_projects_folder(json_data: dict, + default_projects_folder: str or pathlib.Path, + remove: bool = False) -> int: + if remove: + default_projects_folder = manifest.get_o3de_projects_folder() + + # make sure the path exists + default_projects_folder = pathlib.Path(default_projects_folder).resolve() + if not default_projects_folder.is_dir(): + logger.error(f'Default projects folder {default_projects_folder} does not exist.') + return 1 + + default_projects_folder = default_projects_folder.as_posix() + json_data['default_projects_folder'] = default_projects_folder + + return 0 + + +def register_default_gems_folder(json_data: dict, + default_gems_folder: str or pathlib.Path, + remove: bool = False) -> int: + if remove: + default_gems_folder = manifest.get_o3de_gems_folder() + + # make sure the path exists + default_gems_folder = pathlib.Path(default_gems_folder).resolve() + if not default_gems_folder.is_dir(): + logger.error(f'Default gems folder {default_gems_folder} does not exist.') + return 1 + + default_gems_folder = default_gems_folder.as_posix() + json_data['default_gems_folder'] = default_gems_folder + + return 0 + + +def register_default_templates_folder(json_data: dict, + default_templates_folder: str or pathlib.Path, + remove: bool = False) -> int: + if remove: + default_templates_folder = manifest.get_o3de_templates_folder() + + # make sure the path exists + default_templates_folder = pathlib.Path(default_templates_folder).resolve() + if not default_templates_folder.is_dir(): + logger.error(f'Default templates folder {default_templates_folder} does not exist.') + return 1 + + default_templates_folder = default_templates_folder.as_posix() + json_data['default_templates_folder'] = default_templates_folder + + return 0 + + +def register_default_restricted_folder(json_data: dict, + default_restricted_folder: str or pathlib.Path, + remove: bool = False) -> int: + if remove: + default_restricted_folder = manifest.get_o3de_restricted_folder() + + # make sure the path exists + default_restricted_folder = pathlib.Path(default_restricted_folder).resolve() + if not default_restricted_folder.is_dir(): + logger.error(f'Default restricted folder {default_restricted_folder} does not exist.') + return 1 + + default_restricted_folder = default_restricted_folder.as_posix() + json_data['default_restricted_folder'] = default_restricted_folder + + return 0 + + +def register(engine_path: str or pathlib.Path = None, + project_path: str or pathlib.Path = None, + gem_path: str or pathlib.Path = None, + template_path: str or pathlib.Path = None, + restricted_path: str or pathlib.Path = None, + repo_uri: str or pathlib.Path = None, + default_engines_folder: str or pathlib.Path = None, + default_projects_folder: str or pathlib.Path = None, + default_gems_folder: str or pathlib.Path = None, + default_templates_folder: str or pathlib.Path = None, + default_restricted_folder: str or pathlib.Path = None, + remove: bool = False, + force: bool = False + ) -> int: + """ + Adds/Updates entries to the .o3de/o3de_manifest.json + + :param engine_path: if engine folder is supplied the path will be added to the engine if it can, if not global + :param project_path: project folder + :param gem_path: gem folder + :param template_path: template folder + :param restricted_path: restricted folder + :param repo_uri: repo uri + :param default_engines_folder: default engines folder + :param default_projects_folder: default projects folder + :param default_gems_folder: default gems folder + :param default_templates_folder: default templates folder + :param default_restricted_folder: default restricted code folder + :param remove: add/remove the entries + :param force: force update of the engine_path for specified "engine_name" from the engine.json file + + :return: 0 for success or non 0 failure code + """ + + json_data = manifest.load_o3de_manifest() + + result = 0 + + # do anything that could require a engine context first + if isinstance(project_path, str) or isinstance(project_path, pathlib.PurePath): + if not project_path: + logger.error(f'Project path cannot be empty.') + return 1 + result = register_project_path(json_data, project_path, remove, engine_path) + + elif isinstance(gem_path, str) or isinstance(gem_path, pathlib.PurePath): + if not gem_path: + logger.error(f'Gem path cannot be empty.') + return 1 + result = register_gem_path(json_data, gem_path, remove, engine_path) + + elif isinstance(template_path, str) or isinstance(template_path, pathlib.PurePath): + if not template_path: + logger.error(f'Template path cannot be empty.') + return 1 + result = register_template_path(json_data, template_path, remove, engine_path) + + elif isinstance(restricted_path, str) or isinstance(restricted_path, pathlib.PurePath): + if not restricted_path: + logger.error(f'Restricted path cannot be empty.') + return 1 + result = register_restricted_path(json_data, restricted_path, remove, engine_path) + + elif isinstance(repo_uri, str) or isinstance(repo_uri, pathlib.PurePath): + if not repo_uri: + logger.error(f'Repo URI cannot be empty.') + return 1 + result = register_repo(json_data, repo_uri, remove) + + elif isinstance(default_engines_folder, str) or isinstance(default_engines_folder, pathlib.PurePath): + result = register_default_engines_folder(json_data, default_engines_folder, remove) + + elif isinstance(default_projects_folder, str) or isinstance(default_projects_folder, pathlib.PurePath): + result = register_default_projects_folder(json_data, default_projects_folder, remove) + + elif isinstance(default_gems_folder, str) or isinstance(default_gems_folder, pathlib.PurePath): + result = register_default_gems_folder(json_data, default_gems_folder, remove) + + elif isinstance(default_templates_folder, str) or isinstance(default_templates_folder, pathlib.PurePath): + result = register_default_templates_folder(json_data, default_templates_folder, remove) + + elif isinstance(default_restricted_folder, str) or isinstance(default_restricted_folder, pathlib.PurePath): + result = register_default_restricted_folder(json_data, default_restricted_folder, remove) + + # engine is done LAST + # Now that everything that could have an engine context is done, if the engine is supplied that means this is + # registering the engine itself + elif isinstance(engine_path, str) or isinstance(engine_path, pathlib.PurePath): + if not engine_path: + logger.error(f'Engine path cannot be empty.') + return 1 + result = register_engine_path(json_data, engine_path, remove, force) + + if not result: + manifest.save_o3de_manifest(json_data) + + return result + + +def remove_invalid_o3de_objects() -> None: + json_data = manifest.load_o3de_manifest() + + for engine_object in json_data['engines']: + engine_path = engine_object['path'] + if not validation.valid_o3de_engine_json(pathlib.Path(engine_path).resolve() / 'engine.json'): + logger.warn(f"Engine path {engine_path} is invalid.") + register(engine_path=engine_path, remove=True) + else: + for project in engine_object['projects']: + if not validation.valid_o3de_project_json(pathlib.Path(project).resolve() / 'project.json'): + logger.warn(f"Project path {project} is invalid.") + register(engine_path=engine_path, project_path=project, remove=True) + + for gem_path in engine_object['gems']: + if not validation.valid_o3de_gem_json(pathlib.Path(gem_path).resolve() / 'gem.json'): + logger.warn(f"Gem path {gem_path} is invalid.") + register(engine_path=engine_path, gem_path=gem_path, remove=True) + + for template_path in engine_object['templates']: + if not validation.valid_o3de_template_json(pathlib.Path(template_path).resolve() / 'template.json'): + logger.warn(f"Template path {template_path} is invalid.") + register(engine_path=engine_path, template_path=template_path, remove=True) + + for restricted in engine_object['restricted']: + if not validation.valid_o3de_restricted_json(pathlib.Path(restricted).resolve() / 'restricted.json'): + logger.warn(f"Restricted path {restricted} is invalid.") + register(engine_path=engine_path, restricted_path=restricted, remove=True) + + for external in engine_object['external_subdirectories']: + external = pathlib.Path(external).resolve() + if not external.is_dir(): + logger.warn(f"External subdirectory {external} is invalid.") + remove_external_subdirectory.remove_external_subdirectory(external) + + for project in json_data['projects']: + if not validation.valid_o3de_project_json(pathlib.Path(project).resolve() / 'project.json'): + logger.warn(f"Project path {project} is invalid.") + register(project_path=project, remove=True) + + for gem in json_data['gems']: + if not validation.valid_o3de_gem_json(pathlib.Path(gem).resolve() / 'gem.json'): + logger.warn(f"Gem path {gem} is invalid.") + register(gem_path=gem, remove=True) + + for template in json_data['templates']: + if not validation.valid_o3de_template_json(pathlib.Path(template).resolve() / 'template.json'): + logger.warn(f"Template path {template} is invalid.") + register(template_path=template, remove=True) + + for restricted in json_data['restricted']: + if not validation.valid_o3de_restricted_json(pathlib.Path(restricted).resolve() / 'restricted.json'): + logger.warn(f"Restricted path {restricted} is invalid.") + register(restricted_path=restricted, remove=True) + + default_engines_folder = pathlib.Path(json_data['default_engines_folder']).resolve() + if not default_engines_folder.is_dir(): + new_default_engines_folder = manifest.get_o3de_folder() / 'Engines' + new_default_engines_folder.mkdir(parents=True, exist_ok=True) + logger.warn( + f"Default engines folder {default_engines_folder} is invalid. Set default {new_default_engines_folder}") + register(default_engines_folder=new_default_engines_folder.as_posix()) + + default_projects_folder = pathlib.Path(json_data['default_projects_folder']).resolve() + if not default_projects_folder.is_dir(): + new_default_projects_folder = manifest.get_o3de_folder() / 'Projects' + new_default_projects_folder.mkdir(parents=True, exist_ok=True) + logger.warn( + f"Default projects folder {default_projects_folder} is invalid. Set default {new_default_projects_folder}") + register(default_projects_folder=new_default_projects_folder.as_posix()) + + default_gems_folder = pathlib.Path(json_data['default_gems_folder']).resolve() + if not default_gems_folder.is_dir(): + new_default_gems_folder = manifest.get_o3de_folder() / 'Gems' + new_default_gems_folder.mkdir(parents=True, exist_ok=True) + logger.warn(f"Default gems folder {default_gems_folder} is invalid." + f" Set default {new_default_gems_folder}") + register(default_gems_folder=new_default_gems_folder.as_posix()) + + default_templates_folder = pathlib.Path(json_data['default_templates_folder']).resolve() + if not default_templates_folder.is_dir(): + new_default_templates_folder = manifest.get_o3de_folder() / 'Templates' + new_default_templates_folder.mkdir(parents=True, exist_ok=True) + logger.warn( + f"Default templates folder {default_templates_folder} is invalid." + f" Set default {new_default_templates_folder}") + register(default_templates_folder=new_default_templates_folder.as_posix()) + + default_restricted_folder = pathlib.Path(json_data['default_restricted_folder']).resolve() + if not default_restricted_folder.is_dir(): + default_restricted_folder = manifest.get_o3de_folder() / 'Restricted' + default_restricted_folder.mkdir(parents=True, exist_ok=True) + logger.warn( + f"Default restricted folder {default_restricted_folder} is invalid." + f" Set default {default_restricted_folder}") + register(default_restricted_folder=default_restricted_folder.as_posix()) + + +def _run_register(args: argparse) -> int: + if args.override_home_folder: + manifest.override_home_folder = args.override_home_folder + + if args.update: + remove_invalid_o3de_objects() + return repo.refresh_repos() + elif args.this_engine: + ret_val = register(engine_path=manifest.get_this_engine_path(), force=args.force) + error_code = register_shipped_engine_o3de_objects(force=args.force) + if error_code: + ret_val = error_code + return ret_val + elif args.all_engines_path: + return register_all_engines_in_folder(args.all_engines_path, args.remove, args.force) + elif args.all_projects_path: + return register_all_projects_in_folder(args.all_projects_path, args.remove) + elif args.all_gems_path: + return register_all_gems_in_folder(args.all_gems_path, args.remove) + elif args.all_templates_path: + return register_all_templates_in_folder(args.all_templates_path, args.remove) + elif args.all_restricted_path: + return register_all_restricted_in_folder(args.all_restricted_path, args.remove) + elif args.all_repo_uri: + return register_all_repos_in_folder(args.all_restricted_path, args.remove) + else: + return register(engine_path=args.engine_path, + project_path=args.project_path, + gem_path=args.gem_path, + template_path=args.template_path, + restricted_path=args.restricted_path, + repo_uri=args.repo_uri, + default_engines_folder=args.default_engines_folder, + default_projects_folder=args.default_projects_folder, + default_gems_folder=args.default_gems_folder, + default_templates_folder=args.default_templates_folder, + default_restricted_folder=args.default_restricted_folder, + remove=args.remove, + force=args.force) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + # register + register_subparser = subparsers.add_parser('register') + group = register_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('--this-engine', action='store_true', required=False, + default=False, + help='Registers the engine this script is running from.') + group.add_argument('-ep', '--engine-path', type=str, required=False, + help='Engine path to register/remove.') + group.add_argument('-pp', '--project-path', type=str, required=False, + help='Project path to register/remove.') + group.add_argument('-gp', '--gem-path', type=str, required=False, + help='Gem path to register/remove.') + group.add_argument('-tp', '--template-path', type=str, required=False, + help='Template path to register/remove.') + group.add_argument('-rp', '--restricted-path', type=str, required=False, + help='A restricted folder to register/remove.') + group.add_argument('-ru', '--repo-uri', type=str, required=False, + help='A repo uri to register/remove.') + group.add_argument('-aep', '--all-engines-path', type=str, required=False, + help='All engines under this folder to register/remove.') + group.add_argument('-app', '--all-projects-path', type=str, required=False, + help='All projects under this folder to register/remove.') + group.add_argument('-agp', '--all-gems-path', type=str, required=False, + help='All gems under this folder to register/remove.') + group.add_argument('-atp', '--all-templates-path', type=str, required=False, + help='All templates under this folder to register/remove.') + group.add_argument('-arp', '--all-restricted-path', type=str, required=False, + help='All templates under this folder to register/remove.') + group.add_argument('-aru', '--all-repo-uri', type=str, required=False, + help='All repos under this folder to register/remove.') + group.add_argument('-def', '--default-engines-folder', type=str, required=False, + help='The default engines folder to register/remove.') + group.add_argument('-dpf', '--default-projects-folder', type=str, required=False, + help='The default projects folder to register/remove.') + group.add_argument('-dgf', '--default-gems-folder', type=str, required=False, + help='The default gems folder to register/remove.') + group.add_argument('-dtf', '--default-templates-folder', type=str, required=False, + help='The default templates folder to register/remove.') + group.add_argument('-drf', '--default-restricted-folder', type=str, required=False, + help='The default restricted folder to register/remove.') + group.add_argument('-u', '--update', action='store_true', required=False, + default=False, + help='Refresh the repo cache.') + + register_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + register_subparser.add_argument('-r', '--remove', action='store_true', required=False, + default=False, + help='Remove entry.') + register_subparser.add_argument('-f', '--force', action='store_true', default=False, + help='For the update of the registration field being modified.') + register_subparser.set_defaults(func=_run_register) diff --git a/scripts/o3de/o3de/registration.py b/scripts/o3de/o3de/registration.py index 6a165cbea5..801c698ca4 100755 --- a/scripts/o3de/o3de/registration.py +++ b/scripts/o3de/o3de/registration.py @@ -13,4074 +13,7 @@ This file contains all the code that has to do with registering engines, project """ import argparse -import logging -import os import sys -import json -import pathlib -import hashlib -import shutil -import zipfile -import urllib.parse -import urllib.request - -logger = logging.getLogger() -logging.basicConfig() - - -def backup_file(file_name: str or pathlib.Path) -> None: - index = 0 - renamed = False - while not renamed: - backup_file_name = pathlib.Path(str(file_name) + '.bak' + str(index)).resolve() - index += 1 - if not backup_file_name.is_file(): - file_name = pathlib.Path(file_name).resolve() - file_name.rename(backup_file_name) - if backup_file_name.is_file(): - renamed = True - - -def backup_folder(folder: str or pathlib.Path) -> None: - index = 0 - renamed = False - while not renamed: - backup_folder_name = pathlib.Path(str(folder) + '.bak' + str(index)).resolve() - index += 1 - if not backup_folder_name.is_dir(): - folder = pathlib.Path(folder).resolve() - folder.rename(backup_folder_name) - if backup_folder_name.is_dir(): - renamed = True - - -def get_this_engine_path() -> pathlib.Path: - return pathlib.Path(os.path.realpath(__file__)).parents[3].resolve() - - -override_home_folder = None - - -def get_home_folder() -> pathlib.Path: - if override_home_folder: - return pathlib.Path(override_home_folder).resolve() - else: - return pathlib.Path(os.path.expanduser("~")).resolve() - - -def get_o3de_folder() -> pathlib.Path: - o3de_folder = get_home_folder() / '.o3de' - o3de_folder.mkdir(parents=True, exist_ok=True) - return o3de_folder - - -def get_o3de_registry_folder() -> pathlib.Path: - registry_folder = get_o3de_folder() / 'Registry' - registry_folder.mkdir(parents=True, exist_ok=True) - return registry_folder - - -def get_o3de_cache_folder() -> pathlib.Path: - cache_folder = get_o3de_folder() / 'Cache' - cache_folder.mkdir(parents=True, exist_ok=True) - return cache_folder - - -def get_o3de_download_folder() -> pathlib.Path: - download_folder = get_o3de_folder() / 'Download' - download_folder.mkdir(parents=True, exist_ok=True) - return download_folder - - -def get_o3de_engines_folder() -> pathlib.Path: - engines_folder = get_o3de_folder() / 'Engines' - engines_folder.mkdir(parents=True, exist_ok=True) - return engines_folder - - -def get_o3de_projects_folder() -> pathlib.Path: - projects_folder = get_o3de_folder() / 'Projects' - projects_folder.mkdir(parents=True, exist_ok=True) - return projects_folder - - -def get_o3de_gems_folder() -> pathlib.Path: - gems_folder = get_o3de_folder() / 'Gems' - gems_folder.mkdir(parents=True, exist_ok=True) - return gems_folder - - -def get_o3de_templates_folder() -> pathlib.Path: - templates_folder = get_o3de_folder() / 'Templates' - templates_folder.mkdir(parents=True, exist_ok=True) - return templates_folder - - -def get_o3de_restricted_folder() -> pathlib.Path: - restricted_folder = get_o3de_folder() / 'Restricted' - restricted_folder.mkdir(parents=True, exist_ok=True) - return restricted_folder - - -def get_o3de_logs_folder() -> pathlib.Path: - logs_folder = get_o3de_folder() / 'Logs' - logs_folder.mkdir(parents=True, exist_ok=True) - return logs_folder - - -def register_shipped_engine_o3de_objects(force: bool = False) -> int: - engine_path = get_this_engine_path() - - ret_val = 0 - - # directories with engines - starting_engines_directories = [ - ] - for engines_directory in sorted(starting_engines_directories, reverse=True): - error_code = register_all_engines_in_folder(engines_path=engines_directory, force=force) - if error_code: - ret_val = error_code - - # specific engines - starting_engines = [ - ] - for engine_path in sorted(starting_engines): - error_code = register(engine_path=engine_path, force=force) - if error_code: - ret_val = error_code - - # directories with projects - starting_projects_directories = [ - ] - for projects_directory in sorted(starting_projects_directories, reverse=True): - error_code = register_all_projects_in_folder(engine_path=engine_path, projects_path=projects_directory) - if error_code: - ret_val = error_code - - # specific projects - starting_projects = [ - f'{engine_path}/AutomatedTesting' - ] - for project_path in sorted(starting_projects, reverse=True): - error_code = register(engine_path=engine_path, project_path=project_path, force=force) - if error_code: - ret_val = error_code - - # directories with gems - starting_gems_directories = [ - f'{engine_path}/Gems' - ] - for gems_directory in sorted(starting_gems_directories, reverse=True): - error_code = register_all_gems_in_folder(engine_path=engine_path, gems_path=gems_directory) - if error_code: - ret_val = error_code - - # specific gems - starting_gems = [ - ] - for gem_path in sorted(starting_gems, reverse=True): - error_code = register(engine_path=engine_path, gem_path=gem_path, force=force) - if error_code: - ret_val = error_code - - # directories with templates - starting_templates_directories = [ - f'{engine_path}/Templates' - ] - for templates_directory in sorted(starting_templates_directories, reverse=True): - error_code = register_all_templates_in_folder(engine_path=engine_path, templates_path=templates_directory) - if error_code: - ret_val = error_code - - # specific templates - starting_templates = [ - ] - for template_path in sorted(starting_templates, reverse=True): - error_code = register(engine_path=engine_path, template_path=template_path, force=force) - if error_code: - ret_val = error_code - - # directories with restricted - starting_restricted_directories = [ - ] - for restricted_directory in sorted(starting_restricted_directories, reverse=True): - error_code = register_all_restricted_in_folder(engine_path=engine_path, restricted_path=restricted_directory) - if error_code: - ret_val = error_code - - # specific restricted - starting_restricted = [ - ] - for restricted_path in sorted(starting_restricted, reverse=True): - error_code = register(engine_path=engine_path, restricted_path=restricted_path, force=force) - if error_code: - ret_val = error_code - - # directories with repos - starting_repo_directories = [ - ] - for repos_directory in sorted(starting_repo_directories, reverse=True): - error_code = register_all_repos_in_folder(engine_path=engine_path, repos_path=repos_directory) - if error_code: - ret_val = error_code - - # specific repos - starting_repos = [ - ] - for repo_uri in sorted(starting_repos, reverse=True): - error_code = register(repo_uri=repo_uri, force=force) - if error_code: - ret_val = error_code - - # register anything in the users default folders globally - error_code = register_all_engines_in_folder(get_registered(default_folder='engines'), force=force) - if error_code: - ret_val = error_code - error_code = register_all_projects_in_folder(get_registered(default_folder='projects')) - if error_code: - ret_val = error_code - error_code = register_all_gems_in_folder(get_registered(default_folder='gems')) - if error_code: - ret_val = error_code - error_code = register_all_templates_in_folder(get_registered(default_folder='templates')) - if error_code: - ret_val = error_code - error_code = register_all_restricted_in_folder(get_registered(default_folder='restricted')) - if error_code: - ret_val = error_code - error_code = register_all_restricted_in_folder(get_registered(default_folder='projects')) - if error_code: - ret_val = error_code - error_code = register_all_restricted_in_folder(get_registered(default_folder='gems')) - if error_code: - ret_val = error_code - error_code = register_all_restricted_in_folder(get_registered(default_folder='templates')) - if error_code: - ret_val = error_code - - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data) - gems = json_data['gems'].copy() - gems.extend(engine_object['gems']) - for gem_path in sorted(gems, key=len): - gem_path = pathlib.Path(gem_path).resolve() - gem_cmake_lists_txt = gem_path / 'CMakeLists.txt' - if gem_cmake_lists_txt.is_file(): - add_gem_to_cmake(engine_path=engine_path, gem_path=gem_path, suppress_errors=True) # don't care about errors - - return ret_val - - -def register_all_in_folder(folder_path: str or pathlib.Path, - remove: bool = False, - engine_path: str or pathlib.Path = None, - exclude: list = None) -> int: - if not folder_path: - logger.error(f'Folder path cannot be empty.') - return 1 - - folder_path = pathlib.Path(folder_path).resolve() - if not folder_path.is_dir(): - logger.error(f'Folder path is not dir.') - return 1 - - engines_set = set() - projects_set = set() - gems_set = set() - templates_set = set() - restricted_set = set() - repo_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(folder_path): - if root in exclude: - continue - - for name in files: - if name == 'engine.json': - engines_set.add(root) - elif name == 'project.json': - projects_set.add(root) - elif name == 'gem.json': - gems_set.add(root) - elif name == 'template.json': - templates_set.add(root) - elif name == 'restricted.json': - restricted_set.add(root) - elif name == 'repo.json': - repo_set.add(root) - - for engine in sorted(engines_set, reverse=True): - error_code = register(engine_path=engine, remove=remove) - if error_code: - ret_val = error_code - - for project in sorted(projects_set, reverse=True): - error_code = register(engine_path=engine_path, project_path=project, remove=remove) - if error_code: - ret_val = error_code - - for gem in sorted(gems_set, reverse=True): - error_code = register(engine_path=engine_path, gem_path=gem, remove=remove) - if error_code: - ret_val = error_code - - for template in sorted(templates_set, reverse=True): - error_code = register(engine_path=engine_path, template_path=template, remove=remove) - if error_code: - ret_val = error_code - - for restricted in sorted(restricted_set, reverse=True): - error_code = register(engine_path=engine_path, restricted_path=restricted, remove=remove) - if error_code: - ret_val = error_code - - for repo in sorted(repo_set, reverse=True): - error_code = register(engine_path=engine_path, repo_uri=repo, remove=remove) - if error_code: - ret_val = error_code - - return ret_val - - -def register_all_engines_in_folder(engines_path: str or pathlib.Path, - remove: bool = False, - force: bool = False) -> int: - if not engines_path: - logger.error(f'Engines path cannot be empty.') - return 1 - - engines_path = pathlib.Path(engines_path).resolve() - if not engines_path.is_dir(): - logger.error(f'Engines path is not dir.') - return 1 - - engines_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(engines_path): - for name in files: - if name == 'engine.json': - engines_set.add(root) - - for engine in sorted(engines_set, reverse=True): - error_code = register(engine_path=engine, remove=remove, force=force) - if error_code: - ret_val = error_code - - return ret_val - - -def register_all_projects_in_folder(projects_path: str or pathlib.Path, - remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: - if not projects_path: - logger.error(f'Projects path cannot be empty.') - return 1 - - projects_path = pathlib.Path(projects_path).resolve() - if not projects_path.is_dir(): - logger.error(f'Projects path is not dir.') - return 1 - - projects_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(projects_path): - for name in files: - if name == 'project.json': - projects_set.add(root) - - for project in sorted(projects_set, reverse=True): - error_code = register(engine_path=engine_path, project_path=project, remove=remove) - if error_code: - ret_val = error_code - - return ret_val - - -def register_all_gems_in_folder(gems_path: str or pathlib.Path, - remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: - if not gems_path: - logger.error(f'Gems path cannot be empty.') - return 1 - - gems_path = pathlib.Path(gems_path).resolve() - if not gems_path.is_dir(): - logger.error(f'Gems path is not dir.') - return 1 - - gems_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(gems_path): - for name in files: - if name == 'gem.json': - gems_set.add(root) - - for gem in sorted(gems_set, reverse=True): - error_code = register(engine_path=engine_path, gem_path=gem, remove=remove) - if error_code: - ret_val = error_code - - return ret_val - - -def register_all_templates_in_folder(templates_path: str or pathlib.Path, - remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: - if not templates_path: - logger.error(f'Templates path cannot be empty.') - return 1 - - templates_path = pathlib.Path(templates_path).resolve() - if not templates_path.is_dir(): - logger.error(f'Templates path is not dir.') - return 1 - - templates_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(templates_path): - for name in files: - if name == 'template.json': - templates_set.add(root) - - for template in sorted(templates_set, reverse=True): - error_code = register(engine_path=engine_path, template_path=template, remove=remove) - if error_code: - ret_val = error_code - - return ret_val - - -def register_all_restricted_in_folder(restricted_path: str or pathlib.Path, - remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: - if not restricted_path: - logger.error(f'Restricted path cannot be empty.') - return 1 - - restricted_path = pathlib.Path(restricted_path).resolve() - if not restricted_path.is_dir(): - logger.error(f'Restricted path is not dir.') - return 1 - - restricted_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(restricted_path): - for name in files: - if name == 'restricted.json': - restricted_set.add(root) - - for restricted in sorted(restricted_set, reverse=True): - error_code = register(engine_path=engine_path, restricted_path=restricted, remove=remove) - if error_code: - ret_val = error_code - - return ret_val - - -def register_all_repos_in_folder(repos_path: str or pathlib.Path, - remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: - if not repos_path: - logger.error(f'Repos path cannot be empty.') - return 1 - - repos_path = pathlib.Path(repos_path).resolve() - if not repos_path.is_dir(): - logger.error(f'Repos path is not dir.') - return 1 - - repo_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(repos_path): - for name in files: - if name == 'repo.json': - repo_set.add(root) - - for repo in sorted(repo_set, reverse=True): - error_code = register(engine_path=engine_path, repo_uri=repo, remove=remove) - if error_code: - ret_val = error_code - - return ret_val - - -def get_o3de_manifest() -> pathlib.Path: - manifest_path = get_o3de_folder() / 'o3de_manifest.json' - if not manifest_path.is_file(): - username = os.path.split(get_home_folder())[-1] - - o3de_folder = get_o3de_folder() - default_registry_folder = get_o3de_registry_folder() - default_cache_folder = get_o3de_cache_folder() - default_downloads_folder = get_o3de_download_folder() - default_logs_folder = get_o3de_logs_folder() - default_engines_folder = get_o3de_engines_folder() - default_projects_folder = get_o3de_projects_folder() - default_gems_folder = get_o3de_gems_folder() - default_templates_folder = get_o3de_templates_folder() - default_restricted_folder = get_o3de_restricted_folder() - - default_projects_restricted_folder = default_projects_folder / 'Restricted' - default_projects_restricted_folder.mkdir(parents=True, exist_ok=True) - default_gems_restricted_folder = default_gems_folder / 'Restricted' - default_gems_restricted_folder.mkdir(parents=True, exist_ok=True) - default_templates_restricted_folder = default_templates_folder / 'Restricted' - default_templates_restricted_folder.mkdir(parents=True, exist_ok=True) - - json_data = {} - json_data.update({'o3de_manifest_name': f'{username}'}) - json_data.update({'origin': o3de_folder.as_posix()}) - json_data.update({'default_engines_folder': default_engines_folder.as_posix()}) - json_data.update({'default_projects_folder': default_projects_folder.as_posix()}) - json_data.update({'default_gems_folder': default_gems_folder.as_posix()}) - json_data.update({'default_templates_folder': default_templates_folder.as_posix()}) - json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) - - json_data.update({'projects': []}) - json_data.update({'gems': []}) - json_data.update({'templates': []}) - json_data.update({'restricted': []}) - json_data.update({'repos': []}) - json_data.update({'engines': []}) - - default_restricted_folder_json = default_restricted_folder / 'restricted.json' - if not default_restricted_folder_json.is_file(): - with default_restricted_folder_json.open('w') as s: - restricted_json_data = {} - restricted_json_data.update({'restricted_name': 'o3de'}) - s.write(json.dumps(restricted_json_data, indent=4)) - json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) - - default_projects_restricted_folder_json = default_projects_restricted_folder / 'restricted.json' - if not default_projects_restricted_folder_json.is_file(): - with default_projects_restricted_folder_json.open('w') as s: - restricted_json_data = {} - restricted_json_data.update({'restricted_name': 'projects'}) - s.write(json.dumps(restricted_json_data, indent=4)) - - default_gems_restricted_folder_json = default_gems_restricted_folder / 'restricted.json' - if not default_gems_restricted_folder_json.is_file(): - with default_gems_restricted_folder_json.open('w') as s: - restricted_json_data = {} - restricted_json_data.update({'restricted_name': 'gems'}) - s.write(json.dumps(restricted_json_data, indent=4)) - - default_templates_restricted_folder_json = default_templates_restricted_folder / 'restricted.json' - if not default_templates_restricted_folder_json.is_file(): - with default_templates_restricted_folder_json.open('w') as s: - restricted_json_data = {} - restricted_json_data.update({'restricted_name': 'templates'}) - s.write(json.dumps(restricted_json_data, indent=4)) - - with manifest_path.open('w') as s: - s.write(json.dumps(json_data, indent=4)) - - return manifest_path - - -def load_o3de_manifest() -> dict: - with get_o3de_manifest().open('r') as f: - try: - json_data = json.load(f) - except Exception as e: - logger.error(f'Manifest json failed to load: {str(e)}') - else: - return json_data - - -def save_o3de_manifest(json_data: dict) -> None: - with get_o3de_manifest().open('w') as s: - try: - s.write(json.dumps(json_data, indent=4)) - except Exception as e: - logger.error(f'Manifest json failed to save: {str(e)}') - - -def remove_engine_name_to_path(json_data: dict, - engine_path: pathlib.Path) -> int: - """ - Remove the engine at the specified path if it exist in the o3de manifest - :param json_data in-memory json view of the o3de_manifest.json data - :param engine_path path to engine to remove from the manifest data - - returns 0 to indicate no issues has occurred with removal - """ - if engine_path.is_dir() and valid_o3de_engine_json(engine_path): - engine_json_data = get_engine_data(engine_path=engine_path) - if 'engine_name' in engine_json_data and 'engines_path' in json_data: - engine_name = engine_json_data['engine_name'] - try: - del json_data['engines_path'][engine_name] - except KeyError: - # Attempting to remove a non-existent engine_name is fine - pass - return 0 - - -def add_engine_name_to_path(json_data: dict, engine_path: pathlib.Path, force: bool): - # Add an engine path JSON object which maps the "engine_name" -> "engine_path" - engine_json_data = get_engine_data(engine_path=engine_path) - if not engine_json_data: - logger.error(f'Unable to retrieve json data from engine.json at path {engine_path.as_posix()}') - return 1 - engines_path_json = json_data.setdefault('engines_path', {}) - if 'engine_name' not in engine_json_data: - logger.error(f'engine.json at path {engine_path.as_posix()} is missing "engine_name" key') - return 1 - - engine_name = engine_json_data['engine_name'] - if not force and engine_name in engines_path_json and \ - pathlib.PurePath(engines_path_json[engine_name]) != engine_path: - logger.error( - f'Attempting to register existing engine "{engine_name}" with a new path of {engine_path.as_posix()}.' - f' The current path is {pathlib.Path(engines_path_json[engine_name]).as_posix()}.' - f' To force registration of a new engine path, specify the -f/--force option.') - return 1 - engines_path_json[engine_name] = engine_path.as_posix() - return 0 - -def register_engine_path(json_data: dict, - engine_path: str or pathlib.Path, - remove: bool = False, - force: bool = False) -> int: - if not engine_path: - logger.error(f'Engine path cannot be empty.') - return 1 - engine_path = pathlib.Path(engine_path).resolve() - - for engine_object in json_data.get('engines', {}): - engine_object_path = pathlib.Path(engine_object['path']).resolve() - if engine_object_path == engine_path: - json_data['engines'].remove(engine_object) - - if remove: - return remove_engine_name_to_path(json_data, engine_path) - - if not engine_path.is_dir(): - logger.error(f'Engine path {engine_path} does not exist.') - return 1 - - engine_json = engine_path / 'engine.json' - if not valid_o3de_engine_json(engine_json): - logger.error(f'Engine json {engine_json} is not valid.') - return 1 - - engine_object = {} - engine_object.update({'path': engine_path.as_posix()}) - engine_object.update({'projects': []}) - engine_object.update({'gems': []}) - engine_object.update({'templates': []}) - engine_object.update({'restricted': []}) - engine_object.update({'external_subdirectories': []}) - - json_data.setdefault('engines', []).insert(0, engine_object) - - return add_engine_name_to_path(json_data, engine_path, force) - - -def register_gem_path(json_data: dict, - gem_path: str or pathlib.Path, - remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: - if not gem_path: - logger.error(f'Gem path cannot be empty.') - return 1 - gem_path = pathlib.Path(gem_path).resolve() - - if engine_path: - engine_data = find_engine_data(json_data, engine_path) - if not engine_data: - logger.error(f'Engine path {engine_path} is not registered.') - return 1 - - while gem_path in engine_data['gems']: - engine_data['gems'].remove(gem_path) - - while gem_path.as_posix() in engine_data['gems']: - engine_data['gems'].remove(gem_path.as_posix()) - - if remove: - logger.warn(f'Removing Gem path {gem_path}.') - return 0 - else: - while gem_path in json_data['gems']: - json_data['gems'].remove(gem_path) - - while gem_path.as_posix() in json_data['gems']: - json_data['gems'].remove(gem_path.as_posix()) - - if remove: - logger.warn(f'Removing Gem path {gem_path}.') - return 0 - - if not gem_path.is_dir(): - logger.error(f'Gem path {gem_path} does not exist.') - return 1 - - gem_json = gem_path / 'gem.json' - if not valid_o3de_gem_json(gem_json): - logger.error(f'Gem json {gem_json} is not valid.') - return 1 - - if engine_path: - engine_data['gems'].insert(0, gem_path.as_posix()) - else: - json_data['gems'].insert(0, gem_path.as_posix()) - - return 0 - - -def register_project_path(json_data: dict, - project_path: str or pathlib.Path, - remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: - if not project_path: - logger.error(f'Project path cannot be empty.') - return 1 - project_path = pathlib.Path(project_path).resolve() - - if engine_path: - engine_data = find_engine_data(json_data, engine_path) - if not engine_data: - logger.error(f'Engine path {engine_path} is not registered.') - return 1 - - while project_path in engine_data['projects']: - engine_data['projects'].remove(project_path) - - while project_path.as_posix() in engine_data['projects']: - engine_data['projects'].remove(project_path.as_posix()) - - if remove: - logger.warn(f'Engine {engine_path} removing Project path {project_path}.') - return 0 - else: - while project_path in json_data['projects']: - json_data['projects'].remove(project_path) - - while project_path.as_posix() in json_data['projects']: - json_data['projects'].remove(project_path.as_posix()) - - if remove: - logger.warn(f'Removing Project path {project_path}.') - return 0 - - if not project_path.is_dir(): - logger.error(f'Project path {project_path} does not exist.') - return 1 - - project_json = project_path / 'project.json' - if not valid_o3de_project_json(project_json): - logger.error(f'Project json {project_json} is not valid.') - return 1 - - if engine_path: - engine_data['projects'].insert(0, project_path.as_posix()) - else: - json_data['projects'].insert(0, project_path.as_posix()) - - # registering a project has the additional step of setting the project.json 'engine' field - this_engine_json = get_this_engine_path() / 'engine.json' - with this_engine_json.open('r') as f: - try: - this_engine_json = json.load(f) - except Exception as e: - logger.error(f'Engine json failed to load: {str(e)}') - return 1 - with project_json.open('r') as f: - try: - project_json_data = json.load(f) - except Exception as e: - logger.error(f'Project json failed to load: {str(e)}') - return 1 - - update_project_json = False - try: - update_project_json = project_json_data['engine'] != this_engine_json['engine_name'] - except Exception as e: - update_project_json = True - - if update_project_json: - project_json_data['engine'] = this_engine_json['engine_name'] - backup_file(project_json) - with project_json.open('w') as s: - try: - s.write(json.dumps(project_json_data, indent=4)) - except Exception as e: - logger.error(f'Project json failed to save: {str(e)}') - return 1 - - return 0 - - -def register_template_path(json_data: dict, - template_path: str or pathlib.Path, - remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: - if not template_path: - logger.error(f'Template path cannot be empty.') - return 1 - template_path = pathlib.Path(template_path).resolve() - - if engine_path: - engine_data = find_engine_data(json_data, engine_path) - if not engine_data: - logger.error(f'Engine path {engine_path} is not registered.') - return 1 - - while template_path in engine_data['templates']: - engine_data['templates'].remove(template_path) - - while template_path.as_posix() in engine_data['templates']: - engine_data['templates'].remove(template_path.as_posix()) - - if remove: - logger.warn(f'Engine {engine_path} removing Template path {template_path}.') - return 0 - else: - while template_path in json_data['templates']: - json_data['templates'].remove(template_path) - - while template_path.as_posix() in json_data['templates']: - json_data['templates'].remove(template_path.as_posix()) - - if remove: - logger.warn(f'Removing Template path {template_path}.') - return 0 - - if not template_path.is_dir(): - logger.error(f'Template path {template_path} does not exist.') - return 1 - - template_json = template_path / 'template.json' - if not valid_o3de_template_json(template_json): - logger.error(f'Template json {template_json} is not valid.') - return 1 - - if engine_path: - engine_data['templates'].insert(0, template_path.as_posix()) - else: - json_data['templates'].insert(0, template_path.as_posix()) - - return 0 - - -def register_restricted_path(json_data: dict, - restricted_path: str or pathlib.Path, - remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: - if not restricted_path: - logger.error(f'Restricted path cannot be empty.') - return 1 - restricted_path = pathlib.Path(restricted_path).resolve() - - if engine_path: - engine_data = find_engine_data(json_data, engine_path) - if not engine_data: - logger.error(f'Engine path {engine_path} is not registered.') - return 1 - - while restricted_path in engine_data['restricted']: - engine_data['restricted'].remove(restricted_path) - - while restricted_path.as_posix() in engine_data['restricted']: - engine_data['restricted'].remove(restricted_path.as_posix()) - - if remove: - logger.warn(f'Engine {engine_path} removing Restricted path {restricted_path}.') - return 0 - else: - while restricted_path in json_data['restricted']: - json_data['restricted'].remove(restricted_path) - - while restricted_path.as_posix() in json_data['restricted']: - json_data['restricted'].remove(restricted_path.as_posix()) - - if remove: - logger.warn(f'Removing Restricted path {restricted_path}.') - return 0 - - if not restricted_path.is_dir(): - logger.error(f'Restricted path {restricted_path} does not exist.') - return 1 - - restricted_json = restricted_path / 'restricted.json' - if not valid_o3de_restricted_json(restricted_json): - logger.error(f'Restricted json {restricted_json} is not valid.') - return 1 - - if engine_path: - engine_data['restricted'].insert(0, restricted_path.as_posix()) - else: - json_data['restricted'].insert(0, restricted_path.as_posix()) - - return 0 - - -def valid_o3de_repo_json(file_name: str or pathlib.Path) -> bool: - file_name = pathlib.Path(file_name).resolve() - if not file_name.is_file(): - return False - - with file_name.open('r') as f: - try: - json_data = json.load(f) - test = json_data['repo_name'] - test = json_data['origin'] - except Exception as e: - return False - - return True - - -def valid_o3de_engine_json(file_name: str or pathlib.Path) -> bool: - file_name = pathlib.Path(file_name).resolve() - if not file_name.is_file(): - return False - - with file_name.open('r') as f: - try: - json_data = json.load(f) - test = json_data['engine_name'] - # test = json_data['origin'] # will be required soon - except Exception as e: - return False - return True - - -def valid_o3de_project_json(file_name: str or pathlib.Path) -> bool: - file_name = pathlib.Path(file_name).resolve() - if not file_name.is_file(): - return False - - with file_name.open('r') as f: - try: - json_data = json.load(f) - test = json_data['project_name'] - # test = json_data['origin'] # will be required soon - except Exception as e: - return False - return True - - -def valid_o3de_gem_json(file_name: str or pathlib.Path) -> bool: - file_name = pathlib.Path(file_name).resolve() - if not file_name.is_file(): - return False - - with file_name.open('r') as f: - try: - json_data = json.load(f) - test = json_data['gem_name'] - # test = json_data['origin'] # will be required soon - except Exception as e: - return False - return True - - -def valid_o3de_template_json(file_name: str or pathlib.Path) -> bool: - file_name = pathlib.Path(file_name).resolve() - if not file_name.is_file(): - return False - with file_name.open('r') as f: - try: - json_data = json.load(f) - test = json_data['template_name'] - # test = json_data['origin'] # will be required soon - except Exception as e: - return False - return True - - -def valid_o3de_restricted_json(file_name: str or pathlib.Path) -> bool: - file_name = pathlib.Path(file_name).resolve() - if not file_name.is_file(): - return False - with file_name.open('r') as f: - try: - json_data = json.load(f) - test = json_data['restricted_name'] - # test = json_data['origin'] # will be required soon - except Exception as e: - return False - return True - - -def process_add_o3de_repo(file_name: str or pathlib.Path, - repo_set: set) -> int: - file_name = pathlib.Path(file_name).resolve() - if not valid_o3de_repo_json(file_name): - return 1 - - cache_folder = get_o3de_cache_folder() - - with file_name.open('r') as f: - try: - repo_data = json.load(f) - except Exception as e: - logger.error(f'{file_name} failed to load: {str(e)}') - return 1 - - for engine_uri in repo_data['engines']: - engine_uri = f'{engine_uri}/engine.json' - engine_sha256 = hashlib.sha256(engine_uri.encode()) - cache_file = cache_folder / str(engine_sha256.hexdigest() + '.json') - if not cache_file.is_file(): - parsed_uri = urllib.parse.urlparse(engine_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(engine_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - engine_json = pathlib.Path(engine_uri).resolve() - if not engine_json.is_file(): - return 1 - shutil.copy(engine_json, cache_file) - - for project_uri in repo_data['projects']: - project_uri = f'{project_uri}/project.json' - project_sha256 = hashlib.sha256(project_uri.encode()) - cache_file = cache_folder / str(project_sha256.hexdigest() + '.json') - if not cache_file.is_file(): - parsed_uri = urllib.parse.urlparse(project_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(project_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - project_json = pathlib.Path(project_uri).resolve() - if not project_json.is_file(): - return 1 - shutil.copy(project_json, cache_file) - - for gem_uri in repo_data['gems']: - gem_uri = f'{gem_uri}/gem.json' - gem_sha256 = hashlib.sha256(gem_uri.encode()) - cache_file = cache_folder / str(gem_sha256.hexdigest() + '.json') - if not cache_file.is_file(): - parsed_uri = urllib.parse.urlparse(gem_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(gem_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - gem_json = pathlib.Path(gem_uri).resolve() - if not gem_json.is_file(): - return 1 - shutil.copy(gem_json, cache_file) - - for template_uri in repo_data['templates']: - template_uri = f'{template_uri}/template.json' - template_sha256 = hashlib.sha256(template_uri.encode()) - cache_file = cache_folder / str(template_sha256.hexdigest() + '.json') - if not cache_file.is_file(): - parsed_uri = urllib.parse.urlparse(template_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(template_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - template_json = pathlib.Path(template_uri).resolve() - if not template_json.is_file(): - return 1 - shutil.copy(template_json, cache_file) - - for repo_uri in repo_data['repos']: - if repo_uri not in repo_set: - repo_set.add(repo_uri) - repo_uri = f'{repo_uri}/repo.json' - repo_sha256 = hashlib.sha256(repo_uri.encode()) - cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') - if not cache_file.is_file(): - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(repo_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - repo_json = pathlib.Path(repo_uri).resolve() - if not repo_json.is_file(): - return 1 - shutil.copy(repo_json, cache_file) - return 0 - - -def register_repo(json_data: dict, - repo_uri: str or pathlib.Path, - remove: bool = False) -> int: - if not repo_uri: - logger.error(f'Repo URI cannot be empty.') - return 1 - - url = f'{repo_uri}/repo.json' - parsed_uri = urllib.parse.urlparse(url) - - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - while repo_uri in json_data['repos']: - json_data['repos'].remove(repo_uri) - else: - repo_uri = pathlib.Path(repo_uri).resolve() - while repo_uri.as_posix() in json_data['repos']: - json_data['repos'].remove(repo_uri.as_posix()) - - if remove: - logger.warn(f'Removing repo uri {repo_uri}.') - return 0 - - repo_sha256 = hashlib.sha256(url.encode()) - cache_file = get_o3de_cache_folder() / str(repo_sha256.hexdigest() + '.json') - - result = 0 - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - if not cache_file.is_file(): - with urllib.request.urlopen(url) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - json_data['repos'].insert(0, repo_uri) - else: - if not cache_file.is_file(): - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, origin_file) - json_data['repos'].insert(0, repo_uri.as_posix()) - - repo_set = set() - result = process_add_o3de_repo(cache_file, repo_set) - - return result - - -def register_default_engines_folder(json_data: dict, - default_engines_folder: str or pathlib.Path, - remove: bool = False) -> int: - if remove: - default_engines_folder = get_o3de_engines_folder() - - # make sure the path exists - default_engines_folder = pathlib.Path(default_engines_folder).resolve() - if not default_engines_folder.is_dir(): - logger.error(f'Default engines folder {default_engines_folder} does not exist.') - return 1 - - default_engines_folder = default_engines_folder.as_posix() - json_data['default_engines_folder'] = default_engines_folder - - return 0 - - -def register_default_projects_folder(json_data: dict, - default_projects_folder: str or pathlib.Path, - remove: bool = False) -> int: - if remove: - default_projects_folder = get_o3de_projects_folder() - - # make sure the path exists - default_projects_folder = pathlib.Path(default_projects_folder).resolve() - if not default_projects_folder.is_dir(): - logger.error(f'Default projects folder {default_projects_folder} does not exist.') - return 1 - - default_projects_folder = default_projects_folder.as_posix() - json_data['default_projects_folder'] = default_projects_folder - - return 0 - - -def register_default_gems_folder(json_data: dict, - default_gems_folder: str or pathlib.Path, - remove: bool = False) -> int: - if remove: - default_gems_folder = get_o3de_gems_folder() - - # make sure the path exists - default_gems_folder = pathlib.Path(default_gems_folder).resolve() - if not default_gems_folder.is_dir(): - logger.error(f'Default gems folder {default_gems_folder} does not exist.') - return 1 - - default_gems_folder = default_gems_folder.as_posix() - json_data['default_gems_folder'] = default_gems_folder - - return 0 - - -def register_default_templates_folder(json_data: dict, - default_templates_folder: str or pathlib.Path, - remove: bool = False) -> int: - if remove: - default_templates_folder = get_o3de_templates_folder() - - # make sure the path exists - default_templates_folder = pathlib.Path(default_templates_folder).resolve() - if not default_templates_folder.is_dir(): - logger.error(f'Default templates folder {default_templates_folder} does not exist.') - return 1 - - default_templates_folder = default_templates_folder.as_posix() - json_data['default_templates_folder'] = default_templates_folder - - return 0 - - -def register_default_restricted_folder(json_data: dict, - default_restricted_folder: str or pathlib.Path, - remove: bool = False) -> int: - if remove: - default_restricted_folder = get_o3de_restricted_folder() - - # make sure the path exists - default_restricted_folder = pathlib.Path(default_restricted_folder).resolve() - if not default_restricted_folder.is_dir(): - logger.error(f'Default restricted folder {default_restricted_folder} does not exist.') - return 1 - - default_restricted_folder = default_restricted_folder.as_posix() - json_data['default_restricted_folder'] = default_restricted_folder - - return 0 - - -def register(engine_path: str or pathlib.Path = None, - project_path: str or pathlib.Path = None, - gem_path: str or pathlib.Path = None, - template_path: str or pathlib.Path = None, - restricted_path: str or pathlib.Path = None, - repo_uri: str or pathlib.Path = None, - default_engines_folder: str or pathlib.Path = None, - default_projects_folder: str or pathlib.Path = None, - default_gems_folder: str or pathlib.Path = None, - default_templates_folder: str or pathlib.Path = None, - default_restricted_folder: str or pathlib.Path = None, - remove: bool = False, - force: bool = False - ) -> int: - """ - Adds/Updates entries to the .o3de/o3de_manifest.json - - :param engine_path: if engine folder is supplied the path will be added to the engine if it can, if not global - :param project_path: project folder - :param gem_path: gem folder - :param template_path: template folder - :param restricted_path: restricted folder - :param repo_uri: repo uri - :param default_engines_folder: default engines folder - :param default_projects_folder: default projects folder - :param default_gems_folder: default gems folder - :param default_templates_folder: default templates folder - :param default_restricted_folder: default restricted code folder - :param remove: add/remove the entries - :param force: force update of the engine_path for specified "engine_name" from the engine.json file - - :return: 0 for success or non 0 failure code - """ - - json_data = load_o3de_manifest() - - result = 0 - - # do anything that could require a engine context first - if isinstance(project_path, str) or isinstance(project_path, pathlib.PurePath): - if not project_path: - logger.error(f'Project path cannot be empty.') - return 1 - result = register_project_path(json_data, project_path, remove, engine_path) - - elif isinstance(gem_path, str) or isinstance(gem_path, pathlib.PurePath): - if not gem_path: - logger.error(f'Gem path cannot be empty.') - return 1 - result = register_gem_path(json_data, gem_path, remove, engine_path) - - elif isinstance(template_path, str) or isinstance(template_path, pathlib.PurePath): - if not template_path: - logger.error(f'Template path cannot be empty.') - return 1 - result = register_template_path(json_data, template_path, remove, engine_path) - - elif isinstance(restricted_path, str) or isinstance(restricted_path, pathlib.PurePath): - if not restricted_path: - logger.error(f'Restricted path cannot be empty.') - return 1 - result = register_restricted_path(json_data, restricted_path, remove, engine_path) - - elif isinstance(repo_uri, str) or isinstance(repo_uri, pathlib.PurePath): - if not repo_uri: - logger.error(f'Repo URI cannot be empty.') - return 1 - result = register_repo(json_data, repo_uri, remove) - - elif isinstance(default_engines_folder, str) or isinstance(default_engines_folder, pathlib.PurePath): - result = register_default_engines_folder(json_data, default_engines_folder, remove) - - elif isinstance(default_projects_folder, str) or isinstance(default_projects_folder, pathlib.PurePath): - result = register_default_projects_folder(json_data, default_projects_folder, remove) - - elif isinstance(default_gems_folder, str) or isinstance(default_gems_folder, pathlib.PurePath): - result = register_default_gems_folder(json_data, default_gems_folder, remove) - - elif isinstance(default_templates_folder, str) or isinstance(default_templates_folder, pathlib.PurePath): - result = register_default_templates_folder(json_data, default_templates_folder, remove) - - elif isinstance(default_restricted_folder, str) or isinstance(default_restricted_folder, pathlib.PurePath): - result = register_default_restricted_folder(json_data, default_restricted_folder, remove) - - # engine is done LAST - # Now that everything that could have an engine context is done, if the engine is supplied that means this is - # registering the engine itself - elif isinstance(engine_path, str) or isinstance(engine_path, pathlib.PurePath): - if not engine_path: - logger.error(f'Engine path cannot be empty.') - return 1 - result = register_engine_path(json_data, engine_path, remove, force) - - if not result: - save_o3de_manifest(json_data) - - return result - - -def remove_invalid_o3de_objects() -> None: - json_data = load_o3de_manifest() - - for engine_object in json_data['engines']: - engine_path = engine_object['path'] - if not valid_o3de_engine_json(pathlib.Path(engine_path).resolve() / 'engine.json'): - logger.warn(f"Engine path {engine_path} is invalid.") - register(engine_path=engine_path, remove=True) - else: - for project in engine_object['projects']: - if not valid_o3de_project_json(pathlib.Path(project).resolve() / 'project.json'): - logger.warn(f"Project path {project} is invalid.") - register(engine_path=engine_path, project_path=project, remove=True) - - for gem_path in engine_object['gems']: - if not valid_o3de_gem_json(pathlib.Path(gem_path).resolve() / 'gem.json'): - logger.warn(f"Gem path {gem_path} is invalid.") - register(engine_path=engine_path, gem_path=gem_path, remove=True) - - for template_path in engine_object['templates']: - if not valid_o3de_template_json(pathlib.Path(template_path).resolve() / 'template.json'): - logger.warn(f"Template path {template_path} is invalid.") - register(engine_path=engine_path, template_path=template_path, remove=True) - - for restricted in engine_object['restricted']: - if not valid_o3de_restricted_json(pathlib.Path(restricted).resolve() / 'restricted.json'): - logger.warn(f"Restricted path {restricted} is invalid.") - register(engine_path=engine_path, restricted_path=restricted, remove=True) - - for external in engine_object['external_subdirectories']: - external = pathlib.Path(external).resolve() - if not external.is_dir(): - logger.warn(f"External subdirectory {external} is invalid.") - remove_external_subdirectory(external) - - for project in json_data['projects']: - if not valid_o3de_project_json(pathlib.Path(project).resolve() / 'project.json'): - logger.warn(f"Project path {project} is invalid.") - register(project_path=project, remove=True) - - for gem in json_data['gems']: - if not valid_o3de_gem_json(pathlib.Path(gem).resolve() / 'gem.json'): - logger.warn(f"Gem path {gem} is invalid.") - register(gem_path=gem, remove=True) - - for template in json_data['templates']: - if not valid_o3de_template_json(pathlib.Path(template).resolve() / 'template.json'): - logger.warn(f"Template path {template} is invalid.") - register(template_path=template, remove=True) - - for restricted in json_data['restricted']: - if not valid_o3de_restricted_json(pathlib.Path(restricted).resolve() / 'restricted.json'): - logger.warn(f"Restricted path {restricted} is invalid.") - register(restricted_path=restricted, remove=True) - - default_engines_folder = pathlib.Path(json_data['default_engines_folder']).resolve() - if not default_engines_folder.is_dir(): - new_default_engines_folder = get_o3de_folder() / 'Engines' - new_default_engines_folder.mkdir(parents=True, exist_ok=True) - logger.warn( - f"Default engines folder {default_engines_folder} is invalid. Set default {new_default_engines_folder}") - register(default_engines_folder=new_default_engines_folder.as_posix()) - - default_projects_folder = pathlib.Path(json_data['default_projects_folder']).resolve() - if not default_projects_folder.is_dir(): - new_default_projects_folder = get_o3de_folder() / 'Projects' - new_default_projects_folder.mkdir(parents=True, exist_ok=True) - logger.warn( - f"Default projects folder {default_projects_folder} is invalid. Set default {new_default_projects_folder}") - register(default_projects_folder=new_default_projects_folder.as_posix()) - - default_gems_folder = pathlib.Path(json_data['default_gems_folder']).resolve() - if not default_gems_folder.is_dir(): - new_default_gems_folder = get_o3de_folder() / 'Gems' - new_default_gems_folder.mkdir(parents=True, exist_ok=True) - logger.warn(f"Default gems folder {default_gems_folder} is invalid." - f" Set default {new_default_gems_folder}") - register(default_gems_folder=new_default_gems_folder.as_posix()) - - default_templates_folder = pathlib.Path(json_data['default_templates_folder']).resolve() - if not default_templates_folder.is_dir(): - new_default_templates_folder = get_o3de_folder() / 'Templates' - new_default_templates_folder.mkdir(parents=True, exist_ok=True) - logger.warn( - f"Default templates folder {default_templates_folder} is invalid." - f" Set default {new_default_templates_folder}") - register(default_templates_folder=new_default_templates_folder.as_posix()) - - default_restricted_folder = pathlib.Path(json_data['default_restricted_folder']).resolve() - if not default_restricted_folder.is_dir(): - default_restricted_folder = get_o3de_folder() / 'Restricted' - default_restricted_folder.mkdir(parents=True, exist_ok=True) - logger.warn( - f"Default restricted folder {default_restricted_folder} is invalid." - f" Set default {default_restricted_folder}") - register(default_restricted_folder=default_restricted_folder.as_posix()) - - -def refresh_repos() -> int: - json_data = load_o3de_manifest() - - # clear the cache - cache_folder = get_o3de_cache_folder() - shutil.rmtree(cache_folder) - cache_folder = get_o3de_cache_folder() # will recreate it - - result = 0 - - # set will stop circular references - repo_set = set() - - for repo_uri in json_data['repos']: - if repo_uri not in repo_set: - repo_set.add(repo_uri) - - repo_uri = f'{repo_uri}/repo.json' - repo_sha256 = hashlib.sha256(repo_uri.encode()) - cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') - if not cache_file.is_file(): - parsed_uri = urllib.parse.urlparse(repo_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(repo_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(repo_uri).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, cache_file) - - if not valid_o3de_repo_json(cache_file): - logger.error(f'Repo json {repo_uri} is not valid.') - cache_file.unlink() - return 1 - - last_failure = process_add_o3de_repo(cache_file, repo_set) - if last_failure: - result = last_failure - - return result - - -def search_repo(repo_set: set, - repo_json_data: dict, - engine_name: str = None, - project_name: str = None, - gem_name: str = None, - template_name: str = None, - restricted_name: str = None) -> dict or None: - cache_folder = get_o3de_cache_folder() - - if isinstance(engine_name, str) or isinstance(engine_name, pathlib.PurePath): - for engine_uri in repo_json_data['engines']: - engine_uri = f'{engine_uri}/engine.json' - engine_sha256 = hashlib.sha256(engine_uri.encode()) - engine_cache_file = cache_folder / str(engine_sha256.hexdigest() + '.json') - if engine_cache_file.is_file(): - with engine_cache_file.open('r') as f: - try: - engine_json_data = json.load(f) - except Exception as e: - logger.warn(f'{engine_cache_file} failed to load: {str(e)}') - else: - if engine_json_data['engine_name'] == engine_name: - return engine_json_data - - elif isinstance(project_name, str) or isinstance(project_name, pathlib.PurePath): - for project_uri in repo_json_data['projects']: - project_uri = f'{project_uri}/project.json' - project_sha256 = hashlib.sha256(project_uri.encode()) - project_cache_file = cache_folder / str(project_sha256.hexdigest() + '.json') - if project_cache_file.is_file(): - with project_cache_file.open('r') as f: - try: - project_json_data = json.load(f) - except Exception as e: - logger.warn(f'{project_cache_file} failed to load: {str(e)}') - else: - if project_json_data['project_name'] == project_name: - return project_json_data - - elif isinstance(gem_name, str) or isinstance(gem_name, pathlib.PurePath): - for gem_uri in repo_json_data['gems']: - gem_uri = f'{gem_uri}/gem.json' - gem_sha256 = hashlib.sha256(gem_uri.encode()) - gem_cache_file = cache_folder / str(gem_sha256.hexdigest() + '.json') - if gem_cache_file.is_file(): - with gem_cache_file.open('r') as f: - try: - gem_json_data = json.load(f) - except Exception as e: - logger.warn(f'{gem_cache_file} failed to load: {str(e)}') - else: - if gem_json_data['gem_name'] == gem_name: - return gem_json_data - - elif isinstance(template_name, str) or isinstance(template_name, pathlib.PurePath): - for template_uri in repo_json_data['templates']: - template_uri = f'{template_uri}/template.json' - template_sha256 = hashlib.sha256(template_uri.encode()) - template_cache_file = cache_folder / str(template_sha256.hexdigest() + '.json') - if template_cache_file.is_file(): - with template_cache_file.open('r') as f: - try: - template_json_data = json.load(f) - except Exception as e: - logger.warn(f'{template_cache_file} failed to load: {str(e)}') - else: - if template_json_data['template_name'] == template_name: - return template_json_data - - elif isinstance(restricted_name, str) or isinstance(restricted_name, pathlib.PurePath): - for restricted_uri in repo_json_data['restricted']: - restricted_uri = f'{restricted_uri}/restricted.json' - restricted_sha256 = hashlib.sha256(restricted_uri.encode()) - restricted_cache_file = cache_folder / str(restricted_sha256.hexdigest() + '.json') - if restricted_cache_file.is_file(): - with restricted_cache_file.open('r') as f: - try: - restricted_json_data = json.load(f) - except Exception as e: - logger.warn(f'{restricted_cache_file} failed to load: {str(e)}') - else: - if restricted_json_data['restricted_name'] == restricted_name: - return restricted_json_data - # recurse - else: - for repo_repo_uri in repo_json_data['repos']: - if repo_repo_uri not in repo_set: - repo_set.add(repo_repo_uri) - repo_repo_uri = f'{repo_repo_uri}/repo.json' - repo_repo_sha256 = hashlib.sha256(repo_repo_uri.encode()) - repo_repo_cache_file = cache_folder / str(repo_repo_sha256.hexdigest() + '.json') - if repo_repo_cache_file.is_file(): - with repo_repo_cache_file.open('r') as f: - try: - repo_repo_json_data = json.load(f) - except Exception as e: - logger.warn(f'{repo_repo_cache_file} failed to load: {str(e)}') - else: - item = search_repo(repo_set, - repo_repo_json_data, - engine_name, - project_name, - gem_name, - template_name) - if item: - return item - return None - - -def get_downloadable(engine_name: str = None, - project_name: str = None, - gem_name: str = None, - template_name: str = None, - restricted_name: str = None) -> dict or None: - json_data = load_o3de_manifest() - cache_folder = get_o3de_cache_folder() - repo_set = set() - for repo_uri in json_data['repos']: - if repo_uri not in repo_set: - repo_set.add(repo_uri) - repo_uri = f'{repo_uri}/repo.json' - repo_sha256 = hashlib.sha256(repo_uri.encode()) - repo_cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') - if repo_cache_file.is_file(): - with repo_cache_file.open('r') as f: - try: - repo_json_data = json.load(f) - except Exception as e: - logger.warn(f'{repo_cache_file} failed to load: {str(e)}') - else: - item = search_repo(repo_set, - repo_json_data, - engine_name, - project_name, - gem_name, - template_name, - restricted_name) - if item: - return item - return None - - -def get_registered(engine_name: str = None, - project_name: str = None, - gem_name: str = None, - template_name: str = None, - default_folder: str = None, - repo_name: str = None, - restricted_name: str = None) -> pathlib.Path or None: - json_data = load_o3de_manifest() - - # check global first then this engine - if isinstance(engine_name, str): - for engine in json_data['engines']: - engine_path = pathlib.Path(engine['path']).resolve() - engine_json = engine_path / 'engine.json' - with engine_json.open('r') as f: - try: - engine_json_data = json.load(f) - except Exception as e: - logger.warn(f'{engine_json} failed to load: {str(e)}') - else: - this_engines_name = engine_json_data['engine_name'] - if this_engines_name == engine_name: - return engine_path - - elif isinstance(project_name, str): - engine_object = find_engine_data(json_data) - projects = json_data['projects'].copy() - projects.extend(engine_object['projects']) - for project_path in projects: - project_path = pathlib.Path(project_path).resolve() - project_json = project_path / 'project.json' - with project_json.open('r') as f: - try: - project_json_data = json.load(f) - except Exception as e: - logger.warn(f'{project_json} failed to load: {str(e)}') - else: - this_projects_name = project_json_data['project_name'] - if this_projects_name == project_name: - return project_path - - elif isinstance(gem_name, str): - engine_object = find_engine_data(json_data) - gems = json_data['gems'].copy() - gems.extend(engine_object['gems']) - for gem_path in gems: - gem_path = pathlib.Path(gem_path).resolve() - gem_json = gem_path / 'gem.json' - with gem_json.open('r') as f: - try: - gem_json_data = json.load(f) - except Exception as e: - logger.warn(f'{gem_json} failed to load: {str(e)}') - else: - this_gems_name = gem_json_data['gem_name'] - if this_gems_name == gem_name: - return gem_path - - elif isinstance(template_name, str): - engine_object = find_engine_data(json_data) - templates = json_data['templates'].copy() - templates.extend(engine_object['templates']) - for template_path in templates: - template_path = pathlib.Path(template_path).resolve() - template_json = template_path / 'template.json' - with template_json.open('r') as f: - try: - template_json_data = json.load(f) - except Exception as e: - logger.warn(f'{template_path} failed to load: {str(e)}') - else: - this_templates_name = template_json_data['template_name'] - if this_templates_name == template_name: - return template_path - - elif isinstance(restricted_name, str): - engine_object = find_engine_data(json_data) - restricted = json_data['restricted'].copy() - restricted.extend(engine_object['restricted']) - for restricted_path in restricted: - restricted_path = pathlib.Path(restricted_path).resolve() - restricted_json = restricted_path / 'restricted.json' - with restricted_json.open('r') as f: - try: - restricted_json_data = json.load(f) - except Exception as e: - logger.warn(f'{restricted_json} failed to load: {str(e)}') - else: - this_restricted_name = restricted_json_data['restricted_name'] - if this_restricted_name == restricted_name: - return restricted_path - - elif isinstance(default_folder, str): - if default_folder == 'engines': - default_engines_folder = pathlib.Path(json_data['default_engines_folder']).resolve() - return default_engines_folder - elif default_folder == 'projects': - default_projects_folder = pathlib.Path(json_data['default_projects_folder']).resolve() - return default_projects_folder - elif default_folder == 'gems': - default_gems_folder = pathlib.Path(json_data['default_gems_folder']).resolve() - return default_gems_folder - elif default_folder == 'templates': - default_templates_folder = pathlib.Path(json_data['default_templates_folder']).resolve() - return default_templates_folder - elif default_folder == 'restricted': - default_restricted_folder = pathlib.Path(json_data['default_restricted_folder']).resolve() - return default_restricted_folder - - elif isinstance(repo_name, str): - cache_folder = get_o3de_cache_folder() - for repo_uri in json_data['repos']: - repo_uri = pathlib.Path(repo_uri).resolve() - repo_sha256 = hashlib.sha256(repo_uri.encode()) - cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') - if cache_file.is_file(): - repo = pathlib.Path(cache_file).resolve() - with repo.open('r') as f: - try: - repo_json_data = json.load(f) - except Exception as e: - logger.warn(f'{cache_file} failed to load: {str(e)}') - else: - this_repos_name = repo_json_data['repo_name'] - if this_repos_name == repo_name: - return repo_uri - return None - - -def print_engines_data(engines_data: dict) -> None: - print('\n') - print("Engines================================================") - for engine_object in engines_data: - # if it's not local it should be in the cache - engine_uri = engine_object['path'] - parsed_uri = urllib.parse.urlparse(engine_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - repo_sha256 = hashlib.sha256(engine_uri.encode()) - cache_folder = get_o3de_cache_folder() - engine = cache_folder / str(repo_sha256.hexdigest() + '.json') - print(f'{engine_uri}/engine.json cached as:') - else: - engine_json = pathlib.Path(engine_uri).resolve() / 'engine.json' - - with engine_json.open('r') as f: - try: - engine_json_data = json.load(f) - except Exception as e: - logger.warn(f'{engine_json} failed to load: {str(e)}') - else: - print(engine_json) - print(json.dumps(engine_json_data, indent=4)) - print('\n') - - -def print_projects_data(projects_data: dict) -> None: - print('\n') - print("Projects================================================") - for project_uri in projects_data: - # if it's not local it should be in the cache - parsed_uri = urllib.parse.urlparse(project_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - repo_sha256 = hashlib.sha256(project_uri.encode()) - cache_folder = get_o3de_cache_folder() - project_json = cache_folder / str(repo_sha256.hexdigest() + '.json') - else: - project_json = pathlib.Path(project_uri).resolve() / 'project.json' - - with project_json.open('r') as f: - try: - project_json_data = json.load(f) - except Exception as e: - logger.warn(f'{project_json} failed to load: {str(e)}') - else: - print(project_json) - print(json.dumps(project_json_data, indent=4)) - print('\n') - - -def print_gems_data(gems_data: dict) -> None: - print('\n') - print("Gems================================================") - for gem_uri in gems_data: - # if it's not local it should be in the cache - parsed_uri = urllib.parse.urlparse(gem_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - repo_sha256 = hashlib.sha256(gem_uri.encode()) - cache_folder = get_o3de_cache_folder() - gem_json = cache_folder / str(repo_sha256.hexdigest() + '.json') - else: - gem_json = pathlib.Path(gem_uri).resolve() / 'gem.json' - - with gem_json.open('r') as f: - try: - gem_json_data = json.load(f) - except Exception as e: - logger.warn(f'{gem_json} failed to load: {str(e)}') - else: - print(gem_json) - print(json.dumps(gem_json_data, indent=4)) - print('\n') - - -def print_templates_data(templates_data: dict) -> None: - print('\n') - print("Templates================================================") - for template_uri in templates_data: - # if it's not local it should be in the cache - parsed_uri = urllib.parse.urlparse(template_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - repo_sha256 = hashlib.sha256(template_uri.encode()) - cache_folder = get_o3de_cache_folder() - template_json = cache_folder / str(repo_sha256.hexdigest() + '.json') - else: - template_json = pathlib.Path(template_uri).resolve() / 'template.json' - - with template_json.open('r') as f: - try: - template_json_data = json.load(f) - except Exception as e: - logger.warn(f'{template_json} failed to load: {str(e)}') - else: - print(template_json) - print(json.dumps(template_json_data, indent=4)) - print('\n') - - -def print_repos_data(repos_data: dict) -> None: - print('\n') - print("Repos================================================") - cache_folder = get_o3de_cache_folder() - for repo_uri in repos_data: - repo_sha256 = hashlib.sha256(repo_uri.encode()) - cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') - if valid_o3de_repo_json(cache_file): - with cache_file.open('r') as s: - try: - repo_json_data = json.load(s) - except Exception as e: - logger.warn(f'{cache_file} failed to load: {str(e)}') - else: - print(f'{repo_uri}/repo.json cached as:') - print(cache_file) - print(json.dumps(repo_json_data, indent=4)) - print('\n') - - -def print_restricted_data(restricted_data: dict) -> None: - print('\n') - print("Restricted================================================") - for restricted_path in restricted_data: - restricted_json = pathlib.Path(restricted_path).resolve() / 'restricted.json' - with restricted_json.open('r') as f: - try: - restricted_json_data = json.load(f) - except Exception as e: - logger.warn(f'{restricted_json} failed to load: {str(e)}') - else: - print(restricted_json) - print(json.dumps(restricted_json_data, indent=4)) - print('\n') - - -def get_this_engine() -> dict: - json_data = load_o3de_manifest() - engine_data = find_engine_data(json_data) - return engine_data - - -def get_engines() -> dict: - json_data = load_o3de_manifest() - return json_data['engines'] - - -def get_projects() -> dict: - json_data = load_o3de_manifest() - return json_data['projects'] - - -def get_gems() -> dict: - json_data = load_o3de_manifest() - return json_data['gems'] - - -def get_templates() -> dict: - json_data = load_o3de_manifest() - return json_data['templates'] - - -def get_restricted() -> dict: - json_data = load_o3de_manifest() - return json_data['restricted'] - - -def get_repos() -> dict: - json_data = load_o3de_manifest() - return json_data['repos'] - - -def get_engine_projects() -> dict: - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data) - return engine_object['projects'] - - -def get_engine_gems() -> dict: - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data) - return engine_object['gems'] - - -def get_engine_templates() -> dict: - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data) - return engine_object['templates'] - - -def get_engine_restricted() -> dict: - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data) - return engine_object['restricted'] - - -def get_external_subdirectories() -> dict: - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data) - return engine_object['external_subdirectories'] - - -def get_all_projects() -> dict: - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data) - projects_data = json_data['projects'].copy() - projects_data.extend(engine_object['projects']) - return projects_data - - -def get_all_gems() -> dict: - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data) - gems_data = json_data['gems'].copy() - gems_data.extend(engine_object['gems']) - return gems_data - - -def get_all_templates() -> dict: - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data) - templates_data = json_data['templates'].copy() - templates_data.extend(engine_object['templates']) - return templates_data - - -def get_all_restricted() -> dict: - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data) - restricted_data = json_data['restricted'].copy() - restricted_data.extend(engine_object['restricted']) - return restricted_data - - -def print_this_engine(verbose: int) -> None: - engine_data = get_this_engine() - print(json.dumps(engine_data, indent=4)) - if verbose > 0: - print_engines_data(engine_data) - - -def print_engines(verbose: int) -> None: - engines_data = get_engines() - print(json.dumps(engines_data, indent=4)) - if verbose > 0: - print_engines_data(engines_data) - - -def print_projects(verbose: int) -> None: - projects_data = get_projects() - print(json.dumps(projects_data, indent=4)) - if verbose > 0: - print_projects_data(projects_data) - - -def print_gems(verbose: int) -> None: - gems_data = get_gems() - print(json.dumps(gems_data, indent=4)) - if verbose > 0: - print_gems_data(gems_data) - - -def print_templates(verbose: int) -> None: - templates_data = get_templates() - print(json.dumps(templates_data, indent=4)) - if verbose > 0: - print_templates_data(templates_data) - - -def print_restricted(verbose: int) -> None: - restricted_data = get_restricted() - print(json.dumps(restricted_data, indent=4)) - if verbose > 0: - print_restricted_data(restricted_data) - - -def register_show_repos(verbose: int) -> None: - repos_data = get_repos() - print(json.dumps(repos_data, indent=4)) - if verbose > 0: - print_repos_data(repos_data) - - -def print_engine_projects(verbose: int) -> None: - engine_projects_data = get_engine_projects() - print(json.dumps(engine_projects_data, indent=4)) - if verbose > 0: - print_projects_data(engine_projects_data) - - -def print_engine_gems(verbose: int) -> None: - engine_gems_data = get_engine_gems() - print(json.dumps(engine_gems_data, indent=4)) - if verbose > 0: - print_gems_data(engine_gems_data) - - -def print_engine_templates(verbose: int) -> None: - engine_templates_data = get_engine_templates() - print(json.dumps(engine_templates_data, indent=4)) - if verbose > 0: - print_templates_data(engine_templates_data) - - -def print_engine_restricted(verbose: int) -> None: - engine_restricted_data = get_engine_restricted() - print(json.dumps(engine_restricted_data, indent=4)) - if verbose > 0: - print_restricted_data(engine_restricted_data) - - -def print_external_subdirectories(verbose: int) -> None: - external_subdirs_data = get_external_subdirectories() - print(json.dumps(external_subdirs_data, indent=4)) - - -def print_all_projects(verbose: int) -> None: - all_projects_data = get_all_projects() - print(json.dumps(all_projects_data, indent=4)) - if verbose > 0: - print_projects_data(all_projects_data) - - -def print_all_gems(verbose: int) -> None: - all_gems_data = get_all_gems() - print(json.dumps(all_gems_data, indent=4)) - if verbose > 0: - print_gems_data(all_gems_data) - - -def print_all_templates(verbose: int) -> None: - all_templates_data = get_all_templates() - print(json.dumps(all_templates_data, indent=4)) - if verbose > 0: - print_templates_data(all_templates_data) - - -def print_all_restricted(verbose: int) -> None: - all_restricted_data = get_all_restricted() - print(json.dumps(all_restricted_data, indent=4)) - if verbose > 0: - print_restricted_data(all_restricted_data) - - -def register_show(verbose: int) -> None: - json_data = load_o3de_manifest() - print(f"{get_o3de_manifest()}:") - print(json.dumps(json_data, indent=4)) - - if verbose > 0: - print_engines_data(get_engines()) - print_projects_data(get_all_projects()) - print_gems_data(get_gems()) - print_templates_data(get_all_templates()) - print_restricted_data(get_all_restricted()) - print_repos_data(get_repos()) - - -def find_engine_data(json_data: dict, - engine_path: str or pathlib.Path = None) -> dict or None: - if not engine_path: - engine_path = get_this_engine_path() - engine_path = pathlib.Path(engine_path).resolve() - - for engine_object in json_data['engines']: - engine_object_path = pathlib.Path(engine_object['path']).resolve() - if engine_path == engine_object_path: - return engine_object - - return None - - -def get_engine_data(engine_name: str = None, - engine_path: str or pathlib.Path = None, ) -> dict or None: - if not engine_name and not engine_path: - logger.error('Must specify either a Engine name or Engine Path.') - return None - - if engine_name and not engine_path: - engine_path = get_registered(engine_name=engine_name) - - if not engine_path: - logger.error(f'Engine Path {engine_path} has not been registered.') - return None - - engine_path = pathlib.Path(engine_path).resolve() - engine_json = engine_path / 'engine.json' - if not engine_json.is_file(): - logger.error(f'Engine json {engine_json} is not present.') - return None - if not valid_o3de_engine_json(engine_json): - logger.error(f'Engine json {engine_json} is not valid.') - return None - - with engine_json.open('r') as f: - try: - engine_json_data = json.load(f) - except Exception as e: - logger.warn(f'{engine_json} failed to load: {str(e)}') - else: - return engine_json_data - - return None - - -def get_project_data(project_name: str = None, - project_path: str or pathlib.Path = None, ) -> dict or None: - if not project_name and not project_path: - logger.error('Must specify either a Project name or Project Path.') - return None - - if project_name and not project_path: - project_path = get_registered(project_name=project_name) - - if not project_path: - logger.error(f'Project Path {project_path} has not been registered.') - return None - - project_path = pathlib.Path(project_path).resolve() - project_json = project_path / 'project.json' - if not project_json.is_file(): - logger.error(f'Project json {project_json} is not present.') - return None - if not valid_o3de_project_json(project_json): - logger.error(f'Project json {project_json} is not valid.') - return None - - with project_json.open('r') as f: - try: - project_json_data = json.load(f) - except Exception as e: - logger.warn(f'{project_json} failed to load: {str(e)}') - else: - return project_json_data - - return None - - -def get_gem_data(gem_name: str = None, - gem_path: str or pathlib.Path = None, ) -> dict or None: - if not gem_name and not gem_path: - logger.error('Must specify either a Gem name or Gem Path.') - return None - - if gem_name and not gem_path: - gem_path = get_registered(gem_name=gem_name) - - if not gem_path: - logger.error(f'Gem Path {gem_path} has not been registered.') - return None - - gem_path = pathlib.Path(gem_path).resolve() - gem_json = gem_path / 'gem.json' - if not gem_json.is_file(): - logger.error(f'Gem json {gem_json} is not present.') - return None - if not valid_o3de_gem_json(gem_json): - logger.error(f'Gem json {gem_json} is not valid.') - return None - - with gem_json.open('r') as f: - try: - gem_json_data = json.load(f) - except Exception as e: - logger.warn(f'{gem_json} failed to load: {str(e)}') - else: - return gem_json_data - - return None - - -def get_template_data(template_name: str = None, - template_path: str or pathlib.Path = None, ) -> dict or None: - if not template_name and not template_path: - logger.error('Must specify either a Template name or Template Path.') - return None - - if template_name and not template_path: - template_path = get_registered(template_name=template_name) - - if not template_path: - logger.error(f'Template Path {template_path} has not been registered.') - return None - - template_path = pathlib.Path(template_path).resolve() - template_json = template_path / 'template.json' - if not template_json.is_file(): - logger.error(f'Template json {template_json} is not present.') - return None - if not valid_o3de_template_json(template_json): - logger.error(f'Template json {template_json} is not valid.') - return None - - with template_json.open('r') as f: - try: - template_json_data = json.load(f) - except Exception as e: - logger.warn(f'{template_json} failed to load: {str(e)}') - else: - return template_json_data - - return None - - -def get_restricted_data(restricted_name: str = None, - restricted_path: str or pathlib.Path = None, ) -> dict or None: - if not restricted_name and not restricted_path: - logger.error('Must specify either a Restricted name or Restricted Path.') - return None - - if restricted_name and not restricted_path: - restricted_path = get_registered(restricted_name=restricted_name) - - if not restricted_path: - logger.error(f'Restricted Path {restricted_path} has not been registered.') - return None - - restricted_path = pathlib.Path(restricted_path).resolve() - restricted_json = restricted_path / 'restricted.json' - if not restricted_json.is_file(): - logger.error(f'Restricted json {restricted_json} is not present.') - return None - if not valid_o3de_restricted_json(restricted_json): - logger.error(f'Restricted json {restricted_json} is not valid.') - return None - - with restricted_json.open('r') as f: - try: - restricted_json_data = json.load(f) - except Exception as e: - logger.warn(f'{restricted_json} failed to load: {str(e)}') - else: - return restricted_json_data - - return None - - -def get_downloadables() -> dict: - json_data = load_o3de_manifest() - downloadable_data = {} - downloadable_data.update({'engines': []}) - downloadable_data.update({'projects': []}) - downloadable_data.update({'gems': []}) - downloadable_data.update({'templates': []}) - downloadable_data.update({'restricted': []}) - - def recurse_downloadables(repo_uri: str or pathlib.Path) -> None: - cache_folder = get_o3de_cache_folder() - repo_sha256 = hashlib.sha256(repo_uri.encode()) - cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') - if valid_o3de_repo_json(cache_file): - with cache_file.open('r') as s: - try: - repo_json_data = json.load(s) - except Exception as e: - logger.warn(f'{cache_file} failed to load: {str(e)}') - else: - for engine in repo_json_data['engines']: - if engine not in downloadable_data['engines']: - downloadable_data['engines'].append(engine) - - for project in repo_json_data['projects']: - if project not in downloadable_data['projects']: - downloadable_data['projects'].append(project) - - for gem in repo_json_data['gems']: - if gem not in downloadable_data['gems']: - downloadable_data['gems'].append(gem) - - for template in repo_json_data['templates']: - if template not in downloadable_data['templates']: - downloadable_data['templates'].append(template) - - for restricted in repo_json_data['restricted']: - if restricted not in downloadable_data['restricted']: - downloadable_data['restricted'].append(restricted) - - for repo in repo_json_data['repos']: - if repo not in downloadable_data['repos']: - downloadable_data['repos'].append(repo) - - for repo in downloadable_data['repos']: - recurse_downloadables(repo) - - for repo_entry in json_data['repos']: - recurse_downloadables(repo_entry) - return downloadable_data - - -def get_downloadable_engines() -> dict: - downloadable_data = get_downloadables() - return downloadable_data['engines'] - - -def get_downloadable_projects() -> dict: - downloadable_data = get_downloadables() - return downloadable_data['projects'] - - -def get_downloadable_gems() -> dict: - downloadable_data = get_downloadables() - return downloadable_data['gems'] - - -def get_downloadable_templates() -> dict: - downloadable_data = get_downloadables() - return downloadable_data['templates'] - - -def get_downloadable_restricted() -> dict: - downloadable_data = get_downloadables() - return downloadable_data['restricted'] - - -def print_downloadable_engines(verbose: int) -> None: - downloadable_engines = get_downloadable_engines() - for engine_data in downloadable_engines: - print(json.dumps(engine_data, indent=4)) - if verbose > 0: - print_engines_data(downloadable_engines) - - -def print_downloadable_projects(verbose: int) -> None: - downloadable_projects = get_downloadable_projects() - for projects_data in downloadable_projects: - print(json.dumps(projects_data, indent=4)) - if verbose > 0: - print_projects_data(downloadable_projects) - - -def print_downloadable_gems(verbose: int) -> None: - downloadable_gems = get_downloadable_gems() - for gem_data in downloadable_gems: - print(json.dumps(gem_data, indent=4)) - if verbose > 0: - print_gems_data(downloadable_gems) - - -def print_downloadable_templates(verbose: int) -> None: - downloadable_templates = get_downloadable_templates() - for template_data in downloadable_templates: - print(json.dumps(template_data, indent=4)) - if verbose > 0: - print_engines_data(downloadable_templates) - - -def print_downloadable_restricted(verbose: int) -> None: - downloadable_restricted = get_downloadable_restricted() - for restricted_data in downloadable_restricted: - print(json.dumps(restricted_data, indent=4)) - if verbose > 0: - print_engines_data(downloadable_restricted) - - -def print_downloadables(verbose: int) -> None: - downloadable_data = get_downloadables() - print(json.dumps(downloadable_data, indent=4)) - if verbose > 0: - print_engines_data(downloadable_data['engines']) - print_projects_data(downloadable_data['projects']) - print_gems_data(downloadable_data['gems']) - print_templates_data(downloadable_data['templates']) - print_restricted_data(downloadable_data['templates']) - - -def download_engine(engine_name: str, - dest_path: str) -> int: - if not dest_path: - dest_path = get_registered(default_folder='engines') - if not dest_path: - logger.error(f'Destination path not cannot be empty.') - return 1 - - dest_path = pathlib.Path(dest_path).resolve() - dest_path.mkdir(exist_ok=True) - - download_path = get_o3de_download_folder() / 'engines' / engine_name - download_path.mkdir(exist_ok=True) - download_zip_path = download_path / 'engine.zip' - - downloadable_engine_data = get_downloadable(engine_name=engine_name) - if not downloadable_engine_data: - logger.error(f'Downloadable engine {engine_name} not found.') - return 1 - - origin = downloadable_engine_data['origin'] - url = f'{origin}/project.zip' - parsed_uri = urllib.parse.urlparse(url) - - if download_zip_path.is_file(): - logger.warn(f'Project already downloaded to {download_zip_path}.') - elif parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(url) as s: - with download_zip_path.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, download_zip_path) - - if not zipfile.is_zipfile(download_zip_path): - logger.error(f"Engine zip {download_zip_path} is invalid.") - download_zip_path.unlink() - return 1 - - # if the engine.json has a sha256 check it against a sha256 of the zip - try: - sha256A = downloadable_engine_data['sha256'] - except Exception as e: - logger.warn(f'SECURITY WARNING: The advertised engine you downloaded has no "sha256"!!! Be VERY careful!!!' - f' We cannot verify this is the actually the advertised engine!!!') - else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded engine.zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the engine.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - dest_engine_folder = dest_path / engine_name - if dest_engine_folder.is_dir(): - backup_folder(dest_engine_folder) - with zipfile.ZipFile(download_zip_path, 'r') as project_zip: - try: - project_zip.extractall(dest_path) - except Exception as e: - logger.error(f'UnZip exception:{str(e)}') - shutil.rmtree(dest_path) - return 1 - - unzipped_engine_json = dest_engine_folder / 'engine.json' - if not unzipped_engine_json.is_file(): - logger.error(f'Engine json {unzipped_engine_json} is missing.') - return 1 - - if not valid_o3de_engine_json(unzipped_engine_json): - logger.error(f'Engine json {unzipped_engine_json} is invalid.') - return 1 - - # remove the sha256 if present in the advertised downloadable engine.json - # then compare it to the engine.json in the zip, they should now be identical - try: - del downloadable_engine_data['sha256'] - except Exception as e: - pass - - sha256A = hashlib.sha256(json.dumps(downloadable_engine_data, indent=4).encode('utf8')).hexdigest() - with unzipped_engine_json.open('r') as s: - try: - unzipped_engine_json_data = json.load(s) - except Exception as e: - logger.error(f'Failed to read engine json {unzipped_engine_json}. Unable to confirm this' - f' is the same template that was advertised.') - return 1 - sha256B = hashlib.sha256(json.dumps(unzipped_engine_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded engine.json does not match' - f' the advertised engine.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - return 0 - - -def download_project(project_name: str, - dest_path: str or pathlib.Path) -> int: - if not dest_path: - dest_path = get_registered(default_folder='projects') - if not dest_path: - logger.error(f'Destination path not specified and not default projects path.') - return 1 - - dest_path = pathlib.Path(dest_path).resolve() - dest_path.mkdir(exist_ok=True, parents=True) - - download_path = get_o3de_download_folder() / 'projects' / project_name - download_path.mkdir(exist_ok=True, parents=True) - download_zip_path = download_path / 'project.zip' - - downloadable_project_data = get_downloadable(project_name=project_name) - if not downloadable_project_data: - logger.error(f'Downloadable project {project_name} not found.') - return 1 - - origin = downloadable_project_data['origin'] - url = f'{origin}/project.zip' - parsed_uri = urllib.parse.urlparse(url) - - if download_zip_path.is_file(): - logger.warn(f'Project already downloaded to {download_zip_path}.') - elif parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(url) as s: - with download_zip_path.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, download_zip_path) - - if not zipfile.is_zipfile(download_zip_path): - logger.error(f"Project zip {download_zip_path} is invalid.") - download_zip_path.unlink() - return 1 - - # if the project.json has a sha256 check it against a sha256 of the zip - try: - sha256A = downloadable_project_data['sha256'] - except Exception as e: - logger.warn(f'SECURITY WARNING: The advertised project you downloaded has no "sha256"!!! Be VERY careful!!!' - f' We cannot verify this is the actually the advertised project!!!') - else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded project.zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the project.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - dest_project_folder = dest_path / project_name - if dest_project_folder.is_dir(): - backup_folder(dest_project_folder) - with zipfile.ZipFile(download_zip_path, 'r') as project_zip: - try: - project_zip.extractall(dest_project_folder) - except Exception as e: - logger.error(f'UnZip exception:{str(e)}') - shutil.rmtree(dest_path) - return 1 - - unzipped_project_json = dest_project_folder / 'project.json' - if not unzipped_project_json.is_file(): - logger.error(f'Project json {unzipped_project_json} is missing.') - return 1 - - if not valid_o3de_project_json(unzipped_project_json): - logger.error(f'Project json {unzipped_project_json} is invalid.') - return 1 - - # remove the sha256 if present in the advertised downloadable project.json - # then compare it to the project.json in the zip, they should now be identical - try: - del downloadable_project_data['sha256'] - except Exception as e: - pass - - sha256A = hashlib.sha256(json.dumps(downloadable_project_data, indent=4).encode('utf8')).hexdigest() - with unzipped_project_json.open('r') as s: - try: - unzipped_project_json_data = json.load(s) - except Exception as e: - logger.error(f'Failed to read Project json {unzipped_project_json}. Unable to confirm this' - f' is the same project that was advertised.') - return 1 - sha256B = hashlib.sha256(json.dumps(unzipped_project_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded project.json does not match' - f' the advertised project.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - return 0 - - -def download_gem(gem_name: str, - dest_path: str or pathlib.Path) -> int: - if not dest_path: - dest_path = get_registered(default_folder='gems') - if not dest_path: - logger.error(f'Destination path not cannot be empty.') - return 1 - - dest_path = pathlib.Path(dest_path).resolve() - dest_path.mkdir(exist_ok=True, parents=True) - - download_path = get_o3de_download_folder() / 'gems' / gem_name - download_path.mkdir(exist_ok=True, parents=True) - download_zip_path = download_path / 'gem.zip' - - downloadable_gem_data = get_downloadable(gem_name=gem_name) - if not downloadable_gem_data: - logger.error(f'Downloadable gem {gem_name} not found.') - return 1 - - origin = downloadable_gem_data['origin'] - url = f'{origin}/gem.zip' - parsed_uri = urllib.parse.urlparse(url) - - if download_zip_path.is_file(): - logger.warn(f'Project already downloaded to {download_zip_path}.') - elif parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(url) as s: - with download_zip_path.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, download_zip_path) - - if not zipfile.is_zipfile(download_zip_path): - logger.error(f"Gem zip {download_zip_path} is invalid.") - download_zip_path.unlink() - return 1 - - # if the gem.json has a sha256 check it against a sha256 of the zip - try: - sha256A = downloadable_gem_data['sha256'] - except Exception as e: - logger.warn(f'SECURITY WARNING: The advertised gem you downloaded has no "sha256"!!! Be VERY careful!!!' - f' We cannot verify this is the actually the advertised gem!!!') - else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded gem.zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the gem.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - dest_gem_folder = dest_path / gem_name - if dest_gem_folder.is_dir(): - backup_folder(dest_gem_folder) - with zipfile.ZipFile(download_zip_path, 'r') as gem_zip: - try: - gem_zip.extractall(dest_path) - except Exception as e: - logger.error(f'UnZip exception:{str(e)}') - shutil.rmtree(dest_path) - return 1 - - unzipped_gem_json = dest_gem_folder / 'gem.json' - if not unzipped_gem_json.is_file(): - logger.error(f'Engine json {unzipped_gem_json} is missing.') - return 1 - - if not valid_o3de_engine_json(unzipped_gem_json): - logger.error(f'Engine json {unzipped_gem_json} is invalid.') - return 1 - - # remove the sha256 if present in the advertised downloadable gem.json - # then compare it to the gem.json in the zip, they should now be identical - try: - del downloadable_gem_data['sha256'] - except Exception as e: - pass - - sha256A = hashlib.sha256(json.dumps(downloadable_gem_data, indent=4).encode('utf8')).hexdigest() - with unzipped_gem_json.open('r') as s: - try: - unzipped_gem_json_data = json.load(s) - except Exception as e: - logger.error(f'Failed to read gem json {unzipped_gem_json}. Unable to confirm this' - f' is the same gem that was advertised.') - return 1 - sha256B = hashlib.sha256(json.dumps(unzipped_gem_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded gem.json does not match' - f' the advertised gem.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - return 0 - - -def download_template(template_name: str, - dest_path: str or pathlib.Path) -> int: - if not dest_path: - dest_path = get_registered(default_folder='templates') - if not dest_path: - logger.error(f'Destination path not cannot be empty.') - return 1 - - dest_path = pathlib.Path(dest_path).resolve() - dest_path.mkdir(exist_ok=True, parents=True) - - download_path = get_o3de_download_folder() / 'templates' / template_name - download_path.mkdir(exist_ok=True, parents=True) - download_zip_path = download_path / 'template.zip' - - downloadable_template_data = get_downloadable(template_name=template_name) - if not downloadable_template_data: - logger.error(f'Downloadable template {template_name} not found.') - return 1 - - origin = downloadable_template_data['origin'] - url = f'{origin}/project.zip' - parsed_uri = urllib.parse.urlparse(url) - - result = 0 - - if download_zip_path.is_file(): - logger.warn(f'Project already downloaded to {download_zip_path}.') - elif parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(url) as s: - with download_zip_path.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, download_zip_path) - - if not zipfile.is_zipfile(download_zip_path): - logger.error(f"Template zip {download_zip_path} is invalid.") - download_zip_path.unlink() - return 1 - - # if the template.json has a sha256 check it against a sha256 of the zip - try: - sha256A = downloadable_template_data['sha256'] - except Exception as e: - logger.warn(f'SECURITY WARNING: The advertised template you downloaded has no "sha256"!!! Be VERY careful!!!' - f' We cannot verify this is the actually the advertised template!!!') - else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded template.zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the template.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - dest_template_folder = dest_path / template_name - if dest_template_folder.is_dir(): - backup_folder(dest_template_folder) - with zipfile.ZipFile(download_zip_path, 'r') as project_zip: - try: - project_zip.extractall(dest_path) - except Exception as e: - logger.error(f'UnZip exception:{str(e)}') - shutil.rmtree(dest_path) - return 1 - - unzipped_template_json = dest_template_folder / 'template.json' - if not unzipped_template_json.is_file(): - logger.error(f'Template json {unzipped_template_json} is missing.') - return 1 - - if not valid_o3de_engine_json(unzipped_template_json): - logger.error(f'Template json {unzipped_template_json} is invalid.') - return 1 - - # remove the sha256 if present in the advertised downloadable template.json - # then compare it to the template.json in the zip, they should now be identical - try: - del downloadable_template_data['sha256'] - except Exception as e: - pass - - sha256A = hashlib.sha256(json.dumps(downloadable_template_data, indent=4).encode('utf8')).hexdigest() - with unzipped_template_json.open('r') as s: - try: - unzipped_template_json_data = json.load(s) - except Exception as e: - logger.error(f'Failed to read Template json {unzipped_template_json}. Unable to confirm this' - f' is the same template that was advertised.') - return 1 - sha256B = hashlib.sha256(json.dumps(unzipped_template_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded template.json does not match' - f' the advertised template.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - return 0 - - -def download_restricted(restricted_name: str, - dest_path: str or pathlib.Path) -> int: - if not dest_path: - dest_path = get_registered(default_folder='restricted') - if not dest_path: - logger.error(f'Destination path not cannot be empty.') - return 1 - - dest_path = pathlib.Path(dest_path).resolve() - dest_path.mkdir(exist_ok=True, parents=True) - - download_path = get_o3de_download_folder() / 'restricted' / restricted_name - download_path.mkdir(exist_ok=True, parents=True) - download_zip_path = download_path / 'restricted.zip' - - downloadable_restricted_data = get_downloadable(restricted_name=restricted_name) - if not downloadable_restricted_data: - logger.error(f'Downloadable Restricted {restricted_name} not found.') - return 1 - - origin = downloadable_restricted_data['origin'] - url = f'{origin}/restricted.zip' - parsed_uri = urllib.parse.urlparse(url) - - if download_zip_path.is_file(): - logger.warn(f'Restricted already downloaded to {download_zip_path}.') - elif parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(url) as s: - with download_zip_path.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, download_zip_path) - - if not zipfile.is_zipfile(download_zip_path): - logger.error(f"Restricted zip {download_zip_path} is invalid.") - download_zip_path.unlink() - return 1 - - # if the restricted.json has a sha256 check it against a sha256 of the zip - try: - sha256A = downloadable_restricted_data['sha256'] - except Exception as e: - logger.warn(f'SECURITY WARNING: The advertised restricted you downloaded has no "sha256"!!! Be VERY careful!!!' - f' We cannot verify this is the actually the advertised restricted!!!') - else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded restricted.zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the restricted.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - dest_restricted_folder = dest_path / restricted_name - if dest_restricted_folder.is_dir(): - backup_folder(dest_restricted_folder) - with zipfile.ZipFile(download_zip_path, 'r') as project_zip: - try: - project_zip.extractall(dest_path) - except Exception as e: - logger.error(f'UnZip exception:{str(e)}') - shutil.rmtree(dest_path) - return 1 - - unzipped_restricted_json = dest_restricted_folder / 'restricted.json' - if not unzipped_restricted_json.is_file(): - logger.error(f'Restricted json {unzipped_restricted_json} is missing.') - return 1 - - if not valid_o3de_engine_json(unzipped_restricted_json): - logger.error(f'Restricted json {unzipped_restricted_json} is invalid.') - return 1 - - # remove the sha256 if present in the advertised downloadable restricted.json - # then compare it to the restricted.json in the zip, they should now be identical - try: - del downloadable_restricted_data['sha256'] - except Exception as e: - pass - - sha256A = hashlib.sha256(json.dumps(downloadable_restricted_data, indent=4).encode('utf8')).hexdigest() - with unzipped_restricted_json.open('r') as s: - try: - unzipped_restricted_json_data = json.load(s) - except Exception as e: - logger.error( - f'Failed to read Restricted json {unzipped_restricted_json}. Unable to confirm this' - f' is the same restricted that was advertised.') - return 1 - sha256B = hashlib.sha256( - json.dumps(unzipped_restricted_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded restricted.json does not match' - f' the advertised restricted.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - return 0 - - -def add_gem_dependency(cmake_file: str or pathlib.Path, - gem_target: str) -> int: - """ - adds a gem dependency to a cmake file - :param cmake_file: path to the cmake file - :param gem_target: name of the cmake target - :return: 0 for success or non 0 failure code - """ - if not os.path.isfile(cmake_file): - logger.error(f'Failed to locate cmake file {cmake_file}') - return 1 - - # on a line by basis, see if there already is Gem::{gem_name} - # find the first occurrence of a gem, copy its formatting and replace - # the gem name with the new one and append it - # if the gem is already present fail - t_data = [] - added = False - with open(cmake_file, 'r') as s: - for line in s: - if f'Gem::{gem_target}' in line: - logger.warning(f'{gem_target} is already a gem dependency.') - return 0 - if not added and r'Gem::' in line: - new_gem = ' ' * line.find(r'Gem::') + f'Gem::{gem_target}\n' - t_data.append(new_gem) - added = True - t_data.append(line) - - # if we didn't add it the set gem dependencies could be empty so - # add a new gem, if empty the correct format is 1 tab=4spaces - if not added: - index = 0 - for line in t_data: - index = index + 1 - if r'set(GEM_DEPENDENCIES' in line: - t_data.insert(index, f' Gem::{gem_target}\n') - added = True - break - - # if we didn't add it then it's not here, add a whole new one - if not added: - t_data.append('\n') - t_data.append('set(GEM_DEPENDENCIES\n') - t_data.append(f' Gem::{gem_target}\n') - t_data.append(')\n') - - # write the cmake - os.unlink(cmake_file) - with open(cmake_file, 'w') as s: - s.writelines(t_data) - - return 0 - - -def get_project_runtime_gem_targets(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) - - -def get_project_tool_gem_targets(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) - - -def get_project_server_gem_targets(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) - - -def get_project_gem_targets(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - runtime_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) - tool_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) - server_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) - return runtime_gems.union(tool_gems.union(server_gems)) - - -def get_gem_targets_from_cmake_file(cmake_file: str or pathlib.Path) -> set: - """ - Gets a list of declared gem targets dependencies of a cmake file - :param cmake_file: path to the cmake file - :return: set of gem targets found - """ - cmake_file = pathlib.Path(cmake_file).resolve() - - if not cmake_file.is_file(): - logger.error(f'Failed to locate cmake file {cmake_file}') - return set() - - gem_target_set = set() - with cmake_file.open('r') as s: - for line in s: - gem_name = line.split('Gem::') - if len(gem_name) > 1: - # Only take the name as everything leading up to the first '.' if found - # Gem naming conventions will have GemName.Editor, GemName.Server, and GemName - # as different targets of the GemName Gem - gem_target_set.add(gem_name[1].replace('\n', '')) - return gem_target_set - - -def get_project_runtime_gem_names(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) - - -def get_project_tool_gem_names(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) - - -def get_project_server_gem_names(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) - - -def get_project_gem_names(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - runtime_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) - tool_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) - server_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) - return runtime_gem_names.union(tool_gem_names.union(server_gem_names)) - - -def get_gem_names_from_cmake_file(cmake_file: str or pathlib.Path) -> set: - """ - Gets a list of declared gem dependencies of a cmake file - :param cmake_file: path to the cmake file - :return: set of gems found - """ - cmake_file = pathlib.Path(cmake_file).resolve() - - if not cmake_file.is_file(): - logger.error(f'Failed to locate cmake file {cmake_file}') - return set() - - gem_set = set() - with cmake_file.open('r') as s: - for line in s: - gem_name = line.split('Gem::') - if len(gem_name) > 1: - # Only take the name as everything leading up to the first '.' if found - # Gem naming conventions will have GemName.Editor, GemName.Server, and GemName - # as different targets of the GemName Gem - gem_set.add(gem_name[1].split('.')[0].replace('\n', '')) - return gem_set - - -def get_project_runtime_gem_paths(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - gem_names = get_project_runtime_gem_names(project_path, platform) - gem_paths = set() - for gem_name in gem_names: - gem_paths.add(get_registered(gem_name=gem_name)) - return gem_paths - - -def get_project_tool_gem_paths(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - gem_names = get_project_tool_gem_names(project_path, platform) - gem_paths = set() - for gem_name in gem_names: - gem_paths.add(get_registered(gem_name=gem_name)) - return gem_paths - - -def get_project_server_gem_paths(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - gem_names = get_project_server_gem_names(project_path, platform) - gem_paths = set() - for gem_name in gem_names: - gem_paths.add(get_registered(gem_name=gem_name)) - return gem_paths - - -def get_project_gem_paths(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - gem_names = get_project_gem_names(project_path, platform) - gem_paths = set() - for gem_name in gem_names: - gem_paths.add(get_registered(gem_name=gem_name)) - return gem_paths - - -def remove_gem_dependency(cmake_file: str or pathlib.Path, - gem_target: str) -> int: - """ - removes a gem dependency from a cmake file - :param cmake_file: path to the cmake file - :param gem_target: cmake target name - :return: 0 for success or non 0 failure code - """ - if not os.path.isfile(cmake_file): - logger.error(f'Failed to locate cmake file {cmake_file}') - return 1 - - # on a line by basis, remove any line with Gem::{gem_name} - t_data = [] - # Remove the gem from the cmake_dependencies file by skipping the gem name entry - removed = False - with open(cmake_file, 'r') as s: - for line in s: - if f'Gem::{gem_target}' in line: - removed = True - else: - t_data.append(line) - - if not removed: - logger.error(f'Failed to remove Gem::{gem_target} from cmake file {cmake_file}') - return 1 - - # write the cmake - os.unlink(cmake_file) - with open(cmake_file, 'w') as s: - s.writelines(t_data) - - return 0 - - -def get_project_templates(): # temporary until we have a better way to do this... maybe template_type element - project_templates = [] - for template in get_all_templates(): - if 'Project' in template: - project_templates.append(template) - return project_templates - - -def get_gem_templates(): # temporary until we have a better way to do this... maybe template_type element - gem_templates = [] - for template in get_all_templates(): - if 'Gem' in template: - gem_templates.append(template) - return gem_templates - - -def get_generic_templates(): # temporary until we have a better way to do this... maybe template_type element - generic_templates = [] - for template in get_all_templates(): - if 'Project' not in template and 'Gem' not in template: - generic_templates.append(template) - return generic_templates - - -def get_dependencies_cmake_file(project_name: str = None, - project_path: str or pathlib.Path = None, - dependency_type: str = 'runtime', - platform: str = 'Common') -> str or None: - """ - get the standard cmake file name for a particular type of dependency - :param gem_name: name of the gem, resolves gem_path - :param gem_path: path of the gem - :return: list of gem targets - """ - if not project_name and not project_path: - logger.error(f'Must supply either a Project Name or Project Path.') - return None - - if project_name and not project_path: - project_path = get_registered(project_name=project_name) - - project_path = pathlib.Path(project_path).resolve() - - if platform == 'Common': - dependencies_file = f'{dependency_type}_dependencies.cmake' - dependencies_file_path = project_path / 'Gem/Code' / dependencies_file - if dependencies_file_path.is_file(): - return dependencies_file_path - return project_path / 'Code' / dependencies_file - else: - dependencies_file = f'{platform.lower()}_{dependency_type}_dependencies.cmake' - dependencies_file_path = project_path / 'Gem/Code/Platform' / platform / dependencies_file - if dependencies_file_path.is_file(): - return dependencies_file_path - return project_path / 'Code/Platform' / platform / dependencies_file - - -def get_all_gem_targets() -> list: - modules = [] - for gem_path in get_all_gems(): - this_gems_targets = get_gem_targets(gem_path=gem_path) - modules.extend(this_gems_targets) - return modules - - -def get_gem_targets(gem_name: str = None, - gem_path: str or pathlib.Path = None) -> list: - """ - Finds gem targets in a gem - :param gem_name: name of the gem, resolves gem_path - :param gem_path: path of the gem - :return: list of gem targets - """ - if not gem_name and not gem_path: - return [] - - if gem_name and not gem_path: - gem_path = get_registered(gem_name=gem_name) - - if not gem_path: - return [] - - gem_path = pathlib.Path(gem_path).resolve() - gem_json = gem_path / 'gem.json' - if not valid_o3de_gem_json(gem_json): - return [] - - module_identifiers = [ - 'MODULE', - 'GEM_MODULE', - '${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE}' - ] - modules = [] - for root, dirs, files in os.walk(gem_path): - for file in files: - if file == 'CMakeLists.txt': - with open(os.path.join(root, file), 'r') as s: - for line in s: - trimmed = line.lstrip() - if trimmed.startswith('NAME '): - trimmed = trimmed.rstrip(' \n') - split_trimmed = trimmed.split(' ') - if len(split_trimmed) == 3 and split_trimmed[2] in module_identifiers: - modules.append(split_trimmed[1]) - return modules - - -def add_external_subdirectory(external_subdir: str or pathlib.Path, - engine_path: str or pathlib.Path = None, - suppress_errors: bool = False) -> int: - """ - add external subdirectory to a cmake - :param external_subdir: external subdirectory to add to cmake - :param engine_path: optional engine path, defaults to this engine - :param suppress_errors: optional silence errors - :return: 0 for success or non 0 failure code - """ - external_subdir = pathlib.Path(external_subdir).resolve() - if not external_subdir.is_dir(): - if not suppress_errors: - logger.error(f'Add External Subdirectory Failed: {external_subdir} does not exist.') - return 1 - - external_subdir_cmake = external_subdir / 'CMakeLists.txt' - if not external_subdir_cmake.is_file(): - if not suppress_errors: - logger.error(f'Add External Subdirectory Failed: {external_subdir} does not contain a CMakeLists.txt.') - return 1 - - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data, engine_path) - if not engine_object: - if not suppress_errors: - logger.error(f'Add External Subdirectory Failed: {engine_path} not registered.') - return 1 - - while external_subdir.as_posix() in engine_object['external_subdirectories']: - engine_object['external_subdirectories'].remove(external_subdir.as_posix()) - - def parse_cmake_file(cmake: str or pathlib.Path, - files: set): - cmake_path = pathlib.Path(cmake).resolve() - cmake_file = cmake_path - if cmake_path.is_dir(): - files.add(cmake_path) - cmake_file = cmake_path / 'CMakeLists.txt' - elif cmake_path.is_file(): - cmake_path = cmake_path.parent - else: - return - - with cmake_file.open('r') as s: - lines = s.readlines() - for line in lines: - line = line.strip() - start = line.find('include(') - if start == 0: - end = line.find(')', start) - if end > start + len('include('): - try: - include_cmake_file = pathlib.Path(engine_path / line[start + len('include('): end]).resolve() - except Exception as e: - pass - else: - parse_cmake_file(include_cmake_file, files) - else: - start = line.find('add_subdirectory(') - if start == 0: - end = line.find(')', start) - if end > start + len('add_subdirectory('): - try: - include_cmake_file = pathlib.Path( - cmake_path / line[start + len('add_subdirectory('): end]).resolve() - except Exception as e: - pass - else: - parse_cmake_file(include_cmake_file, files) - - cmake_files = set() - parse_cmake_file(engine_path, cmake_files) - for external in engine_object["external_subdirectories"]: - parse_cmake_file(external, cmake_files) - - if external_subdir in cmake_files: - save_o3de_manifest(json_data) - if not suppress_errors: - logger.error(f'External subdirectory {external_subdir.as_posix()} already included by add_subdirectory().') - return 1 - - engine_object['external_subdirectories'].insert(0, external_subdir.as_posix()) - engine_object['external_subdirectories'] = sorted(engine_object['external_subdirectories']) - - save_o3de_manifest(json_data) - - return 0 - - -def remove_external_subdirectory(external_subdir: str or pathlib.Path, - engine_path: str or pathlib.Path = None) -> int: - """ - remove external subdirectory from cmake - :param external_subdir: external subdirectory to add to cmake - :param engine_path: optional engine path, defaults to this engine - :return: 0 for success or non 0 failure code - """ - json_data = load_o3de_manifest() - engine_object = find_engine_data(json_data, engine_path) - if not engine_object: - logger.error(f'Remove External Subdirectory Failed: {engine_path} not registered.') - return 1 - - external_subdir = pathlib.Path(external_subdir).resolve() - while external_subdir.as_posix() in engine_object['external_subdirectories']: - engine_object['external_subdirectories'].remove(external_subdir.as_posix()) - - save_o3de_manifest(json_data) - - return 0 - - -def add_gem_to_cmake(gem_name: str = None, - gem_path: str or pathlib.Path = None, - engine_name: str = None, - engine_path: str or pathlib.Path = None, - suppress_errors: bool = False) -> int: - """ - add a gem to a cmake as an external subdirectory for an engine - :param gem_name: name of the gem to add to cmake - :param gem_path: the path of the gem to add to cmake - :param engine_name: name of the engine to add to cmake - :param engine_path: the path of the engine to add external subdirectory to, default to this engine - :param suppress_errors: optional silence errors - :return: 0 for success or non 0 failure code - """ - if not gem_name and not gem_path: - if not suppress_errors: - logger.error('Must specify either a Gem name or Gem Path.') - return 1 - - if gem_name and not gem_path: - gem_path = get_registered(gem_name=gem_name) - - if not gem_path: - if not suppress_errors: - logger.error(f'Gem Path {gem_path} has not been registered.') - return 1 - - gem_path = pathlib.Path(gem_path).resolve() - gem_json = gem_path / 'gem.json' - if not gem_json.is_file(): - if not suppress_errors: - logger.error(f'Gem json {gem_json} is not present.') - return 1 - if not valid_o3de_gem_json(gem_json): - if not suppress_errors: - logger.error(f'Gem json {gem_json} is not valid.') - return 1 - - if not engine_name and not engine_path: - engine_path = get_this_engine_path() - - if engine_name and not engine_path: - engine_path = get_registered(engine_name=engine_name) - - if not engine_path: - if not suppress_errors: - logger.error(f'Engine Path {engine_path} has not been registered.') - return 1 - - engine_json = engine_path / 'engine.json' - if not engine_json.is_file(): - if not suppress_errors: - logger.error(f'Engine json {engine_json} is not present.') - return 1 - if not valid_o3de_engine_json(engine_json): - if not suppress_errors: - logger.error(f'Engine json {engine_json} is not valid.') - return 1 - - return add_external_subdirectory(external_subdir=gem_path, engine_path=engine_path, suppress_errors=suppress_errors) - - -def remove_gem_from_cmake(gem_name: str = None, - gem_path: str or pathlib.Path = None, - engine_name: str = None, - engine_path: str or pathlib.Path = None) -> int: - """ - remove a gem to cmake as an external subdirectory - :param gem_name: name of the gem to remove from cmake - :param gem_path: the path of the gem to add to cmake - :param engine_name: optional name of the engine to remove from cmake - :param engine_path: the path of the engine to remove external subdirectory from, defaults to this engine - :return: 0 for success or non 0 failure code - """ - if not gem_name and not gem_path: - logger.error('Must specify either a Gem name or Gem Path.') - return 1 - - if gem_name and not gem_path: - gem_path = get_registered(gem_name=gem_name) - - if not gem_path: - logger.error(f'Gem Path {gem_path} has not been registered.') - return 1 - - if not engine_name and not engine_path: - engine_path = get_this_engine_path() - - if engine_name and not engine_path: - engine_path = get_registered(engine_name=engine_name) - - if not engine_path: - logger.error(f'Engine Path {engine_path} is not registered.') - return 1 - - return remove_external_subdirectory(external_subdir=gem_path, engine_path=engine_path) - - -def add_gem_to_project(gem_name: str = None, - gem_path: str or pathlib.Path = None, - gem_target: str = None, - project_name: str = None, - project_path: str or pathlib.Path = None, - dependencies_file: str or pathlib.Path = None, - runtime_dependency: bool = False, - tool_dependency: bool = False, - server_dependency: bool = False, - platforms: str = 'Common', - add_to_cmake: bool = True) -> int: - """ - add a gem to a project - :param gem_name: name of the gem to add - :param gem_path: path to the gem to add - :param gem_target: the name of the cmake gem module - :param project_name: name of to the project to add the gem to - :param project_path: path to the project to add the gem to - :param dependencies_file: if this dependency goes/is in a specific file - :param runtime_dependency: bool to specify this is a runtime gem for the game - :param tool_dependency: bool to specify this is a tool gem for the editor - :param server_dependency: bool to specify this is a server gem for the server - :param platforms: str to specify common or which specific platforms - :param add_to_cmake: bool to specify that this gem should be added to cmake - :return: 0 for success or non 0 failure code - """ - # we need either a project name or path - if not project_name and not project_path: - logger.error(f'Must either specify a Project path or Project Name.') - return 1 - - # if project name resolve it into a path - if project_name and not project_path: - project_path = get_registered(project_name=project_name) - project_path = pathlib.Path(project_path).resolve() - if not project_path.is_dir(): - logger.error(f'Project path {project_path} is not a folder.') - return 1 - - # get the engine name this project is associated with - # and resolve that engines path - project_json = project_path / 'project.json' - if not valid_o3de_project_json(project_json): - logger.error(f'Project json {project_json} is not valid.') - return 1 - with project_json.open('r') as s: - try: - project_json_data = json.load(s) - except Exception as e: - logger.error(f'Error loading Project json {project_json}: {str(e)}') - return 1 - else: - try: - engine_name = project_json_data['engine'] - except Exception as e: - logger.error(f'Project json {project_json} "engine" not found: {str(e)}') - return 1 - else: - engine_path = get_registered(engine_name=engine_name) - if not engine_path: - logger.error(f'Engine {engine_name} is not registered.') - return 1 - - # we need either a gem name or path - if not gem_name and not gem_path: - logger.error(f'Must either specify a Gem path or Gem Name.') - return 1 - - # if gem name resolve it into a path - if gem_name and not gem_path: - gem_path = get_registered(gem_name=gem_name) - gem_path = pathlib.Path(gem_path).resolve() - # make sure this gem already exists if we're adding. We can always remove a gem. - if not gem_path.is_dir(): - logger.error(f'Gem Path {gem_path} does not exist.') - return 1 - - # if add to cmake, make sure the gem.json exists and valid before we proceed - if add_to_cmake: - gem_json = gem_path / 'gem.json' - if not gem_json.is_file(): - logger.error(f'Gem json {gem_json} is not present.') - return 1 - if not valid_o3de_gem_json(gem_json): - logger.error(f'Gem json {gem_json} is not valid.') - return 1 - - # find all available modules in this gem_path - modules = get_gem_targets(gem_path=gem_path) - if len(modules) == 0: - logger.error(f'No gem modules found under {gem_path}.') - return 1 - - # if the gem has no modules and the user has specified a target fail - if gem_target and not modules: - logger.error(f'Gem has no targets, but gem target {gem_target} was specified.') - return 1 - - # if the gem target is not in the modules - if gem_target not in modules: - logger.error(f'Gem target not in gem modules: {modules}') - return 1 - - if gem_target: - # if the user has not specified either we will assume they meant the most common which is runtime - if not runtime_dependency and not tool_dependency and not server_dependency and not dependencies_file: - logger.warning("Dependency type not specified: Assuming '--runtime-dependency'") - runtime_dependency = True - - ret_val = 0 - - # if the user has specified the dependencies file then ignore the runtime_dependency and tool_dependency flags - if dependencies_file: - dependencies_file = pathlib.Path(dependencies_file).resolve() - # make sure this is a project has a dependencies_file - if not dependencies_file.is_file(): - logger.error(f'Dependencies file {dependencies_file} is not present.') - return 1 - # add the dependency - ret_val = add_gem_dependency(dependencies_file, gem_target) - - else: - if ',' in platforms: - platforms = platforms.split(',') - else: - platforms = [platforms] - for platform in platforms: - if runtime_dependency: - # make sure this is a project has a runtime_dependencies.cmake file - project_runtime_dependencies_file = pathlib.Path( - get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)).resolve() - if not project_runtime_dependencies_file.is_file(): - logger.error(f'Runtime dependencies file {project_runtime_dependencies_file} is not present.') - return 1 - # add the dependency - ret_val = add_gem_dependency(project_runtime_dependencies_file, gem_target) - - if (ret_val == 0) and tool_dependency: - # make sure this is a project has a tool_dependencies.cmake file - project_tool_dependencies_file = pathlib.Path( - get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)).resolve() - if not project_tool_dependencies_file.is_file(): - logger.error(f'Tool dependencies file {project_tool_dependencies_file} is not present.') - return 1 - # add the dependency - ret_val = add_gem_dependency(project_tool_dependencies_file, gem_target) - - if (ret_val == 0) and server_dependency: - # make sure this is a project has a tool_dependencies.cmake file - project_server_dependencies_file = pathlib.Path( - get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)).resolve() - if not project_server_dependencies_file.is_file(): - logger.error(f'Server dependencies file {project_server_dependencies_file} is not present.') - return 1 - # add the dependency - ret_val = add_gem_dependency(project_server_dependencies_file, gem_target) - - if not ret_val and add_to_cmake: - ret_val = add_gem_to_cmake(gem_path=gem_path, engine_path=engine_path) - - return ret_val - - -def remove_gem_from_project(gem_name: str = None, - gem_path: str or pathlib.Path = None, - gem_target: str = None, - project_name: str = None, - project_path: str or pathlib.Path = None, - dependencies_file: str or pathlib.Path = None, - runtime_dependency: bool = False, - tool_dependency: bool = False, - server_dependency: bool = False, - platforms: str = 'Common', - remove_from_cmake: bool = False) -> int: - """ - remove a gem from a project - :param gem_name: name of the gem to add - :param gem_path: path to the gem to add - :param gem_target: the name of teh cmake gem module - :param project_name: name of the project to add the gem to - :param project_path: path to the project to add the gem to - :param dependencies_file: if this dependency goes/is in a specific file - :param runtime_dependency: bool to specify this is a runtime gem for the game - :param tool_dependency: bool to specify this is a tool gem for the editor - :param server_dependency: bool to specify this is a server gem for the server - :param platforms: str to specify common or which specific platforms - :param remove_from_cmake: bool to specify that this gem should be removed from cmake - :return: 0 for success or non 0 failure code - """ - - # we need either a project name or path - if not project_name and not project_path: - logger.error(f'Must either specify a Project path or Project Name.') - return 1 - - # if project name resolve it into a path - if project_name and not project_path: - project_path = get_registered(project_name=project_name) - project_path = pathlib.Path(project_path).resolve() - if not project_path.is_dir(): - logger.error(f'Project path {project_path} is not a folder.') - return 1 - - # We need either a gem name or path - if not gem_name and not gem_path: - logger.error(f'Must either specify a Gem path or Gem Name.') - return 1 - - # if gem name resolve it into a path - if gem_name and not gem_path: - gem_path = get_registered(gem_name=gem_name) - gem_path = pathlib.Path(gem_path).resolve() - # make sure this gem already exists if we're adding. We can always remove a gem. - if not gem_path.is_dir(): - logger.error(f'Gem Path {gem_path} does not exist.') - return 1 - - # find all available modules in this gem_path - modules = get_gem_targets(gem_path=gem_path) - if len(modules) == 0: - logger.error(f'No gem modules found.') - return 1 - - # if the user has not set a specific gem target remove all of them - - # if gem target not specified, see if there is only 1 module - if not gem_target: - if len(modules) == 1: - gem_target = modules[0] - else: - logger.error(f'Gem target not specified: {modules}') - return 1 - elif gem_target not in modules: - logger.error(f'Gem target not in gem modules: {modules}') - return 1 - - # if the user has not specified either we will assume they meant the most common which is runtime - if not runtime_dependency and not tool_dependency and not server_dependency and not dependencies_file: - logger.warning("Dependency type not specified: Assuming '--runtime-dependency'") - runtime_dependency = True - - # when removing we will try to do as much as possible even with failures so ret_val will be the last error code - ret_val = 0 - - # if the user has specified the dependencies file then ignore the runtime_dependency and tool_dependency flags - if dependencies_file: - dependencies_file = pathlib.Path(dependencies_file).resolve() - # make sure this is a project has a dependencies_file - if not dependencies_file.is_file(): - logger.error(f'Dependencies file {dependencies_file} is not present.') - return 1 - # remove the dependency - error_code = remove_gem_dependency(dependencies_file, gem_target) - if error_code: - ret_val = error_code - else: - if ',' in platforms: - platforms = platforms.split(',') - else: - platforms = [platforms] - for platform in platforms: - if runtime_dependency: - # make sure this is a project has a runtime_dependencies.cmake file - project_runtime_dependencies_file = pathlib.Path( - get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)).resolve() - if not project_runtime_dependencies_file.is_file(): - logger.error(f'Runtime dependencies file {project_runtime_dependencies_file} is not present.') - else: - # remove the dependency - error_code = remove_gem_dependency(project_runtime_dependencies_file, gem_target) - if error_code: - ret_val = error_code - - if tool_dependency: - # make sure this is a project has a tool_dependencies.cmake file - project_tool_dependencies_file = pathlib.Path( - get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)).resolve() - if not project_tool_dependencies_file.is_file(): - logger.error(f'Tool dependencies file {project_tool_dependencies_file} is not present.') - else: - # remove the dependency - error_code = remove_gem_dependency(project_tool_dependencies_file, gem_target) - if error_code: - ret_val = error_code - - if server_dependency: - # make sure this is a project has a tool_dependencies.cmake file - project_server_dependencies_file = pathlib.Path( - get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)).resolve() - if not project_server_dependencies_file.is_file(): - logger.error(f'Server dependencies file {project_server_dependencies_file} is not present.') - else: - # remove the dependency - error_code = remove_gem_dependency(project_server_dependencies_file, gem_target) - if error_code: - ret_val = error_code - - if remove_from_cmake: - error_code = remove_gem_from_cmake(gem_path=gem_path) - if error_code: - ret_val = error_code - - return ret_val - - -def sha256(file_path: str or pathlib.Path, - json_path: str or pathlib.Path = None) -> int: - if not file_path: - logger.error(f'File path cannot be empty.') - return 1 - file_path = pathlib.Path(file_path).resolve() - if not file_path.is_file(): - logger.error(f'File path {file_path} does not exist.') - return 1 - - if json_path: - json_path = pathlib.Path(json_path).resolve() - if not json_path.is_file(): - logger.error(f'Json path {json_path} does not exist.') - return 1 - - sha256 = hashlib.sha256(file_path.open('rb').read()).hexdigest() - - if json_path: - with json_path.open('r') as s: - try: - json_data = json.load(s) - except Exception as e: - logger.error(f'Failed to read Json path {json_path}: {str(e)}') - return 1 - json_data.update({"sha256": sha256}) - backup_file(json_path) - with json_path.open('w') as s: - try: - s.write(json.dumps(json_data, indent=4)) - except Exception as e: - logger.error(f'Failed to write Json path {json_path}: {str(e)}') - return 1 - else: - print(sha256) - return 0 - - -def _run_get_registered(args: argparse) -> str or pathlib.Path: - if args.override_home_folder: - global override_home_folder - override_home_folder = args.override_home_folder - - return get_registered(args.engine_name, - args.project_name, - args.gem_name, - args.template_name, - args.default_folder, - args.repo_name, - args.restricted_name) - - -def _run_register_show(args: argparse) -> int: - if args.override_home_folder: - global override_home_folder - override_home_folder = args.override_home_folder - - if args.this_engine: - print_this_engine(args.verbose) - return 0 - - elif args.engines: - print_engines(args.verbose) - return 0 - elif args.projects: - print_projects(args.verbose) - return 0 - elif args.gems: - print_gems(args.verbose) - return 0 - elif args.templates: - print_templates(args.verbose) - return 0 - elif args.repos: - register_show_repos(args.verbose) - return 0 - elif args.restricted: - print_restricted(args.verbose) - return 0 - - elif args.engine_projects: - print_engine_projects(args.verbose) - return 0 - elif args.engine_gems: - print_engine_gems(args.verbose) - return 0 - elif args.engine_templates: - print_engine_templates(args.verbose) - return 0 - elif args.engine_restricted: - print_engine_restricted(args.verbose) - return 0 - elif args.external_subdirectories: - print_external_subdirectories(args.verbose) - return 0 - - elif args.all_projects: - print_all_projects(args.verbose) - return 0 - elif args.all_gems: - print_all_gems(args.verbose) - return 0 - elif args.all_templates: - print_all_templates(args.verbose) - return 0 - elif args.all_restricted: - print_all_restricted(args.verbose) - return 0 - - elif args.downloadables: - print_downloadables(args.verbose) - return 0 - if args.downloadable_engines: - print_downloadable_engines(args.verbose) - return 0 - elif args.downloadable_projects: - print_downloadable_projects(args.verbose) - return 0 - elif args.downloadable_gems: - print_downloadable_gems(args.verbose) - return 0 - elif args.downloadable_templates: - print_downloadable_templates(args.verbose) - return 0 - else: - register_show(args.verbose) - return 0 - - -def _run_download(args: argparse) -> int: - if args.override_home_folder: - global override_home_folder - override_home_folder = args.override_home_folder - - if args.engine_name: - return download_engine(args.engine_name, - args.dest_path) - elif args.project_name: - return download_project(args.project_name, - args.dest_path) - elif args.gem_nanme: - return download_gem(args.gem_name, - args.dest_path) - elif args.template_name: - return download_template(args.template_name, - args.dest_path) - - -def _run_register(args: argparse) -> int: - if args.override_home_folder: - global override_home_folder - override_home_folder = args.override_home_folder - - if args.update: - remove_invalid_o3de_objects() - return refresh_repos() - elif args.this_engine: - ret_val = register(engine_path=get_this_engine_path(), force=args.force) - error_code = register_shipped_engine_o3de_objects(force=args.force) - if error_code: - ret_val = error_code - return ret_val - elif args.all_engines_path: - return register_all_engines_in_folder(args.all_engines_path, args.remove, args.force) - elif args.all_projects_path: - return register_all_projects_in_folder(args.all_projects_path, args.remove) - elif args.all_gems_path: - return register_all_gems_in_folder(args.all_gems_path, args.remove) - elif args.all_templates_path: - return register_all_templates_in_folder(args.all_templates_path, args.remove) - elif args.all_restricted_path: - return register_all_restricted_in_folder(args.all_restricted_path, args.remove) - elif args.all_repo_uri: - return register_all_repos_in_folder(args.all_restricted_path, args.remove) - else: - return register(engine_path=args.engine_path, - project_path=args.project_path, - gem_path=args.gem_path, - template_path=args.template_path, - restricted_path=args.restricted_path, - repo_uri=args.repo_uri, - default_engines_folder=args.default_engines_folder, - default_projects_folder=args.default_projects_folder, - default_gems_folder=args.default_gems_folder, - default_templates_folder=args.default_templates_folder, - default_restricted_folder=args.default_restricted_folder, - remove=args.remove, - force=args.force) - - -def _run_add_external_subdirectory(args: argparse) -> int: - if args.override_home_folder: - global override_home_folder - override_home_folder = args.override_home_folder - - return add_external_subdirectory(args.external_subdirectory) - - -def _run_remove_external_subdirectory(args: argparse) -> int: - if args.override_home_folder: - global override_home_folder - override_home_folder = args.override_home_folder - - return remove_external_subdirectory(args.external_subdirectory) - - -def _run_add_gem_to_cmake(args: argparse) -> int: - if args.override_home_folder: - global override_home_folder - override_home_folder = args.override_home_folder - - return add_gem_to_cmake(gem_name=args.gem_name, gem_path=args.gem_path) - - -def _run_remove_gem_from_cmake(args: argparse) -> int: - if args.override_home_folder: - global override_home_folder - override_home_folder = args.override_home_folder - - return remove_gem_from_cmake(args.gem_name, args.gem_path) - - -def _run_add_gem_to_project(args: argparse) -> int: - if args.override_home_folder: - global override_home_folder - override_home_folder = args.override_home_folder - - return add_gem_to_project(args.gem_name, - args.gem_path, - args.gem_target, - args.project_name, - args.project_path, - args.dependencies_file, - args.runtime_dependency, - args.tool_dependency, - args.server_dependency, - args.platforms, - args.add_to_cmake) - - -def _run_remove_gem_from_project(args: argparse) -> int: - if args.override_home_folder: - global override_home_folder - override_home_folder = args.override_home_folder - - return remove_gem_from_project(args.gem_name, - args.gem_path, - args.gem_target, - args.project_path, - args.project_name, - args.dependencies_file, - args.runtime_dependency, - args.tool_dependency, - args.server_dependency, - args.platforms, - args.remove_from_cmake) - - -def _run_sha256(args: argparse) -> int: - return sha256(args.file_path, - args.json_path) def add_args(parser, subparsers) -> None: @@ -4095,320 +28,48 @@ def add_args(parser, subparsers) -> None: :param subparsers: the caller instantiates subparsers and passes it in here """ # register - register_subparser = subparsers.add_parser('register') - group = register_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('--this-engine', action='store_true', required=False, - default=False, - help='Registers the engine this script is running from.') - group.add_argument('-ep', '--engine-path', type=str, required=False, - help='Engine path to register/remove.') - group.add_argument('-pp', '--project-path', type=str, required=False, - help='Project path to register/remove.') - group.add_argument('-gp', '--gem-path', type=str, required=False, - help='Gem path to register/remove.') - group.add_argument('-tp', '--template-path', type=str, required=False, - help='Template path to register/remove.') - group.add_argument('-rp', '--restricted-path', type=str, required=False, - help='A restricted folder to register/remove.') - group.add_argument('-ru', '--repo-uri', type=str, required=False, - help='A repo uri to register/remove.') - group.add_argument('-aep', '--all-engines-path', type=str, required=False, - help='All engines under this folder to register/remove.') - group.add_argument('-app', '--all-projects-path', type=str, required=False, - help='All projects under this folder to register/remove.') - group.add_argument('-agp', '--all-gems-path', type=str, required=False, - help='All gems under this folder to register/remove.') - group.add_argument('-atp', '--all-templates-path', type=str, required=False, - help='All templates under this folder to register/remove.') - group.add_argument('-arp', '--all-restricted-path', type=str, required=False, - help='All templates under this folder to register/remove.') - group.add_argument('-aru', '--all-repo-uri', type=str, required=False, - help='All repos under this folder to register/remove.') - group.add_argument('-def', '--default-engines-folder', type=str, required=False, - help='The default engines folder to register/remove.') - group.add_argument('-dpf', '--default-projects-folder', type=str, required=False, - help='The default projects folder to register/remove.') - group.add_argument('-dgf', '--default-gems-folder', type=str, required=False, - help='The default gems folder to register/remove.') - group.add_argument('-dtf', '--default-templates-folder', type=str, required=False, - help='The default templates folder to register/remove.') - group.add_argument('-drf', '--default-restricted-folder', type=str, required=False, - help='The default restricted folder to register/remove.') - group.add_argument('-u', '--update', action='store_true', required=False, - default=False, - help='Refresh the repo cache.') - - register_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - register_subparser.add_argument('-r', '--remove', action='store_true', required=False, - default=False, - help='Remove entry.') - register_subparser.add_argument('-f', '--force', action='store_true', default=False, - help='For the update of the registration field being modified.') - register_subparser.set_defaults(func=_run_register) + from o3de import register + register.add_args(parser, subparsers) # show - register_show_subparser = subparsers.add_parser('register-show') - group = register_show_subparser.add_mutually_exclusive_group(required=False) - group.add_argument('-te', '--this-engine', action='store_true', required=False, - default=False, - help='Just the local engines.') - - group.add_argument('-e', '--engines', action='store_true', required=False, - default=False, - help='Just the local engines.') - group.add_argument('-p', '--projects', action='store_true', required=False, - default=False, - help='Just the local projects.') - group.add_argument('-g', '--gems', action='store_true', required=False, - default=False, - help='Just the local gems.') - group.add_argument('-t', '--templates', action='store_true', required=False, - default=False, - help='Just the local templates.') - group.add_argument('-r', '--repos', action='store_true', required=False, - default=False, - help='Just the local repos. Ignores repos.') - group.add_argument('-rs', '--restricted', action='store_true', required=False, - default=False, - help='The local restricted folders.') - - group.add_argument('-ep', '--engine-projects', action='store_true', required=False, - default=False, - help='Just the local projects. Ignores repos.') - group.add_argument('-eg', '--engine-gems', action='store_true', required=False, - default=False, - help='Just the local gems. Ignores repos') - group.add_argument('-et', '--engine-templates', action='store_true', required=False, - default=False, - help='Just the local templates. Ignores repos.') - group.add_argument('-ers', '--engine-restricted', action='store_true', required=False, - default=False, - help='The restricted folders.') - group.add_argument('-x', '--external-subdirectories', action='store_true', required=False, - default=False, - help='The external subdirectories.') - - group.add_argument('-ap', '--all-projects', action='store_true', required=False, - default=False, - help='Just the local projects. Ignores repos.') - group.add_argument('-ag', '--all-gems', action='store_true', required=False, - default=False, - help='Just the local gems. Ignores repos') - group.add_argument('-at', '--all-templates', action='store_true', required=False, - default=False, - help='Just the local templates. Ignores repos.') - group.add_argument('-ars', '--all-restricted', action='store_true', required=False, - default=False, - help='The restricted folders.') - - group.add_argument('-d', '--downloadables', action='store_true', required=False, - default=False, - help='Combine all repos into a single list of resources.') - group.add_argument('-de', '--downloadable-engines', action='store_true', required=False, - default=False, - help='Combine all repos engines into a single list of resources.') - group.add_argument('-dp', '--downloadable-projects', action='store_true', required=False, - default=False, - help='Combine all repos projects into a single list of resources.') - group.add_argument('-dg', '--downloadable-gems', action='store_true', required=False, - default=False, - help='Combine all repos gems into a single list of resources.') - group.add_argument('-dt', '--downloadable-templates', action='store_true', required=False, - default=False, - help='Combine all repos templates into a single list of resources.') - - register_show_subparser.add_argument('-v', '--verbose', action='count', required=False, - default=0, - help='How verbose do you want the output to be.') - - register_show_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - register_show_subparser.set_defaults(func=_run_register_show) + from o3de import print_registration + print_registration.add_args(parser, subparsers) # get-registered - get_registered_subparser = subparsers.add_parser('get-registered') - group = get_registered_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('-en', '--engine-name', type=str, required=False, - help='Engine name.') - group.add_argument('-pn', '--project-name', type=str, required=False, - help='Project name.') - group.add_argument('-gn', '--gem-name', type=str, required=False, - help='Gem name.') - group.add_argument('-tn', '--template-name', type=str, required=False, - help='Template name.') - group.add_argument('-df', '--default-folder', type=str, required=False, - choices=['engines', 'projects', 'gems', 'templates', 'restricted'], - help='The default folders for o3de.') - group.add_argument('-rn', '--repo-name', type=str, required=False, - help='Repo name.') - group.add_argument('-rsn', '--restricted-name', type=str, required=False, - help='Restricted name.') - - get_registered_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - get_registered_subparser.set_defaults(func=_run_get_registered) + from o3de import get_registration + get_registration.add_args(parser, subparsers) # download - download_subparser = subparsers.add_parser('download') - group = download_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('-e', '--engine-name', type=str, required=False, - help='Downloadable engine name.') - group.add_argument('-p', '--project-name', type=str, required=False, - help='Downloadable project name.') - group.add_argument('-g', '--gem-name', type=str, required=False, - help='Downloadable gem name.') - group.add_argument('-t', '--template-name', type=str, required=False, - help='Downloadable template name.') - download_subparser.add_argument('-dp', '--dest-path', type=str, required=False, - default=None, - help='Optional destination folder to download into.' - ' i.e. download --project-name "StarterGame" --dest-path "C:/projects"' - ' will result in C:/projects/StarterGame' - ' If blank will download to default object type folder') - - download_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - download_subparser.set_defaults(func=_run_download) + from o3de import download + download.add_args(parser, subparsers) # add external subdirectories - add_external_subdirectory_subparser = subparsers.add_parser('add-external-subdirectory') - add_external_subdirectory_subparser.add_argument('external_subdirectory', metavar='external_subdirectory', type=str, - help='add an external subdirectory to cmake') - - add_external_subdirectory_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - add_external_subdirectory_subparser.set_defaults(func=_run_add_external_subdirectory) + from o3de import add_external_subdirectory + add_external_subdirectory.add_args(parser, subparsers) # remove external subdirectories - remove_external_subdirectory_subparser = subparsers.add_parser('remove-external-subdirectory') - remove_external_subdirectory_subparser.add_argument('external_subdirectory', metavar='external_subdirectory', - type=str, - help='remove external subdirectory from cmake') - - remove_external_subdirectory_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - remove_external_subdirectory_subparser.set_defaults(func=_run_remove_external_subdirectory) + from o3de import remove_external_subdirectory + remove_external_subdirectory.add_args(parser, subparsers) # add gems to cmake - # convenience functions to disambiguate the gem name -> gem_path and call add-external-subdirectory on gem_path - add_gem_to_cmake_subparser = subparsers.add_parser('add-gem-to-cmake') - group = add_gem_to_cmake_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('-gp', '--gem-path', type=str, required=False, - help='The path to the gem.') - group.add_argument('-gn', '--gem-name', type=str, required=False, - help='The name of the gem.') - - add_gem_to_cmake_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - add_gem_to_cmake_subparser.set_defaults(func=_run_add_gem_to_cmake) + from o3de import add_gem_cmake + add_gem_cmake.add_args(parser, subparsers) # remove gems from cmake - # convenience functions to disambiguate the gem name -> gem_path and call remove-external-subdirectory on gem_path - remove_gem_from_cmake_subparser = subparsers.add_parser('remove-gem-from-cmake') - group = remove_gem_from_cmake_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('-gp', '--gem-path', type=str, required=False, - help='The path to the gem.') - group.add_argument('-gn', '--gem-name', type=str, required=False, - help='The name of the gem.') - - remove_gem_from_cmake_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - remove_gem_from_cmake_subparser.set_defaults(func=_run_remove_gem_from_cmake) + from o3de import remove_gem_cmake + remove_gem_cmake.add_args(parser, subparsers) # add a gem to a project - add_gem_subparser = subparsers.add_parser('add-gem-to-project') - group = add_gem_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('-pp', '--project-path', type=str, required=False, - help='The path to the project.') - group.add_argument('-pn', '--project-name', type=str, required=False, - help='The name of the project.') - group = add_gem_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('-gp', '--gem-path', type=str, required=False, - help='The path to the gem.') - group.add_argument('-gn', '--gem-name', type=str, required=False, - help='The name of the gem.') - add_gem_subparser.add_argument('-gt', '--gem-target', type=str, required=False, - help='The cmake target name to add. If not specified it will assume gem_name') - add_gem_subparser.add_argument('-df', '--dependencies-file', type=str, required=False, - help='The cmake dependencies file in which the gem dependencies are specified.' - 'If not specified it will assume ') - add_gem_subparser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be added as a runtime dependency') - add_gem_subparser.add_argument('-td', '--tool-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be added as a tool dependency') - add_gem_subparser.add_argument('-sd', '--server-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be added as a server dependency') - add_gem_subparser.add_argument('-pl', '--platforms', type=str, required=False, - default='Common', - help='Optional list of platforms this gem should be added to.' - ' Ex. --platforms Mac,Windows,Linux') - add_gem_subparser.add_argument('-a', '--add-to-cmake', type=bool, required=False, - default=True, - help='Automatically call add-gem-to-cmake.') - - add_gem_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - add_gem_subparser.set_defaults(func=_run_add_gem_to_project) + from o3de import add_gem_project + add_gem_project.add_args(parser, subparsers) # remove a gem from a project - remove_gem_subparser = subparsers.add_parser('remove-gem-from-project') - group = remove_gem_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('-pp', '--project-path', type=str, required=False, - help='The path to the project.') - group.add_argument('-pn', '--project-name', type=str, required=False, - help='The name of the project.') - group = remove_gem_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('-gp', '--gem-path', type=str, required=False, - help='The path to the gem.') - group.add_argument('-gn', '--gem-name', type=str, required=False, - help='The name of the gem.') - remove_gem_subparser.add_argument('-gt', '--gem-target', type=str, required=False, - help='The cmake target name to add. If not specified it will assume gem_name') - remove_gem_subparser.add_argument('-df', '--dependencies-file', type=str, required=False, - help='The cmake dependencies file in which the gem dependencies are specified.' - 'If not specified it will assume ') - remove_gem_subparser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be removed as a runtime dependency') - remove_gem_subparser.add_argument('-td', '--tool-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be removed as a server dependency') - remove_gem_subparser.add_argument('-sd', '--server-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be removed as a server dependency') - remove_gem_subparser.add_argument('-pl', '--platforms', type=str, required=False, - default='Common', - help='Optional list of platforms this gem should be removed from' - ' Ex. --platforms Mac,Windows,Linux') - remove_gem_subparser.add_argument('-r', '--remove-from-cmake', type=bool, required=False, - default=False, - help='Automatically call remove-from-cmake.') - - remove_gem_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - remove_gem_subparser.set_defaults(func=_run_remove_gem_from_project) + from o3de import remove_gem_project + remove_gem_project.add_args(parser, subparsers) # sha256 - sha256_subparser = subparsers.add_parser('sha256') - sha256_subparser.add_argument('-f', '--file-path', type=str, required=True, - help='The path to the file you want to sha256.') - sha256_subparser.add_argument('-j', '--json-path', type=str, required=False, - help='optional path to an o3de json file to add the "sha256" element to.') - sha256_subparser.set_defaults(func=_run_sha256) + from o3de import sha256 + sha256.add_args(parser, subparsers) if __name__ == "__main__": diff --git a/scripts/o3de/o3de/remove_external_subdirectory.py b/scripts/o3de/o3de/remove_external_subdirectory.py new file mode 100644 index 0000000000..3e022d51b9 --- /dev/null +++ b/scripts/o3de/o3de/remove_external_subdirectory.py @@ -0,0 +1,73 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +Contains command to add a gem to a project's cmake scripts +""" + +import argparse +import logging +import pathlib + +from o3de import manifest + +logger = logging.getLogger() +logging.basicConfig() + +def remove_external_subdirectory(external_subdir: str or pathlib.Path, + engine_path: str or pathlib.Path = None) -> int: + """ + remove external subdirectory from cmake + :param external_subdir: external subdirectory to add to cmake + :param engine_path: optional engine path, defaults to this engine + :return: 0 for success or non 0 failure code + """ + json_data = manifest.load_o3de_manifest() + engine_object = manifest.find_engine_data(json_data, engine_path) + if not engine_object: + logger.error(f'Remove External Subdirectory Failed: {engine_path} not registered.') + return 1 + + external_subdir = pathlib.Path(external_subdir).resolve() + while external_subdir.as_posix() in engine_object['external_subdirectories']: + engine_object['external_subdirectories'].remove(external_subdir.as_posix()) + + manifest.save_o3de_manifest(json_data) + + return 0 + + +def _run_remove_external_subdirectory(args: argparse) -> int: + if args.override_home_folder: + manifest.override_home_folder = args.override_home_folder + + return remove_external_subdirectory(args.external_subdirectory) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + remove_external_subdirectory_subparser = subparsers.add_parser('remove-external-subdirectory') + remove_external_subdirectory_subparser.add_argument('external_subdirectory', metavar='external_subdirectory', + type=str, + help='remove external subdirectory from cmake') + + remove_external_subdirectory_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + remove_external_subdirectory_subparser.set_defaults(func=_run_remove_external_subdirectory) diff --git a/scripts/o3de/o3de/remove_gem_cmake.py b/scripts/o3de/o3de/remove_gem_cmake.py new file mode 100644 index 0000000000..2def94dfbf --- /dev/null +++ b/scripts/o3de/o3de/remove_gem_cmake.py @@ -0,0 +1,89 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +This file contains methods for removing a gem from a project's cmake scripts +""" + +import argparse +import logging +import pathlib + +from o3de import manifest, remove_external_subdirectory + +logger = logging.getLogger() +logging.basicConfig() + +def remove_gem_from_cmake(gem_name: str = None, + gem_path: str or pathlib.Path = None, + engine_name: str = None, + engine_path: str or pathlib.Path = None) -> int: + """ + remove a gem to cmake as an external subdirectory + :param gem_name: name of the gem to remove from cmake + :param gem_path: the path of the gem to add to cmake + :param engine_name: optional name of the engine to remove from cmake + :param engine_path: the path of the engine to remove external subdirectory from, defaults to this engine + :return: 0 for success or non 0 failure code + """ + if not gem_name and not gem_path: + logger.error('Must specify either a Gem name or Gem Path.') + return 1 + + if gem_name and not gem_path: + gem_path = manifest.get_registered(gem_name=gem_name) + + if not gem_path: + logger.error(f'Gem Path {gem_path} has not been registered.') + return 1 + + if not engine_name and not engine_path: + engine_path = manifest.get_this_engine_path() + + if engine_name and not engine_path: + engine_path = manifest.get_registered(engine_name=engine_name) + + if not engine_path: + logger.error(f'Engine Path {engine_path} is not registered.') + return 1 + + return remove_external_subdirectory.remove_external_subdirectory(external_subdir=gem_path, engine_path=engine_path) + + +def _run_remove_gem_from_cmake(args: argparse) -> int: + if args.override_home_folder: + manifest.override_home_folder = args.override_home_folder + + return remove_gem_from_cmake(args.gem_name, args.gem_path) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + # convenience functions to disambiguate the gem name -> gem_path and call remove-external-subdirectory on gem_path + remove_gem_from_cmake_subparser = subparsers.add_parser('remove-gem-from-cmake') + group = remove_gem_from_cmake_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-gp', '--gem-path', type=str, required=False, + help='The path to the gem.') + group.add_argument('-gn', '--gem-name', type=str, required=False, + help='The name of the gem.') + + remove_gem_from_cmake_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + remove_gem_from_cmake_subparser.set_defaults(func=_run_remove_gem_from_cmake) diff --git a/scripts/o3de/o3de/remove_gem_project.py b/scripts/o3de/o3de/remove_gem_project.py new file mode 100644 index 0000000000..a3e623f488 --- /dev/null +++ b/scripts/o3de/o3de/remove_gem_project.py @@ -0,0 +1,270 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +This file contains methods for removing a gem from a project +""" + +import argparse +import logging +import os +import pathlib + +from o3de import cmake, remove_gem_cmake + +logger = logging.getLogger() +logging.basicConfig() + + +def remove_gem_dependency(cmake_file: str or pathlib.Path, + gem_target: str) -> int: + """ + removes a gem dependency from a cmake file + :param cmake_file: path to the cmake file + :param gem_target: cmake target name + :return: 0 for success or non 0 failure code + """ + if not os.path.isfile(cmake_file): + logger.error(f'Failed to locate cmake file {cmake_file}') + return 1 + + # on a line by basis, remove any line with Gem::{gem_name} + t_data = [] + # Remove the gem from the cmake_dependencies file by skipping the gem name entry + removed = False + with open(cmake_file, 'r') as s: + for line in s: + if f'Gem::{gem_target}' in line: + removed = True + else: + t_data.append(line) + + if not removed: + logger.error(f'Failed to remove Gem::{gem_target} from cmake file {cmake_file}') + return 1 + + # write the cmake + os.unlink(cmake_file) + with open(cmake_file, 'w') as s: + s.writelines(t_data) + + return 0 + + +def remove_gem_from_project(gem_name: str = None, + gem_path: str or pathlib.Path = None, + gem_target: str = None, + project_name: str = None, + project_path: str or pathlib.Path = None, + dependencies_file: str or pathlib.Path = None, + runtime_dependency: bool = False, + tool_dependency: bool = False, + server_dependency: bool = False, + platforms: str = 'Common', + remove_from_cmake: bool = False) -> int: + """ + remove a gem from a project + :param gem_name: name of the gem to add + :param gem_path: path to the gem to add + :param gem_target: the name of teh cmake gem module + :param project_name: name of the project to add the gem to + :param project_path: path to the project to add the gem to + :param dependencies_file: if this dependency goes/is in a specific file + :param runtime_dependency: bool to specify this is a runtime gem for the game + :param tool_dependency: bool to specify this is a tool gem for the editor + :param server_dependency: bool to specify this is a server gem for the server + :param platforms: str to specify common or which specific platforms + :param remove_from_cmake: bool to specify that this gem should be removed from cmake + :return: 0 for success or non 0 failure code + """ + + # we need either a project name or path + if not project_name and not project_path: + logger.error(f'Must either specify a Project path or Project Name.') + return 1 + + # if project name resolve it into a path + if project_name and not project_path: + project_path = manifest.get_registered(project_name=project_name) + project_path = pathlib.Path(project_path).resolve() + if not project_path.is_dir(): + logger.error(f'Project path {project_path} is not a folder.') + return 1 + + # We need either a gem name or path + if not gem_name and not gem_path: + logger.error(f'Must either specify a Gem path or Gem Name.') + return 1 + + # if gem name resolve it into a path + if gem_name and not gem_path: + gem_path = manifest.get_registered(gem_name=gem_name) + gem_path = pathlib.Path(gem_path).resolve() + # make sure this gem already exists if we're adding. We can always remove a gem. + if not gem_path.is_dir(): + logger.error(f'Gem Path {gem_path} does not exist.') + return 1 + + # find all available modules in this gem_path + modules = cmake.get_gem_targets(gem_path=gem_path) + if len(modules) == 0: + logger.error(f'No gem modules found.') + return 1 + + # if the user has not set a specific gem target remove all of them + + # if gem target not specified, see if there is only 1 module + if not gem_target: + if len(modules) == 1: + gem_target = modules[0] + else: + logger.error(f'Gem target not specified: {modules}') + return 1 + elif gem_target not in modules: + logger.error(f'Gem target not in gem modules: {modules}') + return 1 + + # if the user has not specified either we will assume they meant the most common which is runtime + if not runtime_dependency and not tool_dependency and not server_dependency and not dependencies_file: + logger.warning("Dependency type not specified: Assuming '--runtime-dependency'") + runtime_dependency = True + + # when removing we will try to do as much as possible even with failures so ret_val will be the last error code + ret_val = 0 + + # if the user has specified the dependencies file then ignore the runtime_dependency and tool_dependency flags + if dependencies_file: + dependencies_file = pathlib.Path(dependencies_file).resolve() + # make sure this is a project has a dependencies_file + if not dependencies_file.is_file(): + logger.error(f'Dependencies file {dependencies_file} is not present.') + return 1 + # remove the dependency + error_code = remove_gem_dependency(dependencies_file, gem_target) + if error_code: + ret_val = error_code + else: + if ',' in platforms: + platforms = platforms.split(',') + else: + platforms = [platforms] + for platform in platforms: + if runtime_dependency: + # make sure this is a project has a runtime_dependencies.cmake file + project_runtime_dependencies_file = pathlib.Path( + cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', + platform=platform)).resolve() + if not project_runtime_dependencies_file.is_file(): + logger.error(f'Runtime dependencies file {project_runtime_dependencies_file} is not present.') + else: + # remove the dependency + error_code = remove_gem_dependency(project_runtime_dependencies_file, gem_target) + if error_code: + ret_val = error_code + + if tool_dependency: + # make sure this is a project has a tool_dependencies.cmake file + project_tool_dependencies_file = pathlib.Path( + cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', + platform=platform)).resolve() + if not project_tool_dependencies_file.is_file(): + logger.error(f'Tool dependencies file {project_tool_dependencies_file} is not present.') + else: + # remove the dependency + error_code = remove_gem_dependency(project_tool_dependencies_file, gem_target) + if error_code: + ret_val = error_code + + if server_dependency: + # make sure this is a project has a tool_dependencies.cmake file + project_server_dependencies_file = pathlib.Path( + cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='server', + platform=platform)).resolve() + if not project_server_dependencies_file.is_file(): + logger.error(f'Server dependencies file {project_server_dependencies_file} is not present.') + else: + # remove the dependency + error_code = remove_gem_dependency(project_server_dependencies_file, gem_target) + if error_code: + ret_val = error_code + + if remove_from_cmake: + error_code = remove_gem_cmake.remove_gem_from_cmake(gem_path=gem_path) + if error_code: + ret_val = error_code + + return ret_val + + +def _run_remove_gem_from_project(args: argparse) -> int: + if args.override_home_folder: + manifest.override_home_folder = args.override_home_folder + + return remove_gem_from_project(args.gem_name, + args.gem_path, + args.gem_target, + args.project_path, + args.project_name, + args.dependencies_file, + args.runtime_dependency, + args.tool_dependency, + args.server_dependency, + args.platforms, + args.remove_from_cmake) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + remove_gem_subparser = subparsers.add_parser('remove-gem-from-project') + group = remove_gem_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-pp', '--project-path', type=str, required=False, + help='The path to the project.') + group.add_argument('-pn', '--project-name', type=str, required=False, + help='The name of the project.') + group = remove_gem_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-gp', '--gem-path', type=str, required=False, + help='The path to the gem.') + group.add_argument('-gn', '--gem-name', type=str, required=False, + help='The name of the gem.') + remove_gem_subparser.add_argument('-gt', '--gem-target', type=str, required=False, + help='The cmake target name to add. If not specified it will assume gem_name') + remove_gem_subparser.add_argument('-df', '--dependencies-file', type=str, required=False, + help='The cmake dependencies file in which the gem dependencies are specified.' + 'If not specified it will assume ') + remove_gem_subparser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be removed as a runtime dependency') + remove_gem_subparser.add_argument('-td', '--tool-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be removed as a server dependency') + remove_gem_subparser.add_argument('-sd', '--server-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be removed as a server dependency') + remove_gem_subparser.add_argument('-pl', '--platforms', type=str, required=False, + default='Common', + help='Optional list of platforms this gem should be removed from' + ' Ex. --platforms Mac,Windows,Linux') + remove_gem_subparser.add_argument('-r', '--remove-from-cmake', type=bool, required=False, + default=False, + help='Automatically call remove-from-cmake.') + + remove_gem_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + remove_gem_subparser.set_defaults(func=_run_remove_gem_from_project) diff --git a/scripts/o3de/o3de/repo.py b/scripts/o3de/o3de/repo.py new file mode 100644 index 0000000000..9cb93d53ae --- /dev/null +++ b/scripts/o3de/o3de/repo.py @@ -0,0 +1,291 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +import json +import logging +import pathlib +import shutil +import urllib.parse +import urllib.request + +from o3de import manifest, validation + +logger = logging.getLogger() +logging.basicConfig() + +def process_add_o3de_repo(file_name: str or pathlib.Path, + repo_set: set) -> int: + file_name = pathlib.Path(file_name).resolve() + if not validation.valid_o3de_repo_json(file_name): + return 1 + + cache_folder = manifest.get_o3de_cache_folder() + + with file_name.open('r') as f: + try: + repo_data = json.load(f) + except Exception as e: + logger.error(f'{file_name} failed to load: {str(e)}') + return 1 + + for engine_uri in repo_data['engines']: + engine_uri = f'{engine_uri}/engine.json' + engine_sha256 = hashlib.sha256(engine_uri.encode()) + cache_file = cache_folder / str(engine_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + parsed_uri = urllib.parse.urlparse(engine_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(engine_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + engine_json = pathlib.Path(engine_uri).resolve() + if not engine_json.is_file(): + return 1 + shutil.copy(engine_json, cache_file) + + for project_uri in repo_data['projects']: + project_uri = f'{project_uri}/project.json' + project_sha256 = hashlib.sha256(project_uri.encode()) + cache_file = cache_folder / str(project_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + parsed_uri = urllib.parse.urlparse(project_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(project_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + project_json = pathlib.Path(project_uri).resolve() + if not project_json.is_file(): + return 1 + shutil.copy(project_json, cache_file) + + for gem_uri in repo_data['gems']: + gem_uri = f'{gem_uri}/gem.json' + gem_sha256 = hashlib.sha256(gem_uri.encode()) + cache_file = cache_folder / str(gem_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + parsed_uri = urllib.parse.urlparse(gem_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(gem_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + gem_json = pathlib.Path(gem_uri).resolve() + if not gem_json.is_file(): + return 1 + shutil.copy(gem_json, cache_file) + + for template_uri in repo_data['templates']: + template_uri = f'{template_uri}/template.json' + template_sha256 = hashlib.sha256(template_uri.encode()) + cache_file = cache_folder / str(template_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + parsed_uri = urllib.parse.urlparse(template_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(template_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + template_json = pathlib.Path(template_uri).resolve() + if not template_json.is_file(): + return 1 + shutil.copy(template_json, cache_file) + + for repo_uri in repo_data['repos']: + if repo_uri not in repo_set: + repo_set.add(repo_uri) + repo_uri = f'{repo_uri}/repo.json' + repo_sha256 = hashlib.sha256(repo_uri.encode()) + cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(repo_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + repo_json = pathlib.Path(repo_uri).resolve() + if not repo_json.is_file(): + return 1 + shutil.copy(repo_json, cache_file) + return 0 + + +def refresh_repos() -> int: + json_data = manifest.load_o3de_manifest() + + # clear the cache + cache_folder = manifest.get_o3de_cache_folder() + shutil.rmtree(cache_folder) + cache_folder = manifest.get_o3de_cache_folder() # will recreate it + + result = 0 + + # set will stop circular references + repo_set = set() + + for repo_uri in json_data['repos']: + if repo_uri not in repo_set: + repo_set.add(repo_uri) + + repo_uri = f'{repo_uri}/repo.json' + repo_sha256 = hashlib.sha256(repo_uri.encode()) + cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + parsed_uri = urllib.parse.urlparse(repo_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(repo_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(repo_uri).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, cache_file) + + if not validation.valid_o3de_repo_json(cache_file): + logger.error(f'Repo json {repo_uri} is not valid.') + cache_file.unlink() + return 1 + + last_failure = process_add_o3de_repo(cache_file, repo_set) + if last_failure: + result = last_failure + + return result + + +def search_repo(repo_set: set, + repo_json_data: dict, + engine_name: str = None, + project_name: str = None, + gem_name: str = None, + template_name: str = None, + restricted_name: str = None) -> dict or None: + cache_folder = manifest.get_o3de_cache_folder() + + if isinstance(engine_name, str) or isinstance(engine_name, pathlib.PurePath): + for engine_uri in repo_json_data['engines']: + engine_uri = f'{engine_uri}/engine.json' + engine_sha256 = hashlib.sha256(engine_uri.encode()) + engine_cache_file = cache_folder / str(engine_sha256.hexdigest() + '.json') + if engine_cache_file.is_file(): + with engine_cache_file.open('r') as f: + try: + engine_json_data = json.load(f) + except Exception as e: + logger.warn(f'{engine_cache_file} failed to load: {str(e)}') + else: + if engine_json_data['engine_name'] == engine_name: + return engine_json_data + + elif isinstance(project_name, str) or isinstance(project_name, pathlib.PurePath): + for project_uri in repo_json_data['projects']: + project_uri = f'{project_uri}/project.json' + project_sha256 = hashlib.sha256(project_uri.encode()) + project_cache_file = cache_folder / str(project_sha256.hexdigest() + '.json') + if project_cache_file.is_file(): + with project_cache_file.open('r') as f: + try: + project_json_data = json.load(f) + except Exception as e: + logger.warn(f'{project_cache_file} failed to load: {str(e)}') + else: + if project_json_data['project_name'] == project_name: + return project_json_data + + elif isinstance(gem_name, str) or isinstance(gem_name, pathlib.PurePath): + for gem_uri in repo_json_data['gems']: + gem_uri = f'{gem_uri}/gem.json' + gem_sha256 = hashlib.sha256(gem_uri.encode()) + gem_cache_file = cache_folder / str(gem_sha256.hexdigest() + '.json') + if gem_cache_file.is_file(): + with gem_cache_file.open('r') as f: + try: + gem_json_data = json.load(f) + except Exception as e: + logger.warn(f'{gem_cache_file} failed to load: {str(e)}') + else: + if gem_json_data['gem_name'] == gem_name: + return gem_json_data + + elif isinstance(template_name, str) or isinstance(template_name, pathlib.PurePath): + for template_uri in repo_json_data['templates']: + template_uri = f'{template_uri}/template.json' + template_sha256 = hashlib.sha256(template_uri.encode()) + template_cache_file = cache_folder / str(template_sha256.hexdigest() + '.json') + if template_cache_file.is_file(): + with template_cache_file.open('r') as f: + try: + template_json_data = json.load(f) + except Exception as e: + logger.warn(f'{template_cache_file} failed to load: {str(e)}') + else: + if template_json_data['template_name'] == template_name: + return template_json_data + + elif isinstance(restricted_name, str) or isinstance(restricted_name, pathlib.PurePath): + for restricted_uri in repo_json_data['restricted']: + restricted_uri = f'{restricted_uri}/restricted.json' + restricted_sha256 = hashlib.sha256(restricted_uri.encode()) + restricted_cache_file = cache_folder / str(restricted_sha256.hexdigest() + '.json') + if restricted_cache_file.is_file(): + with restricted_cache_file.open('r') as f: + try: + restricted_json_data = json.load(f) + except Exception as e: + logger.warn(f'{restricted_cache_file} failed to load: {str(e)}') + else: + if restricted_json_data['restricted_name'] == restricted_name: + return restricted_json_data + # recurse + else: + for repo_repo_uri in repo_json_data['repos']: + if repo_repo_uri not in repo_set: + repo_set.add(repo_repo_uri) + repo_repo_uri = f'{repo_repo_uri}/repo.json' + repo_repo_sha256 = hashlib.sha256(repo_repo_uri.encode()) + repo_repo_cache_file = cache_folder / str(repo_repo_sha256.hexdigest() + '.json') + if repo_repo_cache_file.is_file(): + with repo_repo_cache_file.open('r') as f: + try: + repo_repo_json_data = json.load(f) + except Exception as e: + logger.warn(f'{repo_repo_cache_file} failed to load: {str(e)}') + else: + item = search_repo(repo_set, + repo_repo_json_data, + engine_name, + project_name, + gem_name, + template_name) + if item: + return item + return None + diff --git a/scripts/o3de/o3de/sha256.py b/scripts/o3de/o3de/sha256.py new file mode 100644 index 0000000000..bc35919c4e --- /dev/null +++ b/scripts/o3de/o3de/sha256.py @@ -0,0 +1,82 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +import argparse +import json +import logging +import hashlib + +from o3de import utils + +logger = logging.getLogger() +logging.basicConfig() + + +def sha256(file_path: str or pathlib.Path, + json_path: str or pathlib.Path = None) -> int: + if not file_path: + logger.error(f'File path cannot be empty.') + return 1 + file_path = pathlib.Path(file_path).resolve() + if not file_path.is_file(): + logger.error(f'File path {file_path} does not exist.') + return 1 + + if json_path: + json_path = pathlib.Path(json_path).resolve() + if not json_path.is_file(): + logger.error(f'Json path {json_path} does not exist.') + return 1 + + sha256 = hashlib.sha256(file_path.open('rb').read()).hexdigest() + + if json_path: + with json_path.open('r') as s: + try: + json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to read Json path {json_path}: {str(e)}') + return 1 + json_data.update({"sha256": sha256}) + utils.backup_file(json_path) + with json_path.open('w') as s: + try: + s.write(json.dumps(json_data, indent=4)) + except Exception as e: + logger.error(f'Failed to write Json path {json_path}: {str(e)}') + return 1 + else: + print(sha256) + return 0 + + +def _run_sha256(args: argparse) -> int: + return sha256(args.file_path, + args.json_path) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" + OR + o3de.py can downloadable commands by importing engine_template, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + sha256_subparser = subparsers.add_parser('sha256') + sha256_subparser.add_argument('-f', '--file-path', type=str, required=True, + help='The path to the file you want to sha256.') + sha256_subparser.add_argument('-j', '--json-path', type=str, required=False, + help='optional path to an o3de json file to add the "sha256" element to.') + sha256_subparser.set_defaults(func=_run_sha256) diff --git a/scripts/o3de/o3de/utils.py b/scripts/o3de/o3de/utils.py index 37c84ea331..50a9e5d6dd 100755 --- a/scripts/o3de/o3de/utils.py +++ b/scripts/o3de/o3de/utils.py @@ -45,3 +45,28 @@ def validate_uuid4(uuid_string: str) -> bool: except ValueError: return False return str(val) == uuid_string + +def backup_file(file_name: str or pathlib.Path) -> None: + index = 0 + renamed = False + while not renamed: + backup_file_name = pathlib.Path(str(file_name) + '.bak' + str(index)).resolve() + index += 1 + if not backup_file_name.is_file(): + file_name = pathlib.Path(file_name).resolve() + file_name.rename(backup_file_name) + if backup_file_name.is_file(): + renamed = True + + +def backup_folder(folder: str or pathlib.Path) -> None: + index = 0 + renamed = False + while not renamed: + backup_folder_name = pathlib.Path(str(folder) + '.bak' + str(index)).resolve() + index += 1 + if not backup_folder_name.is_dir(): + folder = pathlib.Path(folder).resolve() + folder.rename(backup_folder_name) + if backup_folder_name.is_dir(): + renamed = True \ No newline at end of file diff --git a/scripts/o3de/o3de/validation.py b/scripts/o3de/o3de/validation.py new file mode 100644 index 0000000000..56839fe056 --- /dev/null +++ b/scripts/o3de/o3de/validation.py @@ -0,0 +1,103 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +""" +This file contains functions for querying paths from ~/.o3de directory +""" +import json +import pathlib + +def valid_o3de_repo_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['repo_name'] + test = json_data['origin'] + except Exception as e: + return False + + return True + + +def valid_o3de_engine_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['engine_name'] + # test = json_data['origin'] # will be required soon + except Exception as e: + return False + return True + + +def valid_o3de_project_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['project_name'] + # test = json_data['origin'] # will be required soon + except Exception as e: + return False + return True + + +def valid_o3de_gem_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['gem_name'] + # test = json_data['origin'] # will be required soon + except Exception as e: + return False + return True + + +def valid_o3de_template_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['template_name'] + # test = json_data['origin'] # will be required soon + except Exception as e: + return False + return True + + +def valid_o3de_restricted_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['restricted_name'] + # test = json_data['origin'] # will be required soon + except Exception as e: + return False + return True diff --git a/scripts/o3de/tests/unit_test_add_remove_gem.py b/scripts/o3de/tests/unit_test_add_remove_gem.py index 81f0fa615e..cc793bf32b 100755 --- a/scripts/o3de/tests/unit_test_add_remove_gem.py +++ b/scripts/o3de/tests/unit_test_add_remove_gem.py @@ -12,7 +12,7 @@ import os import pytest -from . import add_remove_gem +from o3de import add_gem_project TEST_WITHOUT_NO_GEM_CONTENT = """ # {BEGIN_LICENSE} @@ -105,7 +105,7 @@ def test_add_gem_dependency(tmpdir, contents, gem, expected_result, runtime_pres with open(runtime_dependencies_cmake_file, 'a') as s: s.write(contents) - result = add_remove_gem.add_gem_dependency(runtime_dependencies_cmake_file, gem) + result = add_gem_project.add_gem_dependency(runtime_dependencies_cmake_file, gem) if expect_failure: assert result != 0 diff --git a/scripts/o3de/tests/unit_test_registration.py b/scripts/o3de/tests/unit_test_registration.py index 31a2dcb2f0..a0abb6cacd 100644 --- a/scripts/o3de/tests/unit_test_registration.py +++ b/scripts/o3de/tests/unit_test_registration.py @@ -16,7 +16,7 @@ import pytest import pathlib from unittest.mock import patch -from .. import registration +from o3de import register string_manifest_data = '{}' @@ -38,7 +38,7 @@ def test_register_engine_path(engine_path, engine_name, force, expected_result): subparser = parser.add_subparsers(help='sub-command help') # Register the registration script subparsers with the current argument parser - registration.add_args(parser, subparser) + register.add_args(parser, subparser) arg_list = ['register', '--engine-path', str(engine_path)] if force: arg_list += ['--force'] @@ -56,11 +56,11 @@ def test_register_engine_path(engine_path, engine_name, force, expected_result): string_manifest_data = json.dumps(manifest_json) engine_json_data = {'engine_name': engine_name} - with patch('o3de.registration.load_o3de_manifest', side_effect=load_manifest_from_string) as load_manifest_mock, \ - patch('o3de.registration.save_o3de_manifest', side_effect=save_manifest_to_string) as save_manifest_mock, \ - patch('o3de.registration.get_engine_data', return_value=engine_json_data) as engine_paths_mock, \ - patch('o3de.registration.valid_o3de_engine_json', return_value=True) as valid_engine_mock, \ + with patch('o3de.manifest.load_o3de_manifest', side_effect=load_manifest_from_string) as load_manifest_mock, \ + patch('o3de.manifest.save_o3de_manifest', side_effect=save_manifest_to_string) as save_manifest_mock, \ + patch('o3de.manifest.get_engine_json_data', return_value=engine_json_data) as engine_paths_mock, \ + patch('o3de.validation.valid_o3de_engine_json', return_value=True) as valid_engine_mock, \ patch('pathlib.Path.is_dir', return_value=True) as pathlib_is_dir_mock: - result = registration._run_register(args) + result = register._run_register(args) assert result == expected_result From 470fde461f3dcbb3bd3c1cfee3b84c247d73b7fb Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 21 May 2021 02:04:07 -0500 Subject: [PATCH 087/811] Removed engine registration from the Jenkins build scripts which builds the Engine in an engine centric manner --- .../build/Platform/Android/build_config.json | 12 ++++----- .../build/Platform/Linux/build_config.json | 22 ++++++++-------- scripts/build/Platform/Mac/build_config.json | 16 ++++++------ .../build/Platform/Windows/build_config.json | 26 +++++++++---------- .../Windows/package_build_config.json | 4 +-- scripts/build/Platform/iOS/build_config.json | 8 +++--- 6 files changed, 44 insertions(+), 44 deletions(-) diff --git a/scripts/build/Platform/Android/build_config.json b/scripts/build/Platform/Android/build_config.json index d0fce80964..699ccdf20a 100644 --- a/scripts/build/Platform/Android/build_config.json +++ b/scripts/build/Platform/Android/build_config.json @@ -35,7 +35,7 @@ "PARAMETERS": { "CONFIGURATION":"debug", "OUTPUT_DIRECTORY":"build\\android", - "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS":"AutomatedTesting", "CMAKE_TARGET":"all", "CMAKE_BUILD_ARGS":"-j!NUMBER_OF_PROCESSORS!" @@ -60,7 +60,7 @@ "PARAMETERS": { "CONFIGURATION":"profile", "OUTPUT_DIRECTORY":"build\\android", - "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS":"AutomatedTesting", "CMAKE_TARGET":"all", "CMAKE_BUILD_ARGS":"-j!NUMBER_OF_PROCESSORS!" @@ -76,7 +76,7 @@ "PARAMETERS": { "CONFIGURATION":"profile", "OUTPUT_DIRECTORY":"build\\android", - "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=FALSE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=FALSE", "CMAKE_LY_PROJECTS":"AutomatedTesting", "CMAKE_TARGET":"all", "CMAKE_BUILD_ARGS":"-j!NUMBER_OF_PROCESSORS!" @@ -93,7 +93,7 @@ "PARAMETERS": { "CONFIGURATION":"profile", "OUTPUT_DIRECTORY":"build\\windows_vs2019", - "CMAKE_OPTIONS":"-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS":"-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS":"AutomatedTesting", "CMAKE_TARGET":"AssetProcessorBatch", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", @@ -112,7 +112,7 @@ "PARAMETERS": { "CONFIGURATION":"release", "OUTPUT_DIRECTORY":"build\\android", - "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS":"AutomatedTesting", "CMAKE_TARGET":"all", "CMAKE_BUILD_ARGS":"-j!NUMBER_OF_PROCESSORS!" @@ -128,7 +128,7 @@ "PARAMETERS": { "CONFIGURATION":"release", "OUTPUT_DIRECTORY":"build\\mono_android", - "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS":"AutomatedTesting", "CMAKE_TARGET":"all", "CMAKE_BUILD_ARGS":"-j!NUMBER_OF_PROCESSORS!" diff --git a/scripts/build/Platform/Linux/build_config.json b/scripts/build/Platform/Linux/build_config.json index bbfc3e4269..4ae4c4ec0b 100644 --- a/scripts/build/Platform/Linux/build_config.json +++ b/scripts/build/Platform/Linux/build_config.json @@ -37,7 +37,7 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all" } @@ -53,7 +53,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all" } @@ -66,7 +66,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all" } @@ -80,7 +80,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all", "CTEST_OPTIONS": "-E (Gem::EMotionFX.Editor.Tests|Gem::AWSClientAuth.Tests|Gem::AWSCore.Editor.Tests) -L FRAMEWORK_googletest" @@ -92,7 +92,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all", "CTEST_OPTIONS": "-E (Gem::EMotionFX.Editor.Tests|Gem::AWSClientAuth.Tests|Gem::AWSCore.Editor.Tests) -L FRAMEWORK_googletest" @@ -108,7 +108,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "AssetProcessorBatch", "ASSET_PROCESSOR_BINARY": "bin/profile/AssetProcessorBatch", @@ -122,7 +122,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "AssetProcessorBatch", "ASSET_PROCESSOR_BINARY": "bin/profile/AssetProcessorBatch", @@ -140,7 +140,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_periodic", "CTEST_OPTIONS": "-L \"(SUITE_periodic)\"" @@ -156,7 +156,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_benchmark", "CTEST_OPTIONS": "-L \"(SUITE_benchmark)\"" @@ -172,7 +172,7 @@ "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all" } @@ -187,7 +187,7 @@ "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/mono_linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all" } diff --git a/scripts/build/Platform/Mac/build_config.json b/scripts/build/Platform/Mac/build_config.json index f312279fe6..1e6ca79d8e 100644 --- a/scripts/build/Platform/Mac/build_config.json +++ b/scripts/build/Platform/Mac/build_config.json @@ -37,7 +37,7 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD" } @@ -51,7 +51,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD" } @@ -66,7 +66,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=FALSE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=FALSE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD" } @@ -81,7 +81,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "AssetProcessorBatch", "ASSET_PROCESSOR_BINARY": "bin/profile/AssetProcessorBatch", @@ -99,7 +99,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_periodic", "CTEST_OPTIONS": "-L \"(SUITE_periodic)\"" @@ -115,7 +115,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_benchmark", "CTEST_OPTIONS": "-L \"(SUITE_benchmark)\"" @@ -131,7 +131,7 @@ "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD" } @@ -146,7 +146,7 @@ "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/mono_mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD" } diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index ee34bae3e3..d3adf69f43 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -87,7 +87,7 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG=FALSE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG=FALSE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" @@ -101,7 +101,7 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG=FALSE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG=FALSE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_smoke TEST_SUITE_main", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", @@ -119,7 +119,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" @@ -135,7 +135,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=FALSE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=FALSE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" @@ -150,7 +150,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_smoke TEST_SUITE_main", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", @@ -171,7 +171,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_smoke TEST_SUITE_main", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", @@ -190,7 +190,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "AssetProcessorBatch", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", @@ -209,7 +209,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_periodic", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", @@ -231,7 +231,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_sandbox", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", @@ -250,7 +250,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_benchmark", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", @@ -269,7 +269,7 @@ "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" @@ -285,7 +285,7 @@ "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build\\mono_windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" @@ -300,7 +300,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_DISABLE_TEST_MODULES=TRUE -DCMAKE_INSTALL_PREFIX=install -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_DISABLE_TEST_MODULES=TRUE -DCMAKE_INSTALL_PREFIX=install", "CMAKE_LY_PROJECTS": "", "CMAKE_TARGET": "INSTALL", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" diff --git a/scripts/build/Platform/Windows/package_build_config.json b/scripts/build/Platform/Windows/package_build_config.json index 40f479a098..a5ca861377 100644 --- a/scripts/build/Platform/Windows/package_build_config.json +++ b/scripts/build/Platform/Windows/package_build_config.json @@ -4,7 +4,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "windows_vs2017", - "CMAKE_OPTIONS": "-G \"Visual Studio 15 2017\" -A x64 -T host=x64 -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 15 2017\" -A x64 -T host=x64 -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AtomTest;AtomSampleViewer", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m:4 /p:CL_MPCount=!HALF_PROCESSORS! /nologo" @@ -15,7 +15,7 @@ "PARAMETERS": { "CONFIGURATION":"profile", "OUTPUT_DIRECTORY":"windows_vs2019", - "CMAKE_OPTIONS":"-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS":"-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS":"AtomTest;AtomSampleViewer", "CMAKE_TARGET":"ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" diff --git a/scripts/build/Platform/iOS/build_config.json b/scripts/build/Platform/iOS/build_config.json index bb5f2d2fe6..75b5e7b10d 100644 --- a/scripts/build/Platform/iOS/build_config.json +++ b/scripts/build/Platform/iOS/build_config.json @@ -27,7 +27,7 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" @@ -44,7 +44,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" @@ -60,7 +60,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=FALSE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=FALSE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" @@ -94,7 +94,7 @@ "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" From e818bfe905427477816b0acf48d778bbc139f31a Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 21 May 2021 02:39:50 -0500 Subject: [PATCH 088/811] Updating the ProjectManager code to use the new location of the o3de python scripts --- .../ProjectManager/Source/GemCatalog/GemInfo.cpp | 2 +- Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h | 1 - Code/Tools/ProjectManager/Source/PythonBindings.cpp | 11 +++++------ 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.cpp index 7ba4021205..d4c7220d45 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.cpp @@ -25,7 +25,7 @@ namespace O3DE::ProjectManager bool GemInfo::IsValid() const { - return !m_path.isEmpty() && !m_uuid.IsNull(); + return !m_path.isEmpty(); } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h index 098b67dbf5..e6344ce5f8 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h @@ -43,7 +43,6 @@ namespace O3DE::ProjectManager QString m_path; QString m_name; QString m_displayName; - AZ::Uuid m_uuid; QString m_creator; bool m_isAdded = false; //! Is the gem currently added and enabled in the project? QString m_summary; diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index bc154ea059..2dd6f91d23 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -112,7 +112,7 @@ namespace O3DE::ProjectManager AZ_Warning("ProjectManagerWindow", result != -1, "Append to sys path failed"); // import required modules - m_registration = pybind11::module::import("o3de.registration"); + m_registration = pybind11::module::import("o3de.manifest"); return result == 0 && !PyErr_Occurred(); } catch ([[maybe_unused]] const std::exception& e) @@ -227,14 +227,13 @@ namespace O3DE::ProjectManager GemInfo gemInfo; gemInfo.m_path = Py_To_String(path); - auto data = m_registration.attr("get_gem_data")(pybind11::none(), path); + auto data = m_registration.attr("get_gem_json_data")(pybind11::none(), path); if (pybind11::isinstance(data)) { try { // required - gemInfo.m_name = Py_To_String(data["Name"]); - gemInfo.m_uuid = AZ::Uuid(Py_To_String(data["Uuid"])); + gemInfo.m_name = Py_To_String(data["gem_name"]); // optional gemInfo.m_displayName = Py_To_String_Optional(data, "DisplayName", gemInfo.m_name); @@ -270,7 +269,7 @@ namespace O3DE::ProjectManager ProjectInfo projectInfo; projectInfo.m_path = Py_To_String(path); - auto projectData = m_registration.attr("get_project_data")(pybind11::none(), path); + auto projectData = m_registration.attr("get_project_json_data")(pybind11::none(), path); if (pybind11::isinstance(projectData)) { try @@ -327,7 +326,7 @@ namespace O3DE::ProjectManager ProjectTemplateInfo templateInfo; templateInfo.m_path = Py_To_String(path); - auto data = m_registration.attr("get_template_data")(pybind11::none(), path); + auto data = m_registration.attr("get_template_json_data")(pybind11::none(), path); if (pybind11::isinstance(data)) { try From c90d4467351d4affd235b702f2a0c2ccc5b88e45 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 21 May 2021 02:49:09 -0500 Subject: [PATCH 089/811] Removing the o3de_manifest.cmake file Removed the EngineFinder.cmake file from the Engine cmake directory as it is only needed in a Project Added an EngineJson.cmake which reads the "external_subdirectories" list from the engine.json file and calls add_subdirectory on it Re-ordered the population of the generated gem dependency list to prepend the dependencies before the dependent targets --- CMakeLists.txt | 30 +- cmake/EngineFinder.cmake | 52 -- cmake/EngineJson.cmake | 45 ++ cmake/PAL.cmake | 138 +++-- cmake/SettingsRegistry.cmake | 4 +- cmake/cmake_files.cmake | 5 +- cmake/o3de_manifest.cmake | 970 ----------------------------------- 7 files changed, 164 insertions(+), 1080 deletions(-) delete mode 100644 cmake/EngineFinder.cmake create mode 100644 cmake/EngineJson.cmake delete mode 100644 cmake/o3de_manifest.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 50670c0b85..d743a8ab57 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -25,10 +25,6 @@ include(cmake/LySet.cmake) include(cmake/Version.cmake) include(cmake/OutputDirectory.cmake) -# Set the engine_path and engine_json -set(o3de_engine_path ${CMAKE_CURRENT_LIST_DIR}) -set(o3de_engine_json ${o3de_engine_path}/engine.json) - if(NOT PROJECT_NAME) project(O3DE LANGUAGES C CXX @@ -36,21 +32,6 @@ if(NOT PROJECT_NAME) ) endif() -################################################################################ -# Resolve this engines name and restricted path -################################################################################ -include(cmake/o3de_manifest.cmake) -o3de_engine_name(${o3de_engine_json} o3de_engine_name) -o3de_restricted_path(${o3de_engine_json} o3de_engine_restricted_path) -message(STATUS "O3DE Engine Name: ${o3de_engine_name}") -message(STATUS "O3DE Engine Path: ${o3de_engine_path}") -if(o3de_engine_restricted_path) - message(STATUS "O3DE Engine Restricted Path: ${o3de_engine_restricted_path}") -endif() - -# add the engines cmake folder to the CMAKE_MODULE_PATH -list(APPEND CMAKE_MODULE_PATH "${o3de_engine_path}/cmake") - ################################################################################ # Initialize ################################################################################ @@ -92,12 +73,11 @@ if(NOT INSTALLED_ENGINE) add_subdirectory(Tools/RemoteConsole/ly_remote_console/tests/) endif() - # Add any engine restricted platforms as external subdirs - o3de_add_engine_restricted_platform_external_subdirs() - - # Add external subdirectories listed in the manifest. LY_EXTERNAL_SUBDIRS is a cache variable so the user can add extra + include(cmake/EngineJson.cmake) + # Add external subdirectories listed in the engine.json. LY_EXTERNAL_SUBDIRS is a cache variable so the user can add extra # external subdirectories - list(APPEND LY_EXTERNAL_SUBDIRS ${o3de_engine_external_subdirectories}) + read_engine_external_subdirs(engine_external_subdirectories) + list(APPEND LY_EXTERNAL_SUBDIRS ${engine_external_subdirectories}) # Loop over the additional external subdirectories and invoke add_subdirectory on them foreach(external_directory ${LY_EXTERNAL_SUBDIRS}) @@ -111,7 +91,7 @@ if(NOT INSTALLED_ENGINE) string(SUBSTRING ${full_directory_hash} 0 8 full_directory_hash) # Use the last directory as the suffix path to use for the Binary Directory get_filename_component(directory_name ${external_directory} NAME) - add_subdirectory(${external_directory} ${CMAKE_BINARY_DIR}/${directory_name}-${full_directory_hash}) + add_subdirectory(${external_directory} ${CMAKE_BINARY_DIR}/External/${directory_name}-${full_directory_hash}) endforeach() else() diff --git a/cmake/EngineFinder.cmake b/cmake/EngineFinder.cmake deleted file mode 100644 index 9ff8ce4d66..0000000000 --- a/cmake/EngineFinder.cmake +++ /dev/null @@ -1,52 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# -# This file is copied during engine registration. Edits to this file will be lost next -# time a registration happens. - -include_guard() - -# Read the engine name from the project_json file -file(READ ${CMAKE_CURRENT_LIST_DIR}/project.json project_json) -string(JSON LY_ENGINE_NAME_TO_USE ERROR_VARIABLE json_error GET ${project_json} engine) -if(json_error) - message(FATAL_ERROR "Unable to read key 'engine' from 'project.json', error: ${json_error}") -endif() - -# Read the list of paths from ~.o3de/o3de_manifest.json -file(TO_CMAKE_PATH "$ENV{USERPROFILE}" home_directory) # Windows -if((NOT home_directory) OR (NOT EXISTS ${home_directory})) - file(TO_CMAKE_PATH "$ENV{HOME}" home_directory)# Unix -endif() - -if (NOT home_directory) - message(FATAL_ERROR "Cannot find user home directory, the o3de manifest cannot be found") -endif() -# Set manifest path to path in the user home directory -set(manifest_path ${home_directory}/.o3de/o3de_manifest.json) - -if(EXISTS ${manifest_path}) - file(READ ${manifest_path} manifest_json) - string(JSON engines_count ERROR_VARIABLE json_error LENGTH ${manifest_json} engines) - if(json_error) - message(FATAL_ERROR "Unable to read key 'engines' from '${manifest_path}', error: ${json_error}") - endif() - - math(EXPR engines_count "${engines_count}-1") - foreach(engine_path_index RANGE ${engines_count}) - string(JSON engine_path ERROR_VARIABLE json_error GET ${manifest_json} engines ${engine_path_index}) - if(${json_error}) - message(FATAL_ERROR "Unable to read engines[${engine_path_index}] '${manifest_path}', error: ${json_error}") - endif() - if(engine_path) - list(APPEND CMAKE_MODULE_PATH "${engine_path}/cmake") - endif() - endforeach() -endif() diff --git a/cmake/EngineJson.cmake b/cmake/EngineJson.cmake new file mode 100644 index 0000000000..9a82d4a2c5 --- /dev/null +++ b/cmake/EngineJson.cmake @@ -0,0 +1,45 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# +# This file is copied during engine registration. Edits to this file will be lost next +# time a registration happens. + +include_guard() + +#! read_engine_external_subdirs +# Read the external subdirectories from the engine.json file +# External subdirectories are any folders with CMakeLists.txt in them +# This could be regular subdirectories, Gems(contains an additional gem.json), +# Restricted folders(contains an additional restricted.json), etc... +# \arg:output_external_subdirs name of output variable to store external subdirectories into +function(read_engine_external_subdirs output_external_subdirs) + file(READ ${LY_ROOT_FOLDER}/engine.json engine_json_data) + string(JSON external_subdirs_count ERROR_VARIABLE engine_json_error + LENGTH ${engine_json_data} "external_subdirectories") + if(engine_json_error) + message(FATAL_ERROR "Error querying number of elements in JSON array \"external_subdirectories\": ${engine_json_error}") + endif() + + if(external_subdirs_count GREATER 0) + math(EXPR external_subdir_range "${external_subdirs_count}-1") + # Convert the paths the relative paths to absolute paths using the engine root + # as the base directory + foreach(external_subdir_index RANGE ${external_subdir_range}) + string(JSON external_subdir ERROR_VARIABLE engine_json_error + GET ${engine_json_data} "external_subdirectories" "${external_subdir_index}") + if(engine_json_error) + message(FATAL_ERROR "Error reading field at index ${external_subdir_index} in \"external_subdirectories\" JSON array: ${engine_json_error}") + endif() + file(REAL_PATH ${external_subdir} real_external_subdir BASE_DIRECTORY ${CMAKE_SOURCE_DIR}) + list(APPEND external_subdirs ${real_external_subdir}) + endforeach() + endif() + set(${output_external_subdirs} ${external_subdirs} PARENT_SCOPE) +endfunction() diff --git a/cmake/PAL.cmake b/cmake/PAL.cmake index 7802ac8c58..e10ef758da 100644 --- a/cmake/PAL.cmake +++ b/cmake/PAL.cmake @@ -22,7 +22,107 @@ file(GLOB detection_files "cmake/Platform/*/PALDetection_*.cmake") foreach(detection_file ${detection_files}) include(${detection_file}) endforeach() -file(GLOB detection_files ${o3de_engine_restricted_path}/*/cmake/PALDetection_*.cmake) + + +#! o3de_restricted_id: Reads the "restricted" key from the o3de manifest +# +# \arg:restricted returns the restricted association element from an o3de json, otherwise engine 'o3de' is assumed +# \arg:o3de_json_file name of the o3de json file +function(o3de_restricted_id o3de_json_file restricted) + file(READ ${o3de_json_file} json_data) + string(JSON restricted_entry ERROR_VARIABLE json_error GET ${json_data} "restricted_name") + if(json_error) + message(WARNING "Unable to read restricted from '${o3de_json_file}', error: ${json_error}") + message(WARNING "Setting restricted to engine default 'o3de'") + set(restricted_entry "o3de") + endif() + if(restricted_entry) + set(${restricted} ${restricted_entry} PARENT_SCOPE) + endif() +endfunction() + +#! o3de_find_restricted_folder: +# +# \arg:restricted_path returns the path of the o3de restricted folder with name restricted_name +# \arg:restricted_name name of the restricted +function(o3de_find_restricted_folder restricted_name restricted_path) + # Read the restricted path from engine.json if one EXISTS + file(READ ${LY_ROOT_FOLDER}/engine.json engine_json_data) + string(JSON restricted_subdirs_count ERROR_VARIABLE engine_json_error LENGTH ${engine_json_data} "restricted") + if(restricted_subdirs_count GREATER 0) + string(JSON restricted_subdir ERROR_VARIABLE engine_json_error GET ${engine_json_data} "restricted" "0") + set(${restricted_path} ${restricted_subdir} PARENT_SCOPE) + return() + endif() + + + file(TO_CMAKE_PATH "$ENV{USERPROFILE}" home_directory) # Windows + if(NOT EXISTS ${home_directory}) + file(TO_CMAKE_PATH "$ENV{HOME}" home_directory) # Unix + if (NOT EXISTS ${home_directory}) + return() + endif() + endif() + + # Examine the o3de manifest file for the list of restricted directories + set(o3de_manifest_path ${home_directory}/.o3de/o3de_manifest.json) + if(EXISTS ${o3de_manifest_path}) + file(READ ${o3de_manifest_path} o3de_manifest_json_data) + string(JSON restricted_subdirs_count ERROR_VARIABLE engine_json_error LENGTH ${o3de_manifest_json_data} "restricted") + if(restricted_subdirs_count GREATER 0) + math(EXPR restricted_subdirs_range "${restricted_subdirs_count}-1") + foreach(restricted_subdir_index RANGE ${restricted_subdirs_range}) + string(JSON restricted_subdir ERROR_VARIABLE engine_json_error GET ${o3de_manifest_json_data} "restricted" "${restricted_subdir_index}") + list(APPEND restricted_subdirs ${restricted_subdir}) + endforeach() + endif() + endif() + # Iterate over the restricted directories from the manifest file + foreach(restricted_entry ${restricted_subdirs}) + set(restricted_json_file ${restricted_entry}/restricted.json) + file(READ ${restricted_json_file} restricted_json) + string(JSON this_restricted_name ERROR_VARIABLE json_error GET ${restricted_json} "restricted_name") + if(json_error) + message(WARNING "Unable to read restricted_name from '${restricted_json_file}', error: ${json_error}") + else() + if(this_restricted_name STREQUAL restricted_name) + set(${restricted_path} ${restricted_entry} PARENT_SCOPE) + return() + endif() + endif() + endforeach() +endfunction() + + +#! o3de_restricted_path: +# +# \arg:restricted_path returns the path of the o3de restricted folder with name restricted_name +# \arg:restricted_name name of the restricted +function(o3de_restricted_path o3de_json_file restricted_path) + o3de_restricted_id(${o3de_json_file} restricted_name) + if(restricted_name) + o3de_find_restricted_folder(${restricted_name} restricted_folder) + if(restricted_folder) + set(${restricted_path} ${restricted_folder} PARENT_SCOPE) + endif() + endif() +endfunction() + +#! read_engine_restricted_path: Locates the restricted path within the engine from a json file +# +# \arg:restricted_path returns the path of the o3de restricted folder with name restricted_name +# \arg:restricted_name name of the restricted +function(read_engine_restricted_path output_restricted_path) + # Set manifest path to path in the user home directory + set(manifest_path ${LY_ROOT_FOLDER}/engine.json) + if(EXISTS ${manifest_path}) + o3de_restricted_path(${manifest_path} output_restricted_path) + endif() +endfunction() + +read_engine_restricted_path(O3DE_ENGINE_RESTRICTED_PATH) + +file(GLOB detection_files ${O3DE_ENGINE_RESTRICTED_PATH}/*/cmake/PALDetection_*.cmake) foreach(detection_file ${detection_files}) include(${detection_file}) endforeach() @@ -37,8 +137,8 @@ ly_set(PAL_HOST_PLATFORM_NAME_LOWERCASE ${PAL_HOST_PLATFORM_NAME_LOWERCASE}) set(PAL_RESTRICTED_PLATFORMS) -string(LENGTH ${o3de_engine_restricted_path} engine_restricted_length) -file(GLOB pal_restricted_files ${o3de_engine_restricted_path}/*/cmake/PAL_*.cmake) +string(LENGTH "${O3DE_ENGINE_RESTRICTED_PATH}" engine_restricted_length) +file(GLOB pal_restricted_files ${O3DE_ENGINE_RESTRICTED_PATH}/*/cmake/PAL_*.cmake) foreach(pal_restricted_file ${pal_restricted_files}) string(FIND ${pal_restricted_file} "/cmake/PAL" end) if(${end} GREATER -1) @@ -109,18 +209,18 @@ function(ly_get_absolute_pal_filename out_name in_name) else() # The user has not supplied any path so we must assume it is the o3de engine restricted and o3de engine path # if the file is not in the o3de engine path then we cannot determine a PAL file for it - file(RELATIVE_PATH relative_path ${o3de_engine_path} ${full_name}) + file(RELATIVE_PATH relative_path ${LY_ROOT_FOLDER} ${full_name}) if (NOT (IS_ABSOLUTE relative_path OR relative_path MATCHES [[^(\.\./)+(.*)]])) if (NOT EXISTS ${full_name}) - string(REGEX MATCH "${o3de_engine_path}/(.*)/Platform/([^/]*)/?(.*)$" match ${full_name}) + string(REGEX MATCH "${LY_ROOT_FOLDER}/(.*)/Platform/([^/]*)/?(.*)$" match ${full_name}) if(NOT CMAKE_MATCH_1) - string(REGEX MATCH "${o3de_engine_path}/Platform/([^/]*)/?(.*)$" match ${full_name}) - set(full_name ${o3de_engine_restricted_path}/${CMAKE_MATCH_1}) + string(REGEX MATCH "${LY_ROOT_FOLDER}/Platform/([^/]*)/?(.*)$" match ${full_name}) + set(full_name ${O3DE_ENGINE_RESTRICTED_PATH}/${CMAKE_MATCH_1}) if(CMAKE_MATCH_2) string(APPEND full_name "/" ${CMAKE_MATCH_2}) endif() elseif("${CMAKE_MATCH_2}" IN_LIST PAL_RESTRICTED_PLATFORMS) - set(full_name ${o3de_engine_restricted_path}/${CMAKE_MATCH_2}/${CMAKE_MATCH_1}) + set(full_name ${O3DE_ENGINE_RESTRICTED_PATH}/${CMAKE_MATCH_2}/${CMAKE_MATCH_1}) if(CMAKE_MATCH_3) string(APPEND full_name "/" ${CMAKE_MATCH_3}) endif() @@ -149,25 +249,3 @@ set(LY_DISABLE_TEST_MODULES FALSE CACHE BOOL "Option to forcibly disable the inc if(LY_DISABLE_TEST_MODULES) ly_set(PAL_TRAIT_BUILD_TESTS_SUPPORTED FALSE) endif() - -################################################################################ -# Add each restricted platform in the engines restricted folder -# If the enabled restricted platform does not have a folder add one. -# If the restricted platform folder does not have a CMakeLists.txt, create one -# so the add_subdirectory on the external folder does not fail. -################################################################################ -function(o3de_add_engine_restricted_platform_external_subdirs) - foreach(restricted_platform ${PAL_RESTRICTED_PLATFORMS}) - if(restricted_platform IN_LIST enabled_platforms) - set(o3de_engine_restricted_platform_folder ${o3de_engine_restricted_path}/${restricted_platform}) - if(NOT EXISTS ${o3de_engine_restricted_platform_folder}) - file(MAKE_DIRECTORY ${o3de_engine_restricted_platform_folder}) - endif() - set(o3de_engine_restricted_platform_folder_cmakelists ${o3de_engine_restricted_platform_folder}/CMakeLists.txt) - if(NOT EXISTS ${o3de_engine_restricted_platform_folder_cmakelists}) - file(TOUCH ${o3de_engine_restricted_platform_folder_cmakelists}) - endif() - list(APPEND LY_EXTERNAL_SUBDIRS ${o3de_engine_restricted_platform_folder}) - endif() - endforeach() -endfunction() diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index 31ce36c516..dda498eeb4 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -108,11 +108,11 @@ function(ly_delayed_generate_settings_registry) # Get the gem dependencies for the given project and target combination get_property(gem_dependencies GLOBAL PROPERTY LY_DELAYED_LOAD_"${prefix_target}") list(REMOVE_DUPLICATES gem_dependencies) # Strip out any duplicate gem targets - set(all_gem_dependencies ${gem_dependencies}) + unset(all_gem_dependencies) foreach(gem_target ${gem_dependencies}) ly_get_gem_load_dependencies(gem_load_gem_dependencies ${gem_target}) - list(APPEND all_gem_dependencies ${gem_load_gem_dependencies}) + list(APPEND all_gem_dependencies ${gem_load_gem_dependencies} ${gem_target}) endforeach() list(REMOVE_DUPLICATES all_gem_dependencies) diff --git a/cmake/cmake_files.cmake b/cmake/cmake_files.cmake index baa2a272fc..b42d29c9c2 100644 --- a/cmake/cmake_files.cmake +++ b/cmake/cmake_files.cmake @@ -17,16 +17,19 @@ set(FILES Configurations.cmake Dependencies.cmake Deployment.cmake - EngineFinder.cmake + EngineJson.cmake FileUtil.cmake Findo3de.cmake + GeneralSettings.cmake Install.cmake LyAutoGen.cmake + LYPackage_S3Downloader.cmake LySet.cmake LYTestWrappers.cmake LYPython.cmake LYWrappers.cmake Monolithic.cmake + OutputDirectory.cmake Packaging.cmake PAL.cmake PALTools.cmake diff --git a/cmake/o3de_manifest.cmake b/cmake/o3de_manifest.cmake deleted file mode 100644 index 632f064659..0000000000 --- a/cmake/o3de_manifest.cmake +++ /dev/null @@ -1,970 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -# Set the user home directory -set(O3DE_HOME_PATH "" CACHE PATH "Override the user home to this path") -if(O3DE_HOME_PATH) - set(home_directory ${O3DE_HOME_PATH}) -elseif(CMAKE_HOST_WIN32) - file(TO_CMAKE_PATH "$ENV{USERPROFILE}" home_directory) -else() - file(TO_CMAKE_PATH "$ENV{HOME}" home_directory) -endif() -if (NOT home_directory) - message(FATAL_ERROR "Cannot find user home directory, without the user home directory the o3de manifest cannot be found") -endif() - -# Optionally delete the home directory -if(O3DE_DELETE_HOME_PATH) - if(EXISTS ${home_directory}/.o3de) - message(STATUS "Deleting ${home_directory}/.o3de") - file(REMOVE_RECURSE ${home_directory}/.o3de) - else() - message(STATUS "Home path ${home_directory}/.o3de doesnt exist.") - endif() -endif() - -######################################################################################################################## -# If O3DE_REGISTER_ENGINE_PATH variable is set on the commandline this will allow registration of anything using -# O3DE_REGISTER_ENGINE_PATH o3de script. This is handy for situations like build servers which download the code and -# are expected to build without the need for someone to register o3de objects like this engine by manually typing it in. -# If O3DE_REGISTER_THIS_ENGINE=TRUE is set on the commandline when O3DE_REGISTER_ENGINE_PATH is also set this will call: -# O3DE_REGISTER_ENGINE_PATH/scripts>o3de register --this-engine --override-home-folder -# Note: register --this-engine will automatically register anything it finds in known folders, so if you put your -# o3de objects like projects/gems/templates/restricted/etc... in known folders for those types they will get registered -# automatically. Known folders for types are your .o3de/Projects and .o3de/Gems etc. So if I wanted my project to be -# registered and built by this build server I could simply put them in those known folders on the build server and they -# would get registered automatically by this call. -# OR -# I could put them on the commandline as well. This would be the way if the o3de objects we need to regiater are NOT -# in known folders or you do not intend to call with O3DE_REGISTER_THIS_ENGINE=TRUE Ex. -# -DO3DE_REGISTER_ENGINE_PATH=C:\this\engine -# -DO3DE_REGISTER_PROJECT_PATHS=C:\ThisGame;C:\ThatGame -# -DO3DE_REGISTER_GEM_PATHS=C:\ThisGem;C:\ThatGem;C:\And\Some\Other\Gem -# -DO3DE_REGISTER_RESTRICTED_PATHS=C:\this\engine\Restricted;C:\ThisGame\Restricted;C:\ThisGem\Restricted -######################################################################################################################## -if(O3DE_REGISTER_ENGINE_PATH) - if(O3DE_REGISTER_THIS_ENGINE) - if(CMAKE_HOST_WIN32) - execute_process( - COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --this-engine --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_this_engine_cmd_result - ) - else() - execute_process( - COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --this-engine --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_this_engine_cmd_result - ) - endif() - if(o3de_register_this_engine_cmd_result) - message(FATAL_ERROR "An error occured trying to register --this-engine: ${o3de_register_this_engine_cmd_result}") - else() - message(STATUS "Engine ${O3DE_REGISTER_ENGINE_PATH} registration successfull.") - endif() - endif() - - if(O3DE_REGISTER_RESTRICTED_PATHS) - foreach(restricted_path ${O3DE_REGISTER_RESTRICTED_PATHS}) - if(CMAKE_HOST_WIN32) - execute_process( - COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --restricted-path ${restricted_path} --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_restricted_cmd_result - ) - else() - execute_process( - COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --restricted-path ${restricted_path} --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_restricted_cmd_result - ) - endif() - if(o3de_register_restricted_cmd_result) - message(FATAL_ERROR "An error occured trying to ${O3DE_REGISTER_ENGINE_PATH}/scripts>o3de register --restricted-path ${restricted_path} --override-home-folder ${home_directory}: ${o3de_register_restricted_cmd_result}") - else() - message(STATUS "Restricted ${restricted_path} registration successfull.") - endif() - endforeach() - endif() - - if(O3DE_REGISTER_PROJECT_PATHS) - foreach(project_path ${O3DE_REGISTER_PROJECT_PATHS}) - if(CMAKE_HOST_WIN32) - execute_process( - COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --project-path ${project_path} --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_project_cmd_result - ) - else() - execute_process( - COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --project-path ${project_path} --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_project_cmd_result - ) - endif() - if(o3de_register_project_cmd_result) - message(FATAL_ERROR "An error occured trying to ${O3DE_REGISTER_ENGINE_PATH}/scripts>o3de register --project-path ${project_path} --override-home-folder ${home_directory}") - else() - message(STATUS "Project ${project_path} registration successfull.") - endif() - endforeach() - endif() - - if(O3DE_REGISTER_GEM_PATHS) - foreach(gem_path ${O3DE_REGISTER_GEM_PATHS}) - if(CMAKE_HOST_WIN32) - execute_process( - COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --gem-path ${gem_path} --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_gem_cmd_result - ) - else() - execute_process( - COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --gem-path ${gem_path} --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_gem_cmd_result - ) - endif() - if(o3de_register_gem_cmd_result) - message(FATAL_ERROR "An error occured trying to ${O3DE_REGISTER_ENGINE_PATH}/scripts>o3de register --gem-path ${gem_path} --override-home-folder ${home_directory}") - else() - message(STATUS "Gem ${gem_path} registration successfull.") - endif() - endforeach() - endif() - - if(O3DE_REGISTER_TEMPLATE_PATHS) - foreach(template_path ${O3DE_REGISTER_TEMPLATE_PATHS}) - if(CMAKE_HOST_WIN32) - execute_process( - COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --template-path ${template_path} --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_template_cmd_result - ) - else() - execute_process( - COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --template-path ${template_path} --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_template_cmd_result - ) - endif() - if(o3de_register_template_cmd_result) - message(FATAL_ERROR "An error occured trying to ${O3DE_REGISTER_ENGINE_PATH}/scripts>o3de register --template-path ${template_path} --override-home-folder ${home_directory}") - else() - message(STATUS "Template ${template_path} registration successfull.") - endif() - endforeach() - endif() - - if(O3DE_REGISTER_REPO_URIS) - foreach(repo_uri ${O3DE_REGISTER_REPO_URIS}) - if(CMAKE_HOST_WIN32) - execute_process( - COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --repo-uri ${repo_uri} --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_repo_cmd_result - ) - else() - execute_process( - COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --repo-uri ${repo_uri} --override-home-folder ${home_directory} - RESULT_VARIABLE o3de_register_repo_cmd_result - ) - endif() - if(o3de_register_repo_cmd_result) - message(FATAL_ERROR "An error occured trying to ${O3DE_REGISTER_ENGINE_PATH}/scripts>o3de register --repo-uri ${repo_uri} --override-home-folder ${home_directory}") - else() - message(STATUS "Repo ${repo_uri} registration successfull.") - endif() - endforeach() - endif() -endif() - -################################################################################ -# o3de manifest -################################################################################ -# Set manifest json path to the /.o3de/o3de_manifest.json -set(o3de_manifest_json_path ${home_directory}/.o3de/o3de_manifest.json) -if(NOT EXISTS ${o3de_manifest_json_path}) - message(FATAL_ERROR "${o3de_manifest_json_path} not found. You must o3de register --this-engine.") -endif() -file(READ ${o3de_manifest_json_path} manifest_json_data) - -################################################################################ -# o3de manifest name -################################################################################ -string(JSON o3de_manifest_name ERROR_VARIABLE json_error GET ${manifest_json_data} o3de_manifest_name) -if(json_error) - message(FATAL_ERROR "Unable to read repo_name from '${o3de_manifest_json_path}', error: ${json_error}") -endif() - -################################################################################ -# o3de origin -################################################################################ -string(JSON o3de_origin ERROR_VARIABLE json_error GET ${manifest_json_data} origin) -if(json_error) - message(FATAL_ERROR "Unable to read origin from '${o3de_manifest_json_path}', error: ${json_error}") -endif() - -################################################################################ -# o3de default engines folder -################################################################################ -string(JSON o3de_default_engines_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_engines_folder) -if(json_error) - message(FATAL_ERROR "Unable to read default_engines_folder from '${o3de_manifest_json_path}', error: ${json_error}") -endif() - -################################################################################ -# o3de default projects folder -################################################################################ -string(JSON o3de_default_projects_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_projects_folder) -if(json_error) - message(FATAL_ERROR "Unable to read default_projects_folder from '${o3de_manifest_json_path}', error: ${json_error}") -endif() - -################################################################################ -# o3de default gems folder -################################################################################ -string(JSON o3de_default_gems_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_gems_folder) -if(json_error) - message(FATAL_ERROR "Unable to read default_gems_folder from '${o3de_manifest_json_path}', error: ${json_error}") -endif() - -################################################################################ -# o3de default templates folder -################################################################################ -string(JSON o3de_default_templates_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_templates_folder) -if(json_error) - message(FATAL_ERROR "Unable to read default_templates_folder from '${o3de_manifest_json_path}', error: ${json_error}") -endif() - -################################################################################ -# o3de default restricted folder -################################################################################ -string(JSON o3de_default_restricted_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_restricted_folder) -if(json_error) - message(FATAL_ERROR "Unable to read default_restricted_folder from '${o3de_manifest_json_path}', error: ${json_error}") -endif() - -################################################################################ -# o3de projects -################################################################################ -string(JSON o3de_projects_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} projects) -if(json_error) - message(FATAL_ERROR "Unable to read key 'projects' from '${o3de_manifest_json_path}', error: ${json_error}") -endif() -if(${o3de_projects_count} GREATER 0) - math(EXPR o3de_projects_count "${o3de_projects_count}-1") - foreach(projects_index RANGE ${o3de_projects_count}) - string(JSON projects_path ERROR_VARIABLE json_error GET ${manifest_json_data} projects ${projects_index}) - if(json_error) - message(FATAL_ERROR "Unable to read projects[${projects_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - list(APPEND o3de_projects ${projects_path}) - list(APPEND o3de_global_projects ${projects_path}) - endforeach() -endif() - -################################################################################ -# o3de gems -################################################################################ -string(JSON o3de_gems_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} gems) -if(json_error) - message(FATAL_ERROR "Unable to read key 'gems' from '${o3de_manifest_json_path}', error: ${json_error}") -endif() -if(${o3de_gems_count} GREATER 0) - math(EXPR o3de_gems_count "${o3de_gems_count}-1") - foreach(gems_index RANGE ${o3de_gems_count}) - string(JSON gems_path ERROR_VARIABLE json_error GET ${manifest_json_data} gems ${gems_index}) - if(json_error) - message(FATAL_ERROR "Unable to read gems[${gems_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - list(APPEND o3de_gems ${gems_path}) - list(APPEND o3de_global_gems ${gems_path}) - endforeach() -endif() - -################################################################################ -# o3de templates -################################################################################ -string(JSON o3de_templates_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} templates) -if(json_error) - message(FATAL_ERROR "Unable to read key 'templates' from '${o3de_manifest_json_path}', error: ${json_error}") -endif() -if(${o3de_templates_count} GREATER 0) - math(EXPR o3de_templates_count "${o3de_templates_count}-1") - foreach(templates_index RANGE ${o3de_templates_count}) - string(JSON templates_path ERROR_VARIABLE json_error GET ${manifest_json_data} templates ${templates_index}) - if(json_error) - message(FATAL_ERROR "Unable to read templates[${templates_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - list(APPEND o3de_templates ${templates_path}) - list(APPEND o3de_global_templates ${templates_path}) - endforeach() -endif() - -################################################################################ -# o3de repos -################################################################################ -string(JSON o3de_repos_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} repos) -if(json_error) - message(FATAL_ERROR "Unable to read key 'repos' from '${o3de_manifest_json_path}', error: ${json_error}") -endif() -if(${o3de_repos_count} GREATER 0) - math(EXPR o3de_repos_count "${o3de_repos_count}-1") - foreach(repos_index RANGE ${o3de_repos_count}) - string(JSON repo_uri ERROR_VARIABLE json_error GET ${manifest_json_data} repos ${repos_index}) - if(json_error) - message(FATAL_ERROR "Unable to read repos[${repos_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - list(APPEND o3de_repos ${repo_uri}) - list(APPEND o3de_global_repos ${repo_uri}) - endforeach() -endif() - -################################################################################ -# o3de restricted -################################################################################ -string(JSON o3de_restricted_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} restricted) -if(json_error) - message(FATAL_ERROR "Unable to read key 'restricted' from '${o3de_manifest_json_path}', error: ${json_error}") -endif() -if(${o3de_restricted_count} GREATER 0) - math(EXPR o3de_restricted_count "${o3de_restricted_count}-1") - foreach(restricted_index RANGE ${o3de_restricted_count}) - string(JSON restricted_path ERROR_VARIABLE json_error GET ${manifest_json_data} restricted ${restricted_index}) - if(json_error) - message(FATAL_ERROR "Unable to read restricted[${restricted_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - list(APPEND o3de_restricted ${restricted_path}) - list(APPEND o3de_global_restricted ${restricted_path}) - endforeach() -endif() - -################################################################################ -# o3de engines -################################################################################ -string(JSON o3de_engines_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} engines) -if(json_error) - message(FATAL_ERROR "Unable to read key 'engines' from '${o3de_manifest_json_path}', error: ${json_error}") -endif() - -if(${o3de_engines_count} GREATER 0) - math(EXPR o3de_engines_count "${o3de_engines_count}-1") - # Either the engine_path and engine_json are set in which case the user is configuring from the engine - # or project_path and project_json are set in which case the user is configuring from the project. - # We need to know which engine_path the user is using so if the project_json is set then we need - # to read the project_json and disambiguate the engine_path. - if(NOT o3de_engine_path) - if(NOT o3de_project_json) - message(FATAL_ERROR "Neither o3de_engine_path nor o3de_project_json defined. Cannot determine engine!") - endif() - - # get the name of the engine this project uses - file(READ ${o3de_project_json} project_json_data) - string(JSON project_engine_name ERROR_VARIABLE json_error GET ${project_json_data} engine) - if(json_error) - message(FATAL_ERROR "Unable to read 'engine' from '${o3de_project_json}', error: ${json_error}") - endif() - - # search each engine in order from the manifest to find the matching engine name - foreach(engines_index RANGE ${o3de_engines_count}) - string(JSON engine_data ERROR_VARIABLE json_error GET ${manifest_json_data} engines ${engines_index}) - if(json_error) - message(FATAL_ERROR "Unable to read engines[${engines_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - - # get this engines path - string(JSON this_engine_path ERROR_VARIABLE json_error GET ${engine_data} path) - if(json_error) - message(FATAL_ERROR "Unable to read engine path from '${o3de_manifest_json_path}', error: ${json_error}") - endif() - - # add this engine to the engines list - list(APPEND o3de_engines ${this_engine_path}) - - # use path to get the engine.json - set(this_engine_json ${this_engine_path}/engine.json) - - # read the name of this engine - file(READ ${this_engine_json} this_engine_json_data) - string(JSON this_engine_name ERROR_VARIABLE json_error GET ${this_engine_json_data} engine_name) - if(json_error) - message(FATAL_ERROR "Unable to read engine_name from '${this_engine_json}', error: ${json_error}") - endif() - - # see if this engines name is the same as the one this projects should use - if(${this_engine_name} STREQUAL ${project_engine_name}) - message(STATUS "Found engine: '${project_engine_name}' at ${this_engine_path}") - set(o3de_engine_path ${this_engine_path}) - break() - endif() - endforeach() - endif() -endif() - -#we should have an engine_path at this point -if(NOT o3de_engine_path) - message(FATAL_ERROR "o3de_engine_path not defined. Cannot determine engine!") -endif() - -# now that we have an engine_path read in that engines o3de resources -if(${o3de_engines_count} GREATER -1) - foreach(engines_index RANGE ${o3de_engines_count}) - string(JSON engine_data ERROR_VARIABLE json_error GET ${manifest_json_data} engines ${engines_index}) - if(json_error) - message(FATAL_ERROR "Unable to read engines[${engines_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - - # get this engines path - string(JSON this_engine_path ERROR_VARIABLE json_error GET ${engine_data} path) - if(json_error) - message(FATAL_ERROR "Unable to read engine path from '${o3de_manifest_json_path}', error: ${json_error}") - endif() - - if(${o3de_engine_path} STREQUAL ${this_engine_path}) - ################################################################################ - # o3de engine projects - ################################################################################ - string(JSON o3de_engine_projects_count ERROR_VARIABLE json_error LENGTH ${engine_data} projects) - if(json_error) - message(FATAL_ERROR "Unable to read key 'projects' from '${engine_data}', error: ${json_error}") - endif() - if(${o3de_engine_projects_count} GREATER 0) - math(EXPR o3de_engine_projects_count "${o3de_engine_projects_count}-1") - foreach(engine_projects_index RANGE ${o3de_engine_projects_count}) - string(JSON engine_projects_path ERROR_VARIABLE json_error GET ${engine_data} projects ${engine_projects_index}) - if(json_error) - message(FATAL_ERROR "Unable to read engine projects[${projects_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - list(APPEND o3de_projects ${engine_projects_path}) - list(APPEND o3de_engine_projects ${engine_projects_path}) - endforeach() - endif() - - ################################################################################ - # o3de engine gems - ################################################################################ - string(JSON o3de_engine_gems_count ERROR_VARIABLE json_error LENGTH ${engine_data} gems) - if(json_error) - message(FATAL_ERROR "Unable to read key 'gems' from '${engine_data}', error: ${json_error}") - endif() - if(${o3de_engine_gems_count} GREATER 0) - math(EXPR o3de_engine_gems_count "${o3de_engine_gems_count}-1") - foreach(engine_gems_index RANGE ${o3de_engine_gems_count}) - string(JSON engine_gems_path ERROR_VARIABLE json_error GET ${engine_data} gems ${engine_gems_index}) - if(json_error) - message(FATAL_ERROR "Unable to read engine gems[${gems_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - list(APPEND o3de_gems ${engine_gems_path}) - list(APPEND o3de_engine_gems ${engine_gems_path}) - endforeach() - endif() - - ################################################################################ - # o3de engine templates - ################################################################################ - string(JSON o3de_engine_templates_count ERROR_VARIABLE json_error LENGTH ${engine_data} templates) - if(json_error) - message(FATAL_ERROR "Unable to read key 'templates' from '${o3de_manifest_json_path}', error: ${json_error}") - endif() - if(${o3de_engine_gems_count} GREATER 0) - math(EXPR o3de_engine_templates_count "${o3de_engine_templates_count}-1") - foreach(engine_templates_index RANGE ${o3de_engine_templates_count}) - string(JSON engine_templates_path ERROR_VARIABLE json_error GET ${engine_data} templates ${engine_templates_index}) - if(json_error) - message(FATAL_ERROR "Unable to read engine templates[${templates_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - list(APPEND o3de_templates ${engine_templates_path}) - list(APPEND o3de_engine_templates ${engine_templates_path}) - endforeach() - endif() - - ################################################################################ - # o3de engine restricted - ################################################################################ - string(JSON o3de_engine_restricted_count ERROR_VARIABLE json_error LENGTH ${engine_data} restricted) - if(json_error) - message(FATAL_ERROR "Unable to read key 'restricted' from '${o3de_manifest_json_path}', error: ${json_error}") - endif() - if(${o3de_engine_restricted_count} GREATER 0) - math(EXPR o3de_engine_restricted_count "${o3de_engine_restricted_count}-1") - foreach(engine_restricted_index RANGE ${o3de_engine_restricted_count}) - string(JSON engine_restricted_path ERROR_VARIABLE json_error GET ${engine_data} restricted ${engine_restricted_index}) - if(json_error) - message(FATAL_ERROR "Unable to read engine restricted[${engine_restricted_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - list(APPEND o3de_restricted ${engine_restricted_path}) - list(APPEND o3de_engine_restricted ${engine_restricted_path}) - endforeach() - endif() - - ################################################################################ - # o3de engine external_subdirectories - ################################################################################ - string(JSON o3de_external_subdirectories_count ERROR_VARIABLE json_error LENGTH ${engine_data} external_subdirectories) - if(json_error) - message(FATAL_ERROR "Unable to read key 'external_subdirectories' from '${o3de_manifest_json_path}', error: ${json_error}") - endif() - if(${o3de_external_subdirectories_count} GREATER 0) - math(EXPR o3de_external_subdirectories_count "${o3de_external_subdirectories_count}-1") - foreach(external_subdirectories_index RANGE ${o3de_external_subdirectories_count}) - string(JSON external_subdirectories_path ERROR_VARIABLE json_error GET ${engine_data} external_subdirectories ${external_subdirectories_index}) - if(json_error) - message(FATAL_ERROR "Unable to read engine external_subdirectories[${gems_index}] '${o3de_manifest_json_path}', error: ${json_error}") - endif() - list(APPEND o3de_engine_external_subdirectories ${external_subdirectories_path}) - endforeach() - endif() - - break() - - endif() - endforeach() -endif() - - -################################################################################ -#! o3de_engine_id: -# -# \arg:engine returns the engine association element from an o3de json -# \arg:o3de_json_file name of the o3de json file -################################################################################ -function(o3de_engine_id o3de_json_file engine) - file(READ ${o3de_json_file} json_data) - string(JSON engine_entry ERROR_VARIABLE json_error GET ${json_data} engine) - if(json_error) - message(WARNING "Unable to read engine from '${o3de_json_file}', error: ${json_error}") - message(WARNING "Setting engine to engine default 'o3de'") - set(engine_entry "o3de") - endif() - if(engine_entry) - set(${engine} ${engine_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_project_id: -# -# \arg:project returns the project association element from an o3de json -# \arg:o3de_json_file name of the o3de json file -################################################################################ -function(o3de_project_id o3de_json_file project) - file(READ ${o3de_json_file} json_data) - string(JSON project_entry ERROR_VARIABLE json_error GET ${json_data} project) - if(json_error) - message(FATAL_ERROR "Unable to read project from '${o3de_json_file}', error: ${json_error}") - endif() - if(project_entry) - set(${project} ${project_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_gem_id: -# -# \arg:gem returns the gem association element from an o3de json -# \arg:o3de_json_file name of the o3de json file -################################################################################ -function(o3de_gem_id o3de_json_file gem) - file(READ ${o3de_json_file} json_data) - string(JSON gem_entry ERROR_VARIABLE json_error GET ${json_data} gem) - if(json_error) - message(FATAL_ERROR "Unable to read gem from '${o3de_json_file}', error: ${json_error}") - endif() - if(gem_entry) - set(${gem} ${gem_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_template_id: -# -# \arg:template returns the template association element from an o3de json -# \arg:o3de_json_file name of the o3de json file -################################################################################ -function(o3de_template_id o3de_json_file template) - file(READ ${o3de_json_file} json_data) - string(JSON template_entry ERROR_VARIABLE json_error GET ${json_data} template) - if(json_error) - message(FATAL_ERROR "Unable to read template from '${o3de_json_file}', error: ${json_error}") - endif() - if(template_entry) - set(${template} ${template_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_repo_id: -# -# \arg:repo returns the repo association element from an o3de json -# \arg:o3de_json_file name of the o3de json file -################################################################################ -function(o3de_repo_id o3de_json_file repo) - file(READ ${o3de_json_file} json_data) - string(JSON repo_entry ERROR_VARIABLE json_error GET ${json_data} repo) - if(json_error) - message(FATAL_ERROR "Unable to read repo from '${o3de_json_file}', error: ${json_error}") - endif() - if(repo_entry) - set(${repo} ${repo_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_restricted_id: -# -# \arg:restricted returns the restricted association element from an o3de json, otherwise engine 'o3de' is assumed -# \arg:o3de_json_file name of the o3de json file -################################################################################ -function(o3de_restricted_id o3de_json_file restricted) - file(READ ${o3de_json_file} json_data) - string(JSON restricted_entry ERROR_VARIABLE json_error GET ${json_data} restricted) - if(json_error) - message(WARNING "Unable to read restricted from '${o3de_json_file}', error: ${json_error}") - message(WARNING "Setting restricted to engine default 'o3de'") - set(restricted_entry "o3de") - endif() - if(restricted_entry) - set(${restricted} ${restricted_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_find_engine_folder: -# -# \arg:engine_path returns the path of the o3de engine folder with name engine_name -# \arg:engine_name name of the engine -################################################################################ -function(o3de_find_engine_folder engine_name engine_path) - foreach(engine_entry ${o3de_engines}) - set(engine_json_file ${engine_entry}/engine.json) - file(READ ${engine_json_file} engine_json) - string(JSON this_engine_name ERROR_VARIABLE json_error GET ${engine_json} engine_name) - if(json_error) - message(WARNING "Unable to read engine_name from '${engine_json_file}', error: ${json_error}") - else() - if(this_engine_name STREQUAL engine_name) - set(${engine_path} ${engine_entry} PARENT_SCOPE) - return() - endif() - endif() - endforeach() - message(FATAL_ERROR "Unable to find repo_name: '${engine_name}'") -endfunction() - - -################################################################################ -#! o3de_find_project_folder: -# -# \arg:project_path returns the path of the o3de project folder with name project_name -# \arg:project_name name of the project -################################################################################ -function(o3de_find_project_folder project_name project_path) - foreach(project_entry ${o3de_projects}) - set(project_json_file ${project_entry}/project.json) - file(READ ${project_json_file} project_json) - string(JSON this_project_name ERROR_VARIABLE json_error GET ${project_json} project_name) - if(json_error) - message(WARNING "Unable to read project_name from '${project_json_file}', error: ${json_error}") - else() - if(this_project_name STREQUAL project_name) - set(${project_path} ${project_entry} PARENT_SCOPE) - return() - endif() - endif() - endforeach() - message(FATAL_ERROR "Unable to find project_name: '${project_name}'") -endfunction() - - -################################################################################ -#! o3de_find_gem_folder: -# -# \arg:gem_path returns the path of the o3de gem folder with name gem_name -# \arg:gem_name name of the gem -################################################################################ -function(o3de_find_gem_folder gem_name gem_path) - foreach(gem_entry ${o3de_gems}) - set(gem_json_file ${gem_entry}/gem.json) - file(READ ${gem_json_file} gem_json) - string(JSON this_gem_name ERROR_VARIABLE json_error GET ${gem_json} gem_name) - if(json_error) - message(WARNING "Unable to read gem_name from '${gem_json_file}', error: ${json_error}") - else() - if(this_gem_name STREQUAL gem_name) - set(${gem_path} ${gem_entry} PARENT_SCOPE) - return() - endif() - endif() - endforeach() - message(FATAL_ERROR "Unable to find gem_name: '${gem_name}'") -endfunction() - - -################################################################################ -#! o3de_find_template_folder: -# -# \arg:template_path returns the path of the o3de template folder with name template_name -# \arg:template_name name of the template -################################################################################ -function(o3de_find_template_folder template_name template_path) - foreach(template_entry ${o3de_templates}) - set(template_json_file ${template_entry}/template.json) - file(READ ${template_json_file} template_json) - string(JSON this_template_name ERROR_VARIABLE json_error GET ${template_json} template_name) - if(json_error) - message(WARNING "Unable to read template_name from '${template_json_file}', error: ${json_error}") - else() - if(this_template_name STREQUAL template_name) - set(${template_path} ${template_entry} PARENT_SCOPE) - return() - endif() - endif() - endforeach() - message(FATAL_ERROR "Unable to find template_name: '${template_name}'") -endfunction() - - -################################################################################ -#! o3de_find_repo_folder: -# -# \arg:repo_path returns the path of the o3de repo folder with name repo_name -# \arg:repo_name name of the repo -################################################################################ -function(o3de_find_repo_folder repo_name repo_path) - foreach(repo_entry ${o3de_repos}) - set(repo_json_file ${repo_entry}/repo.json) - file(READ ${repo_json_file} repo_json) - string(JSON this_repo_name ERROR_VARIABLE json_error GET ${repo_json} repo_name) - if(json_error) - message(WARNING "Unable to read repo_name from '${repo_json_file}', error: ${json_error}") - else() - if(this_repo_name STREQUAL repo_name) - set(${repo_path} ${repo_entry} PARENT_SCOPE) - return() - endif() - endif() - endforeach() - message(FATAL_ERROR "Unable to find repo_name: '${repo_name}'") -endfunction() - - -################################################################################ -#! o3de_find_restricted_folder: -# -# \arg:restricted_path returns the path of the o3de restricted folder with name restricted_name -# \arg:restricted_name name of the restricted -################################################################################ -function(o3de_find_restricted_folder restricted_name restricted_path) - foreach(restricted_entry ${o3de_restricted}) - set(restricted_json_file ${restricted_entry}/restricted.json) - file(READ ${restricted_json_file} restricted_json) - string(JSON this_restricted_name ERROR_VARIABLE json_error GET ${restricted_json} restricted_name) - if(json_error) - message(WARNING "Unable to read restricted_name from '${restricted_json_file}', error: ${json_error}") - else() - if(this_restricted_name STREQUAL restricted_name) - set(${restricted_path} ${restricted_entry} PARENT_SCOPE) - return() - endif() - endif() - endforeach() - message(FATAL_ERROR "Unable to find restricted_name: '${restricted_name}'") -endfunction() - - -################################################################################ -#! o3de_engine_name: -# -# \arg:engine returns the engine_name element from an engine.json -# \arg:o3de_engine_json_file name of the o3de json file -################################################################################ -function(o3de_engine_name o3de_engine_json_file engine) - file(READ ${o3de_engine_json_file} json_data) - string(JSON engine_entry ERROR_VARIABLE json_error GET ${json_data} engine_name) - if(json_error) - message(FATAL_ERROR "Unable to read engine_name from '${o3de_json_file}', error: ${json_error}") - endif() - if(engine_entry) - set(${engine} ${engine_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_project_name: -# -# \arg:project returns the project_name element from an project.json -# \arg:o3de_project_json_file name of the o3de json file -################################################################################ -function(o3de_project_name o3de_project_json_file project) - file(READ ${o3de_project_json_file} json_data) - string(JSON project_entry ERROR_VARIABLE json_error GET ${json_data} project_name) - if(json_error) - message(FATAL_ERROR "Unable to read project_name from '${o3de_json_file}', error: ${json_error}") - endif() - if(project_entry) - set(${project} ${project_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_gem_name: -# -# \arg:gem returns the gem_name element from an gem.json -# \arg:o3de_gem_json_file name of the o3de json file -################################################################################ -function(o3de_gem_name o3de_gem_json_file gem) - file(READ ${o3de_gem_json_file} json_data) - string(JSON gem_entry ERROR_VARIABLE json_error GET ${json_data} gem_name) - if(json_error) - message(FATAL_ERROR "Unable to read gem_name from '${o3de_json_file}', error: ${json_error}") - endif() - if(gem_entry) - set(${gem} ${gem_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_template_name: -# -# \arg:template returns the template_name element from an template json -# \arg:o3de_template_json_file name of the o3de json file -################################################################################ -function(o3de_template_name o3de_template_json_file template) - file(READ ${o3de_template_json_file} json_data) - string(JSON template_entry ERROR_VARIABLE json_error GET ${json_data} template_name) - if(json_error) - message(FATAL_ERROR "Unable to read template_name from '${o3de_json_file}', error: ${json_error}") - endif() - if(template_entry) - set(${template} ${template_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_repo_name: -# -# \arg:repo returns the repo_name element from an repo.json or o3de_manifest.json -# \arg:o3de_repo_json_file name of the o3de json file -################################################################################ -function(o3de_repo_name o3de_repo_json_file repo) - file(READ ${o3de_repo_json_file} json_data) - string(JSON repo_entry ERROR_VARIABLE json_error GET ${json_data} repo_name) - if(json_error) - message(FATAL_ERROR "Unable to read repo_name from '${o3de_json_file}', error: ${json_error}") - endif() - if(repo_entry) - set(${repo} ${repo_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_restricted_name: -# -# \arg:restricted returns the restricted association element from an o3de json -# \arg:o3de_json_file name of the o3de json file -################################################################################ -function(o3de_restricted_name o3de_json_file restricted) - file(READ ${o3de_json_file} json_data) - string(JSON restricted_entry ERROR_VARIABLE json_error GET ${json_data} restricted_name) - if(json_error) - message(WARNING "FATAL_ERROR to read restricted_name from '${o3de_json_file}', error: ${json_error}") - endif() - if(restricted_entry) - set(${restricted} ${restricted_entry} PARENT_SCOPE) - endif() -endfunction() - - -################################################################################ -#! o3de_engine_path: -# -# \arg:engine_path returns the path of the o3de engine folder with name engine_name -# \arg:engine_name name of the engine -################################################################################ -function(o3de_engine_path o3de_json_file engine_path) - o3de_engine_id(${o3de_json_file} engine_name) - if(engine_name) - o3de_find_engine_folder(${engine_name} engine_folder) - if(engine_folder) - set(${engine_path} ${engine_folder} PARENT_SCOPE) - endif() - endif() -endfunction() - - -################################################################################ -#! o3de_project_path: -# -# \arg:project_path returns the path of the o3de project folder with name project_name -# \arg:project_name name of the project -################################################################################ -function(o3de_project_path o3de_json_file project_path) - o3de_project_id(${o3de_json_file} project_name) - if(project_name) - o3de_find_project_folder(${project_name} project_folder) - if(project_folder) - set(${project_path} ${project_folder} PARENT_SCOPE) - endif() - endif() -endfunction() - - -################################################################################ -#! o3de_template_path: -# -# \arg:template_path returns the path of the o3de template folder with name template_name -# \arg:template_name name of the template -################################################################################ -function(o3de_template_path o3de_json_file template_path) - o3de_template_id(${o3de_json_file} template_name) - if(template_name) - o3de_find_template_folder(${template_name} template_folder) - if(template_folder) - set(${template_path} ${template_folder} PARENT_SCOPE) - endif() - endif() -endfunction() - - -################################################################################ -#! o3de_repo_path: -# -# \arg:repo_path returns the path of the o3de repo folder with name repo_name -# \arg:repo_name name of the repo -################################################################################ -function(o3de_repo_path o3de_json_file repo_path) - o3de_repo_id(${o3de_json_file} repo_name) - if(repo_name) - o3de_find_repo_folder(${repo_name} repo_folder) - if(repo_folder) - set(${repo_path} ${repo_folder} PARENT_SCOPE) - endif() - endif() -endfunction() - - -################################################################################ -#! o3de_restricted_path: -# -# \arg:restricted_path returns the path of the o3de restricted folder with name restricted_name -# \arg:restricted_name name of the restricted -################################################################################ -function(o3de_restricted_path o3de_json_file restricted_path) - o3de_restricted_id(${o3de_json_file} restricted_name) - if(restricted_name) - o3de_find_restricted_folder(${restricted_name} restricted_folder) - if(restricted_folder) - set(${restricted_path} ${restricted_folder} PARENT_SCOPE) - endif() - endif() -endfunction() From 7e4070e5f1edd9366562dbfb1860699e7a4db114 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 21 May 2021 02:50:30 -0500 Subject: [PATCH 090/811] Updating the DefaultProject and DefaultGem templates to use the "restricted_name" key for indicating the identifier of a restricted directory location instead of "restricted" --- Templates/DefaultGem/template.json | 2 +- Templates/DefaultProject/template.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Templates/DefaultGem/template.json b/Templates/DefaultGem/template.json index 22d4eb27e6..b653718095 100644 --- a/Templates/DefaultGem/template.json +++ b/Templates/DefaultGem/template.json @@ -1,6 +1,6 @@ { "template_name": "DefaultGem", - "restricted": "o3de", + "restricted_name": "o3de", "restricted_platform_relative_path": "Templates", "origin": "The primary repo for DefaultGem goes here: i.e. http://www.mydomain.com", "license": "What license DefaultGem uses goes here: i.e. https://opensource.org/licenses/MIT", diff --git a/Templates/DefaultProject/template.json b/Templates/DefaultProject/template.json index e823b6df19..31b448c9f6 100644 --- a/Templates/DefaultProject/template.json +++ b/Templates/DefaultProject/template.json @@ -1,6 +1,6 @@ { "template_name": "DefaultProject", - "restricted": "o3de", + "restricted_name": "o3de", "restricted_platform_relative_path": "Templates", "origin": "The primary repo for DefaultProject goes here: i.e. http://www.mydomain.com", "license": "What license DefaultProject uses goes here: i.e. https://opensource.org/licenses/MIT", From 7872360e4a6b9c2411ee7365c8ec595f49a0c960 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 21 May 2021 02:53:40 -0500 Subject: [PATCH 091/811] Updating the engine.json file with the list of external_subdirectories, projects and template that come with it --- engine.json | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 92 insertions(+), 2 deletions(-) diff --git a/engine.json b/engine.json index e8dba6d965..7662d4f034 100644 --- a/engine.json +++ b/engine.json @@ -1,8 +1,98 @@ { "engine_name": "o3de", - "restricted": "o3de", + "restricted_name": "o3de", "FileVersion": 1, "O3DEVersion": "0.0.0.0", "O3DECopyrightYear": 2021, - "O3DEBuildNumber": 0 + "O3DEBuildNumber": 0, + "external_subdirectories": [ + "Gems/Achievements", + "Gems/AssetMemoryAnalyzer", + "Gems/AssetValidation", + "Gems/Atom", + "Gems/AtomContent", + "Gems/AtomLyIntegration", + "Gems/AtomTressFX", + "Gems/AudioEngineWwise", + "Gems/AudioSystem", + "Gems/AutomatedLauncherTesting", + "Gems/AWSClientAuth", + "Gems/AWSCore", + "Gems/AWSMetrics", + "Gems/Blast", + "Gems/Camera", + "Gems/CameraFramework", + "Gems/CertificateManager", + "Gems/CrashReporting", + "Gems/CustomAssetExample", + "Gems/DebugDraw", + "Gems/DevTextures", + "Gems/EditorPythonBindings", + "Gems/EMotionFX", + "Gems/ExpressionEvaluation", + "Gems/FastNoise", + "Gems/GameState", + "Gems/GameStateSamples", + "Gems/Gestures", + "Gems/GradientSignal", + "Gems/GraphCanvas", + "Gems/GraphModel", + "Gems/HttpRequestor", + "Gems/ImGui", + "Gems/InAppPurchases", + "Gems/LandscapeCanvas", + "Gems/LmbrCentral", + "Gems/LocalUser", + "Gems/LyShine", + "Gems/LyShineExamples", + "Gems/Maestro", + "Gems/MessagePopup", + "Gems/Metastream", + "Gems/Microphone", + "Gems/Multiplayer", + "Gems/MultiplayerCompression", + "Gems/NvCloth", + "Gems/PBSreferenceMaterials", + "Gems/PhysicsEntities", + "Gems/PhysX", + "Gems/PhysXDebug", + "Gems/PhysXSamples", + "Gems/Prefab", + "Gems/Presence", + "Gems/PrimitiveAssets", + "Gems/PythonAssetBuilder", + "Gems/QtForPython", + "Gems/RADTelemetry", + "Gems/SaveData", + "Gems/SceneLoggingExample", + "Gems/SceneProcessing", + "Gems/ScriptCanvas", + "Gems/ScriptCanvasDeveloper", + "Gems/ScriptCanvasPhysics", + "Gems/ScriptCanvasTesting", + "Gems/ScriptedEntityTweener", + "Gems/ScriptEvents", + "Gems/SliceFavorites", + "Gems/StartingPointCamera", + "Gems/StartingPointInput", + "Gems/StartingPointMovement", + "Gems/SurfaceData", + "Gems/TestAssetBuilder", + "Gems/TextureAtlas", + "Gems/TickBusOrderViewer", + "Gems/Twitch", + "Gems/UIBasics", + "Gems/Vegetation", + "Gems/Vegetation_Gem_Assets", + "Gems/VideoPlaybackFramework", + "Gems/VirtualGamepad", + "Gems/WhiteBox" + ], + "projects": [ + "AutomatedTesting" + ], + "templates": [ + "Templates/DefaultGem", + "Templates/DefaultProject" + ] } From a424ac63ecfa387f3da99c86e4aebefa00d9b6d3 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 21 May 2021 02:07:36 -0500 Subject: [PATCH 092/811] Adding empty CMakeLists.txt to Asset only gems to fit the new definition of a gem. That defintion is that a gem is a directory with a gem.json and a CMakeLists.txt in it --- Gems/AtomContent/CMakeLists.txt | 10 ++++++++++ Gems/AtomContent/gem.json | 14 ++++++++++++++ Gems/AtomTressFX/CMakeLists.txt | 10 ++++++++++ Gems/DevTextures/CMakeLists.txt | 10 ++++++++++ Gems/PBSreferenceMaterials/CMakeLists.txt | 10 ++++++++++ Gems/PhysXSamples/CMakeLists.txt | 10 ++++++++++ Gems/PhysicsEntities/CMakeLists.txt | 10 ++++++++++ Gems/PrimitiveAssets/CMakeLists.txt | 10 ++++++++++ Gems/UiBasics/CMakeLists.txt | 10 ++++++++++ Gems/Vegetation_Gem_Assets/CMakeLists.txt | 10 ++++++++++ 10 files changed, 104 insertions(+) create mode 100644 Gems/AtomContent/CMakeLists.txt create mode 100644 Gems/AtomContent/gem.json create mode 100644 Gems/AtomTressFX/CMakeLists.txt create mode 100644 Gems/DevTextures/CMakeLists.txt create mode 100644 Gems/PBSreferenceMaterials/CMakeLists.txt create mode 100644 Gems/PhysXSamples/CMakeLists.txt create mode 100644 Gems/PhysicsEntities/CMakeLists.txt create mode 100644 Gems/PrimitiveAssets/CMakeLists.txt create mode 100644 Gems/UiBasics/CMakeLists.txt create mode 100644 Gems/Vegetation_Gem_Assets/CMakeLists.txt diff --git a/Gems/AtomContent/CMakeLists.txt b/Gems/AtomContent/CMakeLists.txt new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/AtomContent/CMakeLists.txt @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/Gems/AtomContent/gem.json b/Gems/AtomContent/gem.json new file mode 100644 index 0000000000..941e7dea20 --- /dev/null +++ b/Gems/AtomContent/gem.json @@ -0,0 +1,14 @@ +{ + "gem_name": "AtomContent", + "origin": "The primary repo for Atom goes here: i.e. http://www.mydomain.com", + "license": "What license Atom uses goes here: i.e. https://opensource.org/licenses/MIT", + "display_name": "Atom Content", + "summary": "ontains multiple packages containing source Assets that can be used with Atom", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + "AtomConent" + ], + "icon_path": "preview.png" +} diff --git a/Gems/AtomTressFX/CMakeLists.txt b/Gems/AtomTressFX/CMakeLists.txt new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/AtomTressFX/CMakeLists.txt @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/Gems/DevTextures/CMakeLists.txt b/Gems/DevTextures/CMakeLists.txt new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/DevTextures/CMakeLists.txt @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/Gems/PBSreferenceMaterials/CMakeLists.txt b/Gems/PBSreferenceMaterials/CMakeLists.txt new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/PBSreferenceMaterials/CMakeLists.txt @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/Gems/PhysXSamples/CMakeLists.txt b/Gems/PhysXSamples/CMakeLists.txt new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/PhysXSamples/CMakeLists.txt @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/Gems/PhysicsEntities/CMakeLists.txt b/Gems/PhysicsEntities/CMakeLists.txt new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/PhysicsEntities/CMakeLists.txt @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/Gems/PrimitiveAssets/CMakeLists.txt b/Gems/PrimitiveAssets/CMakeLists.txt new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/PrimitiveAssets/CMakeLists.txt @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/Gems/UiBasics/CMakeLists.txt b/Gems/UiBasics/CMakeLists.txt new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/UiBasics/CMakeLists.txt @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/Gems/Vegetation_Gem_Assets/CMakeLists.txt b/Gems/Vegetation_Gem_Assets/CMakeLists.txt new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/Vegetation_Gem_Assets/CMakeLists.txt @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# From 530c9a424e2d128282f735dcaabb11566b4476ea Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 21 May 2021 04:11:02 -0500 Subject: [PATCH 093/811] Updating the manifest get_registered command to read the engine projects, gems, external_subdirectories, restricted and templates paths from the engine.json --- scripts/o3de/o3de/add_external_subdirectory.py | 3 ++- scripts/o3de/o3de/cmake.py | 2 +- scripts/o3de/o3de/download.py | 2 +- scripts/o3de/o3de/manifest.py | 16 ++++++++-------- scripts/o3de/o3de/register.py | 1 - .../o3de/o3de/remove_external_subdirectory.py | 4 ++-- scripts/o3de/o3de/remove_gem_cmake.py | 2 +- scripts/o3de/o3de/remove_gem_project.py | 2 +- scripts/o3de/o3de/validation.py | 2 +- 9 files changed, 17 insertions(+), 17 deletions(-) diff --git a/scripts/o3de/o3de/add_external_subdirectory.py b/scripts/o3de/o3de/add_external_subdirectory.py index 15dc5163c5..388f0027da 100644 --- a/scripts/o3de/o3de/add_external_subdirectory.py +++ b/scripts/o3de/o3de/add_external_subdirectory.py @@ -9,7 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # """ -Contains command to add a gem to a project's cmake scripts +Contains command to add an external_subdirectory to a project's cmake scripts """ import argparse @@ -50,6 +50,7 @@ def add_external_subdirectory(external_subdir: str or pathlib.Path, logger.error(f'Add External Subdirectory Failed: {engine_path} not registered.') return 1 + engine_object.setdefault('external_subdirectories', []) while external_subdir.as_posix() in engine_object['external_subdirectories']: engine_object['external_subdirectories'].remove(external_subdir.as_posix()) diff --git a/scripts/o3de/o3de/cmake.py b/scripts/o3de/o3de/cmake.py index b5b28cbb7e..7e95a9c2fe 100644 --- a/scripts/o3de/o3de/cmake.py +++ b/scripts/o3de/o3de/cmake.py @@ -9,7 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # """ -This file contains methods for introspecting data from cmake scripts +Contains methods for query CMake gem target information """ import logging diff --git a/scripts/o3de/o3de/download.py b/scripts/o3de/o3de/download.py index 218463f98b..3db2f077cd 100644 --- a/scripts/o3de/o3de/download.py +++ b/scripts/o3de/o3de/download.py @@ -9,7 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # """ -This file contains functions for querying paths from ~/.o3de directory +Implements functionality for downloading o3de objecs either locally or from a URI """ import argparse diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index b3aac6d1f3..44d6ff1b61 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -9,7 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # """ -This file contains functions for querying paths from ~/.o3de directory +Contains functions for data from json files such as the o3de_manifests.json, engine.json, project.json, etc... """ import json @@ -496,7 +496,7 @@ def get_registered(engine_name: str = None, return engine_path elif isinstance(project_name, str): - engine_object = find_engine_data(json_data) + enging_projects = get_engine_projects() projects = json_data['projects'].copy() projects.extend(engine_object['projects']) for project_path in projects: @@ -513,9 +513,9 @@ def get_registered(engine_name: str = None, return project_path elif isinstance(gem_name, str): - engine_object = find_engine_data(json_data) + engine_gems = get_engine_gems() gems = json_data['gems'].copy() - gems.extend(engine_object['gems']) + gems.extend(engine_gems) for gem_path in gems: gem_path = pathlib.Path(gem_path).resolve() gem_json = gem_path / 'gem.json' @@ -530,9 +530,9 @@ def get_registered(engine_name: str = None, return gem_path elif isinstance(template_name, str): - engine_object = find_engine_data(json_data) + engine_templates = get_engine_templates() templates = json_data['templates'].copy() - templates.extend(engine_object['templates']) + templates.extend(engine_templates) for template_path in templates: template_path = pathlib.Path(template_path).resolve() template_json = template_path / 'template.json' @@ -547,9 +547,9 @@ def get_registered(engine_name: str = None, return template_path elif isinstance(restricted_name, str): - engine_object = find_engine_data(json_data) + engine_restricted = get_engine_restricted() restricted = json_data['restricted'].copy() - restricted.extend(engine_object['restricted']) + restricted.extend(engine_restricted) for restricted_path in restricted: restricted_path = pathlib.Path(restricted_path).resolve() restricted_json = restricted_path / 'restricted.json' diff --git a/scripts/o3de/o3de/register.py b/scripts/o3de/o3de/register.py index e96d057e9c..d6a734e1fd 100644 --- a/scripts/o3de/o3de/register.py +++ b/scripts/o3de/o3de/register.py @@ -374,7 +374,6 @@ def register_engine_path(json_data: dict, engine_object = {} engine_object.update({'path': engine_path.as_posix()}) - engine_object.update({'restricted': []}) json_data.setdefault('engines', []).insert(0, engine_object) diff --git a/scripts/o3de/o3de/remove_external_subdirectory.py b/scripts/o3de/o3de/remove_external_subdirectory.py index 3e022d51b9..a636474fba 100644 --- a/scripts/o3de/o3de/remove_external_subdirectory.py +++ b/scripts/o3de/o3de/remove_external_subdirectory.py @@ -9,7 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # """ -Contains command to add a gem to a project's cmake scripts +Implemens functinality to remove external_subdirectories from the o3de_manifests.json """ import argparse @@ -31,7 +31,7 @@ def remove_external_subdirectory(external_subdir: str or pathlib.Path, """ json_data = manifest.load_o3de_manifest() engine_object = manifest.find_engine_data(json_data, engine_path) - if not engine_object: + if not engine_object or not 'external_subdirectories' in engine_object: logger.error(f'Remove External Subdirectory Failed: {engine_path} not registered.') return 1 diff --git a/scripts/o3de/o3de/remove_gem_cmake.py b/scripts/o3de/o3de/remove_gem_cmake.py index 2def94dfbf..8f73caaad1 100644 --- a/scripts/o3de/o3de/remove_gem_cmake.py +++ b/scripts/o3de/o3de/remove_gem_cmake.py @@ -9,7 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # """ -This file contains methods for removing a gem from a project's cmake scripts +Contains methods for removing a gem from a project's cmake scripts """ import argparse diff --git a/scripts/o3de/o3de/remove_gem_project.py b/scripts/o3de/o3de/remove_gem_project.py index a3e623f488..7644357042 100644 --- a/scripts/o3de/o3de/remove_gem_project.py +++ b/scripts/o3de/o3de/remove_gem_project.py @@ -9,7 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # """ -This file contains methods for removing a gem from a project +Contains methods for removing a gem target from a project """ import argparse diff --git a/scripts/o3de/o3de/validation.py b/scripts/o3de/o3de/validation.py index 56839fe056..f3a5f5e376 100644 --- a/scripts/o3de/o3de/validation.py +++ b/scripts/o3de/o3de/validation.py @@ -9,7 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # """ -This file contains functions for querying paths from ~/.o3de directory +This file validating o3de object json files """ import json import pathlib From d6e25bbb333a207d208baa47fcc2966bc5a00d66 Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Fri, 21 May 2021 03:26:29 -0700 Subject: [PATCH 094/811] Added DiffuseProbeGrid texture baking --- .../Config/LUT_R32F.preset | 45 +++ .../Config/LUT_RGBA16.preset | 59 +++ .../Config/LUT_RGBA16F.preset | 59 +++ ...iffuseProbeGridFeatureProcessorInterface.h | 76 ++++ .../DiffuseProbeGrid/DiffuseProbeGrid.cpp | 254 +++++++++---- .../DiffuseProbeGrid/DiffuseProbeGrid.h | 53 ++- .../DiffuseProbeGridBlendDistancePass.cpp | 8 +- .../DiffuseProbeGridBlendIrradiancePass.cpp | 8 +- .../DiffuseProbeGridBorderUpdatePass.cpp | 8 +- .../DiffuseProbeGridClassificationPass.cpp | 8 +- .../DiffuseProbeGridFeatureProcessor.cpp | 202 +++++++++- .../DiffuseProbeGridFeatureProcessor.h | 54 ++- .../DiffuseProbeGridRayTracingPass.cpp | 10 +- .../DiffuseProbeGridRelocationPass.cpp | 10 +- .../DiffuseProbeGridRenderPass.cpp | 48 +++ .../DiffuseProbeGridTextureReadback.cpp | 134 +++++++ .../DiffuseProbeGridTextureReadback.h | 60 +++ .../Code/atom_feature_common_files.cmake | 2 + .../DiffuseProbeGridComponentController.cpp | 158 +++++++- .../DiffuseProbeGridComponentController.h | 25 ++ .../EditorDiffuseProbeGridComponent.cpp | 352 +++++++++++++++++- .../EditorDiffuseProbeGridComponent.h | 29 ++ 22 files changed, 1538 insertions(+), 124 deletions(-) create mode 100644 Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_R32F.preset create mode 100644 Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16.preset create mode 100644 Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16F.preset create mode 100644 Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp create mode 100644 Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.h diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_R32F.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_R32F.preset new file mode 100644 index 0000000000..1bb23c6e96 --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_R32F.preset @@ -0,0 +1,45 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "MultiplatformPresetSettings", + "ClassData": { + "DefaultPreset": { + "UUID": "{10D4D7D8-23E2-4FC5-BE6A-DA9949D2C603}", + "Name": "LUT_R32F", + "FileMasks": ["_lutr32f"], + "SourceColor": "Linear", + "DestColor": "Linear", + "PixelFormat": "R32F" + }, + "PlatformsPresets": { + "es3": { + "UUID": "{10D4D7D8-23E2-4FC5-BE6A-DA9949D2C603}", + "Name": "LUT_R32F", + "SourceColor": "Linear", + "DestColor": "Linear", + "PixelFormat": "R32F" + }, + "ios": { + "UUID": "{10D4D7D8-23E2-4FC5-BE6A-DA9949D2C603}", + "Name": "LUT_R32F", + "SourceColor": "Linear", + "DestColor": "Linear", + "PixelFormat": "R32F" + }, + "osx_gl": { + "UUID": "{10D4D7D8-23E2-4FC5-BE6A-DA9949D2C603}", + "Name": "LUT_R32F", + "SourceColor": "Linear", + "DestColor": "Linear", + "PixelFormat": "R32F" + }, + "provo": { + "UUID": "{10D4D7D8-23E2-4FC5-BE6A-DA9949D2C603}", + "Name": "LUT_R32F", + "SourceColor": "Linear", + "DestColor": "Linear", + "PixelFormat": "R32F" + } + } + } +} diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16.preset new file mode 100644 index 0000000000..f36d566d7e --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16.preset @@ -0,0 +1,59 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "MultiplatformPresetSettings", + "ClassData": { + "DefaultPreset": { + "UUID": "{ABDFCED1-0565-4B7B-9BC1-82C473BCEEA2}", + "Name": "LUT_RGBA16", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ + "_lutrgba16" + ], + "PixelFormat": "R16G16B16A16" + }, + "PlatformsPresets": { + "es3": { + "UUID": "{ABDFCED1-0565-4B7B-9BC1-82C473BCEEA2}", + "Name": "LUT_RGBA16", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ + "_lutrgba16" + ], + "PixelFormat": "R16G16B16A16" + }, + "ios": { + "UUID": "{ABDFCED1-0565-4B7B-9BC1-82C473BCEEA2}", + "Name": "LUT_RGBA16", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ + "_lutrgba16" + ], + "PixelFormat": "R16G16B16A16" + }, + "osx_gl": { + "UUID": "{ABDFCED1-0565-4B7B-9BC1-82C473BCEEA2}", + "Name": "LUT_RGBA16", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ + "_lutrgba16" + ], + "PixelFormat": "R16G16B16A16" + }, + "provo": { + "UUID": "{ABDFCED1-0565-4B7B-9BC1-82C473BCEEA2}", + "Name": "LUT_RGBA16", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ + "_lutrgba16" + ], + "PixelFormat": "R16G16B16A16" + } + } + } +} diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16F.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16F.preset new file mode 100644 index 0000000000..367c5101b3 --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16F.preset @@ -0,0 +1,59 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "MultiplatformPresetSettings", + "ClassData": { + "DefaultPreset": { + "UUID": "{6D75F093-C826-437A-AD94-8631A5A4E8A2}", + "Name": "LUT_RGBA16F", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ + "_lutrgba16f" + ], + "PixelFormat": "R16G16B16A16F" + }, + "PlatformsPresets": { + "es3": { + "UUID": "{6D75F093-C826-437A-AD94-8631A5A4E8A2}", + "Name": "LUT_RGBA16F", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ + "_lutrgba16f" + ], + "PixelFormat": "R16G16B16A16F" + }, + "ios": { + "UUID": "{6D75F093-C826-437A-AD94-8631A5A4E8A2}", + "Name": "LUT_RGBA16F", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ + "_lutrgba16f" + ], + "PixelFormat": "R16G16B16A16F" + }, + "osx_gl": { + "UUID": "{6D75F093-C826-437A-AD94-8631A5A4E8A2}", + "Name": "LUT_RGBA16F", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ + "_lutrgba16f" + ], + "PixelFormat": "R16G16B16A16F" + }, + "provo": { + "UUID": "{6D75F093-C826-437A-AD94-8631A5A4E8A2}", + "Name": "LUT_RGBA16F", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ + "_lutrgba16f" + ], + "PixelFormat": "R16G16B16A16F" + } + } + } +} diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h index 15b416597d..cf46383a64 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h @@ -14,6 +14,9 @@ #include #include +#include +#include +#include namespace AZ { @@ -23,6 +26,57 @@ namespace AZ using DiffuseProbeGridHandle = AZStd::shared_ptr; + enum class DiffuseProbeGridMode : uint8_t + { + RealTime, + Baked, + AutoSelect + }; + + enum class DiffuseProbeGridTextureNotificationType + { + None, + Ready, + Error + }; + + struct DiffuseProbeGridTexture + { + const AZStd::shared_ptr> m_data; + RHI::Format m_format; + RHI::Size m_size; + }; + + static const char* DiffuseProbeGridIrradianceFileName = "Irradiance_lutrgba16.dds"; + static const char* DiffuseProbeGridDistanceFileName = "Distance_lutrg32f.dds"; + static const char* DiffuseProbeGridRelocationFileName = "Relocation_lutrgba16f.dds"; + static const char* DiffuseProbeGridClassificationFileName = "Classification_lutr32f.dds"; + + using DiffuseProbeGridBakeTexturesCallback = AZStd::function; + + struct DiffuseProbeGridBakedTextures + { + // irradiance and distance images can be used directly + Data::Instance m_irradianceImage; + AZStd::string m_irradianceImageRelativePath; + + Data::Instance m_distanceImage; + AZStd::string m_distanceImageRelativePath; + + // relocation and classification images need to be recreated as RW textures + RHI::ImageDescriptor m_relocationImageDescriptor; + AZStd::array_view m_relocationImageData; + AZStd::string m_relocationImageRelativePath; + + RHI::ImageDescriptor m_classificationImageDescriptor; + AZStd::array_view m_classificationImageData; + AZStd::string m_classificationImageRelativePath; + }; + // DiffuseProbeGridFeatureProcessorInterface provides an interface to the feature processor for code outside of Atom class DiffuseProbeGridFeatureProcessorInterface : public RPI::FeatureProcessor @@ -44,6 +98,28 @@ namespace AZ virtual void Enable(const DiffuseProbeGridHandle& probeGrid, bool enable) = 0; virtual void SetGIShadows(const DiffuseProbeGridHandle& probeGrid, bool giShadows) = 0; virtual void SetUseDiffuseIbl(const DiffuseProbeGridHandle& probeGrid, bool useDiffuseIbl) = 0; + virtual void SetMode(const DiffuseProbeGridHandle& probeGrid, DiffuseProbeGridMode mode) = 0; + virtual void SetBakedTextures(const DiffuseProbeGridHandle& probeGrid, const DiffuseProbeGridBakedTextures& bakedTextures) = 0; + + virtual void BakeTextures( + const DiffuseProbeGridHandle& probeGrid, + DiffuseProbeGridBakeTexturesCallback callback, + const AZStd::string& irradianceTextureRelativePath, + const AZStd::string& distanceTextureRelativePath, + const AZStd::string& relocationTextureRelativePath, + const AZStd::string& classificationTextureRelativePath) = 0; + + virtual bool CheckTextureAssetNotification( + const AZStd::string& relativePath, + Data::Asset& outTextureAsset, + DiffuseProbeGridTextureNotificationType& outNotificationType) = 0; + + virtual bool AreBakedTexturesReferenced( + const AZStd::string& irradianceTextureRelativePath, + const AZStd::string& distanceTextureRelativePath, + const AZStd::string& relocationTextureRelativePath, + const AZStd::string& classificationTextureRelativePath) = 0; + }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.cpp index 5be1303434..a55d8fc78c 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -23,6 +24,11 @@ namespace AZ { namespace Render { + DiffuseProbeGrid::DiffuseProbeGrid() + : m_textureReadback(this) + { + } + DiffuseProbeGrid::~DiffuseProbeGrid() { m_scene->GetCullingScene()->UnregisterCullable(m_cullable); @@ -166,6 +172,84 @@ namespace AZ m_updateRenderObjectSrg = true; } + void DiffuseProbeGrid::SetMode(DiffuseProbeGridMode mode) + { + // handle auto-select + if (mode == DiffuseProbeGridMode::AutoSelect) + { + RHI::Ptr device = RHI::RHISystemInterface::Get()->GetDevice(); + m_mode = (device->GetFeatures().m_rayTracing) ? DiffuseProbeGridMode::RealTime : DiffuseProbeGridMode::Baked; + } + else + { + m_mode = mode; + } + + m_updateTextures = true; + } + + void DiffuseProbeGrid::SetBakedTextures(const DiffuseProbeGridBakedTextures& bakedTextures) + { + AZ_Assert(bakedTextures.m_irradianceImage.get(), "Invalid Irradiance image passed to SetBakedTextures"); + AZ_Assert(bakedTextures.m_distanceImage.get(), "Invalid Distance image passed to SetBakedTextures"); + AZ_Assert(bakedTextures.m_relocationImageData.size() > 0, "Invalid Relocation image data passed to SetBakedTextures"); + AZ_Assert(bakedTextures.m_classificationImageData.size() > 0, "Invalid Classification image data passed to SetBakedTextures"); + + m_bakedIrradianceImage = bakedTextures.m_irradianceImage; + m_bakedDistanceImage = bakedTextures.m_distanceImage; + + m_bakedIrradianceRelativePath = bakedTextures.m_irradianceImageRelativePath; + m_bakedDistanceRelativePath = bakedTextures.m_distanceImageRelativePath; + m_bakedRelocationRelativePath = bakedTextures.m_relocationImageRelativePath; + m_bakedClassificationRelativePath = bakedTextures.m_classificationImageRelativePath; + + m_bakedRelocationImageData.resize(bakedTextures.m_relocationImageData.size()); + memcpy(m_bakedRelocationImageData.data(), bakedTextures.m_relocationImageData.data(), bakedTextures.m_relocationImageData.size()); + + m_bakedClassificationImageData.resize(bakedTextures.m_classificationImageData.size()); + memcpy(m_bakedClassificationImageData.data(), bakedTextures.m_classificationImageData.data(), bakedTextures.m_classificationImageData.size()); + + // create the relocation and distance RW textures now, these are needed for shader compatibility + // (image data is copied in UpdateTextures) + { + m_bakedRelocationImage = RHI::Factory::Get().CreateImage(); + RHI::ImageInitRequest initRequest; + initRequest.m_image = m_bakedRelocationImage.get(); + initRequest.m_descriptor = RHI::ImageDescriptor::Create2D( + RHI::ImageBindFlags::ShaderReadWrite | RHI::ImageBindFlags::CopyRead, + bakedTextures.m_relocationImageDescriptor.m_size.m_width, + bakedTextures.m_relocationImageDescriptor.m_size.m_height, + bakedTextures.m_relocationImageDescriptor.m_format); + + [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(initRequest); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize Relocation image"); + } + + { + m_bakedClassificationImage = RHI::Factory::Get().CreateImage(); + RHI::ImageInitRequest initRequest; + initRequest.m_image = m_bakedClassificationImage.get(); + initRequest.m_descriptor = RHI::ImageDescriptor::Create2D( + RHI::ImageBindFlags::ShaderReadWrite | RHI::ImageBindFlags::CopyRead, + bakedTextures.m_classificationImageDescriptor.m_size.m_width, + bakedTextures.m_classificationImageDescriptor.m_size.m_height, + bakedTextures.m_classificationImageDescriptor.m_format); + + [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(initRequest); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize Classification image"); + } + + m_updateTextures = true; + } + + bool DiffuseProbeGrid::HasValidBakedTextures() const + { + return m_bakedIrradianceImage.get() && + m_bakedDistanceImage.get() && + m_bakedRelocationImage.get() && + m_bakedClassificationImage.get(); + } + uint32_t DiffuseProbeGrid::GetTotalProbeCount() const { return m_probeCountX * m_probeCountY * m_probeCountZ; @@ -188,83 +272,117 @@ namespace AZ RHI::Ptr device = RHI::RHISystemInterface::Get()->GetDevice(); - // advance to the next image in the frame image array - m_currentImageIndex = (m_currentImageIndex + 1) % ImageFrameCount; - - // probe raytrace - { - uint32_t width = m_numRaysPerProbe; - uint32_t height = GetTotalProbeCount(); - - m_rayTraceImage[m_currentImageIndex] = RHI::Factory::Get().CreateImage(); - - RHI::ImageInitRequest request; - request.m_image = m_rayTraceImage[m_currentImageIndex].get(); - request.m_descriptor = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::ShaderReadWrite, width, height, DiffuseProbeGridRenderData::RayTraceImageFormat); - [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(request); - AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize m_probeRayTraceImage image"); - } - uint32_t probeCountX; uint32_t probeCountY; GetTexture2DProbeCount(probeCountX, probeCountY); - // probe irradiance + if (m_mode == DiffuseProbeGridMode::RealTime) { - uint32_t width = probeCountX * (DefaultNumIrradianceTexels + 2); - uint32_t height = probeCountY * (DefaultNumIrradianceTexels + 2); + // advance to the next image in the frame image array + m_currentImageIndex = (m_currentImageIndex + 1) % ImageFrameCount; - m_irradianceImage[m_currentImageIndex] = RHI::Factory::Get().CreateImage(); + // probe raytrace + { + uint32_t width = m_numRaysPerProbe; + uint32_t height = GetTotalProbeCount(); - RHI::ImageInitRequest request; - request.m_image = m_irradianceImage[m_currentImageIndex].get(); - request.m_descriptor = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::ShaderReadWrite, width, height, DiffuseProbeGridRenderData::IrradianceImageFormat); - RHI::ClearValue clearValue = RHI::ClearValue::CreateVector4Float(0.0f, 0.0f, 0.0f, 0.0f); - request.m_optimizedClearValue = &clearValue; - [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(request); - AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize m_probeIrradianceImage image"); + m_rayTraceImage[m_currentImageIndex] = RHI::Factory::Get().CreateImage(); + + RHI::ImageInitRequest request; + request.m_image = m_rayTraceImage[m_currentImageIndex].get(); + request.m_descriptor = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::ShaderReadWrite | RHI::ImageBindFlags::CopyRead, width, height, DiffuseProbeGridRenderData::RayTraceImageFormat); + [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(request); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize m_probeRayTraceImage image"); + } + + // probe irradiance + { + uint32_t width = probeCountX * (DefaultNumIrradianceTexels + 2); + uint32_t height = probeCountY * (DefaultNumIrradianceTexels + 2); + + m_irradianceImage[m_currentImageIndex] = RHI::Factory::Get().CreateImage(); + + RHI::ImageInitRequest request; + request.m_image = m_irradianceImage[m_currentImageIndex].get(); + request.m_descriptor = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::ShaderReadWrite | RHI::ImageBindFlags::CopyRead, width, height, DiffuseProbeGridRenderData::IrradianceImageFormat); + RHI::ClearValue clearValue = RHI::ClearValue::CreateVector4Float(0.0f, 0.0f, 0.0f, 0.0f); + request.m_optimizedClearValue = &clearValue; + [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(request); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize m_probeIrradianceImage image"); + } + + // probe distance + { + uint32_t width = probeCountX * (DefaultNumDistanceTexels + 2); + uint32_t height = probeCountY * (DefaultNumDistanceTexels + 2); + + m_distanceImage[m_currentImageIndex] = RHI::Factory::Get().CreateImage(); + + RHI::ImageInitRequest request; + request.m_image = m_distanceImage[m_currentImageIndex].get(); + request.m_descriptor = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::ShaderReadWrite | RHI::ImageBindFlags::CopyRead, width, height, DiffuseProbeGridRenderData::DistanceImageFormat); + [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(request); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize m_probeDistanceImage image"); + } + + // probe relocation + { + uint32_t width = probeCountX; + uint32_t height = probeCountY; + + m_relocationImage[m_currentImageIndex] = RHI::Factory::Get().CreateImage(); + + RHI::ImageInitRequest request; + request.m_image = m_relocationImage[m_currentImageIndex].get(); + request.m_descriptor = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::ShaderReadWrite | RHI::ImageBindFlags::CopyRead, width, height, DiffuseProbeGridRenderData::RelocationImageFormat); + [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(request); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize m_probeRelocationImage image"); + } + + // probe classification + { + uint32_t width = probeCountX; + uint32_t height = probeCountY; + + m_classificationImage[m_currentImageIndex] = RHI::Factory::Get().CreateImage(); + + RHI::ImageInitRequest request; + request.m_image = m_classificationImage[m_currentImageIndex].get(); + request.m_descriptor = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::ShaderReadWrite | RHI::ImageBindFlags::CopyRead, width, height, DiffuseProbeGridRenderData::ClassificationImageFormat); + [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(request); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize m_probeClassificationImage image"); + } } - - // probe distance + else if (m_mode == DiffuseProbeGridMode::Baked && HasValidBakedTextures()) { - uint32_t width = probeCountX * (DefaultNumDistanceTexels + 2); - uint32_t height = probeCountY * (DefaultNumDistanceTexels + 2); + // copy the baked relocation and classification texture data to the RW textures + // (these need to be RW for shader compatibility) + RHI::ImageSubresourceRange range{ 0, 0, 0 ,0 }; + RHI::ImageSubresourceLayoutPlaced layout; - m_distanceImage[m_currentImageIndex] = RHI::Factory::Get().CreateImage(); + // relocation + { + m_bakedRelocationImage->GetSubresourceLayouts(range, &layout, nullptr); - RHI::ImageInitRequest request; - request.m_image = m_distanceImage[m_currentImageIndex].get(); - request.m_descriptor = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::ShaderReadWrite, width, height, DiffuseProbeGridRenderData::DistanceImageFormat); - [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(request); - AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize m_probeDistanceImage image"); - } + RHI::ImageUpdateRequest updateRequest; + updateRequest.m_image = m_bakedRelocationImage.get(); + updateRequest.m_sourceSubresourceLayout = layout; + updateRequest.m_sourceData = m_bakedRelocationImageData.data(); + updateRequest.m_imageSubresourcePixelOffset = RHI::Origin(0, 0, 0); + m_renderData->m_imagePool->UpdateImageContents(updateRequest); + } - // probe relocation - { - uint32_t width = probeCountX; - uint32_t height = probeCountY; + // classification + { + m_bakedClassificationImage->GetSubresourceLayouts(range, &layout, nullptr); - m_relocationImage[m_currentImageIndex] = RHI::Factory::Get().CreateImage(); - - RHI::ImageInitRequest request; - request.m_image = m_relocationImage[m_currentImageIndex].get(); - request.m_descriptor = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::ShaderReadWrite, width, height, DiffuseProbeGridRenderData::RelocationImageFormat); - [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(request); - AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize m_probeRelocationImage image"); - } - - // probe classification - { - uint32_t width = probeCountX; - uint32_t height = probeCountY; - - m_classificationImage[m_currentImageIndex] = RHI::Factory::Get().CreateImage(); - - RHI::ImageInitRequest request; - request.m_image = m_classificationImage[m_currentImageIndex].get(); - request.m_descriptor = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::ShaderReadWrite, width, height, DiffuseProbeGridRenderData::ClassificationImageFormat); - [[maybe_unused]] RHI::ResultCode result = m_renderData->m_imagePool->InitImage(request); - AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialize m_probeClassificationImage image"); + RHI::ImageUpdateRequest updateRequest; + updateRequest.m_image = m_bakedClassificationImage.get(); + updateRequest.m_sourceSubresourceLayout = layout; + updateRequest.m_sourceData = m_bakedClassificationImageData.data(); + updateRequest.m_imageSubresourcePixelOffset = RHI::Origin(0, 0, 0); + m_renderData->m_imagePool->UpdateImageContents(updateRequest); + } } m_updateTextures = false; @@ -639,16 +757,16 @@ namespace AZ m_renderObjectSrg->SetConstant(constantIndex, m_ambientMultiplier); imageIndex = srgLayout->FindShaderInputImageIndex(Name("m_probeIrradiance")); - m_renderObjectSrg->SetImageView(imageIndex, m_irradianceImage[m_currentImageIndex]->GetImageView(m_renderData->m_probeIrradianceImageViewDescriptor).get()); + m_renderObjectSrg->SetImageView(imageIndex, GetIrradianceImage()->GetImageView(m_renderData->m_probeIrradianceImageViewDescriptor).get()); imageIndex = srgLayout->FindShaderInputImageIndex(Name("m_probeDistance")); - m_renderObjectSrg->SetImageView(imageIndex, m_distanceImage[m_currentImageIndex]->GetImageView(m_renderData->m_probeDistanceImageViewDescriptor).get()); + m_renderObjectSrg->SetImageView(imageIndex, GetDistanceImage()->GetImageView(m_renderData->m_probeDistanceImageViewDescriptor).get()); imageIndex = srgLayout->FindShaderInputImageIndex(Name("m_probeOffsets")); - m_renderObjectSrg->SetImageView(imageIndex, m_relocationImage[m_currentImageIndex]->GetImageView(m_renderData->m_probeRelocationImageViewDescriptor).get()); + m_renderObjectSrg->SetImageView(imageIndex, GetRelocationImage()->GetImageView(m_renderData->m_probeRelocationImageViewDescriptor).get()); imageIndex = srgLayout->FindShaderInputImageIndex(Name("m_probeStates")); - m_renderObjectSrg->SetImageView(imageIndex, m_classificationImage[m_currentImageIndex]->GetImageView(m_renderData->m_probeClassificationImageViewDescriptor).get()); + m_renderObjectSrg->SetImageView(imageIndex, GetClassificationImage()->GetImageView(m_renderData->m_probeClassificationImageViewDescriptor).get()); SetGridConstants(m_renderObjectSrg); diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h index e1ca2123a5..325cbcb616 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h @@ -17,6 +17,7 @@ #include #include #include +#include namespace AZ { @@ -30,7 +31,7 @@ namespace AZ static const RHI::Format IrradianceImageFormat = RHI::Format::R16G16B16A16_UNORM; static const RHI::Format DistanceImageFormat = RHI::Format::R32G32_FLOAT; static const RHI::Format RelocationImageFormat = RHI::Format::R16G16B16A16_FLOAT; - static const RHI::Format ClassificationImageFormat = RHI::Format::R8_UINT; + static const RHI::Format ClassificationImageFormat = RHI::Format::R32_FLOAT; // image pool RHI::Ptr m_imagePool; @@ -61,7 +62,7 @@ namespace AZ class DiffuseProbeGrid final { public: - DiffuseProbeGrid() = default; + DiffuseProbeGrid(); ~DiffuseProbeGrid(); void Init(RPI::Scene* scene, DiffuseProbeGridRenderData* diffuseProbeGridRenderData); @@ -96,6 +97,9 @@ namespace AZ bool GetUseDiffuseIbl() const { return m_useDiffuseIbl; } void SetUseDiffuseIbl(bool useDiffuseIbl) { m_useDiffuseIbl = useDiffuseIbl; } + DiffuseProbeGridMode GetMode() const { return m_mode; } + void SetMode(DiffuseProbeGridMode mode); + uint32_t GetNumRaysPerProbe() const { return m_numRaysPerProbe; } uint32_t GetRemainingRelocationIterations() const { return aznumeric_cast(m_remainingRelocationIterations); } @@ -133,11 +137,16 @@ namespace AZ void UpdateRenderObjectSrg(); // textures - const RHI::Ptr& GetRayTraceImage() { return m_rayTraceImage[m_currentImageIndex]; } - const RHI::Ptr& GetIrradianceImage() { return m_irradianceImage[m_currentImageIndex]; } - const RHI::Ptr& GetDistanceImage() { return m_distanceImage[m_currentImageIndex]; } - const RHI::Ptr& GetRelocationImage() { return m_relocationImage[m_currentImageIndex]; } - const RHI::Ptr& GetClassificationImage() { return m_classificationImage[m_currentImageIndex]; } + const RHI::Ptr GetRayTraceImage() { return m_rayTraceImage[m_currentImageIndex]; } + const RHI::Ptr GetIrradianceImage() { return m_mode == DiffuseProbeGridMode::RealTime ? m_irradianceImage[m_currentImageIndex] : m_bakedIrradianceImage->GetRHIImage(); } + const RHI::Ptr GetDistanceImage() { return m_mode == DiffuseProbeGridMode::RealTime ? m_distanceImage[m_currentImageIndex] : m_bakedDistanceImage->GetRHIImage(); } + const RHI::Ptr GetRelocationImage() { return m_mode == DiffuseProbeGridMode::RealTime ? m_relocationImage[m_currentImageIndex] : m_bakedRelocationImage; } + const RHI::Ptr GetClassificationImage() { return m_mode == DiffuseProbeGridMode::RealTime ? m_classificationImage[m_currentImageIndex] : m_bakedClassificationImage; } + + const AZStd::string& GetBakedIrradianceRelativePath() const { return m_bakedIrradianceRelativePath; } + const AZStd::string& GetBakedDistanceRelativePath() const { return m_bakedDistanceRelativePath; } + const AZStd::string& GetBakedRelocationRelativePath() const { return m_bakedRelocationRelativePath; } + const AZStd::string& GetBakedClassificationRelativePath() const { return m_bakedClassificationRelativePath; } // attachment Ids const RHI::AttachmentId GetRayTraceImageAttachmentId() const { return m_rayTraceImageAttachmentId; } @@ -152,6 +161,12 @@ namespace AZ bool GetIrradianceClearRequired() const { return m_irradianceClearRequired; } void ResetIrradianceClearRequired() { m_irradianceClearRequired = false; } + // texture readback + DiffuseProbeGridTextureReadback& GetTextureReadback() { return m_textureReadback; } + + void SetBakedTextures(const DiffuseProbeGridBakedTextures& bakedTextures); + bool HasValidBakedTextures() const; + static constexpr uint32_t DefaultNumIrradianceTexels = 6; static constexpr uint32_t DefaultNumDistanceTexels = 14; static constexpr int32_t DefaultNumRelocationIterations = 100; @@ -221,7 +236,10 @@ namespace AZ // culling RPI::Cullable m_cullable; - // textures + // grid mode (RealTime or Baked) + DiffuseProbeGridMode m_mode = DiffuseProbeGridMode::RealTime; + + // real-time textures static const uint32_t MaxTextureDimension = 8192; static const uint32_t ImageFrameCount = 3; RHI::Ptr m_rayTraceImage[ImageFrameCount]; @@ -233,6 +251,25 @@ namespace AZ bool m_updateTextures = false; bool m_irradianceClearRequired = true; + // baked textures + Data::Instance m_bakedIrradianceImage; + Data::Instance m_bakedDistanceImage; + RHI::Ptr m_bakedRelocationImage; + RHI::Ptr m_bakedClassificationImage; + + // baked texture relative paths + AZStd::string m_bakedIrradianceRelativePath; + AZStd::string m_bakedDistanceRelativePath; + AZStd::string m_bakedRelocationRelativePath; + AZStd::string m_bakedClassificationRelativePath; + + // baked texture data (only needed for the relocation and classification textures) + AZStd::vector m_bakedRelocationImageData; + AZStd::vector m_bakedClassificationImageData; + + // texture readback + DiffuseProbeGridTextureReadback m_textureReadback; + // Srgs Data::Instance m_rayTraceSrg; Data::Instance m_blendIrradianceSrg; diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.cpp index 3df13556d3..2a06dacf3f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.cpp @@ -87,7 +87,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetProbeGrids().empty()) + if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids().empty()) { // no diffuse probe grids return; @@ -111,7 +111,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // probe raytrace image { @@ -150,7 +150,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // the diffuse probe grid Srg must be updated in the Compile phase in order to successfully bind the ReadWrite shader inputs // (see ValidateSetImageView() in ShaderResourceGroupData.cpp) @@ -167,7 +167,7 @@ namespace AZ DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); // submit the DispatchItem for each DiffuseProbeGrid - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { const RHI::ShaderResourceGroup* shaderResourceGroup = diffuseProbeGrid->GetBlendDistanceSrg()->GetRHIShaderResourceGroup(); commandList->SetShaderResourceGroupForDispatch(*shaderResourceGroup); diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.cpp index 4e05b8ef31..4818018ea3 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.cpp @@ -87,7 +87,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetProbeGrids().empty()) + if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids().empty()) { // no diffuse probe grids return; @@ -111,7 +111,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // probe raytrace image { @@ -150,7 +150,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // the diffuse probe grid Srg must be updated in the Compile phase in order to successfully bind the ReadWrite shader inputs // (see ValidateSetImageView() in ShaderResourceGroupData.cpp) @@ -167,7 +167,7 @@ namespace AZ DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); // submit the DispatchItem for each DiffuseProbeGrid - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { const RHI::ShaderResourceGroup* shaderResourceGroup = diffuseProbeGrid->GetBlendIrradianceSrg()->GetRHIShaderResourceGroup(); commandList->SetShaderResourceGroupForDispatch(*shaderResourceGroup); diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.cpp index 59549de331..8821de8a9d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.cpp @@ -100,7 +100,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetProbeGrids().empty()) + if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids().empty()) { // no diffuse probe grids return; @@ -124,7 +124,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // probe irradiance image { @@ -153,7 +153,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // the diffuse probe grid Srg must be updated in the Compile phase in order to successfully bind the ReadWrite shader inputs // (see line ValidateSetImageView() in ShaderResourceGroupData.cpp) @@ -173,7 +173,7 @@ namespace AZ DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); // submit the DispatchItems for each DiffuseProbeGrid - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { uint32_t probeCountX; uint32_t probeCountY; diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.cpp index db85914cee..65f1c2dd5a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.cpp @@ -91,7 +91,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetProbeGrids().empty()) + if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids().empty()) { // no diffuse probe grids return; @@ -115,7 +115,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // probe raytrace image { @@ -143,7 +143,7 @@ namespace AZ { RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // the diffuse probe grid Srg must be updated in the Compile phase in order to successfully bind the ReadWrite shader inputs // (see ValidateSetImageView() in ShaderResourceGroupData.cpp) @@ -159,7 +159,7 @@ namespace AZ DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); // submit the DispatchItems for each DiffuseProbeGrid - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { const RHI::ShaderResourceGroup* shaderResourceGroup = diffuseProbeGrid->GetClassificationSrg()->GetRHIShaderResourceGroup(); commandList->SetShaderResourceGroupForDispatch(*shaderResourceGroup); diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp index 1aaa06c797..11d7dc0385 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp @@ -45,6 +45,7 @@ namespace AZ RHI::RHISystemInterface* rhiSystem = RHI::RHISystemInterface::Get(); m_diffuseProbeGrids.reserve(InitialProbeGridAllocationSize); + m_realTimeDiffuseProbeGrids.reserve(InitialProbeGridAllocationSize); RHI::BufferPoolDescriptor desc; desc.m_heapMemoryLevel = RHI::HeapMemoryLevel::Device; @@ -61,7 +62,7 @@ namespace AZ // image pool { RHI::ImagePoolDescriptor imagePoolDesc; - imagePoolDesc.m_bindFlags = RHI::ImageBindFlags::ShaderReadWrite; + imagePoolDesc.m_bindFlags = RHI::ImageBindFlags::ShaderReadWrite | RHI::ImageBindFlags::CopyRead; m_probeGridRenderData.m_imagePool = RHI::Factory::Get().CreateImagePool(); [[maybe_unused]] RHI::ResultCode result = m_probeGridRenderData.m_imagePool->Init(*rhiSystem->GetDevice(), imagePoolDesc); @@ -123,6 +124,32 @@ namespace AZ m_needUpdatePipelineStates = false; } + // check pending textures and connect bus for notifications + for (auto& notificationEntry : m_notifyTextureAssets) + { + if (notificationEntry.m_assetId.IsValid()) + { + // asset already has an assetId + continue; + } + + // query for the assetId + AZ::Data::AssetId assetId; + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetId, + &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, + notificationEntry.m_relativePath.c_str(), + azrtti_typeid(), + false); + + if (assetId.IsValid()) + { + notificationEntry.m_assetId = assetId; + notificationEntry.m_asset.Create(assetId, true); + Data::AssetBus::MultiHandler::BusConnect(assetId); + } + } + // if the volumes changed we need to re-sort the probe list if (m_probeGridSortRequired) { @@ -139,6 +166,7 @@ namespace AZ }; AZStd::sort(m_diffuseProbeGrids.begin(), m_diffuseProbeGrids.end(), sortFn); + AZStd::sort(m_realTimeDiffuseProbeGrids.begin(), m_realTimeDiffuseProbeGrids.end(), sortFn); m_probeGridSortRequired = false; } @@ -160,6 +188,9 @@ namespace AZ diffuseProbeGrid->SetExtents(extents); diffuseProbeGrid->SetProbeSpacing(probeSpacing); m_diffuseProbeGrids.push_back(diffuseProbeGrid); + + UpdateRealTimeList(diffuseProbeGrid); + m_probeGridSortRequired = true; return diffuseProbeGrid; @@ -169,6 +200,7 @@ namespace AZ { AZ_Assert(probeGrid.get(), "RemoveProbeGrid called with an invalid handle"); + // remove from main list auto itEntry = AZStd::find_if(m_diffuseProbeGrids.begin(), m_diffuseProbeGrids.end(), [&](AZStd::shared_ptr const& entry) { return (entry == probeGrid); @@ -176,6 +208,18 @@ namespace AZ AZ_Assert(itEntry != m_diffuseProbeGrids.end(), "RemoveProbeGrid called with a probe grid that is not in the probe list"); m_diffuseProbeGrids.erase(itEntry); + + // remove from side list of real-time grids + itEntry = AZStd::find_if(m_realTimeDiffuseProbeGrids.begin(), m_realTimeDiffuseProbeGrids.end(), [&](AZStd::shared_ptr const& entry) + { + return (entry == probeGrid); + }); + + if (itEntry != m_realTimeDiffuseProbeGrids.end()) + { + m_realTimeDiffuseProbeGrids.erase(itEntry); + } + probeGrid = nullptr; } @@ -247,6 +291,133 @@ namespace AZ probeGrid->SetUseDiffuseIbl(useDiffuseIbl); } + void DiffuseProbeGridFeatureProcessor::BakeTextures( + const DiffuseProbeGridHandle& probeGrid, + DiffuseProbeGridBakeTexturesCallback callback, + const AZStd::string& irradianceTextureRelativePath, + const AZStd::string& distanceTextureRelativePath, + const AZStd::string& relocationTextureRelativePath, + const AZStd::string& classificationTextureRelativePath) + { + AZ_Assert(probeGrid.get(), "BakeTextures called with an invalid handle"); + + AddNotificationEntry(irradianceTextureRelativePath); + AddNotificationEntry(distanceTextureRelativePath); + AddNotificationEntry(relocationTextureRelativePath); + AddNotificationEntry(classificationTextureRelativePath); + + probeGrid->GetTextureReadback().BeginTextureReadback(callback); + } + + void DiffuseProbeGridFeatureProcessor::UpdateRealTimeList(const DiffuseProbeGridHandle& diffuseProbeGrid) + { + if (diffuseProbeGrid->GetMode() == DiffuseProbeGridMode::RealTime) + { + // add to side list of real-time grids + auto itEntry = AZStd::find_if(m_realTimeDiffuseProbeGrids.begin(), m_realTimeDiffuseProbeGrids.end(), [&](AZStd::shared_ptr const& entry) + { + return (entry == diffuseProbeGrid); + }); + + if (itEntry == m_realTimeDiffuseProbeGrids.end()) + { + m_realTimeDiffuseProbeGrids.push_back(diffuseProbeGrid); + } + } + else + { + // remove from side list of real-time grids + auto itEntry = AZStd::find_if(m_realTimeDiffuseProbeGrids.begin(), m_realTimeDiffuseProbeGrids.end(), [&](AZStd::shared_ptr const& entry) + { + return (entry == diffuseProbeGrid); + }); + + if (itEntry != m_realTimeDiffuseProbeGrids.end()) + { + m_realTimeDiffuseProbeGrids.erase(itEntry); + } + } + } + + void DiffuseProbeGridFeatureProcessor::AddNotificationEntry(const AZStd::string& relativePath) + { + AZStd::string assetPath = relativePath + ".streamingimage"; + + // check to see if this is an existing asset + AZ::Data::AssetId assetId; + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetId, + &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, + assetPath.c_str(), + azrtti_typeid(), + false); + + // we only track notifications for new texture assets, existing assets are automatically reloaded by the RPI + if (!assetId.IsValid()) + { + m_notifyTextureAssets.push_back({ assetPath, assetId }); + } + } + + bool DiffuseProbeGridFeatureProcessor::CheckTextureAssetNotification( + const AZStd::string& relativePath, + Data::Asset& outTextureAsset, + DiffuseProbeGridTextureNotificationType& outNotificationType) + { + for (NotifyTextureAssetVector::iterator itNotification = m_notifyTextureAssets.begin(); itNotification != m_notifyTextureAssets.end(); ++itNotification) + { + if (itNotification->m_relativePath == relativePath) + { + outNotificationType = itNotification->m_notificationType; + if (outNotificationType != DiffuseProbeGridTextureNotificationType::None) + { + outTextureAsset = itNotification->m_asset; + m_notifyTextureAssets.erase(itNotification); + } + + return true; + } + } + + return false; + } + + bool DiffuseProbeGridFeatureProcessor::AreBakedTexturesReferenced( + const AZStd::string& irradianceTextureRelativePath, + const AZStd::string& distanceTextureRelativePath, + const AZStd::string& relocationTextureRelativePath, + const AZStd::string& classificationTextureRelativePath) + { + for (auto& diffuseProbeGrid : m_diffuseProbeGrids) + { + if ((diffuseProbeGrid->GetBakedIrradianceRelativePath() == irradianceTextureRelativePath) || + (diffuseProbeGrid->GetBakedDistanceRelativePath() == distanceTextureRelativePath) || + (diffuseProbeGrid->GetBakedRelocationRelativePath() == relocationTextureRelativePath) || + (diffuseProbeGrid->GetBakedClassificationRelativePath() == classificationTextureRelativePath)) + { + return true; + } + } + + return false; + } + + void DiffuseProbeGridFeatureProcessor::SetMode(const DiffuseProbeGridHandle& probeGrid, DiffuseProbeGridMode mode) + { + AZ_Assert(probeGrid.get(), "SetMode called with an invalid handle"); + probeGrid->SetMode(mode); + + UpdateRealTimeList(probeGrid); + + m_probeGridSortRequired = true; + } + + void DiffuseProbeGridFeatureProcessor::SetBakedTextures(const DiffuseProbeGridHandle& probeGrid, const DiffuseProbeGridBakedTextures& bakedTextures) + { + AZ_Assert(probeGrid.get(), "SetBakedTextures called with an invalid handle"); + probeGrid->SetBakedTextures(bakedTextures); + } + void DiffuseProbeGridFeatureProcessor::CreateBoxMesh() { // vertex positions @@ -418,5 +589,34 @@ namespace AZ } } + void DiffuseProbeGridFeatureProcessor::HandleAssetNotification(Data::Asset asset, DiffuseProbeGridTextureNotificationType notificationType) + { + for (NotifyTextureAssetVector::iterator itNotification = m_notifyTextureAssets.begin(); itNotification != m_notifyTextureAssets.end(); ++itNotification) + { + if (itNotification->m_assetId == asset.GetId()) + { + // store the texture asset + itNotification->m_asset = Data::static_pointer_cast(asset); + itNotification->m_notificationType = notificationType; + + // stop notifications on this asset + Data::AssetBus::MultiHandler::BusDisconnect(itNotification->m_assetId); + + break; + } + } + } + + void DiffuseProbeGridFeatureProcessor::OnAssetReady(Data::Asset asset) + { + HandleAssetNotification(asset, DiffuseProbeGridTextureNotificationType::Ready); + } + + void DiffuseProbeGridFeatureProcessor::OnAssetError(Data::Asset asset) + { + AZ_Error("ReflectionProbeFeatureProcessor", false, "Failed to load cubemap [%s]", asset.GetHint().c_str()); + + HandleAssetNotification(asset, DiffuseProbeGridTextureNotificationType::Error); + } } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.h index ad36f8aafa..19e9bf1b1d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.h @@ -22,6 +22,7 @@ namespace AZ //! This class manages DiffuseProbeGrids which generate diffuse global illumination class DiffuseProbeGridFeatureProcessor final : public DiffuseProbeGridFeatureProcessorInterface + , private Data::AssetBus::MultiHandler { public: AZ_RTTI(AZ::Render::DiffuseProbeGridFeatureProcessor, "{BCD232F9-1EBF-4D0D-A5F4-84AEC933A93C}", DiffuseProbeGridFeatureProcessorInterface); @@ -46,6 +47,27 @@ namespace AZ void Enable(const DiffuseProbeGridHandle& probeGrid, bool enable) override; void SetGIShadows(const DiffuseProbeGridHandle& probeGrid, bool giShadows) override; void SetUseDiffuseIbl(const DiffuseProbeGridHandle& probeGrid, bool useDiffuseIbl) override; + void SetMode(const DiffuseProbeGridHandle& probeGrid, DiffuseProbeGridMode mode) override; + void SetBakedTextures(const DiffuseProbeGridHandle& probeGrid, const DiffuseProbeGridBakedTextures& bakedTextures) override; + + void BakeTextures( + const DiffuseProbeGridHandle& probeGrid, + DiffuseProbeGridBakeTexturesCallback callback, + const AZStd::string& irradianceTextureRelativePath, + const AZStd::string& distanceTextureRelativePath, + const AZStd::string& relocationTextureRelativePath, + const AZStd::string& classificationTextureRelativePath) override; + + bool CheckTextureAssetNotification( + const AZStd::string& relativePath, + Data::Asset& outTextureAsset, + DiffuseProbeGridTextureNotificationType& outNotificationType) override; + + bool AreBakedTexturesReferenced( + const AZStd::string& irradianceTextureRelativePath, + const AZStd::string& distanceTextureRelativePath, + const AZStd::string& relocationTextureRelativePath, + const AZStd::string& classificationTextureRelativePath) override; // FeatureProcessor overrides void Activate() override; @@ -56,12 +78,28 @@ namespace AZ using DiffuseProbeGridVector = AZStd::vector>; DiffuseProbeGridVector& GetProbeGrids() { return m_diffuseProbeGrids; } + // retrieve the side list of probe grids that are using real-time (raytraced) mode + DiffuseProbeGridVector& GetRealTimeProbeGrids() { return m_realTimeDiffuseProbeGrids; } + private: AZ_DISABLE_COPY_MOVE(DiffuseProbeGridFeatureProcessor); // create the box vertex and index streams, which are used to render the probe volumes void CreateBoxMesh(); + // AssetBus::MultiHandler overrides... + void OnAssetReady(Data::Asset asset) override; + void OnAssetError(Data::Asset asset) override; + + // updates the real-time list for a specific probe grid + void UpdateRealTimeList(const DiffuseProbeGridHandle& diffuseProbeGrid); + + // adds a notification entry for a new asset + void AddNotificationEntry(const AZStd::string& relativePath); + + // notifies and removes the notification entry + void HandleAssetNotification(Data::Asset asset, DiffuseProbeGridTextureNotificationType notificationType); + // RPI::SceneNotificationBus::Handler overrides void OnRenderPipelinePassesChanged(RPI::RenderPipeline* renderPipeline) override; void OnRenderPipelineAdded(RPI::RenderPipelinePtr pipeline) override; @@ -70,10 +108,13 @@ namespace AZ void UpdatePipelineStates(); void UpdatePasses(); - // list of diffuse probe grids + // list of all diffuse probe grids const size_t InitialProbeGridAllocationSize = 64; DiffuseProbeGridVector m_diffuseProbeGrids; + // side list of diffuse probe grids that are in real-time mode (subset of m_diffuseProbeGrids) + DiffuseProbeGridVector m_realTimeDiffuseProbeGrids; + // position structure for the box vertices struct Position { @@ -102,6 +143,17 @@ namespace AZ // indicates the the diffuse probe grid render pipeline state needs to be updated bool m_needUpdatePipelineStates = false; + + // list of texture assets that we need to check during Simulate() to see if they are ready + struct NotifyTextureAssetEntry + { + AZStd::string m_relativePath; + AZ::Data::AssetId m_assetId; + Data::Asset m_asset; + DiffuseProbeGridTextureNotificationType m_notificationType = DiffuseProbeGridTextureNotificationType::None; + }; + typedef AZStd::vector NotifyTextureAssetVector; + NotifyTextureAssetVector m_notifyTextureAssets; }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.cpp index 143ae1a08c..1062bedae3 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.cpp @@ -132,7 +132,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetProbeGrids().empty()) + if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids().empty()) { // no diffuse probe grids return; @@ -210,10 +210,10 @@ namespace AZ DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor(); - frameGraph.SetEstimatedItemCount(aznumeric_cast(diffuseProbeGridFeatureProcessor->GetProbeGrids().size())); + frameGraph.SetEstimatedItemCount(aznumeric_cast(diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids().size())); frameGraph.ExecuteAfter(m_rayTracingScopeProducerShaderTable->GetScopeId()); - for (const auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (const auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // TLAS { @@ -318,7 +318,7 @@ namespace AZ rayTracingFeatureProcessor->GetMeshInfoBuffer() && rayTracingFeatureProcessor->GetSubMeshCount()) { - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // the diffuse probe grid Srg must be updated in the Compile phase in order to successfully bind the ReadWrite shader // inputs (see line ValidateSetImageView() in ShaderResourceGroupData.cpp) @@ -341,7 +341,7 @@ namespace AZ m_rayTracingShaderTable) { // submit the DispatchRaysItem for each DiffuseProbeGrid - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { const RHI::ShaderResourceGroup* shaderResourceGroups[] = { diffuseProbeGrid->GetRayTraceSrg()->GetRHIShaderResourceGroup(), diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.cpp index 2bd6595b71..86a26f002d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.cpp @@ -91,7 +91,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetProbeGrids().empty()) + if (!diffuseProbeGridFeatureProcessor || diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids().empty()) { // no diffuse probe grids return; @@ -108,7 +108,7 @@ namespace AZ // create the Relocation Srgs for each DiffuseProbeGrid, and check to see if any grids need relocation bool needRelocation = false; - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { uint32_t rayTracingDataRevision = rayTracingFeatureProcessor->GetRevision(); if (rayTracingDataRevision != m_rayTracingDataRevision) @@ -139,7 +139,7 @@ namespace AZ RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // probe raytrace image { @@ -167,7 +167,7 @@ namespace AZ { RPI::Scene* scene = m_pipeline->GetScene(); DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { // the diffuse probe grid Srg must be updated in the Compile phase in order to successfully bind the ReadWrite shader inputs // (see ValidateSetImageView() in ShaderResourceGroupData.cpp) @@ -187,7 +187,7 @@ namespace AZ DiffuseProbeGridFeatureProcessor* diffuseProbeGridFeatureProcessor = scene->GetFeatureProcessor(); // submit the DispatchItems for each DiffuseProbeGrid - for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) { const RHI::ShaderResourceGroup* shaderResourceGroup = diffuseProbeGrid->GetRelocationSrg()->GetRHIShaderResourceGroup(); commandList->SetShaderResourceGroupForDispatch(*shaderResourceGroup); diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.cpp index af6fce6f6a..4f9221a65f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.cpp @@ -79,6 +79,12 @@ namespace AZ params.m_scissorState = scissor; Base::FrameBeginInternal(params); + + for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetRealTimeProbeGrids()) + { + // process attachment readback + diffuseProbeGrid->GetTextureReadback().FrameBegin(params); + } } void DiffuseProbeGridRenderPass::SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) @@ -88,8 +94,21 @@ namespace AZ for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) { + if (diffuseProbeGrid->GetMode() == DiffuseProbeGridMode::Baked && + !diffuseProbeGrid->HasValidBakedTextures()) + { + continue; + } + // probe irradiance image { + if (diffuseProbeGrid->GetMode() == DiffuseProbeGridMode::Baked) + { + // import the irradiance image now, since it is baked and therefore was not imported during the raytracing pass + [[maybe_unused]] RHI::ResultCode result = frameGraph.GetAttachmentDatabase().ImportImage(diffuseProbeGrid->GetIrradianceImageAttachmentId(), diffuseProbeGrid->GetIrradianceImage()); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to import probeIrradianceImage"); + } + RHI::ImageScopeAttachmentDescriptor desc; desc.m_attachmentId = diffuseProbeGrid->GetIrradianceImageAttachmentId(); desc.m_imageViewDescriptor = diffuseProbeGrid->GetRenderData()->m_probeIrradianceImageViewDescriptor; @@ -100,6 +119,13 @@ namespace AZ // probe distance image { + if (diffuseProbeGrid->GetMode() == DiffuseProbeGridMode::Baked) + { + // import the distance image now, since it is baked and therefore was not imported during the raytracing pass + [[maybe_unused]] RHI::ResultCode result = frameGraph.GetAttachmentDatabase().ImportImage(diffuseProbeGrid->GetDistanceImageAttachmentId(), diffuseProbeGrid->GetDistanceImage()); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to import probeDistanceImage"); + } + RHI::ImageScopeAttachmentDescriptor desc; desc.m_attachmentId = diffuseProbeGrid->GetDistanceImageAttachmentId(); desc.m_imageViewDescriptor = diffuseProbeGrid->GetRenderData()->m_probeDistanceImageViewDescriptor; @@ -110,6 +136,13 @@ namespace AZ // probe relocation image { + if (diffuseProbeGrid->GetMode() == DiffuseProbeGridMode::Baked) + { + // import the relocation image now, since it is baked and therefore was not imported during the raytracing pass + [[maybe_unused]] RHI::ResultCode result = frameGraph.GetAttachmentDatabase().ImportImage(diffuseProbeGrid->GetRelocationImageAttachmentId(), diffuseProbeGrid->GetRelocationImage()); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to import probeRelocationImage"); + } + RHI::ImageScopeAttachmentDescriptor desc; desc.m_attachmentId = diffuseProbeGrid->GetRelocationImageAttachmentId(); desc.m_imageViewDescriptor = diffuseProbeGrid->GetRenderData()->m_probeRelocationImageViewDescriptor; @@ -120,6 +153,13 @@ namespace AZ // probe classification image { + if (diffuseProbeGrid->GetMode() == DiffuseProbeGridMode::Baked) + { + // import the classification image now, since it is baked and therefore was not imported during the raytracing pass + [[maybe_unused]] RHI::ResultCode result = frameGraph.GetAttachmentDatabase().ImportImage(diffuseProbeGrid->GetClassificationImageAttachmentId(), diffuseProbeGrid->GetClassificationImage()); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to import probeClassificationImage"); + } + RHI::ImageScopeAttachmentDescriptor desc; desc.m_attachmentId = diffuseProbeGrid->GetClassificationImageAttachmentId(); desc.m_imageViewDescriptor = diffuseProbeGrid->GetRenderData()->m_probeClassificationImageViewDescriptor; @@ -127,6 +167,8 @@ namespace AZ frameGraph.UseShaderAttachment(desc, RHI::ScopeAttachmentAccess::ReadWrite); } + + diffuseProbeGrid->GetTextureReadback().Update(GetName()); } Base::SetupFrameGraphDependencies(frameGraph); @@ -139,6 +181,12 @@ namespace AZ for (auto& diffuseProbeGrid : diffuseProbeGridFeatureProcessor->GetProbeGrids()) { + if (diffuseProbeGrid->GetMode() == DiffuseProbeGridMode::Baked && + !diffuseProbeGrid->HasValidBakedTextures()) + { + continue; + } + // the diffuse probe grid Srg must be updated in the Compile phase in order to successfully bind the ReadWrite shader inputs // (see ValidateSetImageView() of ShaderResourceGroupData.cpp) diffuseProbeGrid->UpdateRenderObjectSrg(); diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp new file mode 100644 index 0000000000..b7fa9c1630 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp @@ -0,0 +1,134 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include + +namespace AZ +{ + namespace Render + { + DiffuseProbeGridTextureReadback::DiffuseProbeGridTextureReadback(DiffuseProbeGrid* diffuseProbeGrid) + : m_diffuseProbeGrid(diffuseProbeGrid) + { + } + + void DiffuseProbeGridTextureReadback::BeginTextureReadback(DiffuseProbeGridBakeTexturesCallback callback) + { + AZ_Assert(m_readbackState == DiffuseProbeGridReadbackState::Idle, "DiffuseProbeGridTextureReadback is already processing a readback request"); + + m_callback = callback; + m_readbackState = DiffuseProbeGridReadbackState::Irradiance; + } + + void DiffuseProbeGridTextureReadback::Update(const AZ::Name& passName) + { + if (m_readbackState == DiffuseProbeGridReadbackState::Idle || m_readbackState == DiffuseProbeGridReadbackState::Complete) + { + return; + } + + if (m_attachmentReadback.get() && m_attachmentReadback->GetReadbackState() > RPI::AttachmentReadback::ReadbackState::Idle) + { + // still processing previous request + return; + } + + AZStd::string readbackName = AZStd::string::format("DiffuseProbeGridReadback_%s", passName.GetCStr()); + RHI::ImageDescriptor descriptor; + RHI::AttachmentId attachmentId; + RPI::AttachmentReadback::CallbackFunction callbackFunction; + + switch (m_readbackState) + { + case DiffuseProbeGridReadbackState::Irradiance: + descriptor = m_diffuseProbeGrid->GetIrradianceImage()->GetDescriptor(); + attachmentId = m_diffuseProbeGrid->GetIrradianceImageAttachmentId(); + callbackFunction = [this](const AZ::RPI::AttachmentReadback::ReadbackResult& readbackResult) + { + m_irradianceReadbackResult = readbackResult; + m_readbackState = DiffuseProbeGridReadbackState::Distance; + }; + break; + case DiffuseProbeGridReadbackState::Distance: + descriptor = m_diffuseProbeGrid->GetDistanceImage()->GetDescriptor(); + attachmentId = m_diffuseProbeGrid->GetDistanceImageAttachmentId(); + callbackFunction = [this](const AZ::RPI::AttachmentReadback::ReadbackResult& readbackResult) + { + m_distanceReadbackResult = readbackResult; + m_readbackState = DiffuseProbeGridReadbackState::Relocation; + }; + break; + case DiffuseProbeGridReadbackState::Relocation: + descriptor = m_diffuseProbeGrid->GetRelocationImage()->GetDescriptor(); + attachmentId = m_diffuseProbeGrid->GetRelocationImageAttachmentId(); + callbackFunction = [this](const AZ::RPI::AttachmentReadback::ReadbackResult& readbackResult) + { + m_relocationReadbackResult = readbackResult; + m_readbackState = DiffuseProbeGridReadbackState::Classification; + }; + break; + case DiffuseProbeGridReadbackState::Classification: + descriptor = m_diffuseProbeGrid->GetClassificationImage()->GetDescriptor(); + attachmentId = m_diffuseProbeGrid->GetClassificationImageAttachmentId(); + callbackFunction = [this](const AZ::RPI::AttachmentReadback::ReadbackResult& readbackResult) + { + m_classificationReadbackResult = readbackResult; + m_readbackState = DiffuseProbeGridReadbackState::Complete; + }; + break; + default: + AZ_Assert(false, "Unknown readback state"); + } + + m_attachmentReadback = AZStd::make_shared(AZ::RHI::ScopeId{ "DiffuseProbeGridTextureReadBack" }); + m_attachmentReadback->SetCallback(callbackFunction); + + AZ::RPI::PassAttachment passAttachment; + passAttachment.m_descriptor = descriptor; + passAttachment.m_path = attachmentId; + passAttachment.m_name = readbackName; + passAttachment.m_lifetime = RHI::AttachmentLifetimeType::Imported; + + m_attachmentReadback->ReadPassAttachment(&passAttachment, AZ::Name(readbackName)); + } + + void DiffuseProbeGridTextureReadback::FrameBegin(AZ::RPI::Pass::FramePrepareParams& params) + { + if (m_readbackState == DiffuseProbeGridReadbackState::Idle) + { + return; + } + + if (!m_attachmentReadback.get()) + { + return; + } + + if (m_readbackState == DiffuseProbeGridReadbackState::Complete) + { + // readback of all textures is complete, invoke callback and return to Idle state + m_callback( + { m_irradianceReadbackResult.m_dataBuffer, m_irradianceReadbackResult.m_imageDescriptor.m_format, m_irradianceReadbackResult.m_imageDescriptor.m_size }, + { m_distanceReadbackResult.m_dataBuffer, m_distanceReadbackResult.m_imageDescriptor.m_format, m_distanceReadbackResult.m_imageDescriptor.m_size }, + { m_relocationReadbackResult.m_dataBuffer, m_relocationReadbackResult.m_imageDescriptor.m_format, m_relocationReadbackResult.m_imageDescriptor.m_size }, + { m_classificationReadbackResult.m_dataBuffer, m_classificationReadbackResult.m_imageDescriptor.m_format, m_classificationReadbackResult.m_imageDescriptor.m_size }); + + m_readbackState = DiffuseProbeGridReadbackState::Idle; + m_attachmentReadback.reset(); + return; + } + + m_attachmentReadback->FrameBegin(params); + } + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.h new file mode 100644 index 0000000000..1becd6fb3e --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.h @@ -0,0 +1,60 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + class DiffuseProbeGrid; + + enum class DiffuseProbeGridReadbackState + { + Idle, + Irradiance, + Distance, + Relocation, + Classification, + Complete + }; + + //! This class contains functionality necessary to read back the DiffuseProbeGrid textures, which + //! allows them to be saved as assets to run the DiffuseProbeGrid in non-realtime mode. + class DiffuseProbeGridTextureReadback final + { + public: + DiffuseProbeGridTextureReadback(DiffuseProbeGrid* diffuseProbeGrid); + ~DiffuseProbeGridTextureReadback() = default; + + void BeginTextureReadback(DiffuseProbeGridBakeTexturesCallback callback); + void Update(const AZ::Name& passName); + void FrameBegin(AZ::RPI::Pass::FramePrepareParams& params); + + private: + + DiffuseProbeGrid* m_diffuseProbeGrid = nullptr; + DiffuseProbeGridReadbackState m_readbackState = DiffuseProbeGridReadbackState::Idle; + AZStd::shared_ptr m_attachmentReadback; + DiffuseProbeGridBakeTexturesCallback m_callback; + + AZ::RPI::AttachmentReadback::ReadbackResult m_irradianceReadbackResult; + AZ::RPI::AttachmentReadback::ReadbackResult m_distanceReadbackResult; + AZ::RPI::AttachmentReadback::ReadbackResult m_relocationReadbackResult; + AZ::RPI::AttachmentReadback::ReadbackResult m_classificationReadbackResult; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake index 8926b0c19f..46a4e06ac2 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -135,6 +135,8 @@ set(FILES Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.h Source/DiffuseProbeGrid/DiffuseProbeGrid.cpp Source/DiffuseProbeGrid/DiffuseProbeGrid.h + Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp + Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.h Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.h Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp Source/DisplayMapper/AcesOutputTransformPass.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp index 0ddace1f87..1ec09995fd 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp @@ -44,7 +44,17 @@ namespace AZ ->Field("AmbientMultiplier", &DiffuseProbeGridComponentConfig::m_ambientMultiplier) ->Field("ViewBias", &DiffuseProbeGridComponentConfig::m_viewBias) ->Field("NormalBias", &DiffuseProbeGridComponentConfig::m_normalBias) - ; + ->Field("EditorMode", &DiffuseProbeGridComponentConfig::m_editorMode) + ->Field("RuntimeMode", &DiffuseProbeGridComponentConfig::m_runtimeMode) + ->Field("BakedIrradianceTextureRelativePath", &DiffuseProbeGridComponentConfig::m_bakedIrradianceTextureRelativePath) + ->Field("BakedDistanceTextureRelativePath", &DiffuseProbeGridComponentConfig::m_bakedDistanceTextureRelativePath) + ->Field("BakedRelocationTextureRelativePath", &DiffuseProbeGridComponentConfig::m_bakedRelocationTextureRelativePath) + ->Field("BakedClassificationTextureRelativePath", &DiffuseProbeGridComponentConfig::m_bakedClassificationTextureRelativePath) + ->Field("BakedIrradianceTextureAsset", &DiffuseProbeGridComponentConfig::m_bakedIrradianceTextureAsset) + ->Field("BakedDistanceTextureAsset", &DiffuseProbeGridComponentConfig::m_bakedDistanceTextureAsset) + ->Field("BakedRelocationTextureAsset", &DiffuseProbeGridComponentConfig::m_bakedRelocationTextureAsset) + ->Field("BakedClassificationTextureAsset", &DiffuseProbeGridComponentConfig::m_bakedClassificationTextureAsset) + ; } } @@ -110,6 +120,26 @@ namespace AZ m_boxShapeInterface = LmbrCentral::BoxShapeComponentRequestsBus::FindFirstHandler(m_entityId); AZ_Assert(m_boxShapeInterface, "DiffuseProbeGridComponentController was unable to find box shape component"); + // special handling is required if this component is being cloned in the editor: + // check to see if the baked textures are already referenced by another DiffuseProbeGrid + if (m_featureProcessor->AreBakedTexturesReferenced( + m_configuration.m_bakedIrradianceTextureRelativePath, + m_configuration.m_bakedDistanceTextureRelativePath, + m_configuration.m_bakedRelocationTextureRelativePath, + m_configuration.m_bakedClassificationTextureRelativePath)) + { + // clear the baked texture paths and assets + m_configuration.m_bakedIrradianceTextureRelativePath.clear(); + m_configuration.m_bakedDistanceTextureRelativePath.clear(); + m_configuration.m_bakedRelocationTextureRelativePath.clear(); + m_configuration.m_bakedClassificationTextureRelativePath.clear(); + + m_configuration.m_bakedIrradianceTextureAsset.Reset(); + m_configuration.m_bakedDistanceTextureAsset.Reset(); + m_configuration.m_bakedRelocationTextureAsset.Reset(); + m_configuration.m_bakedClassificationTextureAsset.Reset(); + } + // add this diffuse probe grid to the feature processor const AZ::Transform& transform = m_transformInterface->GetWorldTM(); m_handle = m_featureProcessor->AddProbeGrid(transform, m_configuration.m_extents, m_configuration.m_probeSpacing); @@ -118,11 +148,61 @@ namespace AZ m_featureProcessor->SetViewBias(m_handle, m_configuration.m_viewBias); m_featureProcessor->SetNormalBias(m_handle, m_configuration.m_normalBias); + // load the baked texture assets, but only if they are all valid + if (m_configuration.m_bakedIrradianceTextureAsset.GetId().IsValid() && + m_configuration.m_bakedDistanceTextureAsset.GetId().IsValid() && + m_configuration.m_bakedRelocationTextureAsset.GetId().IsValid() && + m_configuration.m_bakedClassificationTextureAsset.GetId().IsValid()) + { + Data::AssetBus::MultiHandler::BusConnect(m_configuration.m_bakedIrradianceTextureAsset.GetId()); + Data::AssetBus::MultiHandler::BusConnect(m_configuration.m_bakedDistanceTextureAsset.GetId()); + Data::AssetBus::MultiHandler::BusConnect(m_configuration.m_bakedRelocationTextureAsset.GetId()); + Data::AssetBus::MultiHandler::BusConnect(m_configuration.m_bakedClassificationTextureAsset.GetId()); + + m_configuration.m_bakedIrradianceTextureAsset.QueueLoad(); + m_configuration.m_bakedDistanceTextureAsset.QueueLoad(); + m_configuration.m_bakedRelocationTextureAsset.QueueLoad(); + m_configuration.m_bakedClassificationTextureAsset.QueueLoad(); + } + else if (m_configuration.m_runtimeMode == DiffuseProbeGridMode::Baked || + m_configuration.m_runtimeMode == DiffuseProbeGridMode::AutoSelect || + m_configuration.m_editorMode == DiffuseProbeGridMode::Baked || + m_configuration.m_editorMode == DiffuseProbeGridMode::AutoSelect) + { + AZ_Error("DiffuseProbeGrid", false, "DiffuseProbeGrid mdoe is set to Baked or Auto-Select, but it does not have baked texture assets. Please re-bake this DiffuseProbeGrid."); + } + + m_featureProcessor->SetMode(m_handle, m_configuration.m_runtimeMode); + // set box shape component dimensions from the configuration // this will invoke the OnShapeChanged() handler and set the outer extents on the feature processor m_boxShapeInterface->SetBoxDimensions(m_configuration.m_extents); } + void DiffuseProbeGridComponentController::OnAssetReady(Data::Asset asset) + { + // if all assets are ready we can set the baked texture images + if (m_configuration.m_bakedIrradianceTextureAsset.IsReady() && + m_configuration.m_bakedDistanceTextureAsset.IsReady() && + m_configuration.m_bakedRelocationTextureAsset.IsReady() && + m_configuration.m_bakedClassificationTextureAsset.IsReady()) + { + Data::AssetBus::MultiHandler::BusDisconnect(m_configuration.m_bakedIrradianceTextureAsset.GetId()); + Data::AssetBus::MultiHandler::BusDisconnect(m_configuration.m_bakedDistanceTextureAsset.GetId()); + Data::AssetBus::MultiHandler::BusDisconnect(m_configuration.m_bakedRelocationTextureAsset.GetId()); + Data::AssetBus::MultiHandler::BusDisconnect(m_configuration.m_bakedClassificationTextureAsset.GetId()); + + UpdateBakedTextures(); + } + } + + void DiffuseProbeGridComponentController::OnAssetError(Data::Asset asset) + { + Data::AssetBus::MultiHandler::BusDisconnect(asset.GetId()); + + AZ_Error("DiffuseProbeGrid", false, "Failed to load baked texture [%s], please re-bake this DiffuseProbeGrid.", asset.GetId().ToString().c_str()); + } + void DiffuseProbeGridComponentController::Deactivate() { if (m_featureProcessor) @@ -212,20 +292,96 @@ namespace AZ void DiffuseProbeGridComponentController::SetAmbientMultiplier(float ambientMultiplier) { + if (!m_featureProcessor) + { + return; + } + m_configuration.m_ambientMultiplier = ambientMultiplier; m_featureProcessor->SetAmbientMultiplier(m_handle, m_configuration.m_ambientMultiplier); } void DiffuseProbeGridComponentController::SetViewBias(float viewBias) { + if (!m_featureProcessor) + { + return; + } + m_configuration.m_viewBias = viewBias; m_featureProcessor->SetViewBias(m_handle, m_configuration.m_viewBias); } void DiffuseProbeGridComponentController::SetNormalBias(float normalBias) { + if (!m_featureProcessor) + { + return; + } + m_configuration.m_normalBias = normalBias; m_featureProcessor->SetNormalBias(m_handle, m_configuration.m_normalBias); } + + void DiffuseProbeGridComponentController::SetEditorMode(DiffuseProbeGridMode editorMode) + { + if (!m_featureProcessor) + { + return; + } + + // update the configuration and change the DiffuseProbeGrid mode + m_configuration.m_editorMode = editorMode; + m_featureProcessor->SetMode(m_handle, m_configuration.m_editorMode); + } + + void DiffuseProbeGridComponentController::SetRuntimeMode(DiffuseProbeGridMode runtimeMode) + { + if (!m_featureProcessor) + { + return; + } + + // only update the configuration + m_configuration.m_runtimeMode = runtimeMode; + } + + void DiffuseProbeGridComponentController::BakeTextures(DiffuseProbeGridBakeTexturesCallback callback) + { + if (!m_featureProcessor) + { + return; + } + + m_featureProcessor->BakeTextures( + m_handle, + callback, + m_configuration.m_bakedIrradianceTextureRelativePath, + m_configuration.m_bakedDistanceTextureRelativePath, + m_configuration.m_bakedRelocationTextureRelativePath, + m_configuration.m_bakedClassificationTextureRelativePath); + } + + void DiffuseProbeGridComponentController::UpdateBakedTextures() + { + if (!m_featureProcessor) + { + return; + } + + DiffuseProbeGridBakedTextures bakedTextures; + bakedTextures.m_irradianceImage = RPI::StreamingImage::FindOrCreate(m_configuration.m_bakedIrradianceTextureAsset); + bakedTextures.m_irradianceImageRelativePath = m_configuration.m_bakedIrradianceTextureRelativePath; + bakedTextures.m_distanceImage = RPI::StreamingImage::FindOrCreate(m_configuration.m_bakedDistanceTextureAsset); + bakedTextures.m_distanceImageRelativePath = m_configuration.m_bakedDistanceTextureRelativePath; + bakedTextures.m_relocationImageDescriptor = m_configuration.m_bakedRelocationTextureAsset->GetImageDescriptor(); + bakedTextures.m_relocationImageData = m_configuration.m_bakedRelocationTextureAsset->GetSubImageData(0, 0); + bakedTextures.m_relocationImageRelativePath = m_configuration.m_bakedRelocationTextureRelativePath; + bakedTextures.m_classificationImageDescriptor = m_configuration.m_bakedClassificationTextureAsset->GetImageDescriptor(); + bakedTextures.m_classificationImageData = m_configuration.m_bakedClassificationTextureAsset->GetSubImageData(0, 0); + bakedTextures.m_classificationImageRelativePath = m_configuration.m_bakedClassificationTextureRelativePath; + + m_featureProcessor->SetBakedTextures(m_handle, bakedTextures); + } } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.h index 2bcb4132e9..4122a07ba2 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.h @@ -39,6 +39,19 @@ namespace AZ float m_ambientMultiplier = DefaultDiffuseProbeGridAmbientMultiplier; float m_viewBias = DefaultDiffuseProbeGridViewBias; float m_normalBias = DefaultDiffuseProbeGridNormalBias; + + DiffuseProbeGridMode m_editorMode = DiffuseProbeGridMode::RealTime; + DiffuseProbeGridMode m_runtimeMode = DiffuseProbeGridMode::RealTime; + + AZStd::string m_bakedIrradianceTextureRelativePath; + AZStd::string m_bakedDistanceTextureRelativePath; + AZStd::string m_bakedRelocationTextureRelativePath; + AZStd::string m_bakedClassificationTextureRelativePath; + + Data::Asset m_bakedIrradianceTextureAsset; + Data::Asset m_bakedDistanceTextureAsset; + Data::Asset m_bakedRelocationTextureAsset; + Data::Asset m_bakedClassificationTextureAsset; }; class DiffuseProbeGridComponentController final @@ -79,12 +92,24 @@ namespace AZ // ShapeComponentNotificationsBus overrides void OnShapeChanged(ShapeChangeReasons changeReason) override; + // AssetBus overrides + void OnAssetReady(Data::Asset asset) override; + void OnAssetError(Data::Asset asset) override; + // Property handlers bool ValidateProbeSpacing(const AZ::Vector3& newSpacing); void SetProbeSpacing(const AZ::Vector3& probeSpacing); void SetAmbientMultiplier(float ambientMultiplier); void SetViewBias(float viewBias); void SetNormalBias(float normalBias); + void SetEditorMode(DiffuseProbeGridMode editorMode); + void SetRuntimeMode(DiffuseProbeGridMode runtimeMode); + + // Bake the diffuse probe grid textures to assets + void BakeTextures(DiffuseProbeGridBakeTexturesCallback callback); + + // Update the baked texture assets from the configuration + void UpdateBakedTextures(); // box shape component, used for defining the outer extents of the probe area LmbrCentral::BoxShapeComponentRequests* m_boxShapeInterface = nullptr; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp index ae22ec06c9..162740fe1e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp @@ -16,6 +16,15 @@ #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 AZ { @@ -35,7 +44,9 @@ namespace AZ ->Field("ambientMultiplier", &EditorDiffuseProbeGridComponent::m_ambientMultiplier) ->Field("viewBias", &EditorDiffuseProbeGridComponent::m_viewBias) ->Field("normalBias", &EditorDiffuseProbeGridComponent::m_normalBias) - ; + ->Field("editorMode", &EditorDiffuseProbeGridComponent::m_editorMode) + ->Field("runtimeMode", &EditorDiffuseProbeGridComponent::m_runtimeMode) + ; if (AZ::EditContext* editContext = serializeContext->GetEditContext()) { @@ -48,25 +59,26 @@ namespace AZ ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::PrimaryAssetType, AZ::AzTypeInfo::Uuid()) - ->ClassElement(AZ::Edit::ClassElements::Group, "Probe Spacing") + ->ClassElement(AZ::Edit::ClassElements::Group, "Probe Spacing (meters between probes)") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorDiffuseProbeGridComponent::m_probeSpacingX, "X", "Probe spacing on the X-axis") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorDiffuseProbeGridComponent::m_probeSpacingX, "X", "Probe spacing on the X-axis, in meters") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::ChangeValidate, &EditorDiffuseProbeGridComponent::OnProbeSpacingValidateX) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorDiffuseProbeGridComponent::OnProbeSpacingChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorDiffuseProbeGridComponent::m_probeSpacingY, "Y", "Probe spacing on the Y-axis") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorDiffuseProbeGridComponent::m_probeSpacingY, "Y", "Probe spacing on the Y-axis, in meters") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::ChangeValidate, &EditorDiffuseProbeGridComponent::OnProbeSpacingValidateY) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorDiffuseProbeGridComponent::OnProbeSpacingChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorDiffuseProbeGridComponent::m_probeSpacingZ, "Z", "Probe spacing on the Z-axis") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorDiffuseProbeGridComponent::m_probeSpacingZ, "Z", "Probe spacing on the Z-axis, in meters") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::ChangeValidate, &EditorDiffuseProbeGridComponent::OnProbeSpacingValidateZ) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorDiffuseProbeGridComponent::OnProbeSpacingChanged) ->ClassElement(AZ::Edit::ClassElements::Group, "Grid Settings") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Slider, &EditorDiffuseProbeGridComponent::m_ambientMultiplier, "Ambient Multiplier", "Multiplier for the irradiance intensity") ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorDiffuseProbeGridComponent::OnAmbientMultiplierChanged) - ->Attribute(Edit::Attributes::Decimals, 0) - ->Attribute(Edit::Attributes::Step, 1.0f) + ->Attribute(Edit::Attributes::Decimals, 1) + ->Attribute(Edit::Attributes::Step, 0.1f) ->Attribute(Edit::Attributes::Min, 0.0f) ->Attribute(Edit::Attributes::Max, 10.0f) ->DataElement(AZ::Edit::UIHandlers::Slider, &EditorDiffuseProbeGridComponent::m_viewBias, "View Bias", "View bias adjustment") @@ -81,6 +93,27 @@ namespace AZ ->Attribute(Edit::Attributes::Step, 0.1f) ->Attribute(Edit::Attributes::Min, 0.0f) ->Attribute(Edit::Attributes::Max, 1.0f) + ->ClassElement(AZ::Edit::ClassElements::EditorData, "Grid mode") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(Edit::UIHandlers::ComboBox, &EditorDiffuseProbeGridComponent::m_editorMode, "Editor Mode", "Controls whether the editor uses RealTime or Baked diffuse GI. RealTime requires a ray-tracing capable GPU. Auto-Select will fallback to Baked if ray-tracing is not available") + ->Attribute(AZ::Edit::Attributes::ChangeValidate, &EditorDiffuseProbeGridComponent::OnModeChangeValidate) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorDiffuseProbeGridComponent::OnEditorModeChanged) + ->EnumAttribute(DiffuseProbeGridMode::RealTime, "Real Time (Ray-Traced)") + ->EnumAttribute(DiffuseProbeGridMode::Baked, "Baked") + ->EnumAttribute(DiffuseProbeGridMode::AutoSelect, "Auto Select") + ->DataElement(Edit::UIHandlers::ComboBox, &EditorDiffuseProbeGridComponent::m_runtimeMode, "Runtime Mode", "Controls whether the runtime uses RealTime or Baked diffuse GI. RealTime requires a ray-tracing capable GPU. Auto-Select will fallback to Baked if ray-tracing is not available") + ->Attribute(AZ::Edit::Attributes::ChangeValidate, &EditorDiffuseProbeGridComponent::OnModeChangeValidate) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorDiffuseProbeGridComponent::OnRuntimeModeChanged) + ->EnumAttribute(DiffuseProbeGridMode::RealTime, "Real Time (Ray-Traced)") + ->EnumAttribute(DiffuseProbeGridMode::Baked, "Baked") + ->EnumAttribute(DiffuseProbeGridMode::AutoSelect, "Auto Select") + ->ClassElement(AZ::Edit::ClassElements::Group, "Bake Textures") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->UIElement(AZ::Edit::UIHandlers::Button, "Bake Textures", "Bake the Diffuse Probe Grid textures to static assets that will be used when the mode is set to Baked") + ->Attribute(AZ::Edit::Attributes::NameLabelOverride, "") + ->Attribute(AZ::Edit::Attributes::ButtonText, "Bake Textures") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorDiffuseProbeGridComponent::BakeDiffuseProbeGrid) + ->Attribute(AZ::Edit::Attributes::Visibility, &EditorDiffuseProbeGridComponent::GetBakeDiffuseProbeGridVisibilitySetting) ; editContext->Class( @@ -90,12 +123,6 @@ namespace AZ ->DataElement(AZ::Edit::UIHandlers::Default, &DiffuseProbeGridComponentController::m_configuration, "Configuration", "") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ; - - editContext->Class( - "DiffuseProbeGridComponentConfig", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ; } } @@ -121,15 +148,73 @@ namespace AZ BaseClass::Activate(); AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(GetEntityId()); AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusConnect(GetEntityId()); + AZ::TickBus::Handler::BusConnect(); + AzToolsFramework::EditorEntityInfoNotificationBus::Handler::BusConnect(); } void EditorDiffuseProbeGridComponent::Deactivate() { + AzToolsFramework::EditorEntityInfoNotificationBus::Handler::BusDisconnect(); + AZ::TickBus::Handler::BusDisconnect(); AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusDisconnect(); AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(); BaseClass::Deactivate(); } + void EditorDiffuseProbeGridComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) + { + if (!m_controller.m_featureProcessor) + { + return; + } + + DiffuseProbeGridComponentConfig& configuration = m_controller.m_configuration; + + // set the editor mode, which will override the runtime mode set by the controller + if (!m_editorModeSet) + { + m_controller.m_featureProcessor->SetMode(m_controller.m_handle, configuration.m_editorMode); + m_editorModeSet = true; + } + + CheckTextureAssetNotification(configuration.m_bakedIrradianceTextureRelativePath, configuration.m_bakedIrradianceTextureAsset); + CheckTextureAssetNotification(configuration.m_bakedDistanceTextureRelativePath, configuration.m_bakedDistanceTextureAsset); + CheckTextureAssetNotification(configuration.m_bakedRelocationTextureRelativePath, configuration.m_bakedRelocationTextureAsset); + CheckTextureAssetNotification(configuration.m_bakedClassificationTextureRelativePath, configuration.m_bakedClassificationTextureAsset); + } + + void EditorDiffuseProbeGridComponent::CheckTextureAssetNotification(const AZStd::string& relativePath, Data::Asset& configurationAsset) + { + Data::Asset textureAsset; + DiffuseProbeGridTextureNotificationType notificationType = DiffuseProbeGridTextureNotificationType::None; + if (m_controller.m_featureProcessor->CheckTextureAssetNotification(relativePath + ".streamingimage", textureAsset, notificationType)) + { + if (notificationType == DiffuseProbeGridTextureNotificationType::Ready) + { + // bake is complete, update configuration with the new baked texture asset + AzToolsFramework::ScopedUndoBatch undoBatch("DiffuseProbeGrid Texture Bake"); + configurationAsset = { textureAsset.GetAs(), AZ::Data::AssetLoadBehavior::PreLoad }; + SetDirty(); + + if (m_controller.m_configuration.m_bakedIrradianceTextureAsset.IsReady() && + m_controller.m_configuration.m_bakedDistanceTextureAsset.IsReady() && + m_controller.m_configuration.m_bakedClassificationTextureAsset.IsReady() && + m_controller.m_configuration.m_bakedRelocationTextureAsset.IsReady()) + { + m_controller.UpdateBakedTextures(); + } + } + else if (notificationType == DiffuseProbeGridTextureNotificationType::Error) + { + QMessageBox::information( + QApplication::activeWindow(), + "Diffuse Probe Grid", + "Diffuse Probe Grid texture failed to bake, please check the Asset Processor for more information.", + QMessageBox::Ok); + } + } + } + AZ::Aabb EditorDiffuseProbeGridComponent::GetEditorSelectionBoundsViewport([[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo) { return m_controller.GetAabb(); @@ -140,11 +225,19 @@ namespace AZ return false; } + void EditorDiffuseProbeGridComponent::OnEntityInfoUpdatedVisibility(AZ::EntityId entityId, bool visible) + { + if ((GetEntityId() == entityId) && !visible) + { + m_editorModeSet = false; + } + } + AZ::Outcome EditorDiffuseProbeGridComponent::OnProbeSpacingValidateX(void* newValue, [[maybe_unused]] const AZ::Uuid& valueType) { if (!m_controller.m_featureProcessor) { - return AZ::Failure(AZStd::string("Unable to adjust probe spacing, please try again")); + return AZ::Failure(AZStd::string("This Diffuse Probe Grid entity is hidden, it must be visible in order to change the probe spacing.")); } float newProbeSpacingX = *(reinterpret_cast(newValue)); @@ -152,7 +245,7 @@ namespace AZ Vector3 newSpacing(newProbeSpacingX, m_probeSpacingY, m_probeSpacingZ); if (!m_controller.ValidateProbeSpacing(newSpacing)) { - return AZ::Failure(AZStd::string("Probe spacing exceeds max allowable grid size with current extents")); + return AZ::Failure(AZStd::string("Probe spacing exceeds max allowable grid size with current extents.")); } return AZ::Success(); @@ -162,7 +255,7 @@ namespace AZ { if (!m_controller.m_featureProcessor) { - return AZ::Failure(AZStd::string("Unable to adjust probe spacing, please try again")); + return AZ::Failure(AZStd::string("This Diffuse Probe Grid entity is hidden, it must be visible in order to change the probe spacing.")); } float newProbeSpacingY = *(reinterpret_cast(newValue)); @@ -170,7 +263,7 @@ namespace AZ Vector3 newSpacing(m_probeSpacingX, newProbeSpacingY, m_probeSpacingZ); if (!m_controller.ValidateProbeSpacing(newSpacing)) { - return AZ::Failure(AZStd::string("Probe spacing exceeds max allowable grid size with current extents")); + return AZ::Failure(AZStd::string("Probe spacing exceeds max allowable grid size with current extents.")); } return AZ::Success(); @@ -180,7 +273,7 @@ namespace AZ { if (!m_controller.m_featureProcessor) { - return AZ::Failure(AZStd::string("Unable to adjust probe spacing, please try again")); + return AZ::Failure(AZStd::string("This Diffuse Probe Grid entity is hidden, it must be visible in order to change the probe spacing.")); } float newProbeSpacingZ = *(reinterpret_cast(newValue)); @@ -188,7 +281,7 @@ namespace AZ Vector3 newSpacing(m_probeSpacingX, m_probeSpacingY, newProbeSpacingZ); if (!m_controller.ValidateProbeSpacing(newSpacing)) { - return AZ::Failure(AZStd::string("Probe spacing exceeds max allowable grid size with current extents")); + return AZ::Failure(AZStd::string("Probe spacing exceeds max allowable grid size with current extents.")); } return AZ::Success(); @@ -218,5 +311,226 @@ namespace AZ m_controller.SetNormalBias(m_normalBias); return AZ::Edit::PropertyRefreshLevels::None; } + + AZ::u32 EditorDiffuseProbeGridComponent::OnEditorModeChanged() + { + // this will update the configuration and also change the DiffuseProbeGrid mode + m_controller.SetEditorMode(m_editorMode); + return AZ::Edit::PropertyRefreshLevels::EntireTree; + } + + AZ::u32 EditorDiffuseProbeGridComponent::OnRuntimeModeChanged() + { + // this will only update the configuration + m_controller.SetRuntimeMode(m_runtimeMode); + return AZ::Edit::PropertyRefreshLevels::None; + } + + AZ::Outcome EditorDiffuseProbeGridComponent::OnModeChangeValidate([[maybe_unused]] void* newValue, [[maybe_unused]] const AZ::Uuid& valueType) + { + DiffuseProbeGridMode newMode = (*(reinterpret_cast(newValue))); + + if (newMode == DiffuseProbeGridMode::Baked || newMode == DiffuseProbeGridMode::AutoSelect) + { + if (!m_controller.m_configuration.m_bakedIrradianceTextureAsset.GetId().IsValid() || + !m_controller.m_configuration.m_bakedDistanceTextureAsset.GetId().IsValid() || + !m_controller.m_configuration.m_bakedRelocationTextureAsset.GetId().IsValid() || + !m_controller.m_configuration.m_bakedClassificationTextureAsset.GetId().IsValid()) + { + return AZ::Failure(AZStd::string("Please bake textures before changing the Diffuse Probe Grid to Baked or Auto-Select mode.")); + } + } + + return AZ::Success(); + } + + AZ::u32 EditorDiffuseProbeGridComponent::GetBakeDiffuseProbeGridVisibilitySetting() + { + // the Bake button is visible only when the editor mode is set to RealTime + return m_editorMode == DiffuseProbeGridMode::RealTime ? AZ::Edit::PropertyVisibility::Show : AZ::Edit::PropertyVisibility::Hide; + } + + AZ::u32 EditorDiffuseProbeGridComponent::BakeDiffuseProbeGrid() + { + if (m_bakeInProgress) + { + return AZ::Edit::PropertyRefreshLevels::None; + } + + // retrieve entity visibility + bool isHidden = false; + AzToolsFramework::EditorEntityInfoRequestBus::EventResult( + isHidden, + GetEntityId(), + &AzToolsFramework::EditorEntityInfoRequestBus::Events::IsHidden); + + // the entity must be visible in order to bake + if (isHidden) + { + QMessageBox::information( + QApplication::activeWindow(), + "Diffuse Probe Grid", + "This Diffuse Probe Grid entity is hidden, it must be visible in order to bake textures.", + QMessageBox::Ok); + + return AZ::Edit::PropertyRefreshLevels::None; + } + + DiffuseProbeGridComponentConfig& configuration = m_controller.m_configuration; + + // retrieve the source image paths from the configuration + // Note: we need to make sure to use the same source image for each bake + AZStd::string irradianceTextureRelativePath = ValidateOrCreateNewTexturePath(configuration.m_bakedIrradianceTextureRelativePath, DiffuseProbeGridIrradianceFileName); + AZStd::string distanceTextureRelativePath = ValidateOrCreateNewTexturePath(configuration.m_bakedDistanceTextureRelativePath, DiffuseProbeGridDistanceFileName); + AZStd::string relocationTextureRelativePath = ValidateOrCreateNewTexturePath(configuration.m_bakedRelocationTextureRelativePath, DiffuseProbeGridRelocationFileName); + AZStd::string classificationTextureRelativePath = ValidateOrCreateNewTexturePath(configuration.m_bakedClassificationTextureRelativePath, DiffuseProbeGridClassificationFileName); + + // create the full paths + char projectPath[AZ_MAX_PATH_LEN]; + AZ::IO::FileIOBase::GetInstance()->ResolvePath("@devassets@", projectPath, AZ_MAX_PATH_LEN); + + AZStd::string irradianceTextureFullPath; + AzFramework::StringFunc::Path::Join(projectPath, irradianceTextureRelativePath.c_str(), irradianceTextureFullPath, true, true); + AZStd::string distanceTextureFullPath; + AzFramework::StringFunc::Path::Join(projectPath, distanceTextureRelativePath.c_str(), distanceTextureFullPath, true, true); + AZStd::string relocationTextureFullPath; + AzFramework::StringFunc::Path::Join(projectPath, relocationTextureRelativePath.c_str(), relocationTextureFullPath, true, true); + AZStd::string classificationTextureFullPath; + AzFramework::StringFunc::Path::Join(projectPath, classificationTextureRelativePath.c_str(), classificationTextureFullPath, true, true); + + // make sure the folder is created + AZStd::string diffuseProbeGridFolder; + AzFramework::StringFunc::Path::GetFolderPath(irradianceTextureFullPath.data(), diffuseProbeGridFolder); + AZ::IO::SystemFile::CreateDir(diffuseProbeGridFolder.c_str()); + + // check out the files in source control + CheckoutSourceTextureFile(irradianceTextureFullPath); + CheckoutSourceTextureFile(distanceTextureFullPath); + CheckoutSourceTextureFile(relocationTextureFullPath); + CheckoutSourceTextureFile(classificationTextureFullPath); + + // update the configuration + AzToolsFramework::ScopedUndoBatch undoBatch("DiffuseProbeGrid bake"); + configuration.m_bakedIrradianceTextureRelativePath = irradianceTextureRelativePath; + configuration.m_bakedDistanceTextureRelativePath = distanceTextureRelativePath; + configuration.m_bakedRelocationTextureRelativePath = relocationTextureRelativePath; + configuration.m_bakedClassificationTextureRelativePath = classificationTextureRelativePath; + SetDirty(); + + // callback for the texture readback + DiffuseProbeGridBakeTexturesCallback bakeTexturesCallback = [=]( + DiffuseProbeGridTexture irradianceTexture, + DiffuseProbeGridTexture distanceTexture, + DiffuseProbeGridTexture relocationTexture, + DiffuseProbeGridTexture classificationTexture) + { + // irradiance + { + AZ::DdsFile::DdsFileData fileData = { irradianceTexture.m_size, irradianceTexture.m_format, irradianceTexture.m_data.get() }; + [[maybe_unused]] const auto outcome = AZ::DdsFile::WriteFile(irradianceTextureFullPath, fileData); + AZ_Assert(outcome.IsSuccess(), "Failed to write Irradiance texture .dds file [%s]", irradianceTextureFullPath.c_str()); + } + + // distance + { + AZ::DdsFile::DdsFileData fileData = { distanceTexture.m_size, distanceTexture.m_format, distanceTexture.m_data.get() }; + [[maybe_unused]] const auto outcome = AZ::DdsFile::WriteFile(distanceTextureFullPath, fileData); + AZ_Assert(outcome.IsSuccess(), "Failed to write Distance texture .dds file [%s]", distanceTextureFullPath.c_str()); + } + + // relocation + { + AZ::DdsFile::DdsFileData fileData = { relocationTexture.m_size, relocationTexture.m_format, relocationTexture.m_data.get() }; + [[maybe_unused]] const auto outcome = AZ::DdsFile::WriteFile(relocationTextureFullPath, fileData); + AZ_Assert(outcome.IsSuccess(), "Failed to write Relocation texture .dds file [%s]", relocationTextureFullPath.c_str()); + } + + // classification + { + AZ::DdsFile::DdsFileData fileData = { classificationTexture.m_size, classificationTexture.m_format, classificationTexture.m_data.get() }; + [[maybe_unused]] const auto outcome = AZ::DdsFile::WriteFile(classificationTextureFullPath, fileData); + AZ_Assert(outcome.IsSuccess(), "Failed to write Classification texture .dds file [%s]", classificationTextureFullPath.c_str()); + } + + m_bakeInProgress = false; + }; + + m_bakeInProgress = true; + m_controller.BakeTextures(bakeTexturesCallback); + + while (m_bakeInProgress) + { + QApplication::processEvents(); + AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(100)); + } + + QMessageBox::information( + QApplication::activeWindow(), + "Diffuse Probe Grid", + "Successfully baked Diffuse Probe Grid textures.", + QMessageBox::Ok); + + return AZ::Edit::PropertyRefreshLevels::None; + } + + AZStd::string EditorDiffuseProbeGridComponent::ValidateOrCreateNewTexturePath(const AZStd::string& configurationRelativePath, const char* fileSuffix) + { + AZStd::string relativePath = configurationRelativePath; + AZStd::string fullPath; + + char projectPath[AZ_MAX_PATH_LEN]; + AZ::IO::FileIOBase::GetInstance()->ResolvePath("@devassets@", projectPath, AZ_MAX_PATH_LEN); + + if (!relativePath.empty()) + { + // test to see if the texture file is actually there, if it was removed we need to + // generate a new filename, otherwise it will cause an error in the asset system + AzFramework::StringFunc::Path::Join(projectPath, configurationRelativePath.c_str(), fullPath, true, true); + + if (!AZ::IO::FileIOBase::GetInstance()->Exists(fullPath.c_str())) + { + // file does not exist, clear the relative path so we generate a new name + relativePath.clear(); + } + } + + // build a new image path if necessary + if (relativePath.empty()) + { + // the file name is a combination of the entity name, a UUID, and the filemask + Entity* entity = GetEntity(); + AZ_Assert(entity, "DiffuseProbeGrid entity is null"); + + AZ::Uuid uuid = AZ::Uuid::CreateRandom(); + AZStd::string uuidString; + uuid.ToString(uuidString); + + relativePath = "DiffuseProbeGrids/" + entity->GetName() + uuidString + fileSuffix; + + // replace any invalid filename characters + auto invalidCharacters = [](char letter) + { + return + letter == ':' || letter == '"' || letter == '\'' || + letter == '{' || letter == '}' || + letter == '<' || letter == '>'; + }; + AZStd::replace_if(relativePath.begin(), relativePath.end(), invalidCharacters, '_'); + } + + return relativePath; + } + + void EditorDiffuseProbeGridComponent::CheckoutSourceTextureFile(const AZStd::string& fullPath) + { + bool checkedOutSuccessfully = false; + using ApplicationBus = AzToolsFramework::ToolsApplicationRequestBus; + ApplicationBus::BroadcastResult( + checkedOutSuccessfully, + &ApplicationBus::Events::RequestEditForFileBlocking, + fullPath.c_str(), + "Checking out for edit...", + ApplicationBus::Events::RequestEditProgressCallback()); + } } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.h index 2a50c47b81..15c46d45ba 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.h @@ -12,8 +12,10 @@ #pragma once +#include #include #include +#include #include #include #include @@ -26,6 +28,8 @@ namespace AZ : public EditorRenderComponentAdapter , private AzToolsFramework::EditorComponentSelectionRequestsBus::Handler , private AzFramework::EntityDebugDisplayEventBus::Handler + , private AZ::TickBus::Handler + , private AzToolsFramework::EditorEntityInfoNotificationBus::Handler { public: using BaseClass = EditorRenderComponentAdapter; @@ -41,10 +45,22 @@ namespace AZ void Deactivate() override; private: + + // AZ::TickBus overrides + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + // EditorComponentSelectionRequestsBus overrides AZ::Aabb GetEditorSelectionBoundsViewport(const AzFramework::ViewportInfo& viewportInfo) override; bool SupportsEditorRayIntersect() override; + // EditorEntityInfoNotifications overrides + void OnEntityInfoUpdatedVisibility(AZ::EntityId entityId, bool visible) override; + + // helper functions + AZStd::string ValidateOrCreateNewTexturePath(const AZStd::string& relativePath, const char* fileSuffix); + void CheckoutSourceTextureFile(const AZStd::string& fullPath); + void CheckTextureAssetNotification(const AZStd::string& relativePath, Data::Asset& configurationAsset); + // property change notifications AZ::Outcome OnProbeSpacingValidateX(void* newValue, const AZ::Uuid& valueType); AZ::Outcome OnProbeSpacingValidateY(void* newValue, const AZ::Uuid& valueType); @@ -53,6 +69,13 @@ namespace AZ AZ::u32 OnAmbientMultiplierChanged(); AZ::u32 OnViewBiasChanged(); AZ::u32 OnNormalBiasChanged(); + AZ::u32 OnEditorModeChanged(); + AZ::u32 OnRuntimeModeChanged(); + AZ::Outcome OnModeChangeValidate(void* newValue, const AZ::Uuid& valueType); + + // Button handler + AZ::u32 BakeDiffuseProbeGrid(); + AZ::u32 GetBakeDiffuseProbeGridVisibilitySetting(); // properties float m_probeSpacingX = DefaultDiffuseProbeGridSpacing; @@ -61,6 +84,12 @@ namespace AZ float m_ambientMultiplier = DefaultDiffuseProbeGridAmbientMultiplier; float m_viewBias = DefaultDiffuseProbeGridViewBias; float m_normalBias = DefaultDiffuseProbeGridNormalBias; + DiffuseProbeGridMode m_editorMode = DiffuseProbeGridMode::RealTime; + DiffuseProbeGridMode m_runtimeMode = DiffuseProbeGridMode::RealTime; + + // flags + bool m_editorModeSet = false; + AZStd::atomic_bool m_bakeInProgress = false; }; } // namespace Render } // namespace AZ From dfb0d7f9f567ec0d1d8cfa449b5619190296c231 Mon Sep 17 00:00:00 2001 From: igarri Date: Fri, 21 May 2021 12:33:55 +0100 Subject: [PATCH 095/811] Fixed numeric_cast, style, const variables --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 17 +++++++++-------- .../AssetBrowser/AssetBrowserFilterModel.h | 2 +- .../AssetBrowser/AssetBrowserModel.cpp | 2 +- .../AssetBrowser/AssetBrowserTableModel.cpp | 5 ----- .../AssetBrowser/AssetBrowserTableModel.h | 1 - .../AssetBrowser/Views/AssetBrowserTableView.h | 3 ++- .../AssetBrowser/Views/AssetBrowserTreeView.cpp | 2 +- .../AssetBrowser/Views/EntryDelegate.cpp | 2 +- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 4 ---- 9 files changed, 15 insertions(+), 23 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index c5723832c7..7c7f2aa601 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -135,28 +135,29 @@ namespace AzToolsFramework auto compFilter = qobject_cast >(m_filter); if (compFilter) { - auto& subFilters = compFilter->GetSubFilters(); + const auto& subFilters = compFilter->GetSubFilters(); - auto it = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool + auto compositeFilterIterator = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { - auto assetTypeFilter = qobject_cast >(filter); + const auto assetTypeFilter = qobject_cast >(filter); return !assetTypeFilter.isNull(); }); - if (it != subFilters.end()) + if (compositeFilterIterator != subFilters.end()) { - m_assetTypeFilter = qobject_cast >(*it); + m_assetTypeFilter = qobject_cast >(*compositeFilterIterator); } auto compStringFilterIter = AZStd::find_if(subFilters.begin(), subFilters.end(), [](FilterConstType filter) -> bool { //The real StringFilter is really a CompositeFilter with just one StringFilter in its subfilter list //To know if it is actually a StringFilter we have to get that subfilter and check if it is a Stringfilter. - auto stringCompositeFilter = qobject_cast >(filter); + const auto stringCompositeFilter = qobject_cast >(filter); bool isStringFilter = false; if (stringCompositeFilter) { const auto& stringSubfilters = stringCompositeFilter->GetSubFilters(); - auto canBeCasted = [](FilterConstType filt) -> bool { + auto canBeCasted = [](FilterConstType filt) -> bool + { auto strFilter = qobject_cast>(filt); return !strFilter.isNull(); }; @@ -173,7 +174,7 @@ namespace AzToolsFramework }); if (compStringFilterIter != subFilters.end()) { - auto compStringFilter = qobject_cast>(*compStringFilterIter); + const auto compStringFilter = qobject_cast>(*compStringFilterIter); if (!compStringFilter->GetSubFilters().isEmpty() && compStringFilter->GetSubFilters()[0]) { m_stringFilter = qobject_cast>(compStringFilter->GetSubFilters()[0]); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h index 7a6faf9f18..5d22791699 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.h @@ -68,7 +68,7 @@ namespace AzToolsFramework protected: //set for filtering columns //if the column is in the set the column is not filtered and is shown - AZStd::fixed_unordered_set(AssetBrowserEntry::Column::Count)> m_showColumn; + AZStd::fixed_unordered_set(AssetBrowserEntry::Column::Count)> m_showColumn; bool m_alreadyRecomputingFilters = false; //asset source name match filter FilterConstType m_filter; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp index a5cfad09ba..c0f78baccb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp @@ -163,7 +163,7 @@ namespace AzToolsFramework int AssetBrowserModel::columnCount(const QModelIndex& /*parent*/) const { - return static_cast(AssetBrowserEntry::Column::Count); + return aznumeric_cast(AssetBrowserEntry::Column::Count); } QVariant AssetBrowserModel::data(const QModelIndex& index, int role) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 6d9803dfd4..40f8318a2d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -81,11 +81,6 @@ namespace AzToolsFramework return parent.isValid() ? QModelIndex() : createIndex(row, column, m_indexMap[row].internalPointer()); } - QModelIndex AssetBrowserTableModel::parent([[maybe_unused]] const QModelIndex& child) const - { - return QModelIndex(); - } - int AssetBrowserTableModel::rowCount(const QModelIndex& parent) const { return !parent.isValid() ? m_indexMap.size() : 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index b0497213a0..6b64ceaf92 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -36,7 +36,6 @@ namespace AzToolsFramework // QSortFilterProxyModel void setSourceModel(QAbstractItemModel* sourceModel) override; QModelIndex mapToSource(const QModelIndex& proxyIndex) const override; - QModelIndex parent(const QModelIndex& child) const override; QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; public Q_SLOTS: diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h index 482a072373..65f97d1a6d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -68,7 +68,8 @@ namespace AzToolsFramework protected Q_SLOTS: void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) override; void rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) override; - void layoutChangedSlot(const QList &parents = QList(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint); + void layoutChangedSlot(const QList &parents = QList(), + QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint); private: QString m_name; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp index 660c04ccd4..b93caf85f7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp @@ -176,7 +176,7 @@ namespace AzToolsFramework void AssetBrowserTreeView::OnAssetBrowserComponentReady() { - hideColumn(static_cast(AssetBrowserEntry::Column::Path)); + hideColumn(aznumeric_cast(AssetBrowserEntry::Column::Path)); if (!m_name.isEmpty()) { auto crc = AZ::Crc32(m_name.toUtf8().data()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp index dff8a170c7..c73c00981b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp @@ -75,7 +75,7 @@ namespace AzToolsFramework auto sourceEntry = azrtti_cast(entry); QPalette actualPalette(option.palette); - if (index.column() == static_cast(AssetBrowserEntry::Column::Name)) + if (index.column() == aznumeric_cast(AssetBrowserEntry::Column::Name)) { int thumbX = DrawThumbnail(painter, iconTopLeft, iconSize, entry->GetThumbnailKey()); if (sourceEntry) diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 35734042a0..1b123dd000 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -110,7 +110,6 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) connect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); connect(m_ui->m_viewSwitcherCheckBox, &QCheckBox::stateChanged, this, &AzAssetBrowserWindow::LockToDefaultView); - } m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); @@ -124,17 +123,14 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->m_assetBrowserTreeViewWidget->UpdateAfterFilter(hasFilter, selectFirstFilteredIndex); }); - connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); connect(m_ui->m_assetBrowserTreeViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); - connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, &SearchWidget::ClearStringFilter); connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, &SearchWidget::ClearTypeFilter); - m_ui->m_assetBrowserTreeViewWidget->SetName("AssetBrowserTreeView_main"); } From 7d594a6823a79ea458bd5bddf51fbc780fc5ef5d Mon Sep 17 00:00:00 2001 From: Peng Date: Fri, 21 May 2021 09:12:29 -0700 Subject: [PATCH 096/811] ATOM-15576 [RHI][Vulkan][Android] Set the correct image type for 3D image null descriptor JIRA: https://jira.agscollab.com/browse/ATOM-15576 --- Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.cpp index cdacd2578f..791fa006b0 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.cpp @@ -180,6 +180,7 @@ namespace AZ for (uint32_t imageIndex = static_cast(NullDescriptorManager::ImageTypes::General2D); imageIndex < static_cast(NullDescriptorManager::ImageTypes::Count); imageIndex++) { // different options for the images + imageCreateInfo.imageType = (imageIndex >= static_cast(NullDescriptorManager::ImageTypes::General3D)) ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D; imageCreateInfo.extent = { m_imageNullDescriptor.m_images[imageIndex].m_dimension, m_imageNullDescriptor.m_images[imageIndex].m_dimension, 1 }; imageCreateInfo.samples = m_imageNullDescriptor.m_images[imageIndex].m_sampleCountFlag; imageCreateInfo.format = m_imageNullDescriptor.m_images[imageIndex].m_format; From a7c41064a43a4cf80384f71d521cb09fda69d44e Mon Sep 17 00:00:00 2001 From: puvvadar Date: Fri, 21 May 2021 17:01:10 -0700 Subject: [PATCH 097/811] Update fixed_vector autogen to account for IsRewindable --- .../Source/AutoGen/AutoComponent_Header.jinja | 4 ++-- .../Source/AutoGen/AutoComponent_Source.jinja | 24 ++++++++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index 71e81b6bfb..4061ddd7b6 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -13,7 +13,7 @@ const {{ Property.attrib['Type'] }} &Get{{ PropertyName }}(int32_t index) const; void {{ PropertyName }}AddEvent(AZ::Event::Handler& handler); {% endif %} {% elif Property.attrib['Container'] == 'Vector' %} -const AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> &Get{{ PropertyName }}Vector() const; +const AZStd::fixed_vector<{% if Property.attrib['IsRewindable']|booleanTrue %}RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> &Get{{ PropertyName }}Vector() const; const {{ Property.attrib['Type'] }} &Get{{ PropertyName }}(int32_t index) const; const {{ Property.attrib['Type'] }} &{{ PropertyName }}GetBack() const; uint32_t {{ PropertyName }}GetSize() const; @@ -158,7 +158,7 @@ AZ::Event<{{ Property.attrib['Type'] }}> m_{{ LowerFirst(Property.attrib['Name'] {% if Property.attrib['Container'] == 'Array' %} AZStd::array<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; {% elif Property.attrib['Container'] == 'Vector' %} -AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; +AZStd::fixed_vector<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; {% elif Property.attrib['IsRewindable']|booleanTrue %} Multiplayer::RewindableObject<{{ Property.attrib['Type'] }}, Multiplayer::RewindHistorySize> m_{{ LowerFirst(Property.attrib['Name']) }} = {{ Property.attrib['Init'] }}; {% else %} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 7d5295aabb..3437969901 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -21,7 +21,7 @@ void {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}AddEvent(AZ::Even {% endif %} {% elif Property.attrib['Container'] == 'Vector' %} -const AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const +const AZStd::fixed_vector<{% if Property.attrib['IsRewindable']|booleanTrue %}RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const { return {{ Prefix }}m_{{ LowerFirst(Property.attrib['Name']) }}; } @@ -202,7 +202,7 @@ void {{ ClassName }}::Set{{ UpperFirst(Property.attrib['Name']) }}(int32_t index int32_t bitIndex = index + static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(bitIndex, true); GetParent().MarkDirty(); - return static_cast<{{ Property.attrib['Type'] }}&>(GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}[index]); + return static_cast<{{ Property.attrib['Type'] }}&>(GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}[index]{% if Property.attrib['IsRewindable']|booleanTrue %}.Modify(){% endif %}); } bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PushBack(const {{ Property.attrib['Type'] }} &value) @@ -567,7 +567,7 @@ bool {{ ClassName }}::Serialize{{ AutoComponentMacros.GetNetPropertiesSetName(Re [[maybe_unused]] bool modifyRecord = serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject; {% call(Property) AutoComponentMacros.ParseNetworkProperties(Component, ReplicateFrom, ReplicateTo) %} {% if Property.attrib['Container'] != 'None' and Property.attrib['Container'] != 'Object' %} - { /* @todo Implement serialization for Vector and Array Network Properties + { // Serialization for Vector and Array Network Properties const uint32_t firstBit = static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); {% if Property.attrib['Container'] == 'Vector' %} const uint32_t lastBit = static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}); @@ -575,17 +575,16 @@ bool {{ ClassName }}::Serialize{{ AutoComponentMacros.GetNetPropertiesSetName(Re const uint32_t lastBit = static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'End') }}); {% endif %} - AzNetworking::BitsetView deltaRecord(replicationRecord.m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}, firstBit, lastBit - firstBit + 1); + AzNetworking::FixedSizeBitsetView deltaRecord(replicationRecord.m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}, firstBit, lastBit - firstBit + 1); if (deltaRecord.AnySet()) { {% if Property.attrib['Container'] == 'Vector' %} - Multiplayer::SerializableFixedSizeVectorDeltaStruct<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> deltaStruct(m_{{ LowerFirst(Property.attrib['Name']) }}, deltaRecord); + Multiplayer::SerializableFixedSizeVectorDeltaStruct<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> deltaStruct(m_{{ Property.attrib['Name'] }}, deltaRecord); {% else %} Multiplayer::SerializableFixedSizeArrayDeltaStruct<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> deltaStruct(m_{{ Property.attrib['Name'] }}, deltaRecord); {% endif %} serializer.Serialize(deltaStruct, "{{ UpperFirst(Property.attrib['Name']) }}"); } - */ } {% else %} Multiplayer::SerializeNetworkPropertyHelper @@ -615,7 +614,7 @@ void {{ ClassName }}::NotifyChanges{{ AutoComponentMacros.GetNetPropertiesSetNam {% call(Property) AutoComponentMacros.ParseNetworkProperties(Component, ReplicateFrom, ReplicateTo) %} {% if (Property.attrib['GenerateEventBindings']|booleanTrue) %} {% if Property.attrib['Container'] != 'None' and Property.attrib['Container'] != 'Object' %} - /* todo Implement NotifyChangesAuthorityToClientProperties for Arrays and Vectors + // NotifyChangesAuthorityToClientProperties for Arrays and Vectors for (uint32_t bitIndex = static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}), elementIndex = 0; bitIndex <= static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component, ReplicateFrom, ReplicateTo, Property, 'End') }}); ++bitIndex, ++elementIndex) { if (replicationRecord.m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.GetBit(bitIndex){% if Property.attrib['Container'] == 'Vector' %} && elementIndex < m_{{ Property.attrib['Name'] }}.GetSize(){% endif %}) @@ -627,7 +626,7 @@ void {{ ClassName }}::NotifyChanges{{ AutoComponentMacros.GetNetPropertiesSetNam if (replicationRecord.m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.GetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}))) { m_{{ LowerFirst(Property.attrib['Name']) }}SizeChangedEvent.Signal(m_{{ LowerFirst(Property.attrib['Name']) }}.size()); - } */ + } {% endif %} {% else %} if (replicationRecord.m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.GetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property) }}))) @@ -656,7 +655,7 @@ const {{ Property.attrib['Type'] }}& {{ ClassName }}::Get{{ UpperFirst(Property. } {% elif Property.attrib['Container'] == 'Vector' %} -const AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const +const AZStd::fixed_vector<{% if Property.attrib['IsRewindable']|booleanTrue %}RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const { return {{ Prefix }}m_{{ LowerFirst(Property.attrib['Name']) }}; } @@ -1472,7 +1471,14 @@ namespace {{ Component.attrib['Namespace'] }} { {% for Property in Component.iter('NetworkProperty') %} {% if Property.attrib['IsRewindable']|booleanTrue %} +{% if Property.attrib['Container'] == 'Vector' %} + for ( auto& element: m_{{ LowerFirst(Property.attrib['Name']) }}) + { + element.SetOwningConnectionId(connectionId); + } +{% else %} m_{{ LowerFirst(Property.attrib['Name']) }}.SetOwningConnectionId(connectionId); +{% endif %} {% endif %} {% endfor %} } From 68a5216122f4092e2ec3180962798057d2c992e1 Mon Sep 17 00:00:00 2001 From: sconel Date: Fri, 21 May 2021 17:53:45 -0700 Subject: [PATCH 098/811] First version of spawning Script Canvas node --- .../ScriptCanvas/Libraries/Libraries.cpp | 6 +++ .../ScriptCanvas/Libraries/Libraries.h | 11 ++++ .../SpawnNodeable.ScriptCanvasNodeable.xml | 18 +++++++ .../Libraries/Spawning/SpawnNodeable.cpp | 42 ++++++++++++++++ .../Libraries/Spawning/SpawnNodeable.h | 43 ++++++++++++++++ .../Libraries/Spawning/Spawning.cpp | 50 +++++++++++++++++++ .../Libraries/Spawning/Spawning.h | 17 +++++++ .../Code/scriptcanvasgem_common_files.cmake | 5 ++ 8 files changed, 192 insertions(+) create mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml create mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp create mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h create mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/Spawning.cpp create mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/Spawning.h diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Libraries.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Libraries.cpp index 641bdca8f7..8c2671ac6d 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Libraries.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Libraries.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -33,6 +34,7 @@ namespace ScriptCanvas Entity::InitNodeRegistry(*g_nodeRegistry); Comparison::InitNodeRegistry(*g_nodeRegistry); Time::InitNodeRegistry(*g_nodeRegistry); + Spawning::InitNodeRegistry(*g_nodeRegistry); String::InitNodeRegistry(*g_nodeRegistry); Operators::InitNodeRegistry(*g_nodeRegistry); @@ -61,6 +63,7 @@ namespace ScriptCanvas Entity::Reflect(reflectContext); Comparison::Reflect(reflectContext); Time::Reflect(reflectContext); + Spawning::Reflect(reflectContext); String::Reflect(reflectContext); Operators::Reflect(reflectContext); @@ -90,6 +93,9 @@ namespace ScriptCanvas componentDescriptors = Time::GetComponentDescriptors(); libraryDescriptors.insert(libraryDescriptors.end(), componentDescriptors.begin(), componentDescriptors.end()); + componentDescriptors = Spawning::GetComponentDescriptors(); + libraryDescriptors.insert(libraryDescriptors.end(), componentDescriptors.begin(), componentDescriptors.end()); + componentDescriptors = String::GetComponentDescriptors(); libraryDescriptors.insert(libraryDescriptors.end(), componentDescriptors.begin(), componentDescriptors.end()); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Libraries.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Libraries.h index 3388a029ac..67094f4db8 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Libraries.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Libraries.h @@ -143,6 +143,17 @@ namespace ScriptCanvas }; + struct Spawning : public LibraryDefinition + { + AZ_RTTI(Spawning, "{41E910AE-FBD2-41AD-9173-5105141F0466}", LibraryDefinition); + + static void Reflect(AZ::ReflectContext*); + static void InitNodeRegistry(NodeRegistry& nodeRegistry); + static AZStd::vector GetComponentDescriptors(); + + ~Spawning() override = default; + }; + struct String : public LibraryDefinition { AZ_RTTI(String, "{5B700838-21A2-4579-9303-F4A4822AFEF4}", LibraryDefinition); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml new file mode 100644 index 0000000000..d930e16057 --- /dev/null +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml @@ -0,0 +1,18 @@ + + + + + + + + + + diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp new file mode 100644 index 0000000000..5c72f60625 --- /dev/null +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -0,0 +1,42 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include + +namespace ScriptCanvas +{ + namespace Nodeables + { + namespace Spawning + { + SpawnNodeable::SpawnNodeable() + { + AZ::Data::AssetId cubeAssetId("{90552CB9-2F29-5A2E-976C-61BF7ADACB81}", 272062881); + m_spawnableAsset = AZ::Data::AssetManager::Instance().GetAsset(cubeAssetId, AZ::Data::AssetLoadBehavior::PreLoad); + AZ::Data::AssetManager::Instance().BlockUntilLoadComplete(m_spawnableAsset); + + m_spawnTicket = AzFramework::EntitySpawnTicket(m_spawnableAsset); + } + + SpawnNodeable::SpawnNodeable(const SpawnNodeable& rhs) + { + m_spawnableAsset = rhs.m_spawnableAsset; + m_spawnTicket = AzFramework::EntitySpawnTicket(rhs.m_spawnableAsset); + } + + void SpawnNodeable::Spawn() + { + AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_spawnTicket); + } + } + } +} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h new file mode 100644 index 0000000000..1eb53d53a2 --- /dev/null +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h @@ -0,0 +1,43 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include + +#include +#include +#include +#include + +namespace ScriptCanvas +{ + namespace Nodeables + { + namespace Spawning + { + class SpawnNodeable + : public ScriptCanvas::Nodeable + { + SCRIPTCANVAS_NODE(SpawnNodeable); + public: + SpawnNodeable(); + + SpawnNodeable(const SpawnNodeable& rhs); + + private: + AZ::Data::Asset m_spawnableAsset; + AzFramework::EntitySpawnTicket m_spawnTicket; + }; + } + } +} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/Spawning.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/Spawning.cpp new file mode 100644 index 0000000000..6591950b77 --- /dev/null +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/Spawning.cpp @@ -0,0 +1,50 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include + +namespace ScriptCanvas +{ + namespace Library + { + void Spawning::Reflect(AZ::ReflectContext* reflection) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(reflection)) + { + serializeContext->Class() + ->Version(1) + ; + + AZ::EditContext* editContext = serializeContext->GetEditContext(); + if (editContext) + { + editContext->Class("Spawning", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::Icon, "Icons/ScriptCanvas/Libraries/Entity.png"); + } + } + } + + void Spawning::InitNodeRegistry(NodeRegistry& nodeRegistry) + { + AddNodeToRegistry(nodeRegistry); + } + + AZStd::vector Spawning::GetComponentDescriptors() + { + return AZStd::vector({ + ScriptCanvas::Nodes::SpawnNodeableNode::CreateDescriptor(), + }); + } + } +} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/Spawning.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/Spawning.h new file mode 100644 index 0000000000..fa92ee97a9 --- /dev/null +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/Spawning.h @@ -0,0 +1,17 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +// This header is only meant to include the nodes and should not contain +// shared code +#include diff --git a/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake b/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake index 84391021df..f0be1accc9 100644 --- a/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake +++ b/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake @@ -454,6 +454,11 @@ set(FILES Include/ScriptCanvas/Libraries/Time/TimerNodeable.h Include/ScriptCanvas/Libraries/Time/TimerNodeable.cpp Include/ScriptCanvas/Libraries/Time/TimerNodeable.ScriptCanvasNodeable.xml + Include/ScriptCanvas/Libraries/Spawning/Spawning.cpp + Include/ScriptCanvas/Libraries/Spawning/Spawning.h + Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp + Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h + Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml Include/ScriptCanvas/Libraries/String/Contains.cpp Include/ScriptCanvas/Libraries/String/Contains.h Include/ScriptCanvas/Libraries/String/Contains.ScriptCanvasGrammar.xml From fcdd79eff1c75739007d38951b16f4585b374f70 Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Fri, 21 May 2021 20:22:52 -0700 Subject: [PATCH 099/811] Fixed include file name for Linux build. --- .../Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp index b7fa9c1630..bc619cc277 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include namespace AZ From b42cc19f28280ad4b87c0bc1c4c225aee8f7a816 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Sun, 23 May 2021 21:54:56 -0500 Subject: [PATCH 100/811] Moved the preview.png from the that the o3de engine template script from cmake/Tools directory to the o3de/resources directory --- {cmake/Tools => scripts/o3de/o3de/resources}/preview.png | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {cmake/Tools => scripts/o3de/o3de/resources}/preview.png (100%) diff --git a/cmake/Tools/preview.png b/scripts/o3de/o3de/resources/preview.png similarity index 100% rename from cmake/Tools/preview.png rename to scripts/o3de/o3de/resources/preview.png From e59b154139ab530e99cda544fcea60eadcdb1302 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Sun, 23 May 2021 22:10:09 -0500 Subject: [PATCH 101/811] Updated the refactored o3de command scripts to be able to run standalone by adding a main section Removed the ability to suppress errors in the add-gem-to-cmake and add-external-subdirectory command Reduced duplicate logic in the download.py, register.py and repo.py scripts Removed the registration.py script and moved the registration of those comamnds directly to the o3de.py script Reduced the exception scope in the o3de command scripts to be as constrained as possible. For example instead of having a block of Exception for catching a dictionary KeyError, the block has been updated to just catch KeyError Added a python test for validating the "register.py --this-engine" functionality --- scripts/o3de.py | 81 ++- .../o3de/o3de/add_external_subdirectory.py | 77 ++- scripts/o3de/o3de/add_gem_cmake.py | 86 ++- scripts/o3de/o3de/add_gem_project.py | 78 ++- scripts/o3de/o3de/download.py | 641 ++++-------------- scripts/o3de/o3de/engine_template.py | 89 ++- scripts/o3de/o3de/get_registration.py | 60 +- scripts/o3de/o3de/global_project.py | 15 +- scripts/o3de/o3de/manifest.py | 26 +- scripts/o3de/o3de/print_registration.py | 72 +- scripts/o3de/o3de/register.py | 398 ++++------- scripts/o3de/o3de/registration.py | 92 --- .../o3de/o3de/remove_external_subdirectory.py | 55 +- scripts/o3de/o3de/remove_gem_cmake.py | 59 +- scripts/o3de/o3de/remove_gem_project.py | 74 +- scripts/o3de/o3de/repo.py | 275 ++------ scripts/o3de/o3de/sha256.py | 63 +- scripts/o3de/o3de/utils.py | 44 +- scripts/o3de/o3de/validation.py | 21 +- scripts/o3de/tests/unit_test_registration.py | 57 +- 20 files changed, 1031 insertions(+), 1332 deletions(-) delete mode 100755 scripts/o3de/o3de/registration.py diff --git a/scripts/o3de.py b/scripts/o3de.py index d3b877620f..dabb83b068 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -13,27 +13,70 @@ import argparse import pathlib import sys -# As o3de.py shares the same name as the o3de package attempting to use a regular -# from o3de import line tries to import from the current o3de.py script and not the package -# So the current script directory is removed from the sys.path temporary -SCRIPT_DIR_REMOVED = False -SCRIPT_DIR = pathlib.Path(__file__).parent.resolve() -while str(SCRIPT_DIR) in sys.path: - SCRIPT_DIR_REMOVED = True - sys.path.remove(str(SCRIPT_DIR)) - -from o3de import engine_template -from o3de import global_project -from o3de import registration - -if SCRIPT_DIR_REMOVED: - sys.path.insert(0, str(SCRIPT_DIR)) - def add_args(parser, subparsers) -> None: - global_project.add_args(parser, subparsers) - engine_template.add_args(parser, subparsers) - registration.add_args(parser, subparsers) + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked by o3de.py + Ex o3de.py can invoke the register downloadable commands by importing register, + call add_args and execute: python o3de.py register --gem-path "C:/TestGem" + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + + # As o3de.py shares the same name as the o3de package attempting to use a regular + # from o3de import line tries to import from the current o3de.py script and not the package + # So the current script directory is removed from the sys.path temporary + SCRIPT_DIR_REMOVED = False + SCRIPT_DIR = pathlib.Path(__file__).parent.resolve() + while str(SCRIPT_DIR) in sys.path: + SCRIPT_DIR_REMOVED = True + sys.path.remove(str(SCRIPT_DIR)) + + from o3de import engine_template, global_project, register, print_registration, get_registration, download, \ + add_external_subdirectory, remove_external_subdirectory, add_gem_cmake, remove_gem_cmake, add_gem_project, \ + remove_gem_project, sha256 + + if SCRIPT_DIR_REMOVED: + sys.path.insert(0, str(SCRIPT_DIR)) + + # global_project + global_project.add_args(subparsers) + # engine templaate + engine_template.add_args(subparsers) + + # register + register.add_args(subparsers) + + # show + print_registration.add_args(subparsers) + + # get-registered + get_registration.add_args(subparsers) + + # download + download.add_args(subparsers) + + # add external subdirectories + add_external_subdirectory.add_args(subparsers) + + # remove external subdirectories + remove_external_subdirectory.add_args(subparsers) + + # add gems to cmake + add_gem_cmake.add_args(subparsers) + + # remove gems from cmake + remove_gem_cmake.add_args(subparsers) + + # add a gem to a project + add_gem_project.add_args(subparsers) + + # remove a gem from a project + remove_gem_project.add_args(subparsers) + + # sha256 + sha256.add_args(subparsers) if __name__ == "__main__": diff --git a/scripts/o3de/o3de/add_external_subdirectory.py b/scripts/o3de/o3de/add_external_subdirectory.py index 388f0027da..29013d30c8 100644 --- a/scripts/o3de/o3de/add_external_subdirectory.py +++ b/scripts/o3de/o3de/add_external_subdirectory.py @@ -15,6 +15,7 @@ Contains command to add an external_subdirectory to a project's cmake scripts import argparse import logging import pathlib +import sys from o3de import manifest @@ -22,32 +23,27 @@ logger = logging.getLogger() logging.basicConfig() def add_external_subdirectory(external_subdir: str or pathlib.Path, - engine_path: str or pathlib.Path = None, - suppress_errors: bool = False) -> int: + engine_path: str or pathlib.Path = None) -> int: """ add external subdirectory to a cmake :param external_subdir: external subdirectory to add to cmake :param engine_path: optional engine path, defaults to this engine - :param suppress_errors: optional silence errors :return: 0 for success or non 0 failure code """ external_subdir = pathlib.Path(external_subdir).resolve() if not external_subdir.is_dir(): - if not suppress_errors: - logger.error(f'Add External Subdirectory Failed: {external_subdir} does not exist.') + logger.error(f'Add External Subdirectory Failed: {external_subdir} does not exist.') return 1 external_subdir_cmake = external_subdir / 'CMakeLists.txt' if not external_subdir_cmake.is_file(): - if not suppress_errors: - logger.error(f'Add External Subdirectory Failed: {external_subdir} does not contain a CMakeLists.txt.') + logger.error(f'Add External Subdirectory Failed: {external_subdir} does not contain a CMakeLists.txt.') return 1 json_data = manifest.load_o3de_manifest() engine_object = manifest.find_engine_data(json_data, engine_path) if not engine_object: - if not suppress_errors: - logger.error(f'Add External Subdirectory Failed: {engine_path} not registered.') + logger.error(f'Add External Subdirectory Failed: {engine_path} not registered.') return 1 engine_object.setdefault('external_subdirectories', []) @@ -76,7 +72,7 @@ def add_external_subdirectory(external_subdir: str or pathlib.Path, if end > start + len('include('): try: include_cmake_file = pathlib.Path(engine_path / line[start + len('include('): end]).resolve() - except Exception as e: + except FileNotFoundError as e: pass else: parse_cmake_file(include_cmake_file, files) @@ -88,7 +84,7 @@ def add_external_subdirectory(external_subdir: str or pathlib.Path, try: include_cmake_file = pathlib.Path( cmake_path / line[start + len('add_subdirectory('): end]).resolve() - except Exception as e: + except FileNotFoundError as e: pass else: parse_cmake_file(include_cmake_file, files) @@ -100,8 +96,7 @@ def add_external_subdirectory(external_subdir: str or pathlib.Path, if external_subdir in cmake_files: manifest.save_o3de_manifest(json_data) - if not suppress_errors: - logger.error(f'External subdirectory {external_subdir.as_posix()} already included by add_subdirectory().') + logger.warning(f'External subdirectory {external_subdir.as_posix()} already included by add_subdirectory().') return 1 engine_object['external_subdirectories'].insert(0, external_subdir.as_posix()) @@ -119,23 +114,55 @@ def _run_add_external_subdirectory(args: argparse) -> int: return add_external_subdirectory(args.external_subdirectory) -def add_args(parser, subparsers) -> None: +def add_parser_args(parser): """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here + Ex. Directly run from this file alone with: python add-external-subdirectory.py "/home/foo/external-subdir" + :param parser: the caller passes an argparse parser like instance to this method + """ + parser.add_argument('external_subdirectory', metavar='external_subdirectory', type=str, + help='add an external subdirectory to cmake') + + parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + parser.set_defaults(func=_run_add_external_subdirectory) + + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py add_external_subdirectory "/home/foo/external-subdir" :param subparsers: the caller instantiates subparsers and passes it in here """ add_external_subdirectory_subparser = subparsers.add_parser('add-external-subdirectory') - add_external_subdirectory_subparser.add_argument('external_subdirectory', metavar='external_subdirectory', type=str, - help='add an external subdirectory to cmake') + add_parser_args(add_external_subdirectory_subparser) - add_external_subdirectory_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - add_external_subdirectory_subparser.set_defaults(func=_run_add_external_subdirectory) +def main(): + """ + Runs add_external_subdirectory.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/add_gem_cmake.py b/scripts/o3de/o3de/add_gem_cmake.py index fa2d2f4bb3..523fb8dce8 100644 --- a/scripts/o3de/o3de/add_gem_cmake.py +++ b/scripts/o3de/o3de/add_gem_cmake.py @@ -15,6 +15,7 @@ Contains command to add a gem to a project's cmake scripts import argparse import logging import pathlib +import sys from o3de import add_external_subdirectory, manifest, validation @@ -24,39 +25,33 @@ logging.basicConfig() def add_gem_to_cmake(gem_name: str = None, gem_path: str or pathlib.Path = None, engine_name: str = None, - engine_path: str or pathlib.Path = None, - suppress_errors: bool = False) -> int: + engine_path: str or pathlib.Path = None) -> int: """ add a gem to a cmake as an external subdirectory for an engine :param gem_name: name of the gem to add to cmake :param gem_path: the path of the gem to add to cmake :param engine_name: name of the engine to add to cmake :param engine_path: the path of the engine to add external subdirectory to, default to this engine - :param suppress_errors: optional silence errors :return: 0 for success or non 0 failure code """ if not gem_name and not gem_path: - if not suppress_errors: - logger.error('Must specify either a Gem name or Gem Path.') + logger.error('Must specify either a Gem name or Gem Path.') return 1 if gem_name and not gem_path: gem_path = manifest.get_registered(gem_name=gem_name) if not gem_path: - if not suppress_errors: - logger.error(f'Gem Path {gem_path} has not been registered.') + logger.error(f'Gem Path {gem_path} has not been registered.') return 1 gem_path = pathlib.Path(gem_path).resolve() gem_json = gem_path / 'gem.json' if not gem_json.is_file(): - if not suppress_errors: - logger.error(f'Gem json {gem_json} is not present.') + logger.error(f'Gem json {gem_json} is not present.') return 1 if not validation.valid_o3de_gem_json(gem_json): - if not suppress_errors: - logger.error(f'Gem json {gem_json} is not valid.') + logger.error(f'Gem json {gem_json} is not valid.') return 1 if not engine_name and not engine_path: @@ -66,22 +61,18 @@ def add_gem_to_cmake(gem_name: str = None, engine_path = manifest.get_registered(engine_name=engine_name) if not engine_path: - if not suppress_errors: - logger.error(f'Engine Path {engine_path} has not been registered.') + logger.error(f'Engine Path {engine_path} has not been registered.') return 1 engine_json = engine_path / 'engine.json' if not engine_json.is_file(): - if not suppress_errors: - logger.error(f'Engine json {engine_json} is not present.') + logger.error(f'Engine json {engine_json} is not present.') return 1 if not validation.valid_o3de_engine_json(engine_json): - if not suppress_errors: - logger.error(f'Engine json {engine_json} is not valid.') + logger.error(f'Engine json {engine_json} is not valid.') return 1 - return add_external_subdirectory.add_external_subdirectory(external_subdir=gem_path, engine_path=engine_path, suppress_errors=suppress_errors) - + return add_external_subdirectory.add_external_subdirectory(external_subdir=gem_path, engine_path=engine_path) def _run_add_gem_to_cmake(args: argparse) -> int: if args.override_home_folder: @@ -90,25 +81,58 @@ def _run_add_gem_to_cmake(args: argparse) -> int: return add_gem_to_cmake(gem_name=args.gem_name, gem_path=args.gem_path) -def add_args(parser, subparsers) -> None: +def add_parser_args(parser): """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here + Ex. Directly run from this file alone with: python add_gem_cmake.py --gem-path "/path/to/gem" + :param parser: the caller passes an argparse parser like instance to this method """ - add_gem_to_cmake_subparser = subparsers.add_parser('add-gem-to-cmake') - group = add_gem_to_cmake_subparser.add_mutually_exclusive_group(required=True) + group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-gp', '--gem-path', type=str, required=False, help='The path to the gem.') group.add_argument('-gn', '--gem-name', type=str, required=False, help='The name of the gem.') - add_gem_to_cmake_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, help='By default the home folder is the user folder, override it to this folder.') - add_gem_to_cmake_subparser.set_defaults(func=_run_add_gem_to_cmake) + parser.set_defaults(func=_run_add_gem_to_cmake) + + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py add-gem-to-cmake --gem-path "/path/to/gem" + :param subparsers: the caller instantiates subparsers and passes it in here + """ + add_gem_cmake_subparser = subparsers.add_parser('add-gem-to-cmake') + add_parser_args(add_gem_cmake_subparser) + + +def main(): + """ + Runs add_gem_cmake.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/add_gem_project.py b/scripts/o3de/o3de/add_gem_project.py index 933fd019bb..78dffc4477 100644 --- a/scripts/o3de/o3de/add_gem_project.py +++ b/scripts/o3de/o3de/add_gem_project.py @@ -17,6 +17,7 @@ import json import logging import os import pathlib +import sys from o3de import add_gem_cmake, cmake, manifest, validation @@ -126,13 +127,13 @@ def add_gem_to_project(gem_name: str = None, with project_json.open('r') as s: try: project_json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Error loading Project json {project_json}: {str(e)}') return 1 else: try: engine_name = project_json_data['engine'] - except Exception as e: + except KeyError as e: logger.error(f'Project json {project_json} "engine" not found: {str(e)}') return 1 else: @@ -261,51 +262,84 @@ def _run_add_gem_to_project(args: argparse) -> int: args.add_to_cmake) -def add_args(parser, subparsers) -> None: +def add_parser_args(parser): """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here + Ex. Directly run from this file alone with: python add_gem_project.py --project-path "D:/TestProject" --gem-path "D:/TestGem" + :param parser: the caller passes an argparse parser like instance to this method """ - add_gem_subparser = subparsers.add_parser('add-gem-to-project') - group = add_gem_subparser.add_mutually_exclusive_group(required=True) + group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-pp', '--project-path', type=str, required=False, help='The path to the project.') group.add_argument('-pn', '--project-name', type=str, required=False, help='The name of the project.') - group = add_gem_subparser.add_mutually_exclusive_group(required=True) + group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-gp', '--gem-path', type=str, required=False, help='The path to the gem.') group.add_argument('-gn', '--gem-name', type=str, required=False, help='The name of the gem.') - add_gem_subparser.add_argument('-gt', '--gem-target', type=str, required=False, + parser.add_argument('-gt', '--gem-target', type=str, required=False, help='The cmake target name to add. If not specified it will assume gem_name') - add_gem_subparser.add_argument('-df', '--dependencies-file', type=str, required=False, + parser.add_argument('-df', '--dependencies-file', type=str, required=False, help='The cmake dependencies file in which the gem dependencies are specified.' 'If not specified it will assume ') - add_gem_subparser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, + parser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, default=False, help='Optional toggle if this gem should be added as a runtime dependency') - add_gem_subparser.add_argument('-td', '--tool-dependency', action='store_true', required=False, + parser.add_argument('-td', '--tool-dependency', action='store_true', required=False, default=False, help='Optional toggle if this gem should be added as a tool dependency') - add_gem_subparser.add_argument('-sd', '--server-dependency', action='store_true', required=False, + parser.add_argument('-sd', '--server-dependency', action='store_true', required=False, default=False, help='Optional toggle if this gem should be added as a server dependency') - add_gem_subparser.add_argument('-pl', '--platforms', type=str, required=False, + parser.add_argument('-pl', '--platforms', type=str, required=False, default='Common', help='Optional list of platforms this gem should be added to.' ' Ex. --platforms Mac,Windows,Linux') - add_gem_subparser.add_argument('-a', '--add-to-cmake', type=bool, required=False, + parser.add_argument('-a', '--add-to-cmake', type=bool, required=False, default=True, help='Automatically call add-gem-to-cmake.') - add_gem_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, help='By default the home folder is the user folder, override it to this folder.') - add_gem_subparser.set_defaults(func=_run_add_gem_to_project) + parser.set_defaults(func=_run_add_gem_to_project) + + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py add-gem-to-project --project-path "D:/TestProject" --gem-path "D:/TestGem" + :param subparsers: the caller instantiates subparsers and passes it in here + """ + add_gem_project_subparser = subparsers.add_parser('add-gem-to-project') + add_parser_args(add_gem_project_subparser) + + +def main(): + """ + Runs add_gem_project.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/download.py b/scripts/o3de/o3de/download.py index 3db2f077cd..1dbb584c92 100644 --- a/scripts/o3de/o3de/download.py +++ b/scripts/o3de/o3de/download.py @@ -18,18 +18,90 @@ import json import logging import pathlib import shutil +import sys import urllib.parse import urllib.request -from o3de import manifest, utils, validation +from o3de import manifest, repo, utils, validation logger = logging.getLogger() logging.basicConfig() -def download_engine(engine_name: str, - dest_path: str) -> int: +def unzip_manifest_json_data(download_zip_path: pathlib.Path, zip_file_name: str) -> dict: + json_data = {} + with zipfile.ZipFile(download_zip_path, 'r') as zip_data: + with zip_data.open(zip_file_name) as manifest_json_file: + try: + json_data = json.load(manifest_json_file) + except json.JSONDecodeError as e: + logger.error(f'UnZip exception:{str(e)}') + + return json_data + +def validate_downloaded_zip_sha256(download_uri_json_data: dict, download_zip_path: pathlib.Path, + manifest_json_name) -> int: + # if the engine.json has a sha256 check it against a sha256 of the zip + try: + sha256A = download_uri_json_data['sha256'] + except KeyError as e: + logger.warn(f'SECURITY WARNING: The advertised o3de object you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised object!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the f{manifest_json_name}. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + manifest_json_data = unzip_manifest_json_data(download_zip_path, manifest_json_name) + + # remove the sha256 if present in the advertised downloadable manifest json + # then compare it to the json in the zip, they should now be identical + try: + del download_uri_json_data['sha256'] + except KeyError as e: + pass + + sha256A = hashlib.sha256(json.dumps(download_uri_json_data, indent=4).encode('utf8')).hexdigest() + with unzipped_manifest_json.open('r') as s: + try: + unzipped_manifest_json_data = json.load(s) + except json.JSONDecodeError as e: + logger.error(f'Failed to read manifest json {unzipped_manifest_json}. Unable to confirm this' + f' is the same template that was advertised.') + return 1 + sha256B = hashlib.sha256(json.dumps(unzipped_manifest_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded manifest json does not match' + f' the advertised manifest json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def get_downloadable(engine_name: str = None, + project_name: str = None, + gem_name: str = None, + template_name: str = None, + restricted_name: str = None) -> dict or None: + json_data = manifest.load_o3de_manifest() + try: + o3de_object_uris = json_data['repos'] + except KeyError as key_err: + logger.error(f'Unable to load repos from o3de manifest: {str(key_err)}') + return None + + manifest_json = 'repo.json' + search_func = lambda: repo.search_repo(manifest_json, engine_name, project_name, gem_name, template_name) + return repo.search_o3de_object(manifest_json, o3de_object_uris, search_func) + + +def download_o3de_object(object_name: str, default_folder_name: str, dest_path: str or pathlib.Path, + object_type: str, downloadable_kwarg_key) -> int: if not dest_path: - dest_path = manifest.get_registered(default_folder='engines') + dest_path = manifest.get_registered(default_folder=default_folder_name) if not dest_path: logger.error(f'Destination path not cannot be empty.') return 1 @@ -37,512 +109,50 @@ def download_engine(engine_name: str, dest_path = pathlib.Path(dest_path).resolve() dest_path.mkdir(exist_ok=True) - download_path = manifest.get_o3de_download_folder() / 'engines' / engine_name + download_path = manifest.get_o3de_download_folder() / default_folder_name / object_name download_path.mkdir(exist_ok=True) - download_zip_path = download_path / 'engine.zip' + download_zip_path = download_path / f'{object_type}.zip' - downloadable_engine_data = get_downloadable(engine_name=engine_name) - if not downloadable_engine_data: - logger.error(f'Downloadable engine {engine_name} not found.') + downloadable_object_data = get_downloadable(**{downloadable_kwarg_key : object_name}) + if not downloadable_object_data: + logger.error(f'Downloadable o3de object {object_name} not found.') return 1 - origin = downloadable_engine_data['origin'] - url = f'{origin}/project.zip' + origin = downloadable_json_data['origin'] + url = f'{origin}/object_type.zip' parsed_uri = urllib.parse.urlparse(url) - if download_zip_path.is_file(): - logger.warn(f'Project already downloaded to {download_zip_path}.') - elif parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(url) as s: - with download_zip_path.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, download_zip_path) + download_zip_result = utils.download_zip_file(parsed_uri, download_zip_path) + if download_zip_result != 0: + return download_zip_result - if not zipfile.is_zipfile(download_zip_path): - logger.error(f"Engine zip {download_zip_path} is invalid.") - download_zip_path.unlink() - return 1 + return validate_downloaded_zip_sha256(downloadable_object_data, download_zip_path) - # if the engine.json has a sha256 check it against a sha256 of the zip - try: - sha256A = downloadable_engine_data['sha256'] - except Exception as e: - logger.warn(f'SECURITY WARNING: The advertised engine you downloaded has no "sha256"!!! Be VERY careful!!!' - f' We cannot verify this is the actually the advertised engine!!!') - else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded engine.zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the engine.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - dest_engine_folder = dest_path / engine_name - if dest_engine_folder.is_dir(): - utils.backup_folder(dest_engine_folder) - with zipfile.ZipFile(download_zip_path, 'r') as project_zip: - try: - project_zip.extractall(dest_path) - except Exception as e: - logger.error(f'UnZip exception:{str(e)}') - shutil.rmtree(dest_path) - return 1 - - unzipped_engine_json = dest_engine_folder / 'engine.json' - if not unzipped_engine_json.is_file(): - logger.error(f'Engine json {unzipped_engine_json} is missing.') - return 1 - - if not validation.valid_o3de_engine_json(unzipped_engine_json): - logger.error(f'Engine json {unzipped_engine_json} is invalid.') - return 1 - - # remove the sha256 if present in the advertised downloadable engine.json - # then compare it to the engine.json in the zip, they should now be identical - try: - del downloadable_engine_data['sha256'] - except Exception as e: - pass - - sha256A = hashlib.sha256(json.dumps(downloadable_engine_data, indent=4).encode('utf8')).hexdigest() - with unzipped_engine_json.open('r') as s: - try: - unzipped_engine_json_data = json.load(s) - except Exception as e: - logger.error(f'Failed to read engine json {unzipped_engine_json}. Unable to confirm this' - f' is the same template that was advertised.') - return 1 - sha256B = hashlib.sha256(json.dumps(unzipped_engine_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded engine.json does not match' - f' the advertised engine.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - return 0 +def download_engine(engine_name: str, + dest_path: str or pathlib.Path) -> int: + return download_o3de_object(engine_name, 'engines', dest_path, 'engine', 'engine_name') def download_project(project_name: str, dest_path: str or pathlib.Path) -> int: - if not dest_path: - dest_path = manifest.get_registered(default_folder='projects') - if not dest_path: - logger.error(f'Destination path not specified and not default projects path.') - return 1 - - dest_path = pathlib.Path(dest_path).resolve() - dest_path.mkdir(exist_ok=True, parents=True) - - download_path = manifest.get_o3de_download_folder() / 'projects' / project_name - download_path.mkdir(exist_ok=True, parents=True) - download_zip_path = download_path / 'project.zip' - - downloadable_project_data = get_downloadable(project_name=project_name) - if not downloadable_project_data: - logger.error(f'Downloadable project {project_name} not found.') - return 1 - - origin = downloadable_project_data['origin'] - url = f'{origin}/project.zip' - parsed_uri = urllib.parse.urlparse(url) - - if download_zip_path.is_file(): - logger.warn(f'Project already downloaded to {download_zip_path}.') - elif parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(url) as s: - with download_zip_path.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, download_zip_path) - - if not zipfile.is_zipfile(download_zip_path): - logger.error(f"Project zip {download_zip_path} is invalid.") - download_zip_path.unlink() - return 1 - - # if the project.json has a sha256 check it against a sha256 of the zip - try: - sha256A = downloadable_project_data['sha256'] - except Exception as e: - logger.warn(f'SECURITY WARNING: The advertised project you downloaded has no "sha256"!!! Be VERY careful!!!' - f' We cannot verify this is the actually the advertised project!!!') - else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded project.zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the project.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - dest_project_folder = dest_path / project_name - if dest_project_folder.is_dir(): - utils.backup_folder(dest_project_folder) - with zipfile.ZipFile(download_zip_path, 'r') as project_zip: - try: - project_zip.extractall(dest_project_folder) - except Exception as e: - logger.error(f'UnZip exception:{str(e)}') - shutil.rmtree(dest_path) - return 1 - - unzipped_project_json = dest_project_folder / 'project.json' - if not unzipped_project_json.is_file(): - logger.error(f'Project json {unzipped_project_json} is missing.') - return 1 - - if not validation.valid_o3de_project_json(unzipped_project_json): - logger.error(f'Project json {unzipped_project_json} is invalid.') - return 1 - - # remove the sha256 if present in the advertised downloadable project.json - # then compare it to the project.json in the zip, they should now be identical - try: - del downloadable_project_data['sha256'] - except Exception as e: - pass - - sha256A = hashlib.sha256(json.dumps(downloadable_project_data, indent=4).encode('utf8')).hexdigest() - with unzipped_project_json.open('r') as s: - try: - unzipped_project_json_data = json.load(s) - except Exception as e: - logger.error(f'Failed to read Project json {unzipped_project_json}. Unable to confirm this' - f' is the same project that was advertised.') - return 1 - sha256B = hashlib.sha256(json.dumps(unzipped_project_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded project.json does not match' - f' the advertised project.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - return 0 + return download_o3de_object(project_name, 'projects', dest_path, 'project', 'project_name') def download_gem(gem_name: str, dest_path: str or pathlib.Path) -> int: - if not dest_path: - dest_path = manifest.get_registered(default_folder='gems') - if not dest_path: - logger.error(f'Destination path not cannot be empty.') - return 1 - - dest_path = pathlib.Path(dest_path).resolve() - dest_path.mkdir(exist_ok=True, parents=True) - - download_path = manifest.get_o3de_download_folder() / 'gems' / gem_name - download_path.mkdir(exist_ok=True, parents=True) - download_zip_path = download_path / 'gem.zip' - - downloadable_gem_data = get_downloadable(gem_name=gem_name) - if not downloadable_gem_data: - logger.error(f'Downloadable gem {gem_name} not found.') - return 1 - - origin = downloadable_gem_data['origin'] - url = f'{origin}/gem.zip' - parsed_uri = urllib.parse.urlparse(url) - - if download_zip_path.is_file(): - logger.warn(f'Project already downloaded to {download_zip_path}.') - elif parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(url) as s: - with download_zip_path.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, download_zip_path) - - if not zipfile.is_zipfile(download_zip_path): - logger.error(f"Gem zip {download_zip_path} is invalid.") - download_zip_path.unlink() - return 1 - - # if the gem.json has a sha256 check it against a sha256 of the zip - try: - sha256A = downloadable_gem_data['sha256'] - except Exception as e: - logger.warn(f'SECURITY WARNING: The advertised gem you downloaded has no "sha256"!!! Be VERY careful!!!' - f' We cannot verify this is the actually the advertised gem!!!') - else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded gem.zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the gem.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - dest_gem_folder = dest_path / gem_name - if dest_gem_folder.is_dir(): - utils.backup_folder(dest_gem_folder) - with zipfile.ZipFile(download_zip_path, 'r') as gem_zip: - try: - gem_zip.extractall(dest_path) - except Exception as e: - logger.error(f'UnZip exception:{str(e)}') - shutil.rmtree(dest_path) - return 1 - - unzipped_gem_json = dest_gem_folder / 'gem.json' - if not unzipped_gem_json.is_file(): - logger.error(f'Engine json {unzipped_gem_json} is missing.') - return 1 - - if not validation.valid_o3de_engine_json(unzipped_gem_json): - logger.error(f'Engine json {unzipped_gem_json} is invalid.') - return 1 - - # remove the sha256 if present in the advertised downloadable gem.json - # then compare it to the gem.json in the zip, they should now be identical - try: - del downloadable_gem_data['sha256'] - except Exception as e: - pass - - sha256A = hashlib.sha256(json.dumps(downloadable_gem_data, indent=4).encode('utf8')).hexdigest() - with unzipped_gem_json.open('r') as s: - try: - unzipped_gem_json_data = json.load(s) - except Exception as e: - logger.error(f'Failed to read gem json {unzipped_gem_json}. Unable to confirm this' - f' is the same gem that was advertised.') - return 1 - sha256B = hashlib.sha256(json.dumps(unzipped_gem_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded gem.json does not match' - f' the advertised gem.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - return 0 + return download_o3de_object(gem_name, 'gems', dest_path, 'gem', 'gem_name') def download_template(template_name: str, dest_path: str or pathlib.Path) -> int: - if not dest_path: - dest_path = manifest.get_registered(default_folder='templates') - if not dest_path: - logger.error(f'Destination path not cannot be empty.') - return 1 + return download_o3de_object(template_name, 'templates', dest_path, 'template', 'template_name') - dest_path = pathlib.Path(dest_path).resolve() - dest_path.mkdir(exist_ok=True, parents=True) - - download_path = manifest.get_o3de_download_folder() / 'templates' / template_name - download_path.mkdir(exist_ok=True, parents=True) - download_zip_path = download_path / 'template.zip' - - downloadable_template_data = get_downloadable(template_name=template_name) - if not downloadable_template_data: - logger.error(f'Downloadable template {template_name} not found.') - return 1 - - origin = downloadable_template_data['origin'] - url = f'{origin}/project.zip' - parsed_uri = urllib.parse.urlparse(url) - - result = 0 - - if download_zip_path.is_file(): - logger.warn(f'Project already downloaded to {download_zip_path}.') - elif parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(url) as s: - with download_zip_path.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, download_zip_path) - - if not zipfile.is_zipfile(download_zip_path): - logger.error(f"Template zip {download_zip_path} is invalid.") - download_zip_path.unlink() - return 1 - - # if the template.json has a sha256 check it against a sha256 of the zip - try: - sha256A = downloadable_template_data['sha256'] - except Exception as e: - logger.warn(f'SECURITY WARNING: The advertised template you downloaded has no "sha256"!!! Be VERY careful!!!' - f' We cannot verify this is the actually the advertised template!!!') - else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded template.zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the template.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - dest_template_folder = dest_path / template_name - if dest_template_folder.is_dir(): - utils.backup_folder(dest_template_folder) - with zipfile.ZipFile(download_zip_path, 'r') as project_zip: - try: - project_zip.extractall(dest_path) - except Exception as e: - logger.error(f'UnZip exception:{str(e)}') - shutil.rmtree(dest_path) - return 1 - - unzipped_template_json = dest_template_folder / 'template.json' - if not unzipped_template_json.is_file(): - logger.error(f'Template json {unzipped_template_json} is missing.') - return 1 - - if not validation.valid_o3de_engine_json(unzipped_template_json): - logger.error(f'Template json {unzipped_template_json} is invalid.') - return 1 - - # remove the sha256 if present in the advertised downloadable template.json - # then compare it to the template.json in the zip, they should now be identical - try: - del downloadable_template_data['sha256'] - except Exception as e: - pass - - sha256A = hashlib.sha256(json.dumps(downloadable_template_data, indent=4).encode('utf8')).hexdigest() - with unzipped_template_json.open('r') as s: - try: - unzipped_template_json_data = json.load(s) - except Exception as e: - logger.error(f'Failed to read Template json {unzipped_template_json}. Unable to confirm this' - f' is the same template that was advertised.') - return 1 - sha256B = hashlib.sha256(json.dumps(unzipped_template_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded template.json does not match' - f' the advertised template.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - return 0 def download_restricted(restricted_name: str, dest_path: str or pathlib.Path) -> int: - if not dest_path: - dest_path = manifest.get_registered(default_folder='restricted') - if not dest_path: - logger.error(f'Destination path not cannot be empty.') - return 1 - - dest_path = pathlib.Path(dest_path).resolve() - dest_path.mkdir(exist_ok=True, parents=True) - - download_path = manifest.get_o3de_download_folder() / 'restricted' / restricted_name - download_path.mkdir(exist_ok=True, parents=True) - download_zip_path = download_path / 'restricted.zip' - - downloadable_restricted_data = get_downloadable(restricted_name=restricted_name) - if not downloadable_restricted_data: - logger.error(f'Downloadable Restricted {restricted_name} not found.') - return 1 - - origin = downloadable_restricted_data['origin'] - url = f'{origin}/restricted.zip' - parsed_uri = urllib.parse.urlparse(url) - - if download_zip_path.is_file(): - logger.warn(f'Restricted already downloaded to {download_zip_path}.') - elif parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(url) as s: - with download_zip_path.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, download_zip_path) - - if not zipfile.is_zipfile(download_zip_path): - logger.error(f"Restricted zip {download_zip_path} is invalid.") - download_zip_path.unlink() - return 1 - - # if the restricted.json has a sha256 check it against a sha256 of the zip - try: - sha256A = downloadable_restricted_data['sha256'] - except Exception as e: - logger.warn(f'SECURITY WARNING: The advertised restricted you downloaded has no "sha256"!!! Be VERY careful!!!' - f' We cannot verify this is the actually the advertised restricted!!!') - else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded restricted.zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the restricted.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - dest_restricted_folder = dest_path / restricted_name - if dest_restricted_folder.is_dir(): - utils.backup_folder(dest_restricted_folder) - with zipfile.ZipFile(download_zip_path, 'r') as project_zip: - try: - project_zip.extractall(dest_path) - except Exception as e: - logger.error(f'UnZip exception:{str(e)}') - shutil.rmtree(dest_path) - return 1 - - unzipped_restricted_json = dest_restricted_folder / 'restricted.json' - if not unzipped_restricted_json.is_file(): - logger.error(f'Restricted json {unzipped_restricted_json} is missing.') - return 1 - - if not validation.valid_o3de_engine_json(unzipped_restricted_json): - logger.error(f'Restricted json {unzipped_restricted_json} is invalid.') - return 1 - - # remove the sha256 if present in the advertised downloadable restricted.json - # then compare it to the restricted.json in the zip, they should now be identical - try: - del downloadable_restricted_data['sha256'] - except Exception as e: - pass - - sha256A = hashlib.sha256(json.dumps(downloadable_restricted_data, indent=4).encode('utf8')).hexdigest() - with unzipped_restricted_json.open('r') as s: - try: - unzipped_restricted_json_data = json.load(s) - except Exception as e: - logger.error( - f'Failed to read Restricted json {unzipped_restricted_json}. Unable to confirm this' - f' is the same restricted that was advertised.') - return 1 - sha256B = hashlib.sha256( - json.dumps(unzipped_restricted_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded restricted.json does not match' - f' the advertised restricted.json. Deleting unzipped files!!!') - shutil.rmtree(dest_path) - return 1 - - return 0 + return download_o3de_object(restricted_name, 'restricted', dest_path, 'restricted', 'restricted_name') def _run_download(args: argparse) -> int: @@ -562,20 +172,16 @@ def _run_download(args: argparse) -> int: return download_template(args.template_name, args.dest_path) + return 1 -def add_args(parser, subparsers) -> None: +def add_parser_args(parser): """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here + Ex. Directly run from this file alone with: python download.py --engine-name "o3de" + :param parser: the caller passes an argparse parser like instance to this method """ - download_subparser = subparsers.add_parser('download') - group = download_subparser.add_mutually_exclusive_group(required=True) + group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-e', '--engine-name', type=str, required=False, help='Downloadable engine name.') group.add_argument('-p', '--project-name', type=str, required=False, @@ -584,15 +190,52 @@ def add_args(parser, subparsers) -> None: help='Downloadable gem name.') group.add_argument('-t', '--template-name', type=str, required=False, help='Downloadable template name.') - download_subparser.add_argument('-dp', '--dest-path', type=str, required=False, + parser.add_argument('-dp', '--dest-path', type=str, required=False, default=None, help='Optional destination folder to download into.' - ' i.e. download --project-name "StarterGame" --dest-path "C:/projects"' - ' will result in C:/projects/StarterGame' + ' i.e. download --project-name "AstomSamplerViewer" --dest-path "C:/projects"' + ' will result in C:/projects/AtomSampleViewer' ' If blank will download to default object type folder') - download_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, help='By default the home folder is the user folder, override it to this folder.') - download_subparser.set_defaults(func=_run_download) + parser.set_defaults(func=_run_download) + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py download --engine-name "o3de" + :param subparsers: the caller instantiates subparsers and passes it in here + """ + download_subparser = subparsers.add_parser('download') + add_parser_args(download_subparser) + + +def main(): + """ + Runs download.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/engine_template.py b/scripts/o3de/o3de/engine_template.py index 324c204a43..0c63d4e42e 100755 --- a/scripts/o3de/o3de/engine_template.py +++ b/scripts/o3de/o3de/engine_template.py @@ -79,7 +79,7 @@ restricted_platforms = { } template_file_name = 'template.json' - +this_script_parent = os.path.dirname(os.path.realpath(__file__)) def _transform(s_data: str, replacements: list, @@ -329,7 +329,7 @@ def _instantiate_template(template_json_data: dict, with open(platform_json, 'r') as s: try: json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Failed to load {platform_json}: ' + str(e)) return 1 else: @@ -407,7 +407,7 @@ def create_template(source_path: str, template_path = f'{default_templates_folder}/{template_path}' logger.info(f'Template path not a full path. Using default templates folder {template_path}') if os.path.isdir(template_path): - logger.error(f'Template path {template_path} is already exists.') + logger.error(f'Template path {template_path} already exists.') return 1 # template name is now the last component of the template_path @@ -432,12 +432,12 @@ def create_template(source_path: str, with open(engine_json) as s: try: engine_json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f"Failed to read engine json {engine_json}: {str(e)}") return 1 try: engine_restricted = engine_json_data['restricted_name'] - except Exception as e: + except KeyError as e: logger.error(f"Engine json {engine_json} restricted not found.") return 1 engine_restricted_folder = manifest.get_registered(restricted_name=engine_restricted) @@ -475,12 +475,12 @@ def create_template(source_path: str, with open(restricted_json, 'r') as s: try: restricted_json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Failed to load {restricted_json}: ' + str(e)) return 1 try: template_restricted_name = restricted_json_data['restricted_name'] - except Exception as e: + except KeyError as e: logger.error(f'Failed to read restricted_name from {restricted_json}') return 1 else: @@ -943,8 +943,7 @@ def create_template(source_path: str, s.write(json.dumps(json_data, indent=4)) # copy the default preview.png - this_script_parent = os.path.dirname(os.path.realpath(__file__)) - preview_png_src = f'{this_script_parent}/preview.png' + preview_png_src = f'{this_script_parent}/resources/preview.png' preview_png_dst = f'{template_path}/Template/preview.png' if not os.path.isfile(preview_png_dst): shutil.copy(preview_png_src, preview_png_dst) @@ -1067,14 +1066,14 @@ def create_from_template(destination_path: str, with open(template_json) as s: try: template_json_data = json.load(s) - except Exception as e: + except KeyError as e: logger.error(f'Could read template json {template_json}: {str(e)}.') return 1 # read template name from the json try: template_name = template_json_data['template_name'] - except Exception as e: + except KeyError as e: logger.error(f'Could not read "template_name" from template json {template_json}: {str(e)}.') return 1 @@ -1083,7 +1082,7 @@ def create_from_template(destination_path: str, if not template_restricted_name and not template_restricted_path: try: template_json_restricted_name = template_json_data['restricted_name'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_name' element warn and use it logger.info(f'The template does not specify a "restricted_name".') else: @@ -1100,7 +1099,7 @@ def create_from_template(destination_path: str, # The user specified a --template-restricted-name try: template_json_restricted_name = template_json_data['restricted_name'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_name' element warn and use it logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_name}') @@ -1120,7 +1119,7 @@ def create_from_template(destination_path: str, template_restricted_path = template_restricted_path.replace('\\', '/') try: template_json_restricted_name = template_json_data['restricted_name'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_name' element warn and use it logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_path}') @@ -1154,7 +1153,7 @@ def create_from_template(destination_path: str, try: template_json_restricted_platform_relative_path = template_json_data[ 'restricted_platform_relative_path'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_platform_relative_path' element warn and use it logger.info(f'The template does not specify a "restricted_platform_relative_path".' f' Using {template_restricted_platform_relative_path}') @@ -1175,7 +1174,7 @@ def create_from_template(destination_path: str, try: template_restricted_platform_relative_path = template_json_data[ 'restricted_platform_relative_path'] - except Exception as e: + except KeyError as e: # The template json doesn't have a 'restricted_platform_relative_path' element, set empty string. template_restricted_platform_relative_path = '' @@ -1356,14 +1355,14 @@ def create_project(project_path: str, with open(template_json) as s: try: template_json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Could read template json {template_json}: {str(e)}.') return 1 # read template name from the json try: template_name = template_json_data['template_name'] - except Exception as e: + except KeyError as e: logger.error(f'Could not read "template_name" from template json {template_json}: {str(e)}.') return 1 @@ -1372,7 +1371,7 @@ def create_project(project_path: str, if not template_restricted_name and not template_restricted_path: try: template_json_restricted_name = template_json_data['restricted_name'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_name' element warn and use it logger.info(f'The template does not specify a "restricted_name".') else: @@ -1389,7 +1388,7 @@ def create_project(project_path: str, # The user specified a --template-restricted-name try: template_json_restricted_name = template_json_data['restricted_name'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_name' element warn and use it logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_name}') @@ -1409,7 +1408,7 @@ def create_project(project_path: str, template_restricted_path = template_restricted_path.replace('\\', '/') try: template_json_restricted_name = template_json_data['restricted_name'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_name' element warn and use it logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_path}') @@ -1442,7 +1441,7 @@ def create_project(project_path: str, try: template_json_restricted_platform_relative_path = template_json_data[ 'restricted_platform_relative_path'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_platform_relative_path' element warn and use it logger.info(f'The template does not specify a "restricted_platform_relative_path".' f' Using {template_restricted_platform_relative_path}') @@ -1463,7 +1462,7 @@ def create_project(project_path: str, try: template_restricted_platform_relative_path = template_json_data[ 'restricted_platform_relative_path'] - except Exception as e: + except KeyError as e: # The template json doesn't have a 'restricted_platform_relative_path' element, set empty string. template_restricted_platform_relative_path = '' if not template_restricted_platform_relative_path: @@ -1597,13 +1596,13 @@ def create_project(project_path: str, with open(restricted_json, 'r') as s: try: restricted_json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Failed to load restricted json {restricted_json}.') return 1 try: restricted_name = restricted_json_data["restricted_name"] - except Exception as e: + except KeyError as e: logger.error(f'Failed to read "restricted_name" from restricted json {restricted_json}.') return 1 @@ -1616,7 +1615,7 @@ def create_project(project_path: str, with open(project_json, 'r') as s: try: project_json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Failed to load project json {project_json}.') return 1 @@ -1625,7 +1624,7 @@ def create_project(project_path: str, with open(project_json, 'w') as s: try: s.write(json.dumps(project_json_data, indent=4)) - except Exception as e: + except OSError as e: logger.error(f'Failed to write project json {project_json}.') return 1 @@ -1656,7 +1655,7 @@ def create_project(project_path: str, engine_json_data = manifest.get_engine_json_data(engine_path=manifest.get_this_engine_path()) try: engine_name = engine_json_data['engine_name'] - except Exception as e: + except KeyError as e: logger.error(f"engine_name for this engine not found in engine.json.") return 1 @@ -1665,7 +1664,7 @@ def create_project(project_path: str, with open(project_json, 'w') as s: try: s.write(json.dumps(project_json_data, indent=4)) - except Exception as e: + except OSError as e: logger.error(f'Failed to write project json at {project_path}.') return 1 @@ -1749,14 +1748,14 @@ def create_gem(gem_path: str, with open(template_json) as s: try: template_json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Could read template json {template_json}: {str(e)}.') return 1 # read template name from the json try: template_name = template_json_data['template_name'] - except Exception as e: + except KeyError as e: logger.error(f'Could not read "template_name" from template json {template_json}: {str(e)}.') return 1 @@ -1765,7 +1764,7 @@ def create_gem(gem_path: str, if not template_restricted_name and not template_restricted_path: try: template_json_restricted_name = template_json_data['restricted_name'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_name' element warn and use it logger.info(f'The template does not specify a "restricted_name".') else: @@ -1781,7 +1780,7 @@ def create_gem(gem_path: str, # The user specified a --template-restricted-name try: template_json_restricted_name = template_json_data['restricted_name'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_name' element warn and use it logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_name}') @@ -1801,7 +1800,7 @@ def create_gem(gem_path: str, template_restricted_path = template_restricted_path.replace('\\', '/') try: template_json_restricted_name = template_json_data['restricted_name'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_name' element warn and use it logger.info(f'The template does not specify a "restricted_name".' f' Using supplied {template_restricted_path}') @@ -1833,7 +1832,7 @@ def create_gem(gem_path: str, try: template_json_restricted_platform_relative_path = template_json_data[ 'restricted_platform_relative_path'] - except Exception as e: + except KeyError as e: # the template json doesn't have a 'restricted_platform_relative_path' element warn and use it logger.info(f'The template does not specify a "restricted_platform_relative_path".' f' Using {template_restricted_platform_relative_path}') @@ -1854,7 +1853,7 @@ def create_gem(gem_path: str, try: template_restricted_platform_relative_path = template_json_data[ 'restricted_platform_relative_path'] - except Exception as e: + except KeyError as e: # The template json doesn't have a 'restricted_platform_relative_path' element, set empty string. template_restricted_platform_relative_path = '' if not template_restricted_platform_relative_path: @@ -1988,13 +1987,13 @@ def create_gem(gem_path: str, with open(restricted_json, 'r') as s: try: restricted_json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Failed to load restricted json {restricted_json}.') return 1 try: restricted_name = restricted_json_data["restricted_name"] - except Exception as e: + except KeyError as e: logger.error(f'Failed to read "restricted_name" from restricted json {restricted_json}.') return 1 @@ -2007,7 +2006,7 @@ def create_gem(gem_path: str, with open(gem_json, 'r') as s: try: gem_json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Failed to load gem json {gem_json}.') return 1 @@ -2016,7 +2015,7 @@ def create_gem(gem_path: str, with open(gem_json, 'w') as s: try: s.write(json.dumps(gem_json_data, indent=4)) - except Exception as e: + except OSError as e: logger.error(f'Failed to write project json {gem_json}.') return 1 @@ -2110,15 +2109,14 @@ def _run_create_gem(args: argparse) -> int: args.module_id) -def add_args(parser, subparsers) -> None: +def add_args(subparsers) -> None: """ add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be invoked locally or aggregated by a central python file. - Ex. Directly run from this file alone with: python engine_template.py create_gem --gem-path TestGem + Ex. Directly run from this file alone with: python engine_template.py create-gem --gem-path TestGem OR o3de.py can aggregate commands by importing engine_template, - call add_args and execute: python o3de.py create_gem --gem-path TestGem - :param parser: the caller instantiates a parser and passes it in here + call add_args and execute: python o3de.py create-gem --gem-path TestGem :param subparsers: the caller instantiates subparsers and passes it in here """ # turn a directory into a template @@ -2438,13 +2436,12 @@ if __name__ == "__main__": the_subparsers = the_parser.add_subparsers(help='sub-command help', dest='command', required=True) # add args to the parser - add_args(the_parser, the_subparsers) + add_args(the_subparsers) # parse args the_args = the_parser.parse_args() # run - ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 # return diff --git a/scripts/o3de/o3de/get_registration.py b/scripts/o3de/o3de/get_registration.py index c38d4d1cfb..d51600826c 100644 --- a/scripts/o3de/o3de/get_registration.py +++ b/scripts/o3de/o3de/get_registration.py @@ -11,6 +11,7 @@ import argparse import pathlib +import sys from o3de import manifest @@ -27,19 +28,14 @@ def _run_get_registered(args: argparse) -> str or pathlib.Path: args.restricted_name) -def add_args(parser, subparsers) -> None: +def add_parser_args(parser): """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here + Ex. Directly run from this file alone with: python get_registration.py --engine-name "o3de" + :param parser: the caller passes an argparse parser like instance to this method """ - get_registered_subparser = subparsers.add_parser('get-registered') - group = get_registered_subparser.add_mutually_exclusive_group(required=True) + group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-en', '--engine-name', type=str, required=False, help='Engine name.') group.add_argument('-pn', '--project-name', type=str, required=False, @@ -56,7 +52,45 @@ def add_args(parser, subparsers) -> None: group.add_argument('-rsn', '--restricted-name', type=str, required=False, help='Restricted name.') - get_registered_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') + parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') - get_registered_subparser.set_defaults(func=_run_get_registered) + parser.set_defaults(func=_run_get_registered) + + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py get-registered --engine-name "o3de" + :param subparsers: the caller instantiates subparsers and passes it in here + """ + get_registered_subparser = subparsers.add_parser('get-registered') + add_parser_args(get_registered_subparser) + + +def main(): + """ + Runs get_registration.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/global_project.py b/scripts/o3de/o3de/global_project.py index 1a17e3b79e..787e676a7e 100644 --- a/scripts/o3de/o3de/global_project.py +++ b/scripts/o3de/o3de/global_project.py @@ -52,17 +52,17 @@ def set_global_project(project_name: str or None, with bootstrap_setreg_file.open('r') as f: try: json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Bootstrap.setreg failed to load: {str(e)}') else: try: json_data["Amazon"]["AzCore"]["Bootstrap"]["project_path"] = project_path - except Exception as e: + except KeyError as e: logger.error(f'Bootstrap.setreg failed to load: {str(e)}') else: try: os.unlink(bootstrap_setreg_file) - except Exception as e: + except OSError as e: logger.error(f'Failed to unlink bootstrap file {bootstrap_setreg_file}: {str(e)}') return 1 else: @@ -88,12 +88,12 @@ def get_global_project() -> pathlib.Path or None: with bootstrap_setreg_file.open('r') as f: try: json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Bootstrap.setreg failed to load: {str(e)}') else: try: project_path = json_data["Amazon"]["AzCore"]["Bootstrap"]["project_path"] - except Exception as e: + except KeyError as e: logger.error(f'Bootstrap.setreg cannot find Amazon:AzCore:Bootstrap:project_path: {str(e)}') else: return pathlib.Path(project_path).resolve() @@ -118,7 +118,7 @@ def _run_set_global_project(args: argparse) -> int: args.project_path) -def add_args(parser, subparsers) -> None: +def add_args(subparsers) -> None: """ add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be invoked locally or aggregated by a central python file. @@ -126,7 +126,6 @@ def add_args(parser, subparsers) -> None: OR o3de.py can aggregate commands by importing global_project, call add_args and execute: python o3de.py set_global_project --project-path C:/TestProject - :param parser: the caller instantiates a parser and passes it in here :param subparsers: the caller instantiates subparsers and passes it in here """ get_global_project_subparser = subparsers.add_parser('get-global-project') @@ -156,7 +155,7 @@ if __name__ == "__main__": the_subparsers = the_parser.add_subparsers(help='sub-command help', dest='command', required=True) # add args to the parser - add_args(the_parser, the_subparsers) + add_args(the_subparsers) # parse args the_args = the_parser.parse_args() diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index 44d6ff1b61..6c14c2533f 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -176,7 +176,7 @@ def load_o3de_manifest() -> dict: with get_o3de_manifest().open('r') as f: try: json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Manifest json failed to load: {str(e)}') return {} else: @@ -187,7 +187,7 @@ def save_o3de_manifest(json_data: dict) -> None: with get_o3de_manifest().open('w') as s: try: s.write(json.dumps(json_data, indent=4)) - except Exception as e: + except OSError as e: logger.error(f'Manifest json failed to save: {str(e)}') @@ -331,7 +331,7 @@ def get_engine_json_data(engine_name: str = None, with engine_json.open('r') as f: try: engine_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{engine_json} failed to load: {str(e)}') else: return engine_json_data @@ -364,7 +364,7 @@ def get_project_json_data(project_name: str = None, with project_json.open('r') as f: try: project_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{project_json} failed to load: {str(e)}') else: return project_json_data @@ -397,7 +397,7 @@ def get_gem_json_data(gem_name: str = None, with gem_json.open('r') as f: try: gem_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{gem_json} failed to load: {str(e)}') else: return gem_json_data @@ -430,7 +430,7 @@ def get_template_json_data(template_name: str = None, with template_json.open('r') as f: try: template_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{template_json} failed to load: {str(e)}') else: return template_json_data @@ -463,7 +463,7 @@ def get_restricted_data(restricted_name: str = None, with restricted_json.open('r') as f: try: restricted_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{restricted_json} failed to load: {str(e)}') else: return restricted_json_data @@ -488,7 +488,7 @@ def get_registered(engine_name: str = None, with engine_json.open('r') as f: try: engine_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{engine_json} failed to load: {str(e)}') else: this_engines_name = engine_json_data['engine_name'] @@ -505,7 +505,7 @@ def get_registered(engine_name: str = None, with project_json.open('r') as f: try: project_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{project_json} failed to load: {str(e)}') else: this_projects_name = project_json_data['project_name'] @@ -522,7 +522,7 @@ def get_registered(engine_name: str = None, with gem_json.open('r') as f: try: gem_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{gem_json} failed to load: {str(e)}') else: this_gems_name = gem_json_data['gem_name'] @@ -539,7 +539,7 @@ def get_registered(engine_name: str = None, with template_json.open('r') as f: try: template_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{template_path} failed to load: {str(e)}') else: this_templates_name = template_json_data['template_name'] @@ -556,7 +556,7 @@ def get_registered(engine_name: str = None, with restricted_json.open('r') as f: try: restricted_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{restricted_json} failed to load: {str(e)}') else: this_restricted_name = restricted_json_data['restricted_name'] @@ -591,7 +591,7 @@ def get_registered(engine_name: str = None, with repo.open('r') as f: try: repo_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{cache_file} failed to load: {str(e)}') else: this_repos_name = repo_json_data['repo_name'] diff --git a/scripts/o3de/o3de/print_registration.py b/scripts/o3de/o3de/print_registration.py index 7900fad7e4..292f2224bc 100644 --- a/scripts/o3de/o3de/print_registration.py +++ b/scripts/o3de/o3de/print_registration.py @@ -13,6 +13,7 @@ import argparse import json import hashlib import logging +import sys import urllib.parse from o3de import manifest, validation @@ -143,7 +144,7 @@ def print_engines_data(engines_data: dict) -> None: with engine_json.open('r') as f: try: engine_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{engine_json} failed to load: {str(e)}') else: print(engine_json) @@ -170,7 +171,7 @@ def print_projects_data(projects_data: dict) -> None: with project_json.open('r') as f: try: project_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{project_json} failed to load: {str(e)}') else: print(project_json) @@ -197,7 +198,7 @@ def print_gems_data(gems_data: dict) -> None: with gem_json.open('r') as f: try: gem_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{gem_json} failed to load: {str(e)}') else: print(gem_json) @@ -224,7 +225,7 @@ def print_templates_data(templates_data: dict) -> None: with template_json.open('r') as f: try: template_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{template_json} failed to load: {str(e)}') else: print(template_json) @@ -243,7 +244,7 @@ def print_repos_data(repos_data: dict) -> None: with cache_file.open('r') as s: try: repo_json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{cache_file} failed to load: {str(e)}') else: print(f'{repo_uri}/repo.json cached as:') @@ -260,7 +261,7 @@ def print_restricted_data(restricted_data: dict) -> None: with restricted_json.open('r') as f: try: restricted_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.warn(f'{restricted_json} failed to load: {str(e)}') else: print(restricted_json) @@ -365,19 +366,14 @@ def _run_register_show(args: argparse) -> int: return 0 -def add_args(parser, subparsers) -> None: +def add_parser_args(parser): """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here + Ex. Directly run from this file alone with: python print_registration.py --engine-projects + :param parser: the caller passes an argparse parser like instance to this method """ - register_show_subparser = subparsers.add_parser('register-show') - group = register_show_subparser.add_mutually_exclusive_group(required=False) + group = parser.add_mutually_exclusive_group(required=False) group.add_argument('-te', '--this-engine', action='store_true', required=False, default=False, help='Just the local engines.') @@ -446,11 +442,49 @@ def add_args(parser, subparsers) -> None: default=False, help='Combine all repos templates into a single list of resources.') - register_show_subparser.add_argument('-v', '--verbose', action='count', required=False, + parser.add_argument('-v', '--verbose', action='count', required=False, default=0, help='How verbose do you want the output to be.') - register_show_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, help='By default the home folder is the user folder, override it to this folder.') - register_show_subparser.set_defaults(func=_run_register_show) \ No newline at end of file + parser.set_defaults(func=_run_register_show) + + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py register-show --engine-projects + :param subparsers: the caller instantiates subparsers and passes it in here + """ + register_show_subparser = subparsers.add_parser('register-show') + add_parser_args(register_show_subparser) + + +def main(): + """ + Runs print_registration.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/register.py b/scripts/o3de/o3de/register.py index d6a734e1fd..c44af03b30 100644 --- a/scripts/o3de/o3de/register.py +++ b/scripts/o3de/o3de/register.py @@ -19,6 +19,7 @@ import json import os import pathlib import shutil +import sys import urllib.parse import urllib.request @@ -134,172 +135,74 @@ def register_all_in_folder(folder_path: str or pathlib.Path, return ret_val -def register_all_engines_in_folder(engines_path: str or pathlib.Path, - remove: bool = False, - force: bool = False) -> int: - if not engines_path: +def register_all_o3de_objects_of_type_in_folder(o3de_object_path: str or pathlib.Path, + o3de_object_type: str, + remove: bool, + force: bool, + **register_kwargs) -> int: + if not o3de_object_path: logger.error(f'Engines path cannot be empty.') return 1 - engines_path = pathlib.Path(engines_path).resolve() - if not engines_path.is_dir(): + o3de_object_path = pathlib.Path(o3de_object_path).resolve() + if not o3de_object_path.is_dir(): logger.error(f'Engines path is not dir.') return 1 - engines_set = set() + o3de_object_type_set = set() + register_path_kwarg = f'{o3de_object_type}_path' if o3de_object_type != 'repo' else f'{o3de_object_type}_uri' ret_val = 0 - for root, dirs, files in os.walk(engines_path): - for name in files: - if name == 'engine.json': - engines_set.add(root) + for root, dirs, files in os.walk(o3de_object_path): + if f'{o3de_object_type}.json' in files: + o3de_object_type_set.add(root) + # Stop iteration of any subdirectories + # Nested o3de objects of the same type aren't supported(i.e an engine cannot be inside of a engine). + dirs[:] = [] - for engine in sorted(engines_set, reverse=True): - error_code = register(engine_path=engine, remove=remove, force=force) + for o3de_object_type_root in sorted(o3de_object_type_set, reverse=True): + error_code = register(**{register_path_kwarg: o3de_object_type_root}, + remove=remove, force=force, **register_kwargs) if error_code: ret_val = error_code return ret_val +def register_all_engines_in_folder(engines_path: str or pathlib.Path, + remove: bool = False, + force: bool = False) -> int: + return register_all_o3de_objects_of_type_in_folder(engines_path, 'engine', remove, force) + + def register_all_projects_in_folder(projects_path: str or pathlib.Path, remove: bool = False, engine_path: str or pathlib.Path = None) -> int: - if not projects_path: - logger.error(f'Projects path cannot be empty.') - return 1 - - projects_path = pathlib.Path(projects_path).resolve() - if not projects_path.is_dir(): - logger.error(f'Projects path is not dir.') - return 1 - - projects_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(projects_path): - for name in files: - if name == 'project.json': - projects_set.add(root) - - for project in sorted(projects_set, reverse=True): - error_code = register(engine_path=engine_path, project_path=project, remove=remove) - if error_code: - ret_val = error_code - - return ret_val + return register_all_o3de_objects_of_type_in_folder(projects_path, 'project', remove, False, engine_path=engine_path) def register_all_gems_in_folder(gems_path: str or pathlib.Path, remove: bool = False, engine_path: str or pathlib.Path = None) -> int: - if not gems_path: - logger.error(f'Gems path cannot be empty.') - return 1 - - gems_path = pathlib.Path(gems_path).resolve() - if not gems_path.is_dir(): - logger.error(f'Gems path is not dir.') - return 1 - - gems_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(gems_path): - for name in files: - if name == 'gem.json': - gems_set.add(root) - - for gem in sorted(gems_set, reverse=True): - error_code = register(engine_path=engine_path, gem_path=gem, remove=remove) - if error_code: - ret_val = error_code - - return ret_val + return register_all_o3de_objects_of_type_in_folder(gems_path, 'gem', remove, False, engine_path=engine_path) def register_all_templates_in_folder(templates_path: str or pathlib.Path, remove: bool = False, engine_path: str or pathlib.Path = None) -> int: - if not templates_path: - logger.error(f'Templates path cannot be empty.') - return 1 - - templates_path = pathlib.Path(templates_path).resolve() - if not templates_path.is_dir(): - logger.error(f'Templates path is not dir.') - return 1 - - templates_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(templates_path): - for name in files: - if name == 'template.json': - templates_set.add(root) - - for template in sorted(templates_set, reverse=True): - error_code = register(engine_path=engine_path, template_path=template, remove=remove) - if error_code: - ret_val = error_code - - return ret_val + return register_all_o3de_objects_of_type_in_folder(templates_path, 'template', remove, False, engine_path=engine_path) def register_all_restricted_in_folder(restricted_path: str or pathlib.Path, remove: bool = False, engine_path: str or pathlib.Path = None) -> int: - if not restricted_path: - logger.error(f'Restricted path cannot be empty.') - return 1 - - restricted_path = pathlib.Path(restricted_path).resolve() - if not restricted_path.is_dir(): - logger.error(f'Restricted path is not dir.') - return 1 - - restricted_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(restricted_path): - for name in files: - if name == 'restricted.json': - restricted_set.add(root) - - for restricted in sorted(restricted_set, reverse=True): - error_code = register(engine_path=engine_path, restricted_path=restricted, remove=remove) - if error_code: - ret_val = error_code - - return ret_val + return register_all_o3de_objects_of_type_in_folder(restricted_path, 'restricted', remove, False, engine_path=engine_path) def register_all_repos_in_folder(repos_path: str or pathlib.Path, remove: bool = False, engine_path: str or pathlib.Path = None) -> int: - if not repos_path: - logger.error(f'Repos path cannot be empty.') - return 1 - - repos_path = pathlib.Path(repos_path).resolve() - if not repos_path.is_dir(): - logger.error(f'Repos path is not dir.') - return 1 - - repo_set = set() - - ret_val = 0 - for root, dirs, files in os.walk(repos_path): - for name in files: - if name == 'repo.json': - repo_set.add(root) - - for repo in sorted(repo_set, reverse=True): - error_code = register(engine_path=engine_path, repo_uri=repo, remove=remove) - if error_code: - ret_val = error_code - - return ret_val + return register_all_o3de_objects_of_type_in_folder(repos_path, 'repo', remove, force, engine_path=engine_path) def remove_engine_name_to_path(json_data: dict, @@ -395,21 +298,13 @@ def register_gem_path(json_data: dict, logger.error(f'Engine path {engine_path} is not registered.') return 1 - while gem_path in engine_data['gems']: - engine_data['gems'].remove(gem_path) - - while gem_path.as_posix() in engine_data['gems']: - engine_data['gems'].remove(gem_path.as_posix()) + engine_data['gems'] = list(filter(lambda p: gem_path != pathlib.Path(p), engine_data['gems'])) if remove: logger.warn(f'Removing Gem path {gem_path}.') return 0 else: - while gem_path in json_data['gems']: - json_data['gems'].remove(gem_path) - - while gem_path.as_posix() in json_data['gems']: - json_data['gems'].remove(gem_path.as_posix()) + json_data['gems'] = list(filter(lambda p: gem_path != pathlib.Path(p), json_data['gems'])) if remove: logger.warn(f'Removing Gem path {gem_path}.') @@ -447,21 +342,13 @@ def register_project_path(json_data: dict, logger.error(f'Engine path {engine_path} is not registered.') return 1 - while project_path in engine_data['projects']: - engine_data['projects'].remove(project_path) - - while project_path.as_posix() in engine_data['projects']: - engine_data['projects'].remove(project_path.as_posix()) + engine_data['projects'] = list(filter(lambda p: project_path != pathlib.Path(p), engine_data['projects'])) if remove: logger.warn(f'Engine {engine_path} removing Project path {project_path}.') return 0 else: - while project_path in json_data['projects']: - json_data['projects'].remove(project_path) - - while project_path.as_posix() in json_data['projects']: - json_data['projects'].remove(project_path.as_posix()) + json_data['projects'] = list(filter(lambda p: project_path != pathlib.Path(p), json_data['projects'])) if remove: logger.warn(f'Removing Project path {project_path}.') @@ -486,20 +373,20 @@ def register_project_path(json_data: dict, with this_engine_json.open('r') as f: try: this_engine_json = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Engine json failed to load: {str(e)}') return 1 with project_json.open('r') as f: try: project_json_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Project json failed to load: {str(e)}') return 1 update_project_json = False try: update_project_json = project_json_data['engine'] != this_engine_json['engine_name'] - except Exception as e: + except KeyError as e: update_project_json = True if update_project_json: @@ -508,7 +395,7 @@ def register_project_path(json_data: dict, with project_json.open('w') as s: try: s.write(json.dumps(project_json_data, indent=4)) - except Exception as e: + except OSError as e: logger.error(f'Project json failed to save: {str(e)}') return 1 @@ -530,21 +417,13 @@ def register_template_path(json_data: dict, logger.error(f'Engine path {engine_path} is not registered.') return 1 - while template_path in engine_data['templates']: - engine_data['templates'].remove(template_path) - - while template_path.as_posix() in engine_data['templates']: - engine_data['templates'].remove(template_path.as_posix()) + engine_data['templates'] = list(filter(lambda p: template_path != pathlib.Path(p), engine_data['templates'])) if remove: logger.warn(f'Engine {engine_path} removing Template path {template_path}.') return 0 else: - while template_path in json_data['templates']: - json_data['templates'].remove(template_path) - - while template_path.as_posix() in json_data['templates']: - json_data['templates'].remove(template_path.as_posix()) + json_data['templates'] = list(filter(lambda p: template_path != pathlib.Path(p), json_data['templates'])) if remove: logger.warn(f'Removing Template path {template_path}.') @@ -582,21 +461,13 @@ def register_restricted_path(json_data: dict, logger.error(f'Engine path {engine_path} is not registered.') return 1 - while restricted_path in engine_data['restricted']: - engine_data['restricted'].remove(restricted_path) - - while restricted_path.as_posix() in engine_data['restricted']: - engine_data['restricted'].remove(restricted_path.as_posix()) + engine_data['restricted'] = list(filter(lambda p: restricted_path != pathlib.Path(p), engine_data['restricted'])) if remove: logger.warn(f'Engine {engine_path} removing Restricted path {restricted_path}.') return 0 else: - while restricted_path in json_data['restricted']: - json_data['restricted'].remove(restricted_path) - - while restricted_path.as_posix() in json_data['restricted']: - json_data['restricted'].remove(restricted_path.as_posix()) + json_data['restricted'] = list(filter(lambda p: restricted_path != pathlib.Path(p), json_data['restricted'])) if remove: logger.warn(f'Removing Restricted path {restricted_path}.') @@ -629,10 +500,7 @@ def register_repo(json_data: dict, url = f'{repo_uri}/repo.json' parsed_uri = urllib.parse.urlparse(url) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': + if parsed_uri.scheme in ['http', 'https', 'ftp', 'ftps']: while repo_uri in json_data['repos']: json_data['repos'].remove(repo_uri) else: @@ -647,118 +515,67 @@ def register_repo(json_data: dict, repo_sha256 = hashlib.sha256(url.encode()) cache_file = manifest.get_o3de_cache_folder() / str(repo_sha256.hexdigest() + '.json') - result = 0 - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - if not cache_file.is_file(): - with urllib.request.urlopen(url) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - json_data['repos'].insert(0, repo_uri) - else: - if not cache_file.is_file(): - origin_file = pathlib.Path(url).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, origin_file) + result = utils.download_file(url, cache_file) + if result == 0: json_data['repos'].insert(0, repo_uri.as_posix()) - repo_set = set() result = repo.process_add_o3de_repo(cache_file, repo_set) return result +def register_default_o3de_object_folder(json_data: dict, + default_o3de_object_folder: str or pathlib.Path, + o3de_object_key: str) -> int: + # make sure the path exists + default_o3de_object_folder = pathlib.Path(default_o3de_object_folder).resolve() + if not default_o3de_object_folder.is_dir(): + logger.error(f'Default o3de object folder {default_o3de_object_folder} does not exist.') + return 1 + + json_data[o3de_object_key] = default_o3de_object_folder.as_posix() + + return 0 + + def register_default_engines_folder(json_data: dict, default_engines_folder: str or pathlib.Path, remove: bool = False) -> int: - if remove: - default_engines_folder = manifest.get_o3de_engines_folder() - - # make sure the path exists - default_engines_folder = pathlib.Path(default_engines_folder).resolve() - if not default_engines_folder.is_dir(): - logger.error(f'Default engines folder {default_engines_folder} does not exist.') - return 1 - - default_engines_folder = default_engines_folder.as_posix() - json_data['default_engines_folder'] = default_engines_folder - - return 0 + return register_default_o3de_object_folder(json_data, + manifest.get_o3de_engines_folder() if remove else default_engines_folder, + 'default_engines_folder', remove) def register_default_projects_folder(json_data: dict, default_projects_folder: str or pathlib.Path, remove: bool = False) -> int: - if remove: - default_projects_folder = manifest.get_o3de_projects_folder() - - # make sure the path exists - default_projects_folder = pathlib.Path(default_projects_folder).resolve() - if not default_projects_folder.is_dir(): - logger.error(f'Default projects folder {default_projects_folder} does not exist.') - return 1 - - default_projects_folder = default_projects_folder.as_posix() - json_data['default_projects_folder'] = default_projects_folder - - return 0 + return register_default_o3de_object_folder(json_data, + manifest.get_o3de_projects_folder() if remove else default_projects_folder, + 'default_projects_folder', remove) def register_default_gems_folder(json_data: dict, default_gems_folder: str or pathlib.Path, remove: bool = False) -> int: - if remove: - default_gems_folder = manifest.get_o3de_gems_folder() - - # make sure the path exists - default_gems_folder = pathlib.Path(default_gems_folder).resolve() - if not default_gems_folder.is_dir(): - logger.error(f'Default gems folder {default_gems_folder} does not exist.') - return 1 - - default_gems_folder = default_gems_folder.as_posix() - json_data['default_gems_folder'] = default_gems_folder - - return 0 + return register_default_o3de_object_folder(json_data, + manifest.get_o3de_gems_folder() if remove else default_gems_folder, + 'default_gems_folder', remove) def register_default_templates_folder(json_data: dict, default_templates_folder: str or pathlib.Path, remove: bool = False) -> int: - if remove: - default_templates_folder = manifest.get_o3de_templates_folder() - - # make sure the path exists - default_templates_folder = pathlib.Path(default_templates_folder).resolve() - if not default_templates_folder.is_dir(): - logger.error(f'Default templates folder {default_templates_folder} does not exist.') - return 1 - - default_templates_folder = default_templates_folder.as_posix() - json_data['default_templates_folder'] = default_templates_folder - - return 0 + return register_default_o3de_object_folder(json_data, + manifest.get_o3de_templates_folder() if remove else default_templates_folder, + 'default_templates_folder', remove) def register_default_restricted_folder(json_data: dict, default_restricted_folder: str or pathlib.Path, - remove: bool = False) -> int: - if remove: - default_restricted_folder = manifest.get_o3de_restricted_folder() - - # make sure the path exists - default_restricted_folder = pathlib.Path(default_restricted_folder).resolve() - if not default_restricted_folder.is_dir(): - logger.error(f'Default restricted folder {default_restricted_folder} does not exist.') - return 1 - - default_restricted_folder = default_restricted_folder.as_posix() - json_data['default_restricted_folder'] = default_restricted_folder - - return 0 + reset_to_default: bool = False) -> int: + return register_default_o3de_object_folder(json_data, + manifest.get_o3de_restricted_folder() if remove else default_restricted_folder, + 'default_restricted_folder', remove) def register(engine_path: str or pathlib.Path = None, @@ -999,20 +816,14 @@ def _run_register(args: argparse) -> int: force=args.force) -def add_args(parser, subparsers) -> None: +def add_parser_args(parser): """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here + Ex. Directly run from this file alone with: python register.py --engine-path "C:/o3de" + :param parser: the caller passes an argparse parser like instance to this method """ - # register - register_subparser = subparsers.add_parser('register') - group = register_subparser.add_mutually_exclusive_group(required=True) + group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--this-engine', action='store_true', required=False, default=False, help='Registers the engine this script is running from.') @@ -1054,12 +865,49 @@ def add_args(parser, subparsers) -> None: default=False, help='Refresh the repo cache.') - register_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, help='By default the home folder is the user folder, override it to this folder.') - - register_subparser.add_argument('-r', '--remove', action='store_true', required=False, + parser.add_argument('-r', '--remove', action='store_true', required=False, default=False, help='Remove entry.') - register_subparser.add_argument('-f', '--force', action='store_true', default=False, + parser.add_argument('-f', '--force', action='store_true', default=False, help='For the update of the registration field being modified.') - register_subparser.set_defaults(func=_run_register) + parser.set_defaults(func=_run_register) + + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py register --engine-path "C:/o3de" + :param subparsers: the caller instantiates subparsers and passes it in here + """ + register_subparser = subparsers.add_parser('register') + add_parser_args(register_subparser) + + +def main(): + """ + Runs register.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/registration.py b/scripts/o3de/o3de/registration.py deleted file mode 100755 index 801c698ca4..0000000000 --- a/scripts/o3de/o3de/registration.py +++ /dev/null @@ -1,92 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# -""" -This file contains all the code that has to do with registering engines, projects, gems and templates -""" - -import argparse -import sys - - -def add_args(parser, subparsers) -> None: - """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be - invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here - """ - # register - from o3de import register - register.add_args(parser, subparsers) - - # show - from o3de import print_registration - print_registration.add_args(parser, subparsers) - - # get-registered - from o3de import get_registration - get_registration.add_args(parser, subparsers) - - # download - from o3de import download - download.add_args(parser, subparsers) - - # add external subdirectories - from o3de import add_external_subdirectory - add_external_subdirectory.add_args(parser, subparsers) - - # remove external subdirectories - from o3de import remove_external_subdirectory - remove_external_subdirectory.add_args(parser, subparsers) - - # add gems to cmake - from o3de import add_gem_cmake - add_gem_cmake.add_args(parser, subparsers) - - # remove gems from cmake - from o3de import remove_gem_cmake - remove_gem_cmake.add_args(parser, subparsers) - - # add a gem to a project - from o3de import add_gem_project - add_gem_project.add_args(parser, subparsers) - - # remove a gem from a project - from o3de import remove_gem_project - remove_gem_project.add_args(parser, subparsers) - - # sha256 - from o3de import sha256 - sha256.add_args(parser, subparsers) - - -if __name__ == "__main__": - # parse the command line args - the_parser = argparse.ArgumentParser() - - # add subparsers - the_subparsers = the_parser.add_subparsers(help='sub-command help', dest='command', required=True) - - # add args to the parser - add_args(the_parser, the_subparsers) - - # parse args - the_args = the_parser.parse_args() - - # run - ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 - - # return - sys.exit(ret) diff --git a/scripts/o3de/o3de/remove_external_subdirectory.py b/scripts/o3de/o3de/remove_external_subdirectory.py index a636474fba..b433e9c398 100644 --- a/scripts/o3de/o3de/remove_external_subdirectory.py +++ b/scripts/o3de/o3de/remove_external_subdirectory.py @@ -15,6 +15,7 @@ Implemens functinality to remove external_subdirectories from the o3de_manifests import argparse import logging import pathlib +import sys from o3de import manifest @@ -62,12 +63,58 @@ def add_args(parser, subparsers) -> None: :param parser: the caller instantiates a parser and passes it in here :param subparsers: the caller instantiates subparsers and passes it in here """ - remove_external_subdirectory_subparser = subparsers.add_parser('remove-external-subdirectory') - remove_external_subdirectory_subparser.add_argument('external_subdirectory', metavar='external_subdirectory', + + +def add_parser_args(parser): + """ + add_parser_args is called to add arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python remove_external_subdirectory.py "D:/subdir" + :param parser: the caller passes an argparse parser like instance to this method + """ + parser.add_argument('external_subdirectory', metavar='external_subdirectory', type=str, help='remove external subdirectory from cmake') - remove_external_subdirectory_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, help='By default the home folder is the user folder, override it to this folder.') - remove_external_subdirectory_subparser.set_defaults(func=_run_remove_external_subdirectory) + parser.set_defaults(func=_run_remove_external_subdirectory) + + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py remove-external-subdirectory "D:/subdir" + :param subparsers: the caller instantiates subparsers and passes it in here + """ + remove_external_subdirectory_subparser = subparsers.add_parser('remove-external-subdirectory') + add_parser_args(remove_external_subdirectory_subparser) + + +def main(): + """ + Runs remove_external_subdirectory.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/remove_gem_cmake.py b/scripts/o3de/o3de/remove_gem_cmake.py index 8f73caaad1..3d988a579a 100644 --- a/scripts/o3de/o3de/remove_gem_cmake.py +++ b/scripts/o3de/o3de/remove_gem_cmake.py @@ -15,6 +15,7 @@ Contains methods for removing a gem from a project's cmake scripts import argparse import logging import pathlib +import sys from o3de import manifest, remove_external_subdirectory @@ -64,26 +65,58 @@ def _run_remove_gem_from_cmake(args: argparse) -> int: return remove_gem_from_cmake(args.gem_name, args.gem_path) -def add_args(parser, subparsers) -> None: +def add_parser_args(parser): """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here + Ex. Directly run from this file alone with: python remove_gem_cmake.py --gem-name Atom + :param parser: the caller passes an argparse parser like instance to this method """ - # convenience functions to disambiguate the gem name -> gem_path and call remove-external-subdirectory on gem_path - remove_gem_from_cmake_subparser = subparsers.add_parser('remove-gem-from-cmake') - group = remove_gem_from_cmake_subparser.add_mutually_exclusive_group(required=True) + group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-gp', '--gem-path', type=str, required=False, help='The path to the gem.') group.add_argument('-gn', '--gem-name', type=str, required=False, help='The name of the gem.') - remove_gem_from_cmake_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, help='By default the home folder is the user folder, override it to this folder.') - remove_gem_from_cmake_subparser.set_defaults(func=_run_remove_gem_from_cmake) + parser.set_defaults(func=_run_remove_gem_from_cmake) + + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py remove-gem-from-cmake --gem-name Atom + :param subparsers: the caller instantiates subparsers and passes it in here + """ + remove_gem_from_cmake_subparser = subparsers.add_parser('remove-gem-from-cmake') + add_parser_args(remove_gem_from_cmake_subparser) + + +def main(): + """ + Runs remove_gem_cmake.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/remove_gem_project.py b/scripts/o3de/o3de/remove_gem_project.py index 7644357042..671427db14 100644 --- a/scripts/o3de/o3de/remove_gem_project.py +++ b/scripts/o3de/o3de/remove_gem_project.py @@ -16,6 +16,7 @@ import argparse import logging import os import pathlib +import sys from o3de import cmake, remove_gem_cmake @@ -220,51 +221,84 @@ def _run_remove_gem_from_project(args: argparse) -> int: args.remove_from_cmake) -def add_args(parser, subparsers) -> None: +def add_parser_args(parser): """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here + Ex. Directly run from this file alone with: python remove_gem_project.py --project-path D:/Test --gem-name Atom + :param parser: the caller passes an argparse parser like instance to this method """ - remove_gem_subparser = subparsers.add_parser('remove-gem-from-project') - group = remove_gem_subparser.add_mutually_exclusive_group(required=True) + group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-pp', '--project-path', type=str, required=False, help='The path to the project.') group.add_argument('-pn', '--project-name', type=str, required=False, help='The name of the project.') - group = remove_gem_subparser.add_mutually_exclusive_group(required=True) + group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-gp', '--gem-path', type=str, required=False, help='The path to the gem.') group.add_argument('-gn', '--gem-name', type=str, required=False, help='The name of the gem.') - remove_gem_subparser.add_argument('-gt', '--gem-target', type=str, required=False, + parser.add_argument('-gt', '--gem-target', type=str, required=False, help='The cmake target name to add. If not specified it will assume gem_name') - remove_gem_subparser.add_argument('-df', '--dependencies-file', type=str, required=False, + parser.add_argument('-df', '--dependencies-file', type=str, required=False, help='The cmake dependencies file in which the gem dependencies are specified.' 'If not specified it will assume ') - remove_gem_subparser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, + parser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, default=False, help='Optional toggle if this gem should be removed as a runtime dependency') - remove_gem_subparser.add_argument('-td', '--tool-dependency', action='store_true', required=False, + parser.add_argument('-td', '--tool-dependency', action='store_true', required=False, default=False, help='Optional toggle if this gem should be removed as a server dependency') - remove_gem_subparser.add_argument('-sd', '--server-dependency', action='store_true', required=False, + parser.add_argument('-sd', '--server-dependency', action='store_true', required=False, default=False, help='Optional toggle if this gem should be removed as a server dependency') - remove_gem_subparser.add_argument('-pl', '--platforms', type=str, required=False, + parser.add_argument('-pl', '--platforms', type=str, required=False, default='Common', help='Optional list of platforms this gem should be removed from' ' Ex. --platforms Mac,Windows,Linux') - remove_gem_subparser.add_argument('-r', '--remove-from-cmake', type=bool, required=False, + parser.add_argument('-r', '--remove-from-cmake', type=bool, required=False, default=False, help='Automatically call remove-from-cmake.') - remove_gem_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, help='By default the home folder is the user folder, override it to this folder.') - remove_gem_subparser.set_defaults(func=_run_remove_gem_from_project) + parser.set_defaults(func=_run_remove_gem_from_project) + + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py remove-gem-from-project --project-path D:/Test --gem-name Atom + :param subparsers: the caller instantiates subparsers and passes it in here + """ + remove_gem_project_subparser = subparsers.add_parser('remove-gem-from-project') + add_parser_args(remove_gem_project_subparser) + + +def main(): + """ + Runs remove_gem_project.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/repo.py b/scripts/o3de/o3de/repo.py index 9cb93d53ae..c6b4874b6a 100644 --- a/scripts/o3de/o3de/repo.py +++ b/scripts/o3de/o3de/repo.py @@ -16,11 +16,12 @@ import shutil import urllib.parse import urllib.request -from o3de import manifest, validation +from o3de import manifest, utils, validation logger = logging.getLogger() logging.basicConfig() + def process_add_o3de_repo(file_name: str or pathlib.Path, repo_set: set) -> int: file_name = pathlib.Path(file_name).resolve() @@ -32,105 +33,26 @@ def process_add_o3de_repo(file_name: str or pathlib.Path, with file_name.open('r') as f: try: repo_data = json.load(f) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'{file_name} failed to load: {str(e)}') return 1 - for engine_uri in repo_data['engines']: - engine_uri = f'{engine_uri}/engine.json' - engine_sha256 = hashlib.sha256(engine_uri.encode()) - cache_file = cache_folder / str(engine_sha256.hexdigest() + '.json') - if not cache_file.is_file(): - parsed_uri = urllib.parse.urlparse(engine_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(engine_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - engine_json = pathlib.Path(engine_uri).resolve() - if not engine_json.is_file(): - return 1 - shutil.copy(engine_json, cache_file) - - for project_uri in repo_data['projects']: - project_uri = f'{project_uri}/project.json' - project_sha256 = hashlib.sha256(project_uri.encode()) - cache_file = cache_folder / str(project_sha256.hexdigest() + '.json') - if not cache_file.is_file(): - parsed_uri = urllib.parse.urlparse(project_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(project_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - project_json = pathlib.Path(project_uri).resolve() - if not project_json.is_file(): - return 1 - shutil.copy(project_json, cache_file) - - for gem_uri in repo_data['gems']: - gem_uri = f'{gem_uri}/gem.json' - gem_sha256 = hashlib.sha256(gem_uri.encode()) - cache_file = cache_folder / str(gem_sha256.hexdigest() + '.json') - if not cache_file.is_file(): - parsed_uri = urllib.parse.urlparse(gem_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(gem_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - gem_json = pathlib.Path(gem_uri).resolve() - if not gem_json.is_file(): - return 1 - shutil.copy(gem_json, cache_file) - - for template_uri in repo_data['templates']: - template_uri = f'{template_uri}/template.json' - template_sha256 = hashlib.sha256(template_uri.encode()) - cache_file = cache_folder / str(template_sha256.hexdigest() + '.json') - if not cache_file.is_file(): - parsed_uri = urllib.parse.urlparse(template_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(template_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - template_json = pathlib.Path(template_uri).resolve() - if not template_json.is_file(): - return 1 - shutil.copy(template_json, cache_file) - - for repo_uri in repo_data['repos']: - if repo_uri not in repo_set: - repo_set.add(repo_uri) - repo_uri = f'{repo_uri}/repo.json' - repo_sha256 = hashlib.sha256(repo_uri.encode()) - cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') + for o3de_object_uris, manifest_json in [(repo_data['engines'], 'engine.json'), + (repo_data['projects'], 'project.json'), + (repo_data['gems'], 'gem.json'), + (repo_data['template'], 'template.json'), + (repo_data['restricted'], 'restricted.json')]: + for o3de_object_uri in o3de_object_uris: + manifest_json_uri = f'{o3de_object_uri}/{manifest_json}' + manifest_json_sha256 = hashlib.sha256(manifest_json_uri.encode()) + cache_file = cache_folder / str(manifest_json_sha256.hexdigest() + '.json') if not cache_file.is_file(): - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(repo_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - repo_json = pathlib.Path(repo_uri).resolve() - if not repo_json.is_file(): - return 1 - shutil.copy(repo_json, cache_file) + parsed_uri = urllib.parse.urlparse(manifest_json_uri) + download_file_result = utils.download_file(parsed_uri, cache_file) + if download_file_result != 0: + return download_file_result + + repo_set |= repo_data['repos'] return 0 @@ -156,18 +78,9 @@ def refresh_repos() -> int: cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') if not cache_file.is_file(): parsed_uri = urllib.parse.urlparse(repo_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - with urllib.request.urlopen(repo_uri) as s: - with cache_file.open('wb') as f: - shutil.copyfileobj(s, f) - else: - origin_file = pathlib.Path(repo_uri).resolve() - if not origin_file.is_file(): - return 1 - shutil.copy(origin_file, cache_file) + download_file_result = utils.download_file(parsed_uri, cache_file) + if download_file_result != 0: + return download_file_result if not validation.valid_o3de_repo_json(cache_file): logger.error(f'Repo json {repo_uri} is not valid.') @@ -181,111 +94,67 @@ def refresh_repos() -> int: return result -def search_repo(repo_set: set, - repo_json_data: dict, +def search_repo(repo_json_data: dict, engine_name: str = None, project_name: str = None, gem_name: str = None, template_name: str = None, restricted_name: str = None) -> dict or None: - cache_folder = manifest.get_o3de_cache_folder() if isinstance(engine_name, str) or isinstance(engine_name, pathlib.PurePath): - for engine_uri in repo_json_data['engines']: - engine_uri = f'{engine_uri}/engine.json' - engine_sha256 = hashlib.sha256(engine_uri.encode()) - engine_cache_file = cache_folder / str(engine_sha256.hexdigest() + '.json') - if engine_cache_file.is_file(): - with engine_cache_file.open('r') as f: - try: - engine_json_data = json.load(f) - except Exception as e: - logger.warn(f'{engine_cache_file} failed to load: {str(e)}') - else: - if engine_json_data['engine_name'] == engine_name: - return engine_json_data - + o3de_object_uris = repo_json_data['engines'] + manifest_json = 'engine.json' + json_key = 'engine_name' + search_func = lambda: None if manifest_json_data.get(json_key, '') == engine_name else manifest_json_data elif isinstance(project_name, str) or isinstance(project_name, pathlib.PurePath): - for project_uri in repo_json_data['projects']: - project_uri = f'{project_uri}/project.json' - project_sha256 = hashlib.sha256(project_uri.encode()) - project_cache_file = cache_folder / str(project_sha256.hexdigest() + '.json') - if project_cache_file.is_file(): - with project_cache_file.open('r') as f: - try: - project_json_data = json.load(f) - except Exception as e: - logger.warn(f'{project_cache_file} failed to load: {str(e)}') - else: - if project_json_data['project_name'] == project_name: - return project_json_data - + o3de_object_uris = repo_json_data['projects'] + manifest_json = 'project.json' + json_key = 'project_name' + search_func = lambda: None if manifest_json_data.get(json_key, '') == project_name else manifest_json_data elif isinstance(gem_name, str) or isinstance(gem_name, pathlib.PurePath): - for gem_uri in repo_json_data['gems']: - gem_uri = f'{gem_uri}/gem.json' - gem_sha256 = hashlib.sha256(gem_uri.encode()) - gem_cache_file = cache_folder / str(gem_sha256.hexdigest() + '.json') - if gem_cache_file.is_file(): - with gem_cache_file.open('r') as f: - try: - gem_json_data = json.load(f) - except Exception as e: - logger.warn(f'{gem_cache_file} failed to load: {str(e)}') - else: - if gem_json_data['gem_name'] == gem_name: - return gem_json_data - + o3de_object_uris = repo_json_data['gems'] + manifest_json = 'gem.json' + json_key = 'gem_name' + search_func = lambda: None if manifest_json_data.get(json_key, '') == gem_name else manifest_json_data elif isinstance(template_name, str) or isinstance(template_name, pathlib.PurePath): - for template_uri in repo_json_data['templates']: - template_uri = f'{template_uri}/template.json' - template_sha256 = hashlib.sha256(template_uri.encode()) - template_cache_file = cache_folder / str(template_sha256.hexdigest() + '.json') - if template_cache_file.is_file(): - with template_cache_file.open('r') as f: - try: - template_json_data = json.load(f) - except Exception as e: - logger.warn(f'{template_cache_file} failed to load: {str(e)}') - else: - if template_json_data['template_name'] == template_name: - return template_json_data - + o3de_object_uris = repo_json_data['template'] + manifest_json = 'template.json' + json_key = 'template_name' + search_func = lambda: None if manifest_json_data.get(json_key, '') == template_name_name else manifest_json_data elif isinstance(restricted_name, str) or isinstance(restricted_name, pathlib.PurePath): - for restricted_uri in repo_json_data['restricted']: - restricted_uri = f'{restricted_uri}/restricted.json' - restricted_sha256 = hashlib.sha256(restricted_uri.encode()) - restricted_cache_file = cache_folder / str(restricted_sha256.hexdigest() + '.json') - if restricted_cache_file.is_file(): - with restricted_cache_file.open('r') as f: - try: - restricted_json_data = json.load(f) - except Exception as e: - logger.warn(f'{restricted_cache_file} failed to load: {str(e)}') - else: - if restricted_json_data['restricted_name'] == restricted_name: - return restricted_json_data - # recurse + o3de_object_uris = repo_json_data['restricted'] + manifest_json = 'restricted.json' + json_key = 'restricted_name' + search_func = lambda: None if manifest_json_data.get(json_key, '') == restricted_name else manifest_json_data else: - for repo_repo_uri in repo_json_data['repos']: - if repo_repo_uri not in repo_set: - repo_set.add(repo_repo_uri) - repo_repo_uri = f'{repo_repo_uri}/repo.json' - repo_repo_sha256 = hashlib.sha256(repo_repo_uri.encode()) - repo_repo_cache_file = cache_folder / str(repo_repo_sha256.hexdigest() + '.json') - if repo_repo_cache_file.is_file(): - with repo_repo_cache_file.open('r') as f: - try: - repo_repo_json_data = json.load(f) - except Exception as e: - logger.warn(f'{repo_repo_cache_file} failed to load: {str(e)}') - else: - item = search_repo(repo_set, - repo_repo_json_data, - engine_name, - project_name, - gem_name, - template_name) - if item: - return item - return None + return None + o3de_object = search_o3de_object(manifest_json, o3de_object_uris, search_func) + if o3de_object: + return o3de_object + + # recurse into the repos object to search for the o3de object + o3de_object_uris = repo_json_data['repos'] + manifest_json = 'repo.json' + search_func = lambda: search_repo(manifest_json, engine_name, project_name, gem_name, template_name) + return search_o3de_object(manifest_json, o3de_object_uris, search_func) + + +def search_o3de_object(manifest_json, o3de_object_uris, search_func): + # Search for the o3de object based on the supplied object name in the current repo + cache_folder = manifest.get_o3de_cache_folder() + for o3de_object_uri in o3de_object_uris: + manifest_json_uri = f'{o3de_object_uri}/{manifest_json}' + manifest_json_sha256 = hashlib.sha256(manifest_json_uri.encode()) + cache_file = cache_folder / str(manifest_json_sha256.hexdigest() + '.json') + if cache_file.is_file(): + with cache_file.open('r') as f: + try: + manifest_json_data = json.load(f) + except json.JSONDecodeError as e: + logger.warn(f'{cache_file} failed to load: {str(e)}') + else: + result_json_data = search_func() + if result_json_data: + return result_json_data + return None diff --git a/scripts/o3de/o3de/sha256.py b/scripts/o3de/o3de/sha256.py index bc35919c4e..bbec7696d6 100644 --- a/scripts/o3de/o3de/sha256.py +++ b/scripts/o3de/o3de/sha256.py @@ -13,6 +13,8 @@ import argparse import json import logging import hashlib +import pathlib +import sys from o3de import utils @@ -42,7 +44,7 @@ def sha256(file_path: str or pathlib.Path, with json_path.open('r') as s: try: json_data = json.load(s) - except Exception as e: + except json.JSONDecodeError as e: logger.error(f'Failed to read Json path {json_path}: {str(e)}') return 1 json_data.update({"sha256": sha256}) @@ -50,7 +52,7 @@ def sha256(file_path: str or pathlib.Path, with json_path.open('w') as s: try: s.write(json.dumps(json_data, indent=4)) - except Exception as e: + except OSError as e: logger.error(f'Failed to write Json path {json_path}: {str(e)}') return 1 else: @@ -63,20 +65,53 @@ def _run_sha256(args: argparse) -> int: args.json_path) -def add_args(parser, subparsers) -> None: +def add_parser_args(parser): """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here + Ex. Directly run from this file alone with: python sha256.py --file-path "C:/TestGem" + :param parser: the caller passes an argparse parser like instance to this method + """ + parser.add_argument('-f', '--file-path', type=str, required=True, + help='The path to the file you want to sha256.') + parser.add_argument('-j', '--json-path', type=str, required=False, + help='optional path to an o3de json file to add the "sha256" element to.') + parser.set_defaults(func=_run_sha256) + + +def add_args(subparsers) -> None: + """ + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py sha256 --file-path "C:/TestGem" :param subparsers: the caller instantiates subparsers and passes it in here """ sha256_subparser = subparsers.add_parser('sha256') - sha256_subparser.add_argument('-f', '--file-path', type=str, required=True, - help='The path to the file you want to sha256.') - sha256_subparser.add_argument('-j', '--json-path', type=str, required=False, - help='optional path to an o3de json file to add the "sha256" element to.') - sha256_subparser.set_defaults(func=_run_sha256) + add_parser_args(sha256_subparser) + + +def main(): + """ + Runs sha256.py script as standalone script + """ + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + + # add args to the parser + add_parser_args(the_parser) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + + # return + sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/utils.py b/scripts/o3de/o3de/utils.py index 50a9e5d6dd..4330de25b8 100755 --- a/scripts/o3de/o3de/utils.py +++ b/scripts/o3de/o3de/utils.py @@ -13,7 +13,9 @@ This file contains utility functions """ import uuid - +import pathlib +import shutil +import urllib.request def validate_identifier(identifier: str) -> bool: """ @@ -46,6 +48,7 @@ def validate_uuid4(uuid_string: str) -> bool: return False return str(val) == uuid_string + def backup_file(file_name: str or pathlib.Path) -> None: index = 0 renamed = False @@ -69,4 +72,41 @@ def backup_folder(folder: str or pathlib.Path) -> None: folder = pathlib.Path(folder).resolve() folder.rename(backup_folder_name) if backup_folder_name.is_dir(): - renamed = True \ No newline at end of file + renamed = True + + +def download_file(parsed_uri, download_path: pathlib.Path) -> int: + """ + :param parsed_uri: uniform resource identifier to zip file to download + :param download_path: location path on disk to download file + """ + if download_path.is_file(): + logger.warn(f'File already downloaded to {download_path}.') + elif parsed_uri.scheme in ['http', 'https', 'ftp', 'ftps']: + with urllib.request.urlopen(url) as s: + with download_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_path) + + return 0 + + +def download_zip_file(parsed_uri, download_zip_path: pathlib.Path) -> int: + """ + :param parsed_uri: uniform resource identifier to zip file to download + :param download_zip_path: path to output zip file + """ + download_file_result = download_file(parsed_uri, download_zip_path) + if download_file_result != 0: + return download_file_result + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"File zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + return 0 \ No newline at end of file diff --git a/scripts/o3de/o3de/validation.py b/scripts/o3de/o3de/validation.py index f3a5f5e376..721b7eae09 100644 --- a/scripts/o3de/o3de/validation.py +++ b/scripts/o3de/o3de/validation.py @@ -14,6 +14,10 @@ This file validating o3de object json files import json import pathlib +def valid_o3de_json_dict(json_data: dict, key: str) -> bool: + return key in json_data + + def valid_o3de_repo_json(file_name: str or pathlib.Path) -> bool: file_name = pathlib.Path(file_name).resolve() if not file_name.is_file(): @@ -24,7 +28,7 @@ def valid_o3de_repo_json(file_name: str or pathlib.Path) -> bool: json_data = json.load(f) test = json_data['repo_name'] test = json_data['origin'] - except Exception as e: + except (json.JSONDecodeError, KeyError) as e: return False return True @@ -39,8 +43,7 @@ def valid_o3de_engine_json(file_name: str or pathlib.Path) -> bool: try: json_data = json.load(f) test = json_data['engine_name'] - # test = json_data['origin'] # will be required soon - except Exception as e: + except (json.JSONDecodeError, KeyError) as e: return False return True @@ -54,8 +57,7 @@ def valid_o3de_project_json(file_name: str or pathlib.Path) -> bool: try: json_data = json.load(f) test = json_data['project_name'] - # test = json_data['origin'] # will be required soon - except Exception as e: + except (json.JSONDecodeError, KeyError) as e: return False return True @@ -69,8 +71,7 @@ def valid_o3de_gem_json(file_name: str or pathlib.Path) -> bool: try: json_data = json.load(f) test = json_data['gem_name'] - # test = json_data['origin'] # will be required soon - except Exception as e: + except (json.JSONDecodeError, KeyError) as e: return False return True @@ -83,8 +84,7 @@ def valid_o3de_template_json(file_name: str or pathlib.Path) -> bool: try: json_data = json.load(f) test = json_data['template_name'] - # test = json_data['origin'] # will be required soon - except Exception as e: + except (json.JSONDecodeError, KeyError) as e: return False return True @@ -97,7 +97,6 @@ def valid_o3de_restricted_json(file_name: str or pathlib.Path) -> bool: try: json_data = json.load(f) test = json_data['restricted_name'] - # test = json_data['origin'] # will be required soon - except Exception as e: + except (json.JSONDecodeError, KeyError) as e: return False return True diff --git a/scripts/o3de/tests/unit_test_registration.py b/scripts/o3de/tests/unit_test_registration.py index a0abb6cacd..eb866e76d4 100644 --- a/scripts/o3de/tests/unit_test_registration.py +++ b/scripts/o3de/tests/unit_test_registration.py @@ -35,11 +35,10 @@ string_manifest_data = '{}' ) def test_register_engine_path(engine_path, engine_name, force, expected_result): parser = argparse.ArgumentParser() - subparser = parser.add_subparsers(help='sub-command help') # Register the registration script subparsers with the current argument parser - register.add_args(parser, subparser) - arg_list = ['register', '--engine-path', str(engine_path)] + register.add_parser_args(parser) + arg_list = ['--engine-path', str(engine_path)] if force: arg_list += ['--force'] args = parser.parse_args(arg_list) @@ -64,3 +63,55 @@ def test_register_engine_path(engine_path, engine_name, force, expected_result): result = register._run_register(args) assert result == expected_result + +@pytest.fixture(scope='class') +def init_manifest_data(request): + class ManifestData: + def __init__(self): + self.json_string = json.dumps({'default_engines_folder': '', + 'default_projects_folder': '', 'default_gems_folder': '', + 'default_templates_folder': '', 'default_restricted_folder': ''}) + + request.cls.manifest_data = ManifestData() + + +@pytest.mark.usefixtures('init_manifest_data') +class TestRegisterThisEngine: + @pytest.mark.parametrize( + "engine_path, engine_name, force, expected_result", [ + pytest.param(pathlib.PurePath('D:/o3de/o3de'), "o3de", False, 0), + pytest.param(pathlib.PurePath('F:/Open3DEngine'), "o3de", False, 1), + pytest.param(pathlib.PurePath('F:/Open3DEngine'), "o3de", True, 0) + ] + ) + def test_register_this_engine(self, engine_path, engine_name, force, expected_result): + parser = argparse.ArgumentParser() + + # Register the registration script subparsers with the current argument parser + register.add_parser_args(parser) + arg_list = ['--this-engine'] + if force: + arg_list += ['--force'] + args = parser.parse_args(arg_list) + + def load_manifest_from_string() -> dict: + try: + manifest_json = json.loads(self.manifest_data.json_string) + except json.JSONDecodeError as err: + logging.error("Error decoding Json from Manifest file") + else: + return manifest_json + def save_manifest_to_string(manifest_json: dict) -> None: + self.manifest_data.json_string = json.dumps(manifest_json) + + engine_json_data = {'engine_name': engine_name} + + with patch('o3de.manifest.load_o3de_manifest', side_effect=load_manifest_from_string) as load_manifest_mock, \ + patch('o3de.manifest.save_o3de_manifest', side_effect=save_manifest_to_string) as save_manifest_mock, \ + patch('o3de.manifest.get_engine_json_data', return_value=engine_json_data) as engine_paths_mock, \ + patch('o3de.manifest.get_this_engine_path', return_value=engine_path) as engine_paths_mock, \ + patch('o3de.validation.valid_o3de_engine_json', return_value=True) as valid_engine_mock, \ + patch('pathlib.Path.is_dir', return_value=True) as pathlib_is_dir_mock: + result = register._run_register(args) + assert result == expected_result + From 98c3660bd92424094a501d06710c9396d627de4b Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Sun, 23 May 2021 22:15:48 -0500 Subject: [PATCH 102/811] Correcting the comments in the PAL.cmake file --- cmake/PAL.cmake | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/cmake/PAL.cmake b/cmake/PAL.cmake index e10ef758da..dca54e4731 100644 --- a/cmake/PAL.cmake +++ b/cmake/PAL.cmake @@ -26,6 +26,7 @@ endforeach() #! o3de_restricted_id: Reads the "restricted" key from the o3de manifest # +# \arg:o3de_json_file name of the o3de json file to read the "restricted_name" key from # \arg:restricted returns the restricted association element from an o3de json, otherwise engine 'o3de' is assumed # \arg:o3de_json_file name of the o3de json file function(o3de_restricted_id o3de_json_file restricted) @@ -33,8 +34,6 @@ function(o3de_restricted_id o3de_json_file restricted) string(JSON restricted_entry ERROR_VARIABLE json_error GET ${json_data} "restricted_name") if(json_error) message(WARNING "Unable to read restricted from '${o3de_json_file}', error: ${json_error}") - message(WARNING "Setting restricted to engine default 'o3de'") - set(restricted_entry "o3de") endif() if(restricted_entry) set(${restricted} ${restricted_entry} PARENT_SCOPE) @@ -96,8 +95,8 @@ endfunction() #! o3de_restricted_path: # -# \arg:restricted_path returns the path of the o3de restricted folder with name restricted_name -# \arg:restricted_name name of the restricted +# \arg:o3de_json_file json file to read restricted id from +# \arg:restricted_name name of the restricted object function(o3de_restricted_path o3de_json_file restricted_path) o3de_restricted_id(${o3de_json_file} restricted_name) if(restricted_name) @@ -110,8 +109,7 @@ endfunction() #! read_engine_restricted_path: Locates the restricted path within the engine from a json file # -# \arg:restricted_path returns the path of the o3de restricted folder with name restricted_name -# \arg:restricted_name name of the restricted +# \arg:output_restricted_path returns the path of the o3de restricted folder with name restricted_name function(read_engine_restricted_path output_restricted_path) # Set manifest path to path in the user home directory set(manifest_path ${LY_ROOT_FOLDER}/engine.json) From 574efd711cae5326c87d39ff58a17853f32019bf Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Sun, 23 May 2021 22:48:52 -0500 Subject: [PATCH 103/811] Adding a "gem_module_roots" array to the gem.json for the Atom and AtomLyIntegration gems to allow additional module roots to be checked when determining the root directory of a GEM_MODULE target With this change the AtomViewportDisplayInfo gem.json as it is no longer needed. --- Gems/Atom/gem.json | 16 +++++++++++++++- .../AtomViewportDisplayInfo/gem.json | 12 ------------ Gems/AtomLyIntegration/gem.json | 12 +++++++++++- 3 files changed, 26 insertions(+), 14 deletions(-) delete mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json diff --git a/Gems/Atom/gem.json b/Gems/Atom/gem.json index c74a9013f3..99a715281e 100644 --- a/Gems/Atom/gem.json +++ b/Gems/Atom/gem.json @@ -1,3 +1,17 @@ { - "gem_name": "Atom" + "gem_name": "Atom", + "gem_module_roots": [ + "Asset/ImageProcessingAtom", + "Asset/Shader", + "Bootstrap", + "Component/DebugCamera", + "Feature/Common", + "RHI", + "RHI/DX12", + "RHI/Metal", + "RHI/Null", + "RHI/Vulkan", + "RPI", + "Tools/AtomToolsFramework" + ] } diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json deleted file mode 100644 index dd92a99ea9..0000000000 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "gem_name": "AtomLyIntegration_AtomViewportDisplayInfo", - "display_name": "Atom Viewport Display Info Overlay", - "summary": "Provides a diagnostic viewport overlay for the default O3DE Atom viewport.", - "canonical_tags": [ - "Gem" - ], - "user_tags": [ - "AtomLyIntegration", - "AtomViewportDisplayInfo" - ] -} \ No newline at end of file diff --git a/Gems/AtomLyIntegration/gem.json b/Gems/AtomLyIntegration/gem.json index 0971ad53c2..c350281ad1 100644 --- a/Gems/AtomLyIntegration/gem.json +++ b/Gems/AtomLyIntegration/gem.json @@ -1,3 +1,13 @@ { - "gem_name": "AtomLyIntegration" + "gem_name": "AtomLyIntegration", + "gem_module_roots": [ + "AtomBridge", + "AtomFont", + "AtomImGuiTools", + "AtomViewportDisplayInfo", + "CommonFeatures", + "EMotionFXAtom", + "ImguiAtom", + "TechnicalArt/DccScriptingInterface" + ] } From d004365e278551ef275ef3876f1242b3f2cdfaa7 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Sun, 23 May 2021 22:52:10 -0500 Subject: [PATCH 104/811] Updating the generation for the cmake_dependencies...setreg files to detect the nearest gem module root for a cmake target that has been marked with the GEM_MODULE property. The list of gem module roots are made up of the gem.json location + list of paths in the gem.json "gem_module_roots" JSON array if it exist --- cmake/SettingsRegistry.cmake | 115 ++++++++++++++++++++++++++++++----- 1 file changed, 100 insertions(+), 15 deletions(-) diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index b0d9624728..d1f4041cce 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -31,7 +31,7 @@ set(gem_module_template [[ "@stripped_gem_target@": { "Modules":["$"], - "SourcePaths":["@gem_relative_source_dir@"] + "SourcePaths":["@gem_module_root_relative_to_engine_root@"] }]] ) @@ -85,6 +85,101 @@ function(ly_get_gem_load_dependencies ly_GEM_LOAD_DEPENDENCIES ly_TARGET) set(${ly_GEM_LOAD_DEPENDENCIES} ${all_gem_load_dependencies} PARENT_SCOPE) endfunction() +#!ly_get_gem_module_roots: Uses the supplied gem_target to lookup the nearest gem.json file above the SOURCE_DIR +# If a gem.json file is found it is added as gem module root and then queried for additional gem module root +# by looking up the "gem_module_root" key +# +# \arg:gem_target(TARGET) - Target to look upwards from using its SOURCE_DIR property +function(ly_get_gem_module_roots output_gem_module_roots gem_target) + unset(gem_module_roots) + get_property(gem_source_dir TARGET ${gem_target} PROPERTY SOURCE_DIR) + + if(gem_source_dir) + set(candidate_gem_dir ${gem_source_dir}) + # Locate the root of the gem by finding the gem.json location + while(NOT EXISTS ${candidate_gem_dir}/gem.json) + get_filename_component(parent_dir ${candidate_gem_dir} DIRECTORY) + if (${parent_dir} STREQUAL ${candidate_gem_dir}) + message(WARNING "Did not find a gem.json while processing GEM_MODULE target ${gem_target}!") + break() + endif() + set(candidate_gem_dir ${parent_dir}) + endwhile() + endif() + + if (EXISTS ${candidate_gem_dir}/gem.json) + set(gem_source_dir ${candidate_gem_dir}) + file(READ ${gem_source_dir}/gem.json gem_json_data) + string(JSON module_root_count ERROR_VARIABLE gem_json_error LENGTH ${gem_json_data} gem_module_roots) + if(module_root_count GREATER 0) + math(EXPR module_root_range "${module_root_count}-1") + # Convert the paths the relative paths to absolute paths using the engine root + # as the base directory + foreach(module_root_index RANGE ${module_root_range}) + string(JSON module_root ERROR_VARIABLE gem_json_error GET ${gem_json_data} gem_module_roots ${module_root_index}) + file(REAL_PATH ${module_root} gem_absolute_module_root BASE_DIRECTORY ${gem_source_dir}) + list(APPEND gem_module_roots ${gem_absolute_module_root}) + endforeach() + endif() + endif() + + # Prepend the relative path from the Engine Root to the gem_module_roots list + list(PREPEND gem_module_roots ${gem_source_dir}) + set(${output_gem_module_roots} ${gem_module_roots} PARENT_SCOPE) +endfunction() + +#!ly_find_best_gem_module_roots: Attempts to find the gem module root which is the closest ancestor directory +# to the gem_target using the supplied gem_module_roots +# If a gem.json file is found it is added as gem module root and then queried for additional gem module root +# by looking up the "gem_module_root" key + +# \arg:gem_target(TARGET) - Target to whose SOURCE_DIR property is compared against the module roots +# \arg:gem_module_roots(list:PATH) - list of absolute gem module roots to search for nearest ancestor +function(ly_find_best_gem_module_root output_module_root gem_target gem_module_roots) + + get_property(module_root_cached DIRECTORY PROPERTY gem_module_root_${gem_target} SET) + if(module_root_cached) + get_property(module_root_prop DIRECTORY PROPERTY gem_module_root_${gem_target} ) + set(${output_module_root} ${module_root_prop} PARENT_SCOPE) + return() + endif() + + # An optimization for the case where there is only one gem_module_roots. The output_module_root is set to that + list(LENGTH gem_module_roots gem_module_roots_count) + if(gem_module_roots_count EQUAL 1) + list(GET gem_module_roots 0 best_module_root) + set_property(DIRECTORY PROPERTY gem_module_root_${gem_target} ${best_module_root}) + set(${output_module_root} ${best_module_root} PARENT_SCOPE) + return() + endif() + + get_property(gem_source_dir TARGET ${gem_target} PROPERTY SOURCE_DIR) + # shortest_prefix is used to store the shortest prefix from a gem module root to the gem source dir + # Initialized to 10000 to make sure it is larger than any file path length + set(shortest_prefix "10000") + unset(best_module_root) + foreach(gem_module_root ${gem_module_roots}) + file(RELATIVE_PATH relative_to_module_root ${gem_module_root} ${gem_source_dir}) + # if the gem SOURCE_DIR is not relative to the module root then continue + if(relative_to_module_root MATCHES [[^\.\./]] OR IS_ABSOLUTE ${relative_to_module_root}) + continue() + endif() + # Update the shortest prefix + string(LENGTH "${relative_to_module_root}" module_to_source_dir_length) + if(module_to_source_dir_length LESS shortest_prefix) + set(best_module_root ${gem_module_root}) + set(shortest_prefix "${module_to_source_dir_length}") + endif() + endforeach() + + # Assign the best_module_root path to the output variable and stored it in a DIRECTORY property for caching + if(best_module_root) + set_property(DIRECTORY PROPERTY gem_module_root_${gem_target} ${best_module_root}) + set(${output_module_root} ${best_module_root} PARENT_SCOPE) + endif() + +endfunction() + #! ly_delayed_generate_settings_registry: Generates a .setreg file for each target with dependencies # added to it via ly_add_target_dependencies # The generated file contains the file to the each dependent targets @@ -102,7 +197,7 @@ function(ly_delayed_generate_settings_registry) # Retrieve the target name from the back of the list list(POP_BACK prefix_target_list target) - # Retreives the prefix if available from the remaining element of the list + # Retrieves the prefix if available from the remaining element of the list list(POP_BACK prefix_target_list prefix) # Get the gem dependencies for the given project and target combination @@ -123,20 +218,10 @@ function(ly_delayed_generate_settings_registry) if (NOT TARGET ${gem_target}) message(FATAL_ERROR "Dependency ${gem_target} from ${target} does not exist") endif() - get_property(gem_relative_source_dir TARGET ${gem_target} PROPERTY SOURCE_DIR) - if(gem_relative_source_dir) - # Most gems SOURCE dir is nested in the path, we need to find the path where an 'Assets' or 'Code' folder resides - while(NOT EXISTS ${gem_relative_source_dir}/Assets AND NOT EXISTS ${gem_relative_source_dir}/Code) - get_filename_component(parent_dir ${gem_relative_source_dir} DIRECTORY) - if (${parent_dir} STREQUAL ${gem_relative_source_dir}) - message(FATAL_ERROR "Did not find a Gem source dir while processing target ${gem_target}!") - endif() - set(gem_relative_source_dir ${parent_dir}) - endwhile() - file(TO_CMAKE_PATH ${LY_ROOT_FOLDER} ly_root_folder_cmake) - file(RELATIVE_PATH gem_relative_source_dir ${ly_root_folder_cmake} ${gem_relative_source_dir}) - endif() + ly_get_gem_module_roots(gem_module_roots ${gem_target}) + ly_find_best_gem_module_root(best_gem_module_root "${gem_target}" "${gem_module_roots}") + file(RELATIVE_PATH gem_module_root_relative_to_engine_root ${LY_ROOT_FOLDER} ${best_gem_module_root}) # Strip target namespace from gem targets before configuring them into the json template ly_strip_target_namespace(TARGET ${gem_target} OUTPUT_VARIABLE stripped_gem_target) From 911ad84e53b616e9337ce819f25120630cbf6955 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Sun, 23 May 2021 23:26:31 -0500 Subject: [PATCH 105/811] Updating the exclusion rule for the install folder to only include an install folder at the root of the repo --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index c396847560..8a63faa2f1 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ __pycache__ AssetProcessorTemp/** [Bb]uild/** [Cc]ache/ -install/ +/install/ Editor/EditorEventLog.xml Editor/EditorLayout.xml **/*egg-info/** From b99bcea24a1932c7dde20007636dd99048d5b763 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Sun, 23 May 2021 23:29:05 -0500 Subject: [PATCH 106/811] Updating the engine.json.in template for the cmake INSTALL target to add the list of external subdirectories to allow the installed layout to access the subdirectories via it's engine.json file --- cmake/EngineJson.cmake | 2 ++ cmake/Platform/Common/Install_common.cmake | 10 ++++++++++ cmake/install/engine.json.in | 7 +++++-- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/cmake/EngineJson.cmake b/cmake/EngineJson.cmake index 9a82d4a2c5..c3ab29d09e 100644 --- a/cmake/EngineJson.cmake +++ b/cmake/EngineJson.cmake @@ -13,6 +13,8 @@ include_guard() +set(LY_EXTERNAL_SUBDIRS "" CACHE STRING "List of subdirectories to recurse into when running cmake against the engine's CMakeLists.txt") + #! read_engine_external_subdirs # Read the external subdirectories from the engine.json file # External subdirectories are any folders with CMakeLists.txt in them diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index ebe31a4cfa..b8202a1314 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -224,6 +224,16 @@ function(ly_setup_cmake_install) REGEX "Platform\/.*\/BuiltInPackages_.*\.cmake" EXCLUDE ) + # Transform the LY_EXTERNAL_SUBDIRS list into a json array + set(LY_INSTALL_EXTERNAL_SUBDIRS "[]") + set(external_subdir_index "0") + foreach(external_subdir ${LY_EXTERNAL_SUBDIRS}) + math(EXPR external_subdir_index "${external_subdir_index} + 1") + file(RELATIVE_PATH engine_rel_external_subdir ${LY_ROOT_FOLDER} ${external_subdir}) + string(JSON LY_INSTALL_EXTERNAL_SUBDIRS ERROR_VARIABLE external_subdir_error SET ${LY_INSTALL_EXTERNAL_SUBDIRS} + ${external_subdir_index} "\"${engine_rel_external_subdir}\"") + endforeach() + configure_file(${LY_ROOT_FOLDER}/cmake/install/engine.json.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/engine.json @ONLY) install( diff --git a/cmake/install/engine.json.in b/cmake/install/engine.json.in index 4a8579d864..1cfb1826ce 100644 --- a/cmake/install/engine.json.in +++ b/cmake/install/engine.json.in @@ -1,8 +1,11 @@ { "engine_name": "@LY_VERSION_ENGINE_NAME@", - "restricted": "o3de", + "restricted_name": "o3de", "FileVersion": 1, "O3DEVersion": "@LY_VERSION_STRING@", "O3DECopyrightYear": @LY_VERSION_COPYRIGHT_YEAR@, - "O3DEBuildNumber": @LY_VERSION_BUILD_NUMBER@ + "O3DEBuildNumber": @LY_VERSION_BUILD_NUMBER@, + "external_subdirectories": @LY_INSTALL_EXTERNAL_SUBDIRS@, + "projects": [@LY_INSTALL_PROJECTS@], + "templates": [@LY_INSTALL_TEMPLATES@] } From 57bdc58c68995642c13045d81a9e45dbacb1f1bf Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Mon, 24 May 2021 00:49:00 -0500 Subject: [PATCH 107/811] Renamed the unit_test_registration.py script to be unit_test_register.py to be inline with the register.py script --- scripts/o3de/tests/CMakeLists.txt | 2 +- .../tests/{unit_test_registration.py => unit_test_register.py} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename scripts/o3de/tests/{unit_test_registration.py => unit_test_register.py} (100%) diff --git a/scripts/o3de/tests/CMakeLists.txt b/scripts/o3de/tests/CMakeLists.txt index 29410e3523..7abc22a030 100644 --- a/scripts/o3de/tests/CMakeLists.txt +++ b/scripts/o3de/tests/CMakeLists.txt @@ -16,7 +16,7 @@ endif() # Add a test to test out the o3de package `o3de.py register` command ly_add_pytest( NAME o3de_register - PATH ${CMAKE_CURRENT_LIST_DIR}/unit_test_registration.py + PATH ${CMAKE_CURRENT_LIST_DIR}/unit_test_register.py TEST_SUITE smoke EXCLUDE_TEST_RUN_TARGET_FROM_IDE ) diff --git a/scripts/o3de/tests/unit_test_registration.py b/scripts/o3de/tests/unit_test_register.py similarity index 100% rename from scripts/o3de/tests/unit_test_registration.py rename to scripts/o3de/tests/unit_test_register.py From c29c1825cb519551356da38ac7cbfabfa500b4ab Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Mon, 24 May 2021 01:19:37 -0700 Subject: [PATCH 108/811] Added RayTracingPass and RayTracingPassData --- .../Code/Source/CommonSystemComponent.cpp | 6 + .../Code/Source/RayTracing/RayTracingPass.cpp | 326 ++++++++++++++++++ .../Code/Source/RayTracing/RayTracingPass.h | 81 +++++ .../Source/RayTracing/RayTracingPassData.h | 73 ++++ .../Code/atom_feature_common_files.cmake | 3 + .../RPI/Code/Include/Atom/RPI.Reflect/Base.h | 3 + 6 files changed, 492 insertions(+) create mode 100644 Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp create mode 100644 Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.h create mode 100644 Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPassData.h diff --git a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp index 089a6168b1..d4053d0b31 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp @@ -91,6 +91,8 @@ #include #include +#include +#include #include #include #include @@ -132,6 +134,7 @@ namespace AZ SMAAFeatureProcessor::Reflect(context); PostProcessFeatureProcessor::Reflect(context); ImGuiPassData::Reflect(context); + RayTracingPassData::Reflect(context); LightingPreset::Reflect(context); ModelPreset::Reflect(context); @@ -275,6 +278,9 @@ namespace AZ passSystem->AddPassCreator(Name("ReflectionScreenSpaceBlurChildPass"), &Render::ReflectionScreenSpaceBlurChildPass::Create); passSystem->AddPassCreator(Name("ReflectionCopyFrameBufferPass"), &Render::ReflectionCopyFrameBufferPass::Create); + // Add RayTracing pas + passSystem->AddPassCreator(Name("RayTracingPass"), &Render::RayTracingPass::Create); + // setup handler for load pass template mappings m_loadTemplatesHandler = RPI::PassSystemInterface::OnReadyLoadTemplatesEvent::Handler([this]() { this->LoadPassTemplateMappings(); }); RPI::PassSystemInterface::Get()->ConnectEvent(m_loadTemplatesHandler); diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp new file mode 100644 index 0000000000..2c0c7e986e --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp @@ -0,0 +1,326 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + RPI::Ptr RayTracingPass::Create(const RPI::PassDescriptor& descriptor) + { + RPI::Ptr pass = aznew RayTracingPass(descriptor); + return pass; + } + + RayTracingPass::RayTracingPass(const RPI::PassDescriptor& descriptor) + : RenderPass(descriptor) + , m_passDescriptor(descriptor) + { + RHI::Ptr device = RHI::RHISystemInterface::Get()->GetDevice(); + if (device->GetFeatures().m_rayTracing == false) + { + // raytracing is not supported on this platform + SetEnabled(false); + } + + Init(); + } + + RayTracingPass::~RayTracingPass() + { + RPI::ShaderReloadNotificationBus::MultiHandler::BusDisconnect(); + } + + void RayTracingPass::Init() + { + RHI::Ptr device = RHI::RHISystemInterface::Get()->GetDevice(); + + m_passData = RPI::PassUtils::GetPassData(m_passDescriptor); + if (m_passData == nullptr) + { + AZ_Error("PassSystem", false, "RayTracingPass [%s]: Invalid RayTracingPassData", GetPathName().GetCStr()); + return; + } + + // ray generation shader + m_rayGenerationShader = LoadShader(m_passData->m_rayGenerationShaderAssetReference); + if (m_rayGenerationShader == nullptr) + { + AZ_Error("PassSystem", false, "RayTracingPass [%s]: Failed to load RayGeneration shader [%s]", GetPathName().GetCStr(), m_passData->m_rayGenerationShaderAssetReference.m_filePath.data()); + return; + } + + auto shaderVariant = m_rayGenerationShader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId); + RHI::PipelineStateDescriptorForRayTracing rayGenerationShaderDescriptor; + shaderVariant.ConfigurePipelineState(rayGenerationShaderDescriptor); + + // closest hit shader + m_closestHitShader = LoadShader(m_passData->m_closestHitShaderAssetReference); + if (m_closestHitShader == nullptr) + { + AZ_Error("PassSystem", false, "RayTracingPass [%s]: Failed to load ClosestHit shader [%s]", GetPathName().GetCStr(), m_passData->m_closestHitShaderAssetReference.m_filePath.data()); + return; + } + + shaderVariant = m_closestHitShader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId); + RHI::PipelineStateDescriptorForRayTracing closestHitShaderDescriptor; + shaderVariant.ConfigurePipelineState(closestHitShaderDescriptor); + + // miss shader + m_missShader = LoadShader(m_passData->m_missShaderAssetReference); + if (m_missShader == nullptr) + { + AZ_Error("PassSystem", false, "RayTracingPass [%s]: Failed to load Miss shader [%s]", GetPathName().GetCStr(), m_passData->m_missShaderAssetReference.m_filePath.data()); + return; + } + + shaderVariant = m_missShader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId); + RHI::PipelineStateDescriptorForRayTracing missShaderDescriptor; + shaderVariant.ConfigurePipelineState(missShaderDescriptor); + + // retrieve global pipeline state + m_globalPipelineState = m_rayGenerationShader->AcquirePipelineState(rayGenerationShaderDescriptor); + AZ_Assert(m_globalPipelineState, "Failed to acquire ray tracing global pipeline state"); + + // create global srg + static const uint32_t RayTracingGlobalSrgBindingSlot = 0; + Data::Asset globalSrgAsset = m_rayGenerationShader->FindShaderResourceGroupAsset(RayTracingGlobalSrgBindingSlot); + AZ_Error("PassSystem", globalSrgAsset.GetId().IsValid(), "RayTracingPass [%s] Failed to find RayTracingGlobalSrg asset", GetPathName().GetCStr()); + AZ_Error("PassSystem", globalSrgAsset.IsReady(), "RayTracingPass [%s] asset is not loaded for shader", GetPathName().GetCStr()); + + m_shaderResourceGroup = RPI::ShaderResourceGroup::Create(globalSrgAsset); + AZ_Assert(m_shaderResourceGroup, "RayTracingPass [%s]: Failed to create RayTracingGlobalSrg", GetPathName().GetCStr()); + RPI::PassUtils::BindDataMappingsToSrg(m_passDescriptor, m_shaderResourceGroup.get()); + + // check to see if the shader requires a ViewSrg + Data::Asset viewSrgAsset = m_rayGenerationShader->FindShaderResourceGroupAsset(RPI::SrgBindingSlot::View); + m_requiresViewSrg = viewSrgAsset.GetId().IsValid(); + + // build the ray tracing pipeline state descriptor + RHI::RayTracingPipelineStateDescriptor descriptor; + descriptor.Build() + ->PipelineState(m_globalPipelineState.get()) + ->MaxPayloadSize(m_passData->m_maxPayloadSize) + ->MaxAttributeSize(m_passData->m_maxAttributeSize) + ->MaxRecursionDepth(m_passData->m_maxRecursionDepth) + ->ShaderLibrary(rayGenerationShaderDescriptor) + ->RayGenerationShaderName(AZ::Name(m_passData->m_rayGenerationShaderName.c_str())) + ->ShaderLibrary(missShaderDescriptor) + ->MissShaderName(AZ::Name(m_passData->m_missShaderName.c_str())) + ->ShaderLibrary(closestHitShaderDescriptor) + ->ClosestHitShaderName(AZ::Name(m_passData->m_closestHitShaderName.c_str())) + ->HitGroup(AZ::Name("HitGroup")) + ->ClosestHitShaderName(AZ::Name(m_passData->m_closestHitShaderName.c_str())); + + // create the ray tracing pipeline state object + m_rayTracingPipelineState = RHI::Factory::Get().CreateRayTracingPipelineState(); + m_rayTracingPipelineState->Init(*device.get(), &descriptor); + + // make sure the shader table rebuilds if we're hotreloading + m_rayTracingRevision = 0; + + RPI::ShaderReloadNotificationBus::MultiHandler::BusDisconnect(); + RPI::ShaderReloadNotificationBus::MultiHandler::BusConnect(m_passData->m_rayGenerationShaderAssetReference.m_assetId); + RPI::ShaderReloadNotificationBus::MultiHandler::BusConnect(m_passData->m_closestHitShaderAssetReference.m_assetId); + RPI::ShaderReloadNotificationBus::MultiHandler::BusConnect(m_passData->m_missShaderAssetReference.m_assetId); + } + + Data::Instance RayTracingPass::LoadShader(const RPI::AssetReference& shaderAssetReference) + { + Data::Asset shaderAsset; + if (shaderAssetReference.m_assetId.IsValid()) + { + shaderAsset = RPI::FindShaderAsset(shaderAssetReference.m_assetId, shaderAssetReference.m_filePath); + } + + if (!shaderAsset.GetId().IsValid()) + { + AZ_Error("PassSystem", false, "RayTracingPass [%s]: Failed to load shader asset [%s]", GetPathName().GetCStr(), shaderAssetReference.m_filePath.data()); + return nullptr; + } + + return RPI::Shader::FindOrCreate(shaderAsset); + } + + void RayTracingPass::FrameBeginInternal(FramePrepareParams params) + { + RPI::Scene* scene = m_pipeline->GetScene(); + RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor(); + if (!rayTracingFeatureProcessor) + { + return; + } + + if (!m_rayTracingShaderTable) + { + RHI::Ptr device = RHI::RHISystemInterface::Get()->GetDevice(); + RHI::RayTracingBufferPools& rayTracingBufferPools = rayTracingFeatureProcessor->GetBufferPools(); + + m_rayTracingShaderTable = RHI::Factory::Get().CreateRayTracingShaderTable(); + m_rayTracingShaderTable->Init(*device.get(), rayTracingBufferPools); + } + + RPI::RenderPass::FrameBeginInternal(params); + } + + void RayTracingPass::SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) + { + RPI::RenderPass::SetupFrameGraphDependencies(frameGraph); + frameGraph.SetEstimatedItemCount(1); + } + + void RayTracingPass::CompileResources(const RHI::FrameGraphCompileContext& context) + { + RPI::Scene* scene = m_pipeline->GetScene(); + RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor(); + AZ_Assert(rayTracingFeatureProcessor, "RayTracingPass requires the RayTracingFeatureProcessor"); + + if (m_shaderResourceGroup != nullptr) + { + BindPassSrg(context, m_shaderResourceGroup); + m_shaderResourceGroup->Compile(); + } + + uint32_t rayTracingRevision = rayTracingFeatureProcessor->GetRevision(); + if (m_rayTracingRevision != rayTracingRevision) + { + // scene changed, need to rebuild the shader table + m_rayTracingRevision = rayTracingRevision; + + AZStd::shared_ptr descriptor = AZStd::make_shared(); + + if (rayTracingFeatureProcessor->GetSubMeshCount()) + { + // build the ray tracing shader table descriptor + RHI::RayTracingShaderTableDescriptor* descriptorBuild = descriptor->Build(AZ::Name("RayTracingShaderTable"), m_rayTracingPipelineState) + ->RayGenerationRecord(AZ::Name(m_passData->m_rayGenerationShaderName.c_str())) + ->MissRecord(AZ::Name(m_passData->m_missShaderName.c_str())); + + // add a hit group for each mesh to the shader table + for (uint32_t i = 0; i < rayTracingFeatureProcessor->GetSubMeshCount(); ++i) + { + descriptorBuild->HitGroupRecord(AZ::Name("HitGroup")); + } + } + + m_rayTracingShaderTable->Build(descriptor); + } + } + + void RayTracingPass::BuildCommandListInternal(const RHI::FrameGraphExecuteContext& context) + { + RPI::Scene* scene = m_pipeline->GetScene(); + RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor(); + AZ_Assert(rayTracingFeatureProcessor, "RayTracingPass requires the RayTracingFeatureProcessor"); + + if (!rayTracingFeatureProcessor || + !rayTracingFeatureProcessor->GetTlas()->GetTlasBuffer() || + !rayTracingFeatureProcessor->GetSubMeshCount() || + !m_rayTracingShaderTable) + { + return; + } + + RHI::DispatchRaysItem dispatchRaysItem; + + // calculate thread counts if this is a full screen raytracing pass + if (m_passData->m_makeFullscreenPass) + { + RPI::PassAttachment* outputAttachment = nullptr; + + if (GetOutputCount() > 0) + { + outputAttachment = GetOutputBinding(0).m_attachment.get(); + } + else if (GetInputOutputCount() > 0) + { + outputAttachment = GetInputOutputBinding(0).m_attachment.get(); + } + + AZ_Assert(outputAttachment != nullptr, "[RayTracingPass '%s']: A fullscreen RayTracing pass must have a valid output or input/output.", GetPathName().GetCStr()); + AZ_Assert(outputAttachment->GetAttachmentType() == RHI::AttachmentType::Image, "[RayTracingPass '%s']: The output of a fullscreen RayTracing pass must be an image.", GetPathName().GetCStr()); + + RHI::Size imageSize = outputAttachment->m_descriptor.m_image.m_size; + + dispatchRaysItem.m_width = imageSize.m_width; + dispatchRaysItem.m_height = imageSize.m_height; + dispatchRaysItem.m_depth = imageSize.m_depth; + } + else + { + dispatchRaysItem.m_width = m_passData->m_threadCountX; + dispatchRaysItem.m_height = m_passData->m_threadCountY; + dispatchRaysItem.m_depth = m_passData->m_threadCountZ; + } + + // bind RayTracingGlobal, RayTracingScene, and View Srgs + // [GFX TODO][ATOM-15610] Add RenderPass::SetSrgsForRayTracingDispatch + AZStd::vector shaderResourceGroups = + { + m_shaderResourceGroup->GetRHIShaderResourceGroup(), + rayTracingFeatureProcessor->GetRayTracingSceneSrg()->GetRHIShaderResourceGroup() + }; + + if (m_requiresViewSrg) + { + const AZStd::vector& views = m_pipeline->GetViews(m_passData->m_pipelineViewTag); + if (views.size() > 0) + { + shaderResourceGroups.push_back(views[0]->GetRHIShaderResourceGroup()); + } + } + + dispatchRaysItem.m_shaderResourceGroupCount = aznumeric_cast(shaderResourceGroups.size()); + dispatchRaysItem.m_shaderResourceGroups = shaderResourceGroups.data(); + dispatchRaysItem.m_rayTracingPipelineState = m_rayTracingPipelineState.get(); + dispatchRaysItem.m_rayTracingShaderTable = m_rayTracingShaderTable.get(); + dispatchRaysItem.m_globalPipelineState = m_globalPipelineState.get(); + + // submit the DispatchRays item + context.GetCommandList()->Submit(dispatchRaysItem); + } + + void RayTracingPass::OnShaderReinitialized([[maybe_unused]] const RPI::Shader& shader) + { + Init(); + } + + void RayTracingPass::OnShaderAssetReinitialized([[maybe_unused]] const Data::Asset& shaderAsset) + { + Init(); + } + + void RayTracingPass::OnShaderVariantReinitialized([[maybe_unused]] const RPI::Shader& shader, [[maybe_unused]] const RPI::ShaderVariantId& shaderVariantId, [[maybe_unused]] RPI::ShaderVariantStableId shaderVariantStableId) + { + Init(); + } + } // namespace RPI +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.h b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.h new file mode 100644 index 0000000000..935d034513 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.h @@ -0,0 +1,81 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + struct RayTracingPassData; + + //! This pass executes a raytracing shader as specified in the PassData. + class RayTracingPass + : public RPI::RenderPass + , private RPI::ShaderReloadNotificationBus::MultiHandler + { + AZ_RPI_PASS(RayTracingPass); + + public: + AZ_RTTI(RayTracingPass, "{7A68A36E-956A-4258-93FE-38686042C4D9}", RPI::RenderPass); + AZ_CLASS_ALLOCATOR(RayTracingPass, SystemAllocator, 0); + virtual ~RayTracingPass(); + + //! Creates a RayTracingPass + static RPI::Ptr Create(const RPI::PassDescriptor& descriptor); + + protected: + RayTracingPass(const RPI::PassDescriptor& descriptor); + + // Pass overrides + void FrameBeginInternal(FramePrepareParams params) override; + + // Scope producer functions + void SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) override; + void CompileResources(const RHI::FrameGraphCompileContext& context) override; + void BuildCommandListInternal(const RHI::FrameGraphExecuteContext& context) override; + + // ShaderReloadNotificationBus::Handler overrides + void OnShaderReinitialized(const RPI::Shader& shader) override; + void OnShaderAssetReinitialized(const Data::Asset& shaderAsset) override; + void OnShaderVariantReinitialized(const RPI::Shader& shader, const RPI::ShaderVariantId& shaderVariantId, RPI::ShaderVariantStableId shaderVariantStableId) override; + + // load the raytracing shaders and setup pipeline states + void Init(); + + // helper for loading a shader from a shader asset reference + Data::Instance LoadShader(const RPI::AssetReference& shaderAssetReference); + + // pass data + RPI::PassDescriptor m_passDescriptor; + const RayTracingPassData* m_passData = nullptr; + + // revision number of the ray tracing TLAS when the shader table was built + uint32_t m_rayTracingRevision = 0; + + // raytracing shaders, pipeline states, and shader table + Data::Instance m_rayGenerationShader; + Data::Instance m_missShader; + Data::Instance m_closestHitShader; + RHI::Ptr m_rayTracingPipelineState; + RHI::ConstPtr m_globalPipelineState; + RHI::Ptr m_rayTracingShaderTable; + bool m_requiresViewSrg = false; + }; + } // namespace RPI +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPassData.h b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPassData.h new file mode 100644 index 0000000000..bc15a8372c --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPassData.h @@ -0,0 +1,73 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include +#include + +namespace AZ +{ + namespace Render + { + //! Custom data for the RayTracingPass, specified in the PassRequest. + struct RayTracingPassData + : public RPI::RenderPassData + { + AZ_RTTI(RayTracingPassData, "{26C2E2FD-D30A-4142-82A3-0167BC94B3EE}", RPI::RenderPassData); + AZ_CLASS_ALLOCATOR(RayTracingPassData, SystemAllocator, 0); + + RayTracingPassData() = default; + virtual ~RayTracingPassData() = default; + + static void Reflect(ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("RayGenerationShaderAsset", &RayTracingPassData::m_rayGenerationShaderAssetReference) + ->Field("RayGenerationShaderName", &RayTracingPassData::m_rayGenerationShaderName) + ->Field("ClosestHitShaderAsset", &RayTracingPassData::m_closestHitShaderAssetReference) + ->Field("ClosestHitShaderName", &RayTracingPassData::m_closestHitShaderName) + ->Field("MissShaderAsset", &RayTracingPassData::m_missShaderAssetReference) + ->Field("MissShaderName", &RayTracingPassData::m_missShaderName) + ->Field("MaxPayloadSize", &RayTracingPassData::m_maxPayloadSize) + ->Field("MaxAttributeSize", &RayTracingPassData::m_maxAttributeSize) + ->Field("MaxRecursionDepth", &RayTracingPassData::m_maxRecursionDepth) + ->Field("Thread Count X", &RayTracingPassData::m_threadCountX) + ->Field("Thread Count Y", &RayTracingPassData::m_threadCountY) + ->Field("Thread Count Z", &RayTracingPassData::m_threadCountZ) + ->Field("Make Fullscreen Pass", &RayTracingPassData::m_makeFullscreenPass) + ; + } + } + + RPI::AssetReference m_rayGenerationShaderAssetReference; + AZStd::string m_rayGenerationShaderName; + RPI::AssetReference m_closestHitShaderAssetReference; + AZStd::string m_closestHitShaderName; + RPI::AssetReference m_missShaderAssetReference; + AZStd::string m_missShaderName; + + uint32_t m_maxPayloadSize = 64; + uint32_t m_maxAttributeSize = 32; + uint32_t m_maxRecursionDepth = 1; + + uint32_t m_threadCountX = 1; + uint32_t m_threadCountY = 1; + uint32_t m_threadCountZ = 1; + + bool m_makeFullscreenPass = false; + }; + } // namespace RPI +} // namespace AZ + diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake index 8926b0c19f..064e49922d 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -252,6 +252,9 @@ set(FILES Source/RayTracing/RayTracingFeatureProcessor.cpp Source/RayTracing/RayTracingAccelerationStructurePass.cpp Source/RayTracing/RayTracingAccelerationStructurePass.h + Source/RayTracing/RayTracingPass.cpp + Source/RayTracing/RayTracingPass.h + Source/RayTracing/RayTracingPassData.h Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp Source/ReflectionProbe/ReflectionProbe.cpp Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Base.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Base.h index c376112290..52b75c4157 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Base.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Base.h @@ -59,7 +59,10 @@ namespace AZ static constexpr uint32_t Draw = 0; static constexpr uint32_t Object = 1; static constexpr uint32_t Material = 2; + static constexpr uint32_t SubPass = 3; static constexpr uint32_t Pass = 4; + static constexpr uint32_t View = 5; + static constexpr uint32_t Scene = 6; }; } } From 6a0cf974560d5d617d601cc9c765d7de022be1ea Mon Sep 17 00:00:00 2001 From: igarri Date: Mon, 24 May 2021 13:19:35 +0100 Subject: [PATCH 109/811] Fixed Selection in AssetBrowserTreeView --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 5 +++-- .../AssetBrowser/Views/AssetBrowserTreeView.cpp | 4 +++- Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp | 5 ++--- .../Code/Editor/Model/UnitTestBrowserFilterModel.cpp | 2 +- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 7c7f2aa601..fc2fc41656 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -23,8 +23,9 @@ AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") #include AZ_POP_DISABLE_WARNING -AZ_CVAR_EXTERNED(bool, ed_useNewAssetBrowserTableView); - +AZ_CVAR( + bool, ed_useNewAssetBrowserTableView, false, nullptr, AZ::ConsoleFunctorFlags::Null, + "Use the new AssetBrowser TableView for searching assets."); namespace AzToolsFramework { namespace AssetBrowser diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp index b93caf85f7..52c785d678 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.cpp @@ -99,8 +99,10 @@ namespace AzToolsFramework AZStd::vector AssetBrowserTreeView::GetSelectedAssets() const { + + const QModelIndexList& selectedIndexes = selectionModel()->selectedRows(); QModelIndexList sourceIndexes; - for (const auto& index : selectedIndexes()) + for (const auto& index : selectedIndexes) { //If we check for more than one column then the model will try to select the same entry several times. if (index.column() == 0) diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 1b123dd000..e722d6d03e 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -33,9 +33,8 @@ AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -AZ_CVAR( - bool, ed_useNewAssetBrowserTableView, false, nullptr, AZ::ConsoleFunctorFlags::Null, - "Use the new AssetBrowser TableView for searching assets."); +AZ_CVAR_EXTERNED(bool, ed_useNewAssetBrowserTableView); + class ListenerForShowAssetEditorEvent : public QObject diff --git a/Gems/ScriptCanvas/Code/Editor/Model/UnitTestBrowserFilterModel.cpp b/Gems/ScriptCanvas/Code/Editor/Model/UnitTestBrowserFilterModel.cpp index 665c81fa57..1a4d95c585 100644 --- a/Gems/ScriptCanvas/Code/Editor/Model/UnitTestBrowserFilterModel.cpp +++ b/Gems/ScriptCanvas/Code/Editor/Model/UnitTestBrowserFilterModel.cpp @@ -34,7 +34,7 @@ namespace ScriptCanvasEditor { setDynamicSortFilter(true); - m_showColumn.insert(AssetBrowserModel::m_column); + m_showColumn.insert(aznumeric_cast(AssetBrowserEntry::Column::DisplayName)); UnitTestWidgetNotificationBus::Handler::BusConnect(); From 21285809bf0dfb8a30fd00061d5e81bb80cb3f10 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Mon, 24 May 2021 11:39:07 -0500 Subject: [PATCH 110/811] Adding back gem.json files to the Atom and AtomLyIntegration folders which are to be seen as sub gem roots as a workaround for detecting the location of the "gem" root for the Atom/AtomLyIntegration GEM_MODULE targets Removed the logic in the SettingsRegistry.cmake for reading a "gem_module_roots" key from the gem.json file in order to determine the root of the Atom and Atom LyIntegration sub gem modules --- Gems/Atom/Asset/ImageProcessingAtom/gem.json | 10 +++ Gems/Atom/Asset/Shader/gem.json | 10 +++ Gems/Atom/Bootstrap/gem.json | 10 +++ Gems/Atom/Component/DebugCamera/gem.json | 10 +++ Gems/Atom/Feature/Common/gem.json | 10 +++ Gems/Atom/RHI/DX12/gem.json | 10 +++ Gems/Atom/RHI/Metal/gem.json | 10 +++ Gems/Atom/RHI/Null/gem.json | 10 +++ Gems/Atom/RHI/Vulkan/gem.json | 10 +++ Gems/Atom/RHI/gem.json | 10 +++ Gems/Atom/RPI/gem.json | 10 +++ Gems/Atom/Tools/AtomToolsFramework/gem.json | 10 +++ Gems/Atom/gem.json | 16 +--- Gems/AtomLyIntegration/AtomBridge/gem.json | 10 +++ Gems/AtomLyIntegration/AtomFont/gem.json | 10 +++ .../AtomLyIntegration/AtomImGuiTools/gem.json | 10 +++ .../AtomViewportDisplayInfo/gem.json | 12 +++ .../AtomLyIntegration/CommonFeatures/gem.json | 10 +++ Gems/AtomLyIntegration/EMotionFXAtom/gem.json | 10 +++ Gems/AtomLyIntegration/ImguiAtom/gem.json | 10 +++ .../DccScriptingInterface/gem.json | 10 +++ Gems/AtomLyIntegration/gem.json | 12 +-- cmake/SettingsRegistry.cmake | 80 ++----------------- 23 files changed, 213 insertions(+), 97 deletions(-) create mode 100644 Gems/Atom/Asset/ImageProcessingAtom/gem.json create mode 100644 Gems/Atom/Asset/Shader/gem.json create mode 100644 Gems/Atom/Bootstrap/gem.json create mode 100644 Gems/Atom/Component/DebugCamera/gem.json create mode 100644 Gems/Atom/Feature/Common/gem.json create mode 100644 Gems/Atom/RHI/DX12/gem.json create mode 100644 Gems/Atom/RHI/Metal/gem.json create mode 100644 Gems/Atom/RHI/Null/gem.json create mode 100644 Gems/Atom/RHI/Vulkan/gem.json create mode 100644 Gems/Atom/RHI/gem.json create mode 100644 Gems/Atom/RPI/gem.json create mode 100644 Gems/Atom/Tools/AtomToolsFramework/gem.json create mode 100644 Gems/AtomLyIntegration/AtomBridge/gem.json create mode 100644 Gems/AtomLyIntegration/AtomFont/gem.json create mode 100644 Gems/AtomLyIntegration/AtomImGuiTools/gem.json create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json create mode 100644 Gems/AtomLyIntegration/CommonFeatures/gem.json create mode 100644 Gems/AtomLyIntegration/EMotionFXAtom/gem.json create mode 100644 Gems/AtomLyIntegration/ImguiAtom/gem.json create mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/gem.json diff --git a/Gems/Atom/Asset/ImageProcessingAtom/gem.json b/Gems/Atom/Asset/ImageProcessingAtom/gem.json new file mode 100644 index 0000000000..86256bff9d --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "ImageProcessingAtom", + "display_name": "Atom Image Processing", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/Asset/Shader/gem.json b/Gems/Atom/Asset/Shader/gem.json new file mode 100644 index 0000000000..71c741f436 --- /dev/null +++ b/Gems/Atom/Asset/Shader/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "AtomShader", + "display_name": "Atom Shader Builder", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/Bootstrap/gem.json b/Gems/Atom/Bootstrap/gem.json new file mode 100644 index 0000000000..8aa5cade6e --- /dev/null +++ b/Gems/Atom/Bootstrap/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Atom_Bootstrap", + "display_name": "Atom Bootstrap", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/Component/DebugCamera/gem.json b/Gems/Atom/Component/DebugCamera/gem.json new file mode 100644 index 0000000000..06d39d1fc0 --- /dev/null +++ b/Gems/Atom/Component/DebugCamera/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Atom_Component_DebugCamera", + "display_name": "Atom Debug Camera Component", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/Feature/Common/gem.json b/Gems/Atom/Feature/Common/gem.json new file mode 100644 index 0000000000..6980863b4c --- /dev/null +++ b/Gems/Atom/Feature/Common/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Atom_Feature_Common", + "display_name": "Atom Feature Common", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/RHI/DX12/gem.json b/Gems/Atom/RHI/DX12/gem.json new file mode 100644 index 0000000000..683ccfb43a --- /dev/null +++ b/Gems/Atom/RHI/DX12/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Atom_RHI_DX12", + "display_name": "Atom RHI DX12", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/RHI/Metal/gem.json b/Gems/Atom/RHI/Metal/gem.json new file mode 100644 index 0000000000..3e1726e8fa --- /dev/null +++ b/Gems/Atom/RHI/Metal/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Atom_RHI_Metal", + "display_name": "Atom RHI Metal", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/RHI/Null/gem.json b/Gems/Atom/RHI/Null/gem.json new file mode 100644 index 0000000000..4fa5f1e480 --- /dev/null +++ b/Gems/Atom/RHI/Null/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Atom_RHI_Null", + "display_name": "Atom RHI Null", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/RHI/Vulkan/gem.json b/Gems/Atom/RHI/Vulkan/gem.json new file mode 100644 index 0000000000..1f2fcd7f30 --- /dev/null +++ b/Gems/Atom/RHI/Vulkan/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Atom_RHI_Vulkan", + "display_name": "Atom RHI Vulkan", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/RHI/gem.json b/Gems/Atom/RHI/gem.json new file mode 100644 index 0000000000..eb67e40a4a --- /dev/null +++ b/Gems/Atom/RHI/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Atom_RHI", + "display_name": "Atom RHI", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/RPI/gem.json b/Gems/Atom/RPI/gem.json new file mode 100644 index 0000000000..7e822611a9 --- /dev/null +++ b/Gems/Atom/RPI/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Atom_RPI", + "display_name": "Atom API", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/Tools/AtomToolsFramework/gem.json b/Gems/Atom/Tools/AtomToolsFramework/gem.json new file mode 100644 index 0000000000..3060d3f51a --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "AtomToolsFramework", + "display_name": "Atom Tools Framework", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/Atom/gem.json b/Gems/Atom/gem.json index 99a715281e..91bc9bcf53 100644 --- a/Gems/Atom/gem.json +++ b/Gems/Atom/gem.json @@ -1,17 +1,5 @@ { "gem_name": "Atom", - "gem_module_roots": [ - "Asset/ImageProcessingAtom", - "Asset/Shader", - "Bootstrap", - "Component/DebugCamera", - "Feature/Common", - "RHI", - "RHI/DX12", - "RHI/Metal", - "RHI/Null", - "RHI/Vulkan", - "RPI", - "Tools/AtomToolsFramework" - ] + "display_name": "Atom", + "summary": "Next-Gen Rendering Package for the O3DE engine" } diff --git a/Gems/AtomLyIntegration/AtomBridge/gem.json b/Gems/AtomLyIntegration/AtomBridge/gem.json new file mode 100644 index 0000000000..329741bb8e --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Atom_AtomBridge", + "display_name": "Atom Bridge", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/AtomLyIntegration/AtomFont/gem.json b/Gems/AtomLyIntegration/AtomFont/gem.json new file mode 100644 index 0000000000..a609061ea3 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomFont/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "AtomFont", + "display_name": "Atom Font", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/AtomLyIntegration/AtomImGuiTools/gem.json b/Gems/AtomLyIntegration/AtomImGuiTools/gem.json new file mode 100644 index 0000000000..5cee62f7bb --- /dev/null +++ b/Gems/AtomLyIntegration/AtomImGuiTools/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "AtomImGuiTools", + "display_name": "Atom ImGui", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json new file mode 100644 index 0000000000..3a83607924 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json @@ -0,0 +1,12 @@ +{ + "gem_name": "AtomLyIntegration_AtomViewportDisplayInfo", + "display_name": "Atom Viewport Display Info Overlay", + "summary": "Provides a diagnostic viewport overlay for the default O3DE Atom viewport.", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + "AtomLyIntegration", + "AtomViewportDisplayInfo" + ] +} diff --git a/Gems/AtomLyIntegration/CommonFeatures/gem.json b/Gems/AtomLyIntegration/CommonFeatures/gem.json new file mode 100644 index 0000000000..306c61e6d7 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "CommonFeaturesAtom", + "display_name": "Common Features Atom", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/gem.json b/Gems/AtomLyIntegration/EMotionFXAtom/gem.json new file mode 100644 index 0000000000..e2a81d0a5e --- /dev/null +++ b/Gems/AtomLyIntegration/EMotionFXAtom/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "EMotionFX_Atom", + "display_name": "EMotionFX Atom", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/AtomLyIntegration/ImguiAtom/gem.json b/Gems/AtomLyIntegration/ImguiAtom/gem.json new file mode 100644 index 0000000000..6d6551b5fa --- /dev/null +++ b/Gems/AtomLyIntegration/ImguiAtom/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "ImguiAtom", + "display_name": "Imgui Atom", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/gem.json b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/gem.json new file mode 100644 index 0000000000..94f5bb6d43 --- /dev/null +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "DccScriptingInterface", + "display_name": "Atom Dcc Scripting Interface", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/AtomLyIntegration/gem.json b/Gems/AtomLyIntegration/gem.json index c350281ad1..4f587a8806 100644 --- a/Gems/AtomLyIntegration/gem.json +++ b/Gems/AtomLyIntegration/gem.json @@ -1,13 +1,5 @@ { "gem_name": "AtomLyIntegration", - "gem_module_roots": [ - "AtomBridge", - "AtomFont", - "AtomImGuiTools", - "AtomViewportDisplayInfo", - "CommonFeatures", - "EMotionFXAtom", - "ImguiAtom", - "TechnicalArt/DccScriptingInterface" - ] + "display_name": "Atom O3DE Integration", + "summary": "Collection of module targets for integrating Atom with the O3DE engine" } diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index d1f4041cce..825440e100 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -85,12 +85,10 @@ function(ly_get_gem_load_dependencies ly_GEM_LOAD_DEPENDENCIES ly_TARGET) set(${ly_GEM_LOAD_DEPENDENCIES} ${all_gem_load_dependencies} PARENT_SCOPE) endfunction() -#!ly_get_gem_module_roots: Uses the supplied gem_target to lookup the nearest gem.json file above the SOURCE_DIR -# If a gem.json file is found it is added as gem module root and then queried for additional gem module root -# by looking up the "gem_module_root" key +#!ly_get_gem_module_root: Uses the supplied gem_target to lookup the nearest gem.json file above the SOURCE_DIR # # \arg:gem_target(TARGET) - Target to look upwards from using its SOURCE_DIR property -function(ly_get_gem_module_roots output_gem_module_roots gem_target) +function(ly_get_gem_module_root output_gem_module_root gem_target) unset(gem_module_roots) get_property(gem_source_dir TARGET ${gem_target} PROPERTY SOURCE_DIR) @@ -109,76 +107,13 @@ function(ly_get_gem_module_roots output_gem_module_roots gem_target) if (EXISTS ${candidate_gem_dir}/gem.json) set(gem_source_dir ${candidate_gem_dir}) - file(READ ${gem_source_dir}/gem.json gem_json_data) - string(JSON module_root_count ERROR_VARIABLE gem_json_error LENGTH ${gem_json_data} gem_module_roots) - if(module_root_count GREATER 0) - math(EXPR module_root_range "${module_root_count}-1") - # Convert the paths the relative paths to absolute paths using the engine root - # as the base directory - foreach(module_root_index RANGE ${module_root_range}) - string(JSON module_root ERROR_VARIABLE gem_json_error GET ${gem_json_data} gem_module_roots ${module_root_index}) - file(REAL_PATH ${module_root} gem_absolute_module_root BASE_DIRECTORY ${gem_source_dir}) - list(APPEND gem_module_roots ${gem_absolute_module_root}) - endforeach() - endif() endif() - # Prepend the relative path from the Engine Root to the gem_module_roots list - list(PREPEND gem_module_roots ${gem_source_dir}) - set(${output_gem_module_roots} ${gem_module_roots} PARENT_SCOPE) + # Set the gem module root output directory to the location with the gem.json file within it or + # the supplied gem_target SOURCE_DIR location if no gem.json file was found + set(${output_gem_module_root} ${gem_source_dir} PARENT_SCOPE) endfunction() -#!ly_find_best_gem_module_roots: Attempts to find the gem module root which is the closest ancestor directory -# to the gem_target using the supplied gem_module_roots -# If a gem.json file is found it is added as gem module root and then queried for additional gem module root -# by looking up the "gem_module_root" key - -# \arg:gem_target(TARGET) - Target to whose SOURCE_DIR property is compared against the module roots -# \arg:gem_module_roots(list:PATH) - list of absolute gem module roots to search for nearest ancestor -function(ly_find_best_gem_module_root output_module_root gem_target gem_module_roots) - - get_property(module_root_cached DIRECTORY PROPERTY gem_module_root_${gem_target} SET) - if(module_root_cached) - get_property(module_root_prop DIRECTORY PROPERTY gem_module_root_${gem_target} ) - set(${output_module_root} ${module_root_prop} PARENT_SCOPE) - return() - endif() - - # An optimization for the case where there is only one gem_module_roots. The output_module_root is set to that - list(LENGTH gem_module_roots gem_module_roots_count) - if(gem_module_roots_count EQUAL 1) - list(GET gem_module_roots 0 best_module_root) - set_property(DIRECTORY PROPERTY gem_module_root_${gem_target} ${best_module_root}) - set(${output_module_root} ${best_module_root} PARENT_SCOPE) - return() - endif() - - get_property(gem_source_dir TARGET ${gem_target} PROPERTY SOURCE_DIR) - # shortest_prefix is used to store the shortest prefix from a gem module root to the gem source dir - # Initialized to 10000 to make sure it is larger than any file path length - set(shortest_prefix "10000") - unset(best_module_root) - foreach(gem_module_root ${gem_module_roots}) - file(RELATIVE_PATH relative_to_module_root ${gem_module_root} ${gem_source_dir}) - # if the gem SOURCE_DIR is not relative to the module root then continue - if(relative_to_module_root MATCHES [[^\.\./]] OR IS_ABSOLUTE ${relative_to_module_root}) - continue() - endif() - # Update the shortest prefix - string(LENGTH "${relative_to_module_root}" module_to_source_dir_length) - if(module_to_source_dir_length LESS shortest_prefix) - set(best_module_root ${gem_module_root}) - set(shortest_prefix "${module_to_source_dir_length}") - endif() - endforeach() - - # Assign the best_module_root path to the output variable and stored it in a DIRECTORY property for caching - if(best_module_root) - set_property(DIRECTORY PROPERTY gem_module_root_${gem_target} ${best_module_root}) - set(${output_module_root} ${best_module_root} PARENT_SCOPE) - endif() - -endfunction() #! ly_delayed_generate_settings_registry: Generates a .setreg file for each target with dependencies # added to it via ly_add_target_dependencies @@ -219,9 +154,8 @@ function(ly_delayed_generate_settings_registry) message(FATAL_ERROR "Dependency ${gem_target} from ${target} does not exist") endif() - ly_get_gem_module_roots(gem_module_roots ${gem_target}) - ly_find_best_gem_module_root(best_gem_module_root "${gem_target}" "${gem_module_roots}") - file(RELATIVE_PATH gem_module_root_relative_to_engine_root ${LY_ROOT_FOLDER} ${best_gem_module_root}) + ly_get_gem_module_root(gem_module_root ${gem_target}) + file(RELATIVE_PATH gem_module_root_relative_to_engine_root ${LY_ROOT_FOLDER} ${gem_module_root}) # Strip target namespace from gem targets before configuring them into the json template ly_strip_target_namespace(TARGET ${gem_target} OUTPUT_VARIABLE stripped_gem_target) From 1a95b96985993b31eedff012670f12dcc15e54cf Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Mon, 24 May 2021 13:06:43 -0500 Subject: [PATCH 111/811] Fixed importing of o3de package modules within the o3de.py script when a relative path is used to invoke it --- scripts/o3de.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/scripts/o3de.py b/scripts/o3de.py index dabb83b068..cc3a14a8c3 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -27,18 +27,26 @@ def add_args(parser, subparsers) -> None: # As o3de.py shares the same name as the o3de package attempting to use a regular # from o3de import line tries to import from the current o3de.py script and not the package # So the current script directory is removed from the sys.path temporary - SCRIPT_DIR_REMOVED = False - SCRIPT_DIR = pathlib.Path(__file__).parent.resolve() - while str(SCRIPT_DIR) in sys.path: - SCRIPT_DIR_REMOVED = True - sys.path.remove(str(SCRIPT_DIR)) + script_dir_removed = False + script_abs_dir_removed = False + script_dir = pathlib.Path(__file__).parent + script_abs_dir = pathlib.Path(__file__).parent.resolve() + while str(script_dir) in sys.path: + script_dir_removed = True + sys.path.remove(str(script_dir)) + while str(script_abs_dir) in sys.path: + script_abs_dir_removed = True + # Remove the absolute path to the script_dir as well + sys.path.remove(str(script_abs_dir.resolve())) from o3de import engine_template, global_project, register, print_registration, get_registration, download, \ add_external_subdirectory, remove_external_subdirectory, add_gem_cmake, remove_gem_cmake, add_gem_project, \ remove_gem_project, sha256 - if SCRIPT_DIR_REMOVED: - sys.path.insert(0, str(SCRIPT_DIR)) + if script_abs_dir_removed: + sys.path.insert(0, str(script_abs_dir)) + if script_dir_removed: + sys.path.insert(0, str(script_dir)) # global_project global_project.add_args(subparsers) From 12d0d9e7b78edff156a4cdc3abfb42879126eab5 Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Mon, 24 May 2021 12:49:38 -0700 Subject: [PATCH 112/811] The host will now have autonomy over the default player is has spawned for itself using the sv_defaultPlayerSpawnAsset cvar --- Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index ef8627fe54..39bbf6644e 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -449,6 +449,7 @@ namespace Multiplayer { controlledEntity = entityList[0]; controlledEntity.GetNetBindComponent()->SetOwningConnectionId(connection->GetConnectionId()); + controlledEntity.GetNetBindComponent()->SetAllowAutonomy(true); } if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so From 76985602ce0ab1f41a263a92458a0032f0c017c8 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Mon, 24 May 2021 15:57:01 -0500 Subject: [PATCH 113/811] Remove commented out logic from the DefaultProject CMakeLists.txt --- .../DefaultProject/Template/CMakeLists.txt | 95 ------------------- 1 file changed, 95 deletions(-) diff --git a/Templates/DefaultProject/Template/CMakeLists.txt b/Templates/DefaultProject/Template/CMakeLists.txt index c92607a789..b5b8692059 100644 --- a/Templates/DefaultProject/Template/CMakeLists.txt +++ b/Templates/DefaultProject/Template/CMakeLists.txt @@ -46,98 +46,3 @@ else() add_subdirectory(Code) endif() - - - -# #! Adds the --project-path argument to the VS IDE debugger command arguments -# function(add_vs_debugger_arguments) -# # Inject the project root into the --project-path argument into the Visual Studio Debugger arguments by defaults -# list(APPEND app_targets ${Name}.GameLauncher ${Name}.ServerLauncher) -# list(APPEND app_targets AssetBuilder AssetProcessor AssetProcessorBatch Editor) -# foreach(app_target IN LISTS app_targets) -# if (TARGET ${app_target}) -# set_property(TARGET ${app_target} APPEND PROPERTY VS_DEBUGGER_COMMAND_ARGUMENTS "--project-path=\"${CMAKE_CURRENT_LIST_DIR}\"") -# endif() -# endforeach() -# endfunction() - -# set(o3de_project_path ${CMAKE_CURRENT_LIST_DIR}) -# set(o3de_project_json ${o3de_project_path}/project.json) - -# if(NOT PROJECT_NAME) -# cmake_minimum_required(VERSION 3.19) -# project(${Name} -# LANGUAGES C CXX -# VERSION 1.0.0.0 -# ) - -# # set this project as the only project -# set(LY_PROJECTS ${CMAKE_CURRENT_LIST_DIR}) - -# # o3de manifest -# include(o3de_manifest.cmake) - -# ################################################################################ -# # Set the engine_path and resolve this engines restricted path if it has one -# ################################################################################ -# o3de_engine_path(${o3de_project_json} o3de_engine_path) -# o3de_project_name(${o3de_project_json} o3de_project_name) -# o3de_restricted_path(${o3de_project_json} o3de_project_restricted_path) -# message(STATUS "O3DE Project Name: ${o3de_project_name}") -# message(STATUS "O3DE Project Path: ${o3de_project_path}") -# if(o3de_project_restricted_path) -# message(STATUS "O3DE Project Restricted Path: ${o3de_project_restricted_path}") -# endif() - -# # add the engines cmake folder to the CMAKE_MODULE_PATH -# list(APPEND CMAKE_MODULE_PATH "${o3de_engine_path}/cmake") - -# # add subdirectory on the engine path for this project -# #add_subdirectory(${o3de_engine_path} o3de) -# find_package(o3de REQUIRED) -# o3de_initialize() - -# # add this --project-path arguments to visual studio debugger -# add_vs_debugger_arguments() - -# else() -# ###################################################### -# # the engine is calling add sub_directory() on us -# ###################################################### -# o3de_project_name(${o3de_project_json} o3de_project_name) -# o3de_restricted_path(${o3de_project_json} o3de_project_restricted_path) - -# # Currently we are in the folder: ${CMAKE_CURRENT_LIST_DIR} -# # Get the platform specific folder ${pal_dir} for the folder: ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} -# # Note: ly_get_list_relative_pal_filename will take care of the details for us, as this may be a restricted platform -# # in which case it will see if that platform is present here or in the restricted folder. -# # i.e. It could here: TestDP/Platform/ or -# # //TestDP -# ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} ${o3de_project_restricted_path} ${o3de_project_path} ${o3de_project_name}) - -# # Now that we have the platform abstraction layer (PAL) folder for this folder, thats where we will find the -# # project cmake for this platform. -# include(${pal_dir}/${PAL_PLATFORM_NAME_LOWERCASE}_project.cmake) - -# # Add the project_name to global LY_PROJECTS_TARGET_NAME property -# set_property(GLOBAL APPEND PROPERTY LY_PROJECTS_TARGET_NAME ${o3de_project_name}) - -# add_subdirectory(Code) -# endif() - - - - - - - - - - - - - - - - - From bff7d39f68d2e7fed3afa11dd22e95ed0d1c8c54 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 24 May 2021 16:21:29 -0700 Subject: [PATCH 114/811] passing imported for executables --- cmake/LYWrappers.cmake | 23 +++++++++++++++-------- cmake/SettingsRegistry.cmake | 7 ++++++- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index bddd1a6c66..0e4ba5e214 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -100,22 +100,27 @@ function(ly_add_target) ly_include_cmake_file_list(${file_cmake}) endforeach() - set(linking_options) - set(linking_count) + unset(linking_options) + unset(linking_count) + unset(target_type_options) if(ly_add_target_STATIC) set(linking_options STATIC) + set(target_type_options STATIC) set(linking_count "${linking_count}1") endif() if(ly_add_target_SHARED) set(linking_options SHARED) + set(target_type_options SHARED) set(linking_count "${linking_count}1") endif() if(ly_add_target_MODULE) set(linking_options ${PAL_LINKOPTION_MODULE}) + set(target_type_options ${PAL_LINKOPTION_MODULE}) set(linking_count "${linking_count}1") endif() if(ly_add_target_HEADERONLY) set(linking_options INTERFACE) + set(target_type_options INTERFACE) set(linking_count "${linking_count}1") endif() if(ly_add_target_EXECUTABLE) @@ -130,7 +135,7 @@ function(ly_add_target) message(FATAL_ERROR "More than one of the following options [STATIC | SHARED | MODULE | HEADERONLY | EXECUTABLE | APPLICATION ] was specified and they are mutually exclusive") endif() if(ly_add_target_IMPORTED) - list(APPEND linking_options IMPORTED GLOBAL) + list(APPEND target_type_options IMPORTED GLOBAL) endif() if(ly_add_target_NAMESPACE) @@ -141,7 +146,8 @@ function(ly_add_target) set(project_NAME ${ly_add_target_NAME}) if(ly_add_target_EXECUTABLE) - add_executable(${ly_add_target_NAME} + add_executable(${ly_add_target_NAME} + ${target_type_options} ${ALLFILES} ${ly_add_target_GENERATED_FILES} ) ly_apply_platform_properties(${ly_add_target_NAME}) @@ -149,7 +155,8 @@ function(ly_add_target) set_target_properties(${ly_add_target_NAME} PROPERTIES LINKER_LANGUAGE CXX) endif() elseif(ly_add_target_APPLICATION) - add_executable(${ly_add_target_NAME} + add_executable(${ly_add_target_NAME} + ${target_type_options} ${PAL_EXECUTABLE_APPLICATION_FLAG} ${ALLFILES} ${ly_add_target_GENERATED_FILES} ) @@ -159,12 +166,12 @@ function(ly_add_target) endif() elseif(ly_add_target_HEADERONLY) add_library(${ly_add_target_NAME} - ${linking_options} + ${target_type_options} ${ALLFILES} ${ly_add_target_GENERATED_FILES} ) else() add_library(${ly_add_target_NAME} - ${linking_options} + ${target_type_options} ${ALLFILES} ${ly_add_target_GENERATED_FILES} ) ly_apply_platform_properties(${ly_add_target_NAME}) @@ -302,7 +309,7 @@ function(ly_add_target) set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGETS ${interface_name}) set(runtime_dependencies_list SHARED MODULE EXECUTABLE APPLICATION) - if(linking_options IN_LIST runtime_dependencies_list) + if(NOT ly_add_target_IMPORTED AND linking_options IN_LIST runtime_dependencies_list) add_custom_command(TARGET ${ly_add_target_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -P ${CMAKE_BINARY_DIR}/runtime_dependencies/$/${ly_add_target_NAME}.cmake diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index 31ce36c516..b40650d900 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -150,7 +150,12 @@ function(ly_delayed_generate_settings_registry) list(JOIN target_gem_dependencies_names ",\n" target_gem_dependencies_names) string(CONFIGURE ${gems_json_template} gem_json @ONLY) - set(dependencies_setreg $/Registry/cmake_dependencies.${specialization_name}.setreg) + if(prefix) + set(target_dir $) + else() + set(target_dir $) + endif() + set(dependencies_setreg ${target_dir}/Registry/cmake_dependencies.${specialization_name}.setreg) file(GENERATE OUTPUT ${dependencies_setreg} CONTENT ${gem_json}) set_property(TARGET ${target} APPEND PROPERTY INTERFACE_LY_TARGET_FILES "${dependencies_setreg}\nRegistry") From 7caab501cbcac663f7e2e1628c9a79042a1606b3 Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 24 May 2021 17:52:47 -0700 Subject: [PATCH 115/811] Add inputs and logic to handle spawn transforms --- .../SpawnNodeable.ScriptCanvasNodeable.xml | 9 ++- .../Libraries/Spawning/SpawnNodeable.cpp | 67 +++++++++++++++++-- .../Libraries/Spawning/SpawnNodeable.h | 4 ++ 3 files changed, 74 insertions(+), 6 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml index d930e16057..b2f48fae5f 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml @@ -11,8 +11,15 @@ Namespace="ScriptCanvas" Description="Spawn"> - + + + + + + + + /> diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index 5c72f60625..0e067b65bf 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -10,8 +10,11 @@ * */ +#pragma optimize("", off) #include +#include + namespace ScriptCanvas { namespace Nodeables @@ -23,19 +26,73 @@ namespace ScriptCanvas AZ::Data::AssetId cubeAssetId("{90552CB9-2F29-5A2E-976C-61BF7ADACB81}", 272062881); m_spawnableAsset = AZ::Data::AssetManager::Instance().GetAsset(cubeAssetId, AZ::Data::AssetLoadBehavior::PreLoad); AZ::Data::AssetManager::Instance().BlockUntilLoadComplete(m_spawnableAsset); - - m_spawnTicket = AzFramework::EntitySpawnTicket(m_spawnableAsset); } SpawnNodeable::SpawnNodeable(const SpawnNodeable& rhs) { m_spawnableAsset = rhs.m_spawnableAsset; - m_spawnTicket = AzFramework::EntitySpawnTicket(rhs.m_spawnableAsset); } - void SpawnNodeable::Spawn() + void SpawnNodeable::OnInitializeExecutionState() { - AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_spawnTicket); + m_spawnTicket = AzFramework::EntitySpawnTicket(m_spawnableAsset); + } + + void SpawnNodeable::OnDeactivate() + { + m_spawnTicket = AzFramework::EntitySpawnTicket(); + } + + //void SpawnNodeable::Translation(Data::Vector3Type translation) + //{ + // m_translation = translation; + //} + + //void SpawnNodeable::Rotation(Data::Vector3Type rotation) + //{ + // m_rotation = rotation; + //} + + //void SpawnNodeable::Scale(Data::Vector3Type scale) + //{ + // m_scale = scale; + //} + + void SpawnNodeable::RequestSpawn(Data::Vector3Type translation, Data::Vector3Type rotation, Data::NumberType scale) + { + auto preSpawnCB = [this, translation, rotation, scale]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, + AzFramework::SpawnableEntityContainerView view) + { + + AZ::Entity* rootEntity = *view.begin(); + + AzFramework::TransformComponent* entityTransform = + rootEntity->FindComponent(); + + if (entityTransform) + { + AZ::Vector3 rotationCopy = rotation; + AZ::Quaternion rotationQuat = AZ::Quaternion::CreateFromEulerAnglesDegrees(rotationCopy); + + entityTransform->SetWorldTM(AZ::Transform(translation, rotationQuat, AZ::Vector3(scale, scale, scale))); + } + }; + + auto spawnCompleteCB = [this]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, + AzFramework::SpawnableConstEntityContainerView view) + { + AZStd::vector spawnedEntities; + spawnedEntities.resize(view.size()); + + for (const AZ::Entity* entity : view) + { + spawnedEntities.emplace_back(entity->GetId()); + } + + CallOnSpawn(spawnedEntities); + }; + + AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_spawnTicket, preSpawnCB, spawnCompleteCB); } } } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h index 1eb53d53a2..4d73449d58 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h @@ -34,6 +34,10 @@ namespace ScriptCanvas SpawnNodeable(const SpawnNodeable& rhs); + void OnInitializeExecutionState() override; + + void OnDeactivate() override; + private: AZ::Data::Asset m_spawnableAsset; AzFramework::EntitySpawnTicket m_spawnTicket; From db0db5c1c0c95f73ec7847b86bd1e989b00533f2 Mon Sep 17 00:00:00 2001 From: pappeste Date: Mon, 24 May 2021 18:57:48 -0700 Subject: [PATCH 116/811] Proper dependencies to LmbrCentral/LmbrCentral.Editor, mixing those two can cause Editor modules to load non-Editor modules --- .../ComponentEntityEditorPlugin/CMakeLists.txt | 4 ++-- Gems/AutomatedLauncherTesting/Code/CMakeLists.txt | 2 +- Gems/EMotionFX/Code/CMakeLists.txt | 2 +- Gems/FastNoise/Code/CMakeLists.txt | 2 +- Gems/GradientSignal/Code/CMakeLists.txt | 4 ++-- Gems/ImGui/Code/CMakeLists.txt | 2 +- Gems/LandscapeCanvas/Code/CMakeLists.txt | 2 +- Gems/LyShine/Code/CMakeLists.txt | 12 +++++------- Gems/LyShineExamples/Code/CMakeLists.txt | 4 +++- Gems/Maestro/Code/CMakeLists.txt | 3 --- Gems/PhysX/Code/CMakeLists.txt | 4 ++-- Gems/StartingPointCamera/Code/CMakeLists.txt | 2 +- Gems/SurfaceData/Code/CMakeLists.txt | 2 +- Gems/Vegetation/Code/CMakeLists.txt | 2 +- 14 files changed, 22 insertions(+), 25 deletions(-) diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt index 275bb0ba9f..66c96eb4c6 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt @@ -35,7 +35,7 @@ ly_add_target( AZ::AzToolsFramework Legacy::CryCommon Legacy::EditorLib - Gem::LmbrCentral + Gem::LmbrCentral.Editor ) ly_add_dependencies(Editor ComponentEntityEditorPlugin) @@ -65,7 +65,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzToolsFrameworkTestCommon Legacy::CryCommon Legacy::EditorLib - Gem::LmbrCentral + Gem::LmbrCentral.Editor ) ly_add_googletest( NAME Legacy::ComponentEntityEditorPlugin.Tests diff --git a/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt b/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt index 551f76da02..57b6824060 100644 --- a/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt +++ b/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt @@ -23,7 +23,7 @@ ly_add_target( PUBLIC AZ::AzCore Legacy::CryCommon - Gem::LmbrCentral + Gem::LmbrCentral.Static ) ly_add_target( diff --git a/Gems/EMotionFX/Code/CMakeLists.txt b/Gems/EMotionFX/Code/CMakeLists.txt index b90902a948..8f0957a280 100644 --- a/Gems/EMotionFX/Code/CMakeLists.txt +++ b/Gems/EMotionFX/Code/CMakeLists.txt @@ -36,7 +36,7 @@ ly_add_target( AZ::AzCore AZ::AzFramework Legacy::CryCommon - Gem::LmbrCentral + Gem::LmbrCentral.Static PUBLIC AZ::AtomCore Gem::Atom_RPI.Public diff --git a/Gems/FastNoise/Code/CMakeLists.txt b/Gems/FastNoise/Code/CMakeLists.txt index a49126303a..0f7a92e8d9 100644 --- a/Gems/FastNoise/Code/CMakeLists.txt +++ b/Gems/FastNoise/Code/CMakeLists.txt @@ -23,7 +23,7 @@ ly_add_target( PUBLIC Legacy::CryCommon Gem::GradientSignal - Gem::LmbrCentral + Gem::LmbrCentral.Static ) ly_add_target( diff --git a/Gems/GradientSignal/Code/CMakeLists.txt b/Gems/GradientSignal/Code/CMakeLists.txt index 7b8c9813e6..f7f8571beb 100644 --- a/Gems/GradientSignal/Code/CMakeLists.txt +++ b/Gems/GradientSignal/Code/CMakeLists.txt @@ -22,7 +22,7 @@ ly_add_target( BUILD_DEPENDENCIES PUBLIC Legacy::CryCommon - Gem::LmbrCentral + Gem::LmbrCentral.Static Gem::SurfaceData Gem::ImageProcessingAtom.Headers ) @@ -67,7 +67,7 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) 3rdParty::Qt::Widgets Legacy::CryCommon AZ::AzToolsFramework - Gem::LmbrCentral + Gem::LmbrCentral.Editor Gem::SurfaceData AZ::AssetBuilderSDK Gem::GradientSignal.Static diff --git a/Gems/ImGui/Code/CMakeLists.txt b/Gems/ImGui/Code/CMakeLists.txt index 2f7d6c6ce7..0751c5825b 100644 --- a/Gems/ImGui/Code/CMakeLists.txt +++ b/Gems/ImGui/Code/CMakeLists.txt @@ -70,7 +70,7 @@ ly_add_target( BUILD_DEPENDENCIES PUBLIC Gem::ImGui.ImGuiLYUtils - Gem::LmbrCentral + Gem::LmbrCentral.Static ) ly_add_target( diff --git a/Gems/LandscapeCanvas/Code/CMakeLists.txt b/Gems/LandscapeCanvas/Code/CMakeLists.txt index e8e2fce689..497c83845f 100644 --- a/Gems/LandscapeCanvas/Code/CMakeLists.txt +++ b/Gems/LandscapeCanvas/Code/CMakeLists.txt @@ -35,7 +35,7 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::CryCommon Legacy::Editor.Headers Legacy::EditorCommon - Gem::LmbrCentral + Gem::LmbrCentral.Editor Gem::GraphCanvasWidgets Gem::GraphModel.Editor.Static Gem::GradientSignal.Editor diff --git a/Gems/LyShine/Code/CMakeLists.txt b/Gems/LyShine/Code/CMakeLists.txt index 732bd1cfd4..d9f011750e 100644 --- a/Gems/LyShine/Code/CMakeLists.txt +++ b/Gems/LyShine/Code/CMakeLists.txt @@ -26,13 +26,13 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE Legacy::CryCommon - Gem::LmbrCentral - Gem::TextureAtlas PUBLIC Gem::Atom_RPI.Public Gem::Atom_Utils.Static Gem::Atom_Bootstrap.Headers Gem::AtomFont + Gem::LmbrCentral.Static + Gem::TextureAtlas ) ly_add_target( @@ -49,8 +49,6 @@ ly_add_target( PRIVATE Gem::LyShine.Static Legacy::CryCommon - Gem::LmbrCentral - Gem::TextureAtlas RUNTIME_DEPENDENCIES Gem::LmbrCentral Gem::TextureAtlas @@ -85,7 +83,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::EditorCore Gem::LyShine.Static Legacy::CryCommon - Gem::LmbrCentral + Gem::LmbrCentral.Editor.Static Gem::TextureAtlas Gem::AtomToolsFramework.Static Gem::AtomToolsFramework.Editor @@ -117,7 +115,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::CryCommon AZ::AssetBuilderSDK Gem::LyShine.Editor.Static - Gem::LmbrCentral + Gem::LmbrCentral.Editor Gem::TextureAtlas RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor @@ -175,7 +173,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest Legacy::CryCommon AZ::AssetBuilderSDK - Gem::LmbrCentral + Gem::LmbrCentral.Editor Gem::TextureAtlas Gem::LyShine.Editor.Static ) diff --git a/Gems/LyShineExamples/Code/CMakeLists.txt b/Gems/LyShineExamples/Code/CMakeLists.txt index 372bfa948b..1b8393a806 100644 --- a/Gems/LyShineExamples/Code/CMakeLists.txt +++ b/Gems/LyShineExamples/Code/CMakeLists.txt @@ -22,7 +22,7 @@ ly_add_target( BUILD_DEPENDENCIES PUBLIC Legacy::CryCommon - Gem::LmbrCentral + Gem::LmbrCentral.Static Gem::LyShine.Static ) @@ -39,4 +39,6 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE Gem::LyShineExamples.Static + RUNTIME_DEPENDENCIES + Gem::LmbrCentral ) diff --git a/Gems/Maestro/Code/CMakeLists.txt b/Gems/Maestro/Code/CMakeLists.txt index fe58ba03a6..f21badab80 100644 --- a/Gems/Maestro/Code/CMakeLists.txt +++ b/Gems/Maestro/Code/CMakeLists.txt @@ -22,7 +22,6 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE Legacy::CryCommon - Gem::LmbrCentral ) ly_add_target( @@ -39,7 +38,6 @@ ly_add_target( PRIVATE Legacy::CryCommon Gem::Maestro.Static - Gem::LmbrCentral RUNTIME_DEPENDENCIES Gem::LmbrCentral ) @@ -69,7 +67,6 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AzToolsFramework AZ::AssetBuilderSDK Gem::Maestro.Static - Gem::LmbrCentral RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor ) diff --git a/Gems/PhysX/Code/CMakeLists.txt b/Gems/PhysX/Code/CMakeLists.txt index b4c7b580a6..4ebb32b977 100644 --- a/Gems/PhysX/Code/CMakeLists.txt +++ b/Gems/PhysX/Code/CMakeLists.txt @@ -46,7 +46,7 @@ ly_add_target( AZ::AzCore AZ::AzFramework Legacy::CryCommon - Gem::LmbrCentral + Gem::LmbrCentral.Static ) ly_add_target( @@ -107,7 +107,7 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) AZ::SceneCore AZ::SceneData Legacy::CryCommon - Gem::LmbrCentral + Gem::LmbrCentral.Editor.Static Gem::PhysX.NumericalMethods Gem::PhysX.Static Gem::AtomLyIntegration_CommonFeatures.Static diff --git a/Gems/StartingPointCamera/Code/CMakeLists.txt b/Gems/StartingPointCamera/Code/CMakeLists.txt index d6dd1a7038..b32e713d4a 100644 --- a/Gems/StartingPointCamera/Code/CMakeLists.txt +++ b/Gems/StartingPointCamera/Code/CMakeLists.txt @@ -23,7 +23,7 @@ ly_add_target( PRIVATE AZ::AzCore Gem::CameraFramework.Static - Gem::LmbrCentral + Gem::LmbrCentral.Static Legacy::CryCommon ) diff --git a/Gems/SurfaceData/Code/CMakeLists.txt b/Gems/SurfaceData/Code/CMakeLists.txt index de1aa51938..c45c7aa09b 100644 --- a/Gems/SurfaceData/Code/CMakeLists.txt +++ b/Gems/SurfaceData/Code/CMakeLists.txt @@ -25,7 +25,7 @@ ly_add_target( PUBLIC Gem::Atom_RPI.Public Gem::Atom_Feature_Common.Static - Gem::LmbrCentral + Gem::LmbrCentral.Static ) ly_add_target( diff --git a/Gems/Vegetation/Code/CMakeLists.txt b/Gems/Vegetation/Code/CMakeLists.txt index c4a003bb4a..2dfbd96d60 100644 --- a/Gems/Vegetation/Code/CMakeLists.txt +++ b/Gems/Vegetation/Code/CMakeLists.txt @@ -26,7 +26,7 @@ ly_add_target( BUILD_DEPENDENCIES PUBLIC Legacy::CryCommon - Gem::LmbrCentral + Gem::LmbrCentral.Static Gem::GradientSignal Gem::SurfaceData.Static Gem::AtomLyIntegration_CommonFeatures.Static From d3fb2dd68c2907779c8b8832fee8b058e3082873 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Mon, 24 May 2021 22:49:37 -0500 Subject: [PATCH 117/811] Removed the add_external_subdirectory and add_gem_cmake python scripts as well as their remove counterparts. Updated teh register.py script to be able to register subdirectories to the o3de_manifest.json Also added the ability to register external subdirectories to the project.json if the --external-subdirectory-project-path is supplied Added the ability to register external subdirectories to the engine.json if the --external-subdirector-engine-path is supplied --- scripts/o3de.py | 15 +- .../o3de/o3de/add_external_subdirectory.py | 168 --------- scripts/o3de/o3de/add_gem_cmake.py | 138 ------- scripts/o3de/o3de/add_gem_project.py | 5 +- scripts/o3de/o3de/manifest.py | 66 +++- scripts/o3de/o3de/register.py | 341 ++++++++---------- .../o3de/o3de/remove_external_subdirectory.py | 120 ------ scripts/o3de/o3de/remove_gem_cmake.py | 122 ------- scripts/o3de/o3de/remove_gem_project.py | 10 +- 9 files changed, 203 insertions(+), 782 deletions(-) delete mode 100644 scripts/o3de/o3de/add_external_subdirectory.py delete mode 100644 scripts/o3de/o3de/add_gem_cmake.py delete mode 100644 scripts/o3de/o3de/remove_external_subdirectory.py delete mode 100644 scripts/o3de/o3de/remove_gem_cmake.py diff --git a/scripts/o3de.py b/scripts/o3de.py index cc3a14a8c3..050d860790 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -40,8 +40,7 @@ def add_args(parser, subparsers) -> None: sys.path.remove(str(script_abs_dir.resolve())) from o3de import engine_template, global_project, register, print_registration, get_registration, download, \ - add_external_subdirectory, remove_external_subdirectory, add_gem_cmake, remove_gem_cmake, add_gem_project, \ - remove_gem_project, sha256 + add_gem_project, remove_gem_project, sha256 if script_abs_dir_removed: sys.path.insert(0, str(script_abs_dir)) @@ -65,18 +64,6 @@ def add_args(parser, subparsers) -> None: # download download.add_args(subparsers) - # add external subdirectories - add_external_subdirectory.add_args(subparsers) - - # remove external subdirectories - remove_external_subdirectory.add_args(subparsers) - - # add gems to cmake - add_gem_cmake.add_args(subparsers) - - # remove gems from cmake - remove_gem_cmake.add_args(subparsers) - # add a gem to a project add_gem_project.add_args(subparsers) diff --git a/scripts/o3de/o3de/add_external_subdirectory.py b/scripts/o3de/o3de/add_external_subdirectory.py deleted file mode 100644 index 29013d30c8..0000000000 --- a/scripts/o3de/o3de/add_external_subdirectory.py +++ /dev/null @@ -1,168 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# -""" -Contains command to add an external_subdirectory to a project's cmake scripts -""" - -import argparse -import logging -import pathlib -import sys - -from o3de import manifest - -logger = logging.getLogger() -logging.basicConfig() - -def add_external_subdirectory(external_subdir: str or pathlib.Path, - engine_path: str or pathlib.Path = None) -> int: - """ - add external subdirectory to a cmake - :param external_subdir: external subdirectory to add to cmake - :param engine_path: optional engine path, defaults to this engine - :return: 0 for success or non 0 failure code - """ - external_subdir = pathlib.Path(external_subdir).resolve() - if not external_subdir.is_dir(): - logger.error(f'Add External Subdirectory Failed: {external_subdir} does not exist.') - return 1 - - external_subdir_cmake = external_subdir / 'CMakeLists.txt' - if not external_subdir_cmake.is_file(): - logger.error(f'Add External Subdirectory Failed: {external_subdir} does not contain a CMakeLists.txt.') - return 1 - - json_data = manifest.load_o3de_manifest() - engine_object = manifest.find_engine_data(json_data, engine_path) - if not engine_object: - logger.error(f'Add External Subdirectory Failed: {engine_path} not registered.') - return 1 - - engine_object.setdefault('external_subdirectories', []) - while external_subdir.as_posix() in engine_object['external_subdirectories']: - engine_object['external_subdirectories'].remove(external_subdir.as_posix()) - - def parse_cmake_file(cmake: str or pathlib.Path, - files: set): - cmake_path = pathlib.Path(cmake).resolve() - cmake_file = cmake_path - if cmake_path.is_dir(): - files.add(cmake_path) - cmake_file = cmake_path / 'CMakeLists.txt' - elif cmake_path.is_file(): - cmake_path = cmake_path.parent - else: - return - - with cmake_file.open('r') as s: - lines = s.readlines() - for line in lines: - line = line.strip() - start = line.find('include(') - if start == 0: - end = line.find(')', start) - if end > start + len('include('): - try: - include_cmake_file = pathlib.Path(engine_path / line[start + len('include('): end]).resolve() - except FileNotFoundError as e: - pass - else: - parse_cmake_file(include_cmake_file, files) - else: - start = line.find('add_subdirectory(') - if start == 0: - end = line.find(')', start) - if end > start + len('add_subdirectory('): - try: - include_cmake_file = pathlib.Path( - cmake_path / line[start + len('add_subdirectory('): end]).resolve() - except FileNotFoundError as e: - pass - else: - parse_cmake_file(include_cmake_file, files) - - cmake_files = set() - parse_cmake_file(engine_path, cmake_files) - for external in engine_object["external_subdirectories"]: - parse_cmake_file(external, cmake_files) - - if external_subdir in cmake_files: - manifest.save_o3de_manifest(json_data) - logger.warning(f'External subdirectory {external_subdir.as_posix()} already included by add_subdirectory().') - return 1 - - engine_object['external_subdirectories'].insert(0, external_subdir.as_posix()) - engine_object['external_subdirectories'] = sorted(engine_object['external_subdirectories']) - - manifest.save_o3de_manifest(json_data) - - return 0 - - -def _run_add_external_subdirectory(args: argparse) -> int: - if args.override_home_folder: - manifest.override_home_folder = args.override_home_folder - - return add_external_subdirectory(args.external_subdirectory) - - -def add_parser_args(parser): - """ - add_parser_args is called to add arguments to each command such that it can be - invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python add-external-subdirectory.py "/home/foo/external-subdir" - :param parser: the caller passes an argparse parser like instance to this method - """ - parser.add_argument('external_subdirectory', metavar='external_subdirectory', type=str, - help='add an external subdirectory to cmake') - - parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - parser.set_defaults(func=_run_add_external_subdirectory) - - -def add_args(subparsers) -> None: - """ - add_args is called to add subparsers arguments to each command such that it can be - a central python file such as o3de.py. - It can be run from the o3de.py script as follows - call add_args and execute: python o3de.py add_external_subdirectory "/home/foo/external-subdir" - :param subparsers: the caller instantiates subparsers and passes it in here - """ - add_external_subdirectory_subparser = subparsers.add_parser('add-external-subdirectory') - add_parser_args(add_external_subdirectory_subparser) - - -def main(): - """ - Runs add_external_subdirectory.py script as standalone script - """ - # parse the command line args - the_parser = argparse.ArgumentParser() - - # add subparsers - - # add args to the parser - add_parser_args(the_parser) - - # parse args - the_args = the_parser.parse_args() - - # run - ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 - - # return - sys.exit(ret) - - -if __name__ == "__main__": - main() diff --git a/scripts/o3de/o3de/add_gem_cmake.py b/scripts/o3de/o3de/add_gem_cmake.py deleted file mode 100644 index 523fb8dce8..0000000000 --- a/scripts/o3de/o3de/add_gem_cmake.py +++ /dev/null @@ -1,138 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# -""" -Contains command to add a gem to a project's cmake scripts -""" - -import argparse -import logging -import pathlib -import sys - -from o3de import add_external_subdirectory, manifest, validation - -logger = logging.getLogger() -logging.basicConfig() - -def add_gem_to_cmake(gem_name: str = None, - gem_path: str or pathlib.Path = None, - engine_name: str = None, - engine_path: str or pathlib.Path = None) -> int: - """ - add a gem to a cmake as an external subdirectory for an engine - :param gem_name: name of the gem to add to cmake - :param gem_path: the path of the gem to add to cmake - :param engine_name: name of the engine to add to cmake - :param engine_path: the path of the engine to add external subdirectory to, default to this engine - :return: 0 for success or non 0 failure code - """ - if not gem_name and not gem_path: - logger.error('Must specify either a Gem name or Gem Path.') - return 1 - - if gem_name and not gem_path: - gem_path = manifest.get_registered(gem_name=gem_name) - - if not gem_path: - logger.error(f'Gem Path {gem_path} has not been registered.') - return 1 - - gem_path = pathlib.Path(gem_path).resolve() - gem_json = gem_path / 'gem.json' - if not gem_json.is_file(): - logger.error(f'Gem json {gem_json} is not present.') - return 1 - if not validation.valid_o3de_gem_json(gem_json): - logger.error(f'Gem json {gem_json} is not valid.') - return 1 - - if not engine_name and not engine_path: - engine_path = manifest.get_this_engine_path() - - if engine_name and not engine_path: - engine_path = manifest.get_registered(engine_name=engine_name) - - if not engine_path: - logger.error(f'Engine Path {engine_path} has not been registered.') - return 1 - - engine_json = engine_path / 'engine.json' - if not engine_json.is_file(): - logger.error(f'Engine json {engine_json} is not present.') - return 1 - if not validation.valid_o3de_engine_json(engine_json): - logger.error(f'Engine json {engine_json} is not valid.') - return 1 - - return add_external_subdirectory.add_external_subdirectory(external_subdir=gem_path, engine_path=engine_path) - -def _run_add_gem_to_cmake(args: argparse) -> int: - if args.override_home_folder: - manifest.override_home_folder = args.override_home_folder - - return add_gem_to_cmake(gem_name=args.gem_name, gem_path=args.gem_path) - - -def add_parser_args(parser): - """ - add_parser_args is called to add arguments to each command such that it can be - invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python add_gem_cmake.py --gem-path "/path/to/gem" - :param parser: the caller passes an argparse parser like instance to this method - """ - group = parser.add_mutually_exclusive_group(required=True) - group.add_argument('-gp', '--gem-path', type=str, required=False, - help='The path to the gem.') - group.add_argument('-gn', '--gem-name', type=str, required=False, - help='The name of the gem.') - - parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - parser.set_defaults(func=_run_add_gem_to_cmake) - - -def add_args(subparsers) -> None: - """ - add_args is called to add subparsers arguments to each command such that it can be - a central python file such as o3de.py. - It can be run from the o3de.py script as follows - call add_args and execute: python o3de.py add-gem-to-cmake --gem-path "/path/to/gem" - :param subparsers: the caller instantiates subparsers and passes it in here - """ - add_gem_cmake_subparser = subparsers.add_parser('add-gem-to-cmake') - add_parser_args(add_gem_cmake_subparser) - - -def main(): - """ - Runs add_gem_cmake.py script as standalone script - """ - # parse the command line args - the_parser = argparse.ArgumentParser() - - # add subparsers - - # add args to the parser - add_parser_args(the_parser) - - # parse args - the_args = the_parser.parse_args() - - # run - ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 - - # return - sys.exit(ret) - - -if __name__ == "__main__": - main() diff --git a/scripts/o3de/o3de/add_gem_project.py b/scripts/o3de/o3de/add_gem_project.py index 78dffc4477..8eb1468485 100644 --- a/scripts/o3de/o3de/add_gem_project.py +++ b/scripts/o3de/o3de/add_gem_project.py @@ -19,7 +19,7 @@ import os import pathlib import sys -from o3de import add_gem_cmake, cmake, manifest, validation +from o3de import cmake, manifest, validation logger = logging.getLogger() logging.basicConfig() @@ -239,9 +239,6 @@ def add_gem_to_project(gem_name: str = None, # add the dependency ret_val = add_gem_dependency(project_server_dependencies_file, gem_target) - if not ret_val and add_to_cmake: - ret_val = add_gem_cmake.add_gem_to_cmake(gem_path=gem_path, engine_path=engine_path) - return ret_val diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index 6c14c2533f..bc27d9116c 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -131,7 +131,7 @@ def get_o3de_manifest() -> pathlib.Path: json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) json_data.update({'projects': []}) - json_data.update({'gems': []}) + json_data.update({'external_subdirectories': []}) json_data.update({'templates': []}) json_data.update({'restricted': []}) json_data.update({'repos': []}) @@ -172,8 +172,15 @@ def get_o3de_manifest() -> pathlib.Path: return manifest_path -def load_o3de_manifest() -> dict: - with get_o3de_manifest().open('r') as f: +def load_o3de_manifest(manifest_path: pathlib.Path = None) -> dict: + """ + Loads supplied manifest file or ~/.o3de/o3de_manifest.json if None + + :param manifest_path: optional path to manifest file to load + """ + if not manifest_path: + manifest_path = get_o3de_manifest() + with manifest_path.open('r') as f: try: json_data = json.load(f) except json.JSONDecodeError as e: @@ -183,8 +190,16 @@ def load_o3de_manifest() -> dict: return json_data -def save_o3de_manifest(json_data: dict) -> None: - with get_o3de_manifest().open('w') as s: +def save_o3de_manifest(json_data: dict, manifest_path: pathlib.Path = None) -> None: + """ + Save the json dictionary to the supplied manifest file or ~/.o3de/o3de_manifest.json if None + + :param json_data: dictionary to save in json format at the file path + :param manifest_path: optional path to manifest file to save + """ + if not manifest_path: + manifest_path = get_o3de_manifest() + with manifest_path.open('w') as s: try: s.write(json.dumps(json_data, indent=4)) except OSError as e: @@ -198,36 +213,44 @@ def get_this_engine() -> dict: return engine_data -def get_engines() -> dict: +def get_engines() -> list: json_data = load_o3de_manifest() return json_data['engines'] -def get_projects() -> dict: +def get_projects() -> list: json_data = load_o3de_manifest() return json_data['projects'] -def get_gems() -> dict: - json_data = load_o3de_manifest() - return json_data['gems'] +def get_gems() -> list: + def is_gem_subdirectory(subdir): + return (pathlib.Path(subdir) / 'gem.json').exists() + + external_subdirs = get_external_subdirectories() + return list(filter(is_gem_subdirectory, external_subdirs)) if external_subdirs else [] -def get_templates() -> dict: +def get_templates() -> list: json_data = load_o3de_manifest() return json_data['templates'] -def get_restricted() -> dict: +def get_restricted() -> list: json_data = load_o3de_manifest() return json_data['restricted'] -def get_repos() -> dict: +def get_external_subdirectories() -> list: + json_data = load_o3de_manifest() + return json_data['external_subdirectories'] + + +def get_repos() -> list: json_data = load_o3de_manifest() return json_data['repos'] - +# engine.json queries def get_engine_projects() -> list: engine_path = get_this_engine_path() engine_object = get_engine_json_data(engine_path=engine_path) @@ -264,6 +287,21 @@ def get_engine_external_subdirectories() -> list: engine_object['external_subdirectories'])) if 'external_subdirectories' in engine_object else [] +# project.json queries +def get_project_gems(project_path: pathlib.Path) -> list: + def is_gem_subdirectory(subdir): + return (pathlib.Path(subdir) / 'gem.json').exists() + + external_subdirs = get_project_external_subdirectories() + return list(filter(is_gem_subdirectory, external_subdirs)) if external_subdirs else [] + + +def get_project_external_subdirectories(project_path: pathlib.Path) -> list: + project_object = get_project_json_data(project_path=project_path) + return list(map(lambda rel_path: (pathlib.Path(project_path) / rel_path).as_posix(), + project_object['external_subdirectories'])) if 'external_subdirectories' in project_object else [] + + def get_all_projects() -> list: engine_projects = get_engine_projects() projects_data = get_projects() diff --git a/scripts/o3de/o3de/register.py b/scripts/o3de/o3de/register.py index c44af03b30..1b30448db9 100644 --- a/scripts/o3de/o3de/register.py +++ b/scripts/o3de/o3de/register.py @@ -1,3 +1,4 @@ + # # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. @@ -23,7 +24,7 @@ import sys import urllib.parse import urllib.request -from o3de import add_gem_cmake, get_registration, manifest, remove_external_subdirectory, repo, utils, validation +from o3de import get_registration, manifest, repo, utils, validation logger = logging.getLogger() logging.basicConfig() @@ -183,7 +184,8 @@ def register_all_projects_in_folder(projects_path: str or pathlib.Path, def register_all_gems_in_folder(gems_path: str or pathlib.Path, remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: + engine_path: pathlib.Path = None, + project_path: pathlib.Path = None) -> int: return register_all_o3de_objects_of_type_in_folder(gems_path, 'gem', remove, False, engine_path=engine_path) @@ -283,105 +285,121 @@ def register_engine_path(json_data: dict, return add_engine_name_to_path(json_data, engine_path, force) +def register_o3de_object_path(json_data: dict, + o3de_object_path: str or pathlib.Path, + o3de_object_key: str, + o3de_json_filename: str, + validation_func: callable, + remove: bool = False, + engine_path: pathlib.Path = None, + project_path: pathlib.Path = None) -> int: + # save_path variable is used to save the changes to the store the path to the file to save + # if the registration is for the project or engine + save_path = None + + if not o3de_object_path: + logger.error(f'o3de object path cannot be empty.') + return 1 + + o3de_object_path = pathlib.Path(o3de_object_path).resolve() + + if engine_path and project_path: + logger.error(f'Both a project path: {project_path} and engine path: {engine_path} has been supplied.' + 'A subdirectory can only be registered to either the engine path or project in one command') + + manifest_data = None + if engine_path: + manifest_data = manifest.get_engine_json_data(json_data, 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(json_data, project_path) + if not manifest_data: + logger.error(f'Cannot load project.json data at path {project_path}') + return 1 + + save_path = project_path / 'project.json' + else: + manifest_data = json_data + + paths_to_remove = [o3de_object_path] + if save_path: + try: + paths_to_remove.append(o3de_object_path.relative_to(save_path.parent)) + except ValueError: + pass # It is OK relative path cannot be formed + manifest_data[o3de_object_key] = list(filter(lambda p: pathlib.Path(p) not in paths_to_remove, + manifest_data.setdefault(o3de_object_key, []))) + + if remove: + if save_path: + manifest.save_o3de_manifest(manifest_data, save_path) + return 0 + + if not o3de_object_path.is_dir(): + logger.error(f'o3de object path {o3de_object_path} does not exist.') + return 1 + + manifest_json_path = o3de_object_path / o3de_json_filename + if validation_func and not validation_func(manifest_json_path): + logger.error(f'o3de json {manifest_json_path} is not valid.') + return 1 + + # if there is a save path make it relative the directory containing o3de object json file + if save_path: + try: + o3de_object_path = o3de_object_path.relative_to(save_path.parent) + except ValueError: + pass # It is OK relative path cannot be formed + manifest_data[o3de_object_key].insert(0, o3de_object_path.as_posix()) + if save_path: + manifest.save_o3de_manifest(manifest_data, save_path) + + return 0 + + +def register_external_subdirectory(json_data: dict, + external_subdir_path: str or pathlib.Path, + remove: bool = False, + engine_path: pathlib.Path = None, + project_path: pathlib.Path = None) -> int: + """ + :return An integer return code indicating whether registration or removal of the external subdirectory + completed successfully + """ + return register_o3de_object_path(json_data, external_subdir_path, 'external_subdirectories', '', None, remove, + engine_path, project_path) + + def register_gem_path(json_data: dict, gem_path: str or pathlib.Path, remove: bool = False, - engine_path: str or pathlib.Path = None) -> int: - if not gem_path: - logger.error(f'Gem path cannot be empty.') - return 1 - gem_path = pathlib.Path(gem_path).resolve() - - if engine_path: - engine_data = manifest.find_engine_data(json_data, engine_path) - if not engine_data: - logger.error(f'Engine path {engine_path} is not registered.') - return 1 - - engine_data['gems'] = list(filter(lambda p: gem_path != pathlib.Path(p), engine_data['gems'])) - - if remove: - logger.warn(f'Removing Gem path {gem_path}.') - return 0 - else: - json_data['gems'] = list(filter(lambda p: gem_path != pathlib.Path(p), json_data['gems'])) - - if remove: - logger.warn(f'Removing Gem path {gem_path}.') - return 0 - - if not gem_path.is_dir(): - logger.error(f'Gem path {gem_path} does not exist.') - return 1 - - gem_json = gem_path / 'gem.json' - if not validation.valid_o3de_gem_json(gem_json): - logger.error(f'Gem json {gem_json} is not valid.') - return 1 - - if engine_path: - engine_data['gems'].insert(0, gem_path.as_posix()) - else: - json_data['gems'].insert(0, gem_path.as_posix()) - - return 0 + engine_path: pathlib.Path = None, + project_path: pathlib.Path = None) -> int: + return register_o3de_object_path(json_data, gem_path, 'external_subdirectories', 'gem.json', + validation.valid_o3de_gem_json, remove, engine_path, project_path) def register_project_path(json_data: dict, project_path: str or pathlib.Path, remove: bool = False, engine_path: str or pathlib.Path = None) -> int: - if not project_path: - logger.error(f'Project path cannot be empty.') - return 1 - project_path = pathlib.Path(project_path).resolve() + result = register_o3de_object_path(json_data, project_path, 'projects', 'project.json', + validation.valid_o3de_project_json, remove, engine_path, None) - if engine_path: - engine_data = manifest.find_engine_data(json_data, engine_path) - if not engine_data: - logger.error(f'Engine path {engine_path} is not registered.') - return 1 - - engine_data['projects'] = list(filter(lambda p: project_path != pathlib.Path(p), engine_data['projects'])) - - if remove: - logger.warn(f'Engine {engine_path} removing Project path {project_path}.') - return 0 - else: - json_data['projects'] = list(filter(lambda p: project_path != pathlib.Path(p), json_data['projects'])) - - if remove: - logger.warn(f'Removing Project path {project_path}.') - return 0 - - if not project_path.is_dir(): - logger.error(f'Project path {project_path} does not exist.') - return 1 - - project_json = project_path / 'project.json' - if not validation.valid_o3de_project_json(project_json): - logger.error(f'Project json {project_json} is not valid.') - return 1 - - if engine_path: - engine_data['projects'].insert(0, project_path.as_posix()) - else: - json_data['projects'].insert(0, project_path.as_posix()) + if result != 0: + return result # registering a project has the additional step of setting the project.json 'engine' field - this_engine_json = manifest.get_this_engine_path() / 'engine.json' - with this_engine_json.open('r') as f: - try: - this_engine_json = json.load(f) - except json.JSONDecodeError as e: - logger.error(f'Engine json failed to load: {str(e)}') - return 1 - with project_json.open('r') as f: - try: - project_json_data = json.load(f) - except json.JSONDecodeError as e: - logger.error(f'Project json failed to load: {str(e)}') - return 1 + this_engine_json = manifest.get_engine_json_data(engine_path=manifest.get_this_engine_path()) + if not this_engine_json: + return 1 + project_json_data = manifest.get_project_json_data(project_path=project_path) + if not project_json_data: + return 1 update_project_json = False try: @@ -399,6 +417,7 @@ def register_project_path(json_data: dict, logger.error(f'Project json failed to save: {str(e)}') return 1 + return 0 @@ -406,88 +425,16 @@ def register_template_path(json_data: dict, template_path: str or pathlib.Path, remove: bool = False, engine_path: str or pathlib.Path = None) -> int: - if not template_path: - logger.error(f'Template path cannot be empty.') - return 1 - template_path = pathlib.Path(template_path).resolve() - - if engine_path: - engine_data = manifest.find_engine_data(json_data, engine_path) - if not engine_data: - logger.error(f'Engine path {engine_path} is not registered.') - return 1 - - engine_data['templates'] = list(filter(lambda p: template_path != pathlib.Path(p), engine_data['templates'])) - - if remove: - logger.warn(f'Engine {engine_path} removing Template path {template_path}.') - return 0 - else: - json_data['templates'] = list(filter(lambda p: template_path != pathlib.Path(p), json_data['templates'])) - - if remove: - logger.warn(f'Removing Template path {template_path}.') - return 0 - - if not template_path.is_dir(): - logger.error(f'Template path {template_path} does not exist.') - return 1 - - template_json = template_path / 'template.json' - if not validation.valid_o3de_template_json(template_json): - logger.error(f'Template json {template_json} is not valid.') - return 1 - - if engine_path: - engine_data['templates'].insert(0, template_path.as_posix()) - else: - json_data['templates'].insert(0, template_path.as_posix()) - - return 0 + return register_o3de_object_path(json_data, template_path, 'templates', 'template.json', + validation.valid_o3de_template_json, remove, engine_path, None) def register_restricted_path(json_data: dict, restricted_path: str or pathlib.Path, remove: bool = False, engine_path: str or pathlib.Path = None) -> int: - if not restricted_path: - logger.error(f'Restricted path cannot be empty.') - return 1 - restricted_path = pathlib.Path(restricted_path).resolve() - - if engine_path: - engine_data = manifest.find_engine_data(json_data, engine_path) - if not engine_data: - logger.error(f'Engine path {engine_path} is not registered.') - return 1 - - engine_data['restricted'] = list(filter(lambda p: restricted_path != pathlib.Path(p), engine_data['restricted'])) - - if remove: - logger.warn(f'Engine {engine_path} removing Restricted path {restricted_path}.') - return 0 - else: - json_data['restricted'] = list(filter(lambda p: restricted_path != pathlib.Path(p), json_data['restricted'])) - - if remove: - logger.warn(f'Removing Restricted path {restricted_path}.') - return 0 - - if not restricted_path.is_dir(): - logger.error(f'Restricted path {restricted_path} does not exist.') - return 1 - - restricted_json = restricted_path / 'restricted.json' - if not validation.valid_o3de_restricted_json(restricted_json): - logger.error(f'Restricted json {restricted_json} is not valid.') - return 1 - - if engine_path: - engine_data['restricted'].insert(0, restricted_path.as_posix()) - else: - json_data['restricted'].insert(0, restricted_path.as_posix()) - - return 0 + return register_o3de_object_path(json_data, restricted_path, 'restricted', 'restricted.json', + validation.valid_o3de_restricted_json, remove, engine_path, None) def register_repo(json_data: dict, @@ -581,6 +528,7 @@ def register_default_restricted_folder(json_data: dict, def register(engine_path: str or pathlib.Path = None, project_path: str or pathlib.Path = None, gem_path: str or pathlib.Path = None, + external_subdir_path: str or pathlib.Path = None, template_path: str or pathlib.Path = None, restricted_path: str or pathlib.Path = None, repo_uri: str or pathlib.Path = None, @@ -589,15 +537,18 @@ def register(engine_path: str or pathlib.Path = None, default_gems_folder: str or pathlib.Path = None, default_templates_folder: str or pathlib.Path = None, default_restricted_folder: str or pathlib.Path = None, + external_subdir_engine_path: pathlib.Path = None, + external_subdir_project_path: pathlib.Path = None, remove: bool = False, force: bool = False ) -> int: """ - Adds/Updates entries to the .o3de/o3de_manifest.json + Adds/Updates entries to the ~/.o3de/o3de_manifest.json :param engine_path: if engine folder is supplied the path will be added to the engine if it can, if not global :param project_path: project folder :param gem_path: gem folder + :param external_subdir_path: external subdirectory :param template_path: template folder :param restricted_path: restricted folder :param repo_uri: repo uri @@ -606,6 +557,10 @@ def register(engine_path: str or pathlib.Path = None, :param default_gems_folder: default gems folder :param default_templates_folder: default templates folder :param default_restricted_folder: default restricted code folder + :param external_subdir_engine_path: Path to the engine to use when registering an external subdirectory. + The registration occurs in the engine.json file in this case + :param external_subdir_engine_path: Path to the project to use when registering an external subdirectory. + The registrations occurs in the project.json in this case :param remove: add/remove the entries :param force: force update of the engine_path for specified "engine_name" from the engine.json file @@ -627,7 +582,14 @@ def register(engine_path: str or pathlib.Path = None, if not gem_path: logger.error(f'Gem path cannot be empty.') return 1 - result = register_gem_path(json_data, gem_path, remove, engine_path) + result = register_gem_path(json_data, gem_path, remove, + external_subdir_engine_path, external_subdir_project_path) + elif isinstance(external_subdir_path, str) or isinstance(external_subdir_path, pathlib.PurePath): + if not external_subdir_path: + logger.error(f'External Subdirectory path is None.') + return 1 + result = register_external_subdirectory(json_data, external_subdir_path, remove, + external_subdir_engine_path, external_subdir_project_path) elif isinstance(template_path, str) or isinstance(template_path, pathlib.PurePath): if not template_path: @@ -685,32 +647,6 @@ def remove_invalid_o3de_objects() -> None: if not validation.valid_o3de_engine_json(pathlib.Path(engine_path).resolve() / 'engine.json'): logger.warn(f"Engine path {engine_path} is invalid.") register(engine_path=engine_path, remove=True) - else: - for project in engine_object['projects']: - if not validation.valid_o3de_project_json(pathlib.Path(project).resolve() / 'project.json'): - logger.warn(f"Project path {project} is invalid.") - register(engine_path=engine_path, project_path=project, remove=True) - - for gem_path in engine_object['gems']: - if not validation.valid_o3de_gem_json(pathlib.Path(gem_path).resolve() / 'gem.json'): - logger.warn(f"Gem path {gem_path} is invalid.") - register(engine_path=engine_path, gem_path=gem_path, remove=True) - - for template_path in engine_object['templates']: - if not validation.valid_o3de_template_json(pathlib.Path(template_path).resolve() / 'template.json'): - logger.warn(f"Template path {template_path} is invalid.") - register(engine_path=engine_path, template_path=template_path, remove=True) - - for restricted in engine_object['restricted']: - if not validation.valid_o3de_restricted_json(pathlib.Path(restricted).resolve() / 'restricted.json'): - logger.warn(f"Restricted path {restricted} is invalid.") - register(engine_path=engine_path, restricted_path=restricted, remove=True) - - for external in engine_object['external_subdirectories']: - external = pathlib.Path(external).resolve() - if not external.is_dir(): - logger.warn(f"External subdirectory {external} is invalid.") - remove_external_subdirectory.remove_external_subdirectory(external) for project in json_data['projects']: if not validation.valid_o3de_project_json(pathlib.Path(project).resolve() / 'project.json'): @@ -722,6 +658,12 @@ def remove_invalid_o3de_objects() -> None: logger.warn(f"Gem path {gem} is invalid.") register(gem_path=gem, remove=True) + for external in json_data['external_subdirectories']: + external = pathlib.Path(external).resolve() + if not external.is_dir(): + logger.warn(f"External subdirectory {external} is invalid.") + register(engine_path=engine_path, external_subdir_path=external, remove=True) + for template in json_data['templates']: if not validation.valid_o3de_template_json(pathlib.Path(template).resolve() / 'template.json'): logger.warn(f"Template path {template} is invalid.") @@ -804,6 +746,7 @@ def _run_register(args: argparse) -> int: return register(engine_path=args.engine_path, project_path=args.project_path, gem_path=args.gem_path, + external_subdir_path=args.external_subdirectory, template_path=args.template_path, restricted_path=args.restricted_path, repo_uri=args.repo_uri, @@ -812,6 +755,8 @@ def _run_register(args: argparse) -> int: default_gems_folder=args.default_gems_folder, default_templates_folder=args.default_templates_folder, default_restricted_folder=args.default_restricted_folder, + external_subdir_engine_path=args.external_subdirectory_engine_path, + external_subdir_project_path=args.external_subdirectory_project_path, remove=args.remove, force=args.force) @@ -833,6 +778,8 @@ def add_parser_args(parser): help='Project path to register/remove.') group.add_argument('-gp', '--gem-path', type=str, required=False, help='Gem path to register/remove.') + group.add_argument('-es', '--external-subdirectory', type=str, required=False, + help='External subdirectory path to register/remove.') group.add_argument('-tp', '--template-path', type=str, required=False, help='Template path to register/remove.') group.add_argument('-rp', '--restricted-path', type=str, required=False, @@ -872,6 +819,14 @@ def add_parser_args(parser): help='Remove entry.') parser.add_argument('-f', '--force', action='store_true', default=False, help='For the update of the registration field being modified.') + + external_subdir_group = parser.add_argument_group(title='external-subdirectory', + description='path arguments to use with the --external-subdirectory option') + external_subdir_path_group = external_subdir_group.add_mutually_exclusive_group() + external_subdir_path_group.add_argument('-esep', '--external-subdirectory-engine-path', type=pathlib.Path, + help='If supplied, registers the external subdirectory with the engine.json at' \ + ' the engine-path location') + external_subdir_path_group.add_argument('-espp', '--external-subdirectory-project-path', type=pathlib.Path) parser.set_defaults(func=_run_register) diff --git a/scripts/o3de/o3de/remove_external_subdirectory.py b/scripts/o3de/o3de/remove_external_subdirectory.py deleted file mode 100644 index b433e9c398..0000000000 --- a/scripts/o3de/o3de/remove_external_subdirectory.py +++ /dev/null @@ -1,120 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# -""" -Implemens functinality to remove external_subdirectories from the o3de_manifests.json -""" - -import argparse -import logging -import pathlib -import sys - -from o3de import manifest - -logger = logging.getLogger() -logging.basicConfig() - -def remove_external_subdirectory(external_subdir: str or pathlib.Path, - engine_path: str or pathlib.Path = None) -> int: - """ - remove external subdirectory from cmake - :param external_subdir: external subdirectory to add to cmake - :param engine_path: optional engine path, defaults to this engine - :return: 0 for success or non 0 failure code - """ - json_data = manifest.load_o3de_manifest() - engine_object = manifest.find_engine_data(json_data, engine_path) - if not engine_object or not 'external_subdirectories' in engine_object: - logger.error(f'Remove External Subdirectory Failed: {engine_path} not registered.') - return 1 - - external_subdir = pathlib.Path(external_subdir).resolve() - while external_subdir.as_posix() in engine_object['external_subdirectories']: - engine_object['external_subdirectories'].remove(external_subdir.as_posix()) - - manifest.save_o3de_manifest(json_data) - - return 0 - - -def _run_remove_external_subdirectory(args: argparse) -> int: - if args.override_home_folder: - manifest.override_home_folder = args.override_home_folder - - return remove_external_subdirectory(args.external_subdirectory) - - -def add_args(parser, subparsers) -> None: - """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be - invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" - OR - o3de.py can downloadable commands by importing engine_template, - call add_args and execute: python o3de.py register --gem-path "C:/TestGem" - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here - """ - - -def add_parser_args(parser): - """ - add_parser_args is called to add arguments to each command such that it can be - invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python remove_external_subdirectory.py "D:/subdir" - :param parser: the caller passes an argparse parser like instance to this method - """ - parser.add_argument('external_subdirectory', metavar='external_subdirectory', - type=str, - help='remove external subdirectory from cmake') - - parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - parser.set_defaults(func=_run_remove_external_subdirectory) - - -def add_args(subparsers) -> None: - """ - add_args is called to add subparsers arguments to each command such that it can be - a central python file such as o3de.py. - It can be run from the o3de.py script as follows - call add_args and execute: python o3de.py remove-external-subdirectory "D:/subdir" - :param subparsers: the caller instantiates subparsers and passes it in here - """ - remove_external_subdirectory_subparser = subparsers.add_parser('remove-external-subdirectory') - add_parser_args(remove_external_subdirectory_subparser) - - -def main(): - """ - Runs remove_external_subdirectory.py script as standalone script - """ - # parse the command line args - the_parser = argparse.ArgumentParser() - - # add subparsers - - # add args to the parser - add_parser_args(the_parser) - - # parse args - the_args = the_parser.parse_args() - - # run - ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 - - # return - sys.exit(ret) - - -if __name__ == "__main__": - main() diff --git a/scripts/o3de/o3de/remove_gem_cmake.py b/scripts/o3de/o3de/remove_gem_cmake.py deleted file mode 100644 index 3d988a579a..0000000000 --- a/scripts/o3de/o3de/remove_gem_cmake.py +++ /dev/null @@ -1,122 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# -""" -Contains methods for removing a gem from a project's cmake scripts -""" - -import argparse -import logging -import pathlib -import sys - -from o3de import manifest, remove_external_subdirectory - -logger = logging.getLogger() -logging.basicConfig() - -def remove_gem_from_cmake(gem_name: str = None, - gem_path: str or pathlib.Path = None, - engine_name: str = None, - engine_path: str or pathlib.Path = None) -> int: - """ - remove a gem to cmake as an external subdirectory - :param gem_name: name of the gem to remove from cmake - :param gem_path: the path of the gem to add to cmake - :param engine_name: optional name of the engine to remove from cmake - :param engine_path: the path of the engine to remove external subdirectory from, defaults to this engine - :return: 0 for success or non 0 failure code - """ - if not gem_name and not gem_path: - logger.error('Must specify either a Gem name or Gem Path.') - return 1 - - if gem_name and not gem_path: - gem_path = manifest.get_registered(gem_name=gem_name) - - if not gem_path: - logger.error(f'Gem Path {gem_path} has not been registered.') - return 1 - - if not engine_name and not engine_path: - engine_path = manifest.get_this_engine_path() - - if engine_name and not engine_path: - engine_path = manifest.get_registered(engine_name=engine_name) - - if not engine_path: - logger.error(f'Engine Path {engine_path} is not registered.') - return 1 - - return remove_external_subdirectory.remove_external_subdirectory(external_subdir=gem_path, engine_path=engine_path) - - -def _run_remove_gem_from_cmake(args: argparse) -> int: - if args.override_home_folder: - manifest.override_home_folder = args.override_home_folder - - return remove_gem_from_cmake(args.gem_name, args.gem_path) - - -def add_parser_args(parser): - """ - add_parser_args is called to add arguments to each command such that it can be - invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python remove_gem_cmake.py --gem-name Atom - :param parser: the caller passes an argparse parser like instance to this method - """ - group = parser.add_mutually_exclusive_group(required=True) - group.add_argument('-gp', '--gem-path', type=str, required=False, - help='The path to the gem.') - group.add_argument('-gn', '--gem-name', type=str, required=False, - help='The name of the gem.') - - parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - parser.set_defaults(func=_run_remove_gem_from_cmake) - - -def add_args(subparsers) -> None: - """ - add_args is called to add subparsers arguments to each command such that it can be - a central python file such as o3de.py. - It can be run from the o3de.py script as follows - call add_args and execute: python o3de.py remove-gem-from-cmake --gem-name Atom - :param subparsers: the caller instantiates subparsers and passes it in here - """ - remove_gem_from_cmake_subparser = subparsers.add_parser('remove-gem-from-cmake') - add_parser_args(remove_gem_from_cmake_subparser) - - -def main(): - """ - Runs remove_gem_cmake.py script as standalone script - """ - # parse the command line args - the_parser = argparse.ArgumentParser() - - # add subparsers - - # add args to the parser - add_parser_args(the_parser) - - # parse args - the_args = the_parser.parse_args() - - # run - ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 - - # return - sys.exit(ret) - - -if __name__ == "__main__": - main() diff --git a/scripts/o3de/o3de/remove_gem_project.py b/scripts/o3de/o3de/remove_gem_project.py index 671427db14..463cc69961 100644 --- a/scripts/o3de/o3de/remove_gem_project.py +++ b/scripts/o3de/o3de/remove_gem_project.py @@ -18,7 +18,7 @@ import os import pathlib import sys -from o3de import cmake, remove_gem_cmake +from o3de import cmake logger = logging.getLogger() logging.basicConfig() @@ -196,11 +196,6 @@ def remove_gem_from_project(gem_name: str = None, if error_code: ret_val = error_code - if remove_from_cmake: - error_code = remove_gem_cmake.remove_gem_from_cmake(gem_path=gem_path) - if error_code: - ret_val = error_code - return ret_val @@ -256,9 +251,6 @@ def add_parser_args(parser): default='Common', help='Optional list of platforms this gem should be removed from' ' Ex. --platforms Mac,Windows,Linux') - parser.add_argument('-r', '--remove-from-cmake', type=bool, required=False, - default=False, - help='Automatically call remove-from-cmake.') parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, help='By default the home folder is the user folder, override it to this folder.') From 84a3a3d40a7fa74059cda929888626cca8e21292 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Mon, 24 May 2021 22:53:57 -0500 Subject: [PATCH 118/811] Updating the DefaultProject template to copy over a gem.json file to the Code folder of the created project, since the Code itself is a GEM_MODULE that loads using the Module loading system --- Templates/DefaultProject/Template/Code/gem.json | 14 ++++++++++++++ Templates/DefaultProject/template.json | 6 ++++++ 2 files changed, 20 insertions(+) create mode 100644 Templates/DefaultProject/Template/Code/gem.json diff --git a/Templates/DefaultProject/Template/Code/gem.json b/Templates/DefaultProject/Template/Code/gem.json new file mode 100644 index 0000000000..5b8fb3fde0 --- /dev/null +++ b/Templates/DefaultProject/Template/Code/gem.json @@ -0,0 +1,14 @@ +{ + "gem_name": "${Name}", + "origin": "The primary repo for ${Name} goes here: i.e. http://www.mydomain.com", + "license": "What license ${Name} uses goes here: i.e. https://opensource.org/licenses/MIT", + "display_name": "${Name}", + "summary": "A short description of ${Name}.", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + "${Name}" + ], + "icon_path": "preview.png" +} diff --git a/Templates/DefaultProject/template.json b/Templates/DefaultProject/template.json index 31b448c9f6..d654c3a969 100644 --- a/Templates/DefaultProject/template.json +++ b/Templates/DefaultProject/template.json @@ -48,6 +48,12 @@ "isTemplated": true, "isOptional": false }, + { + "file": "Code/gem.json", + "origin": "Code/gem.json", + "isTemplated": true, + "isOptional": true + }, { "file": "Code/Include/${Name}/${Name}Bus.h", "origin": "Code/Include/${Name}/${Name}Bus.h", From d2a15de66835255d08dfd9e142cc5c951b10bd67 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Mon, 24 May 2021 22:56:35 -0500 Subject: [PATCH 119/811] Adding support to read an "external_subdirectories" key from the project.json when building a project. This allows the project to build additional gems via adding the external subdirectory in the project.json file manually or using the `o3de.py register --external-subdirectory-path= --external_subdirectory-project-path-` command --- CMakeLists.txt | 17 ++++-- Templates/DefaultGem/Template/CMakeLists.txt | 2 +- cmake/O3DEJson.cmake | 55 ++++++++++++++++++++ cmake/Projects.cmake | 39 +++++++++----- 4 files changed, 97 insertions(+), 16 deletions(-) create mode 100644 cmake/O3DEJson.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index d743a8ab57..83c9d7d14f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -53,11 +53,22 @@ include(cmake/Monolithic.cmake) include(cmake/SettingsRegistry.cmake) include(cmake/TestImpactFramework/LYTestImpactFramework.cmake) include(cmake/CMakeFiles.cmake) +include(cmake/O3DEJson.cmake) ################################################################################ # Subdirectory processing ################################################################################ +function(add_engine_json_external_subdirectories) + read_json_external_subdirs(external_subdis ${LY_ROOT_FOLDER}/engine.json) + foreach(external_subdir ${external_subdis}) + file(REAL_PATH ${external_subdir} real_external_subdir BASE_DIRECTORY ${LY_ROOT_FOLDER}) + list(APPEND engine_external_subdirs ${real_external_subdir}) + endforeach() + + set_property(GLOBAL APPEND PROPERTY LY_EXTERNAL_SUBDIRS ${engine_external_subdirs}) +endfunction() + # Add the projects first so the Launcher can find them include(cmake/Projects.cmake) @@ -73,11 +84,11 @@ if(NOT INSTALLED_ENGINE) add_subdirectory(Tools/RemoteConsole/ly_remote_console/tests/) endif() - include(cmake/EngineJson.cmake) # Add external subdirectories listed in the engine.json. LY_EXTERNAL_SUBDIRS is a cache variable so the user can add extra # external subdirectories - read_engine_external_subdirs(engine_external_subdirectories) - list(APPEND LY_EXTERNAL_SUBDIRS ${engine_external_subdirectories}) + add_engine_json_external_subdirectories() + get_property(external_subdirs GLOBAL PROPERTY LY_EXTERNAL_SUBDIRS) + list(APPEND LY_EXTERNAL_SUBDIRS ${external_subdirs}) # Loop over the additional external subdirectories and invoke add_subdirectory on them foreach(external_directory ${LY_EXTERNAL_SUBDIRS}) diff --git a/Templates/DefaultGem/Template/CMakeLists.txt b/Templates/DefaultGem/Template/CMakeLists.txt index fb63008782..1a24bd488f 100644 --- a/Templates/DefaultGem/Template/CMakeLists.txt +++ b/Templates/DefaultGem/Template/CMakeLists.txt @@ -11,7 +11,7 @@ set(o3de_gem_path ${CMAKE_CURRENT_LIST_DIR}) set(o3de_gem_json ${o3de_gem_path}/gem.json) -o3de_gem_name(${o3de_gem_json} o3de_gem_name) +o3de_read_json_key(o3de_gem_name ${o3de_gem_json} "gem_name") o3de_restricted_path(${o3de_gem_json} o3de_gem_restricted_path) # Currently we are in the DefaultProjectSource folder: ${CMAKE_CURRENT_LIST_DIR} diff --git a/cmake/O3DEJson.cmake b/cmake/O3DEJson.cmake new file mode 100644 index 0000000000..5d748e9681 --- /dev/null +++ b/cmake/O3DEJson.cmake @@ -0,0 +1,55 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +include_guard() + +set(LY_EXTERNAL_SUBDIRS "" CACHE STRING "List of subdirectories to recurse into when running cmake against the engine's CMakeLists.txt") + +#! read_json_external_subdirs +# Read the "external_subdirectories" array from a *.json file +# External subdirectories are any folders with CMakeLists.txt in them +# This could be regular subdirectories, Gems(contains an additional gem.json), +# Restricted folders(contains an additional restricted.json), etc... +# +# \arg:output_external_subdirs name of output variable to store external subdirectories into +# \arg:input_json_path path to the *.json file to load and read the external subdirectories from +# \return: external subdirectories as is from the json file. +function(read_json_external_subdirs output_external_subdirs input_json_path) + file(READ ${input_json_path} manifest_json_data) + string(JSON external_subdirs_count ERROR_VARIABLE manifest_json_error + LENGTH ${manifest_json_data} "external_subdirectories") + if(manifest_json_error) + # There is "external_subdirectories" key, so theire are no subdirectories to read + return() + endif() + + if(external_subdirs_count GREATER 0) + math(EXPR external_subdir_range "${external_subdirs_count}-1") + foreach(external_subdir_index RANGE ${external_subdir_range}) + string(JSON external_subdir ERROR_VARIABLE manifest_json_error + GET ${manifest_json_data} "external_subdirectories" "${external_subdir_index}") + if(manifest_json_error) + message(FATAL_ERROR "Error reading field at index ${external_subdir_index} in \"external_subdirectories\" JSON array: ${manifest_json_error}") + endif() + list(APPEND external_subdirs ${external_subdir}) + endforeach() + endif() + set(${output_external_subdirs} ${external_subdirs} PARENT_SCOPE) +endfunction() + +function(o3de_read_json_key output_value input_json_path key) + file(READ ${input_json_path} manifest_json_data) + string(JSON value ERROR_VARIABLE manifest_json_error GET ${manifest_json_data} ${key}) + if(manifest_json_error) + message(FATAL_ERROR "Error reading field at key ${key} in file \"${input_json_path}\" : ${manifest_json_error}") + endif() + set(${output_value} ${value} PARENT_SCOPE) +endfunction() diff --git a/cmake/Projects.cmake b/cmake/Projects.cmake index 781fee3711..297dad4ddf 100644 --- a/cmake/Projects.cmake +++ b/cmake/Projects.cmake @@ -105,6 +105,7 @@ function(ly_add_project_dependencies) ) endfunction() + #template for generating the project build_path setreg set(project_build_path_template [[ { @@ -120,7 +121,6 @@ set(project_build_path_template [[ }]] ) - #! ly_generate_project_build_path_setreg: Generates a .setreg file that contains an absolute path to the ${CMAKE_BINARY_DIR} # This allows locate the directory where the project it's binaries are built to be located within the engine. # Which are the shared libraries and launcher executables @@ -136,18 +136,32 @@ set(project_build_path_template [[ # can only run on the host platform # \arg:project_real_path Full path to the o3de project directory function(ly_generate_project_build_path_setreg project_real_path) - # The build path isn't needed on non-monolithic platforms - # Nor on any non-host platforms - if (LY_MONOLITHIC_GAME OR NOT PAL_TRAIT_BUILD_HOST_TOOLS) - return() - endif() + # The build path isn't needed on non-monolithic platforms + # Nor on any non-host platforms + if (LY_MONOLITHIC_GAME OR NOT PAL_TRAIT_BUILD_HOST_TOOLS) + return() + endif() - # Set the project_bin_path to the ${CMAKE_BINARY_DIR} to provide the configure template - # with the project build directory - set(project_bin_path ${CMAKE_BINARY_DIR}) - string(CONFIGURE ${project_build_path_template} project_build_path_setreg_content @ONLY) - set(project_user_build_path_setreg_file ${project_real_path}/user/Registry/Platform/${PAL_PLATFORM_NAME}/build_path.setreg) - file(GENERATE OUTPUT ${project_user_build_path_setreg_file} CONTENT ${project_build_path_setreg_content}) + # Set the project_bin_path to the ${CMAKE_BINARY_DIR} to provide the configure template + # with the project build directory + set(project_bin_path ${CMAKE_BINARY_DIR}) + string(CONFIGURE ${project_build_path_template} project_build_path_setreg_content @ONLY) + set(project_user_build_path_setreg_file ${project_real_path}/user/Registry/Platform/${PAL_PLATFORM_NAME}/build_path.setreg) + file(GENERATE OUTPUT ${project_user_build_path_setreg_file} CONTENT ${project_build_path_setreg_content}) +endfunction() + + +function(add_project_json_external_subdirectories project_path) + set(project_json_path ${project_path}/project.json) + if(EXISTS ${project_json_path}) + read_json_external_subdirs(external_subdirs ${project_path}/project.json) + foreach(external_subdir ${external_subdirs}) + file(REAL_PATH ${external_subdir} real_external_subdir BASE_DIRECTORY ${project_path}) + list(APPEND project_external_subdirs ${real_external_subdir}) + endforeach() + + set_property(GLOBAL APPEND PROPERTY LY_EXTERNAL_SUBDIRS ${project_external_subdirs}) + endif() endfunction() # Add the projects here so the above function is found @@ -163,5 +177,6 @@ foreach(project ${LY_PROJECTS}) list(APPEND LY_PROJECTS_FOLDER_NAME ${project_folder_name}) add_subdirectory(${project} "${project_folder_name}-${full_directory_hash}") ly_generate_project_build_path_setreg(${full_directory_path}) + add_project_json_external_subdirectories(${full_directory_path}) endforeach() ly_set(LY_PROJECTS_FOLDER_NAME ${LY_PROJECTS_FOLDER_NAME}) From 952901f55b7ebade4c38abc524344330ffb0efa6 Mon Sep 17 00:00:00 2001 From: scottr Date: Tue, 25 May 2021 11:33:59 -0700 Subject: [PATCH 120/811] [cpack_installer] adding setup script to install cmake, python, and registering the engine --- .../CMake/cmake-3.19.1-win64-x64.zip | 3 + scripts/setup.bat | 93 +++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 Tools/Redistributables/CMake/cmake-3.19.1-win64-x64.zip create mode 100644 scripts/setup.bat diff --git a/Tools/Redistributables/CMake/cmake-3.19.1-win64-x64.zip b/Tools/Redistributables/CMake/cmake-3.19.1-win64-x64.zip new file mode 100644 index 0000000000..fc3a243f06 --- /dev/null +++ b/Tools/Redistributables/CMake/cmake-3.19.1-win64-x64.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e95d70549f306adb46e0f131dcecdbcbc6412d3a1e073c2c0078812391bf21d3 +size 36098689 diff --git a/scripts/setup.bat b/scripts/setup.bat new file mode 100644 index 0000000000..34251ad861 --- /dev/null +++ b/scripts/setup.bat @@ -0,0 +1,93 @@ +@echo off +rem +rem All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +rem its licensors. +rem +rem For complete copyright and license terms please see the LICENSE at the root of this +rem distribution (the "License"). All use of this software is governed by the License, +rem or, if provided, by the license below or the license accompanying this file. Do not +rem remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +rem + +pushd %~dp0% + +pushd %~dp0.. +set ENGINE_ROOT=%CD% +popd + +set cmake_version=3.19.1 + +if not "%1"=="" ( + set LY_3RDPARTY_PATH=%1 +) +if "%LY_3RDPARTY_PATH%"=="" goto no_3rd_party + +if not exist %LY_3RDPARTY_PATH% mkdir %LY_3RDPARTY_PATH% +goto install_cmake + +:no_3rd_party +echo A path to where the 3rd party folder is required for setup. +echo Either supply one through the LY_3RDPARTY_PATH environment +echo variable or as an argument to this script +goto fail + + +:install_cmake +set cmake_install_path=%LY_3RDPARTY_PATH%\CMake\%cmake_version%\Windows +set cmake_archive_name=cmake-%cmake_version%-win64-x64 +set cmake_archive_path="%ENGINE_ROOT%\Tools\Redistributables\CMake\%cmake_archive_name%.zip" +if exist "%cmake_install_path%\bin\cmake.exe" goto install_python + +echo Installing CMake %cmake_version% to %cmake_install_path% +if not exist %cmake_install_path% mkdir %cmake_install_path% +powershell.exe -nologo -noprofile -command^ + "& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('%cmake_archive_path%', '%cmake_install_path%'); }" +if ERRORLEVEL 1 goto cmake_failed + +set cmake_extracted_path=%cmake_install_path%\%cmake_archive_name% +for /d %%a in ("%cmake_extracted_path%\*") do move "%%a" "%cmake_install_path%\" +rmdir %cmake_extracted_path% + +goto success + +if ERRORLEVEL 1 goto cmake_failed +set LY_CMAKE_PATH="%cmake_install_path%\bin" +goto install_python + +:cmake_failed +echo Failed to extract cmake to path %cmake_install_path% +goto fail + + +:install_python +echo Installing python... +call %ENGINE_ROOT%\python\get_python.bat +if ERRORLEVEL 1 goto python_failed +goto register_engine + +:python_failed +echo Failed to acquire python +goto fail + + +:register_engine +echo Registering engine... +call %ENGINE_ROOT%\scripts\o3de.bat register --this-engine +if ERRORLEVEL 1 goto registration_failed +goto success + +:registration_failed +echo Failed to register the engine +goto fail + + +:fail +echo O3DE setup failed +popd +exit /b 1 + +:success +echo O3DE setup complete +popd +exit /b %ERRORLEVEL% From be9c9d9fa3f6b4d07a68f96e586c05e4a1f4f204 Mon Sep 17 00:00:00 2001 From: srikappa Date: Tue, 25 May 2021 12:57:16 -0700 Subject: [PATCH 121/811] Remove prefab undo cache dependency on CreatePrefab use case --- .../API/ToolsApplicationAPI.h | 5 + .../Application/ToolsApplication.cpp | 5 + .../Application/ToolsApplication.h | 1 + .../Instance/InstanceToTemplatePropagator.cpp | 20 ++-- .../AzToolsFramework/Prefab/Link/Link.cpp | 5 + .../AzToolsFramework/Prefab/Link/Link.h | 2 + .../Prefab/PrefabPublicHandler.cpp | 97 +++++++++++-------- .../Prefab/PrefabPublicHandler.h | 5 + 8 files changed, 87 insertions(+), 53 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h index 82fa3f94f5..72150b1b57 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h @@ -239,6 +239,11 @@ namespace AzToolsFramework */ virtual int RemoveDirtyEntity(AZ::EntityId target) = 0; + /*! + * Clears the dirty entity set. + */ + virtual void ClearDirtyEntities() = 0; + /*! * \return true if an undo/redo operation is in progress. */ diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp index e77704c920..88057787bb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp @@ -1354,6 +1354,11 @@ namespace AzToolsFramework return static_cast(m_dirtyEntities.erase(entityId)); } + void ToolsApplication::ClearDirtyEntities() + { + m_dirtyEntities.clear(); + } + void ToolsApplication::UndoPressed() { if (m_undoStack) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.h index 6c836ac888..bafced67bd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.h @@ -85,6 +85,7 @@ namespace AzToolsFramework void AddDirtyEntity(AZ::EntityId entityId) override; int RemoveDirtyEntity(AZ::EntityId entityId) override; + void ClearDirtyEntities() override; bool IsDuringUndoRedo() override { return m_isDuringUndoRedo; } void UndoPressed() override; void RedoPressed() override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index a21c5301aa..6d3ddedd51 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -276,18 +276,14 @@ namespace AzToolsFramework PrefabDomValueReference linkPatchesReference = PrefabDomUtils::FindPrefabDomValue(linkDom, PrefabDomUtils::PatchesName); - // This logic only covers addition of patches. If patches already exists, the given list of patches must be appended to them. - if (!linkPatchesReference.has_value()) - { - /* - If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the - linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to - associate them with the linkDom's allocator. - */ - PrefabDom patchesCopy; - patchesCopy.CopyFrom(patches, linkDom.GetAllocator()); - linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patchesCopy, linkDom.GetAllocator()); - } + /* + If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the + linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to + associate them with the linkDom's allocator. + */ + PrefabDom patchesCopy; + patchesCopy.CopyFrom(patches, linkDom.GetAllocator()); + linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patchesCopy, linkDom.GetAllocator()); } } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp index 308749ab28..01a954ebdd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp @@ -234,5 +234,10 @@ namespace AzToolsFramework } } + PrefabDomValueConstReference Link::GetLinkPatches() + { + return PrefabDomUtils::FindPrefabDomValue(m_linkDom, PrefabDomUtils::PatchesName); + } + } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.h index 073e619f20..7d30f9235d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.h @@ -79,6 +79,8 @@ namespace AzToolsFramework */ void AddLinkIdToInstanceDom(PrefabDomValue& instanceDomValue); + PrefabDomValueConstReference GetLinkPatches(); + private: /** diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 579f465eb2..7284a9cd95 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -33,8 +33,6 @@ #include #include -#include - namespace AzToolsFramework { namespace Prefab @@ -98,9 +96,13 @@ namespace AzToolsFramework AZStd::string("Could not create a new prefab out of the entities provided - invalid selection.")); } + AZStd::unordered_map oldEntityAliases; + // Detach the retrieved entities for (AZ::Entity* entity : entities) { + AZ::EntityId entityId = entity->GetId(); + oldEntityAliases.emplace(entityId, commonRootEntityOwningInstance->get().GetEntityAlias(entityId)->get()); commonRootEntityOwningInstance->get().DetachEntity(entity->GetId()).release(); } @@ -110,15 +112,18 @@ namespace AzToolsFramework { AZStd::unique_ptr outInstance = commonRootEntityOwningInstance->get().DetachNestedInstance(nestedInstance->GetInstanceAlias()); - auto linkRef = m_prefabSystemComponentInterface->FindLink(nestedInstance->GetLinkId()); + LinkId detachingInstanceLinkId = nestedInstance->GetLinkId(); + auto linkRef = m_prefabSystemComponentInterface->FindLink(detachingInstanceLinkId); + AZ_Assert(linkRef.has_value(), "Unable to find link with id '%llu' during prefab creation.", detachingInstanceLinkId); - if (linkRef.has_value()) - { - PrefabDom oldLinkPatches; - oldLinkPatches.CopyFrom(linkRef->get().GetLinkDom(), oldLinkPatches.GetAllocator()); + PrefabDomValueConstReference linkPatches = linkRef->get().GetLinkPatches(); + AZ_Assert( + linkPatches.has_value(), "Unable to get patches on link with id '%llu' during prefab creation.", + detachingInstanceLinkId); - nestedInstanceLinkPatchesMap.emplace(nestedInstance, AZStd::move(oldLinkPatches)); - } + PrefabDom linkPatchesCopy; + linkPatchesCopy.CopyFrom(linkPatches->get(), linkPatchesCopy.GetAllocator()); + nestedInstanceLinkPatchesMap.emplace(nestedInstance, AZStd::move(linkPatchesCopy)); RemoveLink(outInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch()); @@ -182,6 +187,24 @@ namespace AzToolsFramework if (nestedInstanceLinkPatchesMap.contains(nestedInstance.get())) { previousPatch = AZStd::move(nestedInstanceLinkPatchesMap[nestedInstance.get()]); + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + previousPatch.Accept(writer); + QString previousPatchString(buffer.GetString()); + + for (AZ::Entity* entity : entities) + { + AZ::EntityId entityId = entity->GetId(); + AZStd::string oldEntityAlias = oldEntityAliases[entityId]; + EntityAliasOptionalReference newEntityAlias = instanceToCreate->get().GetEntityAlias(entityId); + AZ_Assert( + newEntityAlias.has_value(), + "Could not fetch entity alias for entity with id '%llu' during prefab creation.", + static_cast(entityId)); + ReplaceOldAliases(previousPatchString, oldEntityAlias, newEntityAlias->get()); + } + + previousPatch.Parse(previousPatchString.toUtf8().constData()); } // These link creations shouldn't be undone because that would put the template in a non-usable state if a user @@ -203,36 +226,23 @@ namespace AzToolsFramework m_instanceToTemplateInterface->GeneratePatch(reparentPatch, containerEntityDomBefore, containerEntityDomAfter); m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(reparentPatch, nestedInstanceContainerEntityId); - // Update the cache - this prevents these changes from being stored in the regular undo/redo nodes as a separate step - m_prefabUndoCache.Store(nestedInstanceContainerEntityId, AZStd::move(containerEntityDomAfter)); - - // Save these changes as patches to the link - PrefabUndoLinkUpdate* linkUpdate = aznew PrefabUndoLinkUpdate(AZStd::to_string(static_cast(nestedInstanceContainerEntityId))); - linkUpdate->SetParent(undoBatch.GetUndoBatch()); - linkUpdate->Capture(reparentPatch, nestedInstance->GetLinkId()); - - linkUpdate->Redo(); + // We ar not parenting this undo node to the undo batch because we don't want the user to undo these changes + // so that the newly created template and link remain unaffected for supporting instantiating the template later. + PrefabUndoLinkUpdate linkUpdate = PrefabUndoLinkUpdate(AZStd::to_string(static_cast(nestedInstanceContainerEntityId))); + linkUpdate.Capture(reparentPatch, nestedInstance->GetLinkId()); + linkUpdate.Redo(); } }); - + // Create a link between the templates of the newly created instance and the instance it's being parented under. CreateLink( instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(), AZStd::move(patch)); - for (AZ::Entity* topLevelEntity : topLevelEntities) - { - AZ::EntityId topLevelEntityId = topLevelEntity->GetId(); - if (topLevelEntityId.IsValid()) - { - m_prefabUndoCache.UpdateCache(topLevelEntity->GetId()); - - // Parenting entities would mark entities as dirty. But we want to unmark the top level entities as dirty because - // if we don't, the template created would be updated and cause issues with undo operation followed by instantiation. - ToolsApplicationRequests::Bus::Broadcast( - &ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId()); - } - } + // This clears any entities marked as dirty due to reparenting of entities during the process of creating a prefab. + // We are doing this so that the changes in those enities are not queued up twice for propagation. + AzToolsFramework::ToolsApplicationRequestBus::Broadcast( + &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); // Select Container Entity { @@ -824,15 +834,7 @@ namespace AzToolsFramework // This will cover both cases where an alias could be used in a normal entity vs. an instance for (auto aliasMapIter : oldAliasToNewAliasMap) { - QString oldAliasQuotes = QString("\"%1\"").arg(aliasMapIter.first.c_str()); - QString newAliasQuotes = QString("\"%1\"").arg(aliasMapIter.second.c_str()); - - newEntityDomString.replace(oldAliasQuotes, newAliasQuotes); - - QString oldAliasPathRef = QString("/%1").arg(aliasMapIter.first.c_str()); - QString newAliasPathRef = QString("/%1").arg(aliasMapIter.second.c_str()); - - newEntityDomString.replace(oldAliasPathRef, newAliasPathRef); + ReplaceOldAliases(newEntityDomString, aliasMapIter.first, aliasMapIter.second); } // Create the new Entity DOM from parsing the JSON string @@ -1233,5 +1235,18 @@ namespace AzToolsFramework return true; } + + void PrefabPublicHandler::ReplaceOldAliases(QString& stringToReplace, AZStd::string_view oldAlias, AZStd::string_view newAlias) + { + QString oldAliasQuotes = QString("\"%1\"").arg(oldAlias.data()); + QString newAliasQuotes = QString("\"%1\"").arg(newAlias.data()); + + stringToReplace.replace(oldAliasQuotes, newAliasQuotes); + + QString oldAliasPathRef = QString("/%1").arg(oldAlias.data()); + QString newAliasPathRef = QString("/%1").arg(newAlias.data()); + + stringToReplace.replace(oldAliasPathRef, newAliasPathRef); + } } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 223a725c6c..a3e2632ea4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -14,12 +14,15 @@ #include #include +#include #include #include #include #include +#include + namespace AzToolsFramework { using EntityList = AZStd::vector; @@ -130,6 +133,8 @@ namespace AzToolsFramework bool IsCyclicalDependencyFound( InstanceOptionalConstReference instance, const AZStd::unordered_set& templateSourcePaths); + void ReplaceOldAliases(QString& stringToReplace, AZStd::string_view oldAlias, AZStd::string_view newAlias); + static Instance* GetParentInstance(Instance* instance); static Instance* GetAncestorOfInstanceThatIsChildOfRoot(const Instance* ancestor, Instance* descendant); static void GenerateContainerEntityTransform(const EntityList& topLevelEntities, AZ::Vector3& translation, AZ::Quaternion& rotation); From 87ff564badb54fed90c8c906379aedad03112974 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Tue, 25 May 2021 13:15:10 -0700 Subject: [PATCH 122/811] ATOM-14838 Make Parallax Look Decent By Default Updated material types to have default parallax settings of POM, Low quality, 0.05 scale. That way the parallax effect will show up as soon as a user adds a heightmap. Updated StandardMultilayerPBR_Displacement.lua to control the o_parallax_feature_enabled, so we can have the material's parallax.enable=true by default. Again this is to allow parallax behavior to show up as soon as the user adds a heightmap or adjusts the displacement offset. Note that even though we have a functor to drive the feature based on displacement settings, we still need the parallax.enable flag that that the user can set to false when they want to use displacement blending but not parallax. Updated test materials to maintain their prior implied settings. --- .../Materials/Types/EnhancedPBR.materialtype | 4 +- .../Types/StandardMultilayerPBR.materialtype | 17 +++-- .../StandardMultilayerPBR_Displacement.lua | 66 ++++++++++++++++--- .../Materials/Types/StandardPBR.materialtype | 4 +- .../001_ManyFeatures.material | 2 +- .../002_ParallaxPdo.material | 4 +- .../004_UseVertexColors.material | 5 +- 7 files changed, 76 insertions(+), 26 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index 954e01c592..48b576c768 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -973,7 +973,7 @@ "displayName": "Heightmap Scale", "description": "The total height of the heightmap in local model units.", "type": "Float", - "defaultValue": 0.0, + "defaultValue": 0.05, "min": 0.0, "softMax": 0.1, "connection": { @@ -1011,7 +1011,7 @@ "description": "Select the algorithm to use for parallax mapping.", "type": "Enum", "enumValues": [ "Basic", "Steep", "POM", "Relief", "ContactRefinement" ], - "defaultValue": "Basic", + "defaultValue": "POM", "connection": { "type": "ShaderOption", "id": "o_parallax_algorithm" diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype index 274cb4dcb5..05ba40ddae 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype @@ -369,15 +369,14 @@ ], "parallax": [ { + // Note parallax is enabled by default so that as soon as a user hooks up displacement settings they will see some parallax applied. + // The functor that controls parallax will set o_parallax_feature_enabled=false when all the individual layers have no displacement, so + // a default value of true here will not have any initial impact on performance. "id": "enable", "displayName": "Enable", "description": "Whether to enable the parallax feature for this material.", "type": "Bool", - "defaultValue": false, - "connection": { - "type": "ShaderOption", - "id": "o_parallax_feature_enabled" - } + "defaultValue": true }, { "id": "parallaxUv", @@ -409,7 +408,7 @@ "description": "Quality of parallax mapping.", "type": "Enum", "enumValues": [ "Low", "Medium", "High", "Ultra" ], - "defaultValue": "Medium", + "defaultValue": "Low", "connection": { "type": "ShaderOption", "id": "o_parallax_quality" @@ -1141,7 +1140,7 @@ "displayName": "Scale", "description": "The total height of the displacement texture map in local model units.", "type": "Float", - "defaultValue": 0.0, + "defaultValue": 0.05, "min": 0.0, "softMax": 0.1, "connection": { @@ -1847,7 +1846,7 @@ "displayName": "Scale", "description": "The total height of the displacement texture map in local model units.", "type": "Float", - "defaultValue": 0.0, + "defaultValue": 0.05, "min": 0.0, "softMax": 0.1, "connection": { @@ -2553,7 +2552,7 @@ "displayName": "Scale", "description": "The total height of the displacement texture map in local model units.", "type": "Float", - "defaultValue": 0.0, + "defaultValue": 0.05, "min": 0.0, "softMax": 0.1, "connection": { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Displacement.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Displacement.lua index 34a067577d..d2bf8f28d3 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Displacement.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Displacement.lua @@ -35,6 +35,10 @@ function GetMaterialPropertyDependencies() } end +function GetShaderOptionDependencies() + return {"o_parallax_feature_enabled"} +end + -- These values must align with LayerBlendSource in StandardMultilayerPBR_Common.azsli. LayerBlendSource_BlendMaskTexture = 0 LayerBlendSource_BlendMaskVertexColors = 1 @@ -50,6 +54,39 @@ function BlendSourceUsesDisplacement(context) return blendSourceIncludesDisplacement end +function IsParallaxNeededForLayer(context, layerNumber) + local enableLayer = true + if(layerNumber > 1) then -- layer 1 is always enabled, it is the implicit base layer + enableLayer = context:GetMaterialPropertyValue_bool("blend.enableLayer" .. layerNumber) + end + + if not enableLayer then + return false + end + + local parallaxGroupName = "layer" .. layerNumber .. "_parallax." + + local factor = context:GetMaterialPropertyValue_float(parallaxGroupName .. "factor") + local offset = context:GetMaterialPropertyValue_float(parallaxGroupName .. "offset") + + if factor == 0.0 and offset == 0.0 then + return false + end + + local hasTexture = nil ~= context:GetMaterialPropertyValue_Image(parallaxGroupName .. "textureMap") + local useTexture = context:GetMaterialPropertyValue_bool(parallaxGroupName .. "useTexture") + + if not hasTexture or not useTexture then + factorLayer = 0.0 + end + + if factor == 0.0 and offset == 0.0 then + return false + end + + return true +end + -- Calculates the min and max displacement height values encompassing all enabled layers. -- @return a table with two values {min,max}. Negative values are below the surface and positive values are above the surface. function CalcOverallHeightRange(context) @@ -114,21 +151,32 @@ function Process(context) local heightMinMax = CalcOverallHeightRange(context) context:SetShaderConstant_float("m_displacementMin", heightMinMax[0]) context:SetShaderConstant_float("m_displacementMax", heightMinMax[1]) + + local parallaxFeatureEnabled = context:GetMaterialPropertyValue_bool("parallax.enable") + if parallaxFeatureEnabled then + if not IsParallaxNeededForLayer(context, 1) and + not IsParallaxNeededForLayer(context, 2) and + not IsParallaxNeededForLayer(context, 3) then + parallaxFeatureEnabled = false + end + end + + context:SetShaderOptionValue_bool("o_parallax_feature_enabled", parallaxFeatureEnabled) end function ProcessEditor(context) - local enable = context:GetMaterialPropertyValue_bool("parallax.enable") + local enableParallaxSettings = context:GetMaterialPropertyValue_bool("parallax.enable") - local visibility = MaterialPropertyVisibility_Enabled - if(not enable) then - visibility = MaterialPropertyVisibility_Hidden + local parallaxSettingVisibility = MaterialPropertyVisibility_Enabled + if(not enableParallaxSettings) then + parallaxSettingVisibility = MaterialPropertyVisibility_Hidden end - context:SetMaterialPropertyVisibility("parallax.parallaxUv", visibility) - context:SetMaterialPropertyVisibility("parallax.algorithm", visibility) - context:SetMaterialPropertyVisibility("parallax.quality", visibility) - context:SetMaterialPropertyVisibility("parallax.pdo", visibility) - context:SetMaterialPropertyVisibility("parallax.showClipping", visibility) + context:SetMaterialPropertyVisibility("parallax.parallaxUv", parallaxSettingVisibility) + context:SetMaterialPropertyVisibility("parallax.algorithm", parallaxSettingVisibility) + context:SetMaterialPropertyVisibility("parallax.quality", parallaxSettingVisibility) + context:SetMaterialPropertyVisibility("parallax.pdo", parallaxSettingVisibility) + context:SetMaterialPropertyVisibility("parallax.showClipping", parallaxSettingVisibility) if BlendSourceUsesDisplacement(context) then context:SetMaterialPropertyVisibility("blend.displacementBlendDistance", MaterialPropertyVisibility_Enabled) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index 2b0d09bc5c..2d848b2774 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -913,7 +913,7 @@ "displayName": "Heightmap Scale", "description": "The total height of the heightmap in local model units.", "type": "Float", - "defaultValue": 0.0, + "defaultValue": 0.05, "min": 0.0, "softMax": 0.1, "connection": { @@ -951,7 +951,7 @@ "description": "Select the algorithm to use for parallax mapping.", "type": "Enum", "enumValues": [ "Basic", "Steep", "POM", "Relief", "ContactRefinement" ], - "defaultValue": "Basic", + "defaultValue": "POM", "connection": { "type": "ShaderOption", "id": "o_parallax_algorithm" diff --git a/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/001_ManyFeatures.material b/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/001_ManyFeatures.material index 17353a0603..1c02f56af6 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/001_ManyFeatures.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/001_ManyFeatures.material @@ -132,7 +132,7 @@ "rotateDegrees": -57.599998474121097 }, "parallax": { - "enable": true + "quality": "Medium" }, "uv": { "center": [ diff --git a/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/002_ParallaxPdo.material b/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/002_ParallaxPdo.material index 8cddab24bc..64adf317a9 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/002_ParallaxPdo.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/002_ParallaxPdo.material @@ -48,8 +48,8 @@ "textureMap": "TestData/Textures/cc0/Concrete019_1K_Color.jpg" }, "parallax": { - "enable": true, - "pdo": true + "pdo": true, + "quality": "Medium" } } } \ No newline at end of file diff --git a/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/004_UseVertexColors.material b/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/004_UseVertexColors.material index 3201fa3864..ea3ea8b519 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/004_UseVertexColors.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/004_UseVertexColors.material @@ -6,6 +6,9 @@ "properties": { "blend": { "blendSource": "BlendMaskVertexColors" + }, + "parallax": { + "quality": "Medium" } } -} +} \ No newline at end of file From 7129cad1ce504545ce793dc2d9f916960a0fa24a Mon Sep 17 00:00:00 2001 From: puvvadar Date: Tue, 25 May 2021 14:12:47 -0700 Subject: [PATCH 123/811] Add RewindableFixedVector and update jinja components to use it --- .../NetworkTime/RewindableFixedVector.h | 129 ++++++++++ .../NetworkTime/RewindableFixedVector.inl | 242 ++++++++++++++++++ .../NetworkTime/RewindableObject.h | 2 +- .../Source/AutoGen/AutoComponent_Header.jinja | 13 +- .../Source/AutoGen/AutoComponent_Source.jinja | 75 +++--- ...tionPlayerInputComponent.AutoComponent.xml | 3 +- Gems/Multiplayer/Code/multiplayer_files.cmake | 2 + 7 files changed, 424 insertions(+), 42 deletions(-) create mode 100644 Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h create mode 100644 Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h new file mode 100644 index 0000000000..2e265bdb6f --- /dev/null +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h @@ -0,0 +1,129 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Multiplayer +{ + //! @class RewindableFixedVector + //! @brief Data structure that has a compile-time upper bound, provides vector semantics and supports network serialization + template + class RewindableFixedVector + { + public: + //! Default constructor + RewindableFixedVector() = default; + + //! Construct and initialize buffer to the provided value + //! @param initialValue initial value to set the internal buffer to + //! @param count initial value to reserve in the vector + RewindableFixedVector(const TYPE& initialValue, uint32_t count); + + //! Destructor + ~RewindableFixedVector(); + + //! Serialization method for fixed vector contained rewindable objects + //! @param serializer ISerializer instance to use for serialization + //! @return bool true for success, false for serialization failure + bool Serialize(AzNetworking::ISerializer& serializer); + + //! Serialization method for fixed vector contained rewindable objects + //! @param serializer ISerializer instance to use for serialization + //! @return bool true for success, false for serialization failure + bool Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset &deltaRecord); + + //! Copies elements from the buffer pointed to by Buffer to this FixedSizeVector instance, vector size will be set to BufferSize + //! @param buffer pointer to the buffer to copy + //! @param bufferSize number of elements in the buffer to copy + //! @return bool true on success, false if the input data was too large to fit in the vector + bool copy_values(const TYPE* buffer, uint32_t bufferSize); + + //! Copy buffer from the provided vector + //! @param RHS instance to copy from + RewindableFixedVector& operator=(const RewindableFixedVector& RHS); + + //! Equality operator, returns true if the current instance is equal to RHS + //! @param RHS the FixedSizeVector instance to test for equality against + //! @return bool true if equal, false if not + bool operator ==(const RewindableFixedVector& RHS) const; + + //! Inequality operator, returns true if the current instance is not equal to RHS + //! @param RHS the FixedSizeVector instance to test for inequality against + //! @return bool false if equal, true if not equal + bool operator !=(const RewindableFixedVector& RHS) const; + + //! Resizes the vector to the requested number of elements, initializing new elements if necessary + //! @param count the number of elements to size the vector to + //! @return bool true on success + bool resize(uint32_t count); + + //! Resizes the vector to the requested number of elements, without initialization + //! @param count the number of elements to size the vector to + //! @return bool true on success + bool resize_no_construct(uint32_t count); + + //! Resets the vector, returning it to size 0 + void clear(); + + //! Const element access + //! @param Index index of the element to return + //! @return const reference to the requested element + const TYPE& operator[](uint32_t index) const; + + //! Non-const element access + //! @param Index index of the element to return + //! @return non-const reference to the requested element + TYPE& operator[](uint32_t index); + + //! Pushes a new element to the back of the vector + //! @param Value value to append to the back of this vector + //! @return boolean true on success, false if the vector was full + bool push_back(const TYPE& value); + + //! Pops the last element off the vector, decreasing the vector's size by one + //! @return bool true on success, false if the vector was empty + bool pop_back(); + + //! Returns if the vector is empty + //! @return bool true on empty, false if the vector contains valid elements + bool empty() const; + + //! Gets the last element of the vector + const TYPE& back() const; + + //! Gets the size of the vector + uint32_t size() const; + + typedef const RewindableObject* const_iterator; + const_iterator begin() const { return m_container.cbegin(); } + const_iterator end() const { return m_container.cend(); } + typedef RewindableObject* iterator; + iterator begin() { return m_container.begin(); } + iterator end() { return m_container.end(); } + + private: + AZStd::fixed_vector, SIZE> m_container; + // Synchronized value for vector size, prefer using size() locally which checks m_container.size() + RewindableObject m_size; + }; +} + +#include diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl new file mode 100644 index 0000000000..f1c4284fa2 --- /dev/null +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl @@ -0,0 +1,242 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +namespace Multiplayer +{ + template + inline RewindableFixedVector::RewindableFixedVector(const TYPE& initialValue, uint32_t count) + { + resize_no_construct(count); + for (uint32_t idx = 0l idx < size(); ++idx) + { + m_container[idx] = initialValue; + } + } + + template + inline RewindableFixedVector::~RewindableFixedVector() + { + ; + } + + template + inline bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer) + { + m_size = m_container.size(); + if(!m_size.Serialize(serializer) && !resize(m_size)) + { + return false; + } + + for (uint32_t i = 0; i < size(); ++i) + { + if(!m_container[i].Serialize(serializer)) + { + return false; + } + } + + return serializer.IsValid(); + } + + template + inline bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset& deltaRecord) + { + if (deltaRecord.GetBit(SIZE)) + { + uint32_t origSize = m_size; + m_size = m_container.size(); + if(!m_size.Serialize(serializer) && !resize(m_size)) + { + return false; + } + + if ((serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) && origSize == m_size) + { + deltaRecord.SetBit(SIZE, false); + } + } + for (uint32_t i = 0; i < size(); ++i) + { + if (deltaRecord.GetBit(i)) + { + serializer.ClearTrackedChangesFlag(); + if(!m_container[i].Serialize(serializer)) + { + return false; + } + + if ((serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) && !serializer.GetTrackedChangesFlag()) + { + deltaRecord.SetBit(i, false); + } + } + } + + return serializer.IsValid(); + } + + template + inline bool RewindableFixedVector::copy_values(const TYPE* buffer, uint32_t bufferSize) + { + if (!resize(bufferSize)) + { + return false; + } + + for (uint32_t idx = 0; idx < bufferSize; ++i) + { + m_container[idx] = buffer[idx]; + } + + return true; + } + + + template + inline RewindableFixedVector& RewindableFixedVector::operator=(const RewindableFixedVector& RHS) + { + resize(RHS.size()); + for (uint32_t idx = 0; idx < size(); ++i) + { + m_container[idx] = RHS.m_container[idx]; + } + return *this; + } + + template + bool RewindableFixedVector::operator ==(const RewindableFixedVector& RHS) const + { + if (this->size() != RHS.size()) + { + return false; + } + + return m_container == RHS.m_container && m_size == m_size; + } + + template + bool RewindableFixedVector::operator !=(const RewindableFixedVector& RHS) const + { + return !(*this == RHS); + } + + template + bool RewindableFixedVector::resize(uint32_t count) + { + if (count > SIZE) + { + return false; + } + + if (count == size()) + { + return true; + } + + if (count > size()) + { + for (uint32_t idx = size(); idx < count; ++idx) + { + m_container[idx] = TYPE(); + } + } + + m_container.resize(count); + + return true; + } + + template + inline bool RewindableFixedVector::resize_no_construct(uint32_t count) + { + if (count > SIZE) + { + return false; + } + + m_container.resize_no_construct(count); + + return true; + } + + template + inline void RewindableFixedVector::clear() + { + resize(0); + } + + template + inline const TYPE& RewindableFixedVector::operator[](uint32_t index) const + { + AZ_Assert(index < size(), "Out of bounds access (requested %u, reserved %u)", index, size()); + return m_container[index].Get(); + } + + template + inline TYPE& RewindableFixedVector::operator[](uint32_t index) + { + AZ_Assert(index < size(), "Out of bounds access (requested %u, reserved %u)", index, size()); + return m_container[index].Modify(); + } + + template + inline bool RewindableFixedVector::push_back(const TYPE& value) + { + const uint32_t iBufferSize = size(); + + if (!resize(iBufferSize + 1)) + { + return false; + } + + m_container[iBufferSize] = value; + + return true; + } + + template + inline bool RewindableFixedVector::pop_back() + { + const uint32_t iBufferSize = size(); + + if (iBufferSize <= 0) + { + return false; + } + + resize(iBufferSize - 1); + + return true; + } + + template + inline bool RewindableFixedVector::empty() const + { + return m_container.empty(); + } + + template + inline const TYPE& RewindableFixedVector::back() const + { + AZ_Assert(size() > 0, "Attempted to get back element of an empty RewindableFixedVector"); + return m_container[size() - 1].Get(); + } + + template + inline uint32_t RewindableFixedVector::size() const + { + return m_container.size(); + } +} diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h index d5b7d563ab..f7e92bbe26 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h @@ -32,7 +32,7 @@ namespace Multiplayer RewindableObject() = default; //! Constructor. - //! @param connectionId the connectionId of the connection that owns the object. + //! @param value base type value to construct from RewindableObject(const BASE_TYPE& value); //! Copy construct from underlying base type. diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index 4061ddd7b6..071967165f 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -13,7 +13,11 @@ const {{ Property.attrib['Type'] }} &Get{{ PropertyName }}(int32_t index) const; void {{ PropertyName }}AddEvent(AZ::Event::Handler& handler); {% endif %} {% elif Property.attrib['Container'] == 'Vector' %} -const AZStd::fixed_vector<{% if Property.attrib['IsRewindable']|booleanTrue %}RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> &Get{{ PropertyName }}Vector() const; +{% if Property.attrib['IsRewindable']|booleanTrue %} +const RewindableFixedVector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> &Get{{ PropertyName }}Vector() const; +{% else %} +const AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> &Get{{ PropertyName }}Vector() const; +{% endif %} const {{ Property.attrib['Type'] }} &Get{{ PropertyName }}(int32_t index) const; const {{ Property.attrib['Type'] }} &{{ PropertyName }}GetBack() const; uint32_t {{ PropertyName }}GetSize() const; @@ -158,7 +162,11 @@ AZ::Event<{{ Property.attrib['Type'] }}> m_{{ LowerFirst(Property.attrib['Name'] {% if Property.attrib['Container'] == 'Array' %} AZStd::array<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; {% elif Property.attrib['Container'] == 'Vector' %} -AZStd::fixed_vector<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; +{% if Property.attrib['IsRewindable']|booleanTrue %} +RewindableFixedVector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; +{% else %} +AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; +{% endif %} {% elif Property.attrib['IsRewindable']|booleanTrue %} Multiplayer::RewindableObject<{{ Property.attrib['Type'] }}, Multiplayer::RewindHistorySize> m_{{ LowerFirst(Property.attrib['Name']) }} = {{ Property.attrib['Init'] }}; {% else %} @@ -228,6 +236,7 @@ AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] } #include #include #include +#include #include {% call(Include) AutoComponentMacros.ParseIncludes(Component) %} #include <{{ Include.attrib['File'] }}> diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 3437969901..ef83973f48 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -21,7 +21,11 @@ void {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}AddEvent(AZ::Even {% endif %} {% elif Property.attrib['Container'] == 'Vector' %} -const AZStd::fixed_vector<{% if Property.attrib['IsRewindable']|booleanTrue %}RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const +{% if Property.attrib['IsRewindable']|booleanTrue %} +const RewindableFixedVector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const +{% else %} +const AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const +{% endif %} { return {{ Prefix }}m_{{ LowerFirst(Property.attrib['Name']) }}; } @@ -110,25 +114,26 @@ void {{ ClassName }}::Set{{ UpperFirst(Property.attrib['Name']) }}(int32_t index bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PushBack(const {{ Property.attrib['Type'] }} &value) { - int32_t indexToSet = GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size(); - GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.push_back(value); - int32_t bitIndex = indexToSet + static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(bitIndex, true); - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); - GetParent().MarkDirty(); - return true; + if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.push_back(value)) + { + int32_t indexToSet = GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size(); + int32_t bitIndex = indexToSet + static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(bitIndex, true); + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); + GetParent().MarkDirty(); + return true; + } } bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PopBack(const Multiplayer::NetworkInput&) { - if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.empty()) + if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back()) { - return false; + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); + GetParent().MarkDirty(); + return true; } - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); - GetParent().MarkDirty(); - GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back(); - return true; + return false; } void {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}Clear(const Multiplayer::NetworkInput&) @@ -202,30 +207,32 @@ void {{ ClassName }}::Set{{ UpperFirst(Property.attrib['Name']) }}(int32_t index int32_t bitIndex = index + static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(bitIndex, true); GetParent().MarkDirty(); - return static_cast<{{ Property.attrib['Type'] }}&>(GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}[index]{% if Property.attrib['IsRewindable']|booleanTrue %}.Modify(){% endif %}); + return static_cast<{{ Property.attrib['Type'] }}&>(GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}[index]); } bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PushBack(const {{ Property.attrib['Type'] }} &value) { - uint32_t indexToSet = aznumeric_cast(GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size()); - GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.push_back(value); - uint32_t bitIndex = indexToSet + aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(bitIndex, true); - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); - GetParent().MarkDirty(); - return true; + if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.push_back(value)) + { + uint32_t indexToSet = aznumeric_cast(GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size()); + uint32_t bitIndex = indexToSet + aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(bitIndex, true); + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); + GetParent().MarkDirty(); + return true; + } + return false; } bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PopBack() { - if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.empty()) + if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back()) { - return false; + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); + GetParent().MarkDirty(); + return true; } - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); - GetParent().MarkDirty(); - GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back(); - return true; + return false; } void {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}Clear() @@ -562,7 +569,7 @@ bool {{ ClassName }}::Serialize{{ AutoComponentMacros.GetNetPropertiesSetName(Re {%- if networkPropertyCount.update({'value': networkPropertyCount.value + 1}) %}{% endif -%} {% endcall %} {% if networkPropertyCount.value > 0 %} - Multiplayer::MultiplayerStats& stats = Multiplayer::GetMultiplayer()->GetStats(); + [[maybe_unused]] Multiplayer::MultiplayerStats& stats = Multiplayer::GetMultiplayer()->GetStats(); // We modify the record if we are writing an update so that we don't notify for a change that really didn't change the value (just a duplicated send from the server) [[maybe_unused]] bool modifyRecord = serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject; {% call(Property) AutoComponentMacros.ParseNetworkProperties(Component, ReplicateFrom, ReplicateTo) %} @@ -576,15 +583,7 @@ bool {{ ClassName }}::Serialize{{ AutoComponentMacros.GetNetPropertiesSetName(Re {% endif %} AzNetworking::FixedSizeBitsetView deltaRecord(replicationRecord.m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}, firstBit, lastBit - firstBit + 1); - if (deltaRecord.AnySet()) - { -{% if Property.attrib['Container'] == 'Vector' %} - Multiplayer::SerializableFixedSizeVectorDeltaStruct<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> deltaStruct(m_{{ Property.attrib['Name'] }}, deltaRecord); -{% else %} - Multiplayer::SerializableFixedSizeArrayDeltaStruct<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> deltaStruct(m_{{ Property.attrib['Name'] }}, deltaRecord); -{% endif %} - serializer.Serialize(deltaStruct, "{{ UpperFirst(Property.attrib['Name']) }}"); - } + m_{{ LowerFirst(Property.attrib['Name']) }}.Serialize(serializer, deltaRecord); } {% else %} Multiplayer::SerializeNetworkPropertyHelper diff --git a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml index b6edd0e3be..78dc35c111 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml @@ -18,7 +18,8 @@ - + + diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index eb856a48db..856e4893a4 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -33,6 +33,8 @@ set(FILES Include/Multiplayer/NetworkInput/IMultiplayerComponentInput.h Include/Multiplayer/NetworkInput/NetworkInput.h Include/Multiplayer/NetworkTime/INetworkTime.h + Include/Multiplayer/NetworkTime/RewindableFixedVector.h + Include/Multiplayer/NetworkTime/RewindableFixedVector.inl Include/Multiplayer/NetworkTime/RewindableObject.h Include/Multiplayer/NetworkTime/RewindableObject.inl Include/Multiplayer/ReplicationWindows/IReplicationWindow.h From 6d9dd587eefc7da7d6cc9773635751b3019e9361 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Tue, 25 May 2021 14:17:25 -0700 Subject: [PATCH 124/811] Revert change to LocalPrediction xml --- .../LocalPredictionPlayerInputComponent.AutoComponent.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml index 78dc35c111..b6edd0e3be 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml @@ -18,8 +18,7 @@ - - + From e47fb1b7eae9b07d5a3ac8f2a91483adca1dc946 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Tue, 25 May 2021 14:21:14 -0700 Subject: [PATCH 125/811] Fix outdated Rewindable vector jinja generation --- .../Code/Source/AutoGen/AutoComponent_Source.jinja | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index ef83973f48..1124b0e59c 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -654,7 +654,11 @@ const {{ Property.attrib['Type'] }}& {{ ClassName }}::Get{{ UpperFirst(Property. } {% elif Property.attrib['Container'] == 'Vector' %} -const AZStd::fixed_vector<{% if Property.attrib['IsRewindable']|booleanTrue %}RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const +{% if Property.attrib['IsRewindable']|booleanTrue %} +const RewindableFixedVector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const +{% else %} +const AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const +{% endif %} { return {{ Prefix }}m_{{ LowerFirst(Property.attrib['Name']) }}; } From 1f297fc8ac04d8dfdcca1000d113bda10b0fd5bd Mon Sep 17 00:00:00 2001 From: moudgils Date: Tue, 25 May 2021 14:41:14 -0700 Subject: [PATCH 126/811] Updating LuminanceHistogramGenerator to use RWStructuredBuffer as RWBuffer doeesnt work on Metal when combined with atomic operations --- .../Shaders/PostProcessing/LuminanceHistogramGenerator.azsl | 2 +- .../Shaders/PostProcessing/LuminanceHistogramGenerator.shader | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl index 05cc870eea..9d01a12fd6 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl @@ -20,7 +20,7 @@ ShaderResourceGroup PassSrg : SRG_PerPass { Texture2D m_inputTexture; - RWBuffer m_outputTexture; + RWStructuredBuffer m_outputTexture; } groupshared uint shared_histogramBins[NUM_HISTOGRAM_BINS]; diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader index 566144bab8..f3dd11e11a 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader @@ -12,7 +12,5 @@ "type": "Compute" } ] - }, - "DisabledRHIBackends": ["metal"] - + } } From 79ba6c0ecff130ea498a5ebb61cb09caccc3f764 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 25 May 2021 17:00:26 -0500 Subject: [PATCH 127/811] Updating the EngineFinder.cmake for the AutomatedTesting project to use the engines_path key --- AutomatedTesting/EngineFinder.cmake | 51 ++++++++++++++++++----------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/AutomatedTesting/EngineFinder.cmake b/AutomatedTesting/EngineFinder.cmake index 9ff8ce4d66..a7dbf671fd 100644 --- a/AutomatedTesting/EngineFinder.cmake +++ b/AutomatedTesting/EngineFinder.cmake @@ -20,33 +20,46 @@ if(json_error) message(FATAL_ERROR "Unable to read key 'engine' from 'project.json', error: ${json_error}") endif() -# Read the list of paths from ~.o3de/o3de_manifest.json -file(TO_CMAKE_PATH "$ENV{USERPROFILE}" home_directory) # Windows -if((NOT home_directory) OR (NOT EXISTS ${home_directory})) - file(TO_CMAKE_PATH "$ENV{HOME}" home_directory)# Unix +if(DEFINED ENV{USERPROFILE} AND EXISTS $ENV{USERPROFILE}) + set(manifest_path $ENV{USERPROFILE}/.o3de/o3de_manifest.json) # Windows +else() + set(manifest_path $ENV{HOME}/.o3de/o3de_manifest.json) # Unix endif() -if (NOT home_directory) - message(FATAL_ERROR "Cannot find user home directory, the o3de manifest cannot be found") -endif() -# Set manifest path to path in the user home directory -set(manifest_path ${home_directory}/.o3de/o3de_manifest.json) - +# Read the ~/.o3de/o3de_manifest.json file and look through the 'engines_path' object. +# Find a key that matches LY_ENGINE_NAME_TO_USE and use that as the engine path. if(EXISTS ${manifest_path}) file(READ ${manifest_path} manifest_json) - string(JSON engines_count ERROR_VARIABLE json_error LENGTH ${manifest_json} engines) + + string(JSON engines_path_count ERROR_VARIABLE json_error LENGTH ${manifest_json} engines_path) if(json_error) - message(FATAL_ERROR "Unable to read key 'engines' from '${manifest_path}', error: ${json_error}") + message(FATAL_ERROR "Unable to read key 'engines_path' from '${manifest_path}', error: ${json_error}") endif() - math(EXPR engines_count "${engines_count}-1") - foreach(engine_path_index RANGE ${engines_count}) - string(JSON engine_path ERROR_VARIABLE json_error GET ${manifest_json} engines ${engine_path_index}) - if(${json_error}) - message(FATAL_ERROR "Unable to read engines[${engine_path_index}] '${manifest_path}', error: ${json_error}") + string(JSON engines_path_type ERROR_VARIABLE json_error TYPE ${manifest_json} engines_path) + if(json_error OR NOT ${engines_path_type} STREQUAL "OBJECT") + message(FATAL_ERROR "Type of 'engines_path' in '${manifest_path}' is not a JSON Object, error: ${json_error}") + endif() + + math(EXPR engines_path_count "${engines_path_count}-1") + foreach(engine_path_index RANGE ${engines_path_count}) + string(JSON engine_name ERROR_VARIABLE json_error MEMBER ${manifest_json} engines_path ${engine_path_index}) + if(json_error) + message(FATAL_ERROR "Unable to read 'engines_path/${engine_path_index}' from '${manifest_path}', error: ${json_error}") endif() - if(engine_path) - list(APPEND CMAKE_MODULE_PATH "${engine_path}/cmake") + + if(LY_ENGINE_NAME_TO_USE STREQUAL engine_name) + string(JSON engine_path ERROR_VARIABLE json_error GET ${manifest_json} engines_path ${engine_name}) + if(json_error) + message(FATAL_ERROR "Unable to read value from 'engines_path/${engine_name}', error: ${json_error}") + endif() + + if(engine_path) + list(APPEND CMAKE_MODULE_PATH "${engine_path}/cmake") + break() + endif() endif() endforeach() +else() + message(FATAL_ERROR "Engine registration is required before configuring a project. Please register an engine by running 'scripts/o3de register --this-engine'") endif() From 19adbf2f4145ced221d7a2af7c864fac2d5f710b Mon Sep 17 00:00:00 2001 From: pappeste Date: Tue, 25 May 2021 15:12:17 -0700 Subject: [PATCH 128/811] Removing adding runtime dependencies for gems that are in the BUILD_DEPENDENCIES --- Code/Sandbox/Editor/CMakeLists.txt | 5 ++++- .../ComponentEntityEditorPlugin/CMakeLists.txt | 5 ++++- Gems/AWSClientAuth/Code/CMakeLists.txt | 14 ++++++++++---- Gems/AWSMetrics/Code/CMakeLists.txt | 7 +++++-- Gems/AudioEngineWwise/Code/CMakeLists.txt | 3 ++- Gems/AudioSystem/Code/CMakeLists.txt | 3 ++- Gems/GameStateSamples/Code/CMakeLists.txt | 4 ++++ Gems/GradientSignal/Code/CMakeLists.txt | 7 +++---- Gems/GraphCanvas/Code/CMakeLists.txt | 1 - Gems/ImGui/Code/CMakeLists.txt | 2 ++ Gems/LandscapeCanvas/Code/CMakeLists.txt | 15 ++++++++++----- Gems/LyShine/Code/CMakeLists.txt | 12 ++++++++---- Gems/PhysXDebug/Code/CMakeLists.txt | 4 ++-- Gems/SceneProcessing/Code/CMakeLists.txt | 3 ++- Gems/ScriptCanvas/Code/CMakeLists.txt | 7 ++++++- Gems/ScriptCanvasDeveloper/Code/CMakeLists.txt | 1 + Gems/ScriptCanvasPhysics/Code/CMakeLists.txt | 2 ++ Gems/ScriptCanvasTesting/Code/CMakeLists.txt | 5 +++++ Gems/Twitch/Code/CMakeLists.txt | 2 ++ Gems/Vegetation/Code/CMakeLists.txt | 3 ++- cmake/LYWrappers.cmake | 2 -- 21 files changed, 76 insertions(+), 31 deletions(-) diff --git a/Code/Sandbox/Editor/CMakeLists.txt b/Code/Sandbox/Editor/CMakeLists.txt index c62e05f012..843f7cf04d 100644 --- a/Code/Sandbox/Editor/CMakeLists.txt +++ b/Code/Sandbox/Editor/CMakeLists.txt @@ -129,6 +129,8 @@ ly_add_target( 3rdParty::AWSNativeSDK::Core 3rdParty::Qt::Network Legacy::EditorCore + RUNTIME_DEPENDENCIES + Gem::AtomViewportDisplayInfo ) ly_add_source_properties( SOURCES CryEdit.cpp @@ -243,7 +245,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) Legacy::CryCommon AZ::AzToolsFramework Legacy::EditorLib - Gem::LmbrCentral + RUNTIME_DEPENDENCIES + Gem::LmbrCentral ) ly_add_googletest( NAME Legacy::EditorLib.Tests diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt index 66c96eb4c6..80da6e6b2c 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt @@ -36,6 +36,8 @@ ly_add_target( Legacy::CryCommon Legacy::EditorLib Gem::LmbrCentral.Editor + RUNTIME_DEPENDENCIES + Gem::LmbrCentral.Editor ) ly_add_dependencies(Editor ComponentEntityEditorPlugin) @@ -65,7 +67,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzToolsFrameworkTestCommon Legacy::CryCommon Legacy::EditorLib - Gem::LmbrCentral.Editor + RUNTIME_DEPENDENCIES + Gem::LmbrCentral.Editor ) ly_add_googletest( NAME Legacy::ComponentEntityEditorPlugin.Tests diff --git a/Gems/AWSClientAuth/Code/CMakeLists.txt b/Gems/AWSClientAuth/Code/CMakeLists.txt index e9f2a4ed84..a80fb6d532 100644 --- a/Gems/AWSClientAuth/Code/CMakeLists.txt +++ b/Gems/AWSClientAuth/Code/CMakeLists.txt @@ -29,6 +29,9 @@ ly_add_target( Gem::HttpRequestor 3rdParty::AWSNativeSDK::AWSClientAuth 3rdParty::AWSNativeSDK::Core + RUNTIME_DEPENDENCIES + Gem::AWSCore + Gem::HttpRequestor ) ly_add_target( @@ -44,11 +47,13 @@ ly_add_target( AZ::AzCore AZ::AzFramework Gem::AWSCore - Gem::HttpRequestor 3rdParty::AWSNativeSDK::AWSClientAuth 3rdParty::AWSNativeSDK::Core PUBLIC Gem::AWSClientAuth.Static + RUNTIME_DEPENDENCIES + Gem::AWSCore + Gem::HttpRequestor ) ################################################################################ @@ -71,10 +76,11 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) 3rdParty::AWSNativeSDK::AWSClientAuth AZ::AzCore AZ::AzFramework - Gem::AWSCore Gem::AWSClientAuth.Static - AZ::AWSNativeSDKInit - Gem::HttpRequestor + RUNTIUME_DEPENDENCIES + Gem::AWSCore + AZ::AWSNativeSDKInit + Gem::HttpRequestor ) ly_add_googletest( NAME Gem::AWSClientAuth.Tests diff --git a/Gems/AWSMetrics/Code/CMakeLists.txt b/Gems/AWSMetrics/Code/CMakeLists.txt index ffa9ac0408..a67583208e 100644 --- a/Gems/AWSMetrics/Code/CMakeLists.txt +++ b/Gems/AWSMetrics/Code/CMakeLists.txt @@ -23,6 +23,7 @@ ly_add_target( PRIVATE AZ::AzCore AZ::AzFramework + PUBLIC Gem::AWSCore ) @@ -40,8 +41,9 @@ ly_add_target( PRIVATE AZ::AzCore AZ::AzFramework - Gem::AWSCore Gem::AWSMetrics.Static + RUNTIME_DEPENDENCIES + Gem::AWSCore ) ################################################################################ @@ -63,8 +65,9 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest AZ::AzCore AZ::AzFramework - Gem::AWSCore Gem::AWSMetrics.Static + RUNTIME_DEPENDENCIES + Gem::AWSCore ) ly_add_googletest( NAME Gem::AWSMetrics.Tests diff --git a/Gems/AudioEngineWwise/Code/CMakeLists.txt b/Gems/AudioEngineWwise/Code/CMakeLists.txt index 5ea6a6d461..08e3ef53d0 100644 --- a/Gems/AudioEngineWwise/Code/CMakeLists.txt +++ b/Gems/AudioEngineWwise/Code/CMakeLists.txt @@ -205,7 +205,8 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) PUBLIC AZ::AssetBuilderSDK Gem::AudioEngineWwise.Static - Gem::AudioSystem.Editor + RUNTIME_DEPENDENCIES + Gem::AudioSystem.Editor ) ly_add_target( diff --git a/Gems/AudioSystem/Code/CMakeLists.txt b/Gems/AudioSystem/Code/CMakeLists.txt index 8a6f2c417e..83b3393a03 100644 --- a/Gems/AudioSystem/Code/CMakeLists.txt +++ b/Gems/AudioSystem/Code/CMakeLists.txt @@ -101,7 +101,8 @@ if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzFramework Legacy::CryCommon Gem::AudioSystem.Static - Gem::LmbrCentral + RUNTIME_DEPENDENCIES + Gem::LmbrCentral ) ly_add_googletest( NAME Gem::AudioSystem.Tests diff --git a/Gems/GameStateSamples/Code/CMakeLists.txt b/Gems/GameStateSamples/Code/CMakeLists.txt index e3ebc25016..2a7a2cd3ba 100644 --- a/Gems/GameStateSamples/Code/CMakeLists.txt +++ b/Gems/GameStateSamples/Code/CMakeLists.txt @@ -44,4 +44,8 @@ ly_add_target( AZ::AzFramework Gem::LmbrCentral Gem::GameStateSamples.Headers + RUNTIME_DEPENDENCIES + Gem::GameState + Gem::LocalUser + Gem::LmbrCentral ) diff --git a/Gems/GradientSignal/Code/CMakeLists.txt b/Gems/GradientSignal/Code/CMakeLists.txt index f7f8571beb..bb90f6a9af 100644 --- a/Gems/GradientSignal/Code/CMakeLists.txt +++ b/Gems/GradientSignal/Code/CMakeLists.txt @@ -44,7 +44,6 @@ ly_add_target( Gem::ImageProcessingAtom.Headers # Atom/ImageProcessing/PixelFormats.h is part of a header in Includes RUNTIME_DEPENDENCIES Gem::LmbrCentral - Gem::SurfaceData ) if(PAL_TRAIT_BUILD_HOST_TOOLS) @@ -67,10 +66,11 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) 3rdParty::Qt::Widgets Legacy::CryCommon AZ::AzToolsFramework - Gem::LmbrCentral.Editor - Gem::SurfaceData AZ::AssetBuilderSDK Gem::GradientSignal.Static + Gem::SurfaceData + RUNTIME_DEPENDENCIES + Gem::LmbrCentral.Editor ) ly_add_target( @@ -89,7 +89,6 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::GradientSignal.Editor.Static RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor - Gem::SurfaceData.Editor ) endif() diff --git a/Gems/GraphCanvas/Code/CMakeLists.txt b/Gems/GraphCanvas/Code/CMakeLists.txt index 683b0e4bdf..869d981730 100644 --- a/Gems/GraphCanvas/Code/CMakeLists.txt +++ b/Gems/GraphCanvas/Code/CMakeLists.txt @@ -51,7 +51,6 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME GraphCanvas.Editor GEM_MODULE - NAMESPACE Gem AUTOMOC AUTORCC diff --git a/Gems/ImGui/Code/CMakeLists.txt b/Gems/ImGui/Code/CMakeLists.txt index 0751c5825b..16dad0bfd3 100644 --- a/Gems/ImGui/Code/CMakeLists.txt +++ b/Gems/ImGui/Code/CMakeLists.txt @@ -53,6 +53,8 @@ ly_add_target( PUBLIC Gem::ImGui.imguilib Legacy::CryCommon + RUNTIME_DEPENDENCIES + Gem::ImGui.imguilib ) ly_add_target( diff --git a/Gems/LandscapeCanvas/Code/CMakeLists.txt b/Gems/LandscapeCanvas/Code/CMakeLists.txt index 497c83845f..c82225560e 100644 --- a/Gems/LandscapeCanvas/Code/CMakeLists.txt +++ b/Gems/LandscapeCanvas/Code/CMakeLists.txt @@ -35,16 +35,21 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::CryCommon Legacy::Editor.Headers Legacy::EditorCommon - Gem::LmbrCentral.Editor - Gem::GraphCanvasWidgets Gem::GraphModel.Editor.Static Gem::GradientSignal.Editor Gem::SurfaceData.Editor Gem::Vegetation.Editor + Gem::LmbrCentral.Editor + PUBLIC + Gem::GraphCanvasWidgets + RUNTIME_DEPENDENCIES + Gem::GradientSignal.Editor + Gem::SurfaceData.Editor + Gem::Vegetation.Editor + Gem::LmbrCentral.Editor ) ly_add_target( NAME LandscapeCanvas.Editor GEM_MODULE - NAMESPACE Gem FILES_CMAKE landscapecanvas_editor_files.cmake @@ -61,7 +66,6 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AzCore AZ::AzToolsFramework Legacy::Editor.Headers - Gem::GraphCanvasWidgets Gem::GraphModel.Editor.Static Gem::LandscapeCanvas.Editor.Static RUNTIME_DEPENDENCIES @@ -97,9 +101,10 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest AZ::AzFramework AZ::AzToolsFramework - Gem::GraphCanvasWidgets Gem::GraphModel.Editor.Static Gem::LandscapeCanvas.Editor.Static + RUNTIME_DEPENDENCIES + Gem::GraphCanvasWidgets ) ly_add_googletest( NAME Gem::LandscapeCanvas.Editor.Tests diff --git a/Gems/LyShine/Code/CMakeLists.txt b/Gems/LyShine/Code/CMakeLists.txt index d9f011750e..4237434abd 100644 --- a/Gems/LyShine/Code/CMakeLists.txt +++ b/Gems/LyShine/Code/CMakeLists.txt @@ -92,6 +92,8 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Gem::Atom_RPI.Public Gem::Atom_Utils.Static Gem::Atom_Bootstrap.Headers + RUNTIME_DEPENDENCIES + Gem::TextureAtlas ) ly_add_target( @@ -143,8 +145,9 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest Gem::LyShine.Static Legacy::CryCommon - Gem::LmbrCentral - Gem::TextureAtlas + RUNTIME_DEPENDENCIES + Gem::LmbrCentral + Gem::TextureAtlas ) ly_add_googletest( NAME Gem::LyShine.Tests @@ -173,9 +176,10 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest Legacy::CryCommon AZ::AssetBuilderSDK - Gem::LmbrCentral.Editor - Gem::TextureAtlas Gem::LyShine.Editor.Static + RUNTIME_DEPENDENCIES + Gem::LmbrCentral.Editor + Gem::TextureAtlas ) ly_add_googletest( NAME Gem::LyShine.Editor.Tests diff --git a/Gems/PhysXDebug/Code/CMakeLists.txt b/Gems/PhysXDebug/Code/CMakeLists.txt index f198f6f26e..e7d624fe99 100644 --- a/Gems/PhysXDebug/Code/CMakeLists.txt +++ b/Gems/PhysXDebug/Code/CMakeLists.txt @@ -66,9 +66,9 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::CryCommon Legacy::Editor.Headers AZ::AzToolsFramework - Gem::PhysX + Gem::PhysX.Editor Gem::ImGui.imguilib - Gem::ImGui + Gem::ImGui.Editor RUNTIME_DEPENDENCIES Gem::PhysX.Editor Gem::ImGui.Editor diff --git a/Gems/SceneProcessing/Code/CMakeLists.txt b/Gems/SceneProcessing/Code/CMakeLists.txt index 67124a74d5..9af46aaa20 100644 --- a/Gems/SceneProcessing/Code/CMakeLists.txt +++ b/Gems/SceneProcessing/Code/CMakeLists.txt @@ -84,7 +84,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) BUILD_DEPENDENCIES PRIVATE AZ::AzTest - Gem::SceneProcessing + RUNTIME_DEPENDENCIES + Gem::SceneProcessing ) ly_add_googletest( NAME Gem::SceneProcessing.Tests diff --git a/Gems/ScriptCanvas/Code/CMakeLists.txt b/Gems/ScriptCanvas/Code/CMakeLists.txt index 32efa74520..75f1194aa8 100644 --- a/Gems/ScriptCanvas/Code/CMakeLists.txt +++ b/Gems/ScriptCanvas/Code/CMakeLists.txt @@ -81,6 +81,8 @@ ly_add_target( *.ScriptCanvasGrammar.xml,ScriptCanvasGrammar_Source.jinja,$path/$fileprefix.generated.cpp *.ScriptCanvasNodeable.xml,ScriptCanvasNodeable_Header.jinja,$path/$fileprefix.generated.h *.ScriptCanvasNodeable.xml,ScriptCanvasNodeable_Source.jinja,$path/$fileprefix.generated.cpp + RUNTIME_DEPENDENCIES + Gem::ScriptCanvasDebugger ) ly_add_target( @@ -170,6 +172,8 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::ExpressionEvaluation.Static PRIVATE Legacy::EditorCore + RUNTIME_DEPENDENCIES + Gem::ScriptCanvas ) ly_add_target( @@ -228,7 +232,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE AZ::AzTest AZ::AzFramework - Gem::ScriptCanvas + RUNTIME_DEPENDENCIES + Gem::ScriptCanvas ) ly_add_googletest( NAME Gem::ScriptCanvas.Tests diff --git a/Gems/ScriptCanvasDeveloper/Code/CMakeLists.txt b/Gems/ScriptCanvasDeveloper/Code/CMakeLists.txt index d9ce9004d3..5f8c01b70d 100644 --- a/Gems/ScriptCanvasDeveloper/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasDeveloper/Code/CMakeLists.txt @@ -81,5 +81,6 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::GraphCanvasWidgets RUNTIME_DEPENDENCIES Gem::ScriptCanvas.Editor + Gem::GraphCanvasWidgets ) endif() diff --git a/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt b/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt index 23ee6937c7..c75cf1a0db 100644 --- a/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt @@ -36,6 +36,8 @@ ly_add_target( PRIVATE Legacy::CryCommon Gem::ScriptCanvasPhysics.Static + RUNTIME_DEPENDENCIES + Gem::ScriptCanvas ) ################################################################################ diff --git a/Gems/ScriptCanvasTesting/Code/CMakeLists.txt b/Gems/ScriptCanvasTesting/Code/CMakeLists.txt index 639ef114fc..3969a90e8c 100644 --- a/Gems/ScriptCanvasTesting/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasTesting/Code/CMakeLists.txt @@ -45,6 +45,11 @@ ly_add_target( *.ScriptCanvasGrammar.xml,ScriptCanvasGrammar_Source.jinja,$path/$fileprefix.generated.cpp *.ScriptCanvasNodeable.xml,ScriptCanvasNodeable_Header.jinja,$path/$fileprefix.generated.h *.ScriptCanvasNodeable.xml,ScriptCanvasNodeable_Source.jinja,$path/$fileprefix.generated.cpp + RUNTIME_DEPENDENCIES + Gem::ScriptCanvas + Gem::ScriptCanvasEditor + Gem::GraphCanvasWidgets + Gem::ScriptEvents ) ly_add_target( diff --git a/Gems/Twitch/Code/CMakeLists.txt b/Gems/Twitch/Code/CMakeLists.txt index 14d7a41532..20bccf4f52 100644 --- a/Gems/Twitch/Code/CMakeLists.txt +++ b/Gems/Twitch/Code/CMakeLists.txt @@ -29,6 +29,8 @@ ly_add_target( AZ::AzCore Gem::HttpRequestor 3rdParty::AWSNativeSDK::Core + RUNTIME_DEPENDENCIES + Gem::HttpRequestor ) ly_add_target( diff --git a/Gems/Vegetation/Code/CMakeLists.txt b/Gems/Vegetation/Code/CMakeLists.txt index 2dfbd96d60..d7332f5b2e 100644 --- a/Gems/Vegetation/Code/CMakeLists.txt +++ b/Gems/Vegetation/Code/CMakeLists.txt @@ -27,9 +27,10 @@ ly_add_target( PUBLIC Legacy::CryCommon Gem::LmbrCentral.Static - Gem::GradientSignal Gem::SurfaceData.Static Gem::AtomLyIntegration_CommonFeatures.Static + RUNTIME_DEPENDENCIES + Gem::GradientSignal ) ly_add_target( diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index 0e4ba5e214..34eb67c2eb 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -400,8 +400,6 @@ function(ly_delayed_target_link_libraries) target_link_libraries(${target} ${visibility} $) target_compile_definitions(${target} ${visibility} $) target_compile_options(${target} ${visibility} $) - # Add it also as a manual dependency so runtime_dependencies walks it through - ly_add_dependencies(${target} ${item}) else() ly_parse_third_party_dependencies(${item}) target_link_libraries(${target} ${visibility} ${item}) From d536a9438d79a32aa030f3e2ab3b27cb2177d0c7 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 25 May 2021 17:30:47 -0500 Subject: [PATCH 129/811] Revert "Fixes an issue with RUNTIME_DEPENDENCIES including too many targets during install" This reverts commit f972edee010845160615370f66391cbe3c552448. --- cmake/LYWrappers.cmake | 7 ------- cmake/Platform/Common/Install_common.cmake | 2 +- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index 1edd288285..34eb67c2eb 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -379,16 +379,9 @@ function(ly_delayed_target_link_libraries) list(APPEND CMAKE_MODULE_PATH ${additional_module_paths}) get_property(delayed_targets GLOBAL PROPERTY LY_DELAYED_LINK_TARGETS) - foreach(target ${delayed_targets}) get_property(delayed_link GLOBAL PROPERTY LY_DELAYED_LINK_${target}) - - # Cache off the original MANUALLY_ADDED_DEPENDENCIES that were associated with the target - # via previous ly_add_dependencies() calls either explicitly or through RUNTIME_DEPENDENCIES - get_target_property(target_orig_manually_added_dependencies ${target} MANUALLY_ADDED_DEPENDENCIES) - set_property(TARGET ${target} PROPERTY LY_ORIGINAL_MANUALLY_ADDED_DEPENDENCIES ${target_orig_manually_added_dependencies}) - if(delayed_link) cmake_parse_arguments(ly_delayed_target_link_libraries "" "" "${visibilities}" ${delayed_link}) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index b8202a1314..7bf71d7e01 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -125,7 +125,7 @@ function(ly_setup_target ALIAS_TARGET_NAME) endforeach() endif() - get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} LY_ORIGINAL_MANUALLY_ADDED_DEPENDENCIES) + get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") else() From 050574715aed782a39a43cb25cfb5b3b4fed9621 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Tue, 25 May 2021 15:38:13 -0700 Subject: [PATCH 130/811] Address various feedback around RewindableFixedVector --- .../NetworkTime/RewindableFixedVector.h | 46 ++++---- .../NetworkTime/RewindableFixedVector.inl | 104 +++++++----------- 2 files changed, 63 insertions(+), 87 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h index 2e265bdb6f..662013d033 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h @@ -30,12 +30,12 @@ namespace Multiplayer { public: //! Default constructor - RewindableFixedVector() = default; + constexpr RewindableFixedVector() = default; //! Construct and initialize buffer to the provided value //! @param initialValue initial value to set the internal buffer to //! @param count initial value to reserve in the vector - RewindableFixedVector(const TYPE& initialValue, uint32_t count); + constexpr RewindableFixedVector(const TYPE& initialValue, uint32_t count); //! Destructor ~RewindableFixedVector(); @@ -43,86 +43,86 @@ namespace Multiplayer //! Serialization method for fixed vector contained rewindable objects //! @param serializer ISerializer instance to use for serialization //! @return bool true for success, false for serialization failure - bool Serialize(AzNetworking::ISerializer& serializer); + constexpr bool Serialize(AzNetworking::ISerializer& serializer); //! Serialization method for fixed vector contained rewindable objects //! @param serializer ISerializer instance to use for serialization //! @return bool true for success, false for serialization failure - bool Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset &deltaRecord); + constexpr bool Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset &deltaRecord); //! Copies elements from the buffer pointed to by Buffer to this FixedSizeVector instance, vector size will be set to BufferSize //! @param buffer pointer to the buffer to copy //! @param bufferSize number of elements in the buffer to copy //! @return bool true on success, false if the input data was too large to fit in the vector - bool copy_values(const TYPE* buffer, uint32_t bufferSize); + constexpr bool copy_values(const TYPE* buffer, uint32_t bufferSize); //! Copy buffer from the provided vector //! @param RHS instance to copy from - RewindableFixedVector& operator=(const RewindableFixedVector& RHS); + constexpr RewindableFixedVector& operator=(const RewindableFixedVector& rhs); //! Equality operator, returns true if the current instance is equal to RHS - //! @param RHS the FixedSizeVector instance to test for equality against + //! @param rhs the FixedSizeVector instance to test for equality against //! @return bool true if equal, false if not - bool operator ==(const RewindableFixedVector& RHS) const; + constexpr bool operator ==(const RewindableFixedVector& rhs) const; //! Inequality operator, returns true if the current instance is not equal to RHS - //! @param RHS the FixedSizeVector instance to test for inequality against + //! @param rhs the FixedSizeVector instance to test for inequality against //! @return bool false if equal, true if not equal - bool operator !=(const RewindableFixedVector& RHS) const; + constexpr bool operator !=(const RewindableFixedVector& rhs) const; //! Resizes the vector to the requested number of elements, initializing new elements if necessary //! @param count the number of elements to size the vector to //! @return bool true on success - bool resize(uint32_t count); + constexpr bool resize(uint32_t count); //! Resizes the vector to the requested number of elements, without initialization //! @param count the number of elements to size the vector to //! @return bool true on success - bool resize_no_construct(uint32_t count); + constexpr bool resize_no_construct(uint32_t count); //! Resets the vector, returning it to size 0 - void clear(); + constexpr void clear(); //! Const element access //! @param Index index of the element to return //! @return const reference to the requested element - const TYPE& operator[](uint32_t index) const; + constexpr const TYPE& operator[](uint32_t index) const; //! Non-const element access //! @param Index index of the element to return //! @return non-const reference to the requested element - TYPE& operator[](uint32_t index); + constexpr TYPE& operator[](uint32_t index); //! Pushes a new element to the back of the vector //! @param Value value to append to the back of this vector //! @return boolean true on success, false if the vector was full - bool push_back(const TYPE& value); + constexpr bool push_back(const TYPE& value); //! Pops the last element off the vector, decreasing the vector's size by one //! @return bool true on success, false if the vector was empty - bool pop_back(); + constexpr bool pop_back(); //! Returns if the vector is empty //! @return bool true on empty, false if the vector contains valid elements - bool empty() const; + constexpr bool empty() const; //! Gets the last element of the vector - const TYPE& back() const; + constexpr const TYPE& back() const; //! Gets the size of the vector - uint32_t size() const; + constexpr uint32_t size() const; typedef const RewindableObject* const_iterator; const_iterator begin() const { return m_container.cbegin(); } const_iterator end() const { return m_container.cend(); } typedef RewindableObject* iterator; - iterator begin() { return m_container.begin(); } - iterator end() { return m_container.end(); } + constexpr iterator begin() { return m_container.begin(); } + constexpr iterator end() { return m_container.end(); } private: AZStd::fixed_vector, SIZE> m_container; // Synchronized value for vector size, prefer using size() locally which checks m_container.size() - RewindableObject m_size; + RewindableObject m_serializedSize; }; } diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl index f1c4284fa2..c48e534f4f 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl @@ -15,26 +15,22 @@ namespace Multiplayer { template - inline RewindableFixedVector::RewindableFixedVector(const TYPE& initialValue, uint32_t count) + constexpr RewindableFixedVector::RewindableFixedVector(const TYPE& initialValue, uint32_t count) { - resize_no_construct(count); - for (uint32_t idx = 0l idx < size(); ++idx) - { - m_container[idx] = initialValue; - } + m_container.resize(count, initialValue) } template - inline RewindableFixedVector::~RewindableFixedVector() + RewindableFixedVector::~RewindableFixedVector() { ; } template - inline bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer) + constexpr bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer) { - m_size = m_container.size(); - if(!m_size.Serialize(serializer) && !resize(m_size)) + m_serializedSize = m_container.size(); + if(!m_serializedSize.Serialize(serializer) && !resize(m_serializedSize)) { return false; } @@ -51,18 +47,18 @@ namespace Multiplayer } template - inline bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset& deltaRecord) + constexpr bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset& deltaRecord) { if (deltaRecord.GetBit(SIZE)) { - uint32_t origSize = m_size; - m_size = m_container.size(); - if(!m_size.Serialize(serializer) && !resize(m_size)) + uint32_t origSize = m_serializedSize; + m_serializedSize = m_container.size(); + if(!m_serializedSize.Serialize(serializer) && !resize(m_serializedSize)) { return false; } - if ((serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) && origSize == m_size) + if ((serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) && origSize == m_serializedSize) { deltaRecord.SetBit(SIZE, false); } @@ -88,7 +84,7 @@ namespace Multiplayer } template - inline bool RewindableFixedVector::copy_values(const TYPE* buffer, uint32_t bufferSize) + constexpr bool RewindableFixedVector::copy_values(const TYPE* buffer, uint32_t bufferSize) { if (!resize(bufferSize)) { @@ -99,41 +95,35 @@ namespace Multiplayer { m_container[idx] = buffer[idx]; } - + return true; } - template - inline RewindableFixedVector& RewindableFixedVector::operator=(const RewindableFixedVector& RHS) + constexpr RewindableFixedVector& RewindableFixedVector::operator=(const RewindableFixedVector& rhs) { resize(RHS.size()); for (uint32_t idx = 0; idx < size(); ++i) { - m_container[idx] = RHS.m_container[idx]; + m_container[idx] = rhs.m_container[idx]; } return *this; } template - bool RewindableFixedVector::operator ==(const RewindableFixedVector& RHS) const + constexpr bool RewindableFixedVector::operator ==(const RewindableFixedVector& rhs) const { - if (this->size() != RHS.size()) - { - return false; - } - - return m_container == RHS.m_container && m_size == m_size; + return m_container == rhs.m_container && m_serializedSize == rhs.m_serializedSize && size == rhs.size(); } template - bool RewindableFixedVector::operator !=(const RewindableFixedVector& RHS) const + constexpr bool RewindableFixedVector::operator !=(const RewindableFixedVector& rhs) const { - return !(*this == RHS); + return !(*this == rhs); } template - bool RewindableFixedVector::resize(uint32_t count) + constexpr bool RewindableFixedVector::resize(uint32_t count) { if (count > SIZE) { @@ -145,21 +135,13 @@ namespace Multiplayer return true; } - if (count > size()) - { - for (uint32_t idx = size(); idx < count; ++idx) - { - m_container[idx] = TYPE(); - } - } - - m_container.resize(count); + m_container.resize(count, TYPE()); return true; } template - inline bool RewindableFixedVector::resize_no_construct(uint32_t count) + constexpr bool RewindableFixedVector::resize_no_construct(uint32_t count) { if (count > SIZE) { @@ -172,70 +154,64 @@ namespace Multiplayer } template - inline void RewindableFixedVector::clear() + constexpr void RewindableFixedVector::clear() { - resize(0); + m_container.clear(); } template - inline const TYPE& RewindableFixedVector::operator[](uint32_t index) const + constexpr const TYPE& RewindableFixedVector::operator[](uint32_t index) const { AZ_Assert(index < size(), "Out of bounds access (requested %u, reserved %u)", index, size()); return m_container[index].Get(); } template - inline TYPE& RewindableFixedVector::operator[](uint32_t index) + constexpr TYPE& RewindableFixedVector::operator[](uint32_t index) { AZ_Assert(index < size(), "Out of bounds access (requested %u, reserved %u)", index, size()); return m_container[index].Modify(); } template - inline bool RewindableFixedVector::push_back(const TYPE& value) + constexpr bool RewindableFixedVector::push_back(const TYPE& value) { - const uint32_t iBufferSize = size(); - - if (!resize(iBufferSize + 1)) + if (size() < SIZE) { - return false; + m_container.push_back(value); + return true; } - m_container[iBufferSize] = value; - - return true; + return false; } template - inline bool RewindableFixedVector::pop_back() + constexpr bool RewindableFixedVector::pop_back() { - const uint32_t iBufferSize = size(); - - if (iBufferSize <= 0) + if (size() > 0) { - return false; + m_container.pop_back(); + return true; } - resize(iBufferSize - 1); - - return true; + return false; } template - inline bool RewindableFixedVector::empty() const + constexpr bool RewindableFixedVector::empty() const { return m_container.empty(); } template - inline const TYPE& RewindableFixedVector::back() const + constexpr const TYPE& RewindableFixedVector::back() const { AZ_Assert(size() > 0, "Attempted to get back element of an empty RewindableFixedVector"); - return m_container[size() - 1].Get(); + return m_container.back().Get(); } template - inline uint32_t RewindableFixedVector::size() const + constexpr uint32_t RewindableFixedVector::size() const { return m_container.size(); } From f12162a1cfb45a694981ba61776889e68fd6513b Mon Sep 17 00:00:00 2001 From: phistere Date: Tue, 25 May 2021 17:40:09 -0500 Subject: [PATCH 131/811] Update Launcher to find the autoexec.cfg in assets Was looking in the engine root for the autoexec.cfg, changed it to use the project assets path. --- Code/LauncherUnified/Launcher.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Code/LauncherUnified/Launcher.cpp b/Code/LauncherUnified/Launcher.cpp index d0e950c1ad..922397c325 100644 --- a/Code/LauncherUnified/Launcher.cpp +++ b/Code/LauncherUnified/Launcher.cpp @@ -643,7 +643,8 @@ namespace O3DELauncher if (gEnv && gEnv->pConsole) { // Execute autoexec.cfg to load the initial level - AZ::Interface::Get()->ExecuteConfigFile("autoexec.cfg"); + auto autoExecFile = AZ::IO::FixedMaxPath{pathToAssets} / "autoexec.cfg"; + AZ::Interface::Get()->ExecuteConfigFile(autoExecFile.Native()); // Find out if console command file was passed // via --console-command-file=%filename% and execute it From 59254cc9e795d2936fa336e8c9d3585d56d45ffd Mon Sep 17 00:00:00 2001 From: phistere Date: Tue, 25 May 2021 17:40:09 -0500 Subject: [PATCH 132/811] Update Launcher to find the autoexec.cfg in assets Was looking in the engine root for the autoexec.cfg, changed it to use the project assets path. --- Code/LauncherUnified/Launcher.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Code/LauncherUnified/Launcher.cpp b/Code/LauncherUnified/Launcher.cpp index d0e950c1ad..922397c325 100644 --- a/Code/LauncherUnified/Launcher.cpp +++ b/Code/LauncherUnified/Launcher.cpp @@ -643,7 +643,8 @@ namespace O3DELauncher if (gEnv && gEnv->pConsole) { // Execute autoexec.cfg to load the initial level - AZ::Interface::Get()->ExecuteConfigFile("autoexec.cfg"); + auto autoExecFile = AZ::IO::FixedMaxPath{pathToAssets} / "autoexec.cfg"; + AZ::Interface::Get()->ExecuteConfigFile(autoExecFile.Native()); // Find out if console command file was passed // via --console-command-file=%filename% and execute it From 50b9233552570e678e20d899568e5e06ac69ed3c Mon Sep 17 00:00:00 2001 From: puvvadar Date: Tue, 25 May 2021 16:03:53 -0700 Subject: [PATCH 133/811] Cleanup rewind concerns by basing around m_rewindableSize --- .../NetworkTime/RewindableFixedVector.h | 2 +- .../NetworkTime/RewindableFixedVector.inl | 26 ++++++++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h index 662013d033..6d30eabeb8 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h @@ -122,7 +122,7 @@ namespace Multiplayer private: AZStd::fixed_vector, SIZE> m_container; // Synchronized value for vector size, prefer using size() locally which checks m_container.size() - RewindableObject m_serializedSize; + RewindableObject m_rewindableSize; }; } diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl index c48e534f4f..519431793b 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl @@ -17,7 +17,8 @@ namespace Multiplayer template constexpr RewindableFixedVector::RewindableFixedVector(const TYPE& initialValue, uint32_t count) { - m_container.resize(count, initialValue) + m_container.resize(count, initialValue); + m_rewindableSize = m_container.size(); } template @@ -29,8 +30,8 @@ namespace Multiplayer template constexpr bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer) { - m_serializedSize = m_container.size(); - if(!m_serializedSize.Serialize(serializer) && !resize(m_serializedSize)) + m_rewindableSize = m_container.size(); + if(!m_rewindableSize.Serialize(serializer) && !resize(m_rewindableSize)) { return false; } @@ -51,14 +52,14 @@ namespace Multiplayer { if (deltaRecord.GetBit(SIZE)) { - uint32_t origSize = m_serializedSize; - m_serializedSize = m_container.size(); - if(!m_serializedSize.Serialize(serializer) && !resize(m_serializedSize)) + const uint32_t origSize = m_rewindableSize; + m_rewindableSize = m_container.size(); + if(!m_rewindableSize.Serialize(serializer) && !resize(m_rewindableSize)) { return false; } - if ((serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) && origSize == m_serializedSize) + if ((serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) && origSize == m_rewindableSize) { deltaRecord.SetBit(SIZE, false); } @@ -102,7 +103,7 @@ namespace Multiplayer template constexpr RewindableFixedVector& RewindableFixedVector::operator=(const RewindableFixedVector& rhs) { - resize(RHS.size()); + resize(rhs.size()); for (uint32_t idx = 0; idx < size(); ++i) { m_container[idx] = rhs.m_container[idx]; @@ -113,7 +114,7 @@ namespace Multiplayer template constexpr bool RewindableFixedVector::operator ==(const RewindableFixedVector& rhs) const { - return m_container == rhs.m_container && m_serializedSize == rhs.m_serializedSize && size == rhs.size(); + return m_container == rhs.m_container && m_rewindableSize == rhs.m_rewindableSize; } template @@ -136,6 +137,7 @@ namespace Multiplayer } m_container.resize(count, TYPE()); + m_rewindableSize = m_container.size(); return true; } @@ -149,6 +151,7 @@ namespace Multiplayer } m_container.resize_no_construct(count); + m_rewindableSize = m_container.size(); return true; } @@ -157,6 +160,7 @@ namespace Multiplayer constexpr void RewindableFixedVector::clear() { m_container.clear(); + m_rewindableSize = m_container.size(); } template @@ -179,6 +183,7 @@ namespace Multiplayer if (size() < SIZE) { m_container.push_back(value); + m_rewindableSize = m_container.size(); return true; } @@ -191,6 +196,7 @@ namespace Multiplayer if (size() > 0) { m_container.pop_back(); + m_rewindableSize = m_container.size(); return true; } @@ -213,6 +219,6 @@ namespace Multiplayer template constexpr uint32_t RewindableFixedVector::size() const { - return m_container.size(); + return m_rewindableSize; } } From 3bc5ecd9d9d6a87b60771c0a406e9cbd25e67fd7 Mon Sep 17 00:00:00 2001 From: phistere Date: Tue, 25 May 2021 18:24:43 -0500 Subject: [PATCH 134/811] Fixes a divide by zero in Atom FPS Display --- .../Code/Source/AtomViewportDisplayInfoSystemComponent.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp index 672c26a9ab..30841648ae 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp @@ -301,7 +301,10 @@ namespace AZ::Render lastTime = time; } - const double averageFPS = aznumeric_cast(m_fpsHistory.size()) / actualInterval.count(); + const double averageFPS = (actualInterval.count() != 0.0) + ? aznumeric_cast(m_fpsHistory.size()) / actualInterval.count() + : 0.0; + const double frameIntervalSeconds = m_fpsInterval.count(); DrawLine( From 9f46e34cc4daf661f91d8d625200672c2639f1f9 Mon Sep 17 00:00:00 2001 From: phistere Date: Tue, 25 May 2021 18:27:45 -0500 Subject: [PATCH 135/811] Updates to the DefaultProject template Removes raytracingschenesrg.srgi Updates to the root scenesrg.srgi (to match AtomSampleViewer) Adds a SceneSrg.azsli and a README to the template --- .../Template/ShaderLib/README.md | 5 ++++ .../ShaderLib/raytracingscenesrg.srgi | 30 ------------------- .../Template/ShaderLib/scenesrg.srgi | 3 +- .../ShaderResourceGroups/SceneSrg.azsli | 24 +++++++++++++++ Templates/DefaultProject/template.json | 12 ++++++-- 5 files changed, 40 insertions(+), 34 deletions(-) create mode 100644 Templates/DefaultProject/Template/ShaderLib/README.md delete mode 100644 Templates/DefaultProject/Template/ShaderLib/raytracingscenesrg.srgi create mode 100644 Templates/DefaultProject/Template/Shaders/ShaderResourceGroups/SceneSrg.azsli diff --git a/Templates/DefaultProject/Template/ShaderLib/README.md b/Templates/DefaultProject/Template/ShaderLib/README.md new file mode 100644 index 0000000000..034550163d --- /dev/null +++ b/Templates/DefaultProject/Template/ShaderLib/README.md @@ -0,0 +1,5 @@ +# Customizing Shader Resource Groups + +Please read: +*\/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/README.md* +for details on how to customize scenesrg.srgi and viewsrg.srgi. diff --git a/Templates/DefaultProject/Template/ShaderLib/raytracingscenesrg.srgi b/Templates/DefaultProject/Template/ShaderLib/raytracingscenesrg.srgi deleted file mode 100644 index ac27571828..0000000000 --- a/Templates/DefaultProject/Template/ShaderLib/raytracingscenesrg.srgi +++ /dev/null @@ -1,30 +0,0 @@ -// {BEGIN_LICENSE} -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// {END_LICENSE} - -#pragma once - -// Please read README.md for an explanation on why scenesrg.srgi and viewsrg.srgi are -// located in this folder (And how you can optionally customize your own scenesrg.srgi -// and viewsrg.srgi in your game project). - -#include - -partial ShaderResourceGroup RayTracingSceneSrg : SRG_RayTracingScene -{ -/* Intentionally Empty. Helps define the SrgSemantic for RayTracingSceneSrg once.*/ -}; - -#define AZ_COLLECTING_PARTIAL_SRGS -#include -#undef AZ_COLLECTING_PARTIAL_SRGS diff --git a/Templates/DefaultProject/Template/ShaderLib/scenesrg.srgi b/Templates/DefaultProject/Template/ShaderLib/scenesrg.srgi index 9b4803b7dc..0a8cec5963 100644 --- a/Templates/DefaultProject/Template/ShaderLib/scenesrg.srgi +++ b/Templates/DefaultProject/Template/ShaderLib/scenesrg.srgi @@ -26,5 +26,6 @@ partial ShaderResourceGroup SceneSrg : SRG_PerScene }; #define AZ_COLLECTING_PARTIAL_SRGS -#include +#include +#include #undef AZ_COLLECTING_PARTIAL_SRGS diff --git a/Templates/DefaultProject/Template/Shaders/ShaderResourceGroups/SceneSrg.azsli b/Templates/DefaultProject/Template/Shaders/ShaderResourceGroups/SceneSrg.azsli new file mode 100644 index 0000000000..4c962fbbcd --- /dev/null +++ b/Templates/DefaultProject/Template/Shaders/ShaderResourceGroups/SceneSrg.azsli @@ -0,0 +1,24 @@ +// {BEGIN_LICENSE} +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +// {END_LICENSE} + +#ifndef AZ_COLLECTING_PARTIAL_SRGS +#error Do not include this file directly. Include the main .srgi file instead. +#endif + +partial ShaderResourceGroup SceneSrg +{ + float m_time; + float m_deltaTime; +} + diff --git a/Templates/DefaultProject/template.json b/Templates/DefaultProject/template.json index d654c3a969..b79cb67e7d 100644 --- a/Templates/DefaultProject/template.json +++ b/Templates/DefaultProject/template.json @@ -577,10 +577,10 @@ "isOptional": false }, { - "file": "ShaderLib/raytracingscenesrg.srgi", - "origin": "ShaderLib/raytracingscenesrg.srgi", + "file": "ShaderLib/README.md", + "origin": "ShaderLib/README.md", "isTemplated": true, - "isOptional": false + "isOptional": true }, { "file": "ShaderLib/scenesrg.srgi", @@ -600,6 +600,12 @@ "isTemplated": true, "isOptional": false }, + { + "file": "Shaders/ShaderResourceGroups/SceneSrg.azsli", + "origin": "Shaders/ShaderResourceGroups/SceneSrg.azsli", + "isTemplated": true, + "isOptional": false + }, { "file": "autoexec.cfg", "origin": "autoexec.cfg", From d2797c0d15dd9ff1fb9fc86bad7b201f67585b6f Mon Sep 17 00:00:00 2001 From: puvvadar Date: Tue, 25 May 2021 16:40:58 -0700 Subject: [PATCH 136/811] Add RewindableArray and cleanup a bit more of vector --- .../Multiplayer/NetworkTime/RewindableArray.h | 46 ++++++++++++++++ .../NetworkTime/RewindableArray.inl | 53 +++++++++++++++++++ .../NetworkTime/RewindableFixedVector.h | 5 +- .../NetworkTime/RewindableFixedVector.inl | 4 +- .../Source/AutoGen/AutoComponent_Header.jinja | 13 ++++- .../Source/AutoGen/AutoComponent_Source.jinja | 12 ++++- Gems/Multiplayer/Code/multiplayer_files.cmake | 2 + 7 files changed, 127 insertions(+), 8 deletions(-) create mode 100644 Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h create mode 100644 Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.inl diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h new file mode 100644 index 0000000000..36342dffc2 --- /dev/null +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h @@ -0,0 +1,46 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Multiplayer +{ + //! @class RewindableArray + //! @brief Data structure that has a compile-time upper bound, provides array semantics and supports network serialization + template + class RewindableArray + : public AZStd::array, SIZE> + { + public: + //! Serialization method for array contained rewindable objects + //! @param serializer ISerializer instance to use for serialization + //! @return bool true for success, false for serialization failure + bool Serialize(AzNetworking::ISerializer& serializer); + + //! Serialization method for array contained rewindable objects + //! @param serializer ISerializer instance to use for serialization + //! @param deltaRecord Bitset delta record used to detect state change during reconciliation + //! @return bool true for success, false for serialization failure + bool Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset &deltaRecord); + }; +} + +#include diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.inl new file mode 100644 index 0000000000..b3fe18dd79 --- /dev/null +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.inl @@ -0,0 +1,53 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +namespace Multiplayer +{ + template + bool RewindableArray::Serialize(AzNetworking::ISerializer& serializer) + { + for (uint32_t i = 0; i < size(); ++i) + { + if(!this[i].Serialize(serializer)) + { + return false; + } + } + + return serializer.IsValid(); + } + + template + bool RewindableArray::Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset& deltaRecord) + { + for (uint32_t i = 0; i < size(); ++i) + { + if (deltaRecord.GetBit(i)) + { + serializer.ClearTrackedChangesFlag(); + if(!this[i].Serialize(serializer)) + { + return false; + } + + if ((serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) && !serializer.GetTrackedChangesFlag()) + { + deltaRecord.SetBit(i, false); + } + } + } + + return serializer.IsValid(); + } +} diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h index 6d30eabeb8..a33e223a5d 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h @@ -43,12 +43,13 @@ namespace Multiplayer //! Serialization method for fixed vector contained rewindable objects //! @param serializer ISerializer instance to use for serialization //! @return bool true for success, false for serialization failure - constexpr bool Serialize(AzNetworking::ISerializer& serializer); + bool Serialize(AzNetworking::ISerializer& serializer); //! Serialization method for fixed vector contained rewindable objects //! @param serializer ISerializer instance to use for serialization + //! @param deltaRecord Bitset delta record used to detect state change during reconciliation //! @return bool true for success, false for serialization failure - constexpr bool Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset &deltaRecord); + bool Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset &deltaRecord); //! Copies elements from the buffer pointed to by Buffer to this FixedSizeVector instance, vector size will be set to BufferSize //! @param buffer pointer to the buffer to copy diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl index 519431793b..3353877478 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl @@ -28,7 +28,7 @@ namespace Multiplayer } template - constexpr bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer) + bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer) { m_rewindableSize = m_container.size(); if(!m_rewindableSize.Serialize(serializer) && !resize(m_rewindableSize)) @@ -48,7 +48,7 @@ namespace Multiplayer } template - constexpr bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset& deltaRecord) + bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset& deltaRecord) { if (deltaRecord.GetBit(SIZE)) { diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index 071967165f..8cf1eeeb58 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -7,7 +7,11 @@ {% macro DeclareNetworkPropertyGetter(Property) %} {% set PropertyName = UpperFirst(Property.attrib['Name']) %} {% if Property.attrib['Container'] == 'Array' %} -const AZStd::array<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::k_RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> &Get{{ PropertyName }}Array() const; +{% if Property.attrib['IsRewindable']|booleanTrue %} +const RewindableArray<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> &Get{{ PropertyName }}Array() const; +{% else %} +const AZStd::array<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> &Get{{ PropertyName }}Array() const; +{% endif %} const {{ Property.attrib['Type'] }} &Get{{ PropertyName }}(int32_t index) const; {% if Property.attrib['GenerateEventBindings']|booleanTrue %} void {{ PropertyName }}AddEvent(AZ::Event::Handler& handler); @@ -160,7 +164,11 @@ AZ::Event<{{ Property.attrib['Type'] }}> m_{{ LowerFirst(Property.attrib['Name'] {% macro DeclareNetworkPropertyVars(Component, ReplicateFrom, ReplicateTo) %} {% call(Property) AutoComponentMacros.ParseNetworkProperties(Component, ReplicateFrom, ReplicateTo) %} {% if Property.attrib['Container'] == 'Array' %} -AZStd::array<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; +{% if Property.attrib['IsRewindable']|booleanTrue %} +RewindableArray<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; +{% else %} +AZStd::array<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; +{% endif %} {% elif Property.attrib['Container'] == 'Vector' %} {% if Property.attrib['IsRewindable']|booleanTrue %} RewindableFixedVector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}> m_{{ LowerFirst(Property.attrib['Name']) }}; @@ -236,6 +244,7 @@ AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] } #include #include #include +#include #include #include {% call(Include) AutoComponentMacros.ParseIncludes(Component) %} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 1124b0e59c..6b2c5b199a 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -3,7 +3,11 @@ {% macro LowerFirst(text) %}{{ text[0] | lower}}{{ text[1:] }}{% endmacro %} {% macro DefineNetworkPropertyGet(ClassName, Property, Prefix = '') %} {% if Property.attrib['Container'] == 'Array' %} -const AZStd::array<{% if Property.attrib['IsRewindable']|booleanTrue %}Multiplayer::RewindableObject<{% endif %}{{ Property.attrib['Type'] }}{% if Property.attrib['IsRewindable']|booleanTrue %}, Multiplayer::RewindHistorySize>{% endif %}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Array() const +{% if Property.attrib['IsRewindable']|booleanTrue %} +const RewindableArray<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Array() const +{% else %} +const AZStd::array<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Array() const +{% endif %} { return {{ Prefix }}m_{{ LowerFirst(Property.attrib['Name']) }}; } @@ -643,7 +647,11 @@ void {{ ClassName }}::NotifyChanges{{ AutoComponentMacros.GetNetPropertiesSetNam {% macro DefineArchetypePropertyGet(Property, ClassType, ClassName, Prefix = '') %} {% if ClassType == '' or Property.attrib['ExportTo'] == ClassType or Property.attrib['ExportTo'] == "Common" %} {% if Property.attrib['Container'] == 'Array' %} +{% if Property.attrib['IsRewindable']|booleanTrue %} +const RewindableArray<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Array() const +{% else %} const AZStd::array<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Array() const +{% endif %} { return {{ Prefix }}m_{{ LowerFirst(Property.attrib['Name']) }}; } @@ -1474,7 +1482,7 @@ namespace {{ Component.attrib['Namespace'] }} { {% for Property in Component.iter('NetworkProperty') %} {% if Property.attrib['IsRewindable']|booleanTrue %} -{% if Property.attrib['Container'] == 'Vector' %} +{% if Property.attrib['Container'] == 'Vector' or Property.attrib['Container'] == 'Array' %} for ( auto& element: m_{{ LowerFirst(Property.attrib['Name']) }}) { element.SetOwningConnectionId(connectionId); diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index 856e4893a4..1cfef93240 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -33,6 +33,8 @@ set(FILES Include/Multiplayer/NetworkInput/IMultiplayerComponentInput.h Include/Multiplayer/NetworkInput/NetworkInput.h Include/Multiplayer/NetworkTime/INetworkTime.h + Include/Multiplayer/NetworkTime/RewindableArray.h + Include/Multiplayer/NetworkTime/RewindableArray.inl Include/Multiplayer/NetworkTime/RewindableFixedVector.h Include/Multiplayer/NetworkTime/RewindableFixedVector.inl Include/Multiplayer/NetworkTime/RewindableObject.h From 6559b4c5a95420912434da2d4f1bf8d52e8c9287 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Tue, 25 May 2021 16:45:45 -0700 Subject: [PATCH 137/811] Cleanup extraneous includes in Rewindable headers --- .../Include/Multiplayer/NetworkTime/RewindableArray.h | 10 +++------- .../Multiplayer/NetworkTime/RewindableFixedVector.h | 10 +++------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h index 36342dffc2..c9bc3ec8f8 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h @@ -12,14 +12,10 @@ #pragma once -#include -#include -#include -#include -#include #include -#include -#include +#include + +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h index a33e223a5d..9e736ece24 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h @@ -12,14 +12,10 @@ #pragma once -#include -#include -#include -#include -#include #include -#include -#include +#include + +#include namespace Multiplayer { From b256b737a8fc58290fb558eb9f5e842597a9018a Mon Sep 17 00:00:00 2001 From: puvvadar Date: Tue, 25 May 2021 16:52:17 -0700 Subject: [PATCH 138/811] Add IBitset include --- .../Code/Include/Multiplayer/NetworkTime/RewindableArray.h | 1 + .../Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h | 1 + 2 files changed, 2 insertions(+) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h index c9bc3ec8f8..01ae7b1207 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.h @@ -13,6 +13,7 @@ #pragma once #include +#include #include #include diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h index 9e736ece24..06e0655a9c 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h @@ -13,6 +13,7 @@ #pragma once #include +#include #include #include From b5a0df00e1a14ad5f9aefb1063612953b3db8a5d Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Tue, 25 May 2021 17:21:03 -0700 Subject: [PATCH 139/811] Hosts which are not a dedicated server (meaning they also play the game) will spawn a default player for themselves --- .../Source/MultiplayerSystemComponent.cpp | 36 ++++++++++++++----- .../Code/Source/MultiplayerSystemComponent.h | 3 +- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 39bbf6644e..0818f605df 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -438,20 +438,16 @@ namespace Multiplayer m_connAcquiredEvent.Signal(datum); } + // Hosts will spawn a new default player prefab for the user that just connected if (GetAgentType() == MultiplayerAgentType::ClientServer || GetAgentType() == MultiplayerAgentType::DedicatedServer) { - PrefabEntityId playerPrefabEntityId(AZ::Name(static_cast(sv_defaultPlayerSpawnAsset).c_str()), 1); - INetworkEntityManager::EntityList entityList = m_networkEntityManager.CreateEntitiesImmediate(playerPrefabEntityId, NetEntityRole::Authority, AZ::Transform::CreateIdentity()); - - NetworkEntityHandle controlledEntity; - if (entityList.size() > 0) + NetworkEntityHandle controlledEntity = SpawnDefaultPlayerPrefab(); + if (controlledEntity.Exists()) { - controlledEntity = entityList[0]; controlledEntity.GetNetBindComponent()->SetOwningConnectionId(connection->GetConnectionId()); - controlledEntity.GetNetBindComponent()->SetAllowAutonomy(true); } - + if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so { connection->SetUserData(new ServerToClientConnectionData(connection, *this, controlledEntity)); @@ -523,6 +519,17 @@ namespace Multiplayer } } m_agentType = multiplayerType; + + // Spawn the default player for this host since the host is also a player (not a dedicated server) + if (m_agentType == MultiplayerAgentType::ClientServer) + { + NetworkEntityHandle controlledEntity = SpawnDefaultPlayerPrefab(); + if (NetBindComponent* controlledEntityNetBindComponent = controlledEntity.GetNetBindComponent()) + { + controlledEntityNetBindComponent->SetAllowAutonomy(true); + } + } + AZLOG_INFO("Multiplayer operating in %s mode", GetEnumString(m_agentType)); } @@ -630,6 +637,19 @@ namespace Multiplayer } } + NetworkEntityHandle MultiplayerSystemComponent::SpawnDefaultPlayerPrefab() + { + PrefabEntityId playerPrefabEntityId(AZ::Name(static_cast(sv_defaultPlayerSpawnAsset).c_str()), 1); + INetworkEntityManager::EntityList entityList = m_networkEntityManager.CreateEntitiesImmediate(playerPrefabEntityId, NetEntityRole::Authority, AZ::Transform::CreateIdentity()); + + NetworkEntityHandle controlledEntity; + if (entityList.size() > 0) + { + controlledEntity = entityList[0]; + } + return controlledEntity; + } + void host([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { Multiplayer::MultiplayerAgentType serverType = sv_isDedicated ? MultiplayerAgentType::DedicatedServer : MultiplayerAgentType::ClientServer; diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index db83c50fb5..e8e05a9d4c 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -104,7 +104,8 @@ namespace Multiplayer void OnConsoleCommandInvoked(AZStd::string_view command, const AZ::ConsoleCommandContainer& args, AZ::ConsoleFunctorFlags flags, AZ::ConsoleInvokedFrom invokedFrom); void ExecuteConsoleCommandList(AzNetworking::IConnection* connection, const AZStd::fixed_vector& commands); - + NetworkEntityHandle SpawnDefaultPlayerPrefab(); + AZ_CONSOLEFUNC(MultiplayerSystemComponent, DumpStats, AZ::ConsoleFunctorFlags::Null, "Dumps stats for the current multiplayer session"); AzNetworking::INetworkInterface* m_networkInterface = nullptr; From df44f782f2539d37607546a9c13c35eb53bc9ba9 Mon Sep 17 00:00:00 2001 From: pappeste Date: Tue, 25 May 2021 18:11:48 -0700 Subject: [PATCH 140/811] More dependencies fixes --- .../Plugins/ComponentEntityEditorPlugin/CMakeLists.txt | 1 + Gems/AWSClientAuth/Code/CMakeLists.txt | 5 ++++- Gems/AtomLyIntegration/EMotionFXAtom/Code/CMakeLists.txt | 2 ++ Gems/LyShine/Code/CMakeLists.txt | 2 ++ 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt index 80da6e6b2c..5e640e3934 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/CMakeLists.txt @@ -67,6 +67,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzToolsFrameworkTestCommon Legacy::CryCommon Legacy::EditorLib + Gem::LmbrCentral.Editor RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor ) diff --git a/Gems/AWSClientAuth/Code/CMakeLists.txt b/Gems/AWSClientAuth/Code/CMakeLists.txt index a80fb6d532..ea6e765f2b 100644 --- a/Gems/AWSClientAuth/Code/CMakeLists.txt +++ b/Gems/AWSClientAuth/Code/CMakeLists.txt @@ -76,8 +76,11 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) 3rdParty::AWSNativeSDK::AWSClientAuth AZ::AzCore AZ::AzFramework + AZ::AWSNativeSDKInit Gem::AWSClientAuth.Static - RUNTIUME_DEPENDENCIES + Gem::AWSCore + Gem::HttpRequestor + RUNTIME_DEPENDENCIES Gem::AWSCore AZ::AWSNativeSDKInit Gem::HttpRequestor diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/CMakeLists.txt b/Gems/AtomLyIntegration/EMotionFXAtom/Code/CMakeLists.txt index 6492f4f13a..9a9b389227 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/CMakeLists.txt @@ -43,6 +43,8 @@ ly_add_target( PRIVATE AZ::AzCore Gem::EMotionFX_Atom.Static + RUNTIME_DEPENDENCIES + Gem::EMotionFX ) if(PAL_TRAIT_BUILD_HOST_TOOLS) diff --git a/Gems/LyShine/Code/CMakeLists.txt b/Gems/LyShine/Code/CMakeLists.txt index 4237434abd..a8419aa00a 100644 --- a/Gems/LyShine/Code/CMakeLists.txt +++ b/Gems/LyShine/Code/CMakeLists.txt @@ -177,6 +177,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) Legacy::CryCommon AZ::AssetBuilderSDK Gem::LyShine.Editor.Static + Gem::LmbrCentral.Editor + Gem::TextureAtlas RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor Gem::TextureAtlas From 0fc9697e495d13ef8dd45bbc5723b79539336b06 Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Tue, 25 May 2021 19:56:18 -0700 Subject: [PATCH 141/811] Allow Autonomous->Auth properties. Remove the ability of accessing properties Getters from the Component when ReplicateTo is Autonomous; in this case users must be using the controller to Get --- .../Source/AutoGen/AutoComponent_Header.jinja | 5 +++-- .../Source/AutoGen/AutoComponent_Source.jinja | 19 ++++++++++++++++--- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index 71e81b6bfb..aeab2e88e1 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -365,6 +365,8 @@ namespace {{ Component.attrib['Namespace'] }} {{ DeclareNetworkPropertyAccessors(Component, 'Authority', 'Client', true)|indent(8) -}} {{ DeclareNetworkPropertyAccessors(Component, 'Authority', 'Autonomous', false)|indent(8) -}} {{ DeclareNetworkPropertyAccessors(Component, 'Authority', 'Autonomous', true)|indent(8) -}} + {{ DeclareNetworkPropertyAccessors(Component, 'Autonomous', 'Authority', false)|indent(8) -}} + {{ DeclareNetworkPropertyAccessors(Component, 'Autonomous', 'Authority', true)|indent(8) -}} {{ DeclareArchetypePropertyGetters(Component)|indent(8) -}} {{ DeclareRpcInvocations(Component, 'Server', 'Authority', false)|indent(8) -}} {{ DeclareRpcInvocations(Component, 'Server', 'Authority', true)|indent(8) -}} @@ -438,7 +440,7 @@ namespace {{ Component.attrib['Namespace'] }} {% endif %} {{ DeclareNetworkPropertyGetters(Component, 'Authority', 'Server', false)|indent(8) -}} - {{ DeclareNetworkPropertyGetters(Component, 'Authority', 'Autonomous', false)|indent(8) -}} + {{ DeclareNetworkPropertyGetters(Component, 'Autonomous', 'Authority', false)|indent(8) -}} {{ DeclareNetworkPropertyGetters(Component, 'Authority', 'Client', false)|indent(8) -}} {{ DeclareArchetypePropertyGetters(Component)|indent(8) -}} {{ DeclareRpcInvocations(Component, 'Server', 'Authority', false)|indent(8) -}} @@ -463,7 +465,6 @@ namespace {{ Component.attrib['Namespace'] }} //! @} {{ DeclareNetworkPropertyGetters(Component, 'Authority', 'Server', true)|indent(8) -}} - {{ DeclareNetworkPropertyGetters(Component, 'Authority', 'Autonomous', true)|indent(8) -}} {{ DeclareNetworkPropertyGetters(Component, 'Autonomous', 'Authority', true)|indent(8) -}} {{ DeclareNetworkPropertyGetters(Component, 'Authority', 'Client', true)|indent(8) -}} {{ DeclareRpcInvocations(Component, 'Server', 'Authority', true)|indent(8) -}} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 7d5295aabb..3ca4d854bb 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -767,18 +767,33 @@ enum class NetworkProperties return {{ Property.attrib['Type'] }}(); } - {{ ClassName }}* networkComponent = entity->FindComponent<{{ ClassName }}>(); + {{ ClassName }}* networkComponent = entity->FindComponent<{{ ClassName }}>(); if (!networkComponent) { AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }} failed. Entity '%s' (id: %s) is missing {{ ClassName }}, be sure to add {{ ClassName }} to this entity.", entity->GetName().c_str(), id.ToString().c_str()) return {{ Property.attrib['Type'] }}(); } +{% if ReplicateTo == 'Autonomous' %} + // {{ UpperFirst(Property.attrib['Name']) }} is replicated to Automonous; we must go through the controller in order to get this property + {{ ClassName }}Controller* controller = static_cast<{{ ClassName }}Controller*>(networkComponent->GetController()); + if (!controller) + { + AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }} method failed. Entity '%s' (id: %s) {{ ClassName }} is missing the network controller. This property is replicated to autonomous network entities, because this entity doesn't have a controller, it must not be automonous. Please check your network context before attempting to get {{ UpperFirst(Property.attrib['Name']) }}.", entity->GetName().c_str(), id.ToString().c_str()) + return {{ Property.attrib['Type'] }}(); + } +{% if Property.attrib['Container'] == 'Vector' or Property.attrib['Container'] == 'Array' %} + return controller->Get{{ UpperFirst(Property.attrib['Name']) }}(index); +{% else %} + return controller->Get{{ UpperFirst(Property.attrib['Name']) }}(); +{% endif %} +{% else %} {% if Property.attrib['Container'] == 'Vector' or Property.attrib['Container'] == 'Array' %} return networkComponent->Get{{ UpperFirst(Property.attrib['Name']) }}(index); {% else %} return networkComponent->Get{{ UpperFirst(Property.attrib['Name']) }}(); {% endif %} +{% endif %} }) {% if Property.attrib['Container'] == 'Vector' or Property.attrib['Container'] == 'Array' %} ->Method("Set{{ UpperFirst(Property.attrib['Name']) }}", [](AZ::EntityId id, int32_t index, const {{ Property.attrib['Type'] }}& value) -> void @@ -1457,11 +1472,9 @@ namespace {{ Component.attrib['Namespace'] }} } {{ DefineNetworkPropertyGets(Component, 'Authority', 'Server', false, ComponentBaseName)|indent(4) -}} -{{ DefineNetworkPropertyGets(Component, 'Authority', 'Autonomous', false, ComponentBaseName)|indent(4) -}} {{ DefineNetworkPropertyGets(Component, 'Autonomous', 'Authority', false, ComponentBaseName)|indent(4) -}} {{ DefineNetworkPropertyGets(Component, 'Authority', 'Client', false, ComponentBaseName)|indent(4) -}} {{ DefineNetworkPropertyGets(Component, 'Authority', 'Server', true, ComponentBaseName)|indent(4) -}} -{{ DefineNetworkPropertyGets(Component, 'Authority', 'Autonomous', true, ComponentBaseName)|indent(4) -}} {{ DefineNetworkPropertyGets(Component, 'Autonomous', 'Authority', true, ComponentBaseName)|indent(4) -}} {{ DefineNetworkPropertyGets(Component, 'Authority', 'Client', true, ComponentBaseName)|indent(4) }} {{ DefineArchetypePropertyGets(Component, ClassType, ComponentBaseName)|indent(4) -}} From 80f9da800ad7bdea8936622a97ccb78d69673849 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 25 May 2021 22:27:28 -0500 Subject: [PATCH 142/811] insert the scripts/o3de folder to the front of the sys.path for the o3de.py script to allow the o3de package scripts to be imported --- scripts/o3de.py | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/scripts/o3de.py b/scripts/o3de.py index 050d860790..abe1a2990e 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -26,26 +26,19 @@ def add_args(parser, subparsers) -> None: # As o3de.py shares the same name as the o3de package attempting to use a regular # from o3de import line tries to import from the current o3de.py script and not the package - # So the current script directory is removed from the sys.path temporary - script_dir_removed = False - script_abs_dir_removed = False + # So the {current script directory} / 'o3de' is added to the front of the sys.path + script_dir = pathlib.Path(__file__).parent - script_abs_dir = pathlib.Path(__file__).parent.resolve() - while str(script_dir) in sys.path: - script_dir_removed = True - sys.path.remove(str(script_dir)) - while str(script_abs_dir) in sys.path: - script_abs_dir_removed = True - # Remove the absolute path to the script_dir as well - sys.path.remove(str(script_abs_dir.resolve())) + o3de_package_dir = (script_dir / 'o3de').resolve() + + # add the scripts/o3de directory to the front of the sys.path + sys.path.insert(0, str(o3de_package_dir)) from o3de import engine_template, global_project, register, print_registration, get_registration, download, \ add_gem_project, remove_gem_project, sha256 - if script_abs_dir_removed: - sys.path.insert(0, str(script_abs_dir)) - if script_dir_removed: - sys.path.insert(0, str(script_dir)) + # Remove the temporarily added path + sys.path = sys.path[1:] # global_project global_project.add_args(subparsers) From 76c23cda6a02129e575c2beb39359d1894fa8d74 Mon Sep 17 00:00:00 2001 From: balibhan Date: Wed, 26 May 2021 10:17:44 +0530 Subject: [PATCH 143/811] Add all datatype parameters script --- ...vents_AllParamDatatypes_CreationSuccess.py | 210 ++++++++++++++++++ .../scripting/TestSuite_Periodic.py | 30 ++- 2 files changed, 236 insertions(+), 4 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_AllParamDatatypes_CreationSuccess.py diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_AllParamDatatypes_CreationSuccess.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_AllParamDatatypes_CreationSuccess.py new file mode 100644 index 0000000000..4beedec7cf --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_AllParamDatatypes_CreationSuccess.py @@ -0,0 +1,210 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + + +# fmt: off +class Tests(): + new_event_created = ("New Script Event created", "New Script Event not created") + child_event_created = ("Child Event created", "Child Event not created") + params_added = ("New parameters added", "New parameters are not added") + file_saved = ("Script event file saved", "Script event file did not save") + node_found = ("Node found in Script Canvas", "Node not found in Script Canvas") +# fmt: on + + +def ScriptEvents_AllParamDatatypes_CreationSuccess(): + """ + Summary: + Parameters of all types can be created. + + Expected Behavior: + The Method handles the large number of Parameters gracefully. + Parameters of all data types can be successfully created. + Updated ScriptEvent toast appears in Script Canvas. + + Test Steps: + 1) Open Asset Editor + 2) Initially create new Script Event file with one method + 3) Add new method and set name to it + 4) Add new parameters of each type + 5) Verify if parameters are added + 6) Expand the parameter rows + 7) Set different names and datatypes for each parameter + 8) Save file and verify node in SC Node Palette + 9) Close Asset Editor + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + from utils import TestHelper as helper + import pyside_utils + + # Open 3D Engine imports + import azlmbr.legacy.general as general + import azlmbr.editor as editor + import azlmbr.bus as bus + + # Pyside imports + from PySide2 import QtWidgets, QtTest, QtCore + + GENERAL_WAIT = 1.0 # seconds + + FILE_PATH = os.path.join("AutomatedTesting", "TestAssets", "test_file.scriptevents") + N_VAR_TYPES = 10 # Top 10 variable types + TEST_METHOD_NAME = "test_method_name" + + editor_window = pyside_utils.get_editor_main_window() + asset_editor = asset_editor_widget = container = menu_bar = None + sc = node_palette = tree = search_frame = search_box = None + + def initialize_asset_editor_qt_objects(): + nonlocal asset_editor, asset_editor_widget, container, menu_bar + asset_editor = editor_window.findChild(QtWidgets.QDockWidget, "Asset Editor") + asset_editor_widget = asset_editor.findChild(QtWidgets.QWidget, "AssetEditorWindowClass") + container = asset_editor_widget.findChild(QtWidgets.QWidget, "ContainerForRows") + menu_bar = asset_editor_widget.findChild(QtWidgets.QMenuBar) + + def initialize_sc_qt_objects(): + nonlocal sc, node_palette, tree, search_frame, search_box + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + if sc.findChild(QtWidgets.QDockWidget, "NodePalette") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Node Palette", "type": QtWidgets.QAction}) + action.trigger() + node_palette = sc.findChild(QtWidgets.QDockWidget, "NodePalette") + tree = node_palette.findChild(QtWidgets.QTreeView, "treeView") + search_frame = node_palette.findChild(QtWidgets.QFrame, "searchFrame") + search_box = search_frame.findChild(QtWidgets.QLineEdit, "searchFilter") + + def save_file(): + editor.AssetEditorWidgetRequestsBus(bus.Broadcast, "SaveAssetAs", FILE_PATH) + action = pyside_utils.find_child_by_pattern(menu_bar, {"type": QtWidgets.QAction, "iconText": "Save"}) + action.trigger() + # wait till file is saved, to validate that check the text of QLabel at the bottom of the AssetEditor, + # if there are no unsaved changes we will not have any * in the text + label = asset_editor.findChild(QtWidgets.QLabel, "textEdit") + return helper.wait_for_condition(lambda: "*" not in label.text(), 3.0) + + def expand_container_rows(object_name): + children = container.findChildren(QtWidgets.QFrame, object_name) + for child in children: + check_box = child.findChild(QtWidgets.QCheckBox) + if check_box and not check_box.isChecked(): + QtTest.QTest.mouseClick(check_box, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier) + + def node_palette_search(node_name): + search_box.setText(node_name) + helper.wait_for_condition(lambda: search_box.text() == node_name, 1.0) + # Try clicking ENTER in search box multiple times + for _ in range(20): + QtTest.QTest.keyClick(search_box, QtCore.Qt.Key_Enter, QtCore.Qt.NoModifier) + if pyside_utils.find_child_by_pattern(tree, {"text": node_name}) is not None: + break + + def verify_added_params(): + for index in range(N_VAR_TYPES): + if container.findChild(QtWidgets.QFrame, f"[{index}]") is None: + return False + return True + + # 1) Open Asset Editor + general.idle_enable(True) + # Initially close the Asset Editor and then reopen to ensure we don't have any existing assets open + general.close_pane("Asset Editor") + general.open_pane("Asset Editor") + helper.wait_for_condition(lambda: general.is_pane_visible("Asset Editor"), 5.0) + + # 2) Initially create new Script Event file with one method + initialize_asset_editor_qt_objects() + action = pyside_utils.find_child_by_pattern(menu_bar, {"type": QtWidgets.QAction, "text": "Script Events"}) + action.trigger() + result = helper.wait_for_condition( + lambda: container.findChild(QtWidgets.QFrame, "Events") is not None + and container.findChild(QtWidgets.QFrame, "Events").findChild(QtWidgets.QToolButton, "") is not None, + 3 * GENERAL_WAIT, + ) + Report.result(Tests.new_event_created, result) + + # 3) Add new method and set name to it + add_event = container.findChild(QtWidgets.QFrame, "Events").findChild(QtWidgets.QToolButton, "") + add_event.click() + result = helper.wait_for_condition( + lambda: asset_editor_widget.findChild(QtWidgets.QFrame, "EventName") is not None, GENERAL_WAIT + ) + Report.result(Tests.child_event_created, result) + expand_container_rows("EventName") + expand_container_rows("Name") + initialize_asset_editor_qt_objects() + children = container.findChildren(QtWidgets.QFrame, "Name") + for child in children: + line_edit = child.findChild(QtWidgets.QLineEdit) + if line_edit is not None and line_edit.text() == "MethodName": + line_edit.setText(TEST_METHOD_NAME) + + # 4) Add new parameters of each type + helper.wait_for_condition(lambda: container.findChild(QtWidgets.QFrame, "Parameters") is not None, 2.0) + parameters = container.findChild(QtWidgets.QFrame, "Parameters") + add_param = parameters.findChild(QtWidgets.QToolButton, "") + for _ in range(N_VAR_TYPES): + add_param.click() + + # 5) Verify if parameters are added + result = helper.wait_for_condition(verify_added_params, 3.0) + Report.result(Tests.params_added, result) + + # 6) Expand the parameter rows (to render QFrame 'Type' for each param) + for index in range(N_VAR_TYPES): + expand_container_rows(f"[{index}]") + + # 7) Set different names and datatypes for each parameter + expand_container_rows("Name") + children = container.findChildren(QtWidgets.QFrame, "Name") + index = 0 + for child in children: + line_edit = child.findChild(QtWidgets.QLineEdit) + if line_edit is not None and line_edit.text() == "ParameterName": + line_edit.setText(f"param_{index}") + index += 1 + + children = container.findChildren(QtWidgets.QFrame, "Type") + index = 0 + for child in children: + combo_box = child.findChild(QtWidgets.QComboBox) + if combo_box is not None and index < N_VAR_TYPES: + combo_box.setCurrentIndex(index) + index += 1 + + # 8) Save file and verify node in SC Node Palette + Report.result(Tests.file_saved, save_file()) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + initialize_sc_qt_objects() + node_palette_search(TEST_METHOD_NAME) + get_node_index = lambda: pyside_utils.find_child_by_pattern(tree, {"text": TEST_METHOD_NAME}) is not None + result = helper.wait_for_condition(get_node_index, 2.0) + Report.result(Tests.node_found, result) + + # 9) Close Asset Editor + general.close_pane("Asset Editor") + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(ScriptEvents_AllParamDatatypes_CreationSuccess) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py index 85d0b4523f..91d6b3e53e 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py @@ -113,10 +113,6 @@ class TestAutomation(TestAutomationBase): from . import Debugger_HappyPath_TargetMultipleGraphs as test_module self._run_test(request, workspace, editor, test_module) - def test_Debugging_TargetMultipleGraphs(self, request, workspace, editor, launcher_platform, project): - from . import Debugging_TargetMultipleGraphs as test_module - self._run_test(request, workspace, editor, test_module) - @pytest.mark.parametrize("level", ["tmp_level"]) def test_Debugger_HappyPath_TargetMultipleEntities(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -317,4 +313,30 @@ class TestScriptCanvasTests(object): auto_test_mode=False, timeout=60, ) + + def test_ScriptEvents_AllParamDatatypes_CreationSuccess(self, request, workspace, editor, launcher_platform): + def teardown(): + file_system.delete( + [os.path.join(workspace.paths.project(), "TestAssets", "test_file.scriptevents")], True, True + ) + request.addfinalizer(teardown) + file_system.delete( + [os.path.join(workspace.paths.project(), "TestAssets", "test_file.scriptevents")], True, True + ) + expected_lines = [ + "Success: New Script Event created", + "Success: Child Event created", + "Success: New parameters added", + "Success: Script event file saved", + "Success: Node found in Script Canvas", + ] + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + editor, + "ScriptEvents_AllParamDatatypes_CreationSuccess.py", + expected_lines, + auto_test_mode=False, + timeout=60, + ) \ No newline at end of file From 59934e6be1f168710dc14781f72708f30b4485bd Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 26 May 2021 00:20:41 -0500 Subject: [PATCH 144/811] Updating the ProjectManager code and scripts with new layout of the o3de package scripts --- .gitignore | 1 + .../Source/GemCatalog/GemModel.cpp | 23 ++-- .../Source/GemCatalog/GemModel.h | 8 +- .../ProjectManager/Source/PythonBindings.cpp | 86 ++++++------- .../ProjectManager/Source/PythonBindings.h | 9 +- scripts/o3de/o3de/manifest.py | 23 ++++ scripts/project_manager/projects.py | 120 +++++++++--------- 7 files changed, 141 insertions(+), 129 deletions(-) diff --git a/.gitignore b/.gitignore index 8a63faa2f1..664680c5bf 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ _savebackup/ TestResults/** *.swatches /imgui.ini +/scripts/project_manager/logs/ diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp index 724a8fa630..df11c4c7a6 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp @@ -33,8 +33,6 @@ namespace O3DE::ProjectManager item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); item->setData(gemInfo.m_name, RoleName); - const QString uuidString = gemInfo.m_uuid.ToString().c_str(); - item->setData(uuidString, RoleUuid); item->setData(gemInfo.m_creator, RoleCreator); item->setData(gemInfo.m_gemOrigin, RoleGemOrigin); item->setData(aznumeric_cast(gemInfo.m_platforms), RolePlatforms); @@ -53,7 +51,7 @@ namespace O3DE::ProjectManager appendRow(item); const QModelIndex modelIndex = index(rowCount()-1, 0); - m_uuidToIndexMap[uuidString] = modelIndex; + m_nameToIndexMap[gemInfo.m_name] = modelIndex; } void GemModel::Clear() @@ -76,11 +74,6 @@ namespace O3DE::ProjectManager return static_cast(modelIndex.data(RoleGemOrigin).toInt()); } - QString GemModel::GetUuidString(const QModelIndex& modelIndex) - { - return modelIndex.data(RoleUuid).toString(); - } - GemInfo::Platforms GemModel::GetPlatforms(const QModelIndex& modelIndex) { return static_cast(modelIndex.data(RolePlatforms).toInt()); @@ -111,10 +104,10 @@ namespace O3DE::ProjectManager return modelIndex.data(RoleDocLink).toString(); } - QModelIndex GemModel::FindIndexByUuidString(const QString& uuidString) const + QModelIndex GemModel::FindIndexByNameString(const QString& nameString) const { - const auto iterator = m_uuidToIndexMap.find(uuidString); - if (iterator != m_uuidToIndexMap.end()) + const auto iterator = m_nameToIndexMap.find(nameString); + if (iterator != m_nameToIndexMap.end()) { return iterator.value(); } @@ -122,11 +115,11 @@ namespace O3DE::ProjectManager return {}; } - void GemModel::FindGemNamesByUuidStrings(QStringList& inOutGemNames) + void GemModel::FindGemNamesByNameStrings(QStringList& inOutGemNames) { for (QString& dependingGemString : inOutGemNames) { - QModelIndex modelIndex = FindIndexByUuidString(dependingGemString); + QModelIndex modelIndex = FindIndexByNameString(dependingGemString); if (modelIndex.isValid()) { dependingGemString = GetName(modelIndex); @@ -147,7 +140,7 @@ namespace O3DE::ProjectManager return {}; } - FindGemNamesByUuidStrings(result); + FindGemNamesByNameStrings(result); return result; } @@ -164,7 +157,7 @@ namespace O3DE::ProjectManager return {}; } - FindGemNamesByUuidStrings(result); + FindGemNamesByNameStrings(result); return result; } diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h index 480f4c74d3..0caa399b58 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h @@ -33,8 +33,8 @@ namespace O3DE::ProjectManager void AddGem(const GemInfo& gemInfo); void Clear(); - QModelIndex FindIndexByUuidString(const QString& uuidString) const; - void FindGemNamesByUuidStrings(QStringList& inOutGemNames); + QModelIndex FindIndexByNameString(const QString& nameString) const; + void FindGemNamesByNameStrings(QStringList& inOutGemNames); QStringList GetDependingGemUuids(const QModelIndex& modelIndex); QStringList GetDependingGemNames(const QModelIndex& modelIndex); QStringList GetConflictingGemUuids(const QModelIndex& modelIndex); @@ -43,7 +43,6 @@ namespace O3DE::ProjectManager static QString GetName(const QModelIndex& modelIndex); static QString GetCreator(const QModelIndex& modelIndex); static GemInfo::GemOrigin GetGemOrigin(const QModelIndex& modelIndex); - static QString GetUuidString(const QModelIndex& modelIndex); static GemInfo::Platforms GetPlatforms(const QModelIndex& modelIndex); static GemInfo::Types GetTypes(const QModelIndex& modelIndex); static QString GetSummary(const QModelIndex& modelIndex); @@ -59,7 +58,6 @@ namespace O3DE::ProjectManager enum UserRole { RoleName = Qt::UserRole, - RoleUuid, RoleCreator, RoleGemOrigin, RolePlatforms, @@ -76,7 +74,7 @@ namespace O3DE::ProjectManager RoleTypes }; - QHash m_uuidToIndexMap; + QHash m_nameToIndexMap; QItemSelectionModel* m_selectionModel = nullptr; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 5b24c8b6e7..efec83bc39 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -283,9 +283,11 @@ namespace O3DE::ProjectManager AZ_Warning("ProjectManagerWindow", result != -1, "Append to sys path failed"); // import required modules - m_register= pybind11::module::import("o3de.register"); + m_register = pybind11::module::import("o3de.register"); m_manifest = pybind11::module::import("o3de.manifest"); m_engineTemplate = pybind11::module::import("o3de.engine_template"); + m_addGemProject = pybind11::module::import("o3de.add_gem_project"); + m_removeGemProject = pybind11::module::import("o3de.remove_gem_project"); return result == 0 && !PyErr_Occurred(); } catch ([[maybe_unused]] const std::exception& e) @@ -331,26 +333,26 @@ namespace O3DE::ProjectManager { EngineInfo engineInfo; bool result = ExecuteWithLock([&] { - pybind11::str enginePath = m_registration.attr("get_this_engine_path")(); + pybind11::str enginePath = m_manifest.attr("get_this_engine_path")(); - auto o3deData = m_registration.attr("load_o3de_manifest")(); + auto o3deData = m_manifest.attr("load_o3de_manifest")(); if (pybind11::isinstance(o3deData)) { - engineInfo.m_path = Py_To_String(enginePath); - engineInfo.m_defaultGemsFolder = Py_To_String(o3deData["default_gems_folder"]); - engineInfo.m_defaultProjectsFolder = Py_To_String(o3deData["default_projects_folder"]); - engineInfo.m_defaultRestrictedFolder = Py_To_String(o3deData["default_restricted_folder"]); - engineInfo.m_defaultTemplatesFolder = Py_To_String(o3deData["default_templates_folder"]); - engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData,"third_party_path",""); + engineInfo.m_path = Py_To_String(enginePath); + engineInfo.m_defaultGemsFolder = Py_To_String(o3deData["default_gems_folder"]); + engineInfo.m_defaultProjectsFolder = Py_To_String(o3deData["default_projects_folder"]); + engineInfo.m_defaultRestrictedFolder = Py_To_String(o3deData["default_restricted_folder"]); + engineInfo.m_defaultTemplatesFolder = Py_To_String(o3deData["default_templates_folder"]); + engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData,"third_party_path",""); } - auto engineData = m_registration.attr("get_engine_json_data")(pybind11::none(), enginePath); + auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath); if (pybind11::isinstance(engineData)) { try { - engineInfo.m_version = Py_To_String_Optional(engineData,"O3DEVersion","0.0.0.0"); - engineInfo.m_name = Py_To_String_Optional(engineData,"engine_name","O3DE"); + engineInfo.m_version = Py_To_String_Optional(engineData,"O3DEVersion","0.0.0.0"); + engineInfo.m_name = Py_To_String_Optional(engineData,"engine_name","O3DE"); } catch ([[maybe_unused]] const std::exception& e) { @@ -365,13 +367,13 @@ namespace O3DE::ProjectManager } else { - return AZ::Success(AZStd::move(engineInfo)); + return AZ::Success(AZStd::move(engineInfo)); } return AZ::Failure(); } - bool PythonBindings::SetEngineInfo(const EngineInfo& engineInfo) + bool PythonBindings::SetEngineInfo(const EngineInfo& engineInfo) { bool result = ExecuteWithLock([&] { pybind11::str enginePath = engineInfo.m_path.toStdString(); @@ -379,17 +381,17 @@ namespace O3DE::ProjectManager pybind11::str defaultGemsFolder = engineInfo.m_defaultGemsFolder.toStdString(); pybind11::str defaultTemplatesFolder = engineInfo.m_defaultTemplatesFolder.toStdString(); - auto registrationResult = m_registration.attr("register")( - enginePath, // engine_path - pybind11::none(), // project_path - pybind11::none(), // gem_path - pybind11::none(), // template_path - pybind11::none(), // restricted_path - pybind11::none(), // repo_uri + auto registrationResult = m_register.attr("register")( + enginePath, // engine_path + pybind11::none(), // project_path + pybind11::none(), // gem_path + pybind11::none(), // template_path + pybind11::none(), // restricted_path + pybind11::none(), // repo_uri pybind11::none(), // default_engines_folder defaultProjectsFolder, - defaultGemsFolder, - defaultTemplatesFolder + defaultGemsFolder, + defaultTemplatesFolder ); if (registrationResult.cast() != 0) @@ -397,13 +399,13 @@ namespace O3DE::ProjectManager result = false; } - auto manifest = m_registration.attr("load_o3de_manifest")(); + auto manifest = m_manifest.attr("load_o3de_manifest")(); if (pybind11::isinstance(manifest)) { try { manifest["third_party_path"] = engineInfo.m_thirdPartyPath.toStdString(); - m_registration.attr("save_o3de_manifest")(manifest); + m_manifest.attr("save_o3de_manifest")(manifest); } catch ([[maybe_unused]] const std::exception& e) { @@ -435,13 +437,13 @@ namespace O3DE::ProjectManager bool result = ExecuteWithLock([&] { // external gems - for (auto path : m_registration.attr("get_gems")()) + for (auto path : m_manifest.attr("get_gems")()) { gems.push_back(GemInfoFromPath(path)); } // gems from the engine - for (auto path : m_registration.attr("get_engine_gems")()) + for (auto path : m_manifest.attr("get_engine_gems")()) { gems.push_back(GemInfoFromPath(path)); } @@ -457,7 +459,7 @@ namespace O3DE::ProjectManager } } - AZ::Outcome PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo) + AZ::Outcome PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo) { ProjectInfo createdProjectInfo; bool result = ExecuteWithLock([&] { @@ -477,7 +479,7 @@ namespace O3DE::ProjectManager } else { - return AZ::Success(AZStd::move(createdProjectInfo)); + return AZ::Success(AZStd::move(createdProjectInfo)); } } @@ -499,7 +501,7 @@ namespace O3DE::ProjectManager GemInfo gemInfo; gemInfo.m_path = Py_To_String(path); - auto data = m_registration.attr("get_gem_json_data")(pybind11::none(), path); + auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path); if (pybind11::isinstance(data)) { try @@ -512,14 +514,6 @@ namespace O3DE::ProjectManager gemInfo.m_summary = Py_To_String_Optional(data, "Summary", ""); gemInfo.m_version = Py_To_String_Optional(data, "Version", ""); - if (data.contains("Dependencies")) - { - for (auto dependency : data["Dependencies"]) - { - const AZ::Uuid uuid = Py_To_String(dependency["Uuid"]); - gemInfo.m_dependingGemUuids.push_back(uuid.ToString().c_str()); - } - } if (data.contains("Tags")) { for (auto tag : data["Tags"]) @@ -543,13 +537,13 @@ namespace O3DE::ProjectManager projectInfo.m_path = Py_To_String(path); projectInfo.m_isNew = false; - auto projectData = m_registration.attr("get_project_json_data")(pybind11::none(), path); + auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path); if (pybind11::isinstance(projectData)) { try { projectInfo.m_projectName = Py_To_String(projectData["project_name"]); - projectInfo.m_displayName = Py_To_String_Optional(projectData,"display_name", projectInfo.m_projectName); + projectInfo.m_displayName = Py_To_String_Optional(projectData,"display_name", projectInfo.m_projectName); } catch ([[maybe_unused]] const std::exception& e) { @@ -566,13 +560,13 @@ namespace O3DE::ProjectManager bool result = ExecuteWithLock([&] { // external projects - for (auto path : m_registration.attr("get_projects")()) + for (auto path : m_manifest.attr("get_projects")()) { projects.push_back(ProjectInfoFromPath(path)); } // projects from the engine - for (auto path : m_registration.attr("get_engine_projects")()) + for (auto path : m_manifest.attr("get_engine_projects")()) { projects.push_back(ProjectInfoFromPath(path)); } @@ -594,7 +588,7 @@ namespace O3DE::ProjectManager pybind11::str pyGemPath = gemPath.toStdString(); pybind11::str pyProjectPath = projectPath.toStdString(); - m_registration.attr("add_gem_to_project")( + m_addGemProject.attr("add_gem_to_project")( pybind11::none(), // gem_name pyGemPath, pybind11::none(), // gem_target @@ -612,7 +606,7 @@ namespace O3DE::ProjectManager pybind11::str pyGemPath = gemPath.toStdString(); pybind11::str pyProjectPath = projectPath.toStdString(); - m_registration.attr("remove_gem_to_project")( + m_removeGemProject.attr("remove_gem_from_project")( pybind11::none(), // gem_name pyGemPath, pybind11::none(), // gem_target @@ -634,7 +628,7 @@ namespace O3DE::ProjectManager ProjectTemplateInfo templateInfo; templateInfo.m_path = Py_To_String(path); - auto data = m_registration.attr("get_template_json_data")(pybind11::none(), path); + auto data = m_manifest.attr("get_template_json_data")(pybind11::none(), path); if (pybind11::isinstance(data)) { try @@ -674,7 +668,7 @@ namespace O3DE::ProjectManager QVector templates; bool result = ExecuteWithLock([&] { - for (auto path : m_registration.attr("get_project_templates")()) + for (auto path : m_manifest.attr("get_project_templates")()) { templates.push_back(ProjectTemplateInfoFromPath(path)); } diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h index 892e13a65b..2dc15bd574 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.h +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -12,7 +12,7 @@ #pragma once #include -#include +#include #include // Qt defines slots, which interferes with the use here. @@ -25,7 +25,7 @@ namespace O3DE::ProjectManager { - class PythonBindings + class PythonBindings : public PythonBindingsInterface::Registrar { public: @@ -66,6 +66,9 @@ namespace O3DE::ProjectManager AZ::IO::FixedMaxPath m_enginePath; pybind11::handle m_engineTemplate; AZStd::recursive_mutex m_lock; - pybind11::handle m_registration; + pybind11::handle m_register; + pybind11::handle m_manifest; + pybind11::handle m_addGemProject; + pybind11::handle m_removeGemProject; }; } diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index bc27d9116c..241f6ecbee 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -322,6 +322,29 @@ def get_all_templates() -> list: templates_data.extend(engine_templates) return templates_data +def get_project_templates(): # temporary until we have a better way to do this... maybe template_type element + project_templates = [] + for template in get_all_templates(): + if 'Project' in template: + project_templates.append(template) + return project_templates + + +def get_gem_templates(): # temporary until we have a better way to do this... maybe template_type element + gem_templates = [] + for template in get_all_templates(): + if 'Gem' in template: + gem_templates.append(template) + return gem_templates + + +def get_generic_templates(): # temporary until we have a better way to do this... maybe template_type element + generic_templates = [] + for template in get_all_templates(): + if 'Project' not in template and 'Gem' not in template: + generic_templates.append(template) + return generic_templates + def get_all_restricted() -> list: engine_restricted = get_engine_restricted() diff --git a/scripts/project_manager/projects.py b/scripts/project_manager/projects.py index e50c8d8a2d..704b7c5f9a 100755 --- a/scripts/project_manager/projects.py +++ b/scripts/project_manager/projects.py @@ -29,10 +29,10 @@ executable_path = '' logger = logging.getLogger() logger.setLevel(logging.INFO) -from o3de import engine_template, registration +from o3de import add_gem_project, cmake, engine_template, manifest, register, remove_gem_project -o3de_folder = registration.get_o3de_folder() -o3de_logs_folder = registration.get_o3de_logs_folder() +o3de_folder = manifest.get_o3de_folder() +o3de_logs_folder = manifest.get_o3de_logs_folder() project_manager_log_file_path = o3de_logs_folder / "project_manager.log" log_file_handler = RotatingFileHandler(filename=project_manager_log_file_path, maxBytes=1024 * 1024, backupCount=1) formatter = logging.Formatter('%(asctime)s | %(levelname)s : %(message)s') @@ -123,7 +123,7 @@ class ProjectManagerDialog(QObject): super(ProjectManagerDialog, self).__init__(parent) self.ui_path = (pathlib.Path(__file__).parent / 'ui').resolve() - self.home_folder = registration.get_home_folder() + self.home_folder = manifest.get_home_folder() self.log_display = None self.dialog_logger = DialogLogger(self) @@ -201,7 +201,7 @@ class ProjectManagerDialog(QObject): self.dialog.show() def refresh_project_list(self) -> None: - projects = registration.get_all_projects() + projects = manifest.get_all_projects() self.project_list_box.clear() for this_slot in range(len(projects)): display_name = f'{os.path.basename(os.path.normpath(projects[this_slot]))} ({projects[this_slot]})' @@ -255,7 +255,7 @@ class ProjectManagerDialog(QObject): return self.project_list_box.itemData(self.project_list_box.currentIndex(), Qt.ToolTipRole) def get_selected_project_name(self) -> str: - project_data = registration.get_project_data(project_path=self.get_selected_project_path()) + project_data = manifest.get_project_json_data(project_path=self.get_selected_project_path()) return project_data['project_name'] def create_project_handler(self): @@ -297,7 +297,7 @@ class ProjectManagerDialog(QObject): return folder_dialog = QFileDialog(self.dialog, "Select a Folder and Enter a New Project Name", - registration.get_o3de_projects_folder().as_posix()) + manifest.get_o3de_projects_folder().as_posix()) folder_dialog.setFileMode(QFileDialog.AnyFile) folder_dialog.setOptions(QFileDialog.ShowDirsOnly) project_count = 0 @@ -313,7 +313,7 @@ class ProjectManagerDialog(QObject): if engine_template.create_project(project_path=project_folder[0], template_path=project_template_path) == 0: # Success - registration.register(project_path=project_folder[0]) + register.register(project_path=project_folder[0]) self.refresh_project_list() msg_box = QMessageBox(parent=self.dialog) msg_box.setWindowTitle("O3DE") @@ -359,7 +359,7 @@ class ProjectManagerDialog(QObject): return folder_dialog = QFileDialog(self.dialog, "Select a Folder and Enter a New Gem Name", - registration.get_o3de_gems_folder().as_posix()) + manifest.get_o3de_gems_folder().as_posix()) folder_dialog.setFileMode(QFileDialog.AnyFile) folder_dialog.setOptions(QFileDialog.ShowDirsOnly) gem_count = 0 @@ -375,7 +375,7 @@ class ProjectManagerDialog(QObject): if engine_template.create_gem(gem_path=gem_folder[0], template_path=gem_template_path) == 0: # Success - registration.register(gem_path=gem_folder[0]) + register.register(gem_path=gem_folder[0]) msg_box = QMessageBox(parent=self.dialog) msg_box.setWindowTitle("O3DE") msg_box.setText(f"Gem {gem_folder[0]} created.") @@ -391,13 +391,13 @@ class ProjectManagerDialog(QObject): source_folder = QFileDialog.getExistingDirectory(self.dialog, "Select a Folder to make a template out of.", - registration.get_o3de_folder().as_posix()) + manifest.get_o3de_folder().as_posix()) if not source_folder: return destination_template_folder_dialog = QFileDialog(self.dialog, "Select where the template is to be created and named.", - registration.get_o3de_templates_folder().as_posix()) + manifest.get_o3de_templates_folder().as_posix()) destination_template_folder_dialog.setFileMode(QFileDialog.AnyFile) destination_template_folder_dialog.setOptions(QFileDialog.ShowDirsOnly) destination_folder = None @@ -409,7 +409,7 @@ class ProjectManagerDialog(QObject): if engine_template.create_template(source_path=source_folder, template_path=destination_folder[0]) == 0: # Success - registration.register(template_path=destination_folder[0]) + register.register(template_path=destination_folder[0]) msg_box = QMessageBox(parent=self.dialog) msg_box.setWindowTitle("O3DE") msg_box.setText(f"Template {destination_folder[0]} created.") @@ -453,7 +453,7 @@ class ProjectManagerDialog(QObject): return folder_dialog = QFileDialog(self.dialog, "Select a Folder and Enter a New Gem Name", - registration.get_o3de_gems_folder().as_posix()) + manifest.get_o3de_gems_folder().as_posix()) folder_dialog.setFileMode(QFileDialog.AnyFile) folder_dialog.setOptions(QFileDialog.ShowDirsOnly) gem_count = 0 @@ -482,9 +482,9 @@ class ProjectManagerDialog(QObject): :return: None """ project_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Project Folder", - registration.get_o3de_projects_folder().as_posix()) + manifest.get_o3de_projects_folder().as_posix()) if project_folder: - if registration.register(project_path=project_folder) == 0: + if register.register(project_path=project_folder) == 0: # Success self.refresh_project_list() @@ -501,9 +501,9 @@ class ProjectManagerDialog(QObject): :return: None """ gem_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Gem Folder", - registration.get_o3de_gems_folder().as_posix()) + manifest.get_o3de_gems_folder().as_posix()) if gem_folder: - if registration.register(gem_path=gem_folder) == 0: + if register.register(gem_path=gem_folder) == 0: # Success msg_box = QMessageBox(parent=self.dialog) msg_box.setWindowTitle("O3DE") @@ -518,9 +518,9 @@ class ProjectManagerDialog(QObject): :return: None """ template_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Template Folder", - registration.get_o3de_templates_folder().as_posix()) + manifest.get_o3de_templates_folder().as_posix()) if template_folder: - if registration.register(template_path=template_folder) == 0: + if register.register(template_path=template_folder) == 0: # Success msg_box = QMessageBox(parent=self.dialog) msg_box.setWindowTitle("O3DE") @@ -535,9 +535,9 @@ class ProjectManagerDialog(QObject): :return: None """ restricted_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Restricted Folder", - registration.get_o3de_restricted_folder().as_posix()) + manifest.get_o3de_restricted_folder().as_posix()) if restricted_folder: - if registration.register(restricted_path=restricted_folder) == 0: + if register.register(restricted_path=restricted_folder) == 0: # Success msg_box = QMessageBox(parent=self.dialog) msg_box.setWindowTitle("O3DE") @@ -552,9 +552,9 @@ class ProjectManagerDialog(QObject): :return: None """ project_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Project Folder", - registration.get_o3de_projects_folder().as_posix()) + manifest.get_o3de_projects_folder().as_posix()) if project_folder: - if registration.register(project_path=project_folder, remove=True) == 0: + if register.register(project_path=project_folder, remove=True) == 0: # Success self.refresh_project_list() @@ -571,9 +571,9 @@ class ProjectManagerDialog(QObject): :return: None """ gem_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Gem Folder", - registration.get_o3de_gems_folder().as_posix()) + manifest.get_o3de_gems_folder().as_posix()) if gem_folder: - if registration.register(gem_path=gem_folder, remove=True) == 0: + if register.register(gem_path=gem_folder, remove=True) == 0: # Success msg_box = QMessageBox(parent=self.dialog) msg_box.setWindowTitle("O3DE") @@ -588,9 +588,9 @@ class ProjectManagerDialog(QObject): :return: None """ template_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Template Folder", - registration.get_o3de_templates_folder().as_posix()) + manifest.get_o3de_templates_folder().as_posix()) if template_folder: - if registration.register(template_path=template_folder, remove=True) == 0: + if register.register(template_path=template_folder, remove=True) == 0: # Success msg_box = QMessageBox(parent=self.dialog) msg_box.setWindowTitle("O3DE") @@ -605,9 +605,9 @@ class ProjectManagerDialog(QObject): :return: None """ restricted_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Restricted Folder", - registration.get_o3de_restricted_folder().as_posix()) + manifest.get_o3de_restricted_folder().as_posix()) if restricted_folder: - if registration.register(restricted_path=restricted_folder, remove=True) == 0: + if register.register(restricted_path=restricted_folder, remove=True) == 0: # Success msg_box = QMessageBox(parent=self.dialog) msg_box.setWindowTitle("O3DE") @@ -767,13 +767,13 @@ class ProjectManagerDialog(QObject): return [(self.enabled_gem_targets_list.model().data(item)) for item in selected_items] def add_runtime_project_gem_targets_handler(self) -> None: - gem_paths = registration.get_all_gems() + gem_paths = manifest.get_all_gems() for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): for gem_path in gem_paths: - this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) for this_gem_target in this_gems_targets: if gem_target == this_gem_target: - registration.add_gem_to_project(gem_path=gem_path, + add_gem_project.add_gem_to_project(gem_path=gem_path, gem_target=gem_target, project_path=self.get_selected_project_path(), runtime_dependency=True) @@ -784,13 +784,13 @@ class ProjectManagerDialog(QObject): self.refresh_runtime_project_gem_targets_enabled_list() def remove_runtime_project_gem_targets_handler(self): - gem_paths = registration.get_all_gems() + gem_paths = manifest.get_all_gems() for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): for gem_path in gem_paths: - this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) for this_gem_target in this_gems_targets: if gem_target == this_gem_target: - registration.remove_gem_from_project(gem_path=gem_path, + remove_gem_project.remove_gem_from_project(gem_path=gem_path, gem_target=gem_target, project_path=self.get_selected_project_path(), runtime_dependency=True) @@ -801,13 +801,13 @@ class ProjectManagerDialog(QObject): self.refresh_runtime_project_gem_targets_enabled_list() def add_tool_project_gem_targets_handler(self) -> None: - gem_paths = registration.get_all_gems() + gem_paths = manifest.get_all_gems() for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): for gem_path in gem_paths: - this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) for this_gem_target in this_gems_targets: if gem_target == this_gem_target: - registration.add_gem_to_project(gem_path=gem_path, + add_gem_project.add_gem_to_project(gem_path=gem_path, gem_target=gem_target, project_path=self.get_selected_project_path(), tool_dependency=True) @@ -818,13 +818,13 @@ class ProjectManagerDialog(QObject): self.refresh_tool_project_gem_targets_enabled_list() def remove_tool_project_gem_targets_handler(self): - gem_paths = registration.get_all_gems() + gem_paths = manifest.get_all_gems() for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): for gem_path in gem_paths: - this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) for this_gem_target in this_gems_targets: if gem_target == this_gem_target: - registration.remove_gem_from_project(gem_path=gem_path, + remove_gem_project.remove_gem_from_project(gem_path=gem_path, gem_target=gem_target, project_path=self.get_selected_project_path(), tool_dependency=True) @@ -835,13 +835,13 @@ class ProjectManagerDialog(QObject): self.refresh_tool_project_gem_targets_enabled_list() def add_server_project_gem_targets_handler(self) -> None: - gem_paths = registration.get_all_gems() + gem_paths = manifest.get_all_gems() for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): for gem_path in gem_paths: - this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) for this_gem_target in this_gems_targets: if gem_target == this_gem_target: - registration.add_gem_to_project(gem_path=gem_path, + add_gem_project.add_gem_to_project(gem_path=gem_path, gem_target=gem_target, project_path=self.get_selected_project_path(), server_dependency=True) @@ -852,13 +852,13 @@ class ProjectManagerDialog(QObject): self.refresh_server_project_gem_targets_enabled_list() def remove_server_project_gem_targets_handler(self): - gem_paths = registration.get_all_gems() + gem_paths = manifest.get_all_gems() for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): for gem_path in gem_paths: - this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) for this_gem_target in this_gems_targets: if gem_target == this_gem_target: - registration.remove_gem_from_project(gem_path=gem_path, + remove_gem_project.remove_gem_from_project(gem_path=gem_path, gem_target=gem_target, project_path=self.get_selected_project_path(), server_dependency=True) @@ -870,7 +870,7 @@ class ProjectManagerDialog(QObject): def refresh_runtime_project_gem_targets_enabled_list(self) -> None: enabled_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = registration.get_project_runtime_gem_targets( + enabled_project_gem_targets = cmake.get_project_runtime_gem_targets( project_path=self.get_selected_project_path()) for gem_target in sorted(enabled_project_gem_targets): model_item = QStandardItem(gem_target) @@ -879,9 +879,9 @@ class ProjectManagerDialog(QObject): def refresh_runtime_project_gem_targets_available_list(self) -> None: available_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = registration.get_project_runtime_gem_targets( + enabled_project_gem_targets = cmake.get_project_runtime_gem_targets( project_path=self.get_selected_project_path()) - all_gem_targets = registration.get_all_gem_targets() + all_gem_targets = cmake.get_all_gem_targets() for gem_target in sorted(all_gem_targets): if gem_target not in enabled_project_gem_targets: model_item = QStandardItem(gem_target) @@ -890,7 +890,7 @@ class ProjectManagerDialog(QObject): def refresh_tool_project_gem_targets_enabled_list(self) -> None: enabled_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = registration.get_project_tool_gem_targets( + enabled_project_gem_targets = cmake.get_project_tool_gem_targets( project_path=self.get_selected_project_path()) for gem_target in sorted(enabled_project_gem_targets): model_item = QStandardItem(gem_target) @@ -899,9 +899,9 @@ class ProjectManagerDialog(QObject): def refresh_tool_project_gem_targets_available_list(self) -> None: available_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = registration.get_project_tool_gem_targets( + enabled_project_gem_targets = cmake.get_project_tool_gem_targets( project_path=self.get_selected_project_path()) - all_gem_targets = registration.get_all_gem_targets() + all_gem_targets = cmake.get_all_gem_targets() for gem_target in sorted(all_gem_targets): if gem_target not in enabled_project_gem_targets: model_item = QStandardItem(gem_target) @@ -910,7 +910,7 @@ class ProjectManagerDialog(QObject): def refresh_server_project_gem_targets_enabled_list(self) -> None: enabled_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = registration.get_project_server_gem_targets( + enabled_project_gem_targets = cmake.get_project_server_gem_targets( project_path=self.get_selected_project_path()) for gem_target in sorted(enabled_project_gem_targets): model_item = QStandardItem(gem_target) @@ -919,9 +919,9 @@ class ProjectManagerDialog(QObject): def refresh_server_project_gem_targets_available_list(self) -> None: available_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = registration.get_project_server_gem_targets( + enabled_project_gem_targets = cmake.get_project_server_gem_targets( project_path=self.get_selected_project_path()) - all_gem_targets = registration.get_all_gem_targets() + all_gem_targets = cmake.get_all_gem_targets() for gem_target in sorted(all_gem_targets): if gem_target not in enabled_project_gem_targets: model_item = QStandardItem(gem_target) @@ -930,21 +930,21 @@ class ProjectManagerDialog(QObject): def refresh_create_project_template_list(self) -> None: self.create_project_template_model = QStandardItemModel() - for project_template_path in registration.get_project_templates(): + for project_template_path in manifest.get_project_templates(): model_item = QStandardItem(project_template_path) self.create_project_template_model.appendRow(model_item) self.create_project_template_list.setModel(self.create_project_template_model) def refresh_create_gem_template_list(self) -> None: self.create_gem_template_model = QStandardItemModel() - for gem_template_path in registration.get_gem_templates(): + for gem_template_path in manifest.get_gem_templates(): model_item = QStandardItem(gem_template_path) self.create_gem_template_model.appendRow(model_item) self.create_gem_template_list.setModel(self.create_gem_template_model) def refresh_create_from_template_list(self) -> None: self.create_from_template_model = QStandardItemModel() - for generic_template_path in registration.get_generic_templates(): + for generic_template_path in manifest.get_generic_templates(): model_item = QStandardItem(generic_template_path) self.create_from_template_model.appendRow(model_item) self.create_from_template_list.setModel(self.create_from_template_model) From 40435fcb2e5326bc28cb750aaa3df270ba263ff9 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Tue, 25 May 2021 23:52:19 -0700 Subject: [PATCH 145/811] Added RayTracingMaterialSrg. Added UV buffer to the RayTracingSceneSrg mesh buffers. Added RayTracingSceneUtils and RayTracingMaterialUtils shader includes. --- .../RayTracing/RayTracingMaterialSrg.azsli | 48 ++++ .../RayTracing/RayTracingMaterialUtils.azsli | 69 +++++ .../RayTracing/RayTracingSceneSrg.azsli | 33 ++- .../RayTracing/RayTracingSceneUtils.azsli | 126 +++++++++ .../Atom/Features/SrgSemantics.azsli | 5 + .../diffuseprobegridraytracing.azshader | Bin 79334 -> 79466 bytes ...probegridraytracing_dx12_0.azshadervariant | Bin 34086 -> 34738 bytes ...probegridraytracing_null_0.azshadervariant | Bin 4502 -> 4502 bytes ...obegridraytracing_vulkan_0.azshadervariant | Bin 36232 -> 36332 bytes ...fuseprobegridraytracingclosesthit.azshader | Bin 79344 -> 79476 bytes ...aytracingclosesthit_dx12_0.azshadervariant | Bin 16754 -> 17150 bytes ...aytracingclosesthit_null_0.azshadervariant | Bin 4502 -> 4502 bytes ...tracingclosesthit_vulkan_0.azshadervariant | Bin 9172 -> 9452 bytes ...raytracingcommon_raytracingglobalsrg.azsrg | 24 +- .../diffuseprobegridraytracingmiss.azshader | Bin 79338 -> 79470 bytes ...egridraytracingmiss_dx12_0.azshadervariant | Bin 16838 -> 17222 bytes ...egridraytracingmiss_null_0.azshadervariant | Bin 4502 -> 4502 bytes ...ridraytracingmiss_vulkan_0.azshadervariant | Bin 10364 -> 10364 bytes .../Code/Source/Mesh/MeshFeatureProcessor.cpp | 213 +++++++++++++--- .../RayTracingAccelerationStructurePass.cpp | 4 +- .../RayTracing/RayTracingFeatureProcessor.cpp | 240 ++++++++++++++---- .../RayTracing/RayTracingFeatureProcessor.h | 111 +++++++- .../Code/Source/RayTracing/RayTracingPass.cpp | 11 +- .../Code/Source/RayTracing/RayTracingPass.h | 1 + 24 files changed, 777 insertions(+), 108 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingMaterialSrg.azsli create mode 100644 Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingMaterialUtils.azsli create mode 100644 Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneUtils.azsli diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingMaterialSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingMaterialSrg.azsli new file mode 100644 index 0000000000..40faba24f9 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingMaterialSrg.azsli @@ -0,0 +1,48 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include + +ShaderResourceGroup RayTracingMaterialSrg : SRG_RayTracingMaterial +{ + Sampler LinearSampler + { + AddressU = Wrap; + AddressV = Wrap; + MinFilter = Linear; + MagFilter = Linear; + MipFilter = Linear; + MaxAnisotropy = 16; + }; + + // material info structured buffer + struct MaterialInfo + { + float4 m_baseColor; + float m_metallicFactor; + float m_roughnessFactor; + uint m_textureFlags; + uint m_textureStartIndex; + }; + + // hit shaders can retrieve the MaterialInfo for a mesh hit using: RayTracingMaterialSrg::m_materialInfo[InstanceIndex()] + StructuredBuffer m_materialInfo; + + // texture flag bits indicating if optional textures are present + #define TEXTURE_FLAG_BASECOLOR 1 + #define TEXTURE_FLAG_NORMAL 2 + #define TEXTURE_FLAG_METALLIC 4 + #define TEXTURE_FLAG_ROUGHNESS 8 + + // unbounded array of Material textures + Texture2D m_materialTextures[]; +} \ No newline at end of file diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingMaterialUtils.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingMaterialUtils.azsli new file mode 100644 index 0000000000..d6dd77f4fa --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingMaterialUtils.azsli @@ -0,0 +1,69 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +struct TextureData +{ + float4 m_baseColor; + float3 m_normal; + float m_metallic; + float m_roughness; +}; + +TextureData GetHitTextureData(RayTracingMaterialSrg::MaterialInfo materialInfo, float2 uv) +{ + TextureData textureData = (TextureData)0; + + uint textureIndex = materialInfo.m_textureStartIndex; + + // base color + if (materialInfo.m_textureFlags & TEXTURE_FLAG_BASECOLOR) + { + textureData.m_baseColor = RayTracingMaterialSrg::m_materialTextures[textureIndex++].SampleLevel(RayTracingMaterialSrg::LinearSampler, uv, 0); + } + else + { + textureData.m_baseColor = materialInfo.m_baseColor; + } + + // normal + if (materialInfo.m_textureFlags & TEXTURE_FLAG_NORMAL) + { + textureData.m_normal = RayTracingMaterialSrg::m_materialTextures[textureIndex++].SampleLevel(RayTracingMaterialSrg::LinearSampler, uv, 0); + } + else + { + textureData.m_normal = float3(0.0f, 0.0f, 1.0f); + } + + // metallic + if (materialInfo.m_textureFlags & TEXTURE_FLAG_METALLIC) + { + textureData.m_metallic = RayTracingMaterialSrg::m_materialTextures[textureIndex++].SampleLevel(RayTracingMaterialSrg::LinearSampler, uv, 0); + } + else + { + textureData.m_metallic = materialInfo.m_metallicFactor; + } + + // roughness + if (materialInfo.m_textureFlags & TEXTURE_FLAG_ROUGHNESS) + { + textureData.m_roughness = RayTracingMaterialSrg::m_materialTextures[textureIndex++].SampleLevel(RayTracingMaterialSrg::LinearSampler, uv, 0); + } + else + { + textureData.m_roughness = materialInfo.m_roughnessFactor; + } + + return textureData; +} + \ No newline at end of file diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli index fdf7ba92de..2352f5d09b 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli @@ -136,18 +136,35 @@ ShaderResourceGroup RayTracingSceneSrg : SRG_RayTracingScene uint m_indexOffset; uint m_positionOffset; uint m_normalOffset; + uint m_tangentOffset; + uint m_bitangentOffset; + uint m_uvOffset; + float m_padding0[2]; + float4 m_irradianceColor; float3x3 m_worldInvTranspose; + float m_padding1[1]; + + uint m_bufferFlags; + uint m_bufferStartIndex; }; - + + // hit shaders can retrieve the MeshInfo for a mesh hit using: RayTracingSceneSrg::m_meshInfo[InstanceIndex()] StructuredBuffer m_meshInfo; - // unbounded array of Index, VertexPosition, and VertexNormal buffers - // each mesh has three entries in this array starting at its InstanceIndex() * BUFFER_COUNT_PER_MESH - #define BUFFER_COUNT_PER_MESH 3 - #define MESH_INDEX_BUFFER_OFFSET 0 - #define MESH_POSITION_BUFFER_OFFSET 1 - #define MESH_NORMAL_BUFFER_OFFSET 2 - + // buffer array index offsets for buffers that are always present for each mesh + #define MESH_INDEX_BUFFER_OFFSET 0 + #define MESH_POSITION_BUFFER_OFFSET 1 + #define MESH_NORMAL_BUFFER_OFFSET 2 + #define MESH_TANGENT_BUFFER_OFFSET 3 + #define MESH_BITANGENT_BUFFER_OFFSET 4 + + // buffer flag bits indicating if optional buffers are present + #define MESH_BUFFER_FLAG_UV 1 + + // Unbounded array of mesh stream buffers: + // - Index, Position, Normal, Tangent, and Bitangent stream buffers are always present + // - Optional stream buffers such as UV are indicated in the MeshInfo.m_bufferFlags field + // - Buffers for a particular mesh start at MeshInfo.m_bufferStartIndex ByteAddressBuffer m_meshBuffers[]; } \ No newline at end of file diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneUtils.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneUtils.azsli new file mode 100644 index 0000000000..f858b9a11a --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneUtils.azsli @@ -0,0 +1,126 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +// returns the normalized camera view ray into the scene for this raytracing dispatch thread +float3 GetViewRayDirection(float4x4 viewProjectionInverseMatrix) +{ + float2 pixel = ((float2)DispatchRaysIndex().xy + float2(0.5f, 0.5f)) / (float2)DispatchRaysDimensions(); + float2 ndc = pixel * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f); + return normalize(mul(viewProjectionInverseMatrix, float4(ndc, 0.0f, 1.0f)).xyz); +} + +// returns the vertex indices for the primitive hit by the ray +// Note: usable only in a raytracing Hit shader +uint3 GetHitIndices(RayTracingSceneSrg::MeshInfo meshInfo) +{ + // compute the array index of the index buffer for this mesh in the m_meshBuffers unbounded array + uint meshIndexBufferArrayIndex = meshInfo.m_bufferStartIndex + MESH_INDEX_BUFFER_OFFSET; + + // compute the offset into the index buffer for this primitve of the mesh + uint offsetBytes = meshInfo.m_indexOffset + (PrimitiveIndex() * 12); + + // load the indices for this primitive from the index buffer + return RayTracingSceneSrg::m_meshBuffers[meshIndexBufferArrayIndex].Load3(offsetBytes); +} + +// returns the interpolated vertex data for the primitive hit by the ray +// Note: usable only in a raytracing hit shader +struct VertexData +{ + float3 m_position; + float3 m_normal; + float3 m_tangent; + float3 m_bitangent; + float2 m_uv; +}; + +VertexData GetHitInterpolatedVertexData(RayTracingSceneSrg::MeshInfo meshInfo, float2 builtInBarycentrics) +{ + // retrieve the poly indices + uint3 indices = GetHitIndices(meshInfo); + + // compute barycentrics + float3 barycentrics = float3((1.0f - builtInBarycentrics.x - builtInBarycentrics.y), builtInBarycentrics.x, builtInBarycentrics.y); + + // compute the vertex data using barycentric interpolation + VertexData vertexData = (VertexData)0; + for (uint i = 0; i < 3; ++i) + { + // position + { + // array index of the position buffer for this mesh in the m_meshBuffers unbounded array + uint meshVertexPositionArrayIndex = meshInfo.m_bufferStartIndex + MESH_POSITION_BUFFER_OFFSET; + + // offset into the position buffer for this vertex + uint positionOffset = meshInfo.m_positionOffset + (indices[i] * 12); + + // load the position data + vertexData.m_position += asfloat(RayTracingSceneSrg::m_meshBuffers[meshVertexPositionArrayIndex].Load3(positionOffset)) * barycentrics[i]; + } + + // normal + { + // array index of the normal buffer for this mesh in the m_meshBuffers unbounded array + uint meshVertexNormalArrayIndex = meshInfo.m_bufferStartIndex + MESH_NORMAL_BUFFER_OFFSET; + + // offset into the normal buffer for this vertex + uint normalOffset = meshInfo.m_normalOffset + (indices[i] * 12); + + // load the normal data + vertexData.m_normal += asfloat(RayTracingSceneSrg::m_meshBuffers[meshVertexNormalArrayIndex].Load3(normalOffset)) * barycentrics[i]; + } + + // tangent + { + // array index of the tangent buffer for this mesh in the m_meshBuffers unbounded array + uint meshVertexTangentArrayIndex = meshInfo.m_bufferStartIndex + MESH_TANGENT_BUFFER_OFFSET; + + // offset into the tangent buffer for this vertex + uint tangentOffset = meshInfo.m_tangentOffset + (indices[i] * 12); + + // load the tangent data + vertexData.m_tangent += asfloat(RayTracingSceneSrg::m_meshBuffers[meshVertexTangentArrayIndex].Load3(tangentOffset)) * barycentrics[i]; + } + + // bitangent + { + // array index of the bitangent buffer for this mesh in the m_meshBuffers unbounded array + uint meshVertexBitangentArrayIndex = meshInfo.m_bufferStartIndex + MESH_BITANGENT_BUFFER_OFFSET; + + // offset into the bitangent buffer for this vertex + uint bitangentOffset = meshInfo.m_bitangentOffset + (indices[i] * 12); + + // load the bitangent data + vertexData.m_bitangent += asfloat(RayTracingSceneSrg::m_meshBuffers[meshVertexBitangentArrayIndex].Load3(bitangentOffset)) * barycentrics[i]; + } + + // optional streams begin after MESH_BITANGENT_BUFFER_OFFSET + uint optionalBufferOffset = MESH_BITANGENT_BUFFER_OFFSET + 1; + + // UV + if (meshInfo.m_bufferFlags & MESH_BUFFER_FLAG_UV) + { + // array index of the UV buffer for this mesh in the m_meshBuffers unbounded array + uint meshVertexUVArrayIndex = meshInfo.m_bufferStartIndex + optionalBufferOffset++; + + // offset into the UV buffer for this vertex + uint uvOffset = meshInfo.m_uvOffset + (indices[i] * 8); + + // load the UV data + vertexData.m_uv += asfloat(RayTracingSceneSrg::m_meshBuffers[meshVertexUVArrayIndex].Load2(uvOffset)) * barycentrics[i]; + } + } + + vertexData.m_normal = normalize(vertexData.m_normal); + + return vertexData; +} \ No newline at end of file diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/SrgSemantics.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/SrgSemantics.azsli index c134a9d293..6d1b05d797 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/SrgSemantics.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/SrgSemantics.azsli @@ -64,3 +64,8 @@ ShaderResourceGroupSemantic SRG_RayTracingScene { FrequencyId = 1; }; + +ShaderResourceGroupSemantic SRG_RayTracingMaterial +{ + FrequencyId = 2; +}; diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing.azshader b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing.azshader index 804b534277c99e83211f6276d08f434bc053295d..746ae357ee6493061a828bd02010fab4308b1164 100644 GIT binary patch delta 430 zcmaF%n&s6SmJOP0LhSOBjs?zccCK6<6U6v&)1iup$rEiv7#Su%ob0f^`U|^iQGwb!_^A}19 zIb<`$<35)+Gh>Fzb8!x*?l*6|oftQ7e(;f%9j9TyfOy9^`GF$K<`=(iS#nf93#i<5 e{&>^m?kp{q28e4`PhV`xXwBjG??Z48(18HC4!d;# delta 414 zcmaF$hUM97mJOP0f^71Wjs?zccCK6<6U6v&)1ivZ0c@*SC%?NYHCgsO$L9X)=b0vJ z-jJF+p^|lT?X7&q&8y3z#5mY)mhS$ubB^!igp`Go4Q}#H{`=|5<_UdGteECa4q$WG zyzA#W#>o@+OB_Awc_mZ-3A8dw$RFkN0_lknD5z z+Gp>**7~fqK0BV=g*#t~(|tshUjXgO#ItEiE`=qcI^PF24KU z2?vM=AC{e~-Tj|m7Y?k3AqX;Vgdie#j{v_3;5QvK1}8%hncLJw;}Csn0w72PA#Cv}cL?FWr2j?3fnATE~+aUDI>Zt*jxsp6(~wNBN=O+AR8+O1@2 zc?!;5@^Sy8#Wz>L4HXc)ioB5Jrl=@CjQ8BRq|707k2Rfu$9}?}shJ5gc`bg$_~~8o zGj#DWe-5Hm1m*wTAS+JDj$q3mfn|UnSf9KBTSz+9_Fq&xv)<LDaexYYC&m~{(atme-9PuU zK;#b)ke?0)t{+-t20qoh|=Q_YXkj-OWCI=xHD z=#Gmq;b-(Hr`IUmRXCgeP zn&Ti=^JhD$qdeWICZIS>cR+zW70$#}i#*e%{UlWw1a)>N^AQLcebt{N<01TpPs(7K z9KPjG0Okh0?u}UXNAZke^OwcV4(b)XkpWm&D5?MRz9HXN>`5~T2ZZcY(Wj5d92Y(44od(3^B`)!u^GSlW`Y_J;0*bdvhNhB8 zBm_v4P9;o+W{wVoAA8L?p1x;vcsi8%^{PuBthbVGuCQL^!(m>|OCRl7(`s$9f_RAR z^Ib0pgK8DiOF9!u*w|Ar;`p9geJ?M)adhrp*xYS|#6di7QT8y*J<<^N0c!4ENZ$@c z*PkKJgxK#Elrm*Bo4{6k9#pZn&q^=5b!!l>;;jVT1=?oNo!7ktbm!Ec1>IfVEd<@k zyFhoD)g208^tduUdj=yv#$pZ@`@YykF~N&erSI zTUiV{7Pe&YS{uLC9ulYzu~Okd^&6H;;_gvblJ3m)I%lVW(y8E8e~^Q>WP);-?*aKQI5Oe_#p+kC@3Ssbsy~vyUA<{&vboxe!AOn|2U-6$$ zgK)gjj}Rndf9wgttg)6}wbEWTidEPJL1zZuh6e$(8hvriG$IR(YI&hUDjXHUjkU;| zlVOr<{OP6BPeX)>r^kCPgm8kfjxzSWKnUil8@%3=W`Jv9o*I_=wD)8*Ssv%#EyFqa zCCC*{ei{YYkEe(u`*o>*@@85m?WpeYJNkfSP}@(UOSL=bkU|5qcG95(8d$rF4xIpC5J3EsY; zL%)GHJsq++2y10@Ft^Pp1RV#SLC(x!eiVqD6 z6g=k->bJqpY7Y(z?o-EdroheW4V-YeOJ9i!~H z3rVC%HLK71ZAIFI3R!WhI>dh$(ahy%w5zZAua)Am>>P`~aE~Ol&k>VSGnInlZKX$U z6Zf*deebidgTrx7+_y05q9G|m!L^Fi;A8Vv6y^%E)_yi8KWmjJyO2@d=0n;=X%{G~ zdhnqRVlKkiW9Mm>yDxd+Bgj;6kF*l_Q+H4lp^gmP0V4~Y(kSFAm+7p-@>XQ6DqJ&P zD$H875sX6cB^3&kF-F0pZ+NL*Sm}@cl#sJn;%iV4Twl*NcuxQU=-LzqC1nQ z^?Ia`cl!0bhCM0dmw6!-A+PVezS$){SDvqcidzux5o=r!=xc1=cIQY*)wO3nm#g;n zrBIgf$&o+}&KyxkN%n^;*Rk#CRcOHT%9^(|?!A2I{*gSc!zEUi zoYD{WrEPRytQdRF1wU_LzVMo4&Qz!xTM6(|urJayR|f71c;IKF8>6@7)RbA{rZ zr0i8Ib2oqujVP-EbJX^{_xX&o&z!iZKXQNK{-0_RF=ZwwEjxMhBPmscZ7w?$ze%;@ z+Q9B_NEP>471k{?23isCQ$%c;8kYFAj?YaM#jD&Hg!n0u#wWF#q3EJl}kyJjgUmH66`RQW{`Xlq zk&6cQqbwu}RmJ|8IkI{yR0D2Ml6n0$#Fc0S@_ zxQ3GG;7Pb4MGE!xuLDy)3Mmf??#gQr4^+HP$yZjDTL}?hh6kTqfAidI?5ys6Rc~(T z?KeH|zZFR)geFsE^Nq4eKd!5_TIUJ+r9ZiDYU%8J(0ezNLz4N6xz+DjJxZXvl&AYM z4%IHMJxE(>eB4Wbqf01>EuINmbp|wb_3sX6riX_Is_Ty0s*lZE?;Y4$$AapCr9W57 z>?2VnrD9D_d!D&H{~fZa%xbf?W6P!4l4R);kkF2G2_6~$2}RfOCQ(tK3)X0 zi#}B^TT;tdjxK*v_Z0DF(-fJ&C(xvlAJcA@RGhecD5YZW<-I944{iHOy6wcyM&~}m zwL1@Q?gg54WKWIMC@D4pMyu@uR?=asvht*z2RjLU%n!h(>Ty*UCSQ!Ye1Us`l6c-L zp%v)p`0L#vU9TIuDu8a9N&H5Gd%>#T9p)Va02^3%?5SYVlC9~25wA?i@*%SWPaXu>p;uk@s^>o2mJ#rz3sQa zb1SL+;JJFMkKUv-yh;kG5D%QaTalkHRaSifla{yIU^mMB^7e!PTWcWMzqxaEbV?-t!lHmrSk!{v|YXJ&oS%X)AHm=3z*e`(f#F-vE_7~ zIu|@=+<(eXlfNv_11PKmD7?zCCB>*eLiCmX%30W-{#{~CMxD@z4eKbJ1JDzLg20If5#%%#S;&kR}`TJX=Rm zpwh-$S<8aX0b6}jtak(;m{YKRZD#g-;pX{kHwZVZTAQD~UYK8)BVD^bkAZa1IV63c znCCF#^7~>F)_rc#TJgrb?3A@d*?HOd8`3uyWIGZd7Z73&Q>874ozLi|oeI4i6?wro zyy)>E zF*~Rt_|Dm&FGMW3beWPc6qwK?AFlWo+W%0)lEKrvdA5b#BFxu* zh(oc&fv{s4ha_UzI}-ls0emT#3J}{sfG?GRI2^*jZG6l^|8ZVe&|R{eLlO(@Kd4`F z7}7oF2c2LkSE$H6UO-Ug+z>I?tyg8QQ-aF#=DvA#=5=60N)T|ebEo!Hgi!VbgT;W5 zY%BBz?)CvVFM#!S%&?8m+ggk#&3CUqxqkP-$?lfU=WqHsBq#(x`DXS&2?hBp4AP#~ zWuQ+n9F#s?^lTYD?Lh6~XUi5>qfZHNCs2Ln zQ^Z98X_G;YR>)JF_Qw$Dooy&UGcJ3sI*@T}-qu2}AO9JJm`U{jUcf$dj$(@Lh<5nK z3SMFshg2`KU-smBTTB0~(&tj+b2I336YNzNeE7nbSE6Df!|E?yj`+Gc3Os6k7>1s} z#ugT9f!X9XZ##10ei}gFz3fB<2v2iBYT@>5{sG2gkkrtRij<++2k)m`+&A0DHFDtv zL(;NR9x)OHX$=rdIr}3J)UfpmN-3o?LqooGyz7>8$b>c!*W0^q_2+6Dua(>f2m~z`RP{&BjsmHAkvsw9d+xNa!>&%g zaFKi78mCutr+Cn>>ENk#c6kpH^B$GvWu3_D?avFj#D0;Oug;mWA_QK!<)j_`^Le$5 zL(4ozGsa#gw)oabTl(j>jY|(Pme=<7*6{Kz1w&fXFH^X%6IUtkgqgiOcfee<2tBY5 zaFch`I)Z&U&MoBo%^#puGSV-*pI&G>Hcf+<&Jwr&IIVIf>j6Hwr4gr@6p3Fq(wSFR z9KP)OFT=|4XWQ33y|9k5|DV&h6EYYJoD$Nf>P@Z}^W48H7`gkyY}r?7v-k-o@Z{L_ zPxqx^-L4b3_u^_2W(5JkQZ{zwkAwtAT!Lmr?}f$bqtBv!moO{gXGjUIY*c?eljgKM zW8yktS`4iZjPIuYex}#Q!A8Y3%dv?lpFm9RUy596dE6%ggn_ zNUye877}b7?SGPB4dD7X36|Rw#cRX+m(mbZCvU6>{wpu?iPfr;qwG^LEHpt~>FRav zJoQutEl6R-|68u6hd|y|~~Sd~A38jL!I&PS}5tKjTvC^y95Dm*Qhoc=Wh(8b;VbywCst;<)gdIb`)T zk8r6<2d52iMtQ`=vdu1DnZ5$AR7iWjQ64d?hC31{`-;Y5RTyj%;&oMTn*uvyDk9)J zlNtdLF#K@GNB+6i600&ay$Sz90t(+g?PB`J#%Wt&KeGS4JWRt*(G-OtW+` zxZ`9COQX(0vz$iXd0VP;s+>U#%c=(_fzEQjGZ?p=QC*FF{z|L(=sdV8bFRY zX5SvfH|H(|+*tfGK$)?B+t+7>rd=Y>-=!@N{V9!gb$5@j8iPlZ;i`y5=x9()5`dxL0wvM#gN+5Cl>ZsFZYSE z@_$G;LeD@zCm*%m$BsDXEr(>GnRfl}G?P2=_(1~!qnbEW2X9J`fLn_7mU$*qG3F`I z`bRRzjX?`zph9SVg*vue8Lh(4qKA~&aYz^=7388Nx1Q)WAjI>{ACtQUl;>JIKxJVx zRSlyl2CyW zS;0s`XvrsNjhf;YMd7C*3!zBTscsv`QF<#t`lGV|TqGK)Z7qnG{ak}{mRwKh^W+JY z+MbqDoR%nX5epSmE9zkx^OWxDv9KtXwt*ECbe1ANFPGs#9lP9^YKjYi^dUN~Xshk9 zAAWh%zYqBp5F?3JVWlpdj@*E=AlD^l4P@tL6N~5i`Q^qB+Bz0*C6!Q=lclowXfe8l z4}xu(qO{I|u%L5r8CFR> zc;0)Gkl+|L-SrAL@=Dlce|g#t^1W=k;PQs#b3a!!fK*jh!)`6C3as0DMhyysI)~0U zkFe?c!=k2Mo?d@3BFgUT%l?YsSHLkbmhu0-q`~XIk_I6Qf|>xY?MP^%+5%J!Q{P@P z!$Bn`Xs6HBy618eO}_^3UK0+f-IgwpLT=@>@`e?szeiz`g7t^3h`=H#2BQ)o1$b|< zT&#c~v)wWNAk}S>{Sp4JDte9mKK}1qdXK$|{~tZ-vs> z9G0!9@)I2_x80DFe3|QuZP3PF-3Yeze+;{g$9j3-hRCULU83?Puj5 zutU1uZ^!z-jPoSyw4m{2WK*dle;e!(s`EyQTJ`x*HwF3{=0%ZTmCB!Sbu9z14do^H zeFf*EMhgClP~d``V=-+>BN|k%kOcXeMIx5%P@`T|Im1H|#KVuEboaN7JXz%&0mQU@ z#EUIL=1795CXw_Zs_(!>sVYwy9GJF*;d0a+A}I{PCSr=JW$}2+JS(L}@$q{z z-hzV%Z=@WITT;#;v=+4bA0)b=0V)FNBx61sEF9Y_fql9+r$?cCF^R{0#v1 zTue&I=)On|Cc7+eADrzFKQ{4$QWCVuY8ajF{;rXys=OIbW!mCK&>4ic^iVFgx6_Q2 zuYn4%{WRHaY7J7*@OYrPOUmaa+Z#B3tVPuYR^OyKmJ^F5IdlYOq!@v6LeP`}+5O^= z(G*B2h+vb!=TK^*V<$_BrugCY8XgcO0ZZc9^uKkPM=M9c(TW20KWMcqb&lX;_F)>H z0G`7td8e}VwN4~c!31PZJ))3v9Ik)Wy)qaFEKh~o+B2(%Fh0<0q3aT-E(bE+S?OI5 z2;NXXoErf&*aLiSrVg{hjRnjvq@g4O3&>z*TwwKUsGFQvB1s1Ni)SCcU%U~GTt8s- z{a}Rw;MBu$c3RONsBU!k^sI0=B=QX`uWR#KCXF`$dN!D+n zN+5(*0wMmSc4ZV0l1;~is#ujnKu9r!%C78?OYZHA zEEWMgC9W;1D6>tEc}l{OS()COtoNHJU!~f9MU4~fcLp0mpq;at# zQvA-0LDwOAyx$+Kif+}tG6M!A-En)mJ2Et#xp5FVir|Msn#gtzT@I7*&hgW@EG0Re z{90c|4oeMf#>aMo`!RDs;>`j(dPh z@9$*oUSu4k_Bh}YuJ$ggvG;SOl9lYc|a!GQeVptQ_ z*^%pARvBC(=>koQW5U60*1HF1RRUKu6vRUu0r$4fPkzGS*4gnuMlp+4bt6Ne5vWO& z%hh*u3uN~a?Y>wi<*WM9MeWxB}cq8esLZG!d z8RiYwb$8Zv-mD9no9XG|^N`=MCN&gor5QF;zYl6{A&5v@s2mY#E6YnnlJLB|5nHfN zsa8#493@r!c#37v&$xkN2P4`emx##&YFZ|m-G2<|qg@eui+4j1^zxWdU^UoiurrC2 z9{Mj{Y179HB-gO;1z~z(_9(QM%E&qNYL3RI00}_;9dj^8n`t`Sx(YP@0~!{K%9SsA z(>8rR5FnK@6zV;hUecjcE8Fy#wcX_}8g84JNOr=o!1?Ztk8$jUTg(eEbBy4V5*-m? z8xOPK4B_&G6Wpv>$vN0_$NN7iNw;fT*nWKBpZyKhE6OT;zM(SbZD#{GvMl`H4+4}_ za@^Q%e%39We99pswX>r*E;iC>sPSmky@CY2cURPHYMNopZgJPUZk4HS=f+Wi-Ts8x zt=ehKuRS#620xdccuBJ706&&v|1TC(ZM9WZd7~9#?%n~%y4d3-k?YH7o8hf(YSvr5K?TV%PfG6?x>>g52c4{ZKwqNf=%>KtzVv4G?=|&FgvX}$`JC8o3sE# z6zwH*d{LLJsn?&I7aQrzmjsc_;qxs4e6u!uKoRgg+A`Mb;GZriOg1BSyr zuu*@TMG!*B_ZA%Lg^lKUf;EEfjz=bKaw*R_Yd5LGO1>yWx#DFaw#S@LVu9Tq`J9oKWWosj?* z7UqIk-r3pj=xA8 z$E}~kqxKOm(U@l{o~kMzBKe&itG%PlqUKP2N3KX#dA}VxT;cvQyC`QRFr~~KU`jgI zCzlTaQ&QCeQ|kM4wN()?B|#1_B`ZmzM=xf7`!V|)`mty=CRDHzl18rYcJ1AXNp&6q zQoPL0&<(_XV+1y z)6jv{nZDMy3&>_sq+?r$0?Q7p01m0F{@pZnO%oy_y`)VOk^aGs5|LiN6wJ?_R3(}Cp%XDu@VG4 z44&}00a9nOer&yu3?=4{{BgY5Qnnq}SDf=j@t=4zj!*3J!7sR}q|fH({so`flcaXV zCF@s~{Mp}7?Y6VhXNm)J-s(vc_*57X_g8$9a%ca?@qfoB)--@mEF>FPr#qHb1z$?D z`LV*TVl+;5$AdVm>XS}Q@M0Bs)fkA=Dc6Zr)*kqqC8N4da6T2=zP%JrBMhe>4| z!yszoqq1@!C9A+7>O0}FNFbz$ben*v>9>ybjzg5658dWbZfURIp5ENF>LCD8J3U5? zh06rS!cvBjUVUvA{p`5te^`so9RJ5J73_D`^a}Ry9P0}9hnv7_!wR3uRP>pPH7WR;YY(BUxRA_Yx}Wyac)6%UTR6RH=j4ki1hZaKWf4Pa7V zsZ3q7+FuHV;3H5=VqFA%F@OG%ag^FL^#rfmC%okZhEf*P83!xv7YhQ)moM@D6dP!~ z|JKzf@FPBvLx0o1`-_YvXzDKSb${)@{lJNKny)m*>x(}hpzB!vLR5LBt;6%PofD`w z@9hH&)iMS<$Aaz~?TPhsbfB!UE|rM6W|6q9t>a1A&dSR)$HO!whOza^0|CCrSO^>4 zlk_}yxYWBiD&V?<;!t)je#%(&CUaS0bEv>idN|QhA-Kdg`EoVc0ws3WQdkt7KFG37 z=foC;`Fk^`(f0!5>$=t1k(?u|tnGrB;k9rqBj$M8oV`6D?XYYKF_weR| zWU1BdP)!nrLFM~XK(Zt*o*ys;Bum-|kSsN)%{_z()%O6Q98+Sz6iiAtACqF7b(#mH z;CU3i1wG2~AN4tUR-mawkUj^f7EC7w_sWR#!pGt#Z;_YtCG~AF$BFOp z;o&?=9G5f!S}V?~iFq8ydi=u&r}!kWlVinKYOp#sFEIP1{zBJkssiLVWBVnZ*MI|7 zssU+9DM(AE4>tD6D=GF8ai{NyQTy>wqwugfe5~Z5e!6bTUn`!zhYRJ-a!CW#EV{u0 zD#VPo6F*d~zMJP0%kv-3pmlfH$YU3h-_hd-JRZ2k4<0)27C(Hb$!%#+M+IGtwxZtdQOWpXUw=@h$47O}crb8mhJDuZ$k z$&lN^Do6b=U<?h6`f_Ha{7d)JWsyyZgq#nQ3gYSqiB^e6N>-sRU6sX=m&y?2>^5I zml&L1ctXAdfLU-21Lnu;!=o7(n!8~M=RfW|0a7HB7)v;Vqvv5lWlb2GUwDyx7YOn0 z{u%G@NxCj3j>Y@**X_9I*2b8orkJHQ3D>*^Y72JnGN95uq({4lbLaysd)(8=5zSWO zTY5ZnBAgLV@^NCsQ+=EnV|Ld0RRp6LvU{$lB$8b~%CEKCkaDMte+fUW9`A_z4b;NJ zK9W{i+&0<@Yx&)<9@ulDs=w~Cx~-s1zM^eqoPTErZUI2A(<~+sG=#wQ(JDwZWrzX+81L@O(+b+Y`eXKg@gECAXTbbP3 z;ApEt5S!3Vth;>ovO=!qh8f(5u__eA&(n95?gQZ|7(Tq(x=J|~p715Lg=)Akiae0l zH9tRsO$C%&jXI&wU+Qi@JeJ73;P($vdd3r(&iwCjh95Un{P<^LGM>o5um3p9{q)Uu z0x-}-q16*&w#(|*r}Y1Kf5Yp!`NDy-z2d+2H@z{tb@X?oP=5Mv0r{JSA=U5mo^AT8 zz^ijVa_0VIyz}4vKV| z+Dz&P+0V+pGR5=Kwb60fi!TD%#>J&+P|0}Z%YQF@a_+kiVB%OM+l^O_`eT03rT zEGKoSQC@v7Nax^S0+(E#@wL8)~c$9zn%-_DRSWa_7aqUxJss`U)8~uAvM* z?vy`YcJE(U8ucUQty{LvcnrK%v5x_~^%dp)!nMF#m*oR*y(GP8th)x>HR&>NSNQuZ z`}dfSzsIB`bu%7eKK=xgdROs&H72!sEzltrkOl57li$VVx5)xPHJyIs-|s>+*RC~P z>utI=YtEAV>Z3cpuSd)K%Je^$t=-3WN@VM}B>YH57x8UlsvmJg<5#1Qh@Iy0)lW8V zbmn^u2(;U+XzmH)6}46=S7#N4Ij36XqNeZp1S>%PS=>u2k`g_N9_n|GqE*`o>H_DPR=4e;8keF;k}G3x<4ebo76`tMdL~r-?*qIr$M6EjHPI z(AtlO@}kfI1B*){;DpdBknRt3W)|e( z;G)Ij1ARbyGC_%A39Q2+(=I-r>@1x!p1co>3U*J>x==M7gzQL5qK%i)P&GdU0rbph z!7NWg&ZCn$-$vgV+XHan3OeERljz-0aaZFqCa7HRn3oiDg z+e;49Hl8z*!R_qG5Ir-C4!3J0&lixp|;0P3Emo7HD8P9v4b_wZ@N zWln!Ut|h79205)8+}NOgyV(;yuBL98EX9?02*)}8?kuPh>=KKP5&M<|qF0fE454Mh z?n(p5NV*@>+R?azY6Gg!fj=$0>M{PQ7xytTjB172YOLE>f@BPB>(~P_6f$7)EvF>t zZ4*-&Ma~VIIQ)>J#bZ%{*i23g)3iby<)8IIeIFBF4^P6^vnSy%2?e7^A&b?!<)dNi zZV1pPAaiD1LqULzk1cW@Y}_rYT#lEBbps;hEG8r9w`EgwXON%VgLXA{V#*8x6L#!xe6ZybqvW3cK*>4DE-IlWI zJM^W0at&AM_1Pw)Xza*pb9bF#F#^XTkyv&=x`)$;?`VUSzRdBN;Rne*VWjt=I<^X9 z1uNx)cfvGrL4Z>|K|LU^iUTHkR@V0RQ$s{@>(042pf^_~g6=W>z*vR@giCB*xHWrLAtnmTe9i{2oO3EqT zVFt7TF9U~F7JGTcmm){$;s$=JM7kLE1k_eCZkghQXmVN6X~W}$<=3%Z?LrB7=JSozYKtY z<$koAW+k_C;=bybVH1L1K5=_0Cf+k~TZc(2mm^ICz@~)i&IoKazOw=6Jy&c_rq2En zT+&Zmx;l0V*62oiIUmfG`N*WXvMI-NwNvWBZ$qxuG7FyVbhqA>1^eKg$e$+!sjU(u z6~7HhjR(Ir44%IjI-!HdxB2QS-eCjx*!VWX2a$i#$q{bjx7$_;4jWP@Zp#lMBXsgj zu**_V-Mlg!M1He0u@-y?`F*0*jjKa^-FmZip99ARr46Yiw}m@4YVg%nx}yd__PPPQ zn5cY4&ry0?4kDA?K4eo*{sj+u9wiZ}>H0ZDn&!Km+TzLp5G$JcZ$=eNtR<(h9t-cPFX#JMw>ntY0U6^@7T!R zL~y8ODHnK=vWJ4dmd(6K!9$kLOI7KtkTd{mmeNw%I@}L{Q=JIfc#Ou^Pzt7?#XxR6 z0@hG+r;x-Xv#6BK3@49du=E{!;(@z@Fl{*^-Sn8XNNF+(1s!(yX+@~!t5qudx1mv# zA$IKhll<7Wj$vV0<=a*&^M@Vm*nQ-o#w=B(4+zysQj;hi$7DEwRKfyd!(#n8_%t#G z|7OEId&=@m=j5jmr8QQYn8Qm`z23W(vo)P(0YBe#2PMfSpmm5DNEp_bx;u(X$2MWm_5!0julvifOtM({8rjJB zu!fsCi21}x)^)xSiQ|zY7~Nv+*YcN0A){D4<`&@VyG+~Sv4T=+@MvBOT>p(? z?G03{d`rpA8qa)-@k5mLZGW))*j`1 zN~r}~q?hn9cD+&PcrDNmo-fcHu``2HRKV;_11!W;fDao8v5^BLiP#=|IO#2L*8>Vw z+XsQeR6(B;?#eTPwvxDGwESshGk@PZ2u_{>Z2?Gzj5J_9aj`ilhNmAp_cM}cKQWRh z1B}ifeh^T+6baH^PsL0Lwmm($25hlFkNb!13Ep`(Do8b{9U#?A1%Fyh?Q##LS?mR%XWdw-1c#wXJ;F6~k*J+a1){^#$B{EL)U{ zhal|#mM%rUBDH4g}6Y?*SKc zHIBs=Z4eyrSWN%{5j9$Bqf!lul;fu!q}Bu0({tAbLjAse&v);0pZmuR2D0{A?;76q zuHXBYNP)zFlL;?_? zfi@6$E{N7XW>X+&P7~AV2@YqC{!VA%Ka?lZgXEE0sKG&0s#uXi>_w~!rLMn z2>vJ9BGiOAqc{tXxTih5gC6m<9~`s~$+W5tk=Ze}p=&h4SY2Q2WAm)GijVNX5Ap-5 zVDjdc3&OQ+k-dc3H6QiiQ~$K%zw6^u3pzI0B5bnY2kMDIkr*p-e2`%Y2qt&lK$Y}MP zXC(gf5&fn!s|E z*@i@s2fSAA^bwCNm2YwMNb?qX2qB(FCw$L7xpm+>=zgqR9s>K*sJhsWJ7-zHgxn*B zpzRB6rYHJf`wCuqdU#MOuAu_Lt)`@~oRt;jN50_SUVXwm>r{oGg@*uVzL(-j;n`*# znjRpZHby}{>3Z(8i;x)g`k4E=q41|irB7ze_u!b^kD)ox2<796Y?ltG8+tbYfoC9$y~$-kWHAMt+4o+g`qVsGt-rx%hrSO>^Fx&HQ?w&x2C(Q(_!A#DP+{A-_C z&>TzzyapEUbCSD3kX!*?u6V!ekXEaO%pGD$>aSOcL?X~cBrjXA2eTZ>TrabLqJb z{f;HX4een&B0rq)Jyvw%AG3sohl|t7_Ex$0*^o0MOW6aTO_|$oEcn>m6 zh6l+!9IB5$I&Cl*62%js%uq;_Mt}ynkSG_F!XS~70C|N&qMe|GvOOGS0}vUSG#{uW zasxz^PbdX~qTOagc-~}5&bD@gaIDFawyM)w4$&t|qAr33ZvrR46J)@~j5UrhST%j5 z3QvP36%A3g2ytWxEO7i)68R0}M$}H0py;nsAiQX@Bxm38hj1)3F7X|C7I+rqR_lV^ z^PFkbBNzDA;-~qv%as%#J<6EoZvIJW-W{J~_te)={xn85tCRt4t;MO!7|@GEAAXBTIg^7jN(Psx+T(D(LS#zqF5`Xptukw8sY6p(6U`n zT(SciAhfl6*;;a4ubP9D_dg{>840s$SyD7v=trTqN#EeyhjFfnv`F-hcN9*9TKRm5 zFXEtclKs%{d>mYd34~^9>>|q|9ef+sH5QvIb(YMs6OLqwQrL_3`xL;1Vx|0TE1KrJ z)69tQQ@5jUeAmfZJ+17B-Y#5n$NX%vFij;o(O#nHHrvbk;obC`!{bxHbP>S$4nzH5vd|r zKaLL$|Hj=PyZ_zbyYx)%XR%>?NFY{K4-@a&fwtKXuMX;4yB@#Z)7RBK>_wLQfDw+c zv`T7+s4Wd1W?8=#*@acx&1$rZvT?L4>UQxWFNpxtJZGTQT!(eYE^73C%T+S|saI=v z2PW>edNJcxMXsv)gqax3mbUu$J(ivc-_|`6OGMCQ4Qk9Woqm_r}j87N8y^^_sq6S$UE+zUzc$FW`6u}Y_>A~geHmJWDTaK+GZ&fr<{&Axx`)oN-Svw3mqtn*>t}Fl(NhruK2nw$A zKMp3-#1GF#;0+J2_B|eW*lPHyr)RKx2q-XzCe^|cZT&0%g-Htn%L8Wg8=}C zlnc5&(9tP`bHTf%IVkKha=AI|A~klzjd&f-=b_pKj+_RcYRO%F3=Nw5-$|FR}=EJaF&!y*{w-+h{P@clV2zxu-Q(BI<)8 zd|JX9&rxIdxVN{%R_t)BRhUnXn~zSQ(&1t+yA%#^{0 zOj!?(gUvID-2%*Z*2Qxz5q=>p=OUWJxL_f99x)5SHdm>z9uoGT;ILWdGyVPZm<65* z`LkzRtX*pfdh!*>&4400A#4T#H*TFx%sm@0-()fkT{$l+0&cx}>C}f&*`XH?_Y4fQcHP4kRo^|_Z5RX)jBT=g+0e?@QDWP zQKI)hy;8WLUjOXqn1n}QpUZ%KmYH+BvW*6? z9G`R2>fG48b-5cd#gYt@F6@X#Z0ZMTtFfsQ0?W&Rp1};XUSsc`Cs0T)`D{W{(c;i5iZcJK83j%ZrJLYmX7ee3ClwNqSLiZp^&GX^C9}iM=P1 zjOj|f^?Lv^=?dFJeRZiz_Z(VIU%IUJQR;)5njc}0qjs&V@fF6_aOXJSl66$G%b;7+=-8TT`Qyw7Ur|*Gg z+$z%cMdB?>&}sHgmh z?%8smTRjcfnJCXuLcL&fS{(478AJx5M$pi+^UOduQRn_n(Sa_1xb)y7*t6fE6?3or zA8Q6L=;8{CYr#I&(oWvkTXFZ~_boYy%vQ>F29vQ}k|f>?-0^a9K4@Pv5B@mte$Z47L&x;N+AHbf=);k@Os5t6-??Nx` zn>XEwn*!vF#XK`Ey=+`A>CAH=xrMz|NiCt0Qx7FvZb3 z6Y5rYk#i7hW?8xeS)$TfjGbenS3{XH>5lzs^IF=jMxNz4`L0VE%NAP2-8kxxa_W6! z#p6q6Pin2-$5p&9vx|6x&b8T_%-OrR#cav?y`SCP`vrS{-qHPATbv5-?l%{>@R)LH zn||iM&asF0Q`@vN|1A(HhpjIIcNvozjVq!cmY!|i#(91L|ETYwl70NimI-U4`J!x= zQBLj9rgQB-EDD08K{4$E0G{;SgITqW-xuG#l|+L+7gY~(=Y@geoU4dA$o$#G=5o-L znHMf1=gjeP^bpsT(W1e{A6Sr)Qj)Q(BV%wNL*$hicz~T*l8N5qt_iPiyl=fEdh zK0vGGh)))H{*QT^u*pFJuHUVio0QC0BI+t)ujwVt~FACcRMsmxF9W0uU) z8l5iYFn^Mc-F`Mtem?mVe#}V%1!Q3*$yl?iMC6X3Cgzg>Ah?l@J^3Rh#tt7-yRz@X zr)cDIPy3~*ZO>;{&b9d|<`d%V2%CP;8v|X*cb;3@K0fFY0@j#2nI>Q)MQ_XmX%TAk zpGk`=;JJyk2(Uq2oV=TU=N}?W+f5lys8;@`M0xI)RhfQ(P@wVYG&uN2z(w#J0_tF`<}CdPE2IZSg4(2l4TArrhobl9(&k4S^Es)7F>q%RDND(ZvC{1Y|owRi`X^WANFDl(cCT$fF5H(>gM3}25 z%*iUTLlh2Bgfjmxnwc zvg!vBLZ`rxR>X_LEl?>ezC?4}rprPh=qx1#TIHtR^uS@@Q0zf@=EM49 zEDw84eJEb2bkYHWgaS|VZ-WrlGCnNVVcm75kb#M^`jRF%kU!$%{5fOSbB?EhIw+q= ze)XCWC~I{Sj6|y$j(D>x$A(Pg$bkP%OTbLXAeBy}@f7)D9r9XRhoJ8tgN^}bg0opT zPKo$fE59vV4U4W0i{-;tBug2$05uAD4J6=@Lf@}En3;f^~0J8 zt-RDE=q1z}K!7yIS0&d@NJG$0x6tLX@%H)5PaE0?JTF#YtMO^K*Ar;J)lU#UM;_Iu zP4~KXDJO;ktN82&xtshfU_s(*W<*=-kL577%Bf%8)Dz@GpO?7tV)_9!f^*(~l!ORd zD06tq+n_1ECNSE1Sp6m7OU%!Mrb~vt0CY+88_?ACAkCWCV?)d*su43D(HW4C7_A}u zKcO`uAm{=C5D!|Qlkr>~Or5gj{|V2L`hQP!{Lef`Q(U4I4i<3AA^SLVc@h&-HwMUo zs4PinlSGq;8xWQ`hYt;ilq{$hqZjN4JG%S2K@97XO>>k)pF?hGD7R7b1#@vT(CX=7 z;J0EygxTshUSy1%m}Wy4(O?xPG2yQqMe~2=C>+c&Avs_tFs{PS;?(nx$cjMwfP4*G zp$e~3WiZYbTX~T`A}_4y8cN%Fy$&`z*SwIT7f~OptpFeLC!^s&%ebqWle+J}&=~>$ zna-H*oC>n`ykezKz)#~mht4OP{vK#Xti*VZ8E`tMcrkq+%J&JQikHGE5SM&fZ(%pi ze)!6&o;!%dOH0fQwDwlm!#ZB)kPfH`k{%YdA-#eb+2m|-8=`NWL91o;5qyB|zAy-( z77)D!4x5iwTil%OmruZVTeP;`dq@jllEXpTJX}mQoADM8eGoWsxqsvC4><>NJYT-B zm~!Vj$U#8#o)gatVYlTsT1u8R`J;8V^e?-Hmt%}X_rSr&UEPLL#QBV%NT-%_Ef;6C zG@fhmRRk>YXv;r(Q{``&mtSz)5=)fp>TLT2u0fIegTiLDMAlyn3A^0l+Zy-*@MZs> zJ72rzd$au9&77}ax=Zsxz(La`dDw9XR z1%}dXY8_qI_5S4hTTr=;oJD?m4T*)6EV4{OWRaCDpNWT0u%iJ%!8WI$OE}-2m|DCM zK7rVYE#%Cq*2E%TD3@pP-&W!usIq8La`^9rEd5*&TpW|3kBfu%woCM~`3QV6CQTnt zhtJ1|X!AF~2ih}f@!9Z>n6_LT3Wmf5Ia zh>w(+RZEK@Cm81>1^>h$Y^a2(+ybfkVc4NZjpwgoq_fGf6e}QSbc`3ccofi+$nv{H zHa&@6beBk`bHX7SQT4fSN51AYCLU{7BnlDJCWcZwrFghrnHXtUb!e#A=yGDn<#xZz zZL#dnwrg(IE3bd^sK!*C-+9gw6;+dJ{NC@%%BFd&sM zW?)Qv)5w!oeky_7EoFVYs8eu4VF1k-JfX9TRZiSwi&dP-lG-UuY%$kV(l~{$pDH!$ zogx$#t2qa0ls4+ua>p!Dy~vhTn;Tcmo6rX#QdDsu)v|SG4W!$kqS-r9UhY&ZRa=iR zI0#S|VV1f=wwD}WAdS&&Y)2Z6u13kQRNsl`M|oNE3j@dllDD+>Rqa}cN23g>!(MpM zC*_8z&0sgMU6fmGKR(mmk~mgQr$b~V&b6pB32~&29LS&(vqQvov38e4Ax8k&@?&+knKc5vZ(U%rGwfNF;Si{85kYQ;`Mr`WIIzwS4bpR?L-HQsG`YC^B$PDn&@ah!Z})1Nd<%2-4};%rW;(M7ZR^E zRz%O0lQvVBGzAZO6h0cgxu#Qtvnjd`Wj`CXe%jA$gJW2ZL`?-DuDo;$Xr^00(Q>WW ze78YPHjnt64}{8MwtVOSLbaVh2(cYp?*@dVZbaGSsd~n9Kd-a(gqPryBDn?osWWct z6?m(Lw6&qtx4d;>IJK#U$R-Ar&`xyHl}0xSxowMHK$npD1?6n=2&V*TAVpx+?VwuZ z4yp@;A@nvI+~>3>0fc0tgnWB-IXm(+rvy4Pd8XeAb{^_n0M;Ll?VFFGESJblwtLQ} zD6>v<1SkTk%vfzy#b&uKK((G&Qd9yq0^4x4)3WqA+tb>$IA9b!{=7m@{fTyd=NnRiTj2%8@8yX9Ca>^#yK5F#6xH2dZ% z&)+zX(}NDupf;**2R5vV*hIX+yRNq?zs4dsM9)T8DzJ&Kv}KeaA+DJqiSC*}ry9cU zq0;5$bRW!${A$c)M8U41j$P$mL~WK5AP=RrOo45Bz2KlcPOL3k*VC0HfB+)tvRY-V za(VzJ=c?ba!zFe-{rW_odd1qOB)G5kH;{)#I`@Qm9WW#QX3UH(AN9({q}B?6)XR>8H9*Qn za{~xznc4R+A-xyTWJPN4*&a-j6@4x6#MSkd)phNt3y5Fj<~aR9={g|?ScPH>u!^=; zU=`|5X&w^tQ3U)tCiL)xEy2P>q;mo<6)pQg=mffN;Q43U8t6TW!feVQFNzE2v)q~F zF@vzH6ON8*BKGjEivk9YgRSXEi|WP-L#S&yGjf0!8Iv)Nq6`FRfq?QZ|4U~!odWd)@9VzYtJS`d3ldxf3R%A1Lf(1|E~0V zLKh@l>ZU6bwB7X9gsyHAjNWO#$s&p&_{rq4;Tr}LL~BL*&ih7n+cMrhi3Z#nUsDqDR6(xrK-a0mC8}Wr(K=zr(*-l#{C;^%y8>j$aNZJ9&zW$t)MK>|3pNlnY~F8 zcnWk*Y@_mD0GK6QG@FRrc%&E6Vf)M)Y}`Mu__?aGu_L#ubD1P;K%&|V_TUZJgQvJ7 zIWBRr8`D<-OH3~TmgsZfLCaxaiM0oCh7MhN7HMONj9MnoB#W4(=xNtJ%zpPVfc*+P zHcBz6+)^MFci_Tm}%xo2{8OLnUP1-Ha{LKQYbX}pYik=a&S4+nd28usGMXKp;w&(MCIEtX9>y(~qszB6+eZCpLW zvafX2hgHD)Vet0%)qXO2igt3r_jSdCojE4FDy-j**A-=wivPqb6Tb1wN4`dcIIr`g_PRZs9hK81w(bcX)28q(FGlb&zR7s=SoZ%F-)OS|zOmp8V6iS( zSTN&KwZ-!!s|qioP8zL^79lrzuw=@d-`+L%b^H)l*fXy$ChDDMu7^7TTr^iwzr?#U zUl60Xz2*Sow1IJ4ezrY{_j@Bz44jHNbtk2FHnm1d=dloxhm zshX}%WejkV8Hk<}o-UG!MKTHa=#wtDl8NQxpXuppnOKdwX1fp{9)G(Oos-R>d@bC1 zWSKJns{RrYx;5KZrkz0unTWns8zJw-wnt6SwOMeI*EK!(;Ykd-CZNcKVD;W9e&t^* zJH8U@$ke_d?PbgsqMe{FB@2KP?FoyYS&ZomE5$qpNDS;VZ51T>{9pGvH+wRgI0 z-!TPs@xR@}pe}W|%ak!_Pi~m6(Sn=ZlEQ3cK(e;Iz0**(qw>6s-4PoV2D}==!65JB zESOE-9oLsNTH;9z^Sf%RJe-k52%XIK!6@sj%9K>|=BH zA(rKb=~4G*&hT{qb^pHV%6}!?1cAvxMI|+a;Lgl~qaKADZRS_^f~cv=7MK03YTop{ zi$K&Qj3;O+RBi`q;;107_q73`R>6ivexV@Ll7)a!YuG0KG$wSy9tg?w^L#@wDfJ>u z%Kdb2Jdo1G+h`~7qnxndxt&V|U1$aljbF{)NHf3Cg#l)Z1J3*0@cFXuo!r(z#c=@> zcylXA!)Fp5VKK{n_DNQhBM~HHshESBE%&b$sDcsIo&UfxuT_6$Uh=aaY<)E>tEZEp za-Q@vPlsl-G1tpp;X3M&NEIODDICjcME@h#%TA-}eR!Hr2CAJ**;3D-)7JURUaBwL zUPDuYsA*DxxoaEnz;0_npi=?@oyg(FexN$*!fdVgn4xOnNF)CU2+=i|Z`ug0$O|Rw zSVWV*c=|j=;h-pNpbbc_v%sEWuDMF}>p}kmd4$=e@~Dkg_-!v;;PF(#8qgn1v&e1;Z&CZj`sQ>N<=OWRbV-ucSt@?fI87=Km zbtU_Pr+akvyeKYhq!CNiN(wX0ABxlx#K22Zg$RETQQ=vzifRanBXFtr$1Aj;LJBIf zv&=^gdfQ<%RcebnkFJ$+DL>_&>@Ao8H$8er>MLVi#kov4Yu)Str_I0hPG%0RJ9m7> z>T$~Y@u#WG0VEC+3CES%Ee<8ys#CUuj{Zx+(OQ1`vtt7(YknISn{3}pFPKrj{q%j= zU)!4tcI$p3D1KU7fv#B3kU3ai@APxqS@~(Cy}SPzc2wrF=)#xHC8MU4exNbzAk$k-#KyYhB)BZsZ|kER`Y>!onoo=0lo#}e0U^vM_QR#d10bx zKtk|zXC9B(Q(1l2vy9>ZP^j&B{6M*^D z??5ELzG9%<0x&QC9)u61H)~|U;Y{EhMx3$u_vS4lCiS=+NU^>POTeV$O+f1C6=T3{ zAjP`tq2X61$siW@(6Bx~846&^7kGNy0 z1!iv;(a1?VW_0*TduBB6qyv)^H*qetp`pwo$m+3{8cT5m8Hm;@FXvVn{}N$#J;4tD z9z(R)32JSaBC4Uu8jb6=nx52p@>*~$! zYZezah`%09ZCil8&ZqMMdD8a{2*xJT5q8+xYz@2ynO|*Yxy>|k?AiN$YN|n$Y->q= zpNeQZ%jZq`cklh^ybW#{uco;JI;J-A5;{&w{W`p0q)}T1b{)%Dx)ir|FzXylHWC(= zn-e?X>J=_VmzI_XNJ13}gy9O(RhM?fOj17ZRrJl!ZN7^YuK-NXOR`J zf64?MP33L(7Yta%3~J8|{!gzWv-Q{ujfHmw#!$jQ@}H*R8`d9(SYe8>h)=%ieGh@|jUOy(pzH@#mUR!)5jx z&c$P>Vb6lAQjZ^wXfV(*$)Z7fZ8i524*U0S=!^0b>V{Ai%j^3oBo42g z-GPsf@)C|TD)!t7Q27)IIFkv2aQiyaQYo1A59el#8CE~oS4cUZoe;%+>sXjQGy|aE z=fe*=!~@H|`wbi%^>ggF?a80>0Gu}bekM3=@vnbNSqDzrirwI}A+iWV-S^mNv4_YO$$-eFQT=$!l58GV3BEy{hDg-K;qf<46Cv&f}&;oFg%cDWx&&V{;vy$h_J zbM@Qr`@a4DlliH+dycJoUQaLY2NNh;w~uch%hn)d!Wg~B>`kN4$84doPf2EHroO?Qcr z(oF7A=L&nGPd3kzZA5nRsqn|$33u`-u)=IdVPg1zB%1ARca2+CS+SDY-r4mXb!w+I zJNeeIidM#_%T0aq{o$E(;>PXiH23JaL1mRE-5G#16=8(LOURMHp}_1e&Du#8mFGxs zrr;&AYcrzmZ~wfo=U*45(7ZQIS^}J_{+VeReQ8xHzUYnj_0EBXJ1cJ;v7ZW?zMvQo zdXdrkgWB5U$2W6^bu7e(NEl7kYCG}7C`Z~bW1JNyM9@05RKf>K6Nt2OYGrMZ%XXcU zw%@5xJUKIwizRGZyCrbX(YhQPB3G&5_zd2yoeB979B2cGbK#3;0<)5W0k5f zkwqFa@T{idnAA?SwMq(=t|XJBqs1m`-AEZh$N_ZHSS?~T(kK(V{25hLDtzE)EbzYz zte(=WOde%~J}RcA3atPm>jL&8qO0?R&K*SAbU>>a_uQciE}s@7CF>ef`0Pk6GD|h>U`@Jy7hg0F?`}yM zO%;M|!AG5P9`bUxBzujeB3+%S(deN9S2y)1{nlB@N!OiNtRof`N$mSa&41i5{CsyDL%N;v{MuGjP_EKVH zQ-s^ml5G?EI(MFGln4%`}cQ)JOdGq^W@RoG+Q zy)ep)_=b~QHfJo==fsi1M8Gef6c&td7G=#Hs|7qh{;{gk;R?w;VY77<_mH44JG@vn zYLHsIX*>#8WddN8OCm5{jOWfwR77!W@!N7CJr%l)<4r77PI||9nSmHHCz+qk(j&N) zaCGjZ9^|A^#@h^JXsWvE2rdgI_)RAMZbPeR2X%4_Q(wO`$}$m|x)t1rVb@+gYs6KR zKen>mzb)oRT>$n3xjdEN{I#8zJ)#`Tq6-7E%tj5Hz#{U>D$UM9?z3A#uwO*jmQ5zT zH>tEeOJApx?lWmrQ4U{aP_h`N>Yl9OI$hONHLe1_B4be2PSy8f;@YWtMFl3F!|1U+ z)Cw+qzE%46-t`BZ^cBBaf$R6+k#Xvgaq^KF@7j2)CBsK>`{YM(_i4uz_gUbL98>I` z$WJEzpV+WFEd zq#?^xtv;nIfC;;%s@FPqtwN@m)ST_y^HC|sSwB_cS*AP7+%jx!@J(aPXOe4GO>MG!Lq zu6oO3&hpj5I$ar`0D{X=Tmu~9OpJ1-C@bM8=g}?;5wNkZ+iucElrLwy^ zck-hg@5U7N9NjT$5ZJvjCFP?(u~Jl~JX!|Q^jYKw>Q7bJq0Xd_aM}QkjW2u&A_f6; zWYX0UYN+X<F2ciqh-AhL4b182)+v!gwH(2fo z@K|aPNWTGNHf^|(jb&)#u{!@Y{M@-{%_P7B43cGw&MNBRw#jc-G428TAR*6Wbgh~4YfbzsaHbGWN5~4ZEzZCZMS&|SK0xQ?q4LUV98mHf zApn3fs{n!vsmjsXdUzFWYC-3zDO?r^G-Q}Ru)5C`JrHSl@;j4WkpBn{WYWBd!;Oon z`1h%5aAOh^)kc+SzEL1I=)#^HUX#KUz40#cZ^1?9*Ra|?ga2a(0w*tgdyc?YXTY$cBGH-Xg@UdF9w$lP! z=ZC-L96dUzgb&L9fODA5YbRINZ@jE{1pmXioF0j>sJ<_A)lCW-E&3Y#FXy6M+GX4$ zc+`3FezKMYb`QISn#iOFnTK-0`acNRg-w)iG!_bl%EsLi*eLLkvYm2_FlyvYrE|L9 z;Q}UcIN0YDt9Ub)Ni^du(a(XR2Iz`=lPYF18p)4{OONAgUSDBNS{fgGg2sYe~~ zcEqt%QIi787K0P?76b?IE#YoI`b>P|7y@Pqa*9>De53J?vu!SjNR**^0m;j$9R_y6gwT?%> z0}BcpRuR}hV%{CNE$rvvCWQgkNr@v(y5Xd-q8#1@zD(4?at|hs_1InktL0r%-UqWK z^jj?RFZa44km|GnhDT5o*8+@9GaECw1G||EzL(MQ2v{|*y3%|npsI|LV#wXj_I+)Y ze$_FpxOXqCHc(_HE`n4NXYHOIiPIZO)K5Xa-w2c7%uMvoSWTxB3iJ(bQ zq8g=YxvYK=G|>Zw9)Zh;$t9(`6s;4PbW^jQbyZ=?%tRf!QMkkg1lT@+7-3Hxu~4g? zFuEz0zaJj{L}bboMbDsZDqYDeKz7MCf}7XZ;0kt#T$ru588xUqha2aB54F3EQt)M& z5_vHJ5H<4R#pIqZRf;G_mk~}skSi@L|7=58Ri#Z4_@2ptP=qE(hK2?dMB7960a`j>cN0YgQAEVVm?M}4 z6tiN$fB|zD1L`=Vjx%G9W5U3F{`=I^Y>!8;_rv|YA71xmz4feTty)#Js%q`s&EQQW z5{cSNYF{}bHEcl7;mI?f{o;wo#@C;=@#W=*cgtDZ=Y#{cKd9f{r+>Aw&2C3dyezSC z{j%fs&3R)|(b!cB^M@^Y@T{*Fw!Swx>6ueDrTV{d&h!&L8-Bxu=bV~X@2}r4Qd~WQ zNA&r2VuxFQeq`CwL9eaoI;G*}hWm7#yY!sZH+Fn#`A)6gD}4UquAe@0)ai}ZHA{Dh z{olDKRczSr|L&HUaP&V9{CLGvOB%0zum97_ODC)uJS4eYBC&DFi}~;6%wODm+dak& zd|}b#4ZEzZ`1I1jFLrysM}rx6w^>tf(sNffS~h0baf#hE&jF8(eB`;k>tAzm^HCSA zYIESZo3>50A6%7t=M%@Rc;G+p-#2#n14RuNHNSiCg$mqf-um`AV|J~4<*kzb3-0QE z*@jJnF5hS4`%NA^CFk&$*XMuq?$Gt;T=V3mUw+vChe=PqHviMg+UNEAsKj%7iW0TEm=id8$@3dvz{a203Zu#!Z+t#ftzH`Jj z)uZO0{#EVH)2Dw?Ki#KU>CmaG)_>ab+*5~McIj(vFJE=@lA~m)m6$Yd?#X9o-JD4a zOYXlXizO#9>9P71`)9Ev5|cI@boD-2Es2dcetGufoLN`REy!DJjHsUS8@Zox(CmY23V{pXFFuim93r|^K5N-Zx_TovO#Oym9PV{T^(7SLM1#hi^G~uMZnOdUfeRktMP5 z?Z2=3Ca2+9H!r&St9~=?UbE)K7E|t9_gjOg7+?MV!53v2eoK1ztd@;^>p#^eXL^J4 zR-N?0$Xga3x1~Yl)0dt!>BRL{F4+9Wk4qN!$g6XG@24jH_u-1_^oym%rXS{Kw=DXs z^DWse{k~a!dzK~YRkiVoEh{?z&ke5$^t`ywVL6}Nc3`j1nhm{Z<>9y0`Jm~_xsyJ+ zVy7pw*=en z{BhL4`Ga}Uta|DCcbA`CIOx*V)vHI%={PR&|A~#>YPGJbH)!dFAN1{f{j4RQR=)B0 z_vv4SytXOv;?S1E`&|FtZN;OzZ+?94s8&Z@{OW|c2M&66)W&tqi@tjImWz8e*l_!Z z)=ej$F*Gr$WB1p;%JS~4qjk34uyNam-`erC^3TWiyZ z+HF7LZ=0x16WN+3S|uLV7`3F2NzNUVD%Wp|gqccRNj(X_fM_6TDA`8RNYYr+M6#_! zp9=|oxuYp3^lOqVUCL|NhFWL2tv zMQKH)*!mIA+{+4QS5%f3=T}sfRF_ng*Ysh&WrgJxm1W6N`qvBbnR{8`w36zvaOwE0 zCE|uDHIZ+cXMJUbRnzB=RYFr+{aJJ5Uod^HpdvR&?4UMTRFo=BRVJB8L3QQKqUxEI zsgdJlZy4oF`6H52Ur>}PPZd;7EmU|QF`6sWiA43>8L2Kcos0X;oH8X<*(FQQ0VS2G zB1TG<4lkKHtvZ@Vqr{GC|A;qh$Csz9u-L)G){ppfZj(eM(z&gi zI(bNWb*fy6R~8&Eo!=SB;$kiH0M^wwIxAV`6dN|Ip(>q+oiwLEoQHyvvKghR{ECwD z>UbVnD@K+vf91`*@#QHioZ(|6wo$~V^H5SgE3aB>of++IIvoYa%}iFN(&wdNBl-MQvnCbk)yqPz? zJem1{|6}<{$4KWVe%2a9vC}yzs;C-LUY@G#Us0aQE1z1L(#Q=Xd-{IH&s#jN=@{v| zsu-hYR>xzIU+(Mgg<0r|^F)r}d+; zetqVMpSGp*I(cU4F@C1&MtnMlQ%aLl$!mj%OTRa=o%6Jv9G4aT`V4aqSQqbDy$7|Qe%+0l zGNmd->5uj`S1s>g6%OxfYL0aBO5ZGbr3Q!mSIMs#e-rY@_pX0(M%B#H)YiJYO`>h~ zaem>+8N`oAbFEHRR!8>(oim6nC$d$hUpz5ByAWozv3PlZ!Kv^$B3pyV zmOl6K`aQCwT6uE3^tn&p70xQ(kXiGrH*PvloYi`XJ>?hWxGKpv08uJE|A;5_|o|c>MhI zJ248B61};ZTfIcbtT7r#KY#sBj3Jej*<^W<*T~OmzvHiWu`ZRo$tyq8W%r$2Qd&}; zN>&!sTu$!h-kzhc-LLNE)||#Rr{;3wyb1yDcx$+goPtT1z9{CKO zTcr>0R8`5={@mxt)_d30ueE_bySKf}+Zb z($bpR4eolmJKEwPT$3HzdFZ_NaaQh2J zwSzfjyTh@2UsIIp>Z>CfKmGe5^{?}b-$`+|Iw@Z4d!VLp50WqIW1pW;5OiYsXE1c` zNm~hb&HC=bJm}n$xE&q4{kbb~J34mmC;ho6aXUJ8#>LKEiQCb!GY)p{N!*T(opG>p zKjL!YO8;m%bX8>ne&0moKF{V@%ivOHlD5V z>ml_%lL4a^M=cuH}j3po8Kw%Y@J7)==V%; zo;N<8cP<7!Tm93&SIC@qu6#1*4VO7@xXgLO#pliX;Fve#I_GfI3AnBj`%#17dc-*D z4%{IU_K#vuyuK3p@w*`&e0T=S$DH$k?mV=OyyE_KqkEj02mI(mT;EH$+JW=_!DZ$F zE}jSGeSo<5{_QTECq8d;o;NykV4Zv5tY@o#n#-Iwe)NgY8!mI+aCL%Tu3C=~pSQWp z{iCn<&--$qxcI(!o^II}W3Lb0>uWE}V;{zb^ZJ;pIj@iNVy<@R>$*x`uh07j=k@Wv zcHerTFY_|z_2tGmpHI#)^_6(ch5h9m6USriBg_+D51iNIdBS-;@xES<&l!GRPp&ZY zg!6i+Z|1xn=4sCB@qMGO*V7~B7r$@r%e$R*^o{v73fzDg$C~gP9OHOz!wrvdysP2z zV;t{ixUn&ge83%(!LgQfuIfZN0FwvLmv=S&R>U~o&v4hoIKJWFZi#W63%EOC9N(XC z_ry59Kj9t<+}>(=;CPq|oc9}G&ih>_#?_WDeH)15Y|$6L?X~OO)aFWL(t6YSLBc%N zy9>wd>?!?sP^_M6b0zqKdr1JXn#Zww3){|I4wd9eZ0{q?9$4=y z%zB8Qr>#OKJ~Op09qn0>u4%ISSNldwYC8Y>n_7tqwYzJ7XQ%~pFOE}7JmR2Ns%0+d#H>UlUmNn!Rkvbq+al#Q`=Z4^FgOp z@lLURj4yw4aoptUw?*!|`!VP0OcWs-PK2^ApgnTj{cYwY;)|;f&Nawt78`C+< zO*8anF`YZyJf@clZzu71oTnC&90}ubo^+g|Gv)Wr$yEx$fYEP5UAAX61H9Fqu!s}!2xuwz*i3JbZeulIyTb{_XzD&BtubI!8 z(ieSy)uDdBo+Ta5;(lj~)BANjI`cS3(nMnYTw!u+eYtS0nEn@G_R{wAgxNdm=L?hD z9OZ($b3qJWD14AkQiWP#@^DALlXj6>a?d@ySi*U-eo2OYX@-7ThJJa5enp0UWrn^Y zLtmMpUzMR>ouOZopIeh?n0_C^W$pzW=EB-O5xa6U&VE7Y;o zfrIDa+>TaW+0Qi+^Yhi8dUR9Z?Q?VRp`U%$3d85=W>foak+6>kNqR?;{(ihw7#p#O zeVYW%bAY=&aP09Z!S4=Xe6cMJ+?~RVi|w?)-4)~V#Z^kbTY@h(=1UIlk-(Fqz0|Ig zaBe4S{xj9y8#w%Uy!QKqvGI8A_Y1?X(sUYI-{D!D#z4+`UpjlFzG zEzf4n3ERVxha~JL_{P7}`;!uUi0}P*N|-%kFMS4{7Um4_cyFH( z#uwWd&100>XC?3#NO7&%XEP=EAmB2X%uS$m_2PZ2p^m$Ffdh;djw<+-M_qufYz@HWJ`Gzq3XvxCB zy(!E-GtQ#G{Y@AifBU^9%zj|wJj_=6cgc1V&J1Uj{qLss9};Z%%~AWd#D0B*@tdyp z9m(4g&hEQvd0dD7Da<*gy;bw-ul7BO?*O@AtbfJ08#Nx>za{p?-dJ@D{y!4-vV(+s z#5^76{h-4;&IiK8p&xc~-Bay{62`FpkubjG9{a}jO@goa?*dOvWQ`v8dtq$!v+rhMVlsT#u@JKL4ci!XH#wG*f;!7RoyfZHC*BUoZEx!X}j?9@p%!xZRS1tcc!FQ;y zbnZ}3we`ef^I5Dfe7|_=P@YwHn(lyY6XsU zHw_%~!LOg%W`V0Ce2+M4MssoaGAGW;cEUWI6>KdeaO?$`Sj2BB%=~!FZ67#jb2|i% zx%vFG5=Vdhu@9Dw98h<5l-^ivk;Vb97RH|^{(fdo{vOy#n6;5>*3dfmvj%KCOW;@o z*mrFgVb*@O`gv}L%Fl(gso!L`(xa`cSy`)31aUS*(=4@i?7;Jfp zJx|=;(i^Ge-Nl^o-$xw$E%M>)bP^^8{5SIHtd{sZ2 z#*V`K31j2@>u>0fFO8(T}@#pg8hFo>l~%v(Pp4^?S3Mbml_q`g4#lZsdaT zPEyP~;qJoNoRc2H>}3y$bJ9~B{OXXCUczw1V*G=JdB_L0LnLs_0qptr7G5Dg=6|JH zbbpr|D$E_{%=mkwk1(|Wn`_Yk`h|S-6;B*$5qODkW-THH=bUwN2jjIUPaL}MaX;yB z)Dzc^{?g%zaf8O?Obn0?&)Ns7!ad?VQ}6NFBlvI!(1!<|)?1+bI=uI0ig0GFm?{q5wPKnuoNGmi zu*br7tOSnOVAjZem@ce8(KjXY_xEY3Ft)Z5*MTzOmGY%VT%i`-_n}-kv#wN#BcIr^ z)s-3Ii9=lhXR9m3;6Ab!%qd=1jtjcaNu_kScwMQI4j->8)zabFlbLFH*c13!5;*b% zj_(OPy7Nfu{huw&UL(%o9AWkzoBier!z28x#2(BO)}QEi8>g#fAAHu17bdT)-}P#~ zu>M5#3cKr-zuQj`M@$Pp!{o{TL~-03?5=Gm2~*p!c`p|T!!wS#g~IU6Kb{lL>(}}% zVV>fjEKI%QEYp%d`jIEsy^+ErB={1C`a!N~UH7O>)Cku-*E#A6eHN*u53TFoDZ<3X z=TymJiR<2J!rTjNOM=aJ>vZYVz4&{0sW^Doy)%S~0Z-jqrk40ToEz+CO5m9nn7Vg@ z>}LtrQ%l_=26t%};j@LYxt^UP49Da1d~V>N?YBH|)ID>52^`-*?t5O~sJXts=ZkZF zyh=Peci;lGJg$!yN@pFku8$W9Gsh+p*T;*6^(V?LcAwcxgwYY7`%8u4S(EGIWy0{T zkCzMckW*||NZ^>oLQr<69?}aeZ4T8YxE7m9t+!z5;(>JyGE}P)}N?GlS9{+ z)xy}?O1#HwgxOo_?d59GeTQ!nrk3PNd>?NXW>2wYtI=!46NefN&Q_y|K@B3e%qd=@ zZwb23<*m};;x+m<>G1IyeYoa(lFy{?%4(}G` z{9&`-J;LyaYxFu{{i&(Z?1RtMy~5;`^}9yjC#*kFjmDl?qwg0-Op9yu1LC;P*j=O7 z3%8SC^IkqE49_^`9ukIU{_&h}XTDaI%hP-w7N$0HpJ+MLwB(WgLtR|HP`Az!G~H%pGSgD>sq}*n7H^nDtS!eTK%{%_XFD#!R9-*Q98A{uY~j7 zPwkW9;9aYq5+(*bwfbqb#OLAsV1Gse&sxCL>Jw#uR=B=eYBez!qmA%$!q{AIpBIMX z@wt8>aM1R9F>tlS`F_46&NcXI@#viKztT~UYw*j`nIEld@GHWM&3$$4dsSF}qMTv( znS4zc9r3x|Bn;17U4vg2hIb8qLzstLVS7^o$6UbdDRV`K_ul+XIJ5q}B@W*8@9)BJ zu7Cd!_E^~7mcS7k?E3ePu>M5#kNNxVzAKEat;G5Lr!aY?mR+V6-S^`?VeV=VsO9N3+5EBfBy-(&&m7J;o|l01L^R@@Xx*N=!y~SLp9||xP5omZeAd1YCaNh}m~;4b9~*Aoc~uFlPdB4)+n}j9{~0Ct-NRXRNa@XOJ^y zzb?Y?h~w=m%pPI${_Q8M6i54q-M;$^W8)sWrXL`T?_Lt@=Y({_%T?uEOw) z=Y8%b%sf4>Joz0Yo%v(){pv2vSe!@f?%zWg8{_+&^c1EqHuvu(?Ect2r-OyPF2_7X z95JyuW^Z9)Vsp$xg&h;SeftPA9(KpOm%ZDID6J#bzI3lEaS-?>Ai!&^M|P;tb??lU+{ znET5b{Z1b)%zF2cVCTFLpEHxEc7!oxDKyBZV8P z<(*6n#%L=%Nf?{op+^bB@t8Y0aL}%Wg@KE|e~$@VotR%TaCODG&QBKSck;F3(W#Y1 zYI*!lE|$(ZXuba_Vdlg5-peV%%o`i^DNiw`29EcG-@Vhs!TU^>2*VN2XYyEKb&1X- zcFrVYdHm_Z_~YmCONEJx&9Tdb;Stxsa$$IK;&*+8Fg)j;9Lx~rVL!1QCxIgmV9qLe zLWlSHsT9t9hgXS%_dC2=7>+Z@STlur7z^7h2^_J()FtY{Y+-W3JDmCZ9WX~2TU!}j z!{!EG#$fH<^LfJTHSg(5)S^45#|vk^+vkg8@33Wix1S)MIK11z+1~BMVE>pCbB({- zPYk-x^GVX-;_vna(&35WpQ9E^hbMn0tK}ho@QWmHyb3;9dk8zH8=E4}nJ6D*8c-WRp{vshB*y}$}n7c?^pPloC zxsTX0t2;+;*W85T6Ol*#KvoQRb8qeHX z>F|ps=57&&C-**=w+bI4!G>R+V%#Ro_Y5|^?ci<~78QLn^R0ppdt0QIvq7mKZ$L1ndt=;8_cp z@0x|OKP1fmE|c#XVlc)Y!Ve2$^Eb>R!f-sU`5OX9{_Xc@;Bd9yV}Xl*>pUK~__xjz zfvX#fw=r=1ogMM|seLkV^@aU@d`g_ZiLMimPHlWzEswv6o{>%tXnlsB6=n?sB+Q?= z`Hns(%-ZAMLC;I4kMGC}!uY|PdoghEKIbn9!;`ls!dm_+%z8LWYsB?e`?7R+&ID_C zMVN=Z#P+HLj&*=tJ6;oJ9pscbaTe`I>l(L77&|$j4>9~b^|~mTCa{oVDpFr4%8jw>4$oeFs+Nbn zg8xhcNB+R^y@E$~erbK4KNse#AkOUAp>b z-50z2ZX5jEx2beE*5SU*q`NP6_MWvg7iK-o%iMOt@Qi1!g)lsEe8yV}!!J@Ca!$PM zr85q{W8&W7!yNL2cL=tqe#Q2pRg90HpB-a-{EX}r#AdE{3*RNdmpJzb zQ_pGr-FmO^I*Gqq?+iZc)$% zBf8Xgy*z8vn^W&SAc=#2I$L2eeius)%{J1ky z#AEZBo+`|pp$_E#d2XdVtVWfVdjF(bDSXz&wR`sC(OLD`F>Uk!xN7=nzFaU?bKXVftg68?#Z%=SkPy^(!t~|eGnhL$aQtt5`TIE5v?y@+W9R2&_)~hk;fswq5bq3O zVq$aOWx~Yc@xPruQ#yUI+3zf2=0Xjy-`Udf#pW^25oR20?t88 zB20gH|C{gggyETs|IPOK!tfVHv)<}^fjIZK?}g&v=|iqP_lu+xld(Mh#lrN*=Khxm z!xM-3dp|Fgj%|vBxw6NX3B$8iul;gic*Zt&Mc_o$%;!pR%mtfsxk8x!*xYxeF!AEK zyh=LzfX#ic7N$Qo=kgk1cyjMGUmN4{wT?>7={j-vV)K7T;d)_s|F;5e5bh;`=kdR> zy-_+ggokxASJ$Rh;_*3D;vBCQW?huCOUErUm?v&2l`G&)8-@AhE zRJHcKJLZesKNsE;_3ThDEyFdUC_{G@c&R7Zl{zE1^TZ1#OR=8N59 zKO;;W?C$@pFk_Ji_kT{h$HMOZ&kGX+JO2%riR$x$F#SDW`uXoMUKCG`=*KrV{x1pB z2b=$%@2|p)SA7>JNlkkzj?i{=> zju<@t-R&FF;h7Wv9S8RPP3iEgiNC9K|G$az9Nhmcaq#i}f0qvL{?s$(^bc{w#?IM+ zds~>fV&j{|>!;8FzsMe{w@TavtKP?;!xx4S6duB!a3nw))A&ZHutS7%-Nx@ zYe7A6oMCM4TVI&|*gQr9Ve-LxsV$7rP#nJ4`2W4Jlele!d&sA!(ZH4jUEK*0f8%?F-i_LYjS@2O4+5K~6a}oDwPQ>Kr%I$E_ zLw&>6LIOv91AB~?!tUq!Z7&WU@x9zZn6a_B_O=QfHuv387#=aVldyUJ{&mad&y2+q95~joLz(+=WzMp>v4A#eq4R*paoS7A&Nqb5 zO$X_GH}Lq3>?ICLO#-`pI|g5D_T4+?i{1OZk1%ntyMHHP#^Q{-e`j$X3%mPw5hez9 zzf1QOroZP)KcA)jWMhx%=exVVFnzFjj}8!K9L@`Sbf7Q~dxWj41dcrdd+ct)#6uXD zhc$4|4+@-`1b%*xcNgY8j@>!vAxsP&zlVEDhmXI9dr609P4V~m!Qwmz_di4&e7t{e zbcy@BP8|v-!Opp2{(Xd*D>lxR*H7#Bcwb@0<*eaPZd|MLgeU7vdGGp3hvOaWv)f-f zJnsr~0|Ljp!Q4P`ybJI(cbG7>AI|F-B#bXM`wbSxCtmx9NQXz5AL|_|On+?dJ4~24 z$7}y^>8u-@`;HK%KQ_;0q%iAaJ+A$ugz?4Z+Mh4nUF(R~{?X##@ptX_&w*paVMlm4 zcldbD1>%oUy!3k0fA=(29K6Lpql^thZRgy9kUO%#S- zCcC*KrNbYo{)~B)TINN|`6bpQ+4=n#fA@hu^YJ)GN$2l<@bUVO7Uu6)u=(y53d8f5 zJ0@`IUc)5=$6oorMKoC){qe`%R2}^H7Ddt<%eP4D2Co*zpNI9_pqBN}{-j;(!A>5L z?f;)|o%1_(+jv_3!ZTNPIXZv8TaHc5`{doaTO!}ut5)}!G-%?KEAD?~^N8CEo=ivh q70aM=yVZWQ%ZyD|oxJkH!#ZDHXY?oU@3v;&1~QEN`SSuY|9=2Crk$t& literal 36232 zcmeI5cYIY<*7tAd2nYy@qCx}(kz%7OLMR5Lg{ojQhU5Z~6ih->R1if(Y>d5vT|lub z7A#m$ETdyV9cR>W9D5xb7T(|Y-2Ds3>($rykN5NZ@pvBA?BDvWwb$Nz?Y-AI3F?zb zBoeik)V^wDa`@mrBMQ%Y_KPPUpICqT#+Q~K-Xm*m{}T_`vFE^j&iHC&o3=+zzC5vU z{j%fs&3Zk*X#A>$dBc}HboSQ^Ti;ih|IDeIlY?GAcgBgIjkximb5F~u_qXpCDXyNO zBl~|lx#Mj=Ke}vb?yD=hPi?rRVdw7imY%!%rcO^U-=)>N1`;U*92X?CzB>zgaS9!QH(s z->^CNiq0F~Z}QNoS%<&0KJTM<4qJcjwNG94<%ffQ$bah9`JYzSK7Zgxy+;mQdGn^} z-@f(fH_;mNPyPJp7eDNB$hm9R4}R&UCR^6dyYKscDa*PCt{$D)^4*uWuUlDs*U0Uv zN6$awtJ+;>%=n^ys!y}h!=|lT|7oA|PCM-K%U*4F#j0DD93@MwME>#fPB|yz=HxFd zdEnj*maIhnhwIBO#_~HwGTsZx#I^_crS&7N>Z*SD>SG+c2_p@^6?z?$ylai_Do$y&DQ^nJQ)7<%#QD<9db)ta{VPFnW&ofcKD8*u4~t%vS^`OiPz zvE|L~9TJI2KfKXl$6wQlKZE=#Re$E>&vWv>@$Mw@^ZU%`_#0*H`R}gyGHdCbW17|P zIIR7Gi`OkLZFR=a8@F7uTS->I0WBxi-8bip2YYnwzNy2TSLA=SV&efB!l;7o{`%Q# zo8Q`~`I?hPFT4G<$qnxxx%@8GV_9B5_UwTVHNU%Z-D4xRp0f9c4IjIvv}a^VY<%k< ztG>xN_$lQLn0vS8iR=^?z=7O`y*u{SVFh{r4 zonA2Lh1>3*IN^!wF6xuotoIwW@0FpCPTiS5Exsp%MbREOY1i?Yqj82aEWN3+7`>4H zTxQzmZvLOU`RAei^KSlGg8r0r4r=x8fzLm&f5Ri+xqH(!SN%A8 z$o!$aXjZ*=!#m5*DagHSb@l4eb308){C{Gjw_2_1>*X%J=z{@WZ%94=Ni&X{GhvsD z#y*g9&byt8PAIKit9|`M-7IBi`$Vz&@-){E^&hlMwRfxCE>SNrE^lJN@S$T1DhuZo zR96-jm6T5t-yq_L95KG2I9XLxSu(S_qOzc*yf`@*dn5HDa_)$6Bf3>p7kBI4V?W|= zpQud}*_tL=B_7cjwWNnXdr1Q*-p|((pb_&vb{u~3kiO? z(_Ero%OqMz6jE_&M=@qAcwPP9j^gqP=ap6z77s40E>!G#5hprPRxqWoDmkd4w4zdM z{fKAoWd(C8Docy=DymAVODf81`Y_+Jg7S*WvcgjO*9-BPds)HslIrnrsralV;)W|V zk#CA;ePsnzGv;3Q zN0dyPULDP&QDSGcf5e-$qmSlw}s`?W|bCJjx8)MnN?L|OXaq5+LU4C z)yZ-tURiLwRDNd`78h%o2e7Wj(OJnbr`WJz4OOW;?4mjS;XI5hDVtfE%&RCVua4)T zwPIu#^H<)?8(*HXf|))>VjD$#Di0;)vvaDo)>+ZsrqVI)xLJjj$<%pi82SD>FM|qo z*GdbuE|2qz{Af(_!#T?^SDlTtwT1lbD*yk-{EVAfQIj5x*C?@D<}p+GiFq?`e0kFI z1OLbJlZuhbPyDPkh+?O5QdChjth_u~IjEvMnNvQkG^vprM)uVGjGwo7UQ;nrcU3V) z&#I2cAivz#-^p*yYL#B)rfFh#wSPFjv6EL<)vrzFv0`4Svw$B@dQRd0SWfFlWBvNf z5kF;1<#o!e(kbBrD>i#iz0R1AnKieFR7AOGtM(7)VsJ^-jBp9bMYj587$@eH$_0Kr z>AA=j_s4S4FdFOExrm>W`jJm6C&ilRww!Rr87pGZyblz0Uvud-ePEnma&lGv=@;mWQa`Hchmb z?;pMcV`dc=$L_$Mna7EFrSgOyPx>8zPv!6T*F>)IP35#SIkkFlNu_l2shmzPES-9I zNwLz(_YnSdBxMD&X5!6W!liPE@6crUw2-YqWJ{g@4<|D z*4s0cC(dfU#9s1?a$Hr&`<$tZZ=UF2Uatk6uJY>N{vsMTHrGy7sV^w?t*0+gV(?^~ zN6qmI-ynl3W|iv}x*xgE*f0IvoYs$h_?><=@0`$0<28xq$v$Q5x2-n2i~2N<`ml!? z`_$BfR2PrI{$})#pZ%Kkq{d+1Gxn+3M~{*6|IK$y$&}L3l_kmY>gZFdW(~ht)8s#7 zuD;9kDXl5!Of=T*%{Z6X{-+K}%D-Nsqd;`F4k+$cQdT&PK-2(!M%lKe+|r6Eg{7&F z@|l$tQyxfOQ8Dlh#ewO;37{e+l zvxVhFUL!wu{f@uh#ky4TCa?T_mf3eoNoh%WvaoVo&E@27?&CT7+WqQoZp&$Gb80Rp z-`K?9$vkef54n{k#nJu1_m}r^Tl}(u!m=qGtC6!xt4n5Yq?rBwN{me{lg=7BZv&yvGs=Q=n9_LK929b?<)~tBk%+wF@;%sMbk$q(0Tm`7vJIAID z)bx+8BkO7y#pcdOHuvIEl`CIS{M6jI(70TY=frjhr;Ce=`v5R zC@mJPF}91w;0{MV1GVVs)#b^msx-ewkst5g$Zy+e9a3IY!B332g=J-hshEu;U)~=n z-}2eXO69)hfd8_K=Rj?U{720y+vYnyIX79#)vCz{ci(b3XylSd`O%eH} z&H?vuc66pjR?JS8X_Ln5w*uS7;ddxeoN+~!6{V#$wa0ti!uElMMKh-AR~NBe@LXEj zXJkqFp_LWo)%ZCPviS`2JDKp)ytq_e_+3Zf_7{w52Xo4Fhhz7?rYP6dS4T8{>UTZr zU*{LUU*c|cQM}mqKuzJ!l`rdKpPy6^bYl7EDRk~hI|+Bq`X0hO=-iXI9UZ&VZ&ajT^ zPK%whkDbRlb{=%jecXqLT&=({2Xo95KYqVKKDw$UcD4i`eox1T= zpEq3XFc$M=KFlMYM}F_avn_s|=yySIo)12rPc{ZU+x%0%FG!zHwtUj(0~enU`G8B$ zBV0U>_G8|R>s;c;{fFx=u^+Vsu6K;1p1>U}ArBOB;ti0{kKg(5;KMUiKIWVUbmyU6 zi%nojEYho;d5- z=AYuy=ZznI;`4?}pEq2c;Fqn|W5nleE`9&#>;3b-94IcnFP^7c_QlxiL-+bR2=my7 zvEjTv=4#ICDyocSlUg*ob%z1s;G0x|cb4=YN9&=%TImg8D zSe=D=;_HF)dOS}!uP5Hu>+w0m&+Ew+W}a|f4|U6&*TX!`c|E>w^!0jr$Nb{=&3$=i zvyK5Vzea%@9OGCMenVp%?_;T8QiTgj&lKbXN=>!67Jp@$9E;%!-3mJEe{+IbAj`I1I&59>%_R) z@}+MBahxss;uVRf3Vl$9@ZyI*E4|i94WwD zIU8NHYV>@G=lN#KTG8J(XUq2}@jN?8+Gy=Nt0j;0ce}eX!#6CpHo||hd6tvMQ46RYKa5aMnA#rsrI+xc%H=L8vtM8wO5NyykfP)gKMpmvRB}fYI)Gx z=qJ7oYFXoN$pG1yJ29uK<;>A%7v2AkYO!TW;QfH%=rb*l_|j)@wTzXi&mQ9GGhHnY zzVzv&Hq$u7;Gs`R3P!#=OFvfn07)ImZu;NuL8nHyQB>Z=-w}3_5oo`$<7>6ZDgVo*ncBL2noIg+b>o?5f;! zQOmhGNU^Aa;(+2Z_hyJhhNyNf?jwq~jEwDZgJ% zk$!xyHvO$HlKw{1rv~s2=M0=G0kglS1kiDfv#?#cIht_wW)4=gIn| zY5HYp`sHc*6>0jFY5G-Z`ieAtWtx62lq4dZCf}^-P_-L^ z&3=!?{QAZG9v8+&zm963kZ`BT#Q?QWO5mJ}(W=hG-xzGzdDuht>@=+p`%@Bpi0}P* zT9`d!FMS3!33D!ZytmH?>o?;IYrV~ zbAtOs!r0qMu-o@j;YAYc<~|diEFlK@r~l^?`2Lb5f%_upjPJf*3ge57{iN?#68d4Y z-+u#-&3<1CkB_1o;pNKes>0UsxVKUPT-De8;ZjQkDMl1 zEIB>MA&W#b6<6z(IT?G@TL)#gZ83vdwy68>=nSIN;U7`18cy&&?J%>cIMPU z(lOXL4|@x9{;+ilwj9MiUfe#?8>!{p#hmf)EDruw`EYi+2onST8~JoqOMD)3kG-1& zo_T>;?+LQ+E6h10J~0?$XW{*Xv2lJ_T$ua9 z{P1TU&N=so`-BhuIqS@wc7f)~9pN5vo~ifv>=}Hx1Lz}yPU|s83KJKfQIgRTY{bhG zW?!(42{xa{vC_Gt{fai`*P)mFs_67Sy2|Q~7b4TaPezUi9FOb%D7@oPV*Gf6RMZ)l$CFW5q%tNlQB_(jo1;^7_JTRZ>&kJ`<8`G{I$XT2R7r== zQ4H6WYU%Lo$t<-z>$M*yt-Fc+-{?8Gf62v*2E1kW^X1{sD@CZLEu?NQs z>reE%jWg7;4?b%r2$NUV?|L;~Sbw5=g*``@as1tWqBvq&_!)+G&`ILBH`ra)z?YoEvOQg3Wj94C&Op_)tE zJ}2*g2^`-*?t6aVsJXts7l?Cxyjnauci=*`Jg$!yNoO6ju8$WBGsh+p*T+kQ^(U&2 z*nMU%6-GyV?k^LDXHBk;mkYzYK3*ZrLr$?>DS=}yVD_H5qQiS0R|)G+G!OFQZ>|-> z*gUV5!ps@|fl#Bb7KSHZN#Ga@>>9mFSbw4#O%7dORtsZmC-EMy5oT|xw^yh|_Z_}jm|Bu8@qN5Sm_5ao zsYb6APaJAAI8%)#Mvi>QEpv+3=v$@7YxHf>;o>#=cIogris2f4hje)MPBc{bQ`ayBrXY8)g>xJ7(uz4>Z5{73Sa}Nu{Gyix_xHDg?%26vG z5vDeCpJ+MLwB(WgLtR|HP`Az!G~H%pGSjE>sq}*n7H^n zCV5=qTK$AD=Lg%9!R9-*Q98AnpRG9We4{=k4&Jr;X<=f(Q>!Y&Qmcu<7;S`~6UOEm{Jbz6kL&GU0|#xt7XlamMtxD7Yw$JlMdytFjgER; zgI|)){AgW+UlwL;?yGCxE5iB{(+Zz%% z<^pCGkhTaqzBx{}6_A{rjh|$HMlO1diBX*T1)g^(U%-%-?tS9bs(k zB(8t|5+<+Ivdh(?`+mGD%stJP_>BKsn0#W(RR7)+PaNtWI8*&2Mvi>g3+5EBfB%sl zuYd1Lhl|(052VBAD2D6bhtlCW8y~6VVNc*cmcWrGaC}eT(Va(H@Bb&l>^0&Xek#n~ zW3%69!tjXe-{->mQ&a!g2cNYsgvl%Gcm4ZPSbw7WhdoC)UjM!lM@)UYA_JI*pK`J*3s@|k!{m>PvIai|~Un$~rX z+C+_T-Fr0nP*>>leb8xL_qGTV7oQ&_KT2HpeiG)~VEZ}Pe7Ckrr|u1uxbA6)1ib5B zmULpkQ}=4AB|Z=5277G@JZk|{_fD3*j&K9D)IDM_Mz(NW@z`9?>IuW~xbD>t97EZ! zLEvz;U&Fw0?(Mf-;P`I!{cR-9_3>Kq=-h$EYI$5An@DFJw62fa3o}RVv(IKz>F|ip zcQavl=I%P$T$nZRZo${zkUI!7PseK^j4!-vsQwYd1Ti_^{;u3nI=(sLt`FauJ4weE z8*6H%mWTbpwzC9|b%8lYtQ#HP=V2G&^jh0m9K37ouEKDxwYv#>ENr_=;D`-&t!*Pr z9@94XOF0xm#IbfUED*MnvgB=y=o_py}_2L*0vW<9BM5%Q>`UN zj(pey<`l2BdrFVj+P$R1#cOQ`>F~sGt?eiso;}%HEf0GF-$?>Tp1|=vfk$^9X?@1_ z5#~%F&S7U^&ImU9brFU~e8##8a|StM_Uk4Lk2v1G!t4>t0U=q?P;c;4q8!pzh2;v2K4bmouE_p6sMV{yN*yMJ$C zY>e-7(npxS*xbLbu=`{8oDLH9x*YRham2*tnEix_iOn$&5q3=M_U$jsc-S3tfH3@6 z&ENfVq`N`$%!Tr-|qJ zjuM8aZ~X2wmhN}*XnfS4nn&A7E&aGp-V@%Jyg%_J4(~SZB(2}cyf=A&`JL={aIMfM zPc40D{Z1YuOk8}%O2!2nKU<6!roLdC5NtVGD}SdoQ9AGBQ4+tC4;KgTck&U!#DM3W zJV`C_d8jYgCrjX&7npbQ0@;rgZm5=bGBFsVop8P|HorrU5{Bb3cXZ&O{r)WoT>Sle zOyKIo{0ajX|Gm)^aegOXCtq}GWszDQzmtolvkqGCe^QwFFuwP4sxb4$Mt$P!ObZED?qyp3mg5!s-&8N$feojOFoX2;+~R$1fEoE;h$56NX1z1IvZs$%)_f z6~geGdvY*Sn1}tucANx`Jb*c?b~3t#%?rNNW!CO@`|-l;HSg(5)uKD6CkUs%+vkg8@33Wh zx1T7UIK11zncnThVE>pCbB({-Pm&&gx1TH>F8*#`ARV3m`BXKDefzA&f6J{~hU4 z;iVb_o4GTE(OI+qS;b}eNwBf*v()miZfs{u;8-`<=jI$?O-)|E9OGQ^%!M(Ccb+g0 z@vtqI{6#`Mu-AXSFn5u-K06l(b04w!K3*tHJ;3ICUL;ID>FXMCu`s@zGxmmgFeYPr z%u9sR$GlV=V`B4|mkBc_wsXGTt&~n|Y>bD^`*^i5`#4a7pYwN(FfqxWeXo^n zU+g}o*9mh@>F+any)ZoS?RSGPe)P59jl%H6Cg0@pCSm$x^IokICKi5V$nCN{^rMHv1pjc0DHboj**bGHh^lY5`b+k}siV8f66-!9De3^u;);O-D6 zUwqr~t%47GTcnn=NbB#KJB9H%F0_l((x3hJIUFlIMuIPK#;GL^t-os~2#=TeyCyIA zOj1jqyMj*Z^Le*0aq+oFa<2p%-!M+-iNM9bb)F0y-#U)BF>v()7yXVoaQtrA@5iUb`J3o^@#xgXO=@}k zP4tX(azN`d^sF#z7%XA_%*}W7Ibqfw{|Xc{wjdl!UXiMqIAim!!k{JL6?x9`+L3D-t-?0e0&Z&+-70yBf>jXeKdEe~_V_ND}mIf9uBdw~w`^ZgIu^zW{J zii7ue*IUAH&d1xr9t+z$5;$UmosWMBlaIC%^6q!pyTaJo$%rp?&JH&FeJKo& zICozObJwU1=Kd?p-J=fpXO6Fh@pXOvMwtD9H}|bDJpJA8yP(_W```m_Zi_In;_-iw z4j=dXF>u6p&G<=J+Z@#l#wWhd($B%hS;EhKwg#R$gFj=r4;x54`rzk2S%Iey{>;UF zYQ_5C=RUP#eeh>~?o%h$2S4Ylt}yd<{i-J&j(O3SZ-)B9%(1xyyZbf>e(u{)Ivn$J z-|d9m7rXm53V!a}SUMc@bl)bz?u*@hw-0{q+f+In>u}#@(%lz3d(T>$3$q^PWo`#y zc*Zl=LKvPnKI1Kg;TI_mIVawZ(iw;EkQ@m<%z@gnQ?RkO@x5pjw|jWD&1x%+4Pw!*BD-#1}ro!oWz z$qs#3m;3Ay>w`VLPrJ~EHM>vySRd@^efA7}$cOvv73+gNy-$bGhg`W&$5bFVPF~9R-eg}xh=Jg#Y%sHaJ?`?PCI^yipLpmINy`G-J^u@*;I%$kv!cD_i z=)I*k3;JGa`$(rY;onhhU+GQMGUwT950dV+`JGDc4i=Bie*I#8%Vj4Xeus$1hF`Vx z{xQGa!7oqk0P)!T4Vfd%Hv!}L-(wpnjNcgf``=?5Bpu%8Z?G_9!aG+(gyF}kpL2Dn zbjHBO&tuFrR~VlDjz3hGF+Hzg!f@l{Z|*SZ@bvfh`|zO4t>*5G5T_-je)lY#BTOxD zpOK*tKE7|GVtuf?k89Itam2;Xaq@(ji;ieboH5cpHum&5W5p2*KgSs-%-VQ7pYhTi z2YY&)3F3%_pW{pvCJy}^=kTCY7qO?uIYJz<@N=9=!o-QMYqE6D2YY&)BgGL5zx%Y$ z{H%~K43970c1H>G@NI|fXbBv(0POo)And#F7y0|1A0r+cesjbZ#{A9?etp$W5s%G& zMKM3VX^Dqlv3P90Gs&3W1;LLyGgUk`pXq7B+!^YC&*pStcY9l`wPS9AT%{b2q8y)zaBRT7HgW4YPzVRLj23mdpt@V$Bt%Kel->8@2p+ z>6{mAC&X;**L>;JerzWO+il^jog^Lmc-i?q!^y!eH9BwD7f9flD|mzY5_h36eGe8k zcS_*+XMOoQG1jywaQI{A=VbU(g|SgDd7r_ZCY?RP=6zi(?0v=VedXRUkJH83$J`Qe z142J@X9PcWsrmPxmx{v|8*?DunZm@x=Dy2>iO1uAcls>p^u=bsvxS)pHNbx7NXHkO z$2eD*aj?1XdBThl@4H+&V_@^YpZynM`osI*`95D5p1Jtn*}gy+{-S8s+k7t+=l=G+ zNE|$U$hGHwv2j=Vj8dO_eZL_V{vPc-HE*Um*<7*ygSb zoT!@lTqTaVU~?{42-6>%`>qrwUObmqOJ^Ujx$iZ?^vC90UMmbw?!D&gVqBiqQK>my zFAiU9{_iNRGFr4Rdt1ujMah<$P_+SY(*Tma};fF}3ZtkAMDtAlUg?@NfzKoHc6igTmN(%&iX`G5sy{kT`s?+3(@t=e;N1 zBjWJI=AXkJ6(&b~cavNEHb{r(8_i=pCLNw{Npp`&hezD^31N7Cj`TPDlhVnp=eAK8 zj>kEEN;+$*Bf)Opr-Lsx`)-Q)V)xk32ondp`#&qpSmeR|pOfyfu)F{B!oF~^n|BeIu{)TjT*2Ldcy8qwB zc@FOXra1U`|9?n_cYo>`bNZ(^Vq@p*z`Z5RT(R-Z;`P(=&4SO{!i>8>fHiYuy|GyFvA-*f54`{TG5;2Z=dQBe_k@cj-v9py!%ddW^WbN#*W za*1ol7Gd%YZ=WB8>0_TCh4F#6&riaPX`i2k;qbH1R$=B~pF|z~o;3LQOlFCrFE;zt z5+)8c&VIGU!6Td#&Sf28`eSq7y26|t`nnd>6UQ0G=DziX>5t80G!P~qte4ut7!AeY zi;e%!ie1EQC)`^;eI!TdjtmgjNE|%=>?!xr_qMS(>^z=l6Y21X{k9jzkF!V};chgQ zjxRRX&1S(zO=S1amCZ%mt2q&q`nCfOdZ=&MT1eoiZ(xtnQrP`Gza7QFBfghA2{Se} z*WOlv!{)v_3&SJkb`du3-@mpN$69&kVkc+RAkUH3fB&_sF!hYOL_g;5IJ*fu&Jps# z*W>Ok{Dk`8WB)cW|4H)4$M1-?!q|CllEZ9a9&(6n4+$JO1bduz!t_JTwHJmzQ~k~D z8GNv@R>z|CTK5V*tRMgQI31*8=NrQ3rlWMe8+d$1_7(@FCV}0)oq{hm`|cC-#qRy? zEKD5i?%ze2vEuLXuHrlvcK7clObqOPm+mV}f6teGK1=(_#vaqpcXxkb`e5@O9U#m& zIr3$X4ix5LkFa%@z_CYQkKIF@83^4y!*RO9U_j{*g03!ss6&u6&vTu>!c{eMbt@ADibgN|^Pr9@qZS!uVoy z?aveLrFFz>{}^%b_`CM|=fJVzup>O2JA6FnapI3rywrMAfA=(A9K6Lpqf8J-|JD-X z;^*HnPZY*ZePEsZK53rf&Xr*EzMdfccnN--lR3iN6Iy>uoG3hB!tZ_XsSZ9TtMy$y zT>Uwh#PS@D5XX4fSRZqkBn*$(Z?Z7_GTF@?DINYu^=HhZ)G{wx&M&d@W#{)}{M`rs z%*W##C7r+b!N==ATA06I!REVHAPmoA?wG)lTXThhW3T+*BAOzO{`g~Wst*2piz4a% zZxMl4s~`S6tmj6xtcUg|?P70s@`z0TKe%_xLcj|79 zd~2^--9JBf^3*FIczMgnJH|bgitsCzLFe_T{aCk|o3B1)<%frMy`s*TPu_34X5R)f M+%~eyrkm9MA3e>YGXMYp diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit.azshader b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit.azshader index c4a83a26dcc61d813d22d92798d7918b141877b3..0f42cd04d6971885c5d9acfd0d5665eee62d132a 100644 GIT binary patch delta 430 zcmezHn&rzImJP;iLhSOBjs?zccCK6<6U6v&)1iup$p@uG7#Sx0bl5!q;%3Il1}rR- z?@krn9KbP;d2)WS)Mmb->r9LZlNF^UH~%j=C(d#3V^5TA(UA$8&#SSr<1}y6&v#(6 zHs76k%aWrc)_9x9y&L;C@66<6WMrKD?)>Y?>$1CX>ZYx0PRev#asHkdG-JLH+z0shC7Tm{XApMalNq7;fb*1 g*2xFXYq2yiFn|JM_4Ku-jMf}}|Gub*GcYg!0Q-Em`Tzg` delta 492 zcmezJhULR+mJP;if^71Wjs?zccCK6<6U6v&)1ivVf_e^{c`t2doNU0tGTC&R=;oW3 z=P^(IaaC$_K+$!k$p?6(rZ-42vTSarl`i$|D zf1h%iY;}`wGW+K%U}GM9(VFZ~#y?r&i#tfmGELNVbNJ0|Agak+k$Z!<}bwCJL?Igj7f)*-ORA>_riUNv2ZM`NT;bI## z5Ks`cvEZdGwLuWXww44`plBntl}qZumU6HMTeKc)PksA+JE%v$@AP^9yno(#o=j%V zT6?Xv*KO~;=6)&sXBli-$zh|RZ&K!|$NvwMJ|}YcSA&_xHEiL`3lH^=Pm@S*I+GuS zFB?0+T-mWWVsXd!Fa$yVp%CN%{=>m99{ifX%PDUNqT{UtoNaIbISYcaAS$G%0esrB zBn03wKo;XI>2C7_RodvR)YQG82d+pdB2eTg_ZFm z;XJ8l{48hxGDZs`lfNf6z7wRlADQplrl_PZ8#(@*Lyvq<4kAm8u8)Bn^i(vE+kZF4caZWGM~?4e{fcMO3_ zppv=3Ta(Ejvb?)WS7$$hTyA*KqZaBW)1xjWQv@P2JH(WYHs- zk$KAC#22tX(1fqr%fF(fOH^3hMneRDS)BZ~*Pz*JQtdi;+taF^^%!z!O+;pFy#~tj zBS{a9Yh}6I?}s-y6Km-Yx1O|16aa}NeW1y3Qb5MH>e+W8=c#0NE9CqO>D;Vm|6Rp? z0GxK($&b}lr4C*8BeP%|y)Kqov6nii!Ak&i@Mu#P1)VdGY1`+?I*#Fez zyzs9y`2|}xhx0?7UP8wxD6lm&5N}r`x=GLe)x>@--+EM#uqxis@C7AJ2vY|6&15(# z6ud->b2*1SlMc*qXGZ!WnUCj~V%AS;ul^TI@!4N0ux5@t2q=Kr70^O3!Syn8=AP9?w}i*s2aq3XvS5aY2v2U z(WdTLEwac2^Q~%cmD<}VFU-eRZ~~J4WXKCpdP0_oavjUx@OX+*w9;<{xp3JOh-s~h zJ>MWm)3szK#FbyfhjZ4@lAyVC5dUE>$nLewdoEt%si*w+vh}E@RqLSle-A!M?|huO zRn>Q8x2Ho-_e_%g5|g~^Xjx|EemzROd3_0lQ96JN=qRM(k*Z|WMp4tZo)qzE+vpYB z>u8aNJ05eDR%B6bMTx3n`y+=Py|lN3Xgny#MYC02QCL^8y%1R!MB8Po*rBf|(j%{o zAv=RAwi+wm($f|bv~6!!6dGwF2#J|Sh-t*1wLfy1-KAeq23j#rEX-9?x|04DWs*h> zbjO`nhuA3dYLLZN=^~H^z3`lA@uKtHaY~Q{=cUnlgx{ozwL1nXJUkPW8MJpkX-#Ie zxKvA*P<)P4_9n4wZ$7CPpFrQrRH|_5`6$=~0=6}{H+o+t^i2PzRN34!uFa}nbl1c%V45dXd&#vtS=#M*uh zqN|>>+6bYlrzl8zECQm)pF%31mxUl=pF*S?9fD#25H_pMQ@}~m>l_1@UPh&q8d9Kx zc+%KqJQ+;mEpe(@;!`7qT@!Be(iF84n95scc7093;Kd*3iPcn|k@R8knn*Km0|~qE zGD!uMx5+SnmX}iBO2ROQ9*U5A1<<+y$eKk}`7eaf2G}^ng8FixToFRH37`+JLiz%# zs&FAx(*Wb&v7oy-P-P@SelCFSUxln&s4CS$h<60WZ?hn$H=y1qguEhvB-fziBC4up zA=Cy?6D%m=4JenGvB`Em1PvjEfmy4OWN4c~5#Va@bfFt0-h6ZgN$3stBKU@F-u|<@ z#B-7`l@1<3VXKJmxRn20yLjj`$5PKD78D*5Vc-o{8$}q*-rMO$O==xJ0M9i@@N(uh z6N8I(HQ+bYa}8hPc}gGWb&66It=S|dHYlV7Q;2HZM65=fdX7AKH?evDiln)^kdHTS z)>PRjFfF6|)ZIMxJl)jY`F;CB3YzmbmqIEt)vwRNmlcySB==X6=Ow3@!u=^$WN{&q zKIHIP9X@3a2D%b;_@p{GA7d2`VcKr08LM#WUQnqtN9i~I;hWg7-oWrn{HS46?*Aj% zCBB(YxP;>tW8T|syX#xZj$SPwTuSit<6oCK$=+x51eIJxVNByB8)WpvlsJ9RzMv&W z6neU&GyFnZWXJ4P94Q11*L=KgsJ(89X9d!CV@xi(SXJg!n&K>^>>R@RznK(#htMus7~oW* zC@M+bvT<{XP#5n_Z_KM~+uc`Ib>bVll6&wYXM6@9URph|O;*uvPI#6$Y>U(e8#rykr^E&~J8OAE`+9KZ1} z;H|)eJnf3J~60+hUzUuIWpQc3nmfxoI>2mVUfTbsN0P^Dvi9j>Cx10L8< zT*xUURKQuLy-wy8z;{Q6h&J(x@gCI2vCNT@Oy!~|Pehl!oKN4CsgXbKDOb<#fkKAb zcAx01s=d9azW!?MbzqeiT({Dler~t<^Q$MWpZL7<--xqHynUtnWZUk}&->1mwLE#h z0)rNUP|6V>S#pZGYvkgj#dfXVHhFAdV4{Cg#9y`!TX~A98@bps`2S)0)?o$KJCxe? zPhviO76gU%Aecw*m@H8*A9YXX3)UVU6%0`Q)J$L2h4K{T=$gYv()nxG)s3bNTZN+y zHmYA0^LzIT<*P<-e%IhBTwC4XRhwQn>S-HIA4XwPw7Mxk6n80(UROG%q^u3*GlFk zJ2hGEpB}ed1|m;h?zi=y9KUvPm?e!CN-VP~G4)>ty+@pKNx6ZNy}!n5oDI zrntGCrk3!I)(=|3I?m4NZ2hEN`AKJ+D5^c|bVqn(%*nQe;TMi~#6(_jk`;OMe0zuT zH90rr!1DR|Ay@C_Z)zU+IDh%iQy<;UoBy%X{*Ut+KkwT==PqmC=E;w*?E?j(iMrM8 z=zKlvFLfKcHE5fBQLDa9b~h59f2r1jvu&LbFRC->5icycKrXabK;8-url#Setl+HW zvC>B2j*p5PLD~33d>$C~ui1Ta{sIy9oSh@Z3ZlYaL>~rGk!5(#-&I)~c=@6Kq16*I zciEwb6CiPOHTI0+CzSn|(pR?cMCZ{J`)WIDSM(j-eQx)Oy)CY{K`ejMR||rB6qg;( z69xT4?s59KNAqnDQ>gIVRv{NnF@Y2rqsEV1wA~sXu?&g$eVajiMkM_^qJe9+Uq6H{vJvbfcW zz@f##4Gk|+{3bpxy{VreNUSz6{Sxg;1{Vo;`hl6mGV=16fX(mX9_h_O)|h?P)wZer z@rnNG@o`JH-o3v+!_Q+2ob~@z~!qffJ{X-KV5j{a7 z{)sVz2a=Pf6qG>GLyn%ke~+J-?$se)~#v z2{*Bp#Nbc4%bE7s2S{v7ZW1%IZ)F$~ncS>k4Z}}Uk3&T!bHYk3S#?H1H5{4kr9`Sv zCuB6!@0BYw)q5bU1$WPC# zIXT7ICB)5gYv^d=SO*gTb=)WbO7_=aF=o1wsQm@a6E@O-t~C1 zWC7R;#2L}qzXh&7=s(+CcF=7?v|1F9eNL@R=+P4N8O5F%d&RP~1-MI?k41GL&13!H z^=s>FscAyb_4PKYZz%VB_uekMcb=>oR{>?X&(EdIBesULVO|D5V;E4SaK9gxYy0YI z`s$nd4kuyBV)ul$6J|Scq|b;Px$PElFEBb(995RCG^*VuWS3Wi%V7+7hIW9h()0$Yezp*mzAR#m9-Zn#)vmihI!?haJ+HBT?U5}+`%IBt z5Y-vka@Mai{H#;_{n=XcLOtWl#_E|&jLqE1Wo9*0$NsTN`3ED9n+Q@V@58LdL`_y= zumOb6aY^0Mo6{gY|8u|}F^LTlrr*v_8-Ray0sqL#@Y>B|FVrlrme2Q=wLB?W-&_Sg zuCE7w0ef3Our3BpJ}Eh}JTgD%F`62GB2}53T{^9!90HpuQ|H;^k?oP4PO`Ie?PX=; z;?K9nhkA{-CI;=x3n(ie*(;e)w;{5UnDp={cs+MxNvcqXuBNY<^az{*6E|+&05(Xg zD^q5c-kY{{vue|a(uS#i$6YhME~pbm-Pd`1cVpcxs$Yw%#p{AXiMTj7e?RvVm*Cb{ zf;+;*`UJHutuFmmTD|aS`p6Jin6JB9CJ#GV)=u@K$6fcRvvJphO9R|RAQ-pxJPdTZ zEDCt*VMM^2;SVN6OWh}Avs2&5SsmD+PS{mOi0FIn2MZ-;>tZ5G6ROulcOfx!hZNG` z6;)Z9$zkoJ!|O_%R#->d(Oa>D?pPJIx2n$ZuyyZI`n$)leb*l)Ady8`alO*n{XZ=2 z(ykamSAMTu`O|nSckvxVYKm)mpX+OPTnp>*R0~z!P3XQnpU?j(GyQUQw|wTg_eA5l}NI~#(P4UN*}jR>WmVfnC>@nzOdkb8_q zCPMkp<-z-x^ZiCcBKM=l;0A<3863g*LVc^T`pwB} z5_em+)Mx%(3iOL5C~4*VkYC=tTM(kVn;3H7O#c4lx+Cdnx72)8|{&kzeQm$C|%BJO`TV-U#&_gZfx+AtSSHP(nB{{yLqqsu>MeM-JuJ{Lpxdy z2|L{xuQ$)l&)-%sf8&Pi%_XZ!jSRuDcQfj3=_3uJHL6@m`QJ0$FXyZYj0_-t(%RZ_h8vF5dEH(ekY9;#HJp7r`-R#;o+U`i4;48O%htaKPE{QcSwFL5k5_Z3d&LhR51 zTl>89?jK_hc*EbyTpc*IY~sti`YULaHhoV^RM+_5{@hpUi9POhFTwpVgbF- zrvIm#c>r`Xffeno&Xwv`5QBZ)E*q1e!|5s^esHOsQfSv-9X{fB6@eLPl{VkE_JCo zkp4n1gYTILi|E(Ssk=ZEo)D`vn>EIKA%jH1HkT$l8g2(CDjg|$uq!Djh4R5RXA}z( zVuVpgUY2<*bG;MgL6-}&}8<==Z`_`Z&li%QQ>I0n5`U= zJBe7u1TD{`kRzfrq+HtdRf@pt6_1Q+Pemm~*oN1v8unaQ-7qY~^xrt|%^2o`<7P6~F^Pp?`fnMx*;A^Y zvFYMeS%tDjb_kr`18Kiqc9X4<<-8iWbWQnEp3I$!*0?_4re?qJA~oROYoaJ(^#s^i zz4h>$R8hsj@tlWLbi+TTnQKI{-vVhj;wfANMVn3_uefa6HsQNQwC0MeBePc%+of?5 z&q`HfwdNHs^8>q)2A8$ytG(0d_B}ON`%j|r+^{(JPYKbdVV!f-DHW`*vOz|0Q+WUzr1fnTyIo z?4OqGKa?lwWboFkW$?r>a{%IfOm1iJPLZ%{8fYKplDDZfCbF}Z^=5W5>IVfR&-#(< zVL=XAC{8bZ6bbsEJ+!{My_LwApscojSEh&V_Zr~Y}IYi1q zpN`&ViOiHkIGtM1McXi@;|D?XQkbu^2vEta)J?=;42WR>F%b2Ho{E^M?m}H4+EuBh zsBpf@Jf~T#7*dKSsEv*=k!iH^c|*=9D8zG&W^=9td&18wFj|EE{er?GJHJN9(r2V5 zMp0Mz#_4YWDWnUeTb{5zq7J@cMm{$4$IMUVs6&Qe-p8*>6Sdt+d&UA@ppuXeV4=?PM3y<%f=|7jhO9T0 zDG*#b}>fncdWQ zoYi%V7Cl|2EaZ!DN*44mZos_2WHG@U9zrDItW-3ikljr>bUEB6SgBAGXWT+0bF5N~ z*-b8yJBveDh%3ApZ2?I1U)T{dKu${wsQ@|VY!sKT5 z*}TMyA1Ec{q-3tD`}xFd*p!p`7S`-^a995M@hl|JTNwCgh%jF%cU&Any8}i17o4B- zwxbdYO1oUChJh=a#mh|6r*4s(TzEfyJJ<*s}ZdBhj?psaFXX&t0lOUmV67 zU(8=|x=bE!b}PS*uA|Gin-u&Nbq?|#IZR@#kaJ_S$*smKf>6R9^GWj_`IyM+1CG_Z z^7Z2jujrjwX#=6?ZPKlnCH~a~cp(l|B1C4PJrXwR-4=$r;h|3E@heG7WES>jrHsQ)^rT3om3AX~s&Zn3aUNv>eQ!0N9Zp7(Jd&S@Z=e7x_nk!*@PFJcob(OtTDVArOsP_e-q}>Uja;MJe zim-p{u`X-=kdZ}^YLxn~z$m4Cm^tsp5}{E{WUB0*$b^L3u2XZdfl%!wwFhvO8Qjc; z?tcg#XGTnCg2d9obpb(yC-?|s|ExomKwtBQuiS%%zMuK919A|uf8$$U?whNbhq!c^ z4~iWp3~m`(V#?;ft75ma VwsNenAw;~GzVgop{_cS1{{>MESCaq$ delta 7827 zcmch6c~q0vy7zvQkO49w0Rjp51}LJShQR=eHVLzUHz-vQyiFKXDqsX0aLPmoRKP$` zBiPeW#6w%9K~aIKO+utV!Gg7I6tsAX9O}^)t;d5suHL(YL))|Zt?#ezd)IoC?7g4; z%+GHR`BjZPRwBkV&eSgcQ~p$X!wrzNF#P7vIy1pVx7~R$cd0%mT^P-%KBO0q`~wM> z{p{}qX5U8u0Q#i>;NUkGzI^x^VCN<8b0f~X5Pyaj0672;VhI4mq$eh0;TRp#JZA$S zj5gijkO7Dy=thDUoYT2nM3Ap^Nv^1@)51oWLxAi{H*+oYNz+7-1o0c#B3~$6@>x1t z{CNBS#36UB{6?SE`sc2uTSU6HPwemk$JRfaB3y1gB^5y_IQ8)izl%3%tKwUm#7kAqMapn<~C|->A_(KcZcq{kU!{&H)MlQ$+gx z@zAVa%U709YWSf+ILD}a6JQnK6ZnQdOgJK-e9j$zW=Vlcbtry+c`q=5176s?`+3X$hL$QjJth zSf8LN;S=`GU>TRzym0E<$mtq@2IBN;{r{)FMlAKj0R2S(kj2#j# z@5DwKqa#h06(?0IMzDb=dm|0lm9vOr_A&fiNIwDJ#L4Ah_&_?v9M|`y&(JyggYT2= zri9o{q3aWMpSdS4+l+YMQFy0wysjZ$(=a8tD?+rVD(Csj9E>~+?qqPfVk?ms^6L#j zA&;c_%-reLjH&Eu-;W0EA5W+ zfR2NTm)aFy*+QqzaB2TEQSbdu_whf~{bL5#t~=4LyFd)|RaBkH{Y_bRv$sXT{>^E| zrYdru!pkD@o-$LmHnV3G-uDIGgA&Gl0eetEd(h18Q+VGIc+Z;Hw!2;yg|`imr%g1I zi6%lLcz@#WgS#9e|61p7IPSOW-2jP@WG@Q<1Y-XXdjh`5K&?7cSIJr=<155W38?2w zj~YS!WT=V3IrerCmHVvga0|LeKNpZqgm*tVCnAqJ*Mn0_dhl`qV8RkqK;$Bl%Yhi3 zAzr(I|K3Es%ccE1f$tPiXZf^$qO^M`;iQT1R7CxrPx}d_?H5xY%uw(0X$1gZIzbRm z5cV1f4`o`rH$UUko&nlDImVQn&80q|Q-9{tiug|VOuNUWKAE9D zHW8*w)Su`uckp69;UK^tl;e;`{`t_<#~Jc6H=pbUVjmIE|G;`xZO~SOy4dux+9FYh zRc(abdQE8rVYducA5fJ_=V}P7(b<#tvw!d(?R0yWvtC%-mVo-DF%I>8_vqFi;1#$p z0B*dH|8TSwLVlL-99AU7xa{CaxLqOXFY8gd10$CBe!pddw!||Z)0p4#uCh|3J%RNF z4!XCOH3UykfPOic;2g%``1WYopJ;DKB7oRE_f$l=(E;XVgIvbd6?pmQwIB%kvdg3; zkmZ2+vL)^h#q$ANP39i%e|FuEDE@v!_09-s#f72)N@ zq2MGOx=jX;;7~Z0f5ij*G7LtfczI7%#_#+I263 zZb0<9zk6>$__{aehhvlY+xrIYUcuZ0}^Y#US?Gg#Y)>?3g zjYo$)F6H4&-R=2hL@jom9<>S<>i!$8a4MBMy5LMr=#Y7#?k9AcyP29MQHls38U@^3 zNi^4qg;Tll$P(QS4pVlnnTTCEfekmQNf>XV1$URaUZN5|uvEz1dBnJ-1x)YY8HbR< zw{!DLwyl-q=I<8{BU5XpuJjFqy&{_yl)~w=+#q^GWIQd zBlG6irg~O}#~mEPR8itA)R+~elSWC|6FKcU%CvZ}4##FlN9od*Wgb**0y7jozAM^ChKu0OrH zeoD40PIJMW@I)b3wcix`?c;X|zb%M}yX*a!v+QPYhs!XS1rV z8aqn$iY!R*UOAzvkEm)$uR1ENA_?bPEqLF%&@_LdaA^UZeB4GKvf|B#DoQlV8k3St zr@pC2K`vLo{Y9)2Pg*PZ3wXr7H3dwmki18kGPa?Sl_B%EqdR^x%i}iQ_Yui5-LDXh zxsTgbxYacFY5;M{{zt!J&DgQArmRfn%WfPJ0E6S>W=$`hG_^epOj)y}I%x4w;pu|u znujSxs=5Y;QT(Rf47q)k}s7sXrFB7bt<=T%kZKC<(=GqOEmqFo}lo z*aZiDg8D5%H?o!5=VqLlmaBLNbv+vYhCA=*)Gpq#^;7G4Z|r{h_0!m+{u_94$DU5P z_4PIEs)!4Jvi|RJ7tIOdO78MvgQxDWzw7+r*7N3$BZAAV-J`*+?=_E7E`QxU3gg~| zUZ`d3@jAhL*QApCLTN$XI_dV(W&rXWncWzqw)T+jQo5mRF|7 zI(rg~WWL9`jYA@!Kb7t={|)^a3?abl-H)Aob5^g2Zei{HxTK{C1zU~ggr~}hL$&OP zITK|0*#-YqoS#=zDk;t1UIg=eX(e~sQ~9S7H#9OcoxNdb-^;p*_eCgknN>{P?(ANY z>b|?#{lFvl=3v3BDnpM}V-`c)2{SzMKep@W6s(S96}PA2aOS3_wDdddwBziC@uqah zL?)nEe&7kE#oM#<;*0Zh*GVNg`9)ix6PH!;rajlp4Wvl+td*3-<=g3(M+-YAChu4WPu#y%d3|cyGTt}X zHaIhAoAM``JPWw>-=U_Kv9_+u1LxHpq*k>ZwH~3;54Kg>T94eeccjosfM*l?O$r*~ zb)x}p#6p-J*Hrw&x}O42nG$rF@qVea&UBh`Wlu%@ZC2){%#5#^Hf3ZUXL-Hloplq3 z?12gQH*f2{Qq~(0-QgW)KMd{;=UrG3dagU9$ByO%R<++M;RP+sOQFjn zq3*v39>jl3S2+3lCY7u>bQ}ex(1u@BGl$!6%8&HrpX__5vu~TVui!>s;bdRYY}}q| zP1(u#eWuU%+u{$-d@f6-i#YE7M820usoUogm{hNG@=bCoVFk*X>d)Td`}qo)<#UR? z(&g02(>!`&6eD)G$;925J63YieV={(QlsNMprYYpN)x1xJRCey(RxU@u`<&4x(lpVgT3QGK* zT&32rhbsU-%HRJDJ)Fmy(wSp(@ZoOH#hZ0mo;UG6h>K;yBSC#HbwFJMJ?qtRxk}w3 zOBs0Y!1)8}^Hr@!x<{9N-7(r~?r1$S0JA8Vv$|#5Y~p`RctQVOYf7`a?(%JzTp$X@ zCs){z7%nBBv^;K`wDesczgBCzW3|{$O&pEp7~-KJ_*HMU!610UAct~BPO^B6 zH)ZqubF%&OLj)rACKU58-Z491LnN`4LnNtqv5w$8p)|{zx&nGo&WOxJP!ZQ*F2`nx2o)`_r0h7-@5fdrVq-As`lp5r|P3| z@#oD6Gv!jXtX*>5-oDr{6=z@G%bDt0c3bCx;WKl7Is&<`;#_NH!A(JP>uAcEd$8k8 z&W&ak4}Hj8u(NnU+1UjL9xrgg1u*(6)dTlxpce;PYwT5+3bne4R$pyPrmt7Hr{f{I zr4`QsUwpy#Y)Qeo;w^8lldX-9-d<$Kyi(!L&71RzS(Vl_VvcIY_pfI;4Dv&)DwK(h z)MKLzDiPfw4RuJbbjZ}Ivqsc!+tj<|n!S~pgEN}CSt#cZ_3X2-<6V~xAQ`oVdAs&1J=7l9lRagMAN93ff!3b=qr?)~WWUW;Z7Ah5AMQBVx|XYAQMYJFQVJx-V@^XsnYGz^}s8S11GZ8PH(Ae zhGp%;Z`7O~swrAcPvi8KbOh>}lJ=D}&7-IE&tyHY*d7c{p2Ed>g+v{T?Bt#e={^;H zHsr!W!P*M)m$B^yKb~1rbh@Buwfrrg-je1oRDn*#CHq>OTI?*Ed<=sh-+(+9mbB=; zQ0+~E>uHnE(BPR;*yphiF0W8l6KP(#)7*wU`P_dk;Uc=g6<;G19TF9TOzGOWVF*#T zFKQV=&~-$)EMJ(_dvC?z`N%hMt`5#esNC7Bg_)LRSyz6Zbru(0II{|7Z#_z zAWQ!uH8mzo_xAV&SKY5s=wkcU-+rrh174}wZ`qc?Yq;OvvR#7xuWs3b&V3pD9fIWR zJ_$u-)8;>3u>I#@_@b;u9ufR!CvBaU+Od$G1^~(k9X3Z8qa%iTqq@vNBdVwyy%8hP zEBm7(wW@#{sz`lwWIuL(zc6AFySP6(qB?qcS8wEyC89yK!lR)#sJ}PzxiGMyH_8yb zs7n=jNj2YKGJLP2xw*22`T(tX3>9b6ir}X;ym|-J5U}n&a%m<}F5l%Vwri8|M7RWhcopirg^Daun z7}!2D2%j*LUJeXr=?Ew-J$e^QUH!!jLOO#*N^k}(7P%Y=M9ByeHsp+32cC#9x{ug( zzdQN@zCDEY=l^>2mHq!X`cj}KA>MkXhjX&Fn&cnfhl|FnHjo{gnQ=Z~^#@!>t|8zZ zL(sbh)bR{^wPGCOfQw<;kJ9!7=tbS%d28r!Z*q%^l7a=`6bXYd>U8iDSoTg}Q*=^s z=svjpyn#d7;97oOz%)<>EMcn9sH8AKI_Ced-ORknZWO(DJmdH{gn%x8BH#(YS;_!6 zH9BvTlTn~GQeyDHgpcnDJ|G9z4_;IXk3o^i+MK`eS$TYZ=a8uiV{kUl0DevdKD$w>xP*v zO(H;f4?PU`NtuVJt3FS<;%On zI+pjGjYJKn4euKk&2>ki=*RQteR?*yCp^;NKac5wqUae{<@_f|JZIwXZPnL4O0I1u zFRiRyvn1toZF>Qg7!WwUplxujn?~%vud%ilRR5SlZL7k?;fchAB!cXu--8E35b@e; zYl^M{$AdEj7Di;_jzC=nt~}nSyklW!L&AF&!o`>T<<<7&B6!*^T+I)&W2#fmIS6(0 zm^&e)PK{Xl2PYfv^bguj;SxPUqTIXBc3)iH-Ep>ipTb|BXhSk_B{H3jhlY5T$r*hxVRwuKM_>;;u=2Y?>N%R zN1TQL;|#ydk?~hP$*Cc8fUyQ~W$w%q;e5dxBI-RsFBv%G;83D+HXH-zg*tBsQ7v2- zXM!oz(MtH785{uUI8}&N^-g&7MSKyrfRD3)Y9<2^m5N=2Z;C2Dq1+MMWO8CTVjBkd zq8WTIK4u1wH8yd`cP1zS%s!@&PH+cdq2tA$Vb2p}c42+s!S1$M1GR!uX<*8oRTv=Pj-;8%i--;$!Cbp; zVF3<2nK6#c05~%srnL>O;oh6_^>JP>8GvtdRM}oru^TotvVu$6#SMzes zRE&~3#CMHz!HB~I#5fnc}Db%ciU$)+F$ zSL7^%H%PQzzQY9WA(xy6vYi`xVef=+#Hp7bYj6@QC1YKYrMSy*5O;;%X@-OH=n*^| zM5zK6x%CmIn#qJN6?i^ZE;N}d6&N|nlp~P_;m9MQ_l#w$5HMPt)+#`z$AsCP>{uV1 zEe0qNzfD9vL$78A$lzRrdAc_c7Zdp098v9$Gi_DUtNqCqiun%x0mXbvJMcL^WfiaB zafexXnBum-z&No^Dy4E?@W~g^E{Pp|@s2<#2KZkloXl)PZ(x5fl-uBHT3=DG*C>^_ zFLX3}POBntuV_&L72!~2opM?W3E?)PxE7L18f^^6?Ta?@x)l2h_F$jc00D}nOysCo zrqA)=^1}n>M3cCS6G7tY^Uw-);x(uofey^!NHAm&_WV&8@a?1 z@=x3$D?6GyVgKl|8j&4TGt6Q(beq}ZNqM5JeC4awtTl1`x7Ksq>WP?Dug2uDt0%3m zTjlE2v*j;ZGRUU#>gwk&o3K^wkR*?N^VLLcY*P8v*R2M1(s=pnmi}te#BZ$=4#|@- z39sfEVw0z>3Ct40V~=3I-626sa+TdGu@xYEI+@$8Crwc?PRwZ;^W1Ba(@P4JH(!%{ z+C|z-vy(7?eoYayv{d=*HN|BcX=;vQD7Y==Z*C=IMX-Ab*{pT@)T7U5$^C4Y^5qCK zSY)rYV4IT>RqgE}=?#ZQ%fYMOX_-?8SGCVnr8mxXr_hz7 zHbMA{vFftDFh_A5W(u=>6qjwxqfUlq%k8V7v!BME$H2dBRUOWc_;0*gSD}35ii?Q=2 z%tr;Jr{XWfcw#_-M;wBv7h{*824icw2GHmt+ggv#Xc56aHp?NZ7e}wbH5>EvhfoFp Rx-Q`=Vn@pQ;}D?1{{pwXlkfll diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_null_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_null_0.azshadervariant index b7bdabeb4e9dfea986d9adf30d0f57c1225bedd9..d9d30c99f7c6609f3be3cfba81ec330469fb67fe 100644 GIT binary patch delta 16 XcmbQHJWY8+pCE_dzb`7{3=9kaH0}jO delta 16 XcmbQHJWY8+pCHFZ->{jC3=9kaF>D05 diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_vulkan_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_vulkan_0.azshadervariant index 1eeeffa8be8df2020435b46d5b5de152d8ece66b..e2f2a13ca3738fe19122583db01704237b19ea4a 100644 GIT binary patch literal 9452 zcmeHLdt8)d7XC)=;*C&IQ$!`r8(u&KOSvkefPmlyoSa4&bOL5@Wc#%W`sLSi+mKm6hS_olkdY52Hw+6YBW=)&QhMn()+d85*|=Zw@%QbXOU zxkD7^RcXmpg$XgmN7npQ*zJHu^}*6cZRGiNnG3&*eXVTWvT)bG-Y!C3Jj%GxpHut2 zdGFm-CDG?9f-*dsJO&0?O4jY%(f>qgSD#Dj(;I@Weel#u&)N>Q0K1=-#fJK!|JhAS znfcGaZz@g{x2d@ld9pMsrCK>b^N1uh6rV}Bq{v_H)y{v)xQ~iv)pxHkT-&HTGvacv zd(M8}YFE{%t)8nU$IO*_VVzO$O?vm#0Jm2*c*U1j`3A0UY^Uw3H2Lj)e{RL$e_cM9 z9D6v;qsVK&vJ8ns7u5AtOzvU)G_DSgX1D9Uq3nL=P$3_wC+*0^!u4-uMQf!uBI;P;~j0AYAgqC zkFi;554{}k*mCRo?%K-qy>YG0@%bxnI1SFs{K3r@(;;i(?5etJA?ue-+_dpr@6A=|WInNlLl%dEZVC!ct3;2U^wAla_Px|9E#Kl`15&-$Pzwr*Cb(t|-})*ukye zggyo3wWV1;EAKTlZR@U6sE2o)>M|t!hr=TV2c7JDVYBK+MZ<6hY48T^aehsW*Dg=5 z>P7LZc7K-YaWJlQFW$$noPTCb#1XH3#@eH?_m@0=)#K>4tdUlW)bQmORW}tLYu+f@ zb|WHZe|7a4?~H@B4=aL~@wUrPlshPY-&WqCr6J7iM5rRu{rRfJS0?Q$oO|Ehcyi-n z)uOts1x@Gg7B3GDciukcgzCq43})Mh#k=uNzGF+#cY}91wnW_A`Idt%;#1YI<$lHB z|6O@3AY?=6c*VE714nN;zS(CxCu4$pKjOfGC9V7_VPu~R8;e$`BhS2faO#v}e=ZBL4ePRJpHU8CaO$4> zW%+&w7GyiL=+R`y*?5K>Y`s0YX#F6!Z1Z=&?y6d**>Y%G?qIUnw{5)}KQ3R%4^7qC?H5bes-rjVH1CX`-+zkqUqY>4wN|gX zMwgUb2^+jUulSnr{IT1%KZTrYl+H}-7#q6%((d%cQBB7z@jlZxe41hjjQ%jbq1G$y z#>HJ5M!Wy`YOv+CFEb8Es{W%syW!y5>5P4Lt8Zxc&V?>3^xr3kz1YPvbWz^^=mp&8 z>%XLA&Yd@nKUBC08ja zVX8VtIazJgSkz{tCQYZG4cy&|kDH#XPS={!jJh1N!Kl{h)3x(y_e2~sN5>|`2AIt0 z0YM{%vP3({$y$lF_V{-cHCjQA%rcm?CbLq9UkvGitw=5)R}lXQ;STZuwFY^DobZqK zJOsNSPaDW)OO7@m$!yF`Gv^w$=@GdZ8Cqk&WQ`@+w&$+O&vIp7f+`Qj%+Hm#_>(QjAV;bnZ$j4q{ z4@RRVU8m8fX(J6;1|u+GXP>jx^9;tU^a=VrG)`~ArnJrVID_WA!x(4VALoK~T3bFo zOEcSKmy`1nwj{I0Xr91R!rr&G&e}omv(?%5Gjhkdk>?v>F>Axq(~Vk_$u?l-@wA?o zhvu<4a!K&zX_2G^jU~&VNsrQ)HP*cmZp54btTey)snmGj$X zI!9+tCgy6*W1A(g7+e#puMM}&(3ELCr`q5AZ8L;_Ql^EuU9d~~=GfK_xsAj>Y)0hj zve46HBPKdKOFKbt)*4OPG#LuNVqCHv#(oom z$Qzt%dm6-Ctigvqe3bAJ7}p++DN$#C7|%U2Ui6N4laGD8z(hQC#&<@pPT+o^fyh9) zGf0vOLVck7KqAK6o$!-9XGipGQG_gx(!8W0yx-k?J` z0>D{|=YsYj;PfZ%jZX9K^g<1MlB_a)hC}8Z5;+59ojGX_l6B^#J_4M3WY1WWe>h`r zITzYTfioZHNj(^x{>=9TboQ0L#Hh1pT(8jC58hw)gm(6T_lSL;dn)(CN>+PCWoC;l4sZBT<$8;d$i49^HaA8k}{wuO~pPO`UytQr5>n=lsTi zxb{T+WZtnd2G)#)${6blzc3kNZDKqd;WEa2%+E6r0b(!c!!r^oV_?$H*h>@zJa-`b zfsX@m59G|j8IK2X57ar6Xb}6yoU|)JTsI#*eE8m&03u!`uWh1?@%_QNG2ncf;7?mD zh!|^Az75W`Q70~H$3f<-!m%r!t4Sc94Zf#nqhDL_co1z|BiEcDV_?l#qKt{Y(r>bi ziN5ljCdn9kz@rXS}d{4yZZ zmp0bq-I)y{&RF8C$@@l}=V=Z&&lCAi=qY1#pb!wx*fXF^kg#Pz7Pf3V8)vNt`GFW` z05NVC_RtkP2Sj@>&`oq~E;#Lcc;0EJPMqtZEc$MQ%=y~p<|6UkY67u$%qjY9mT_^e za-kFJ0}{FNAoGmVCeGD7$i)3YVy^QcJA+u;4@4hP#{!vlk#m7;w?9|U0<({&kBHBQ zOuL9*2$}i)L8AU5$oBE{5%G&5(=N_c0c5U;d1=c>BlYx?hq&l9?-cJCZDM`AOPm?^XMbmTSK7$; z{6)wL&^Qp|2@c8MID5Q(GX@&Uymd3Yq&z2HAh>qM(cSPX*+$pjZ(1#vTY; zCFD>LZOm_Pdl`Bdh&I-tEde`k555gl0b)G;#)G0k;h=6HzB66G>GunE9n76icl38I zeBbx*{xVkc6X2Q^2&uABXd(q{-)z_(NXQ(PVHDk-6PnzQ1N;+=K@BoS$l4XR` h(SV%BmzPvt9Y1)pbK=9&-}`>& zJ35jiNpAUW+v1Edqld>DR)6&42k%d6HnZ+*(c}Wz`-*JUpFKKAwEb<4v&{&G7HdGToDLVr%} z_13-j3Japnl?G>cHF)(6b`-4Jxuf@qqK>|o^rtojU;FUsRo>NYhez~T+-yO@M+Z}dCVty(`!3dS+136PlsF{ z=9#nKuhK*J@iyQr`G1b_k&rbhyQu` zU{dViG_O3L{n}zA4xL}qQ!}xP_0tQc$i@4HZmzA5+S0e~a?2yjG?UNPBz$vmT+O;y zj+b1&8hJ-|{9NuetJ{W%Z-&K1l)Z6s=FeYUyXoAcZrKmh&Rp&H)Vivg(PwwGY^ZX) zb91#L9MdLi+>DBvYs1$sAGf*WT=y*% zZ{|M@q=}@P?^wFl<#2RMOotA*Ks1u>{brUyE)Yr5)eb4|>k^Ubc3fXOT{Fj4Utjyh z*gj>+r~ZB>sBLj-$D+w|zb)P4cJx-viWlxKnYr5C942X`)ZE?PZ62^=5M5SB%^Of( z)zV~}8u#MHtw+qAa-OUU51TezQ+RS^pMJI4jXSr#`?zmq*8?eqe|&cQu zx`j2{7B`%~o4;aMxcl}|Cv^XM*J77HEN$!W}$$7;UY9W>(mHsdyyP2TN(rFEG@_s!Oh$6fRbJ>FrpjBtr)t0Mi{t|?u; zz93}U3zabwChU3cvm5e9rr+PBdxp5tcZ;@ty|+d1@_BzS!mEFNr|NLK56VUzADdIq z*5CKQ$KURg&&jA^-5+s*U`eaKP8bq!p(JmmKJxTi2PY*Td$oADJgm#!0YhEH;M6_; z%ZmLj5M(>F@UbM<*?5LsY`rzQ==>lzZu58l+|@Nsv+>Y2zMG9#P~%PO^7HiY4+=hC z+AC)weJ=%_IyT5_>cxF0%eUQ)ACs%)ho<7p_KQVp^-(1|?K|V=^-h-lOIGJst;uU1 zQ3b_U!uoHYlYh;6{@88#r;u~?(&=&SVnerI+MPaOXu~l_yzi7vpQSj0qCSeRtM*B| zadFqC5uT}IULE;K-oe3=uJ_Q-Z@Bn&x?`W6YU^6Pd!fTh^AAa3FLrPYTsUWc)O_yq zjbBnSXU$FSSUmAi_}WXo(|iuNH3?`YHPxUyt)v~!PrM}g;6L?O+R1z$cyq}^N=%rf zkI_!lTMZ7q-D*fPnP9miTlB7>J+S0719J|G;H<{Co^N4#Rj+vuk6JrBy_VmEu zkbx}GN^)~nBGwvzj-o~r$dOqVo6%<1n(z-pdSEM3Q;-LUKSFqdygwi?qTW@ls=t$`B_jwE@}iD^c&G0{3hA7`}9j5cRj5YrS{ zTY~?Qmj_lrA3oXg7UMHAY(^{<>+^JC+)uVX$6_QRBRkrV0>13FBqbOeSr$Y3XoKB=J$g88#IyC&4K`&5 z+&g{c-Z$7cDXVnx^!{9k?VJoB?v5et)i`P@iX+=l3kmJ$0UI>Ypk)&p37FA}-GR z83iXsVjkk`Q+JT_T~qXK(3yugd#1*z6X*M)MF+&W4uH-_*qDzt`U@NPLmSsDY^+b4 zIv-kJZpv~kU{pS!azZJYyI^hk+PFKR(REM++Ze>i|6pJEzVyF&;n3I^)H9 zdEWV`kaueFSk&^yvZ*&W^YrWX4nXM~??D!Hzelh1O6q3M_<}XB_n)MHe-K z6`eJRhk$d>>?v#V2OG-lJ@KL7#My85WEePO1wI@y>(NgC5#aQv&q(N;1AS?u&K`3= zLTA7D9=X5VkeOctqRt-i4p8g7Z-mYs@!k?T{ds3m55!8?myw_$sLGx- z0r6oEZ$Wz!oOQUbQ6Sc)&b~gS=%b)>zM&wleFFYw-Y^hte1t6=GHt9cY!Ql$wQ1wo ziBxRN$NW4aqe1KieRzh(C^j(ZXY6Gx1w3~kqg}X*(a!4pBW%dwn~n{!6Ai~S}+=J{BLdfb09h_(PwI6A}g zItj!x$~%o1xrm<(nYhrWK<0T8`BEU$#`|lrQX>^I{%7Y8D)al55{GI7`F?3?)K7knv* z_BHTfOde=4NVdy1o)?}U8I#}LWzdsB>NPKiuAW~v=wi()AQKn*O30j{m{mSx+IoOQ zUsge895FGg0?4$h>pl3&5 z>!GXT=_BHcAQKm}`V(ZXiFt{MS#5w!jB%XH3n2AeUW85`*)Gq8?<(J2Vq$%KM>${a zPkk5g9c-c8)y0rCpfMoE^9~CE-w0CA?=k3HPe<@g3LcLy7SG8`ij8(Y%+~}&|3L5( zP;*cc^daDz6`T03Y=O=*#Yfn-LZ*$mgl(H*W9|g3lWQpjF`oX!JAl?H=eG=UDTwvB zuc6>CgVg)#44vzI9K2k?Mf@w!*&o`~-_Ehn#eMlIFZXpGgKFqnz8lJrwws$CmxqGJYYo)$r0jqG%%pE<%W6NTlTz5li z@`pPdn+1x_GchJiekd!sneSE!VEUa+lg`Wh{IM-UvA21&Efa&y?H*+tpG)Xxe5RP delta 451 zcmaF&hUL|3mJPaWf^71Wjs?zccCK6<6U6v&)1ivVbw3?8vtQcGIN4z?%Vhm&qMH*q z<}pvM=aQQIpp#>>0?&D-$+|bBHrL!LVVpd{mu2&p+h$yo1J)T%j((OjSwK#2a>8qg z%@d^ExjEQwmhS$ubB^z3!CqE&Oq({>{d@7HpdlXqunu{1C+uuN|-Wqii5(U0S)5(5JR0P`Ti AlmGw# diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingmiss_dx12_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingmiss_dx12_0.azshadervariant index 839efa72787ebf96ba18125c20d57da3997d6704..c144350c7ff1c7da6a32247b50d0e80f1d29ce31 100644 GIT binary patch delta 5097 zcma)A3sjR=w*K=l2_bQcK5NNQ( zfFj^D$YZEgn+PhXSP~urLIs9)!lO)dkTMQfv|h`!PUoJWw%)bwy6du5$e(l0fA-$r z{`R-e|M$vZy+ttX4jZdAr4I&FYRuoDWbdHypVWG^tvcJrH(-N^lfYt6!&o26>*SPF zVwzjdGyMn*f*{cb2wDNY1Hgv^K0G)C;oKp}%e`gL#vM*=b%mf*2n8*m!F)nwGy>d2 z0PAYOIE&pm?S_M(8MK=3zosSB?hXw0clFQq6!@?~eK^3gW%H_f1P0eD*^mJpxU4pj zw}@9H94pSxL7(8u^Mld(8uS(h^T%FBwR=?6Yx~X#457T2zv7acv2Q7qvooqYnA$)? zDPag25eID?(FbeU!Gm34ZTfY?vaqqP;9>UWK6XgC%xg>*QpFDGL%8;_f@cuEee7T* zdsACi$eHmDoM294dqRW zl~nNxEgg<**pN_=fuZ}KR+n4pyq&rM^dL!|PAaG~I#10fZV?Y-pU|x5%CXP*RzHHB zBV4F4Hmjq5D~c(k<80g_$-C`1h49X;%aMM~39#9Nj)v9}aVUhpElG(8E$j*#l#%-k zzQe2#6Jqn2EUZH2R1SAFvO|=J&39#Civ=OtuFyinW-W|3T;M7xaMeg?apZTmipl@~ z8|MmKTG^XAyTV?>H_sr#DiBy`W6AGnh51$>!r$by59YmCu(<-HxGNN-wF(h>mmNHe zAWLA*OEBURY$fKK3-=E5i*u@qlaA*g65Cen^+JE5DLzqNoLi3AX_B4DDLx)ioR?Fa zOF`2j&>x$b1~UZ+OT7dy?pWFFKUhahS?yU|ie#~Remb7PdZ>B}`I&Mg2jorf1oMI* zbqT#mZRyei+ob;5C6I)*i?XrHV8F0;ml#Z}T{IJAM`605><*|AuAZbzkzu9C`rRc$gT37htWDMllF;#y=X~BBAn>Buhb@YlK8ps*J`$<$H_a}b3L|`eQGB8 zo=+I9Oh+DBnP!jK7lAm`^&HzI!Jc4P&E{CyB6%9Q1)PSmE!k)0lrK%htOFI8JP)VdOIG|{xQ>KuFhrN&2>p2rC@K;m>Bt9;NyR^Zcqtc zYO|7Dv?m9lqJWLIIf$v-(EoLAmU~Md5h10GYTQR(t#;s^iw^<=(b6_qK(nItl&-S< z;z(U4ZDj>ziGsh3=jLJy{Ti4z9vzdP4KCRmVUf%$v4DG<3`l`pmO#dD?JnwEO~>?Z z7ZJzwc)m1p(jn;r$vL)q3gw})xD+WX-9G8Cmsm5t+fht%ouDjq?*?6&T1emX-3ns1wjEgLszo%>BZwwDe;i95|4do=;X5`eHorUaZXhIoZGq zVRqKLiEdxa8obx0%>7x}xtRjdyJ4iC!W-`up1D6?kaaLUEC21dSjq8Ighn7rV<*oi zIPR;OOuRt;UVULane;t?#qv@lqBLr9&&9VxNLa88&rNaY-q!%z+PGlpr&O*RTEHEU zsb*G~3AW+TuTg5XrN?&5JhBh@MCwU3pxQ}hGuv@j?Zmxj(=*1tvs3fUGlr>I)AZ~B z6$6PKMMO+W6$KJ%VUfQW*8e7j$^x33TTkibDph0q#hz#a6lmmoUScY_j=Mw?_qv}B z4i3yHjfQV#shCbj5$)_KB^n?BvXXM-z=8DKxO_owexw;HTciX}Ct4gLe4#>(74@#0 zcf+KU6ve}}psPhasf_kP9E zB5u&j_#e#FPLoxQO58~i@+YzV@-h%sOj%`nWlaCYQ#VfOI~v!6!z!5b1Yyu*^>h1R+zVdWkY;+6LEPcmWdGJ394EQ}4jkK-0`O_a^R*b{k6< zL294Q4A6=F*@UmkQQxA{PnH?0$|l;%rc7e|-=NPd;6956BrFHv{*I)8&S45Fel7KP zdIHeH6!ZvlrT)Q7P(jv@?SV*uLOlpz9h32j1Dff?zYDNW4!itA=VDtJKPR_fF=q?EugviZY;isqNbvkz)CiA!cPiv%jOH5={KdjIjptU-w>iwx)T7&uv`rM=rkL5donaq*orRU|nw*bk(d;0=2y3mSN0E8uI}%bs~Y9)WtH~rWgX^vbC%z@ zAqOt4bQ=RMy|KFENM>YiE@&y{_;;lrOBdzYA|We4oD#yCvnVUy;PxP$|DSKuFSUl; zrrpx{U-rN2f3qFWJ?q|mtf7G2vk-I5R~h5wE6Nf}p>EJh5^bbgK^jxe#~)o&v5F2- znOtbDd!pWqO`^QNQC^~}WXe@~Q2rsH{AsN22*+K6rkUyP0YJQl={dvP==9XGk_=AI zOwe&>HiC{DVw8ApeC!aw8Uw2<=BJHMCkCpg=LaSRrskSompb6jT#p})sfr_}|vXm$Q;1KO{LvcS3gLtEqA`rg`#80x7MuYg_4qWcJ*`upA zGNBisi&j}2rV4qPozouSv-RQ6Jhr^5-}0LWhugs6aklQA*_zhP%`Mz^niD;MjG$yE9q{yH>`d~+qj+aWJPz3SV1>=oa;R|8^4MgWN+3g>aBtZ zQy~xSzYNBku8>DoaCTsZO>i@l>02GRd+1=*Tw${c-&@_u*1UK(di^?WeXpAbz*);nZqP8y%y2i?W;KgpYX%GC`(>n#~dLKLSL1A2mAT9f2kZp-IXb@i# zuAW69-jlz1#X`(FW#+Q}eVKJl=`}QXCF|O{NM)uJdI{2Z+#Vi3$~W>p`QrN8Yb$+h zk=yOtT2Gb8hbr+Mx(>6!y&&x7rPfp5cl7I2%#NYPk;V?Q5+%7+2Z(`USsW*1mZR*; zZmw?)*aQwVXMM~Enx2LQOW(3A@1Zi0Of`>vjukRu!SOKZLH$`vvJYsb9W0TMMiBnW z+FoC?_W>CAnq^`;;>hKvnk$p^_WK^$?}weYkgii8%GR{EwglY5bN&4aRVaIl%T4AV zJN>$y8^p|>La&%>qPKcpYdO-u+$z27jmws)8Z7l_KtZnwN%G)|ePiiTO_c%VK7vV= zX>UA03ZmqA&SRTi)Fat>d_BKb@2J%~-7Ro^4fB?;eA?i?o#x&eyaeCW&=q=xy=AE@ z;&oS)mJ{8|`Cti|Skbe$w&##m-0RrNJ*GgPY(*!wZL4lBxj0qwr}>i4U-vsoO24Qr zy)qcprg(5$`{|v#+wVpbuBRZh0^*$fLpts>bN$Qf%w~s^<22k)x$BWsObY=^MzZ(Q z?HKo<1KRad@YB_!v$GP(b*c8U#_+;8ZRk@N<_r>vq?L-1xQZ}Je6M(BeLwf#4~kMg z{AC5iC{k1P--EIM2M6Vm2nw%cw# zYL*_fRdN307wn=RcFuCwoL@dB2L)|4I+Xtd?Ct*w94)}+L8}=gX!)Tfw&md_8qAI+ zE9ir{PBENj>YNM$XY&QDpw?WK&A>JM+$z&3d6ieJkBoNBKL&E0h$N^O9Aw+8Z6rZg_ zi6AJu)1X}NRi1g6R0GtEyzc_pxsSNF%BlW~R(kMF|MI%?b(QvnwRK{R2CsLDCOm_1 zbX+b2eMBozAVQmE_%7!urn87R-)Z$!QfQncPZlw)=RqIAoz$X_EI%enN71{D#`%fl z(LT_LnvhI;|1gI;{_X9pLAShNBZat!J$}leYtdOz{4uw#ybIug&`15z2@jvtnw6CF zzQyF3f!XQRPiJ}uW}A@dykgwL#=){3e%4QYhsv_DO3P8%?=b(rNl*`m-B#C!XCz+0 zSeA1I-JKAFfSWSmZ@#@WQmonpNwPnqL^KftIRc43TKbNUFTyKKB#Dg-0WoPj*``HB zATb70_^7B8-^o8$fRSe6Qx{PmF<`VJvQ(Y6B|6r|#iZB5Y;q9VtIPpJIFU|~Wt$odz)QG&S%Gk(W=Uf_Zw6PT_zF#e_W3w~196SUaufS3k#p$aKj zgc`;m`)g=ejVWO8mRBSxZ5J*z*d0PVu1O~<_(?Kng~1DKQQ(d1ROn$63bB^yGgi=~ z-ofbcVS9IWWw0P6kqBX=1+T1c6B77+_mS*yI`PGYRIR+gWtJ#~xq^Rn>To8-2MeG~ zD)MZT`F5=|>Cd@iUrFY`H3@lAo6eJ&tZw462=n@L0w;Kwx`4SEv*WiPgUs;%H?uJ) A%m4rY delta 4676 zcmbtYc~q0vw*Nv#5&|D{AP_zVLu3qsL2ya}Mux-}m4a4n6DEl!5y4U@dJ~c`XoC$z z5Cz{21uRyuAcJDnM*>nnut2R+TIB&MczM*3$-xXpcCw;UbUNdfJH5W0*sG!FDludu4HGCb7qa(eswrWuV?;y51v` zL%TKODw^>G#`z-Wi5ZWvBHAkmdyR^g9Ak)oPJ#COvf1ux=du!!?{`1J@hk1WtI?S# zOq@-xhzaR;Qn`+eI@@2`Y+H1;-z#mOn(>SmXWaBgijxAr&Y=rlk?P^Nih{PJ`NRJ= zO`f-hSxkFWIR4r8BdvdcYfT(11R<2Yr}f{uvlYpV(gJpA zQZ_y}AHR`pe8OBtEmG>!DJ~<#Pc?sx_&7nCKI(&_((Ibjf^788%hZ{)dU{$JBXo`23pE zcMYY7m8Cgsl!zWi!RHZ53u^F@hT@!F{0GhW0tP+`!Rq5!p6OQNsIMYzAH%l4Fzw_B z=@OgtP-*v6X!o+WnAiyC}4sg>XNZm+K7G(FOJ^_`x$h{zEZi|qrMQfqttU33KgmUj<(tk=ftUZ;-eg#QrR4w zQcXKDbtvSa4HUc=DvLt1N8O;DThLf8PH7bm&PM?Sf-a!- zEm500s7M%!-s?&+2wwx+!Fgsa_`` z$8J!pf{1Nk(E*Wa3I7>z9TUgsY^j(SPnOO1X55eLvkM;v$>f3nZBVNmWYdW@;w3^E z(;*s}LdXF$*}Iui@!njj7DFTKi9_#GS4>(xAzC~tcO%^q&2e2vj(**KlyhygX}sxL z&-zoRMytjJ3K&{7De`;Dz8&M9B%QiGH)a~VzgRgvIJ`tBu-&B0%0gtxo7_yk8C7Ey z(5zZ}HD=vl-@3_|4SYD3<3cCY!(cmVFBaxkkn$^W-x5*2WS0&Wnm5hP8}3g`&$B4; zaWKz4DR%1mtZ8uK(Hx616bHYr!#P)Uhbp>PT?&uxB=fd8V7wYRUByNlrXVS7Q#A><^y7@8qvXD*%bY}}E9`fbNatqSanAbQu~^e zL@0m>8z&LU`gZT7qh!?+M`}rle{ZTvN$duN9TBOriCqAt!PFR`3l-BB#Ii|K%;5GK z&n^UxmbcjaG&CZ;palUNvEoM5rsf6Gq9u!k(S1;K@2?QiBzY*-WO zM)N|TU`vQLD0oEHBAqW^5P+4gV#gafH_k2mxF|SY9yBz1JRxL6X1gf6AXPzi#*!lB ztrBvagKJKhYb@1*K84gJB3)9FuGAonreHo?DKxmp6+hfMR9xQFb4E~J)l(%HI&-A! zNJZ07Rk@{)ird4Q&eV^SuYKJ!4w~^QqKz;#>&N_EXt@$uwlqU{Kq5cHm+Z|t6m#G` z`5~${Hk9B`W}MaEr&B54I89SMw@7q-W>!xdWxNV*C*i&BSIXU8ViCCVNu}PkGAYCHgyICxgi9t84BOC@;ra_kQ)w7u? z^vINIKYv$VwaXkUIeC`#j8{FEm*;fnjtf9$P`#$q64eqk>g%o*Lqm$l|zEGy2_badsWx_NzvmU%g#Vvz-Ze zf1Lh&Ao*_cou`>8carCLo2&3CEDmHAsVmI*3NMLSsL~fY2G+Xk3)9jHSB2LGHq?Tq zJP4ZdncDnOM0VCP0@lUlt%_5{VDoS4B7mVNu>b$$yxQ!ZG_t(^(-YI$+56M;Bc_4j zH$cz{y&eDp*gMt_2uHR!-BJ)ojMA1xu|5i~sKhzjUuLel7;&ki#@b4Vr)pa{1-nK0TzMG@`CaoSRt*YkR>Ur|23sXi-Lak8=R)F4nE+uDLz zQ2cMClrX#xUC~Jp!^_+AO{i@k8fm{2~+Q!Cw{H*sMQ>3 zQKS}Whf0)u7J+w4O7RE_(_5=ziLV+>KR3^s1}3I&9iP14Z<iRO&$7d%7 zLBP{6?n`z+&_@X&(xB0W$7KtGAgwH6@$vbEz!pJJ>qz;9bH~d=$j5_Q`GBEYte?0` zgirLp(bC$~LPt{CYhH>@tmTq?3qQA1KOa)?ZxxW1AH+Z|a2j!~zO9cO!+77~M`7v6}&ZEG=T>`z{c zgUzGYS|bB`XAMMSQ{%r>1{h|o$8i$jc-Bj9Vnf4}$ghw)&vj4YPhB6In6I9gRty4( z|112N4(C+W{aH`fx`3Xx_KRfR&;I?@I5ZIX&WJ1Lx~`IW4gs<28;xx!BYv&Xas7HypKzyvcJqO54-d>w+@A(vK7|GDNq)_z zO-n$^KZOtLa9@`wJ|^?AZzUDKMJF6%ND+r}CW~WGp0!sw;5Vsxqk$E<>uxS?h0&=cyYHgxoS-v%XSqailovL<1^e~YGghXK3ucJZDT zfv~X(btWS?vpV1P}bt;aX?@eeK8OC@AvLI@SFO2-;;KSgU1d zLu?3yxcw?<-dNH*DdL+erAe2ijC~JNAolLEvLQfq^;M(e%(Oz%G9?uD`i#mH$K`Sr zw1heu5qTxb=TJueyB1cXI^}o|-`IT%yJuok$nA_~(?I6kxk?_Oo5&S}PjxdrlT|~b zK)?moW%Ts?kUX(8FC%BWRfDbDzu)wDo3iuN?ysmj-R_-0R>qWk?~}rMp6nl)%!*vW zP$vNQLj~Cx9J%~}MH9mh$aA-Ab`DiVg8?9uIR(q24{Yz)p9}%EG>h_Qa&s( z21V#1lvs#!)U-@OQVK4Dt+uurlTmI%hq%n4`BTUh7nFP^#ZcuqW590t<}$mc5Ac+prhhkV0`o)p#w&jw4 z_sgBRY6b2&FJ+F0Usd8l{~{}(m3+L_CVf65D+8-ZU@)>`ba+S2T1ZVs)8>sdDP>V< z_e|6`hCkAVr{Xr4)$0-OXU_(@#SnJGq?#PV(3oga*k$$qzCX79pBu!|A6Bep&_~X8xe+LhCk&&B}>gYc65l zeG(^SO4*okNV@;UZ8o`tTxNDt+N&*7gzD%e;%bV3pqVK#kb6bdMFf?MoMy)DXQP-U zR4e^7o4@r-&uKtH_Su-WR+I_7fx<#ma;STCYypDr!^N8Id%JP*cK;AfDhb`F$veyi zj+YG;MtQ-&e$4J?i=8V5{z*s7%l>$bzJNnrrC<^j=7^C?jCi-*Nj7O~d?56L+6+pW zXqVbkqhf$1idNe6mKjk>gi^-|ylw2(4{&av)Osz~iv<2(p{P(^;LWJ-<|4iX(963@ r{N~lceGV^-)jmXS5nLRsref;bGAO0J;8Z|*RLpup`xe4OAMoR!@91)|gbyer>nzJ3LwwZbpHO9E2-Goh>EPmLtVZ~~DA=$j5_#L9& z_sQ)P{5T(zCB}Zg+2Q$dt;q?9Dz8hvYfM$9CQP8)^J+dKJ>uD?(o(CbGYQXcHW67a z2_TQN>_eZf#=3%n*-Hu<3jCDTe>}fXOGwN4x5JG5MlT`kb(7UvzY%W&b~BL=MQw{a zo<#hAc$2hMH$KVCm`8_-=$B=Oa+ueEEG^WDF8Qsp>{D`&CbmbGR?!G%o450Be3S@q z8rVghSY8BiZa}q1U&E0_kv*?&JD%JhirI(Bf`jj>f!4uG-XVXD#$kV*urE@%U9P+#;f>yIq=qIrJ0gY!GoLgKp59SE#@)owI_Afi z7BN2TaX;1&#Oz`^5$d*2(uo0H<`MP4*^^>Sy!OwX@?$)*m&!@l&*=va)l7(H!O57N z&g2GWorvxuVoXYKhBtyGo0nV`JkXtXHPfDC3g^UG!M9%XZ$0nFJMCs>*x}1w7MH|? zY0_=QY+{NUt_Y@aLZCb)=osB;!6|f~Dn|Z{AdkIAer#52bl8jN{l@HSHXbE=Ud##J zv6pSXW(%`uUlj|2Use4RyC#SS_g~j~K?GlhoEv_OnuBwTe!R@zy{+`-yXp6~xFv21 z6qsGD_jkPo2dz6|NlfS#&Q5a?rXj&>#n^9Q!`^p{ca}t;oH90YkNW4FCWD delta 1362 zcmZvbJ7`l;7{^c2#HJX9Yx8K6Cimv%MM$GyC{c^FzNpfgroL-it@x-)B|ZiRhpUsD z4&UJFrs7b=!HPq1b`*rtK^G~milA7k|NqUolEJ`_@0{=P|IRu0%UWZt@uF^QE^Yjn zdVEektLaj0`MbR9?3Si6;{O_XwP>t|ou~?^s8Y%T{FU`S*4qBt$FcXd#e1+0wC#Jb z{sUsFLnUA>5JyH5mV4&1S0Ahew3g#KQgCztHfM4g@J9g?mOjS&)dqKOVa*&5uPy`M z!}s<1i1I7jjd!UqEHyl+#S1fTtEy5ZNOO|~6ygbUpi}QzkO%k;yKz}H%f5tkTch&L zipaVZ3c9xx$4WY^=23f~)DO!D@6M}KV5#N@eb`4}8RuK3Rj=9t%VSc*yLK6C*8C6V z5if?C?QT;#+Y8y4&C+;31D1_g#CM3wXl9$wlslQK(Hew+8i1dNOv+LwiL0(;9t|+R z29&zHv=vw60e1kd8QZDX)Yzrhwmh+moA|JUfR7iI6?<@kwZmWta1bU`(AC?cee6vi zwf1TsACW#AcAxeIJ)g{FOiqC#maIdjDGYed>RfmKVr)=o3qydoVl1RU0sU=?*Az{mV)z&yt8Y2OUi)L|@)5jJHZpNum5 zEI0!=%5JuN%2#KoeICpL{v6z&z6*eUum44?XMy)+m~%<{cxJC|PWv1Dr%JO>PVv51 z!4+^BP=RmPy8G)w)u7fjFb{ahD{gFYwW2H^W<0pINx s^bf%P)b(modelLods.size() - 1); const Data::Instance& modelLod = modelLods[rayTracingLod]; - // setup a stream layout and shader input contract for the position and normal streams + // setup a stream layout and shader input contract for the vertex streams static const char* PositionSemantic = "POSITION"; static const char* NormalSemantic = "NORMAL"; - static const RHI::Format StreamFormat = RHI::Format::R32G32B32_FLOAT; + static const char* TangentSemantic = "TANGENT"; + static const char* BitangentSemantic = "BITANGENT"; + static const char* UVSemantic = "UV"; + static const RHI::Format PositionStreamFormat = RHI::Format::R32G32B32_FLOAT; + static const RHI::Format NormalStreamFormat = RHI::Format::R32G32B32_FLOAT; + static const RHI::Format TangentStreamFormat = RHI::Format::R32G32B32_FLOAT; + static const RHI::Format BitangentStreamFormat = RHI::Format::R32G32B32_FLOAT; + static const RHI::Format UVStreamFormat = RHI::Format::R32G32_FLOAT; RHI::InputStreamLayoutBuilder layoutBuilder; - layoutBuilder.AddBuffer()->Channel(PositionSemantic, StreamFormat); - layoutBuilder.AddBuffer()->Channel(NormalSemantic, StreamFormat); + layoutBuilder.AddBuffer()->Channel(PositionSemantic, PositionStreamFormat); + layoutBuilder.AddBuffer()->Channel(NormalSemantic, NormalStreamFormat); + layoutBuilder.AddBuffer()->Channel(UVSemantic, UVStreamFormat); + layoutBuilder.AddBuffer()->Channel(TangentSemantic, TangentStreamFormat); + layoutBuilder.AddBuffer()->Channel(BitangentSemantic, BitangentStreamFormat); RHI::InputStreamLayout inputStreamLayout = layoutBuilder.End(); RPI::ShaderInputContract::StreamChannelInfo positionStreamChannelInfo; positionStreamChannelInfo.m_semantic = RHI::ShaderSemantic(AZ::Name(PositionSemantic)); - positionStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(StreamFormat); + positionStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(PositionStreamFormat); RPI::ShaderInputContract::StreamChannelInfo normalStreamChannelInfo; normalStreamChannelInfo.m_semantic = RHI::ShaderSemantic(AZ::Name(NormalSemantic)); - normalStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(StreamFormat); + normalStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(NormalStreamFormat); + + RPI::ShaderInputContract::StreamChannelInfo tangentStreamChannelInfo; + tangentStreamChannelInfo.m_semantic = RHI::ShaderSemantic(AZ::Name(TangentSemantic)); + tangentStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(TangentStreamFormat); + + RPI::ShaderInputContract::StreamChannelInfo bitangentStreamChannelInfo; + bitangentStreamChannelInfo.m_semantic = RHI::ShaderSemantic(AZ::Name(BitangentSemantic)); + bitangentStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(BitangentStreamFormat); + + RPI::ShaderInputContract::StreamChannelInfo uvStreamChannelInfo; + uvStreamChannelInfo.m_semantic = RHI::ShaderSemantic(AZ::Name(UVSemantic)); + uvStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(UVStreamFormat); + uvStreamChannelInfo.m_isOptional = true; RPI::ShaderInputContract shaderInputContract; shaderInputContract.m_streamChannels.emplace_back(positionStreamChannelInfo); shaderInputContract.m_streamChannels.emplace_back(normalStreamChannelInfo); + shaderInputContract.m_streamChannels.emplace_back(tangentStreamChannelInfo); + shaderInputContract.m_streamChannels.emplace_back(bitangentStreamChannelInfo); + shaderInputContract.m_streamChannels.emplace_back(uvStreamChannelInfo); // setup the raytracing data for each sub-mesh const size_t meshCount = modelLod->GetMeshes().size(); @@ -739,26 +765,6 @@ namespace AZ { const RPI::ModelLod::Mesh& mesh = modelLod->GetMeshes()[meshIndex]; - // retrieve vertex/index buffers - RPI::ModelLod::StreamBufferViewList streamBufferViews; - [[maybe_unused]] bool result = modelLod->GetStreamsForMesh(inputStreamLayout, streamBufferViews, shaderInputContract, meshIndex); - AZ_Assert(result, "Failed to retrieve mesh stream buffer views"); - - // note that the element count is the size of the entire buffer, even though this mesh may only - // occupy a portion of the vertex buffer. This is necessary since we are accessing it using - // a ByteAddressBuffer in the raytracing shaders and passing the byte offset to the shader in a constant buffer. - uint32_t vertexBufferByteCount = const_cast(streamBufferViews[0].GetBuffer())->GetDescriptor().m_byteCount; - RHI::BufferViewDescriptor vertexBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, vertexBufferByteCount); - - const RHI::IndexBufferView& indexBufferView = mesh.m_indexBufferView; - uint32_t indexElementSize = indexBufferView.GetIndexFormat() == RHI::IndexFormat::Uint16 ? 2 : 4; - uint32_t indexElementCount = (uint32_t)indexBufferView.GetBuffer()->GetDescriptor().m_byteCount / indexElementSize; - RHI::BufferViewDescriptor indexBufferDescriptor; - indexBufferDescriptor.m_elementOffset = 0; - indexBufferDescriptor.m_elementCount = indexElementCount; - indexBufferDescriptor.m_elementSize = indexElementSize; - indexBufferDescriptor.m_elementFormat = indexBufferView.GetIndexFormat() == RHI::IndexFormat::Uint16 ? RHI::Format::R16_UINT : RHI::Format::R32_UINT; - // retrieve the material Data::Instance material = mesh.m_material; @@ -769,31 +775,162 @@ namespace AZ material = materialAssignment.m_materialInstance; } - AZ::Color irradianceColor(1.0f, 1.0f, 1.0f, 1.0f); + // retrieve vertex/index buffers + RPI::ModelLod::StreamBufferViewList streamBufferViews; + [[maybe_unused]] bool result = modelLod->GetStreamsForMesh( + inputStreamLayout, + streamBufferViews, + shaderInputContract, + meshIndex, + materialAssignment.m_matModUvOverrides, + material->GetAsset()->GetMaterialTypeAsset()->GetUvNameMap()); + AZ_Assert(result, "Failed to retrieve mesh stream buffer views"); + + // note that the element count is the size of the entire buffer, even though this mesh may only + // occupy a portion of the vertex buffer. This is necessary since we are accessing it using + // a ByteAddressBuffer in the raytracing shaders and passing the byte offset to the shader in a constant buffer. + uint32_t positionBufferByteCount = const_cast(streamBufferViews[0].GetBuffer())->GetDescriptor().m_byteCount; + RHI::BufferViewDescriptor positionBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, positionBufferByteCount); + + uint32_t normalBufferByteCount = const_cast(streamBufferViews[1].GetBuffer())->GetDescriptor().m_byteCount; + RHI::BufferViewDescriptor normalBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, normalBufferByteCount); + + uint32_t tangentBufferByteCount = const_cast(streamBufferViews[2].GetBuffer())->GetDescriptor().m_byteCount; + RHI::BufferViewDescriptor tangentBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, tangentBufferByteCount); + + uint32_t bitangentBufferByteCount = const_cast(streamBufferViews[3].GetBuffer())->GetDescriptor().m_byteCount; + RHI::BufferViewDescriptor bitangentBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, bitangentBufferByteCount); + + uint32_t uvBufferByteCount = const_cast(streamBufferViews[4].GetBuffer())->GetDescriptor().m_byteCount; + RHI::BufferViewDescriptor uvBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, uvBufferByteCount); + + const RHI::IndexBufferView& indexBufferView = mesh.m_indexBufferView; + uint32_t indexElementSize = indexBufferView.GetIndexFormat() == RHI::IndexFormat::Uint16 ? 2 : 4; + uint32_t indexElementCount = (uint32_t)indexBufferView.GetBuffer()->GetDescriptor().m_byteCount / indexElementSize; + RHI::BufferViewDescriptor indexBufferDescriptor; + indexBufferDescriptor.m_elementOffset = 0; + indexBufferDescriptor.m_elementCount = indexElementCount; + indexBufferDescriptor.m_elementSize = indexElementSize; + indexBufferDescriptor.m_elementFormat = indexBufferView.GetIndexFormat() == RHI::IndexFormat::Uint16 ? RHI::Format::R16_UINT : RHI::Format::R32_UINT; + + // set the SubMesh data to pass to the RayTracingFeatureProcessor, starting with vertex/index data + RayTracingFeatureProcessor::SubMesh subMesh; + subMesh.m_positionFormat = PositionStreamFormat; + subMesh.m_positionVertexBufferView = streamBufferViews[0]; + subMesh.m_positionShaderBufferView = const_cast(streamBufferViews[0].GetBuffer())->GetBufferView(positionBufferDescriptor); + + subMesh.m_normalFormat = NormalStreamFormat; + subMesh.m_normalVertexBufferView = streamBufferViews[1]; + subMesh.m_normalShaderBufferView = const_cast(streamBufferViews[1].GetBuffer())->GetBufferView(normalBufferDescriptor); + + subMesh.m_tangentFormat = TangentStreamFormat; + subMesh.m_tangentVertexBufferView = streamBufferViews[2]; + subMesh.m_tangentShaderBufferView = const_cast(streamBufferViews[2].GetBuffer())->GetBufferView(tangentBufferDescriptor); + + subMesh.m_bitangentFormat = BitangentStreamFormat; + subMesh.m_bitangentVertexBufferView = streamBufferViews[3]; + subMesh.m_bitangentShaderBufferView = const_cast(streamBufferViews[3].GetBuffer())->GetBufferView(bitangentBufferDescriptor); + + if (uvBufferByteCount > 0) + { + subMesh.m_bufferFlags |= RayTracingSubMeshBufferFlags::UV; + subMesh.m_uvFormat = UVStreamFormat; + subMesh.m_uvVertexBufferView = streamBufferViews[4]; + subMesh.m_uvShaderBufferView = const_cast(streamBufferViews[4].GetBuffer())->GetBufferView(uvBufferDescriptor); + } + + subMesh.m_indexBufferView = mesh.m_indexBufferView; + subMesh.m_indexShaderBufferView = const_cast(mesh.m_indexBufferView.GetBuffer())->GetBufferView(indexBufferDescriptor); + + // add material data if (material) { + // irradiance color RPI::MaterialPropertyIndex propertyIndex = material->FindPropertyIndex(AZ::Name("irradiance.color")); if (propertyIndex.IsValid()) { - irradianceColor = material->GetPropertyValue(propertyIndex); + subMesh.m_irradianceColor = material->GetPropertyValue(propertyIndex); } propertyIndex = material->FindPropertyIndex(AZ::Name("irradiance.factor")); if (propertyIndex.IsValid()) { - irradianceColor *= material->GetPropertyValue(propertyIndex); + subMesh.m_irradianceColor *= material->GetPropertyValue(propertyIndex); + } + + // base color + propertyIndex = material->FindPropertyIndex(AZ::Name("baseColor.color")); + if (propertyIndex.IsValid()) + { + subMesh.m_baseColor = material->GetPropertyValue(propertyIndex); + } + + propertyIndex = material->FindPropertyIndex(AZ::Name("baseColor.factor")); + if (propertyIndex.IsValid()) + { + subMesh.m_baseColor *= material->GetPropertyValue(propertyIndex); + } + + // metallic + propertyIndex = material->FindPropertyIndex(AZ::Name("metallic.factor")); + if (propertyIndex.IsValid()) + { + subMesh.m_metallicFactor = material->GetPropertyValue(propertyIndex); + } + + // roughness + propertyIndex = material->FindPropertyIndex(AZ::Name("roughness.factor")); + if (propertyIndex.IsValid()) + { + subMesh.m_roughnessFactor = material->GetPropertyValue(propertyIndex); + } + + // textures + propertyIndex = material->FindPropertyIndex(AZ::Name("baseColor.textureMap")); + if (propertyIndex.IsValid()) + { + Data::Instance image = material->GetPropertyValue>(propertyIndex); + if (image.get()) + { + subMesh.m_textureFlags |= RayTracingSubMeshTextureFlags::BaseColor; + subMesh.m_baseColorImageView = image->GetImageView(); + } + } + + propertyIndex = material->FindPropertyIndex(AZ::Name("normal.textureMap")); + if (propertyIndex.IsValid()) + { + Data::Instance image = material->GetPropertyValue>(propertyIndex); + if (image.get()) + { + subMesh.m_textureFlags |= RayTracingSubMeshTextureFlags::Normal; + subMesh.m_normalImageView = image->GetImageView(); + } + } + + propertyIndex = material->FindPropertyIndex(AZ::Name("metallic.textureMap")); + if (propertyIndex.IsValid()) + { + Data::Instance image = material->GetPropertyValue>(propertyIndex); + if (image.get()) + { + subMesh.m_textureFlags |= RayTracingSubMeshTextureFlags::Metallic; + subMesh.m_metallicImageView = image->GetImageView(); + } + } + + propertyIndex = material->FindPropertyIndex(AZ::Name("roughness.textureMap")); + if (propertyIndex.IsValid()) + { + Data::Instance image = material->GetPropertyValue>(propertyIndex); + if (image.get()) + { + subMesh.m_textureFlags |= RayTracingSubMeshTextureFlags::Roughness; + subMesh.m_roughnessImageView = image->GetImageView(); + } } } - RayTracingFeatureProcessor::SubMesh subMesh; - subMesh.m_vertexFormat = StreamFormat; - subMesh.m_positionVertexBufferView = streamBufferViews[0]; - subMesh.m_positionShaderBufferView = const_cast(streamBufferViews[0].GetBuffer())->GetBufferView(vertexBufferDescriptor); - subMesh.m_normalVertexBufferView = streamBufferViews[1]; - subMesh.m_normalShaderBufferView = const_cast(streamBufferViews[1].GetBuffer())->GetBufferView(vertexBufferDescriptor); - subMesh.m_indexBufferView = mesh.m_indexBufferView; - subMesh.m_indexShaderBufferView = const_cast(mesh.m_indexBufferView.GetBuffer())->GetBufferView(indexBufferDescriptor); - subMesh.m_irradianceColor = irradianceColor; subMeshes.push_back(subMesh); } diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.cpp index 2bb2fa2ac2..92cd41b4e8 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.cpp @@ -115,11 +115,11 @@ namespace AZ } } - // update and compile the RayTracingSceneSrg + // update and compile the RayTracingSceneSrg and RayTracingMaterialSrg // Note: the timing of this update is very important, it needs to be updated after the TLAS is allocated so it can // be set on the RayTracingSceneSrg for this frame, and the ray tracing mesh data in the RayTracingSceneSrg must // exactly match the TLAS. Any mismatch in this data may result in a TDR. - rayTracingFeatureProcessor->UpdateRayTracingSceneSrg(); + rayTracingFeatureProcessor->UpdateRayTracingSrgs(); } } diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp index c4e9306dc9..c28ac32381 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp @@ -71,6 +71,13 @@ namespace AZ AZ_Assert(rayTracingSceneSrgAsset.IsReady(), "Failed to load RayTracingSceneSrg asset"); m_rayTracingSceneSrg = RPI::ShaderResourceGroup::Create(rayTracingSceneSrgAsset); + + // load the RayTracingMaterialSrg asset + Data::Asset rayTracingMaterialSrgAsset = + RPI::AssetUtils::LoadAssetByProductPath("shaderlib/atom/features/raytracing/raytracingmaterialsrg_raytracingmaterialsrg.azsrg", RPI::AssetUtils::TraceLevel::Error); + AZ_Assert(rayTracingMaterialSrgAsset.IsReady(), "Failed to load RayTracingMaterialSrg asset"); + + m_rayTracingMaterialSrg = RPI::ShaderResourceGroup::Create(rayTracingMaterialSrgAsset); } void RayTracingFeatureProcessor::SetMesh(const ObjectId objectId, const SubMeshVector& subMeshes) @@ -104,7 +111,7 @@ namespace AZ RHI::RayTracingBlasDescriptor blasDescriptor; blasDescriptor.Build() ->Geometry() - ->VertexFormat(subMesh.m_vertexFormat) + ->VertexFormat(subMesh.m_positionFormat) ->VertexBuffer(subMesh.m_positionVertexBufferView) ->IndexBuffer(subMesh.m_indexBufferView) ; @@ -124,6 +131,7 @@ namespace AZ m_subMeshCount += aznumeric_cast(subMeshes.size()); m_meshInfoBufferNeedsUpdate = true; + m_materialInfoBufferNeedsUpdate = true; } void RayTracingFeatureProcessor::RemoveMesh(const ObjectId objectId) @@ -142,6 +150,7 @@ namespace AZ } m_meshInfoBufferNeedsUpdate = true; + m_materialInfoBufferNeedsUpdate = true; } void RayTracingFeatureProcessor::SetMeshTransform(const ObjectId objectId, const AZ::Transform transform, const AZ::Vector3 nonUniformScale) @@ -162,14 +171,14 @@ namespace AZ m_meshInfoBufferNeedsUpdate = true; } - void RayTracingFeatureProcessor::UpdateRayTracingSceneSrg() + void RayTracingFeatureProcessor::UpdateRayTracingSrgs() { if (!m_tlas->GetTlasBuffer()) { return; } - if (m_rayTracingSceneSrg->IsQueuedForCompile()) + if (m_rayTracingSceneSrg->IsQueuedForCompile() || m_rayTracingMaterialSrg->IsQueuedForCompile()) { //[GFX TODO][ATOM-14792] AtomSampleViewer: Reset scene and feature processors before switching to sample return; @@ -178,7 +187,144 @@ namespace AZ // update the mesh info buffer with the latest ray tracing enabled meshes UpdateMeshInfoBuffer(); + // update the material info buffer with the latest ray tracing enabled meshes + UpdateMaterialInfoBuffer(); + // update the RayTracingSceneSrg + UpdateRayTracingSceneSrg(); + + // update the RayTracingMaterialSrg + UpdateRayTracingMaterialSrg(); + } + + void RayTracingFeatureProcessor::UpdateMeshInfoBuffer() + { + if (m_meshInfoBufferNeedsUpdate && (m_subMeshCount > 0)) + { + TransformServiceFeatureProcessor* transformFeatureProcessor = GetParentScene()->GetFeatureProcessor(); + + AZStd::vector meshInfos; + meshInfos.reserve(m_subMeshCount); + + uint32_t newMeshByteCount = m_subMeshCount * sizeof(MeshInfo); + + if (m_meshInfoBuffer == nullptr) + { + // allocate the MeshInfo structured buffer + RPI::CommonBufferDescriptor desc; + desc.m_poolType = RPI::CommonBufferPoolType::ReadOnly; + desc.m_bufferName = "RayTracingMeshInfo"; + desc.m_byteCount = newMeshByteCount; + desc.m_elementSize = sizeof(MeshInfo); + m_meshInfoBuffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); + } + else if (m_meshInfoBuffer->GetBufferSize() < newMeshByteCount) + { + // resize for the new sub-mesh count + m_meshInfoBuffer->Resize(newMeshByteCount); + } + + // keep track of the start index of the buffers for each mesh, this is put into the MeshInfo + // entry for each mesh so it knows where to find the start of its buffers in the unbounded array + uint32_t bufferStartIndex = 0; + + for (const auto& mesh : m_meshes) + { + AZ::Transform meshTransform = transformFeatureProcessor->GetTransformForId(TransformServiceFeatureProcessorInterface::ObjectId(mesh.first)); + AZ::Transform noScaleTransform = meshTransform; + noScaleTransform.ExtractScale(); + AZ::Matrix3x3 rotationMatrix = Matrix3x3::CreateFromTransform(noScaleTransform); + rotationMatrix = rotationMatrix.GetInverseFull().GetTranspose(); + + const RayTracingFeatureProcessor::SubMeshVector& subMeshes = mesh.second.m_subMeshes; + for (const auto& subMesh : subMeshes) + { + MeshInfo meshInfo; + meshInfo.m_indexOffset = subMesh.m_indexBufferView.GetByteOffset(); + meshInfo.m_positionOffset = subMesh.m_positionVertexBufferView.GetByteOffset(); + meshInfo.m_normalOffset = subMesh.m_normalVertexBufferView.GetByteOffset(); + meshInfo.m_tangentOffset = subMesh.m_tangentVertexBufferView.GetByteOffset(); + meshInfo.m_bitangentOffset = subMesh.m_bitangentVertexBufferView.GetByteOffset(); + + if (RHI::CheckBitsAll(subMesh.m_bufferFlags, RayTracingSubMeshBufferFlags::UV)) + { + meshInfo.m_uvOffset = subMesh.m_uvVertexBufferView.GetByteOffset(); + } + + subMesh.m_irradianceColor.StoreToFloat4(meshInfo.m_irradianceColor.data()); + rotationMatrix.StoreToRowMajorFloat9(meshInfo.m_worldInvTranspose.data()); + meshInfo.m_bufferFlags = subMesh.m_bufferFlags; + meshInfo.m_bufferStartIndex = bufferStartIndex; + + // add the count of buffers present in this subMesh to the start index for the next subMesh + // note that the Index, Position, Normal, Tangent, and Bitangent buffers are always counted since they are guaranteed + static const uint32_t RayTracingSubMeshFixedStreamCount = 5; + bufferStartIndex += (RayTracingSubMeshFixedStreamCount + RHI::CountBitsSet(aznumeric_cast(meshInfo.m_bufferFlags))); + + meshInfos.emplace_back(meshInfo); + } + } + + m_meshInfoBuffer->UpdateData(meshInfos.data(), newMeshByteCount); + m_meshInfoBufferNeedsUpdate = false; + } + } + + void RayTracingFeatureProcessor::UpdateMaterialInfoBuffer() + { + if (m_materialInfoBufferNeedsUpdate && (m_subMeshCount > 0)) + { + AZStd::vector materialInfos; + materialInfos.reserve(m_subMeshCount); + + uint32_t newMaterialByteCount = m_subMeshCount * sizeof(MaterialInfo); + + if (m_materialInfoBuffer == nullptr) + { + // allocate the MaterialInfo structured buffer + RPI::CommonBufferDescriptor desc; + desc.m_poolType = RPI::CommonBufferPoolType::ReadOnly; + desc.m_bufferName = "RayTracingMaterialInfo"; + desc.m_byteCount = newMaterialByteCount; + desc.m_elementSize = sizeof(MaterialInfo); + m_materialInfoBuffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); + } + else if (m_materialInfoBuffer->GetBufferSize() < newMaterialByteCount) + { + // resize for the new sub-mesh count + m_materialInfoBuffer->Resize(newMaterialByteCount); + } + + // keep track of the start index of the textures for each mesh, this is put into the MaterialInfo + // entry for each mesh so it knows where to find the start of its textures in the unbounded array + uint32_t textureStartIndex = 0; + + for (const auto& mesh : m_meshes) + { + const RayTracingFeatureProcessor::SubMeshVector& subMeshes = mesh.second.m_subMeshes; + for (const auto& subMesh : subMeshes) + { + MaterialInfo materialInfo; + subMesh.m_baseColor.StoreToFloat4(materialInfo.m_baseColor.data()); + materialInfo.m_metallicFactor = subMesh.m_metallicFactor; + materialInfo.m_roughnessFactor = subMesh.m_roughnessFactor; + materialInfo.m_textureFlags = subMesh.m_textureFlags; + materialInfo.m_textureStartIndex = textureStartIndex; + + // add the count of textures present in this subMesh to the start index for the next subMesh + textureStartIndex += RHI::CountBitsSet(aznumeric_cast(materialInfo.m_textureFlags)); + + materialInfos.emplace_back(materialInfo); + } + } + + m_materialInfoBuffer->UpdateData(materialInfos.data(), newMaterialByteCount); + m_materialInfoBufferNeedsUpdate = false; + } + } + + void RayTracingFeatureProcessor::UpdateRayTracingSceneSrg() + { const RHI::ShaderResourceGroupLayout* srgLayout = m_rayTracingSceneSrg->GetLayout(); RHI::ShaderInputImageIndex imageIndex; RHI::ShaderInputBufferIndex bufferIndex; @@ -272,11 +418,18 @@ namespace AZ const SubMeshVector& subMeshes = mesh.second.m_subMeshes; for (const auto& subMesh : subMeshes) { - // add the index, position, and normal buffers for this sub-mesh to the mesh buffer list, this will - // go into the shader as an unbounded array in the Srg + // add the stream buffers for this sub-mesh to the mesh buffer list, + // this is sent to the shader as an unbounded array in the Srg meshBuffers.push_back(subMesh.m_indexShaderBufferView.get()); meshBuffers.push_back(subMesh.m_positionShaderBufferView.get()); meshBuffers.push_back(subMesh.m_normalShaderBufferView.get()); + meshBuffers.push_back(subMesh.m_tangentShaderBufferView.get()); + meshBuffers.push_back(subMesh.m_bitangentShaderBufferView.get()); + + if (RHI::CheckBitsAll(subMesh.m_bufferFlags, RayTracingSubMeshBufferFlags::UV)) + { + meshBuffers.push_back(subMesh.m_uvShaderBufferView.get()); + } } } @@ -287,58 +440,53 @@ namespace AZ m_rayTracingSceneSrg->Compile(); } - void RayTracingFeatureProcessor::UpdateMeshInfoBuffer() + void RayTracingFeatureProcessor::UpdateRayTracingMaterialSrg() { - if (m_meshInfoBufferNeedsUpdate && (m_subMeshCount > 0)) + const RHI::ShaderResourceGroupLayout* srgLayout = m_rayTracingMaterialSrg->GetLayout(); + RHI::ShaderInputImageIndex imageIndex; + RHI::ShaderInputBufferIndex bufferIndex; + RHI::ShaderInputConstantIndex constantIndex; + + bufferIndex = srgLayout->FindShaderInputBufferIndex(AZ::Name("m_materialInfo")); + m_rayTracingMaterialSrg->SetBufferView(bufferIndex, m_materialInfoBuffer->GetBufferView()); + + if (m_subMeshCount) { - TransformServiceFeatureProcessor* transformFeatureProcessor = GetParentScene()->GetFeatureProcessor(); - - AZStd::vector meshInfos; - meshInfos.reserve(m_subMeshCount); - - uint32_t newMeshByteCount = m_subMeshCount * sizeof(MeshInfo); - - if (m_meshInfoBuffer == nullptr) - { - // allocate the MeshInfo structured buffer - RPI::CommonBufferDescriptor desc; - desc.m_poolType = RPI::CommonBufferPoolType::ReadOnly; - desc.m_bufferName = "RayTracingMeshInfo"; - desc.m_byteCount = newMeshByteCount; - desc.m_elementSize = sizeof(MeshInfo); - m_meshInfoBuffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); - } - else if (m_meshInfoBuffer->GetBufferSize() < newMeshByteCount) - { - // resize for the new sub-mesh count - m_meshInfoBuffer->Resize(newMeshByteCount); - } - + AZStd::vector materialTextures; for (const auto& mesh : m_meshes) { - AZ::Transform meshTransform = transformFeatureProcessor->GetTransformForId(TransformServiceFeatureProcessorInterface::ObjectId(mesh.first)); - AZ::Transform noScaleTransform = meshTransform; - noScaleTransform.ExtractScale(); - AZ::Matrix3x3 rotationMatrix = Matrix3x3::CreateFromTransform(noScaleTransform); - rotationMatrix = rotationMatrix.GetInverseFull().GetTranspose(); - - const RayTracingFeatureProcessor::SubMeshVector& subMeshes = mesh.second.m_subMeshes; + const SubMeshVector& subMeshes = mesh.second.m_subMeshes; for (const auto& subMesh : subMeshes) { - MeshInfo meshInfo; - meshInfo.m_indexOffset = subMesh.m_indexBufferView.GetByteOffset(); - meshInfo.m_positionOffset = subMesh.m_positionVertexBufferView.GetByteOffset(); - meshInfo.m_normalOffset = subMesh.m_normalVertexBufferView.GetByteOffset(); - subMesh.m_irradianceColor.StoreToFloat4(meshInfo.m_irradianceColor.data()); - rotationMatrix.StoreToRowMajorFloat9(meshInfo.m_worldInvTranspose.data()); + // add the baseColor, normal, metallic, and roughness images for this sub-mesh to the material texture list, + // this is sent to the shader as an unbounded array in the Srg + if (RHI::CheckBitsAll(subMesh.m_textureFlags, RayTracingSubMeshTextureFlags::BaseColor)) + { + materialTextures.push_back(subMesh.m_baseColorImageView.get()); + } - meshInfos.emplace_back(meshInfo); + if (RHI::CheckBitsAll(subMesh.m_textureFlags, RayTracingSubMeshTextureFlags::Normal)) + { + materialTextures.push_back(subMesh.m_normalImageView.get()); + } + + if (RHI::CheckBitsAll(subMesh.m_textureFlags, RayTracingSubMeshTextureFlags::Metallic)) + { + materialTextures.push_back(subMesh.m_metallicImageView.get()); + } + + if (RHI::CheckBitsAll(subMesh.m_textureFlags, RayTracingSubMeshTextureFlags::Roughness)) + { + materialTextures.push_back(subMesh.m_roughnessImageView.get()); + } } } - m_meshInfoBuffer->UpdateData(meshInfos.data(), newMeshByteCount); - m_meshInfoBufferNeedsUpdate = false; + RHI::ShaderInputImageUnboundedArrayIndex textureUnboundedArrayIndex = srgLayout->FindShaderInputImageUnboundedArrayIndex(AZ::Name("m_materialTextures")); + m_rayTracingMaterialSrg->SetImageViewUnboundedArray(textureUnboundedArrayIndex, materialTextures); } + + m_rayTracingMaterialSrg->Compile(); } } } diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h index f317f1c096..d89b61b2f9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -23,6 +24,28 @@ namespace AZ { namespace Render { + static const uint32_t RayTracingGlobalSrgBindingSlot = 0; + static const uint32_t RayTracingSceneSrgBindingSlot = 1; + static const uint32_t RayTracingMaterialSrgBindingSlot = 2; + + enum class RayTracingSubMeshBufferFlags : uint32_t + { + None = 0, + + UV = AZ_BIT(0) + }; + AZ_DEFINE_ENUM_BITWISE_OPERATORS(AZ::Render::RayTracingSubMeshBufferFlags); + + enum class RayTracingSubMeshTextureFlags : uint32_t + { + None = 0, + BaseColor = AZ_BIT(0), + Normal = AZ_BIT(1), + Metallic = AZ_BIT(2), + Roughness = AZ_BIT(3) + }; + AZ_DEFINE_ENUM_BITWISE_OPERATORS(AZ::Render::RayTracingSubMeshTextureFlags); + //! This feature processor manages ray tracing data for a Scene class RayTracingFeatureProcessor : public RPI::FeatureProcessor @@ -42,20 +65,53 @@ namespace AZ //! Contains data for a single sub-mesh struct SubMesh { - // vertex/index buffer data - RHI::Format m_vertexFormat = RHI::Format::Unknown; + // vertex streams + RHI::Format m_positionFormat = RHI::Format::Unknown; RHI::StreamBufferView m_positionVertexBufferView; RHI::Ptr m_positionShaderBufferView; + + RHI::Format m_normalFormat = RHI::Format::Unknown; RHI::StreamBufferView m_normalVertexBufferView; RHI::Ptr m_normalShaderBufferView; + + RHI::Format m_tangentFormat = RHI::Format::Unknown; + RHI::StreamBufferView m_tangentVertexBufferView; + RHI::Ptr m_tangentShaderBufferView; + + RHI::Format m_bitangentFormat = RHI::Format::Unknown; + RHI::StreamBufferView m_bitangentVertexBufferView; + RHI::Ptr m_bitangentShaderBufferView; + + RHI::Format m_uvFormat = RHI::Format::Unknown; + RHI::StreamBufferView m_uvVertexBufferView; + RHI::Ptr m_uvShaderBufferView; + + // index buffer RHI::IndexBufferView m_indexBufferView; RHI::Ptr m_indexShaderBufferView; + // vertex buffer usage flags + RayTracingSubMeshBufferFlags m_bufferFlags = RayTracingSubMeshBufferFlags::None; + // color of the bounced light from this sub-mesh - AZ::Color m_irradianceColor; + AZ::Color m_irradianceColor = AZ::Color(1.0f); // ray tracing Blas RHI::Ptr m_blas; + + // material data + AZ::Color m_baseColor = AZ::Color(0.0f); + float m_metallicFactor = 0.0f; + float m_roughnessFactor = 0.0f; + + // material texture usage flags + RayTracingSubMeshTextureFlags m_textureFlags = RayTracingSubMeshTextureFlags::None; + + // material textures + RHI::Ptr m_baseColorImageView; + RHI::Ptr m_normalImageView; + RHI::Ptr m_metallicImageView; + RHI::Ptr m_roughnessImageView; }; using SubMeshVector = AZStd::vector; @@ -98,6 +154,9 @@ namespace AZ //! Retrieves the RayTracingSceneSrg Data::Instance GetRayTracingSceneSrg() const { return m_rayTracingSceneSrg; } + //! Retrieves the RayTracingMaterialSrg + Data::Instance GetRayTracingMaterialSrg() const { return m_rayTracingMaterialSrg; } + //! Retrieves the RayTracingTlas const RHI::Ptr& GetTlas() const { return m_tlas; } RHI::Ptr& GetTlas() { return m_tlas; } @@ -118,14 +177,20 @@ namespace AZ //! Retrieves the GPU buffer containing information for all ray tracing meshes. const Data::Instance GetMeshInfoBuffer() const { return m_meshInfoBuffer; } - //! Updates the RayTracingSceneSrg, called after the TLAS is allocated in the RayTracingAccelerationStructurePass - void UpdateRayTracingSceneSrg(); + //! Retrieves the GPU buffer containing information for all ray tracing materials. + const Data::Instance GetMaterialInfoBuffer() const { return m_materialInfoBuffer; } + + //! Updates the RayTracingSceneSrg and RayTracingMaterialSrg, called after the TLAS is allocated in the RayTracingAccelerationStructurePass + void UpdateRayTracingSrgs(); private: AZ_DISABLE_COPY_MOVE(RayTracingFeatureProcessor); void UpdateMeshInfoBuffer(); + void UpdateMaterialInfoBuffer(); + void UpdateRayTracingSceneSrg(); + void UpdateRayTracingMaterialSrg(); // flag indicating if RayTracing is enabled, currently based on device support bool m_rayTracingEnabled = false; @@ -143,6 +208,9 @@ namespace AZ // ray tracing scene Srg Data::Instance m_rayTracingSceneSrg; + // ray tracing material Srg + Data::Instance m_rayTracingMaterialSrg; + // current revision number of ray tracing data uint32_t m_revision = 0; @@ -158,18 +226,43 @@ namespace AZ // structure for data in the m_meshInfoBuffer, shaders that use the buffer must match this type struct MeshInfo { - uint32_t m_indexOffset; - uint32_t m_positionOffset; - uint32_t m_normalOffset; + uint32_t m_indexOffset; + uint32_t m_positionOffset; + uint32_t m_normalOffset; + uint32_t m_tangentOffset; + uint32_t m_bitangentOffset; + uint32_t m_uvOffset; + float m_padding0[2]; + AZStd::array m_irradianceColor; // float4 AZStd::array m_worldInvTranspose; // float3x3 + float m_padding1[1]; + + RayTracingSubMeshBufferFlags m_bufferFlags = RayTracingSubMeshBufferFlags::None; + uint32_t m_bufferStartIndex = 0; }; // buffer containing a MeshInfo for each sub-mesh Data::Instance m_meshInfoBuffer; - // flag indicating we need to update the mesh info GPU buffer + // structure for data in the m_materialInfoBuffer, shaders that use the buffer must match this type + struct MaterialInfo + { + AZStd::array m_baseColor; // float4 + float m_metallicFactor = 0.0f; + float m_roughnessFactor = 0.0f; + RayTracingSubMeshTextureFlags m_textureFlags = RayTracingSubMeshTextureFlags::None; + uint32_t m_textureStartIndex = 0; + }; + + // buffer containing a MaterialInfo for each sub-mesh + Data::Instance m_materialInfoBuffer; + + // flag indicating we need to update the meshInfo buffer bool m_meshInfoBufferNeedsUpdate = false; + + // flag indicating we need to update the materialInfo buffer + bool m_materialInfoBufferNeedsUpdate = false; }; } } diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp index 2c0c7e986e..0fbe7dbc48 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp @@ -111,7 +111,6 @@ namespace AZ AZ_Assert(m_globalPipelineState, "Failed to acquire ray tracing global pipeline state"); // create global srg - static const uint32_t RayTracingGlobalSrgBindingSlot = 0; Data::Asset globalSrgAsset = m_rayGenerationShader->FindShaderResourceGroupAsset(RayTracingGlobalSrgBindingSlot); AZ_Error("PassSystem", globalSrgAsset.GetId().IsValid(), "RayTracingPass [%s] Failed to find RayTracingGlobalSrg asset", GetPathName().GetCStr()); AZ_Error("PassSystem", globalSrgAsset.IsReady(), "RayTracingPass [%s] asset is not loaded for shader", GetPathName().GetCStr()); @@ -120,10 +119,13 @@ namespace AZ AZ_Assert(m_shaderResourceGroup, "RayTracingPass [%s]: Failed to create RayTracingGlobalSrg", GetPathName().GetCStr()); RPI::PassUtils::BindDataMappingsToSrg(m_passDescriptor, m_shaderResourceGroup.get()); - // check to see if the shader requires a ViewSrg + // check to see if the shader requires the View and RayTracingMaterial Srgs Data::Asset viewSrgAsset = m_rayGenerationShader->FindShaderResourceGroupAsset(RPI::SrgBindingSlot::View); m_requiresViewSrg = viewSrgAsset.GetId().IsValid(); + Data::Asset rayTracingMaterialSrgAsset = m_rayGenerationShader->FindShaderResourceGroupAsset(RayTracingMaterialSrgBindingSlot); + m_requiresRayTracingMaterialSrg = rayTracingMaterialSrgAsset.GetId().IsValid(); + // build the ray tracing pipeline state descriptor RHI::RayTracingPipelineStateDescriptor descriptor; descriptor.Build() @@ -298,6 +300,11 @@ namespace AZ } } + if (m_requiresRayTracingMaterialSrg) + { + shaderResourceGroups.push_back(rayTracingFeatureProcessor->GetRayTracingMaterialSrg()->GetRHIShaderResourceGroup()); + } + dispatchRaysItem.m_shaderResourceGroupCount = aznumeric_cast(shaderResourceGroups.size()); dispatchRaysItem.m_shaderResourceGroups = shaderResourceGroups.data(); dispatchRaysItem.m_rayTracingPipelineState = m_rayTracingPipelineState.get(); diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.h b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.h index 935d034513..6ad082e894 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.h @@ -76,6 +76,7 @@ namespace AZ RHI::ConstPtr m_globalPipelineState; RHI::Ptr m_rayTracingShaderTable; bool m_requiresViewSrg = false; + bool m_requiresRayTracingMaterialSrg = false; }; } // namespace RPI } // namespace AZ From 922099050b319c387e6fc5097a99f2bc31c9681c Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 26 May 2021 04:46:16 -0500 Subject: [PATCH 146/811] Simplified the o3de package gem enable/disable logic The add_gem_project and remove_gem project scripts, now just enables on a gem name basis instead of a CMake target basis Updated the ProjectManager code and scripts to account for the add_gem_project and rmeove_gem_project script changes. --- .../ProjectManager/Source/PythonBindings.cpp | 2 - Gems/TextureAtlas/Code/CMakeLists.txt | 4 +- scripts/o3de/o3de/add_gem_project.py | 245 ++++++------------ scripts/o3de/o3de/cmake.py | 186 ++----------- scripts/o3de/o3de/manifest.py | 4 +- scripts/o3de/o3de/remove_gem_project.py | 167 ++++-------- scripts/project_manager/projects.py | 152 ++--------- 7 files changed, 165 insertions(+), 595 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index efec83bc39..c1e62f9c04 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -591,7 +591,6 @@ namespace O3DE::ProjectManager m_addGemProject.attr("add_gem_to_project")( pybind11::none(), // gem_name pyGemPath, - pybind11::none(), // gem_target pybind11::none(), // project_name pyProjectPath ); @@ -609,7 +608,6 @@ namespace O3DE::ProjectManager m_removeGemProject.attr("remove_gem_from_project")( pybind11::none(), // gem_name pyGemPath, - pybind11::none(), // gem_target pybind11::none(), // project_name pyProjectPath ); diff --git a/Gems/TextureAtlas/Code/CMakeLists.txt b/Gems/TextureAtlas/Code/CMakeLists.txt index 45b9549d10..d67601235d 100644 --- a/Gems/TextureAtlas/Code/CMakeLists.txt +++ b/Gems/TextureAtlas/Code/CMakeLists.txt @@ -62,10 +62,10 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::TextureAtlas.Static Gem::ImageProcessingAtom.Headers ) + ly_create_alias(NAME TextureAtlas.Builders NAMESPACE Gem TARGETS Gem::TextureAtlas.Editor) + ly_create_alias(NAME TextureAtlas.Tools NAMESPACE Gem TARGETS Gem::TextureAtlas.Editor) endif() ly_create_alias(NAME TextureAtlas.Servers NAMESPACE Gem TARGETS Gem::TextureAtlas) ly_create_alias(NAME TextureAtlas.Clients NAMESPACE Gem TARGETS Gem::TextureAtlas) -ly_create_alias(NAME TextureAtlas.Builders NAMESPACE Gem TARGETS Gem::TextureAtlas.Editor) -ly_create_alias(NAME TextureAtlas.Tools NAMESPACE Gem TARGETS Gem::TextureAtlas.Editor) diff --git a/scripts/o3de/o3de/add_gem_project.py b/scripts/o3de/o3de/add_gem_project.py index 8eb1468485..42db0a97bd 100644 --- a/scripts/o3de/o3de/add_gem_project.py +++ b/scripts/o3de/o3de/add_gem_project.py @@ -9,7 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # """ -Contains command to add a gem to a project's cmake scripts +Contains command to add a gem to a project's enabled_gem.cmake file """ import argparse @@ -24,55 +24,51 @@ from o3de import cmake, manifest, validation logger = logging.getLogger() logging.basicConfig() -def add_gem_dependency(cmake_file: str or pathlib.Path, - gem_target: str) -> int: +def add_gem_dependency(cmake_file: pathlib.Path, + gem_name: str) -> int: """ adds a gem dependency to a cmake file :param cmake_file: path to the cmake file - :param gem_target: name of the cmake target + :param gem_name: name of the gem :return: 0 for success or non 0 failure code """ - if not os.path.isfile(cmake_file): - logger.error(f'Failed to locate cmake file {cmake_file}') + if not cmake_file.is_file(): + logger.error(f'Failed to locate cmake file {str(cmake_file)}') return 1 - # on a line by basis, see if there already is Gem::{gem_name} + # on a line by basis, see if there already is {gem_name} # find the first occurrence of a gem, copy its formatting and replace # the gem name with the new one and append it # if the gem is already present fail t_data = [] added = False + line_index_to_append = None with open(cmake_file, 'r') as s: + line_index = 0 for line in s: - if f'Gem::{gem_target}' in line: - logger.warning(f'{gem_target} is already a gem dependency.') + if 'ENABLED_GEMS' in line: + line_index_to_append = line_index + if f'{gem_name}' == line.strip(): + logger.warning(f'{gem_name} is already enabled in file {str(cmake_file)}.') return 0 - if not added and r'Gem::' in line: - new_gem = ' ' * line.find(r'Gem::') + f'Gem::{gem_target}\n' - t_data.append(new_gem) - added = True t_data.append(line) + line_index += 1 - # if we didn't add it the set gem dependencies could be empty so + + indent = 4 + if line_index_to_append: + t_data[line_index_to_append] = f'{" " * indent}{gem_name}\n' + added = True + + # if we didn't add, then create a new set(ENABLED_GEMS) variable # add a new gem, if empty the correct format is 1 tab=4spaces - if not added: - index = 0 - for line in t_data: - index = index + 1 - if r'set(GEM_DEPENDENCIES' in line: - t_data.insert(index, f' Gem::{gem_target}\n') - added = True - break - - # if we didn't add it then it's not here, add a whole new one if not added: t_data.append('\n') - t_data.append('set(GEM_DEPENDENCIES\n') - t_data.append(f' Gem::{gem_target}\n') + t_data.append('set(ENABLED_GEMS\n') + t_data.append(f'{" " * indent}{gem_name}\n') t_data.append(')\n') # write the cmake - os.unlink(cmake_file) with open(cmake_file, 'w') as s: s.writelines(t_data) @@ -80,29 +76,19 @@ def add_gem_dependency(cmake_file: str or pathlib.Path, def add_gem_to_project(gem_name: str = None, - gem_path: str or pathlib.Path = None, - gem_target: str = None, + gem_path: pathlib.Path = None, project_name: str = None, - project_path: str or pathlib.Path = None, - dependencies_file: str or pathlib.Path = None, - runtime_dependency: bool = False, - tool_dependency: bool = False, - server_dependency: bool = False, - platforms: str = 'Common', - add_to_cmake: bool = True) -> int: + project_path: pathlib.Path = None, + enabled_gem_file: pathlib.Path = None, + platforms: str = 'Common') -> int: """ add a gem to a project :param gem_name: name of the gem to add :param gem_path: path to the gem to add - :param gem_target: the name of the cmake gem module :param project_name: name of to the project to add the gem to :param project_path: path to the project to add the gem to - :param dependencies_file: if this dependency goes/is in a specific file - :param runtime_dependency: bool to specify this is a runtime gem for the game - :param tool_dependency: bool to specify this is a tool gem for the editor - :param server_dependency: bool to specify this is a server gem for the server + :param enabled_gem_file_file: if this dependency goes/is in a specific file :param platforms: str to specify common or which specific platforms - :param add_to_cmake: bool to specify that this gem should be added to cmake :return: 0 for success or non 0 failure code """ # we need either a project name or path @@ -113,35 +99,16 @@ def add_gem_to_project(gem_name: str = None, # if project name resolve it into a path if project_name and not project_path: project_path = manifest.get_registered(project_name=project_name) + if not project_path: + logger.error(f'Unable to locate project path from the registered manifest.json files:' + f' {str(pathlib.Path.home() / ".o3de/manifest.json")}, engine.json') + return 1 + project_path = pathlib.Path(project_path).resolve() if not project_path.is_dir(): logger.error(f'Project path {project_path} is not a folder.') return 1 - # get the engine name this project is associated with - # and resolve that engines path - project_json = project_path / 'project.json' - if not validation.valid_o3de_project_json(project_json): - logger.error(f'Project json {project_json} is not valid.') - return 1 - with project_json.open('r') as s: - try: - project_json_data = json.load(s) - except json.JSONDecodeError as e: - logger.error(f'Error loading Project json {project_json}: {str(e)}') - return 1 - else: - try: - engine_name = project_json_data['engine'] - except KeyError as e: - logger.error(f'Project json {project_json} "engine" not found: {str(e)}') - return 1 - else: - engine_path = manifest.get_registered(engine_name=engine_name) - if not engine_path: - logger.error(f'Engine {engine_name} is not registered.') - return 1 - # we need either a gem name or path if not gem_name and not gem_path: logger.error(f'Must either specify a Gem path or Gem Name.') @@ -150,94 +117,47 @@ def add_gem_to_project(gem_name: str = None, # if gem name resolve it into a path if gem_name and not gem_path: gem_path = manifest.get_registered(gem_name=gem_name) + if not gem_path: + logger.error(f'Unable to locate gem path from the registered manifest.json files:' + f' {str(pathlib.Path.home() / ".o3de/manifest.json")},' + f' {project_path / "project.json"}, engine.json') + return 1 + gem_path = pathlib.Path(gem_path).resolve() # make sure this gem already exists if we're adding. We can always remove a gem. if not gem_path.is_dir(): logger.error(f'Gem Path {gem_path} does not exist.') return 1 - # if add to cmake, make sure the gem.json exists and valid before we proceed - if add_to_cmake: - gem_json = gem_path / 'gem.json' - if not gem_json.is_file(): - logger.error(f'Gem json {gem_json} is not present.') - return 1 - if not validation.valid_o3de_gem_json(gem_json): - logger.error(f'Gem json {gem_json} is not valid.') + # Read gem.json from the gem path + gem_json_data = manifest.get_gem_json_data(gem_path=gem_path) + if not gem_json_data: + logger.error(f'Could not read gem.json content under {gem_path}.') + return 1 + + + ret_val = 0 + if enabled_gem_file: + # make sure this is a project has a dependencies_file + if not enabled_gem_file.is_file(): + logger.error(f'Enabled gem file {enabled_gem_file} is not present.') return 1 + # add the dependency + ret_val = add_gem_dependency(enabled_gem_file, gem_json_data['gem_name']) - # find all available modules in this gem_path - modules = cmake.get_gem_targets(gem_path=gem_path) - if len(modules) == 0: - logger.error(f'No gem modules found under {gem_path}.') - return 1 - - # if the gem has no modules and the user has specified a target fail - if gem_target and not modules: - logger.error(f'Gem has no targets, but gem target {gem_target} was specified.') - return 1 - - # if the gem target is not in the modules - if gem_target not in modules: - logger.error(f'Gem target not in gem modules: {modules}') - return 1 - - if gem_target: - # if the user has not specified either we will assume they meant the most common which is runtime - if not runtime_dependency and not tool_dependency and not server_dependency and not dependencies_file: - logger.warning("Dependency type not specified: Assuming '--runtime-dependency'") - runtime_dependency = True - - ret_val = 0 - - # if the user has specified the dependencies file then ignore the runtime_dependency and tool_dependency flags - if dependencies_file: - dependencies_file = pathlib.Path(dependencies_file).resolve() - # make sure this is a project has a dependencies_file - if not dependencies_file.is_file(): - logger.error(f'Dependencies file {dependencies_file} is not present.') - return 1 - # add the dependency - ret_val = add_gem_dependency(dependencies_file, gem_target) - + else: + if ',' in platforms: + platforms = platforms.split(',') else: - if ',' in platforms: - platforms = platforms.split(',') - else: - platforms = [platforms] - for platform in platforms: - if runtime_dependency: - # make sure this is a project has a runtime_dependencies.cmake file - project_runtime_dependencies_file = pathlib.Path( - cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', - platform=platform)).resolve() - if not project_runtime_dependencies_file.is_file(): - logger.error(f'Runtime dependencies file {project_runtime_dependencies_file} is not present.') - return 1 - # add the dependency - ret_val = add_gem_dependency(project_runtime_dependencies_file, gem_target) - - if (ret_val == 0) and tool_dependency: - # make sure this is a project has a tool_dependencies.cmake file - project_tool_dependencies_file = pathlib.Path( - cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', - platform=platform)).resolve() - if not project_tool_dependencies_file.is_file(): - logger.error(f'Tool dependencies file {project_tool_dependencies_file} is not present.') - return 1 - # add the dependency - ret_val = add_gem_dependency(project_tool_dependencies_file, gem_target) - - if (ret_val == 0) and server_dependency: - # make sure this is a project has a tool_dependencies.cmake file - project_server_dependencies_file = pathlib.Path( - cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='server', - platform=platform)).resolve() - if not project_server_dependencies_file.is_file(): - logger.error(f'Server dependencies file {project_server_dependencies_file} is not present.') - return 1 - # add the dependency - ret_val = add_gem_dependency(project_server_dependencies_file, gem_target) + platforms = [platforms] + for platform in platforms: + # Find the path to enabled gem file. + # It will be created by add_gem_dependency if it doesn't exist + project_enabled_gem_file = cmake.get_enabled_gem_cmake_file(project_path=project_path, platform=platform) + if not project_enabled_gem_file.is_file(): + project_enabled_gem_file.touch() + # add the dependency + ret_val = add_gem_dependency(project_enabled_gem_file, gem_json_data['gem_name']) return ret_val @@ -248,15 +168,10 @@ def _run_add_gem_to_project(args: argparse) -> int: return add_gem_to_project(args.gem_name, args.gem_path, - args.gem_target, args.project_name, args.project_path, - args.dependencies_file, - args.runtime_dependency, - args.tool_dependency, - args.server_dependency, - args.platforms, - args.add_to_cmake) + args.enabled_gem_file, + args.platforms) def add_parser_args(parser): @@ -267,38 +182,24 @@ def add_parser_args(parser): :param parser: the caller passes an argparse parser like instance to this method """ group = parser.add_mutually_exclusive_group(required=True) - group.add_argument('-pp', '--project-path', type=str, required=False, + group.add_argument('-pp', '--project-path', type=pathlib.Path, required=False, help='The path to the project.') group.add_argument('-pn', '--project-name', type=str, required=False, help='The name of the project.') group = parser.add_mutually_exclusive_group(required=True) - group.add_argument('-gp', '--gem-path', type=str, required=False, + group.add_argument('-gp', '--gem-path', type=pathlib.Path, required=False, help='The path to the gem.') group.add_argument('-gn', '--gem-name', type=str, required=False, help='The name of the gem.') - parser.add_argument('-gt', '--gem-target', type=str, required=False, - help='The cmake target name to add. If not specified it will assume gem_name') - parser.add_argument('-df', '--dependencies-file', type=str, required=False, - help='The cmake dependencies file in which the gem dependencies are specified.' - 'If not specified it will assume ') - parser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be added as a runtime dependency') - parser.add_argument('-td', '--tool-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be added as a tool dependency') - parser.add_argument('-sd', '--server-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be added as a server dependency') + parser.add_argument('-egf', '--enabled-gem-file', type=pathlib.Path, required=False, + help='The cmake enabled_gem file in which the gem dependencies are specified.' + 'If not specified it will assume enabled_gems.cmake') parser.add_argument('-pl', '--platforms', type=str, required=False, default='Common', help='Optional list of platforms this gem should be added to.' ' Ex. --platforms Mac,Windows,Linux') - parser.add_argument('-a', '--add-to-cmake', type=bool, required=False, - default=True, - help='Automatically call add-gem-to-cmake.') - parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + parser.add_argument('-ohf', '--override-home-folder', type=pathlib.Path, required=False, help='By default the home folder is the user folder, override it to this folder.') parser.set_defaults(func=_run_add_gem_to_project) diff --git a/scripts/o3de/o3de/cmake.py b/scripts/o3de/o3de/cmake.py index 7e95a9c2fe..eb8e3957ad 100644 --- a/scripts/o3de/o3de/cmake.py +++ b/scripts/o3de/o3de/cmake.py @@ -21,30 +21,12 @@ from o3de import manifest logger = logging.getLogger() logging.basicConfig() -def get_project_runtime_gem_targets(project_path: str or pathlib.Path, +def get_project_gems(project_path: pathlib.Path, platform: str = 'Common') -> set: - return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) + return get_gems_from_cmake_file(get_enabled_gem_cmake_file(project_path=project_path, platform=platform)) -def get_project_tool_gem_targets(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) - - -def get_project_server_gem_targets(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) - - -def get_project_gem_targets(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - runtime_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) - tool_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) - server_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) - return runtime_gems.union(tool_gems.union(server_gems)) - - -def get_gem_targets_from_cmake_file(cmake_file: str or pathlib.Path) -> set: +def get_gem_from_cmake_file(cmake_file: pathlib.Path) -> set: """ Gets a list of declared gem targets dependencies of a cmake file :param cmake_file: path to the cmake file @@ -59,102 +41,23 @@ def get_gem_targets_from_cmake_file(cmake_file: str or pathlib.Path) -> set: gem_target_set = set() with cmake_file.open('r') as s: for line in s: - gem_name = line.split('Gem::') - if len(gem_name) > 1: - # Only take the name as everything leading up to the first '.' if found - # Gem naming conventions will have GemName.Editor, GemName.Server, and GemName - # as different targets of the GemName Gem - gem_target_set.add(gem_name[1].replace('\n', '')) + gem_name = line.strip() + gem_target_set.add(gem_name) return gem_target_set -def get_project_runtime_gem_names(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) - - -def get_project_tool_gem_names(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) - - -def get_project_server_gem_names(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) - - -def get_project_gem_names(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - runtime_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) - tool_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) - server_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) - return runtime_gem_names.union(tool_gem_names.union(server_gem_names)) - - -def get_gem_names_from_cmake_file(cmake_file: str or pathlib.Path) -> set: - """ - Gets a list of declared gem dependencies of a cmake file - :param cmake_file: path to the cmake file - :return: set of gems found - """ - cmake_file = pathlib.Path(cmake_file).resolve() - - if not cmake_file.is_file(): - logger.error(f'Failed to locate cmake file {cmake_file}') - return set() - - gem_set = set() - with cmake_file.open('r') as s: - for line in s: - gem_name = line.split('Gem::') - if len(gem_name) > 1: - # Only take the name as everything leading up to the first '.' if found - # Gem naming conventions will have GemName.Editor, GemName.Server, and GemName - # as different targets of the GemName Gem - gem_set.add(gem_name[1].split('.')[0].replace('\n', '')) - return gem_set - - -def get_project_runtime_gem_paths(project_path: str or pathlib.Path, +def get_project_gem_paths(project_path: pathlib.Path, platform: str = 'Common') -> set: - gem_names = get_project_runtime_gem_names(project_path, platform) + gem_names = get_project_gems(project_path, platform) gem_paths = set() for gem_name in gem_names: gem_paths.add(manifest.get_registered(gem_name=gem_name)) return gem_paths -def get_project_tool_gem_paths(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - gem_names = get_project_tool_gem_names(project_path, platform) - gem_paths = set() - for gem_name in gem_names: - gem_paths.add(manifest.get_registered(gem_name=gem_name)) - return gem_paths - - -def get_project_server_gem_paths(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - gem_names = get_project_server_gem_names(project_path, platform) - gem_paths = set() - for gem_name in gem_names: - gem_paths.add(manifest.get_registered(gem_name=gem_name)) - return gem_paths - - -def get_project_gem_paths(project_path: str or pathlib.Path, - platform: str = 'Common') -> set: - gem_names = get_project_gem_names(project_path, platform) - gem_paths = set() - for gem_name in gem_names: - gem_paths.add(manifest.get_registered(gem_name=gem_name)) - return gem_paths - - -def get_dependencies_cmake_file(project_name: str = None, +def get_enabled_gem_cmake_file(project_name: str = None, project_path: str or pathlib.Path = None, - dependency_type: str = 'runtime', - platform: str = 'Common') -> str or None: + platform: str = 'Common') -> pathlib.Path or None: """ get the standard cmake file name for a particular type of dependency :param gem_name: name of the gem, resolves gem_path @@ -169,66 +72,17 @@ def get_dependencies_cmake_file(project_name: str = None, project_path = manifest.get_registered(project_name=project_name) project_path = pathlib.Path(project_path).resolve() + enable_gem_filename = "enabled_gem.cmake" if platform == 'Common': - dependencies_file = f'{dependency_type}_dependencies.cmake' - dependencies_file_path = project_path / 'Gem/Code' / dependencies_file - if dependencies_file_path.is_file(): - return dependencies_file_path - return project_path / 'Code' / dependencies_file + project_code_dir = project_path / 'Gem/Code' + if project_code_dir.is_dir(): + dependencies_file_path = project_code_dir / enable_gem_filename + return dependencies_file_path.resolve() + return (project_path / 'Code' / enable_gem_filename).resolve() else: - dependencies_file = f'{platform.lower()}_{dependency_type}_dependencies.cmake' - dependencies_file_path = project_path / 'Gem/Code/Platform' / platform / dependencies_file - if dependencies_file_path.is_file(): - return dependencies_file_path - return project_path / 'Code/Platform' / platform / dependencies_file - - -def get_all_gem_targets() -> list: - modules = [] - for gem_path in manifest.get_all_gems(): - this_gems_targets = get_gem_targets(gem_path=gem_path) - modules.extend(this_gems_targets) - return modules - - -def get_gem_targets(gem_name: str = None, - gem_path: str or pathlib.Path = None) -> list: - """ - Finds gem targets in a gem - :param gem_name: name of the gem, resolves gem_path - :param gem_path: path of the gem - :return: list of gem targets - """ - if not gem_name and not gem_path: - return [] - - if gem_name and not gem_path: - gem_path = manifest.get_registered(gem_name=gem_name) - - if not gem_path: - return [] - - gem_path = pathlib.Path(gem_path).resolve() - gem_json = gem_path / 'gem.json' - if not validation.valid_o3de_gem_json(gem_json): - return [] - - module_identifiers = [ - 'MODULE', - 'GEM_MODULE', - '${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE}' - ] - modules = [] - for root, dirs, files in os.walk(gem_path): - for file in files: - if file == 'CMakeLists.txt': - with open(os.path.join(root, file), 'r') as s: - for line in s: - trimmed = line.lstrip() - if trimmed.startswith('NAME '): - trimmed = trimmed.rstrip(' \n') - split_trimmed = trimmed.split(' ') - if len(split_trimmed) == 3 and split_trimmed[2] in module_identifiers: - modules.append(split_trimmed[1]) - return modules + project_code_dir = project_path / 'Gem/Code/Platform' / platform + if project_code_dir.is_dir(): + dependencies_file_path = project_code_dir / enable_gem_filename + return dependencies_file_path.resolve() + return (project_path / 'Code/Platform' / platform / enable_gem_filename).resolve() diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index 241f6ecbee..c3b327641c 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -574,9 +574,7 @@ def get_registered(engine_name: str = None, return project_path elif isinstance(gem_name, str): - engine_gems = get_engine_gems() - gems = json_data['gems'].copy() - gems.extend(engine_gems) + gems = get_all_gems() for gem_path in gems: gem_path = pathlib.Path(gem_path).resolve() gem_json = gem_path / 'gem.json' diff --git a/scripts/o3de/o3de/remove_gem_project.py b/scripts/o3de/o3de/remove_gem_project.py index 463cc69961..72c51f0e2c 100644 --- a/scripts/o3de/o3de/remove_gem_project.py +++ b/scripts/o3de/o3de/remove_gem_project.py @@ -9,7 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # """ -Contains methods for removing a gem target from a project +Contains methods for removing a gem from a project """ import argparse @@ -18,41 +18,40 @@ import os import pathlib import sys -from o3de import cmake +from o3de import cmake, manifest logger = logging.getLogger() logging.basicConfig() -def remove_gem_dependency(cmake_file: str or pathlib.Path, - gem_target: str) -> int: +def remove_gem_dependency(cmake_file: pathlib.Path, + gem_name: str) -> int: """ removes a gem dependency from a cmake file :param cmake_file: path to the cmake file - :param gem_target: cmake target name + :param gem_name: name of the gem :return: 0 for success or non 0 failure code """ - if not os.path.isfile(cmake_file): + if not cmake_file.is_file(): logger.error(f'Failed to locate cmake file {cmake_file}') return 1 - # on a line by basis, remove any line with Gem::{gem_name} + # on a line by basis, remove any line with {gem_name} t_data = [] - # Remove the gem from the cmake_dependencies file by skipping the gem name entry + # Remove the gem from the enabled_gem file by skipping the gem name entry removed = False with open(cmake_file, 'r') as s: for line in s: - if f'Gem::{gem_target}' in line: + if gem_name == line.strip(): removed = True else: t_data.append(line) if not removed: - logger.error(f'Failed to remove Gem::{gem_target} from cmake file {cmake_file}') + logger.error(f'Failed to remove {gem_name} from cmake file {cmake_file}') return 1 # write the cmake - os.unlink(cmake_file) with open(cmake_file, 'w') as s: s.writelines(t_data) @@ -60,29 +59,19 @@ def remove_gem_dependency(cmake_file: str or pathlib.Path, def remove_gem_from_project(gem_name: str = None, - gem_path: str or pathlib.Path = None, - gem_target: str = None, + gem_path: pathlib.Path = None, project_name: str = None, - project_path: str or pathlib.Path = None, - dependencies_file: str or pathlib.Path = None, - runtime_dependency: bool = False, - tool_dependency: bool = False, - server_dependency: bool = False, - platforms: str = 'Common', - remove_from_cmake: bool = False) -> int: + project_path: pathlib.Path = None, + enabled_gem_file: pathlib.Path = None, + platforms: str = 'Common') -> int: """ remove a gem from a project :param gem_name: name of the gem to add :param gem_path: path to the gem to add - :param gem_target: the name of teh cmake gem module :param project_name: name of the project to add the gem to :param project_path: path to the project to add the gem to - :param dependencies_file: if this dependency goes/is in a specific file - :param runtime_dependency: bool to specify this is a runtime gem for the game - :param tool_dependency: bool to specify this is a tool gem for the editor - :param server_dependency: bool to specify this is a server gem for the server + :param enabled_gem_file: File to remove enabled gem from :param platforms: str to specify common or which specific platforms - :param remove_from_cmake: bool to specify that this gem should be removed from cmake :return: 0 for success or non 0 failure code """ @@ -94,6 +83,11 @@ def remove_gem_from_project(gem_name: str = None, # if project name resolve it into a path if project_name and not project_path: project_path = manifest.get_registered(project_name=project_name) + if not project_path: + logger.error(f'Unable to locate project path from the registered manifest.json files:' + f' {str(pathlib.Path.home() / ".o3de/manifest.json")}, engine.json') + return 1 + project_path = pathlib.Path(project_path).resolve() if not project_path.is_dir(): logger.error(f'Project path {project_path} is not a folder.') @@ -107,48 +101,35 @@ def remove_gem_from_project(gem_name: str = None, # if gem name resolve it into a path if gem_name and not gem_path: gem_path = manifest.get_registered(gem_name=gem_name) + if not gem_path: + logger.error(f'Unable to locate gem path from the registered manifest.json files:' + f' {str(pathlib.Path.home() / ".o3de/manifest.json")},' + f' {project_path / "project.json"}, engine.json') + return 1 gem_path = pathlib.Path(gem_path).resolve() # make sure this gem already exists if we're adding. We can always remove a gem. if not gem_path.is_dir(): logger.error(f'Gem Path {gem_path} does not exist.') return 1 - # find all available modules in this gem_path - modules = cmake.get_gem_targets(gem_path=gem_path) - if len(modules) == 0: - logger.error(f'No gem modules found.') + + # Read gem.json from the gem path + gem_json_data = manifest.get_gem_json_data(gem_path=gem_path) + if not gem_json_data: + logger.error(f'Could not read gem.json content under {gem_path}.') return 1 - # if the user has not set a specific gem target remove all of them - - # if gem target not specified, see if there is only 1 module - if not gem_target: - if len(modules) == 1: - gem_target = modules[0] - else: - logger.error(f'Gem target not specified: {modules}') - return 1 - elif gem_target not in modules: - logger.error(f'Gem target not in gem modules: {modules}') - return 1 - - # if the user has not specified either we will assume they meant the most common which is runtime - if not runtime_dependency and not tool_dependency and not server_dependency and not dependencies_file: - logger.warning("Dependency type not specified: Assuming '--runtime-dependency'") - runtime_dependency = True - # when removing we will try to do as much as possible even with failures so ret_val will be the last error code ret_val = 0 # if the user has specified the dependencies file then ignore the runtime_dependency and tool_dependency flags - if dependencies_file: - dependencies_file = pathlib.Path(dependencies_file).resolve() - # make sure this is a project has a dependencies_file - if not dependencies_file.is_file(): - logger.error(f'Dependencies file {dependencies_file} is not present.') + if enabled_gem_file: + # make sure this is a project has an enabled_gem file + if not enabled_gem_file.is_file(): + logger.error(f'Enabled gem file {enabled_gem_file} is not present.') return 1 # remove the dependency - error_code = remove_gem_dependency(dependencies_file, gem_target) + error_code = remove_gem_dependency(dependencies_file, gem_json_data['gem_name']) if error_code: ret_val = error_code else: @@ -157,44 +138,16 @@ def remove_gem_from_project(gem_name: str = None, else: platforms = [platforms] for platform in platforms: - if runtime_dependency: - # make sure this is a project has a runtime_dependencies.cmake file - project_runtime_dependencies_file = pathlib.Path( - cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', - platform=platform)).resolve() - if not project_runtime_dependencies_file.is_file(): - logger.error(f'Runtime dependencies file {project_runtime_dependencies_file} is not present.') - else: - # remove the dependency - error_code = remove_gem_dependency(project_runtime_dependencies_file, gem_target) - if error_code: - ret_val = error_code + # make sure this is a project has a enabled_gem.cmake file + project_enabled_gem_file = cmake.get_enabled_gem_cmake_file(project_path=project_path, platform=platform) + if not project_enabled_gem_file.is_file(): + logger.error(f'Enabled gem file {project_enabled_gem_file} is not present.') + else: + # remove the dependency + error_code = remove_gem_dependency(project_enabled_gem_file, gem_json_data['gem_name']) + if error_code: + ret_val = error_code - if tool_dependency: - # make sure this is a project has a tool_dependencies.cmake file - project_tool_dependencies_file = pathlib.Path( - cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', - platform=platform)).resolve() - if not project_tool_dependencies_file.is_file(): - logger.error(f'Tool dependencies file {project_tool_dependencies_file} is not present.') - else: - # remove the dependency - error_code = remove_gem_dependency(project_tool_dependencies_file, gem_target) - if error_code: - ret_val = error_code - - if server_dependency: - # make sure this is a project has a tool_dependencies.cmake file - project_server_dependencies_file = pathlib.Path( - cmake.get_dependencies_cmake_file(project_path=project_path, dependency_type='server', - platform=platform)).resolve() - if not project_server_dependencies_file.is_file(): - logger.error(f'Server dependencies file {project_server_dependencies_file} is not present.') - else: - # remove the dependency - error_code = remove_gem_dependency(project_server_dependencies_file, gem_target) - if error_code: - ret_val = error_code return ret_val @@ -205,15 +158,10 @@ def _run_remove_gem_from_project(args: argparse) -> int: return remove_gem_from_project(args.gem_name, args.gem_path, - args.gem_target, - args.project_path, args.project_name, - args.dependencies_file, - args.runtime_dependency, - args.tool_dependency, - args.server_dependency, - args.platforms, - args.remove_from_cmake) + args.project_path, + args.enabled_gem_file, + args.platforms) def add_parser_args(parser): @@ -224,35 +172,24 @@ def add_parser_args(parser): :param parser: the caller passes an argparse parser like instance to this method """ group = parser.add_mutually_exclusive_group(required=True) - group.add_argument('-pp', '--project-path', type=str, required=False, + group.add_argument('-pp', '--project-path', type=pathlib.Path, required=False, help='The path to the project.') group.add_argument('-pn', '--project-name', type=str, required=False, help='The name of the project.') group = parser.add_mutually_exclusive_group(required=True) - group.add_argument('-gp', '--gem-path', type=str, required=False, + group.add_argument('-gp', '--gem-path', type=pathlib.Path, required=False, help='The path to the gem.') group.add_argument('-gn', '--gem-name', type=str, required=False, help='The name of the gem.') - parser.add_argument('-gt', '--gem-target', type=str, required=False, - help='The cmake target name to add. If not specified it will assume gem_name') - parser.add_argument('-df', '--dependencies-file', type=str, required=False, - help='The cmake dependencies file in which the gem dependencies are specified.' + parser.add_argument('-egf', '--enabled-gem-file', type=pathlib.Path, required=False, + help='The cmake enabled gem file in which gem dependencies are to be removed from.' 'If not specified it will assume ') - parser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be removed as a runtime dependency') - parser.add_argument('-td', '--tool-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be removed as a server dependency') - parser.add_argument('-sd', '--server-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be removed as a server dependency') parser.add_argument('-pl', '--platforms', type=str, required=False, default='Common', help='Optional list of platforms this gem should be removed from' ' Ex. --platforms Mac,Windows,Linux') - parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + parser.add_argument('-ohf', '--override-home-folder', type=pathlib.Path, required=False, help='By default the home folder is the user folder, override it to this folder.') parser.set_defaults(func=_run_remove_gem_from_project) diff --git a/scripts/project_manager/projects.py b/scripts/project_manager/projects.py index 704b7c5f9a..71d0d11b2c 100755 --- a/scripts/project_manager/projects.py +++ b/scripts/project_manager/projects.py @@ -766,167 +766,49 @@ class ProjectManagerDialog(QObject): selected_items = self.enabled_gem_targets_list.selectionModel().selectedRows() return [(self.enabled_gem_targets_list.model().data(item)) for item in selected_items] - def add_runtime_project_gem_targets_handler(self) -> None: + def add_project_gem_targets_handler(self) -> None: gem_paths = manifest.get_all_gems() for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): for gem_path in gem_paths: - this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) - for this_gem_target in this_gems_targets: - if gem_target == this_gem_target: - add_gem_project.add_gem_to_project(gem_path=gem_path, - gem_target=gem_target, - project_path=self.get_selected_project_path(), - runtime_dependency=True) - self.refresh_runtime_project_gem_targets_available_list() - self.refresh_runtime_project_gem_targets_enabled_list() - return + add_gem_project.add_gem_to_project(gem_path=gem_path, + project_path=self.get_selected_project_path()) + self.refresh_runtime_project_gem_targets_available_list() + self.refresh_runtime_project_gem_targets_enabled_list() + return self.refresh_runtime_project_gem_targets_available_list() self.refresh_runtime_project_gem_targets_enabled_list() - def remove_runtime_project_gem_targets_handler(self): + def remove_project_gem_targets_handler(self): gem_paths = manifest.get_all_gems() for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): for gem_path in gem_paths: - this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) - for this_gem_target in this_gems_targets: - if gem_target == this_gem_target: - remove_gem_project.remove_gem_from_project(gem_path=gem_path, - gem_target=gem_target, - project_path=self.get_selected_project_path(), - runtime_dependency=True) - self.refresh_runtime_project_gem_targets_available_list() - self.refresh_runtime_project_gem_targets_enabled_list() - return + remove_gem_project.remove_gem_from_project(gem_path=gem_path, + project_path=self.get_selected_project_path()) + self.refresh_runtime_project_gem_targets_available_list() + self.refresh_runtime_project_gem_targets_enabled_list() + return self.refresh_runtime_project_gem_targets_available_list() self.refresh_runtime_project_gem_targets_enabled_list() - def add_tool_project_gem_targets_handler(self) -> None: - gem_paths = manifest.get_all_gems() - for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): - for gem_path in gem_paths: - this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) - for this_gem_target in this_gems_targets: - if gem_target == this_gem_target: - add_gem_project.add_gem_to_project(gem_path=gem_path, - gem_target=gem_target, - project_path=self.get_selected_project_path(), - tool_dependency=True) - self.refresh_tool_project_gem_targets_available_list() - self.refresh_tool_project_gem_targets_enabled_list() - return - self.refresh_tool_project_gem_targets_available_list() - self.refresh_tool_project_gem_targets_enabled_list() - - def remove_tool_project_gem_targets_handler(self): - gem_paths = manifest.get_all_gems() - for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): - for gem_path in gem_paths: - this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) - for this_gem_target in this_gems_targets: - if gem_target == this_gem_target: - remove_gem_project.remove_gem_from_project(gem_path=gem_path, - gem_target=gem_target, - project_path=self.get_selected_project_path(), - tool_dependency=True) - self.refresh_tool_project_gem_targets_available_list() - self.refresh_tool_project_gem_targets_enabled_list() - return - self.refresh_tool_project_gem_targets_available_list() - self.refresh_tool_project_gem_targets_enabled_list() - - def add_server_project_gem_targets_handler(self) -> None: - gem_paths = manifest.get_all_gems() - for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): - for gem_path in gem_paths: - this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) - for this_gem_target in this_gems_targets: - if gem_target == this_gem_target: - add_gem_project.add_gem_to_project(gem_path=gem_path, - gem_target=gem_target, - project_path=self.get_selected_project_path(), - server_dependency=True) - self.refresh_server_project_gem_targets_available_list() - self.refresh_server_project_gem_targets_enabled_list() - return - self.refresh_server_project_gem_targets_available_list() - self.refresh_server_project_gem_targets_enabled_list() - - def remove_server_project_gem_targets_handler(self): - gem_paths = manifest.get_all_gems() - for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): - for gem_path in gem_paths: - this_gems_targets = cmake.get_gem_targets(gem_path=gem_path) - for this_gem_target in this_gems_targets: - if gem_target == this_gem_target: - remove_gem_project.remove_gem_from_project(gem_path=gem_path, - gem_target=gem_target, - project_path=self.get_selected_project_path(), - server_dependency=True) - self.refresh_server_project_gem_targets_available_list() - self.refresh_server_project_gem_targets_enabled_list() - return - self.refresh_server_project_gem_targets_available_list() - self.refresh_server_project_gem_targets_enabled_list() - def refresh_runtime_project_gem_targets_enabled_list(self) -> None: enabled_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = cmake.get_project_runtime_gem_targets( - project_path=self.get_selected_project_path()) - for gem_target in sorted(enabled_project_gem_targets): + enabled_project_gems = cmake.get_project_gems(project_path=self.get_selected_project_path()) + for gem_target in sorted(enabled_project_gems): model_item = QStandardItem(gem_target) enabled_project_gem_targets_model.appendRow(model_item) self.enabled_gem_targets_list.setModel(enabled_project_gem_targets_model) + def refresh_runtime_project_gem_targets_available_list(self) -> None: available_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = cmake.get_project_runtime_gem_targets( - project_path=self.get_selected_project_path()) - all_gem_targets = cmake.get_all_gem_targets() + enabled_project_gem_targets = cmake.get_project_gems(project_path=self.get_selected_project_path()) + all_gem_targets = manifest.get_all_gems() for gem_target in sorted(all_gem_targets): if gem_target not in enabled_project_gem_targets: model_item = QStandardItem(gem_target) available_project_gem_targets_model.appendRow(model_item) self.available_gem_targets_list.setModel(available_project_gem_targets_model) - - def refresh_tool_project_gem_targets_enabled_list(self) -> None: - enabled_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = cmake.get_project_tool_gem_targets( - project_path=self.get_selected_project_path()) - for gem_target in sorted(enabled_project_gem_targets): - model_item = QStandardItem(gem_target) - enabled_project_gem_targets_model.appendRow(model_item) - self.enabled_gem_targets_list.setModel(enabled_project_gem_targets_model) - def refresh_tool_project_gem_targets_available_list(self) -> None: - available_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = cmake.get_project_tool_gem_targets( - project_path=self.get_selected_project_path()) - all_gem_targets = cmake.get_all_gem_targets() - for gem_target in sorted(all_gem_targets): - if gem_target not in enabled_project_gem_targets: - model_item = QStandardItem(gem_target) - available_project_gem_targets_model.appendRow(model_item) - self.available_gem_targets_list.setModel(available_project_gem_targets_model) - - def refresh_server_project_gem_targets_enabled_list(self) -> None: - enabled_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = cmake.get_project_server_gem_targets( - project_path=self.get_selected_project_path()) - for gem_target in sorted(enabled_project_gem_targets): - model_item = QStandardItem(gem_target) - enabled_project_gem_targets_model.appendRow(model_item) - self.enabled_gem_targets_list.setModel(enabled_project_gem_targets_model) - - def refresh_server_project_gem_targets_available_list(self) -> None: - available_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = cmake.get_project_server_gem_targets( - project_path=self.get_selected_project_path()) - all_gem_targets = cmake.get_all_gem_targets() - for gem_target in sorted(all_gem_targets): - if gem_target not in enabled_project_gem_targets: - model_item = QStandardItem(gem_target) - available_project_gem_targets_model.appendRow(model_item) - self.available_gem_targets_list.setModel(available_project_gem_targets_model) def refresh_create_project_template_list(self) -> None: self.create_project_template_model = QStandardItemModel() From 62d196da301fd5e7483ee8c77143e9cc110d71af Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 26 May 2021 04:57:43 -0500 Subject: [PATCH 147/811] Removed tool and server gem query functions from the ProjectManager projects.py script Updated the mentions of the runtime gem targets to just be general project gem targets --- scripts/project_manager/projects.py | 135 ++++------------------------ 1 file changed, 18 insertions(+), 117 deletions(-) diff --git a/scripts/project_manager/projects.py b/scripts/project_manager/projects.py index 71d0d11b2c..d062343662 100755 --- a/scripts/project_manager/projects.py +++ b/scripts/project_manager/projects.py @@ -186,12 +186,8 @@ class ProjectManagerDialog(QObject): self.remove_restricted_button = self.dialog.findChild(QPushButton, 'removeRestrictedButton') self.remove_restricted_button.clicked.connect(self.remove_restricted_handler) - self.manage_runtime_project_gem_targets_button = self.dialog.findChild(QPushButton, 'manageRuntimeGemTargetsButton') - self.manage_runtime_project_gem_targets_button.clicked.connect(self.manage_runtime_project_gem_targets_handler) - self.manage_tool_project_gem_targets_button = self.dialog.findChild(QPushButton, 'manageToolGemTargetsButton') - self.manage_tool_project_gem_targets_button.clicked.connect(self.manage_tool_project_gem_targets_handler) - self.manage_server_project_gem_targets_button = self.dialog.findChild(QPushButton, 'manageServerGemTargetsButton') - self.manage_server_project_gem_targets_button.clicked.connect(self.manage_server_project_gem_targets_handler) + self.manage_project_gem_targets_button = self.dialog.findChild(QPushButton, 'manageRuntimeGemTargetsButton') + self.manage_project_gem_targets_button.clicked.connect(self.manage_project_gem_targets_handler) self.log_display = self.dialog.findChild(QLabel, 'logDisplay') @@ -615,7 +611,7 @@ class ProjectManagerDialog(QObject): msg_box.exec() return - def manage_runtime_project_gem_targets_handler(self): + def manage_project_gem_targets_handler(self): """ Opens the Gem management pane. Waits for the load thread to complete if still running and displays all active gems for the current project as well as all available gems which aren't currently active. @@ -642,121 +638,26 @@ class ProjectManagerDialog(QObject): logger.error(f'Failed to load gems dialog file at {self.manage_project_gem_targets_ui_file_path.as_posix()}') return - self.manage_project_gem_targets_dialog.setWindowTitle(f"Manage Runtime Gem Targets for Project:" + self.manage_project_gem_targets_dialog.setWindowTitle(f"Manage Gems for Project:" f" {self.get_selected_project_name()}") self.add_gem_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, 'addGemTargetsButton') - self.add_gem_button.clicked.connect(self.add_runtime_project_gem_targets_handler) + self.add_gem_button.clicked.connect(self.add_project_gem_targets_handler) self.available_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, 'availableGemTargetsList') - self.refresh_runtime_project_gem_targets_available_list() + self.refresh_project_gem_targets_available_list() self.remove_project_gem_targets_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, 'removeGemTargetsButton') - self.remove_project_gem_targets_button.clicked.connect(self.remove_runtime_project_gem_targets_handler) + self.remove_project_gem_targets_button.clicked.connect(self.remove_project_gem_targets_handler) self.enabled_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, 'enabledGemTargetsList') - self.refresh_runtime_project_gem_targets_enabled_list() + self.refresh_project_gem_targets_enabled_list() self.manage_project_gem_targets_dialog.exec() - def manage_tool_project_gem_targets_handler(self): - """ - Opens the Gem management pane. Waits for the load thread to complete if still running and displays all - active gems for the current project as well as all available gems which aren't currently active. - :return: None - """ - - if not self.get_selected_project_path(): - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText("Please select a project") - msg_box.exec() - return - - loader = QUiLoader() - self.manage_project_gem_targets_file = QFile(self.manage_project_gem_targets_ui_file_path.as_posix()) - - if not self.manage_project_gem_targets_file: - logger.error(f'Failed to load manage gem targets UI file at {self.manage_project_gem_targets_ui_file_path}') - return - - self.manage_project_gem_targets_dialog = loader.load(self.manage_project_gem_targets_file) - - if not self.manage_project_gem_targets_dialog: - logger.error( - f'Failed to load gems dialog file at {self.manage_project_gem_targets_ui_file_path.as_posix()}') - return - - self.manage_project_gem_targets_dialog.setWindowTitle(f"Manage Tool Gem Targets for Project:" - f" {self.get_selected_project_name()}") - - self.add_gem_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, 'addGemTargetsButton') - self.add_gem_button.clicked.connect(self.add_tool_project_gem_targets_handler) - - self.available_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, - 'availableGemTargetsList') - self.refresh_tool_project_gem_targets_available_list() - - self.remove_project_gem_targets_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, - 'removeGemTargetsButton') - self.remove_project_gem_targets_button.clicked.connect(self.remove_tool_project_gem_targets_handler) - - self.enabled_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, - 'enabledGemTargetsList') - self.refresh_tool_project_gem_targets_enabled_list() - - self.manage_project_gem_targets_dialog.exec() - - def manage_server_project_gem_targets_handler(self): - """ - Opens the Gem management pane. Waits for the load thread to complete if still running and displays all - active gems for the current project as well as all available gems which aren't currently active. - :return: None - """ - - if not self.get_selected_project_path(): - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText("Please select a project") - msg_box.exec() - return - - loader = QUiLoader() - self.manage_project_gem_targets_file = QFile(self.manage_project_gem_targets_ui_file_path.as_posix()) - - if not self.manage_project_gem_targets_file: - logger.error(f'Failed to load manage gem targets UI file at {self.manage_project_gem_targets_ui_file_path}') - return - - self.manage_project_gem_targets_dialog = loader.load(self.manage_project_gem_targets_file) - - if not self.manage_project_gem_targets_dialog: - logger.error( - f'Failed to load gems dialog file at {self.manage_project_gem_targets_ui_file_path.as_posix()}') - return - - self.manage_project_gem_targets_dialog.setWindowTitle(f"Manage Server Gem Targets for Project:" - f" {self.get_selected_project_name()}") - - self.add_gem_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, 'addGemTargetsButton') - self.add_gem_button.clicked.connect(self.add_server_project_gem_targets_handler) - - self.available_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, - 'availableGemTargetsList') - self.refresh_server_project_gem_targets_available_list() - - self.remove_project_gem_targets_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, - 'removeGemTargetsButton') - self.remove_project_gem_targets_button.clicked.connect(self.remove_server_project_gem_targets_handler) - - self.enabled_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, - 'enabledGemTargetsList') - self.refresh_server_project_gem_targets_enabled_list() - - self.manage_project_gem_targets_dialog.exec() def manage_project_gem_targets_get_selected_available_gems(self) -> list: selected_items = self.available_gem_targets_list.selectionModel().selectedRows() @@ -772,11 +673,11 @@ class ProjectManagerDialog(QObject): for gem_path in gem_paths: add_gem_project.add_gem_to_project(gem_path=gem_path, project_path=self.get_selected_project_path()) - self.refresh_runtime_project_gem_targets_available_list() - self.refresh_runtime_project_gem_targets_enabled_list() + self.refresh_project_gem_targets_available_list() + self.refresh_project_gem_targets_enabled_list() return - self.refresh_runtime_project_gem_targets_available_list() - self.refresh_runtime_project_gem_targets_enabled_list() + self.refresh_project_gem_targets_available_list() + self.refresh_project_gem_targets_enabled_list() def remove_project_gem_targets_handler(self): gem_paths = manifest.get_all_gems() @@ -784,13 +685,13 @@ class ProjectManagerDialog(QObject): for gem_path in gem_paths: remove_gem_project.remove_gem_from_project(gem_path=gem_path, project_path=self.get_selected_project_path()) - self.refresh_runtime_project_gem_targets_available_list() - self.refresh_runtime_project_gem_targets_enabled_list() + self.refresh_project_gem_targets_available_list() + self.refresh_project_gem_targets_enabled_list() return - self.refresh_runtime_project_gem_targets_available_list() - self.refresh_runtime_project_gem_targets_enabled_list() + self.refresh_project_gem_targets_available_list() + self.refresh_project_gem_targets_enabled_list() - def refresh_runtime_project_gem_targets_enabled_list(self) -> None: + def refresh_project_gem_targets_enabled_list(self) -> None: enabled_project_gem_targets_model = QStandardItemModel() enabled_project_gems = cmake.get_project_gems(project_path=self.get_selected_project_path()) for gem_target in sorted(enabled_project_gems): @@ -799,7 +700,7 @@ class ProjectManagerDialog(QObject): self.enabled_gem_targets_list.setModel(enabled_project_gem_targets_model) - def refresh_runtime_project_gem_targets_available_list(self) -> None: + def refresh_project_gem_targets_available_list(self) -> None: available_project_gem_targets_model = QStandardItemModel() enabled_project_gem_targets = cmake.get_project_gems(project_path=self.get_selected_project_path()) all_gem_targets = manifest.get_all_gems() From 09c5bb8d65e724d2e7f1cc6df69c53ea46056bbb Mon Sep 17 00:00:00 2001 From: mnaumov Date: Wed, 26 May 2021 06:29:09 -0700 Subject: [PATCH 148/811] [ATOM-15464] Fixing Material Editor crash on shutdown --- .../ReleaseResourcesStep.cpp | 41 +++++++++---------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.cpp index bad7c2fe38..ef82792f32 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.cpp @@ -32,32 +32,29 @@ namespace AZ void ReleaseResourcesStep::Start() { - m_context->GetData()->m_defaultMaterialAsset.Release(); - m_context->GetData()->m_defaultModelAsset.Release(); - m_context->GetData()->m_materialAsset.Release(); - m_context->GetData()->m_modelAsset.Release(); + auto data = m_context->GetData(); + + data->m_defaultMaterialAsset.Release(); + data->m_defaultModelAsset.Release(); + data->m_materialAsset.Release(); + data->m_modelAsset.Release(); + data->m_lightingPresetAsset.Release(); - if (m_context->GetData()->m_modelEntity) + if (data->m_modelEntity) { - AzFramework::EntityContextRequestBus::Event(m_context->GetData()->m_entityContext->GetContextId(), - &AzFramework::EntityContextRequestBus::Events::DestroyEntity, m_context->GetData()->m_modelEntity); - m_context->GetData()->m_modelEntity = nullptr; + AzFramework::EntityContextRequestBus::Event(data->m_entityContext->GetContextId(), + &AzFramework::EntityContextRequestBus::Events::DestroyEntity, data->m_modelEntity); + data->m_modelEntity = nullptr; } - m_context->GetData()->m_frameworkScene->UnsetSubsystem(); - - m_context->GetData()->m_scene->Deactivate(); - m_context->GetData()->m_scene->RemoveRenderPipeline(m_context->GetData()->m_renderPipeline->GetId()); - RPI::RPISystemInterface::Get()->UnregisterScene(m_context->GetData()->m_scene); - - auto sceneSystem = AzFramework::SceneSystemInterface::Get(); - AZ_Assert(sceneSystem, "Thumbnail system failed to get scene system implementation."); - [[maybe_unused]] bool sceneRemovedSuccessfully = sceneSystem->RemoveScene(m_context->GetData()->m_sceneName); - AZ_Assert( - sceneRemovedSuccessfully, "Thumbnail system was unable to remove scene '%s' from the scene system.", - m_context->GetData()->m_sceneName.c_str()); - m_context->GetData()->m_scene = nullptr; - m_context->GetData()->m_renderPipeline = nullptr; + data->m_scene->Deactivate(); + data->m_scene->RemoveRenderPipeline(data->m_renderPipeline->GetId()); + RPI::RPISystemInterface::Get()->UnregisterScene(data->m_scene); + data->m_frameworkScene->UnsetSubsystem(data->m_scene); + data->m_frameworkScene->UnsetSubsystem(data->m_entityContext.get()); + data->m_scene = nullptr; + data->m_frameworkScene = nullptr; + data->m_renderPipeline = nullptr; } } // namespace Thumbnails } // namespace LyIntegration From e8428b42beb80a0b9c71ed9112df83543822a2a1 Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 26 May 2021 08:17:09 -0700 Subject: [PATCH 149/811] Adjusting o3de path to run from install (authored by @lumberyard-employee-dm) --- scripts/o3de.py | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/scripts/o3de.py b/scripts/o3de.py index 050d860790..f91d5a25a0 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -26,26 +26,15 @@ def add_args(parser, subparsers) -> None: # As o3de.py shares the same name as the o3de package attempting to use a regular # from o3de import line tries to import from the current o3de.py script and not the package - # So the current script directory is removed from the sys.path temporary - script_dir_removed = False - script_abs_dir_removed = False + # So the {current script directory} / 'o3de' is added to the front of the sys.path script_dir = pathlib.Path(__file__).parent - script_abs_dir = pathlib.Path(__file__).parent.resolve() - while str(script_dir) in sys.path: - script_dir_removed = True - sys.path.remove(str(script_dir)) - while str(script_abs_dir) in sys.path: - script_abs_dir_removed = True - # Remove the absolute path to the script_dir as well - sys.path.remove(str(script_abs_dir.resolve())) - + o3de_package_dir = (script_dir / 'o3de').resolve() + # add the scripts/o3de directory to the front of the sys.path + sys.path.insert(0, str(o3de_package_dir)) from o3de import engine_template, global_project, register, print_registration, get_registration, download, \ add_gem_project, remove_gem_project, sha256 - - if script_abs_dir_removed: - sys.path.insert(0, str(script_abs_dir)) - if script_dir_removed: - sys.path.insert(0, str(script_dir)) + # Remove the temporarily added path + sys.path = sys.path[1:] # global_project global_project.add_args(subparsers) From 5449c5785b04be7219baaf8bcbe120ebefd3d4d3 Mon Sep 17 00:00:00 2001 From: gallowj Date: Wed, 26 May 2021 10:35:50 -0500 Subject: [PATCH 150/811] Several small fixes to the DCCsi to match some o3de changes --- .../3rdParty/Python/.gitignore | 1 + .../Editor/Scripts/bootstrap.py | 6 ++-- .../Launchers/Windows/Env_Core.bat | 13 ++++---- .../DccScriptingInterface/SDK/Maya/readme.txt | 2 +- .../DccScriptingInterface/config.py | 30 +++++++++---------- .../DccScriptingInterface/gem.json | 17 +++++++++++ 6 files changed, 45 insertions(+), 24 deletions(-) create mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/3rdParty/Python/.gitignore create mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/gem.json diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/3rdParty/Python/.gitignore b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/3rdParty/Python/.gitignore new file mode 100644 index 0000000000..f1a223f90e --- /dev/null +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/3rdParty/Python/.gitignore @@ -0,0 +1 @@ +pyside2-tools \ No newline at end of file diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py index 6fd8b03e9e..835c196924 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py @@ -81,8 +81,8 @@ settings = config.get_config_settings() if __name__ == '__main__': """Run this file as main""" - _G_DEBUG = True - _G_TEST_PYSIDE = True + _G_DEBUG = False + _G_TEST_PYSIDE = False _config = get_dccsi_config() _settings = config.get_config_settings() @@ -121,7 +121,7 @@ if __name__ == '__main__': import PySide2 _LOGGER.info(f'PySide2: {PySide2}') - _LOGGER.info(f'QTFORPYTHON_PATH: {_settings.QTFORPYTHON_PATH}') + #_LOGGER.info(f'QTFORPYTHON_PATH: {_settings.QTFORPYTHON_PATH}') _LOGGER.info(f'LY_BIN_PATH: {_settings.LY_BIN_PATH}') _LOGGER.info(f'QT_PLUGIN_PATH: {_settings.QT_PLUGIN_PATH}') _LOGGER.info(f'QT_QPA_PLATFORM_PLUGIN_PATH: {_settings.QT_QPA_PLATFORM_PLUGIN_PATH}') diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Launchers/Windows/Env_Core.bat b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Launchers/Windows/Env_Core.bat index 4a64c43029..37c5a9c2b9 100644 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Launchers/Windows/Env_Core.bat +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Launchers/Windows/Env_Core.bat @@ -68,14 +68,17 @@ IF "%DEV_REL_PATH%"=="" (set DEV_REL_PATH=..\..\..\..) echo DEV_REL_PATH = %DEV_REL_PATH% :: You can define the project name -:: if not defined we just use the DCCsi path as standin -IF "%LY_PROJECT%"=="" ( - for %%a in (%CD%..\..\..) do set LY_PROJECT=%%~na +IF "%LY_PROJECT_NAME%"=="" ( + for %%a in (%CD%..\..\..) do set LY_PROJECT_NAME=%%~na ) +echo LY_PROJECT_NAME = %LY_PROJECT_NAME% + +:: if not defined we just use the DCCsi path as stand-in +IF "%LY_PROJECT%"=="" (set LY_PROJECT=%CD%) echo LY_PROJECT = %LY_PROJECT% :: set up the default project path (dccsi) -:: if not set we lso use the DCCsi path as standin +:: if not set we lso use the DCCsi path as stand-in CD /D ..\..\ IF "%LY_PROJECT_PATH%"=="" (set LY_PROJECT_PATH=%CD%) echo LY_PROJECT_PATH = %LY_PROJECT_PATH% @@ -88,7 +91,7 @@ pushd %ABS_PATH% :: Change to root Lumberyard dev dir CD /d %LY_PROJECT_PATH%\%DEV_REL_PATH% -set LY_DEV=%CD% +IF "%LY_DEV%"=="" (set LY_DEV=%CD%) echo LY_DEV = %LY_DEV% :: Restore original directory popd diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/readme.txt b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/readme.txt index cc090d922f..21882f3d96 100644 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/readme.txt +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/readme.txt @@ -29,7 +29,7 @@ A general goal of the DCCsi is be self-maintained, and to not taint the users in So we boostrap additional access to site-packages in our userSetup.py: "C:\Depot\Lumberyard\Gems\AtomLyIntegration\TechnicalArt\DccScriptingInterface\SDK\Maya\Scripts\userSetup.py" -We don't want users to have to install or use Python2.7 although with maya and possibly other dcc tools we don't have that control. Maya still is on Python2.7, so instead of forcing another install of python we can just use mayapy to manage extensions. +We don't want users to have to install or use Python2.7 although with maya and possibly other dcc tools we don't have that control. Maya 2020 and earlier versions are still on Python2.7, so instead of forcing another install of python we can just use mayapy to manage extensions. Pip may already be installed, you can check like so (your maya install path may be different): diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/config.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/config.py index c62571b2f5..45ff48c272 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/config.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/config.py @@ -109,11 +109,11 @@ def init_ly_pyside(LY_DEV=None): 'bin', 'profile').resolve() - # allows to retreive from settings.QTFORPYTHON_PATH - from azpy.constants import STR_QTFORPYTHON_PATH # a path string constructor - QTFORPYTHON_PATH = Path(STR_QTFORPYTHON_PATH.format(LY_DEV)).resolve() - os.environ["DYNACONF_QTFORPYTHON_PATH"] = str(QTFORPYTHON_PATH) - site.addsitedir(str(QTFORPYTHON_PATH)) # PYTHONPATH + # # allows to retreive from settings.QTFORPYTHON_PATH + # from azpy.constants import STR_QTFORPYTHON_PATH # a path string constructor + # QTFORPYTHON_PATH = Path(STR_QTFORPYTHON_PATH.format(LY_DEV)).resolve() + # os.environ["DYNACONF_QTFORPYTHON_PATH"] = str(QTFORPYTHON_PATH) + # site.addsitedir(str(QTFORPYTHON_PATH)) # PYTHONPATH QT_PLUGIN_PATH = Path.joinpath(LY_BIN_PATH, 'EditorPlugins').resolve() @@ -131,15 +131,15 @@ def init_ly_pyside(LY_DEV=None): # add Qt binaries to the Windows path to handle findings DLL file dependencies if sys.platform.startswith('win'): - path = os.environ['PATH'] - newPath = '' - newPath += str(LY_BIN_PATH) + os.pathsep - newPath += str(Path.joinpath(QTFORPYTHON_PATH, - 'shiboken2').resolve()) + os.pathsep - newPath += str(Path.joinpath(QTFORPYTHON_PATH, - 'PySide2').resolve()) + os.pathsep - newPath += path - os.environ['PATH']=newPath + # path = os.environ['PATH'] + # newPath = '' + # newPath += str(LY_BIN_PATH) + os.pathsep + # newPath += str(Path.joinpath(QTFORPYTHON_PATH, + # 'shiboken2').resolve()) + os.pathsep + # newPath += str(Path.joinpath(QTFORPYTHON_PATH, + # 'PySide2').resolve()) + os.pathsep + # newPath += path + # os.environ['PATH']=newPath _LOGGER.debug('PySide2 bootstrapped PATH for Windows.') try: @@ -319,7 +319,7 @@ if __name__ == '__main__': settings.setenv() # doing this will add/set the additional DYNACONF_ envars - _LOGGER.info('QTFORPYTHON_PATH: {}'.format(settings.QTFORPYTHON_PATH)) + #_LOGGER.info('QTFORPYTHON_PATH: {}'.format(settings.QTFORPYTHON_PATH)) _LOGGER.info('LY_BIN_PATH: {}'.format(settings.LY_BIN_PATH)) _LOGGER.info('QT_PLUGIN_PATH: {}'.format(settings.QT_PLUGIN_PATH)) _LOGGER.info('QT_QPA_PLATFORM_PLUGIN_PATH: {}'.format(settings.QT_QPA_PLATFORM_PLUGIN_PATH)) diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/gem.json b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/gem.json new file mode 100644 index 0000000000..ca80c62dd0 --- /dev/null +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/gem.json @@ -0,0 +1,17 @@ +{ + "gem_name": "Atom_DccScriptingInterface", + "GemFormatVersion": 4, + "Uuid": "7bf5a77dacd8438bb4966a66b5a678d8", + "Name": "Atom_DccScriptingInterface", + "DisplayName": "Atom DccScriptingInterface (DCCsi)", + "Version": "0.1.0", + "Summary": "A python framework for working with various DCC tools and workflows.", + "Tags": ["DCC","Digital","Content","Creation"], + "IconPath": "preview.png", + "Modules": [ + { + "Name": "Editor", + "Type": "EditorModule" + } + ] +} From 607dbc47b3915a6ab504dd01f5f1c70fea97bce5 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 26 May 2021 10:40:47 -0500 Subject: [PATCH 151/811] Surrouding the setting of the BASE_PATH within double quotes in the o3de.bat script. This allows to allow paths with spaces in it leading to the engine root directory to work properly when running the script --- scripts/o3de.bat | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/o3de.bat b/scripts/o3de.bat index 0a65b722d7..9031933e61 100644 --- a/scripts/o3de.bat +++ b/scripts/o3de.bat @@ -12,15 +12,15 @@ REM pushd %~dp0% CD %~dp0.. -SET BASE_PATH=%CD% +SET "BASE_PATH=%CD%" CD %~dp0 -SET PYTHON_DIRECTORY=%BASE_PATH%\python +SET "PYTHON_DIRECTORY=%BASE_PATH%\python" IF EXIST "%PYTHON_DIRECTORY%" GOTO pythonPathAvailable GOTO pythonDirNotFound :pythonPathAvailable SET PYTHON_EXECUTABLE=%PYTHON_DIRECTORY%\python.cmd IF NOT EXIST "%PYTHON_EXECUTABLE%" GOTO pythonExeNotFound -CALL "%PYTHON_EXECUTABLE%" %BASE_PATH%\scripts\o3de.py %* +CALL "%PYTHON_EXECUTABLE%" "%BASE_PATH%\scripts\o3de.py" %* GOTO end :pythonDirNotFound ECHO Python directory not found: %PYTHON_DIRECTORY% From c3e605e6c2d4354d42dc586ea41171f95f019430 Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 26 May 2021 09:12:08 -0700 Subject: [PATCH 152/811] Fixing call to ly_de_alias_target --- cmake/SettingsRegistry.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index e819b5c28e..07ed89c218 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -147,7 +147,7 @@ function(ly_delayed_generate_settings_registry) # de-namespace them foreach(gem_target ${all_gem_dependencies}) - ly_de_alias_target(TARGET ${gem_target} OUTPUT_VARIABLE stripped_gem_target) + ly_de_alias_target(${gem_target} stripped_gem_target) list(APPEND new_gem_dependencies ${stripped_gem_target}) endforeach() set(all_gem_dependencies ${new_gem_dependencies}) @@ -173,7 +173,7 @@ function(ly_delayed_generate_settings_registry) file(RELATIVE_PATH gem_module_root_relative_to_engine_root ${LY_ROOT_FOLDER} ${gem_module_root}) # De-alias namespace from gem targets before configuring them into the json template - ly_de_alias_target(TARGET ${gem_target} OUTPUT_VARIABLE stripped_gem_target) + ly_de_alias_target(${gem_target} stripped_gem_target) string(CONFIGURE ${gem_module_template} gem_module_json @ONLY) list(APPEND target_gem_dependencies_names ${gem_module_json}) endforeach() From 90d9e5d6d8d0db6716b435c31fd8245908053f94 Mon Sep 17 00:00:00 2001 From: gallowj Date: Wed, 26 May 2021 11:30:46 -0500 Subject: [PATCH 153/811] removing the qdarkstyle package we don't own --- .../ui/resources/qdarkstyle/rc/arrow_down.png | 3 - .../qdarkstyle/rc/arrow_down_disabled.png | 3 - .../qdarkstyle/rc/arrow_down_focus.png | 3 - .../qdarkstyle/rc/arrow_down_pressed.png | 3 - .../ui/resources/qdarkstyle/rc/arrow_left.png | 3 - .../qdarkstyle/rc/arrow_left_disabled.png | 3 - .../qdarkstyle/rc/arrow_left_focus.png | 3 - .../qdarkstyle/rc/arrow_left_pressed.png | 3 - .../resources/qdarkstyle/rc/arrow_right.png | 3 - .../qdarkstyle/rc/arrow_right_disabled.png | 3 - .../qdarkstyle/rc/arrow_right_focus.png | 3 - .../qdarkstyle/rc/arrow_right_pressed.png | 3 - .../ui/resources/qdarkstyle/rc/arrow_up.png | 3 - .../qdarkstyle/rc/arrow_up_disabled.png | 3 - .../qdarkstyle/rc/arrow_up_focus.png | 3 - .../qdarkstyle/rc/arrow_up_pressed.png | 3 - .../ui/resources/qdarkstyle/rc/base_icon.png | 3 - .../qdarkstyle/rc/base_icon_disabled.png | 3 - .../qdarkstyle/rc/base_icon_focus.png | 3 - .../qdarkstyle/rc/base_icon_pressed.png | 3 - .../resources/qdarkstyle/rc/branch_closed.png | 3 - .../qdarkstyle/rc/branch_closed_disabled.png | 3 - .../qdarkstyle/rc/branch_closed_focus.png | 3 - .../qdarkstyle/rc/branch_closed_pressed.png | 3 - .../ui/resources/qdarkstyle/rc/branch_end.png | 3 - .../qdarkstyle/rc/branch_end_disabled.png | 3 - .../qdarkstyle/rc/branch_end_focus.png | 3 - .../qdarkstyle/rc/branch_end_pressed.png | 3 - .../resources/qdarkstyle/rc/branch_line.png | 3 - .../qdarkstyle/rc/branch_line_disabled.png | 3 - .../qdarkstyle/rc/branch_line_focus.png | 3 - .../qdarkstyle/rc/branch_line_pressed.png | 3 - .../resources/qdarkstyle/rc/branch_more.png | 3 - .../qdarkstyle/rc/branch_more_disabled.png | 3 - .../qdarkstyle/rc/branch_more_focus.png | 3 - .../qdarkstyle/rc/branch_more_pressed.png | 3 - .../resources/qdarkstyle/rc/branch_open.png | 3 - .../qdarkstyle/rc/branch_open_disabled.png | 3 - .../qdarkstyle/rc/branch_open_focus.png | 3 - .../qdarkstyle/rc/branch_open_pressed.png | 3 - .../qdarkstyle/rc/checkbox_checked.png | 3 - .../rc/checkbox_checked_disabled.png | 3 - .../qdarkstyle/rc/checkbox_checked_focus.png | 3 - .../rc/checkbox_checked_pressed.png | 3 - .../qdarkstyle/rc/checkbox_indeterminate.png | 3 - .../rc/checkbox_indeterminate_disabled.png | 3 - .../rc/checkbox_indeterminate_focus.png | 3 - .../rc/checkbox_indeterminate_pressed.png | 3 - .../qdarkstyle/rc/checkbox_unchecked.png | 3 - .../rc/checkbox_unchecked_disabled.png | 3 - .../rc/checkbox_unchecked_focus.png | 3 - .../rc/checkbox_unchecked_pressed.png | 3 - .../qdarkstyle/rc/line_horizontal.png | 3 - .../rc/line_horizontal_disabled.png | 3 - .../qdarkstyle/rc/line_horizontal_focus.png | 3 - .../qdarkstyle/rc/line_horizontal_pressed.png | 3 - .../resources/qdarkstyle/rc/line_vertical.png | 3 - .../qdarkstyle/rc/line_vertical_disabled.png | 3 - .../qdarkstyle/rc/line_vertical_focus.png | 3 - .../qdarkstyle/rc/line_vertical_pressed.png | 3 - .../resources/qdarkstyle/rc/radio_checked.png | 3 - .../qdarkstyle/rc/radio_checked_disabled.png | 3 - .../qdarkstyle/rc/radio_checked_focus.png | 3 - .../qdarkstyle/rc/radio_checked_pressed.png | 3 - .../qdarkstyle/rc/radio_unchecked.png | 3 - .../rc/radio_unchecked_disabled.png | 3 - .../qdarkstyle/rc/radio_unchecked_focus.png | 3 - .../qdarkstyle/rc/radio_unchecked_pressed.png | 3 - .../qdarkstyle/rc/toolbar_move_horizontal.png | 3 - .../rc/toolbar_move_horizontal_disabled.png | 3 - .../rc/toolbar_move_horizontal_focus.png | 3 - .../rc/toolbar_move_horizontal_pressed.png | 3 - .../qdarkstyle/rc/toolbar_move_vertical.png | 3 - .../rc/toolbar_move_vertical_disabled.png | 3 - .../rc/toolbar_move_vertical_focus.png | 3 - .../rc/toolbar_move_vertical_pressed.png | 3 - .../rc/toolbar_separator_horizontal.png | 3 - .../toolbar_separator_horizontal_disabled.png | 3 - .../rc/toolbar_separator_horizontal_focus.png | 3 - .../toolbar_separator_horizontal_pressed.png | 3 - .../rc/toolbar_separator_vertical.png | 3 - .../toolbar_separator_vertical_disabled.png | 3 - .../rc/toolbar_separator_vertical_focus.png | 3 - .../rc/toolbar_separator_vertical_pressed.png | 3 - .../resources/qdarkstyle/rc/transparent.png | 3 - .../qdarkstyle/rc/transparent_disabled.png | 3 - .../qdarkstyle/rc/transparent_focus.png | 3 - .../qdarkstyle/rc/transparent_pressed.png | 3 - .../resources/qdarkstyle/rc/window_close.png | 3 - .../qdarkstyle/rc/window_close_disabled.png | 3 - .../qdarkstyle/rc/window_close_focus.png | 3 - .../qdarkstyle/rc/window_close_pressed.png | 3 - .../resources/qdarkstyle/rc/window_grip.png | 3 - .../qdarkstyle/rc/window_grip_disabled.png | 3 - .../qdarkstyle/rc/window_grip_focus.png | 3 - .../qdarkstyle/rc/window_grip_pressed.png | 3 - .../qdarkstyle/rc/window_minimize.png | 3 - .../rc/window_minimize_disabled.png | 3 - .../qdarkstyle/rc/window_minimize_focus.png | 3 - .../qdarkstyle/rc/window_minimize_pressed.png | 3 - .../resources/qdarkstyle/rc/window_undock.png | 3 - .../qdarkstyle/rc/window_undock_disabled.png | 3 - .../qdarkstyle/rc/window_undock_focus.png | 3 - .../qdarkstyle/rc/window_undock_pressed.png | 3 - .../shared/ui/resources/qdarkstyle/readme.txt | 5 - .../shared/ui/resources/qdarkstyle/style.qrc | 216 -- .../shared/ui/resources/qdarkstyle/style.qss | 2165 ----------------- 107 files changed, 2698 deletions(-) delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_disabled.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_focus.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_pressed.png delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/readme.txt delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/style.qrc delete mode 100644 Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/style.qss diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down.png deleted file mode 100644 index fa98bc39a3..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:afe9402162c5b4527f12c863d389ee9d75b53a1069b7e177497beba389d91d35 -size 525 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_disabled.png deleted file mode 100644 index eaedad9b31..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dc1e37e22cb75f616d6ada02cce006bae7fb1da515b15afea0fc98fcc542a092 -size 547 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_focus.png deleted file mode 100644 index 170beb53b4..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c7c9c4c8c5bdc755cc026aa23044f546010c0d1e079ecba34ceb8f0eb9e44bde -size 530 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_pressed.png deleted file mode 100644 index 32b2aac93a..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_down_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6111d15f1dc946742b00317bda789a5c625333f65a362f38931dabc50afb2067 -size 518 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left.png deleted file mode 100644 index e84d285f63..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8ac79e7fbd6be51465e0b685dca32c1236f95ad76ab8c5877ec73d20a1de4365 -size 546 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_disabled.png deleted file mode 100644 index d21aea9e87..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a86de88cf4ee32c352776caf46d5512d27679da8b571ea7e791287495fad4514 -size 569 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_focus.png deleted file mode 100644 index 6315e4d488..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5c5b8427bd1497006b8adbcbc445f11b07ec388a3398fe2997f65bdc56f2644f -size 565 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_pressed.png deleted file mode 100644 index c01c95df2b..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_left_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:95ad920de52fd198f1af6d569917be20dc24a39dabdbe6c555c812d424bd9736 -size 541 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right.png deleted file mode 100644 index 7dc1534e3c..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:cb5b2d9b40652764f074dcea9856d6748b0efeac57ef58f306efa999f4b411c1 -size 518 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_disabled.png deleted file mode 100644 index 0bdb8963f1..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6a38dcd5b4078df430fa05780844af3e88e0a8e01c1fa910482e4c217354d728 -size 553 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_focus.png deleted file mode 100644 index 9659eeed4d..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5f60b2dfce514a6f558134b942f255ddf81ca3dc77b0d899a87f6d4cbac38e26 -size 543 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_pressed.png deleted file mode 100644 index 8e8ae64a87..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_right_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:84379a7bd6ffa75692648c6fce328616e8a009d7ea3a83c2288f82ecce37e729 -size 544 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up.png deleted file mode 100644 index 5137aa3c5f..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d7ee7bfb0c60d4687c8a0dcc38a12ee7cacaa2cbb9eb0ae24faa82b992ade445 -size 512 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_disabled.png deleted file mode 100644 index 7c866337ea..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:571b1afb9c2d7e01f56b75e1526dd0a3ffd49a60a4bcb7981ba34823b44a74c0 -size 538 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_focus.png deleted file mode 100644 index a3eaa49ef3..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:45d805ec94b8144bf121ba74ee96dd27f2f8c0890b2eca5e78df39cb5266f94d -size 530 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_pressed.png deleted file mode 100644 index 168493204d..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/arrow_up_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d49428a947ea424fabedd5a08e1d78e0bc57dc8a2d5a231b5d9ec06977870f5a -size 518 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon.png deleted file mode 100644 index 0af10b0138..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d33b23ed0d8450413a2582d8f00bcb808d39f7e09ff394cee1669a4b7e79207e -size 1256 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_disabled.png deleted file mode 100644 index 0af10b0138..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d33b23ed0d8450413a2582d8f00bcb808d39f7e09ff394cee1669a4b7e79207e -size 1256 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_focus.png deleted file mode 100644 index 0af10b0138..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d33b23ed0d8450413a2582d8f00bcb808d39f7e09ff394cee1669a4b7e79207e -size 1256 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_pressed.png deleted file mode 100644 index 0af10b0138..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/base_icon_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d33b23ed0d8450413a2582d8f00bcb808d39f7e09ff394cee1669a4b7e79207e -size 1256 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed.png deleted file mode 100644 index b964f8985a..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:56776b4655640d46eb1031b9c19c2341fdfe1201c774a84bc5c2801fbcfefc37 -size 350 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_disabled.png deleted file mode 100644 index ad619682e6..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d48862b1c68efdf376551d1c35d5d3a68e2ce9809e7c2723f42ece7c77fca009 -size 373 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_focus.png deleted file mode 100644 index 8ea7431745..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:62cc47f4b7751e22ffe4b26289ecc632b4a2c4e5c33ac79864fcfb32398b1139 -size 380 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_pressed.png deleted file mode 100644 index 54a60293b0..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_closed_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ad6e74b57c8876fa28c3a43d1a38369415790507d65d758ea3e77b796c401da2 -size 372 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end.png deleted file mode 100644 index 0fc0630627..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:63324c154ead46027729bcf307ba45fbeb5a8de3ec5e8cef55d315a84a087115 -size 142 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_disabled.png deleted file mode 100644 index 68a6b95488..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8a8b091785c84d37de57aacb7fe5a9b854933cc94b9b6f1f6e0b155879c7d6d0 -size 146 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_focus.png deleted file mode 100644 index 84307b3375..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4f89a6b105df07325dcf7bdcea2165bb065dd99b648aa12ae4e0c6693e04d0a2 -size 146 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_pressed.png deleted file mode 100644 index 3f63a24d56..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_end_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:76f44758619badecf11b3b0d9914612e584ad750a695c942811fe215457b25be -size 146 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line.png deleted file mode 100644 index 7aebe0ec54..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:50a35383d40b4e8a646931e4057cd25045f05a48208e2cb9d9935be76b53bf94 -size 130 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_disabled.png deleted file mode 100644 index f1b83a5734..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ba7550922e9d244620f8f9ad76fe546d542764eba02378f81b188dec5fd7438a -size 134 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_focus.png deleted file mode 100644 index 5daf190e47..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:52bec8528e3c8edd583136d90a37f46bcb45e0d406fc0fb680a8b4d75cfeb731 -size 134 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_pressed.png deleted file mode 100644 index d533bb82b9..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_line_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1b8d2c9a8593a52221c91d2a8c2d3cbd837e408a5f6d1dcad6f79328a13a3bcf -size 134 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more.png deleted file mode 100644 index d0eb02b7fb..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5087f4f06a9718230e1aec2ba681f3432ecd2640a135b4e90c7b009188ec4c29 -size 155 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_disabled.png deleted file mode 100644 index a457e2822c..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dec80a2e8439a0787e10aee70a365e30b5d1f43c29e4c33989cc6cd2f5cac478 -size 162 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_focus.png deleted file mode 100644 index 09b9726550..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:39930fd3e240c9ad94d748d6cda73b2943682fc4825edd1240e882be18c06198 -size 162 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_pressed.png deleted file mode 100644 index 31a17b26f0..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_more_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0d07da719927b26db1c3087bbfe7203510fce077efe9e121935b3aefbb49b95d -size 162 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open.png deleted file mode 100644 index f0f49a375a..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:05a1980b268f598ebb3520067679a8beb4fa3f00da9c87dd93be2642718ceb44 -size 354 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_disabled.png deleted file mode 100644 index d46e6138bc..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:047c00f910dd279e871a6329ea533816d8b458063539b8efbe9949d7363996bf -size 375 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_focus.png deleted file mode 100644 index d6c73e877c..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6bc79f30e3fdc52ec30eb0e9c6b03d1538f7c8c7855033d24d5f993e8ceb9cc1 -size 367 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_pressed.png deleted file mode 100644 index ba1bb5e27b..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/branch_open_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:aa65cf58b8a02bf5f4142ad80de05aba868245c55a790af6ba0230bfd01a2a06 -size 369 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked.png deleted file mode 100644 index d82af2b4ed..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:95c1c1651a13f0562383087549a35a97bbb7899c7d3717d79d4624485b72bf9f -size 452 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_disabled.png deleted file mode 100644 index e96b6ab274..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:80a1d02e6ac7e5d0439b2a077ab8cf82739853ce46ac1556d4035e3bba713242 -size 467 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_focus.png deleted file mode 100644 index abe4bad569..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:64d5ed4d01a9778912b98c9147eb67431560acb5805d1d0832a765c441b9ed9b -size 441 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_pressed.png deleted file mode 100644 index 1bab094a68..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_checked_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f0ffa46106a643a71835056acce66ebe09745a9e6d91fac30ff1caf0589a6677 -size 418 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate.png deleted file mode 100644 index 51d0835feb..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8b291eb9180c0e27d1de6ff008ff4259b2c675a65efa94866a66c7c932fc1260 -size 581 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_disabled.png deleted file mode 100644 index 9e13859a93..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8c7d3d64e8cb5e2f8bc6620b0d58492a56800fc78fc0229a5fa495d3a43987a1 -size 614 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_focus.png deleted file mode 100644 index aea72c9cde..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:43d494685f5d2ed740b69f04fefe0e757626db94685ecc8f4411c6c68a626a5a -size 576 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_pressed.png deleted file mode 100644 index d2c86adef3..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_indeterminate_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7af182d82449663ac37955e45ccc3f8fc86d185649fa9bed24c10167351bd5ee -size 563 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked.png deleted file mode 100644 index bf34be7606..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:232451d0bd9cf1d54c777862030b667cd5078f2f4ff387ec03c44d56eb207c03 -size 397 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_disabled.png deleted file mode 100644 index 596e553c14..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7b54771eaad56ee45f8871248ee1c6b18035aa732f9e4e9257d008a73be04c25 -size 386 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_focus.png deleted file mode 100644 index 96cf982f58..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ae293d387fda8a89d68fc3f15db07ef084e3537a033d02351ff918cfcc82ea8a -size 394 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_pressed.png deleted file mode 100644 index 0984a1fd5d..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/checkbox_unchecked_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f8ccf5cb638a090f0e64f6d336e4c6312cfaf53971afd0f00cd16d0c0759f1b4 -size 403 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal.png deleted file mode 100644 index 4d069c17b1..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:256f010c3084112888189bcbea2995a37f8acbf12d61a4a261a94aca797cd964 -size 117 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_disabled.png deleted file mode 100644 index 06465a0a29..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:85522a94ec26125f65dcafc6158665f40ea570e4a08cbdfbbdf5f6772b887eb7 -size 121 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_focus.png deleted file mode 100644 index 5f1332e6dd..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ae4766527d9e5a2226107ede231878118538e8be89f2dc2ac92b7c5a68ad0fc6 -size 120 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_pressed.png deleted file mode 100644 index f0f11abeb0..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_horizontal_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5f4bdbb4d207aa40366ad90d363a95d80e2b4a43574ca1ad3256ee6e0617f25e -size 120 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical.png deleted file mode 100644 index 7aebe0ec54..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:50a35383d40b4e8a646931e4057cd25045f05a48208e2cb9d9935be76b53bf94 -size 130 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_disabled.png deleted file mode 100644 index f1b83a5734..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ba7550922e9d244620f8f9ad76fe546d542764eba02378f81b188dec5fd7438a -size 134 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_focus.png deleted file mode 100644 index 5daf190e47..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:52bec8528e3c8edd583136d90a37f46bcb45e0d406fc0fb680a8b4d75cfeb731 -size 134 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_pressed.png deleted file mode 100644 index d533bb82b9..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/line_vertical_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1b8d2c9a8593a52221c91d2a8c2d3cbd837e408a5f6d1dcad6f79328a13a3bcf -size 134 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked.png deleted file mode 100644 index 99c9969237..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:abee85006ecef454df64f65a6aa7dbb85bff9c51f53ed87b47e9f4ef1adefec3 -size 1224 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_disabled.png deleted file mode 100644 index 13daed68f4..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7e22fc4d6bf116cebab4655b6bf81b1c384789b45a96f05d8a4b535e34978cb9 -size 1325 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_focus.png deleted file mode 100644 index e42389445a..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3db59af5ba4caa97ac07834e1a919adafdcd610324dacac68cbd2cde551c2397 -size 1293 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_pressed.png deleted file mode 100644 index 4153bb2ed5..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_checked_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:34bce34b70cf7c24d1e54f87f4225f0c4cf8e7dd8c6fd8a38f81e981bae2a2ce -size 1276 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked.png deleted file mode 100644 index 748ab5998b..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f675766febe18edf774b0dd7db11177ca76793c0d2b693b1ffb6a447b79369d2 -size 963 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_disabled.png deleted file mode 100644 index 34230cbb40..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6d5af9296f23e58fc7fde5c9b278a801bd51bb3650d0e5f84dd9eb84434308cc -size 1040 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_focus.png deleted file mode 100644 index 3428ad46be..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c0b650dda797331b8c23ece7e313babb8e6e9118bd3d53e689a7381a33cb5e00 -size 1032 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_pressed.png deleted file mode 100644 index b60ab09f6c..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/radio_unchecked_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2dd40885e1d7b1d3f37cfc3afff07fe47db552602bdc46aa9a8ce7a0c8df30db -size 1022 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal.png deleted file mode 100644 index ad5243fcb8..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:054d47979c0879378a6f5e36d9e5b251c31e15610adeed109b8f128115d4b5ec -size 150 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_disabled.png deleted file mode 100644 index 94ef75054c..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9eca88a1ebba5d42107da4c3b3af3b52a8de1c76bc1bae8d27190ff5e69f8198 -size 155 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_focus.png deleted file mode 100644 index c4fe22a169..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e11a73fcc79cebd854cbdf3c6539eca99b016440c590b5326f90fa9790e9a69d -size 154 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_pressed.png deleted file mode 100644 index e6d3f5a2c6..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_horizontal_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7371a89813b6f4843dc90b4abe866de943ba670057e0802dcc7f0284d9aa079b -size 154 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical.png deleted file mode 100644 index 6f47c7e52c..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8e4d88b8da4d94d4ecaa0eda448d18adcad14c5a62d4e6c9d0ffb2673683d855 -size 137 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_disabled.png deleted file mode 100644 index 43b5911860..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e7422317ab56297babc9025f42dd1f7179588ac4e066cb1b976b1bb56efca656 -size 140 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_focus.png deleted file mode 100644 index 0b918dcdc9..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b9a1520ad62a2b20f53c0709d643af3e8e0d775891597c4bc05e46ed75617bd9 -size 144 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_pressed.png deleted file mode 100644 index 7b104f52b0..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_move_vertical_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:73b0e2dddb1c22848b9b858975cdaae02f0b7b47696922a863358afa30f81dfa -size 143 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal.png deleted file mode 100644 index e7174cd081..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e2986d7bca86f3359817f002ecf125afab71281561925a6ecbffe844a2be9699 -size 145 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_disabled.png deleted file mode 100644 index b45f02655c..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4f7909f6aa1843cb2382ea0e49afb10967a331e128cc8103ab8082c3e46a90aa -size 151 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_focus.png deleted file mode 100644 index e2898bd5bf..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b4c628767e58d08e929a4bfc3f730e1347b186a44a1b0d4159fa722776a660ea -size 149 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_pressed.png deleted file mode 100644 index 3a71bdc89e..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_horizontal_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c2bcf16dee85252fbf33d3eb05009b988f4c7b3795c01d66e471712d76def3ab -size 149 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical.png deleted file mode 100644 index 02c38086c4..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5db0c6a32f562204a4dc77c8958ef29e016af621f11891ca1795da808a879288 -size 133 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_disabled.png deleted file mode 100644 index f9b739bb93..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c705854e5a7aae10edb4d0cd28d1217a0b6599845031053d502aa05030ce5134 -size 135 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_focus.png deleted file mode 100644 index 08661141b3..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:39bd3c687b5bc56d6a62728d3dbfa522f3e1e74ec4de752987768f60c947adf5 -size 139 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_pressed.png deleted file mode 100644 index 5baf760e59..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/toolbar_separator_vertical_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0966303eb702647e3463ffa644611d817741b1ee0d016ecd56c600e9f04ac114 -size 138 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent.png deleted file mode 100644 index 02ade9b47b..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:17cedbceacd7ae3a97319a3db9606b40d8ef31428828b08bdbfe73f5642b4ae5 -size 104 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_disabled.png deleted file mode 100644 index 02ade9b47b..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:17cedbceacd7ae3a97319a3db9606b40d8ef31428828b08bdbfe73f5642b4ae5 -size 104 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_focus.png deleted file mode 100644 index 02ade9b47b..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:17cedbceacd7ae3a97319a3db9606b40d8ef31428828b08bdbfe73f5642b4ae5 -size 104 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_pressed.png deleted file mode 100644 index 02ade9b47b..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/transparent_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:17cedbceacd7ae3a97319a3db9606b40d8ef31428828b08bdbfe73f5642b4ae5 -size 104 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close.png deleted file mode 100644 index dd99b7b8ed..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f7b31e2fb43e9c3dbd9f0e32680422a7d8c8e7ff7cd600e446103e45b0df0523 -size 766 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_disabled.png deleted file mode 100644 index 1f506f9543..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:528a22b6955681f34373fc72a2dfdd19e6255e18c73f0804c09b34ea01c1f0a0 -size 838 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_focus.png deleted file mode 100644 index 244b91f5b8..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bbc009bf89ac37957e2ff6532a9328f71e63f5edb45bd918048c8a69f61a72e2 -size 756 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_pressed.png deleted file mode 100644 index 4a45bda1b2..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_close_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:cd117b3874dec17ebf78f136784eca821f4d916fe34081187c8c28bc2223f545 -size 745 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip.png deleted file mode 100644 index 0f176f5949..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2c2ebc9c32505a0489879f7429034143af2ed48e71d2b2eba449a45c7253a2b7 -size 426 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_disabled.png deleted file mode 100644 index f07d5f0de8..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0e7ffdf7643cd2078127953690098b8ea8899428f7906efa778d70422d254f1e -size 447 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_focus.png deleted file mode 100644 index d7271e6e0a..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:055a219ffe9015ed50585caa1cedd31cb99c034c41c17f3ff97cc3c9a1b9b68c -size 435 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_pressed.png deleted file mode 100644 index 000da02699..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_grip_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:776e4b8d509743bb682783085bd139ad8e419a1bbc02a93480b1a4aaffd89041 -size 444 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize.png deleted file mode 100644 index 1846176c40..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8ddd70f8069320fb09ee8800cecaa190076baaa4b1c251900220541cc83434bd -size 193 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_disabled.png deleted file mode 100644 index d9df85b122..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4bc0af0fc3119eb066333d3c3e4fbdcc65e23bfdb43b5c5dfd65aae7b6916b3b -size 206 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_focus.png deleted file mode 100644 index 30a7f49ed0..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7575b3458ef002ebfe1fece1427dd3170326d35144b0d03f215d091f625f7286 -size 208 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_pressed.png deleted file mode 100644 index 9cd26589f5..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_minimize_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e3dd9475a6db26f45e85d5a688a5e724b7278af4d472caf4b16c1fde346f95db -size 202 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock.png deleted file mode 100644 index 8126d26228..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b07a032c3109f93770c149c4b3199c17cc446e58e50b0d86c4254268a3dc00b0 -size 510 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_disabled.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_disabled.png deleted file mode 100644 index 573cd467ed..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0c97ecbc47699b4ec1189831ae2b8f08eed95e96def84ea48ac63597ecd3d40a -size 541 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_focus.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_focus.png deleted file mode 100644 index 5044d402af..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_focus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0ed098cc564cc6c45cdf43103f06a670089149cbc4e81a733becd49d6d115d44 -size 519 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_pressed.png b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_pressed.png deleted file mode 100644 index be8c5637dd..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/rc/window_undock_pressed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ef37bb94ebabd4d37ed1c8fcd5a095a5d10e2a20a667861d13c772b903c32bb1 -size 523 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/readme.txt b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/readme.txt deleted file mode 100644 index e100551564..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/readme.txt +++ /dev/null @@ -1,5 +0,0 @@ -LICENSE -https://github.com/ColinDuquesnoy/QDarkStyleSheet/blob/master/LICENSE.rst - -DEPOT -https://github.com/ColinDuquesnoy/QDarkStyleSheet diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/style.qrc b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/style.qrc deleted file mode 100644 index e301854e2c..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/style.qrc +++ /dev/null @@ -1,216 +0,0 @@ - - - - rc/arrow_down.png - rc/arrow_down@2x.png - rc/arrow_down_disabled.png - rc/arrow_down_disabled@2x.png - rc/arrow_down_focus.png - rc/arrow_down_focus@2x.png - rc/arrow_down_pressed.png - rc/arrow_down_pressed@2x.png - rc/arrow_left.png - rc/arrow_left@2x.png - rc/arrow_left_disabled.png - rc/arrow_left_disabled@2x.png - rc/arrow_left_focus.png - rc/arrow_left_focus@2x.png - rc/arrow_left_pressed.png - rc/arrow_left_pressed@2x.png - rc/arrow_right.png - rc/arrow_right@2x.png - rc/arrow_right_disabled.png - rc/arrow_right_disabled@2x.png - rc/arrow_right_focus.png - rc/arrow_right_focus@2x.png - rc/arrow_right_pressed.png - rc/arrow_right_pressed@2x.png - rc/arrow_up.png - rc/arrow_up@2x.png - rc/arrow_up_disabled.png - rc/arrow_up_disabled@2x.png - rc/arrow_up_focus.png - rc/arrow_up_focus@2x.png - rc/arrow_up_pressed.png - rc/arrow_up_pressed@2x.png - rc/base_icon.png - rc/base_icon@2x.png - rc/base_icon_disabled.png - rc/base_icon_disabled@2x.png - rc/base_icon_focus.png - rc/base_icon_focus@2x.png - rc/base_icon_pressed.png - rc/base_icon_pressed@2x.png - rc/branch_closed.png - rc/branch_closed@2x.png - rc/branch_closed_disabled.png - rc/branch_closed_disabled@2x.png - rc/branch_closed_focus.png - rc/branch_closed_focus@2x.png - rc/branch_closed_pressed.png - rc/branch_closed_pressed@2x.png - rc/branch_end.png - rc/branch_end@2x.png - rc/branch_end_disabled.png - rc/branch_end_disabled@2x.png - rc/branch_end_focus.png - rc/branch_end_focus@2x.png - rc/branch_end_pressed.png - rc/branch_end_pressed@2x.png - rc/branch_line.png - rc/branch_line@2x.png - rc/branch_line_disabled.png - rc/branch_line_disabled@2x.png - rc/branch_line_focus.png - rc/branch_line_focus@2x.png - rc/branch_line_pressed.png - rc/branch_line_pressed@2x.png - rc/branch_more.png - rc/branch_more@2x.png - rc/branch_more_disabled.png - rc/branch_more_disabled@2x.png - rc/branch_more_focus.png - rc/branch_more_focus@2x.png - rc/branch_more_pressed.png - rc/branch_more_pressed@2x.png - rc/branch_open.png - rc/branch_open@2x.png - rc/branch_open_disabled.png - rc/branch_open_disabled@2x.png - rc/branch_open_focus.png - rc/branch_open_focus@2x.png - rc/branch_open_pressed.png - rc/branch_open_pressed@2x.png - rc/checkbox_checked.png - rc/checkbox_checked@2x.png - rc/checkbox_checked_disabled.png - rc/checkbox_checked_disabled@2x.png - rc/checkbox_checked_focus.png - rc/checkbox_checked_focus@2x.png - rc/checkbox_checked_pressed.png - rc/checkbox_checked_pressed@2x.png - rc/checkbox_indeterminate.png - rc/checkbox_indeterminate@2x.png - rc/checkbox_indeterminate_disabled.png - rc/checkbox_indeterminate_disabled@2x.png - rc/checkbox_indeterminate_focus.png - rc/checkbox_indeterminate_focus@2x.png - rc/checkbox_indeterminate_pressed.png - rc/checkbox_indeterminate_pressed@2x.png - rc/checkbox_unchecked.png - rc/checkbox_unchecked@2x.png - rc/checkbox_unchecked_disabled.png - rc/checkbox_unchecked_disabled@2x.png - rc/checkbox_unchecked_focus.png - rc/checkbox_unchecked_focus@2x.png - rc/checkbox_unchecked_pressed.png - rc/checkbox_unchecked_pressed@2x.png - rc/line_horizontal.png - rc/line_horizontal@2x.png - rc/line_horizontal_disabled.png - rc/line_horizontal_disabled@2x.png - rc/line_horizontal_focus.png - rc/line_horizontal_focus@2x.png - rc/line_horizontal_pressed.png - rc/line_horizontal_pressed@2x.png - rc/line_vertical.png - rc/line_vertical@2x.png - rc/line_vertical_disabled.png - rc/line_vertical_disabled@2x.png - rc/line_vertical_focus.png - rc/line_vertical_focus@2x.png - rc/line_vertical_pressed.png - rc/line_vertical_pressed@2x.png - rc/radio_checked.png - rc/radio_checked@2x.png - rc/radio_checked_disabled.png - rc/radio_checked_disabled@2x.png - rc/radio_checked_focus.png - rc/radio_checked_focus@2x.png - rc/radio_checked_pressed.png - rc/radio_checked_pressed@2x.png - rc/radio_unchecked.png - rc/radio_unchecked@2x.png - rc/radio_unchecked_disabled.png - rc/radio_unchecked_disabled@2x.png - rc/radio_unchecked_focus.png - rc/radio_unchecked_focus@2x.png - rc/radio_unchecked_pressed.png - rc/radio_unchecked_pressed@2x.png - rc/toolbar_move_horizontal.png - rc/toolbar_move_horizontal@2x.png - rc/toolbar_move_horizontal_disabled.png - rc/toolbar_move_horizontal_disabled@2x.png - rc/toolbar_move_horizontal_focus.png - rc/toolbar_move_horizontal_focus@2x.png - rc/toolbar_move_horizontal_pressed.png - rc/toolbar_move_horizontal_pressed@2x.png - rc/toolbar_move_vertical.png - rc/toolbar_move_vertical@2x.png - rc/toolbar_move_vertical_disabled.png - rc/toolbar_move_vertical_disabled@2x.png - rc/toolbar_move_vertical_focus.png - rc/toolbar_move_vertical_focus@2x.png - rc/toolbar_move_vertical_pressed.png - rc/toolbar_move_vertical_pressed@2x.png - rc/toolbar_separator_horizontal.png - rc/toolbar_separator_horizontal@2x.png - rc/toolbar_separator_horizontal_disabled.png - rc/toolbar_separator_horizontal_disabled@2x.png - rc/toolbar_separator_horizontal_focus.png - rc/toolbar_separator_horizontal_focus@2x.png - rc/toolbar_separator_horizontal_pressed.png - rc/toolbar_separator_horizontal_pressed@2x.png - rc/toolbar_separator_vertical.png - rc/toolbar_separator_vertical@2x.png - rc/toolbar_separator_vertical_disabled.png - rc/toolbar_separator_vertical_disabled@2x.png - rc/toolbar_separator_vertical_focus.png - rc/toolbar_separator_vertical_focus@2x.png - rc/toolbar_separator_vertical_pressed.png - rc/toolbar_separator_vertical_pressed@2x.png - rc/transparent.png - rc/transparent@2x.png - rc/transparent_disabled.png - rc/transparent_disabled@2x.png - rc/transparent_focus.png - rc/transparent_focus@2x.png - rc/transparent_pressed.png - rc/transparent_pressed@2x.png - rc/window_close.png - rc/window_close@2x.png - rc/window_close_disabled.png - rc/window_close_disabled@2x.png - rc/window_close_focus.png - rc/window_close_focus@2x.png - rc/window_close_pressed.png - rc/window_close_pressed@2x.png - rc/window_grip.png - rc/window_grip@2x.png - rc/window_grip_disabled.png - rc/window_grip_disabled@2x.png - rc/window_grip_focus.png - rc/window_grip_focus@2x.png - rc/window_grip_pressed.png - rc/window_grip_pressed@2x.png - rc/window_minimize.png - rc/window_minimize@2x.png - rc/window_minimize_disabled.png - rc/window_minimize_disabled@2x.png - rc/window_minimize_focus.png - rc/window_minimize_focus@2x.png - rc/window_minimize_pressed.png - rc/window_minimize_pressed@2x.png - rc/window_undock.png - rc/window_undock@2x.png - rc/window_undock_disabled.png - rc/window_undock_disabled@2x.png - rc/window_undock_focus.png - rc/window_undock_focus@2x.png - rc/window_undock_pressed.png - rc/window_undock_pressed@2x.png - - - style.qss - - diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/style.qss b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/style.qss deleted file mode 100644 index 55dfe093d9..0000000000 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/resources/qdarkstyle/style.qss +++ /dev/null @@ -1,2165 +0,0 @@ -/* --------------------------------------------------------------------------- - - Created by the qtsass compiler v0.1.1 - - The definitions are in the "qdarkstyle.qss._styles.scss" module - - WARNING! All changes made in this file will be lost! - ---------------------------------------------------------------------------- */ -/* QDarkStyleSheet ----------------------------------------------------------- - -This is the main style sheet, the palette has nine colors. - -It is based on three selecting colors, three greyish (background) colors -plus three whitish (foreground) colors. Each set of widgets of the same -type have a header like this: - - ------------------ - GroupName -------- - ------------------ - -And each widget is separated with a header like this: - - QWidgetName ------ - -This makes more easy to find and change some css field. The basic -configuration is described bellow. - - BACKGROUND ----------- - - Light (unpressed) - Normal (border, disabled, pressed, checked, toolbars, menus) - Dark (background) - - FOREGROUND ----------- - - Light (texts/labels) - Normal (not used yet) - Dark (disabled texts) - - SELECTION ------------ - - Light (selection/hover/active) - Normal (selected) - Dark (selected disabled) - -If a stranger configuration is required because of a bugfix or anything -else, keep the comment on the line above so nobody changes it, including the -issue number. - -*/ -/* - -See Qt documentation: - - - https://doc.qt.io/qt-5/stylesheet.html - - https://doc.qt.io/qt-5/stylesheet-reference.html - - https://doc.qt.io/qt-5/stylesheet-examples.html - ---------------------------------------------------------------------------- */ -/* QWidget ---------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QWidget { - background-color: #19232D; - border: 0px solid #32414B; - padding: 0px; - color: #F0F0F0; - selection-background-color: #1464A0; - selection-color: #F0F0F0; -} - -QWidget:disabled { - background-color: #19232D; - color: #787878; - selection-background-color: #14506E; - selection-color: #787878; -} - -QWidget::item:selected { - background-color: #1464A0; -} - -QWidget::item:hover { - background-color: #148CD2; - color: #32414B; -} - -/* QMainWindow ------------------------------------------------------------ - -This adjusts the splitter in the dock widget, not qsplitter -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmainwindow - ---------------------------------------------------------------------------- */ -QMainWindow::separator { - background-color: #32414B; - border: 0px solid #19232D; - spacing: 0px; - padding: 2px; -} - -QMainWindow::separator:hover { - background-color: #505F69; - border: 0px solid #148CD2; -} - -QMainWindow::separator:horizontal { - width: 5px; - margin-top: 2px; - margin-bottom: 2px; - image: url(":/qss_icons/rc/toolbar_separator_vertical.png"); -} - -QMainWindow::separator:vertical { - height: 5px; - margin-left: 2px; - margin-right: 2px; - image: url(":/qss_icons/rc/toolbar_separator_horizontal.png"); -} - -/* QToolTip --------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtooltip - ---------------------------------------------------------------------------- */ -QToolTip { - background-color: #148CD2; - border: 1px solid #19232D; - color: #19232D; - /* Remove padding, for fix combo box tooltip */ - padding: 0px; - /* Remove opacity, fix #174 - may need to use RGBA */ -} - -/* QStatusBar ------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qstatusbar - ---------------------------------------------------------------------------- */ -QStatusBar { - border: 1px solid #32414B; - /* Fixes Spyder #9120, #9121 */ - background: #32414B; - /* Fixes #205, white vertical borders separating items */ -} - -QStatusBar::item { - border: none; -} - -QStatusBar QToolTip { - background-color: #148CD2; - border: 1px solid #19232D; - color: #19232D; - /* Remove padding, for fix combo box tooltip */ - padding: 0px; - /* Reducing transparency to read better */ - opacity: 230; -} - -QStatusBar QLabel { - /* Fixes Spyder #9120, #9121 */ - background: transparent; -} - -/* QCheckBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcheckbox - ---------------------------------------------------------------------------- */ -QCheckBox { - background-color: #19232D; - color: #F0F0F0; - spacing: 4px; - outline: none; - padding-top: 4px; - padding-bottom: 4px; -} - -QCheckBox:focus { - border: none; -} - -QCheckBox QWidget:disabled { - background-color: #19232D; - color: #787878; -} - -QCheckBox::indicator { - margin-left: 4px; - height: 16px; - width: 16px; -} - -QCheckBox::indicator:unchecked { - image: url(":/qss_icons/rc/checkbox_unchecked.png"); -} - -QCheckBox::indicator:unchecked:hover, QCheckBox::indicator:unchecked:focus, QCheckBox::indicator:unchecked:pressed { - border: none; - image: url(":/qss_icons/rc/checkbox_unchecked_focus.png"); -} - -QCheckBox::indicator:unchecked:disabled { - image: url(":/qss_icons/rc/checkbox_unchecked_disabled.png"); -} - -QCheckBox::indicator:checked { - image: url(":/qss_icons/rc/checkbox_checked.png"); -} - -QCheckBox::indicator:checked:hover, QCheckBox::indicator:checked:focus, QCheckBox::indicator:checked:pressed { - border: none; - image: url(":/qss_icons/rc/checkbox_checked_focus.png"); -} - -QCheckBox::indicator:checked:disabled { - image: url(":/qss_icons/rc/checkbox_checked_disabled.png"); -} - -QCheckBox::indicator:indeterminate { - image: url(":/qss_icons/rc/checkbox_indeterminate.png"); -} - -QCheckBox::indicator:indeterminate:disabled { - image: url(":/qss_icons/rc/checkbox_indeterminate_disabled.png"); -} - -QCheckBox::indicator:indeterminate:focus, QCheckBox::indicator:indeterminate:hover, QCheckBox::indicator:indeterminate:pressed { - image: url(":/qss_icons/rc/checkbox_indeterminate_focus.png"); -} - -/* QGroupBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qgroupbox - ---------------------------------------------------------------------------- */ -QGroupBox { - font-weight: bold; - border: 1px solid #32414B; - border-radius: 4px; - padding: 4px; - margin-top: 16px; -} - -QGroupBox::title { - subcontrol-origin: margin; - subcontrol-position: top left; - left: 3px; - padding-left: 3px; - padding-right: 5px; - padding-top: 8px; - padding-bottom: 16px; -} - -QGroupBox::indicator { - margin-left: 2px; - height: 12px; - width: 12px; -} - -QGroupBox::indicator:unchecked:hover, QGroupBox::indicator:unchecked:focus, QGroupBox::indicator:unchecked:pressed { - border: none; - image: url(":/qss_icons/rc/checkbox_unchecked_focus.png"); -} - -QGroupBox::indicator:unchecked:disabled { - image: url(":/qss_icons/rc/checkbox_unchecked_disabled.png"); -} - -QGroupBox::indicator:checked:hover, QGroupBox::indicator:checked:focus, QGroupBox::indicator:checked:pressed { - border: none; - image: url(":/qss_icons/rc/checkbox_checked_focus.png"); -} - -QGroupBox::indicator:checked:disabled { - image: url(":/qss_icons/rc/checkbox_checked_disabled.png"); -} - -/* QRadioButton ----------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qradiobutton - ---------------------------------------------------------------------------- */ -QRadioButton { - background-color: #19232D; - color: #F0F0F0; - spacing: 4px; - padding: 0px; - border: none; - outline: none; -} - -QRadioButton:focus { - border: none; -} - -QRadioButton:disabled { - background-color: #19232D; - color: #787878; - border: none; - outline: none; -} - -QRadioButton QWidget { - background-color: #19232D; - color: #F0F0F0; - spacing: 0px; - padding: 0px; - outline: none; - border: none; -} - -QRadioButton::indicator { - border: none; - outline: none; - margin-left: 4px; - height: 16px; - width: 16px; -} - -QRadioButton::indicator:unchecked { - image: url(":/qss_icons/rc/radio_unchecked.png"); -} - -QRadioButton::indicator:unchecked:hover, QRadioButton::indicator:unchecked:focus, QRadioButton::indicator:unchecked:pressed { - border: none; - outline: none; - image: url(":/qss_icons/rc/radio_unchecked_focus.png"); -} - -QRadioButton::indicator:unchecked:disabled { - image: url(":/qss_icons/rc/radio_unchecked_disabled.png"); -} - -QRadioButton::indicator:checked { - border: none; - outline: none; - image: url(":/qss_icons/rc/radio_checked.png"); -} - -QRadioButton::indicator:checked:hover, QRadioButton::indicator:checked:focus, QRadioButton::indicator:checked:pressed { - border: none; - outline: none; - image: url(":/qss_icons/rc/radio_checked_focus.png"); -} - -QRadioButton::indicator:checked:disabled { - outline: none; - image: url(":/qss_icons/rc/radio_checked_disabled.png"); -} - -/* QMenuBar --------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenubar - ---------------------------------------------------------------------------- */ -QMenuBar { - background-color: #32414B; - padding: 2px; - border: 1px solid #19232D; - color: #F0F0F0; -} - -QMenuBar:focus { - border: 1px solid #148CD2; -} - -QMenuBar::item { - background: transparent; - padding: 4px; -} - -QMenuBar::item:selected { - padding: 4px; - background: transparent; - border: 0px solid #32414B; -} - -QMenuBar::item:pressed { - padding: 4px; - border: 0px solid #32414B; - background-color: #148CD2; - color: #F0F0F0; - margin-bottom: 0px; - padding-bottom: 0px; -} - -/* QMenu ------------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenu - ---------------------------------------------------------------------------- */ -QMenu { - border: 0px solid #32414B; - color: #F0F0F0; - margin: 0px; -} - -QMenu::separator { - height: 1px; - background-color: #505F69; - color: #F0F0F0; -} - -QMenu::icon { - margin: 0px; - padding-left: 8px; -} - -QMenu::item { - background-color: #32414B; - padding: 4px 24px 4px 24px; - /* Reserve space for selection border */ - border: 1px transparent #32414B; -} - -QMenu::item:selected { - color: #F0F0F0; -} - -QMenu::indicator { - width: 12px; - height: 12px; - padding-left: 6px; - /* non-exclusive indicator = check box style indicator (see QActionGroup::setExclusive) */ - /* exclusive indicator = radio button style indicator (see QActionGroup::setExclusive) */ -} - -QMenu::indicator:non-exclusive:unchecked { - image: url(":/qss_icons/rc/checkbox_unchecked.png"); -} - -QMenu::indicator:non-exclusive:unchecked:selected { - image: url(":/qss_icons/rc/checkbox_unchecked_disabled.png"); -} - -QMenu::indicator:non-exclusive:checked { - image: url(":/qss_icons/rc/checkbox_checked.png"); -} - -QMenu::indicator:non-exclusive:checked:selected { - image: url(":/qss_icons/rc/checkbox_checked_disabled.png"); -} - -QMenu::indicator:exclusive:unchecked { - image: url(":/qss_icons/rc/radio_unchecked.png"); -} - -QMenu::indicator:exclusive:unchecked:selected { - image: url(":/qss_icons/rc/radio_unchecked_disabled.png"); -} - -QMenu::indicator:exclusive:checked { - image: url(":/qss_icons/rc/radio_checked.png"); -} - -QMenu::indicator:exclusive:checked:selected { - image: url(":/qss_icons/rc/radio_checked_disabled.png"); -} - -QMenu::right-arrow { - margin: 5px; - image: url(":/qss_icons/rc/arrow_right.png"); - height: 12px; - width: 12px; -} - -/* QAbstractItemView ------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox - ---------------------------------------------------------------------------- */ -QAbstractItemView { - alternate-background-color: #19232D; - color: #F0F0F0; - border: 1px solid #32414B; - border-radius: 4px; -} - -QAbstractItemView QLineEdit { - padding: 2px; -} - -/* QAbstractScrollArea ---------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea - ---------------------------------------------------------------------------- */ -QAbstractScrollArea { - background-color: #19232D; - border: 1px solid #32414B; - border-radius: 4px; - padding: 2px; - /* fix #159 */ - min-height: 1.25em; - /* fix #159 */ - color: #F0F0F0; -} - -QAbstractScrollArea:disabled { - color: #787878; -} - -/* QScrollArea ------------------------------------------------------------ - ---------------------------------------------------------------------------- */ -QScrollArea QWidget QWidget:disabled { - background-color: #19232D; -} - -/* QScrollBar ------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qscrollbar - ---------------------------------------------------------------------------- */ -QScrollBar:horizontal { - height: 16px; - margin: 2px 16px 2px 16px; - border: 1px solid #32414B; - border-radius: 4px; - background-color: #19232D; -} - -QScrollBar:vertical { - background-color: #19232D; - width: 16px; - margin: 16px 2px 16px 2px; - border: 1px solid #32414B; - border-radius: 4px; -} - -QScrollBar::handle:horizontal { - background-color: #787878; - border: 1px solid #32414B; - border-radius: 4px; - min-width: 8px; -} - -QScrollBar::handle:horizontal:hover { - background-color: #148CD2; - border: 1px solid #148CD2; - border-radius: 4px; - min-width: 8px; -} - -QScrollBar::handle:horizontal:focus { - border: 1px solid #1464A0; -} - -QScrollBar::handle:vertical { - background-color: #787878; - border: 1px solid #32414B; - min-height: 8px; - border-radius: 4px; -} - -QScrollBar::handle:vertical:hover { - background-color: #148CD2; - border: 1px solid #148CD2; - border-radius: 4px; - min-height: 8px; -} - -QScrollBar::handle:vertical:focus { - border: 1px solid #1464A0; -} - -QScrollBar::add-line:horizontal { - margin: 0px 0px 0px 0px; - border-image: url(":/qss_icons/rc/arrow_right_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: right; - subcontrol-origin: margin; -} - -QScrollBar::add-line:horizontal:hover, QScrollBar::add-line:horizontal:on { - border-image: url(":/qss_icons/rc/arrow_right.png"); - height: 12px; - width: 12px; - subcontrol-position: right; - subcontrol-origin: margin; -} - -QScrollBar::add-line:vertical { - margin: 3px 0px 3px 0px; - border-image: url(":/qss_icons/rc/arrow_down_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: bottom; - subcontrol-origin: margin; -} - -QScrollBar::add-line:vertical:hover, QScrollBar::add-line:vertical:on { - border-image: url(":/qss_icons/rc/arrow_down.png"); - height: 12px; - width: 12px; - subcontrol-position: bottom; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:horizontal { - margin: 0px 3px 0px 3px; - border-image: url(":/qss_icons/rc/arrow_left_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: left; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:horizontal:hover, QScrollBar::sub-line:horizontal:on { - border-image: url(":/qss_icons/rc/arrow_left.png"); - height: 12px; - width: 12px; - subcontrol-position: left; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:vertical { - margin: 3px 0px 3px 0px; - border-image: url(":/qss_icons/rc/arrow_up_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: top; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:vertical:hover, QScrollBar::sub-line:vertical:on { - border-image: url(":/qss_icons/rc/arrow_up.png"); - height: 12px; - width: 12px; - subcontrol-position: top; - subcontrol-origin: margin; -} - -QScrollBar::up-arrow:horizontal, QScrollBar::down-arrow:horizontal { - background: none; -} - -QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { - background: none; -} - -QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { - background: none; -} - -QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { - background: none; -} - -/* QTextEdit -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-specific-widgets - ---------------------------------------------------------------------------- */ -QTextEdit { - background-color: #19232D; - color: #F0F0F0; - border-radius: 4px; - border: 1px solid #32414B; -} - -QTextEdit:hover { - border: 1px solid #148CD2; - color: #F0F0F0; -} - -QTextEdit:focus { - border: 1px solid #1464A0; -} - -QTextEdit:selected { - background: #1464A0; - color: #32414B; -} - -/* QPlainTextEdit --------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QPlainTextEdit { - background-color: #19232D; - color: #F0F0F0; - border-radius: 4px; - border: 1px solid #32414B; -} - -QPlainTextEdit:hover { - border: 1px solid #148CD2; - color: #F0F0F0; -} - -QPlainTextEdit:focus { - border: 1px solid #1464A0; -} - -QPlainTextEdit:selected { - background: #1464A0; - color: #32414B; -} - -/* QSizeGrip -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsizegrip - ---------------------------------------------------------------------------- */ -QSizeGrip { - background: transparent; - width: 12px; - height: 12px; - image: url(":/qss_icons/rc/window_grip.png"); -} - -/* QStackedWidget --------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QStackedWidget { - padding: 2px; - border: 1px solid #32414B; - border: 1px solid #19232D; -} - -/* QToolBar --------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbar - ---------------------------------------------------------------------------- */ -QToolBar { - background-color: #32414B; - border-bottom: 1px solid #19232D; - padding: 2px; - font-weight: bold; - spacing: 2px; -} - -QToolBar QToolButton { - background-color: #32414B; - border: 1px solid #32414B; -} - -QToolBar QToolButton:hover { - border: 1px solid #148CD2; -} - -QToolBar QToolButton:checked { - border: 1px solid #19232D; - background-color: #19232D; -} - -QToolBar QToolButton:checked:hover { - border: 1px solid #148CD2; -} - -QToolBar::handle:horizontal { - width: 16px; - image: url(":/qss_icons/rc/toolbar_move_horizontal.png"); -} - -QToolBar::handle:vertical { - height: 16px; - image: url(":/qss_icons/rc/toolbar_move_vertical.png"); -} - -QToolBar::separator:horizontal { - width: 16px; - image: url(":/qss_icons/rc/toolbar_separator_horizontal.png"); -} - -QToolBar::separator:vertical { - height: 16px; - image: url(":/qss_icons/rc/toolbar_separator_vertical.png"); -} - -QToolButton#qt_toolbar_ext_button { - background: #32414B; - border: 0px; - color: #F0F0F0; - image: url(":/qss_icons/rc/arrow_right.png"); -} - -/* QAbstractSpinBox ------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QAbstractSpinBox { - background-color: #19232D; - border: 1px solid #32414B; - color: #F0F0F0; - /* This fixes 103, 111 */ - padding-top: 2px; - /* This fixes 103, 111 */ - padding-bottom: 2px; - padding-left: 4px; - padding-right: 4px; - border-radius: 4px; - /* min-width: 5px; removed to fix 109 */ -} - -QAbstractSpinBox:up-button { - background-color: transparent #19232D; - subcontrol-origin: border; - subcontrol-position: top right; - border-left: 1px solid #32414B; - border-bottom: 1px solid #32414B; - border-top-left-radius: 0; - border-bottom-left-radius: 0; - margin: 1px; - width: 12px; - margin-bottom: -1px; -} - -QAbstractSpinBox::up-arrow, QAbstractSpinBox::up-arrow:disabled, QAbstractSpinBox::up-arrow:off { - image: url(":/qss_icons/rc/arrow_up_disabled.png"); - height: 8px; - width: 8px; -} - -QAbstractSpinBox::up-arrow:hover { - image: url(":/qss_icons/rc/arrow_up.png"); -} - -QAbstractSpinBox:down-button { - background-color: transparent #19232D; - subcontrol-origin: border; - subcontrol-position: bottom right; - border-left: 1px solid #32414B; - border-top: 1px solid #32414B; - border-top-left-radius: 0; - border-bottom-left-radius: 0; - margin: 1px; - width: 12px; - margin-top: -1px; -} - -QAbstractSpinBox::down-arrow, QAbstractSpinBox::down-arrow:disabled, QAbstractSpinBox::down-arrow:off { - image: url(":/qss_icons/rc/arrow_down_disabled.png"); - height: 8px; - width: 8px; -} - -QAbstractSpinBox::down-arrow:hover { - image: url(":/qss_icons/rc/arrow_down.png"); -} - -QAbstractSpinBox:hover { - border: 1px solid #148CD2; - color: #F0F0F0; -} - -QAbstractSpinBox:focus { - border: 1px solid #1464A0; -} - -QAbstractSpinBox:selected { - background: #1464A0; - color: #32414B; -} - -/* ------------------------------------------------------------------------ */ -/* DISPLAYS --------------------------------------------------------------- */ -/* ------------------------------------------------------------------------ */ -/* QLabel ----------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe - ---------------------------------------------------------------------------- */ -QLabel { - background-color: #19232D; - border: 0px solid #32414B; - padding: 2px; - margin: 0px; - color: #F0F0F0; -} - -QLabel:disabled { - background-color: #19232D; - border: 0px solid #32414B; - color: #787878; -} - -/* QTextBrowser ----------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea - ---------------------------------------------------------------------------- */ -QTextBrowser { - background-color: #19232D; - border: 1px solid #32414B; - color: #F0F0F0; - border-radius: 4px; -} - -QTextBrowser:disabled { - background-color: #19232D; - border: 1px solid #32414B; - color: #787878; - border-radius: 4px; -} - -QTextBrowser:hover, QTextBrowser:!hover, QTextBrowser:selected, QTextBrowser:pressed { - border: 1px solid #32414B; -} - -/* QGraphicsView ---------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QGraphicsView { - background-color: #19232D; - border: 1px solid #32414B; - color: #F0F0F0; - border-radius: 4px; -} - -QGraphicsView:disabled { - background-color: #19232D; - border: 1px solid #32414B; - color: #787878; - border-radius: 4px; -} - -QGraphicsView:hover, QGraphicsView:!hover, QGraphicsView:selected, QGraphicsView:pressed { - border: 1px solid #32414B; -} - -/* QCalendarWidget -------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QCalendarWidget { - border: 1px solid #32414B; - border-radius: 4px; -} - -QCalendarWidget:disabled { - background-color: #19232D; - color: #787878; -} - -/* QLCDNumber ------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QLCDNumber { - background-color: #19232D; - color: #F0F0F0; -} - -QLCDNumber:disabled { - background-color: #19232D; - color: #787878; -} - -/* QProgressBar ----------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qprogressbar - ---------------------------------------------------------------------------- */ -QProgressBar { - background-color: #19232D; - border: 1px solid #32414B; - color: #F0F0F0; - border-radius: 4px; - text-align: center; -} - -QProgressBar:disabled { - background-color: #19232D; - border: 1px solid #32414B; - color: #787878; - border-radius: 4px; - text-align: center; -} - -QProgressBar::chunk { - background-color: #1464A0; - color: #19232D; - border-radius: 4px; -} - -QProgressBar::chunk:disabled { - background-color: #14506E; - color: #787878; - border-radius: 4px; -} - -/* ------------------------------------------------------------------------ */ -/* BUTTONS ---------------------------------------------------------------- */ -/* ------------------------------------------------------------------------ */ -/* QPushButton ------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qpushbutton - ---------------------------------------------------------------------------- */ -QPushButton { - background-color: #505F69; - border: 1px solid #32414B; - color: #F0F0F0; - border-radius: 4px; - padding: 3px; - outline: none; - /* Issue #194 - Special case of QPushButton inside dialogs, for better UI */ - min-width: 80px; -} - -QPushButton:disabled { - background-color: #32414B; - border: 1px solid #32414B; - color: #787878; - border-radius: 4px; - padding: 3px; -} - -QPushButton:checked { - background-color: #32414B; - border: 1px solid #32414B; - border-radius: 4px; - padding: 3px; - outline: none; -} - -QPushButton:checked:disabled { - background-color: #19232D; - border: 1px solid #32414B; - color: #787878; - border-radius: 4px; - padding: 3px; - outline: none; -} - -QPushButton:checked:selected { - background: #1464A0; - color: #32414B; -} - -QPushButton::menu-indicator { - subcontrol-origin: padding; - subcontrol-position: bottom right; - bottom: 4px; -} - -QPushButton:pressed { - background-color: #19232D; - border: 1px solid #19232D; -} - -QPushButton:pressed:hover { - border: 1px solid #148CD2; -} - -QPushButton:hover { - border: 1px solid #148CD2; - color: #F0F0F0; -} - -QPushButton:selected { - background: #1464A0; - color: #32414B; -} - -QPushButton:hover { - border: 1px solid #148CD2; - color: #F0F0F0; -} - -QPushButton:focus { - border: 1px solid #1464A0; -} - -/* QToolButton ------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbutton - ---------------------------------------------------------------------------- */ -QToolButton { - background-color: transparent; - border: 1px solid transparent; - border-radius: 4px; - margin: 0px; - padding: 2px; - /* The subcontrols below are used only in the DelayedPopup mode */ - /* The subcontrols below are used only in the MenuButtonPopup mode */ - /* The subcontrol below is used only in the InstantPopup or DelayedPopup mode */ -} - -QToolButton:checked { - background-color: transparent; - border: 1px solid #1464A0; -} - -QToolButton:checked:disabled { - border: 1px solid #14506E; -} - -QToolButton:pressed { - margin: 1px; - background-color: transparent; - border: 1px solid #1464A0; -} - -QToolButton:disabled { - border: none; -} - -QToolButton:hover { - border: 1px solid #148CD2; -} - -QToolButton[popupMode="0"] { - /* Only for DelayedPopup */ - padding-right: 2px; -} - -QToolButton[popupMode="1"] { - /* Only for MenuButtonPopup */ - padding-right: 20px; -} - -QToolButton[popupMode="1"]::menu-button { - border: none; -} - -QToolButton[popupMode="1"]::menu-button:hover { - border: none; - border-left: 1px solid #148CD2; - border-radius: 0; -} - -QToolButton[popupMode="2"] { - /* Only for InstantPopup */ - padding-right: 2px; -} - -QToolButton::menu-button { - padding: 2px; - border-radius: 4px; - border: 1px solid #32414B; - width: 12px; - outline: none; -} - -QToolButton::menu-button:hover { - border: 1px solid #148CD2; -} - -QToolButton::menu-button:checked:hover { - border: 1px solid #148CD2; -} - -QToolButton::menu-indicator { - image: url(":/qss_icons/rc/arrow_down.png"); - height: 8px; - width: 8px; - top: 0; - /* Exclude a shift for better image */ - left: -2px; - /* Shift it a bit */ -} - -QToolButton::menu-arrow { - image: url(":/qss_icons/rc/arrow_down.png"); - height: 8px; - width: 8px; -} - -QToolButton::menu-arrow:hover { - image: url(":/qss_icons/rc/arrow_down_focus.png"); -} - -/* QCommandLinkButton ----------------------------------------------------- - ---------------------------------------------------------------------------- */ -QCommandLinkButton { - background-color: transparent; - border: 1px solid #32414B; - color: #F0F0F0; - border-radius: 4px; - padding: 0px; - margin: 0px; -} - -QCommandLinkButton:disabled { - background-color: transparent; - color: #787878; -} - -/* ------------------------------------------------------------------------ */ -/* INPUTS - NO FIELDS ----------------------------------------------------- */ -/* ------------------------------------------------------------------------ */ -/* QComboBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox - ---------------------------------------------------------------------------- */ -QComboBox { - border: 1px solid #32414B; - border-radius: 4px; - selection-background-color: #1464A0; - padding-left: 4px; - padding-right: 36px; - /* 4 + 16*2 See scrollbar size */ - /* Fixes #103, #111 */ - min-height: 1.5em; - /* padding-top: 2px; removed to fix #132 */ - /* padding-bottom: 2px; removed to fix #132 */ - /* min-width: 75px; removed to fix #109 */ - /* Needed to remove indicator - fix #132 */ -} - -QComboBox QAbstractItemView { - border: 1px solid #32414B; - border-radius: 0; - background-color: #19232D; - selection-background-color: #1464A0; -} - -QComboBox QAbstractItemView:hover { - background-color: #19232D; - color: #F0F0F0; -} - -QComboBox QAbstractItemView:selected { - background: #1464A0; - color: #32414B; -} - -QComboBox QAbstractItemView:alternate { - background: #19232D; -} - -QComboBox:disabled { - background-color: #19232D; - color: #787878; -} - -QComboBox:hover { - border: 1px solid #148CD2; -} - -QComboBox:focus { - border: 1px solid #1464A0; -} - -QComboBox:on { - selection-background-color: #1464A0; -} - -QComboBox::indicator { - border: none; - border-radius: 0; - background-color: transparent; - selection-background-color: transparent; - color: transparent; - selection-color: transparent; - /* Needed to remove indicator - fix #132 */ -} - -QComboBox::indicator:alternate { - background: #19232D; -} - -QComboBox::item:alternate { - background: #19232D; -} - -QComboBox::item:checked { - font-weight: bold; -} - -QComboBox::item:selected { - border: 0px solid transparent; -} - -QComboBox::drop-down { - subcontrol-origin: padding; - subcontrol-position: top right; - width: 12px; - border-left: 1px solid #32414B; -} - -QComboBox::down-arrow { - image: url(":/qss_icons/rc/arrow_down_disabled.png"); - height: 8px; - width: 8px; -} - -QComboBox::down-arrow:on, QComboBox::down-arrow:hover, QComboBox::down-arrow:focus { - image: url(":/qss_icons/rc/arrow_down.png"); -} - -/* QSlider ---------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qslider - ---------------------------------------------------------------------------- */ -QSlider:disabled { - background: #19232D; -} - -QSlider:focus { - border: none; -} - -QSlider::groove:horizontal { - background: #32414B; - border: 1px solid #32414B; - height: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::groove:vertical { - background: #32414B; - border: 1px solid #32414B; - width: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::add-page:vertical { - background: #1464A0; - border: 1px solid #32414B; - width: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::add-page:vertical :disabled { - background: #14506E; -} - -QSlider::sub-page:horizontal { - background: #1464A0; - border: 1px solid #32414B; - height: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::sub-page:horizontal:disabled { - background: #14506E; -} - -QSlider::handle:horizontal { - background: #787878; - border: 1px solid #32414B; - width: 8px; - height: 8px; - margin: -8px 0px; - border-radius: 4px; -} - -QSlider::handle:horizontal:hover { - background: #148CD2; - border: 1px solid #148CD2; -} - -QSlider::handle:horizontal:focus { - border: 1px solid #1464A0; -} - -QSlider::handle:vertical { - background: #787878; - border: 1px solid #32414B; - width: 8px; - height: 8px; - margin: 0 -8px; - border-radius: 4px; -} - -QSlider::handle:vertical:hover { - background: #148CD2; - border: 1px solid #148CD2; -} - -QSlider::handle:vertical:focus { - border: 1px solid #1464A0; -} - -/* QLineEdit -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlineedit - ---------------------------------------------------------------------------- */ -QLineEdit { - background-color: #19232D; - padding-top: 2px; - /* This QLineEdit fix 103, 111 */ - padding-bottom: 2px; - /* This QLineEdit fix 103, 111 */ - padding-left: 4px; - padding-right: 4px; - border-style: solid; - border: 1px solid #32414B; - border-radius: 4px; - color: #F0F0F0; -} - -QLineEdit:disabled { - background-color: #19232D; - color: #787878; -} - -QLineEdit:hover { - border: 1px solid #148CD2; - color: #F0F0F0; -} - -QLineEdit:focus { - border: 1px solid #1464A0; -} - -QLineEdit:selected { - background-color: #1464A0; - color: #32414B; -} - -/* QTabWiget -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar - ---------------------------------------------------------------------------- */ -QTabWidget { - padding: 2px; - selection-background-color: #32414B; -} - -QTabWidget QWidget { - /* Fixes #189 */ - border-radius: 4px; -} - -QTabWidget::pane { - border: 1px solid #32414B; - border-radius: 4px; - margin: 0px; - /* Fixes double border inside pane with pyqt5 */ - padding: 0px; -} - -QTabWidget::pane:selected { - background-color: #32414B; - border: 1px solid #1464A0; -} - -/* QTabBar ---------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar - ---------------------------------------------------------------------------- */ -QTabBar { - qproperty-drawBase: 0; - border-radius: 4px; - margin: 0px; - padding: 2px; - border: 0; - /* left: 5px; move to the right by 5px - removed for fix */ -} - -QTabBar::close-button { - border: 0; - margin: 2px; - padding: 2px; - image: url(":/qss_icons/rc/window_close.png"); -} - -QTabBar::close-button:hover { - image: url(":/qss_icons/rc/window_close_focus.png"); -} - -QTabBar::close-button:pressed { - image: url(":/qss_icons/rc/window_close_pressed.png"); -} - -/* QTabBar::tab - selected ------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar - ---------------------------------------------------------------------------- */ -QTabBar::tab { - /* !selected and disabled ----------------------------------------- */ - /* selected ------------------------------------------------------- */ -} - -QTabBar::tab:top:selected:disabled { - border-bottom: 3px solid #14506E; - color: #787878; - background-color: #32414B; -} - -QTabBar::tab:bottom:selected:disabled { - border-top: 3px solid #14506E; - color: #787878; - background-color: #32414B; -} - -QTabBar::tab:left:selected:disabled { - border-right: 3px solid #14506E; - color: #787878; - background-color: #32414B; -} - -QTabBar::tab:right:selected:disabled { - border-left: 3px solid #14506E; - color: #787878; - background-color: #32414B; -} - -QTabBar::tab:top:!selected:disabled { - border-bottom: 3px solid #19232D; - color: #787878; - background-color: #19232D; -} - -QTabBar::tab:bottom:!selected:disabled { - border-top: 3px solid #19232D; - color: #787878; - background-color: #19232D; -} - -QTabBar::tab:left:!selected:disabled { - border-right: 3px solid #19232D; - color: #787878; - background-color: #19232D; -} - -QTabBar::tab:right:!selected:disabled { - border-left: 3px solid #19232D; - color: #787878; - background-color: #19232D; -} - -QTabBar::tab:top:!selected { - border-bottom: 2px solid #19232D; - margin-top: 2px; -} - -QTabBar::tab:bottom:!selected { - border-top: 2px solid #19232D; - margin-bottom: 3px; -} - -QTabBar::tab:left:!selected { - border-left: 2px solid #19232D; - margin-right: 2px; -} - -QTabBar::tab:right:!selected { - border-right: 2px solid #19232D; - margin-left: 2px; -} - -QTabBar::tab:top { - background-color: #32414B; - color: #F0F0F0; - margin-left: 2px; - padding-left: 4px; - padding-right: 4px; - padding-top: 2px; - padding-bottom: 2px; - min-width: 5px; - border-bottom: 3px solid #32414B; - border-top-left-radius: 3px; - border-top-right-radius: 3px; -} - -QTabBar::tab:top:selected { - background-color: #505F69; - color: #F0F0F0; - border-bottom: 3px solid #1464A0; - border-top-left-radius: 3px; - border-top-right-radius: 3px; -} - -QTabBar::tab:top:!selected:hover { - border: 1px solid #148CD2; - border-bottom: 3px solid #148CD2; - /* Fixes spyder-ide/spyder#9766 */ - padding-left: 4px; - padding-right: 4px; -} - -QTabBar::tab:bottom { - color: #F0F0F0; - border-top: 3px solid #32414B; - background-color: #32414B; - margin-left: 2px; - padding-left: 4px; - padding-right: 4px; - padding-top: 2px; - padding-bottom: 2px; - border-bottom-left-radius: 3px; - border-bottom-right-radius: 3px; - min-width: 5px; -} - -QTabBar::tab:bottom:selected { - color: #F0F0F0; - background-color: #505F69; - border-top: 3px solid #1464A0; - border-bottom-left-radius: 3px; - border-bottom-right-radius: 3px; -} - -QTabBar::tab:bottom:!selected:hover { - border: 1px solid #148CD2; - border-top: 3px solid #148CD2; - /* Fixes spyder-ide/spyder#9766 */ - padding-left: 4px; - padding-right: 4px; -} - -QTabBar::tab:left { - color: #F0F0F0; - background-color: #32414B; - margin-top: 2px; - padding-left: 2px; - padding-right: 2px; - padding-top: 4px; - padding-bottom: 4px; - border-top-left-radius: 3px; - border-bottom-left-radius: 3px; - min-height: 5px; -} - -QTabBar::tab:left:selected { - color: #F0F0F0; - background-color: #505F69; - border-right: 3px solid #1464A0; -} - -QTabBar::tab:left:!selected:hover { - border: 1px solid #148CD2; - border-right: 3px solid #148CD2; - padding: 0px; -} - -QTabBar::tab:right { - color: #F0F0F0; - background-color: #32414B; - margin-top: 2px; - padding-left: 2px; - padding-right: 2px; - padding-top: 4px; - padding-bottom: 4px; - border-top-right-radius: 3px; - border-bottom-right-radius: 3px; - min-height: 5px; -} - -QTabBar::tab:right:selected { - color: #F0F0F0; - background-color: #505F69; - border-left: 3px solid #1464A0; -} - -QTabBar::tab:right:!selected:hover { - border: 1px solid #148CD2; - border-left: 3px solid #148CD2; - padding: 0px; -} - -QTabBar QToolButton { - /* Fixes #136 */ - background-color: #32414B; - height: 12px; - width: 12px; -} - -QTabBar QToolButton:pressed { - background-color: #32414B; -} - -QTabBar QToolButton:pressed:hover { - border: 1px solid #148CD2; -} - -QTabBar QToolButton::left-arrow:enabled { - image: url(":/qss_icons/rc/arrow_left.png"); -} - -QTabBar QToolButton::left-arrow:disabled { - image: url(":/qss_icons/rc/arrow_left_disabled.png"); -} - -QTabBar QToolButton::right-arrow:enabled { - image: url(":/qss_icons/rc/arrow_right.png"); -} - -QTabBar QToolButton::right-arrow:disabled { - image: url(":/qss_icons/rc/arrow_right_disabled.png"); -} - -/* QDockWiget ------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QDockWidget { - outline: 1px solid #32414B; - background-color: #19232D; - border: 1px solid #32414B; - border-radius: 4px; - titlebar-close-icon: url(":/qss_icons/rc/window_close.png"); - titlebar-normal-icon: url(":/qss_icons/rc/window_undock.png"); -} - -QDockWidget::title { - /* Better size for title bar */ - padding: 6px; - spacing: 4px; - border: none; - background-color: #32414B; -} - -QDockWidget::close-button { - background-color: #32414B; - border-radius: 4px; - border: none; -} - -QDockWidget::close-button:hover { - image: url(":/qss_icons/rc/window_close_focus.png"); -} - -QDockWidget::close-button:pressed { - image: url(":/qss_icons/rc/window_close_pressed.png"); -} - -QDockWidget::float-button { - background-color: #32414B; - border-radius: 4px; - border: none; -} - -QDockWidget::float-button:hover { - image: url(":/qss_icons/rc/window_undock_focus.png"); -} - -QDockWidget::float-button:pressed { - image: url(":/qss_icons/rc/window_undock_pressed.png"); -} - -/* QTreeView QListView QTableView ----------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtreeview -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlistview -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtableview - ---------------------------------------------------------------------------- */ -QTreeView:branch:selected, QTreeView:branch:hover { - background: url(":/qss_icons/rc/transparent.png"); -} - -QTreeView:branch:has-siblings:!adjoins-item { - border-image: url(":/qss_icons/rc/branch_line.png") 0; -} - -QTreeView:branch:has-siblings:adjoins-item { - border-image: url(":/qss_icons/rc/branch_more.png") 0; -} - -QTreeView:branch:!has-children:!has-siblings:adjoins-item { - border-image: url(":/qss_icons/rc/branch_end.png") 0; -} - -QTreeView:branch:has-children:!has-siblings:closed, QTreeView:branch:closed:has-children:has-siblings { - border-image: none; - image: url(":/qss_icons/rc/branch_closed.png"); -} - -QTreeView:branch:open:has-children:!has-siblings, QTreeView:branch:open:has-children:has-siblings { - border-image: none; - image: url(":/qss_icons/rc/branch_open.png"); -} - -QTreeView:branch:has-children:!has-siblings:closed:hover, QTreeView:branch:closed:has-children:has-siblings:hover { - image: url(":/qss_icons/rc/branch_closed_focus.png"); -} - -QTreeView:branch:open:has-children:!has-siblings:hover, QTreeView:branch:open:has-children:has-siblings:hover { - image: url(":/qss_icons/rc/branch_open_focus.png"); -} - -QTreeView::indicator:checked, -QListView::indicator:checked { - image: url(":/qss_icons/rc/checkbox_checked.png"); -} - -QTreeView::indicator:checked:hover, QTreeView::indicator:checked:focus, QTreeView::indicator:checked:pressed, -QListView::indicator:checked:hover, -QListView::indicator:checked:focus, -QListView::indicator:checked:pressed { - image: url(":/qss_icons/rc/checkbox_checked_focus.png"); -} - -QTreeView::indicator:unchecked, -QListView::indicator:unchecked { - image: url(":/qss_icons/rc/checkbox_unchecked.png"); -} - -QTreeView::indicator:unchecked:hover, QTreeView::indicator:unchecked:focus, QTreeView::indicator:unchecked:pressed, -QListView::indicator:unchecked:hover, -QListView::indicator:unchecked:focus, -QListView::indicator:unchecked:pressed { - image: url(":/qss_icons/rc/checkbox_unchecked_focus.png"); -} - -QTreeView::indicator:indeterminate, -QListView::indicator:indeterminate { - image: url(":/qss_icons/rc/checkbox_indeterminate.png"); -} - -QTreeView::indicator:indeterminate:hover, QTreeView::indicator:indeterminate:focus, QTreeView::indicator:indeterminate:pressed, -QListView::indicator:indeterminate:hover, -QListView::indicator:indeterminate:focus, -QListView::indicator:indeterminate:pressed { - image: url(":/qss_icons/rc/checkbox_indeterminate_focus.png"); -} - -QTreeView, -QListView, -QTableView, -QColumnView { - background-color: #19232D; - border: 1px solid #32414B; - color: #F0F0F0; - gridline-color: #32414B; - border-radius: 4px; -} - -QTreeView:disabled, -QListView:disabled, -QTableView:disabled, -QColumnView:disabled { - background-color: #19232D; - color: #787878; -} - -QTreeView:selected, -QListView:selected, -QTableView:selected, -QColumnView:selected { - background-color: #1464A0; - color: #32414B; -} - -QTreeView:hover, -QListView:hover, -QTableView:hover, -QColumnView:hover { - background-color: #19232D; - border: 1px solid #148CD2; -} - -QTreeView::item:pressed, -QListView::item:pressed, -QTableView::item:pressed, -QColumnView::item:pressed { - background-color: #1464A0; -} - -QTreeView::item:selected:hover, -QListView::item:selected:hover, -QTableView::item:selected:hover, -QColumnView::item:selected:hover { - background: #1464A0; - color: #19232D; -} - -QTreeView::item:selected:active, -QListView::item:selected:active, -QTableView::item:selected:active, -QColumnView::item:selected:active { - background-color: #1464A0; -} - -QTreeView::item:!selected:hover, -QListView::item:!selected:hover, -QTableView::item:!selected:hover, -QColumnView::item:!selected:hover { - outline: 0; - color: #148CD2; - background-color: #32414B; -} - -QTableCornerButton::section { - background-color: #19232D; - border: 1px transparent #32414B; - border-radius: 0px; -} - -/* QHeaderView ------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qheaderview - ---------------------------------------------------------------------------- */ -QHeaderView { - background-color: #32414B; - border: 0px transparent #32414B; - padding: 0px; - margin: 0px; - border-radius: 0px; -} - -QHeaderView:disabled { - background-color: #32414B; - border: 1px transparent #32414B; - padding: 2px; -} - -QHeaderView::section { - background-color: #32414B; - color: #F0F0F0; - padding: 2px; - border-radius: 0px; - text-align: left; -} - -QHeaderView::section:checked { - color: #F0F0F0; - background-color: #1464A0; -} - -QHeaderView::section:checked:disabled { - color: #787878; - background-color: #14506E; -} - -QHeaderView::section::horizontal { - padding-left: 4px; - padding-right: 4px; - border-left: 1px solid #19232D; -} - -QHeaderView::section::horizontal::first, QHeaderView::section::horizontal::only-one { - border-left: 1px solid #32414B; -} - -QHeaderView::section::horizontal:disabled { - color: #787878; -} - -QHeaderView::section::vertical { - padding-left: 4px; - padding-right: 4px; - border-top: 1px solid #19232D; -} - -QHeaderView::section::vertical::first, QHeaderView::section::vertical::only-one { - border-top: 1px solid #32414B; -} - -QHeaderView::section::vertical:disabled { - color: #787878; -} - -QHeaderView::down-arrow { - /* Those settings (border/width/height/background-color) solve bug */ - /* transparent arrow background and size */ - background-color: #32414B; - border: none; - height: 12px; - width: 12px; - padding-left: 2px; - padding-right: 2px; - image: url(":/qss_icons/rc/arrow_down.png"); -} - -QHeaderView::up-arrow { - background-color: #32414B; - border: none; - height: 12px; - width: 12px; - padding-left: 2px; - padding-right: 2px; - image: url(":/qss_icons/rc/arrow_up.png"); -} - -/* QToolBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbox - ---------------------------------------------------------------------------- */ -QToolBox { - padding: 0px; - border: 0px; - border: 1px solid #32414B; -} - -QToolBox:selected { - padding: 0px; - border: 2px solid #1464A0; -} - -QToolBox::tab { - background-color: #19232D; - border: 1px solid #32414B; - color: #F0F0F0; - border-top-left-radius: 4px; - border-top-right-radius: 4px; -} - -QToolBox::tab:disabled { - color: #787878; -} - -QToolBox::tab:selected { - background-color: #505F69; - border-bottom: 2px solid #1464A0; -} - -QToolBox::tab:selected:disabled { - background-color: #32414B; - border-bottom: 2px solid #14506E; -} - -QToolBox::tab:!selected { - background-color: #32414B; - border-bottom: 2px solid #32414B; -} - -QToolBox::tab:!selected:disabled { - background-color: #19232D; -} - -QToolBox::tab:hover { - border-color: #148CD2; - border-bottom: 2px solid #148CD2; -} - -QToolBox QScrollArea QWidget QWidget { - padding: 0px; - border: 0px; - background-color: #19232D; -} - -/* QFrame ----------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe -https://doc.qt.io/qt-5/qframe.html#-prop -https://doc.qt.io/qt-5/qframe.html#details -https://stackoverflow.com/questions/14581498/qt-stylesheet-for-hline-vline-color - ---------------------------------------------------------------------------- */ -/* (dot) .QFrame fix #141, #126, #123 */ -.QFrame { - border-radius: 4px; - border: 1px solid #32414B; - /* No frame */ - /* HLine */ - /* HLine */ -} - -.QFrame[frameShape="0"] { - border-radius: 4px; - border: 1px transparent #32414B; -} - -.QFrame[frameShape="4"] { - max-height: 2px; - border: none; - background-color: #32414B; -} - -.QFrame[frameShape="5"] { - max-width: 2px; - border: none; - background-color: #32414B; -} - -/* QSplitter -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsplitter - ---------------------------------------------------------------------------- */ -QSplitter { - background-color: #32414B; - spacing: 0px; - padding: 0px; - margin: 0px; -} - -QSplitter::handle { - background-color: #32414B; - border: 0px solid #19232D; - spacing: 0px; - padding: 1px; - margin: 0px; -} - -QSplitter::handle:hover { - background-color: #787878; -} - -QSplitter::handle:horizontal { - width: 5px; - image: url(":/qss_icons/rc/line_vertical.png"); -} - -QSplitter::handle:vertical { - height: 5px; - image: url(":/qss_icons/rc/line_horizontal.png"); -} - -/* QDateEdit -------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QDateEdit { - selection-background-color: #1464A0; - border-style: solid; - border: 1px solid #32414B; - border-radius: 4px; - /* This fixes 103, 111 */ - padding-top: 2px; - /* This fixes 103, 111 */ - padding-bottom: 2px; - padding-left: 4px; - padding-right: 4px; - min-width: 10px; -} - -QDateEdit:on { - selection-background-color: #1464A0; -} - -QDateEdit::drop-down { - subcontrol-origin: padding; - subcontrol-position: top right; - width: 12px; - border-left: 1px solid #32414B; -} - -QDateEdit::down-arrow { - image: url(":/qss_icons/rc/arrow_down_disabled.png"); - height: 8px; - width: 8px; -} - -QDateEdit::down-arrow:on, QDateEdit::down-arrow:hover, QDateEdit::down-arrow:focus { - image: url(":/qss_icons/rc/arrow_down.png"); -} - -QDateEdit QAbstractItemView { - background-color: #19232D; - border-radius: 4px; - border: 1px solid #32414B; - selection-background-color: #1464A0; -} - -/* QAbstractView ---------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QAbstractView:hover { - border: 1px solid #148CD2; - color: #F0F0F0; -} - -QAbstractView:selected { - background: #1464A0; - color: #32414B; -} - -/* PlotWidget ------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -PlotWidget { - /* Fix cut labels in plots #134 */ - padding: 0px; -} From cbb85e8ef947e18584d5fd6f885d0336ba9771ae Mon Sep 17 00:00:00 2001 From: gallowj Date: Wed, 26 May 2021 11:32:05 -0500 Subject: [PATCH 154/811] adding qdarkstyle to requirements.txt since we removed the package from codebase --- .../SDK/Maya/requirements.txt | 18 ++++++++++++++---- .../DccScriptingInterface/requirements.txt | 10 ++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/requirements.txt b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/requirements.txt index 8fd084dac8..ceb5be4dea 100644 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/requirements.txt +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/requirements.txt @@ -4,14 +4,14 @@ # # pip-compile --generate-hashes requirements.txt # -cachetools==3.1.1 \ - --hash=sha256:428266a1c0d36dc5aca63a2d7c5942e88c2c898d72139fca0e97fdd2380517ae \ - --hash=sha256:8ea2d3ce97850f31e4a08b0e2b5e6c34997d7216a9d2c98e0f3978630d4da69a - # via -r requirements.txt certifi==2020.6.20 \ --hash=sha256:5930595817496dd21bb8dc35dad090f1c2cd0adfaf21204bf6732ca5d8ee34d3 \ --hash=sha256:8fc0819f1f30ba15bdb34cceffb9ef04d99f420f68eb75d901e9560b8749fc41 # via -r requirements.txt +cachetools==3.1.1 \ + --hash=sha256:428266a1c0d36dc5aca63a2d7c5942e88c2c898d72139fca0e97fdd2380517ae \ + --hash=sha256:8ea2d3ce97850f31e4a08b0e2b5e6c34997d7216a9d2c98e0f3978630d4da69a + # via -r requirements.txt click==7.1.2 \ --hash=sha256:d2b5255c7c6349bc1bd1e59e08cd12acbbd63ce649f2588755783aa94dfb6b1a \ --hash=sha256:dacca89f4bfadd5de3d7489b7c8a566eee0d3676333fbb50030263894c38c0dc @@ -68,6 +68,16 @@ unipath==1.1 \ --hash=sha256:09839adcc72e8a24d4f76d63656f30b5a1f721fc40c9bcd79d8c67bdd8b47dae \ --hash=sha256:e6257e508d8abbfb6ddd8ec357e33589f1f48b1599127f23b017124d90b0fff7 # via -r requirements.txt +qdarkstyle==3.0.2 \ + --hash=sha256:55d149cf5f40ee297397f1818e091118cefb855a4a9c5c38566c47acd2d8c7ae \ + --hash=sha256:7c791535cc20b3cc1e8e1bf6b88dabe53cb0615983df702be83597e73ada2558 + # via -r c:\temp\requirements.txt +qtpy==1.9.0 \ + --hash=sha256:2db72c44b55d0fe1407be8fba35c838ad0d6d3bb81f23007886dc1fc0f459c8d \ + --hash=sha256:fa0b8363b363e89b2a6f49eddc162a04c0699ae95e109a6be3bb145a913190ea + # via + # -r c:\temp\requirements.txt + # qdarkstyle wincertstore==0.2 \ --hash=sha256:22d5eebb52df88a8d4014d5cf6d1b6c3a5d469e6c3b2e2854f3a003e48872356 \ --hash=sha256:780bd1557c9185c15d9f4221ea7f905cb20b93f7151ca8ccaed9714dce4b327a diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/requirements.txt b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/requirements.txt index 2f7626addb..1536b79f3d 100644 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/requirements.txt +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/requirements.txt @@ -36,6 +36,16 @@ unipath==1.1 \ --hash=sha256:09839adcc72e8a24d4f76d63656f30b5a1f721fc40c9bcd79d8c67bdd8b47dae \ --hash=sha256:e6257e508d8abbfb6ddd8ec357e33589f1f48b1599127f23b017124d90b0fff7 # via -r requirements.txt +qdarkstyle==3.0.2 \ + --hash=sha256:55d149cf5f40ee297397f1818e091118cefb855a4a9c5c38566c47acd2d8c7ae \ + --hash=sha256:7c791535cc20b3cc1e8e1bf6b88dabe53cb0615983df702be83597e73ada2558 + # via -r c:\temp\requirements.txt +qtpy==1.9.0 \ + --hash=sha256:2db72c44b55d0fe1407be8fba35c838ad0d6d3bb81f23007886dc1fc0f459c8d \ + --hash=sha256:fa0b8363b363e89b2a6f49eddc162a04c0699ae95e109a6be3bb145a913190ea + # via + # -r c:\temp\requirements.txt + # qdarkstyle wincertstore==0.2 \ --hash=sha256:22d5eebb52df88a8d4014d5cf6d1b6c3a5d469e6c3b2e2854f3a003e48872356 \ --hash=sha256:780bd1557c9185c15d9f4221ea7f905cb20b93f7151ca8ccaed9714dce4b327a From d77fae5c18d4bfa51d1db9dbe0e29e2be3d14aad Mon Sep 17 00:00:00 2001 From: Jonny Galloway Date: Wed, 26 May 2021 11:56:18 -0500 Subject: [PATCH 155/811] update removed a line, that QT/PySide2 location no longer exists, PySide2 is not installed via a .egg in the python runtime --- .../DccScriptingInterface/Editor/Scripts/bootstrap.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py index 835c196924..06b00da981 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py @@ -121,7 +121,6 @@ if __name__ == '__main__': import PySide2 _LOGGER.info(f'PySide2: {PySide2}') - #_LOGGER.info(f'QTFORPYTHON_PATH: {_settings.QTFORPYTHON_PATH}') _LOGGER.info(f'LY_BIN_PATH: {_settings.LY_BIN_PATH}') _LOGGER.info(f'QT_PLUGIN_PATH: {_settings.QT_PLUGIN_PATH}') _LOGGER.info(f'QT_QPA_PLATFORM_PLUGIN_PATH: {_settings.QT_QPA_PLATFORM_PLUGIN_PATH}') From ada73c2834b47fcbb90b3a36f5cae26243a07c1e Mon Sep 17 00:00:00 2001 From: zsolleci Date: Wed, 26 May 2021 12:22:18 -0500 Subject: [PATCH 156/811] T92567323 & T92569017 completed, suite updated --- ...nt_AddRemoveParameter_ActionsSuccessful.py | 133 ++++++++++++++++++ .../scripting/TestSuite_Periodic.py | 12 ++ 2 files changed, 145 insertions(+) create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py new file mode 100644 index 0000000000..a587354985 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py @@ -0,0 +1,133 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + + +# fmt: off +class Tests(): + new_event_created = ("Successfully created a new event", "Failed to create a new event") + child_event_created = ("Successfully created Child Event", "Failed to create Child Event") + file_saved = ("Successfully saved event asset", "Failed to save event asset") + parameter_created = ("Successfully added parameter", "Failed to add parameter") + parameter_removed = ("Successfully removed parameter", "Failed to remove parameter") +# fmt: on + + +def ScriptEvent_AddRemoveParameter_ActionsSuccessful(): + """ + Summary: + Parameter can be removed from a Script Event method + + Expected Behavior: + Upon saving the updated .scriptevents asset the removed paramenter should no longer be present on the Script Event + + Test Steps: + 1) Open Asset Editor + 2) Get Asset Editor Qt object + 3) Create new Script Event Asset + 4) Add Parameter to Event + 5) Verify Parameter exists + 6) Remove Parameter from Event + 7) Verify Parameter has been removed + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + from PySide2 import QtWidgets + + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + import editor_python_test_tools.pyside_utils as pyside_utils + + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.legacy.general as general + + GENERAL_WAIT = 1.0 # seconds + FILE_PATH = os.path.join("AutomatedTesting", "ScriptCanvas", "test_file.scriptevent") + QtObject = object + + def create_script_event(asset_editor: QtObject, file_path: str) -> None: + action = pyside_utils.find_child_by_pattern(menu_bar, {"type": QtWidgets.QAction, "text": "Script Events"}) + action.trigger() + result = helper.wait_for_condition( + lambda: container.findChild(QtWidgets.QFrame, "Events") is not None, 3 * GENERAL_WAIT + ) + Report.result(Tests.new_event_created, result) + + # Add new child event + add_event = container.findChild(QtWidgets.QFrame, "Events").findChild(QtWidgets.QToolButton, "") + add_event.click() + result = helper.wait_for_condition( + lambda: asset_editor.findChild(QtWidgets.QFrame, "EventName") is not None, GENERAL_WAIT + ) + Report.result(Tests.child_event_created, result) + # Save the Script Event file + editor.AssetEditorWidgetRequestsBus(bus.Broadcast, "SaveAssetAs", file_path) + + # Verify if file is created + result = helper.wait_for_condition(lambda: os.path.exists(file_path), 3 * GENERAL_WAIT) + Report.result(Tests.file_saved, result) + + def create_parameter(file_path: str) -> None: + add_param = container.findChild(QtWidgets.QFrame, "Parameters").findChild(QtWidgets.QToolButton, "") + add_param.click() + result = helper.wait_for_condition( + lambda: asset_editor_widget.findChild(QtWidgets.QFrame, "[0]") is not None, GENERAL_WAIT + ) + Report.result(Tests.parameter_created, result) + editor.AssetEditorWidgetRequestsBus(bus.Broadcast, "SaveAssetAs", file_path) + + def remove_parameter(file_path: str) -> None: + remove_param = container.findChild(QtWidgets.QFrame, "[0]").findChild(QtWidgets.QToolButton, "") + remove_param.click() + result = helper.wait_for_condition( + lambda: asset_editor_widget.findChild(QtWidgets.QFrame, "[0]") is None, GENERAL_WAIT + ) + Report.result(Tests.parameter_removed, result) + editor.AssetEditorWidgetRequestsBus(bus.Broadcast, "SaveAssetAs", file_path) + + # 1) Open Asset Editor + general.idle_enable(True) + # Initially close the Asset Editor and then reopen to ensure we don't have any existing assets open + general.close_pane("Asset Editor") + general.open_pane("Asset Editor") + helper.wait_for_condition(lambda: general.is_pane_visible("Asset Editor"), 5.0) + + # 2) Get Asset Editor Qt object + editor_window = pyside_utils.get_editor_main_window() + asset_editor_widget = editor_window.findChild(QtWidgets.QDockWidget, "Asset Editor").findChild( + QtWidgets.QWidget, "AssetEditorWindowClass" + ) + container = asset_editor_widget.findChild(QtWidgets.QWidget, "ContainerForRows") + menu_bar = asset_editor_widget.findChild(QtWidgets.QMenuBar) + + # 3) Create new Script Event Asset + create_script_event(asset_editor_widget, FILE_PATH) + + # 4) Add Parameter to Event + create_parameter(FILE_PATH) + + # 5) Remove Parameter from Event + remove_parameter(FILE_PATH) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from editor_python_test_tools.utils import Report + + Report.start_test(ScriptEvent_AddRemoveParameter_ActionsSuccessful) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py index 85d0b4523f..46d07250bc 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py @@ -190,6 +190,18 @@ class TestAutomation(TestAutomationBase): from . import Node_HappyPath_DuplicateNode as test_module self._run_test(request, workspace, editor, test_module) + def test_ScriptEvent_AddRemoveParameter_ActionsSuccessful(self, request, workspace, editor, launcher_platform): + def teardown(): + file_system.delete( + [os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True + ) + request.addfinalizer(teardown) + file_system.delete( + [os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True + ) + from . import ScriptEvent_AddRemoveParameter_ActionsSuccessful as test_module + self._run_test(request, workspace, editor, test_module) + # NOTE: We had to use hydra_test_utils.py, as TestAutomationBase run_test method # fails because of pyside_utils import @pytest.mark.SUITE_periodic From 8a119f2b18bc643f4841182380eb7dd443796a2a Mon Sep 17 00:00:00 2001 From: zsolleci Date: Wed, 26 May 2021 12:33:46 -0500 Subject: [PATCH 157/811] fixed error in test steps description --- .../ScriptEvent_AddRemoveParameter_ActionsSuccessful.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py index a587354985..638c69e8f3 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py @@ -33,9 +33,7 @@ def ScriptEvent_AddRemoveParameter_ActionsSuccessful(): 2) Get Asset Editor Qt object 3) Create new Script Event Asset 4) Add Parameter to Event - 5) Verify Parameter exists - 6) Remove Parameter from Event - 7) Verify Parameter has been removed + 5) Remove Parameter from Event Note: - This test file must be called from the Open 3D Engine Editor command terminal From 05a0e063a22edab79891fc6c7b34e61675334121 Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Wed, 26 May 2021 10:38:04 -0700 Subject: [PATCH 158/811] Also making Auton->Auth Getters requiring controller --- .../Code/Source/AutoGen/AutoComponent_Header.jinja | 2 -- .../Code/Source/AutoGen/AutoComponent_Source.jinja | 8 +++----- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index aeab2e88e1..96c5433ce0 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -440,7 +440,6 @@ namespace {{ Component.attrib['Namespace'] }} {% endif %} {{ DeclareNetworkPropertyGetters(Component, 'Authority', 'Server', false)|indent(8) -}} - {{ DeclareNetworkPropertyGetters(Component, 'Autonomous', 'Authority', false)|indent(8) -}} {{ DeclareNetworkPropertyGetters(Component, 'Authority', 'Client', false)|indent(8) -}} {{ DeclareArchetypePropertyGetters(Component)|indent(8) -}} {{ DeclareRpcInvocations(Component, 'Server', 'Authority', false)|indent(8) -}} @@ -465,7 +464,6 @@ namespace {{ Component.attrib['Namespace'] }} //! @} {{ DeclareNetworkPropertyGetters(Component, 'Authority', 'Server', true)|indent(8) -}} - {{ DeclareNetworkPropertyGetters(Component, 'Autonomous', 'Authority', true)|indent(8) -}} {{ DeclareNetworkPropertyGetters(Component, 'Authority', 'Client', true)|indent(8) -}} {{ DeclareRpcInvocations(Component, 'Server', 'Authority', true)|indent(8) -}} {{ AutoComponentMacros.DeclareRpcHandlers(Component, 'Authority', 'Client', false)|indent(8) -}} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 3ca4d854bb..b782d7e583 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -767,15 +767,15 @@ enum class NetworkProperties return {{ Property.attrib['Type'] }}(); } - {{ ClassName }}* networkComponent = entity->FindComponent<{{ ClassName }}>(); + {{ ClassName }}* networkComponent = entity->FindComponent<{{ ClassName }}>(); if (!networkComponent) { AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }} failed. Entity '%s' (id: %s) is missing {{ ClassName }}, be sure to add {{ ClassName }} to this entity.", entity->GetName().c_str(), id.ToString().c_str()) return {{ Property.attrib['Type'] }}(); } -{% if ReplicateTo == 'Autonomous' %} +{% if (ReplicateTo == 'Autonomous') or (ReplicateFrom == 'Autonomous' and ReplicateTo == 'Authority') %} - // {{ UpperFirst(Property.attrib['Name']) }} is replicated to Automonous; we must go through the controller in order to get this property + // {{ UpperFirst(Property.attrib['Name']) }} is only sent and received between contoller objects (ie Authority, Autonomous); we must go through the controller in order to get this property {{ ClassName }}Controller* controller = static_cast<{{ ClassName }}Controller*>(networkComponent->GetController()); if (!controller) { @@ -1472,10 +1472,8 @@ namespace {{ Component.attrib['Namespace'] }} } {{ DefineNetworkPropertyGets(Component, 'Authority', 'Server', false, ComponentBaseName)|indent(4) -}} -{{ DefineNetworkPropertyGets(Component, 'Autonomous', 'Authority', false, ComponentBaseName)|indent(4) -}} {{ DefineNetworkPropertyGets(Component, 'Authority', 'Client', false, ComponentBaseName)|indent(4) -}} {{ DefineNetworkPropertyGets(Component, 'Authority', 'Server', true, ComponentBaseName)|indent(4) -}} -{{ DefineNetworkPropertyGets(Component, 'Autonomous', 'Authority', true, ComponentBaseName)|indent(4) -}} {{ DefineNetworkPropertyGets(Component, 'Authority', 'Client', true, ComponentBaseName)|indent(4) }} {{ DefineArchetypePropertyGets(Component, ClassType, ComponentBaseName)|indent(4) -}} {{ DefineRpcInvocations(Component, ComponentBaseName, 'Server', 'Authority', false)|indent(4) -}} From 5a417466832bc875b50f7070dcae0644e7b15568 Mon Sep 17 00:00:00 2001 From: srikappa Date: Wed, 26 May 2021 10:46:00 -0700 Subject: [PATCH 159/811] Fixed a comment and added a forward declaration --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 9 +++++---- .../AzToolsFramework/Prefab/PrefabPublicHandler.h | 3 +-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 7284a9cd95..57e3c87501 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -10,8 +10,6 @@ * */ -#include - #include #include #include @@ -28,11 +26,14 @@ #include #include #include +#include #include #include #include #include +#include + namespace AzToolsFramework { namespace Prefab @@ -226,8 +227,8 @@ namespace AzToolsFramework m_instanceToTemplateInterface->GeneratePatch(reparentPatch, containerEntityDomBefore, containerEntityDomAfter); m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(reparentPatch, nestedInstanceContainerEntityId); - // We ar not parenting this undo node to the undo batch because we don't want the user to undo these changes - // so that the newly created template and link remain unaffected for supporting instantiating the template later. + // We won't parent this undo node to the undo batch so that the newly created template and link will remain + // unaffected by undo actions. This is needed so that any future instantiations of the template will work. PrefabUndoLinkUpdate linkUpdate = PrefabUndoLinkUpdate(AZStd::to_string(static_cast(nestedInstanceContainerEntityId))); linkUpdate.Capture(reparentPatch, nestedInstance->GetLinkId()); linkUpdate.Redo(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index a3e2632ea4..7e2357dd44 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -21,7 +21,7 @@ #include #include -#include +class QString; namespace AzToolsFramework { @@ -30,7 +30,6 @@ namespace AzToolsFramework namespace Prefab { class Instance; - class InstanceEntityMapperInterface; class InstanceToTemplateInterface; class PrefabLoaderInterface; From 55b0a93fd6fb0c02ac7f5b6383ae7a05c2553a85 Mon Sep 17 00:00:00 2001 From: Jonny Galloway Date: Wed, 26 May 2021 12:55:22 -0500 Subject: [PATCH 160/811] fixed a typo --- .../DccScriptingInterface/Launchers/Windows/Env_Core.bat | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Launchers/Windows/Env_Core.bat b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Launchers/Windows/Env_Core.bat index 37c5a9c2b9..ab0708defd 100644 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Launchers/Windows/Env_Core.bat +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Launchers/Windows/Env_Core.bat @@ -78,7 +78,7 @@ IF "%LY_PROJECT%"=="" (set LY_PROJECT=%CD%) echo LY_PROJECT = %LY_PROJECT% :: set up the default project path (dccsi) -:: if not set we lso use the DCCsi path as stand-in +:: if not set we also use the DCCsi path as stand-in CD /D ..\..\ IF "%LY_PROJECT_PATH%"=="" (set LY_PROJECT_PATH=%CD%) echo LY_PROJECT_PATH = %LY_PROJECT_PATH% From c8a84d94356fbec1e502cb6e0651d1cf6e1cb214 Mon Sep 17 00:00:00 2001 From: phistere Date: Wed, 26 May 2021 13:10:55 -0500 Subject: [PATCH 161/811] Fixes an include path error with AudioEngineWwise Was missing a build dependency on the AudioSystem.Editor.Static target. --- Gems/AudioEngineWwise/Code/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/AudioEngineWwise/Code/CMakeLists.txt b/Gems/AudioEngineWwise/Code/CMakeLists.txt index 985bb4cf61..75006a1673 100644 --- a/Gems/AudioEngineWwise/Code/CMakeLists.txt +++ b/Gems/AudioEngineWwise/Code/CMakeLists.txt @@ -207,6 +207,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::EditorCore PUBLIC AZ::AssetBuilderSDK + Gem::AudioSystem.Editor.Static Gem::AudioEngineWwise.Static RUNTIME_DEPENDENCIES Gem::AudioSystem.Editor From 0ffaa5429b9f7d608fdb34da8ecf5b6f3e670d45 Mon Sep 17 00:00:00 2001 From: srikappa Date: Wed, 26 May 2021 11:31:16 -0700 Subject: [PATCH 162/811] Fixed a linux build error where an implicit conversion to const ref is not supported --- .../AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp | 2 +- .../AzToolsFramework/AzToolsFramework/Prefab/Link/Link.h | 2 +- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp index 01a954ebdd..2fb22ea8e8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp @@ -234,7 +234,7 @@ namespace AzToolsFramework } } - PrefabDomValueConstReference Link::GetLinkPatches() + PrefabDomValueReference Link::GetLinkPatches() { return PrefabDomUtils::FindPrefabDomValue(m_linkDom, PrefabDomUtils::PatchesName); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.h index 7d30f9235d..c8f43b291e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.h @@ -79,7 +79,7 @@ namespace AzToolsFramework */ void AddLinkIdToInstanceDom(PrefabDomValue& instanceDomValue); - PrefabDomValueConstReference GetLinkPatches(); + PrefabDomValueReference GetLinkPatches(); private: diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 57e3c87501..0181050a32 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -117,7 +117,7 @@ namespace AzToolsFramework auto linkRef = m_prefabSystemComponentInterface->FindLink(detachingInstanceLinkId); AZ_Assert(linkRef.has_value(), "Unable to find link with id '%llu' during prefab creation.", detachingInstanceLinkId); - PrefabDomValueConstReference linkPatches = linkRef->get().GetLinkPatches(); + PrefabDomValueReference linkPatches = linkRef->get().GetLinkPatches(); AZ_Assert( linkPatches.has_value(), "Unable to get patches on link with id '%llu' during prefab creation.", detachingInstanceLinkId); From a66345e7cbbd3be39fa32391dd25a228cac63593 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Wed, 26 May 2021 11:42:25 -0700 Subject: [PATCH 163/811] ATOM-13828 UV Transform Center Default Middle Updated all UV transform property sets for Atom's core material types to have 0.5 as the transform center. --- .../Assets/Materials/Types/EnhancedPBR.materialtype | 4 ++-- .../Common/Assets/Materials/Types/Skin.materialtype | 2 +- .../Materials/Types/StandardMultilayerPBR.materialtype | 8 ++++---- .../Assets/Materials/Types/StandardPBR.materialtype | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index 48b576c768..a085afa327 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -725,7 +725,7 @@ "description": "Center point for scaling and rotation transformations.", "type": "vector2", "vectorLabels": [ "U", "V" ], - "defaultValue": [ 0.0, 0.0 ] + "defaultValue": [ 0.5, 0.5 ] }, { "id": "tileU", @@ -1388,7 +1388,7 @@ "description": "Center point for scaling and rotation transformations.", "type": "vector2", "vectorLabels": [ "U", "V" ], - "defaultValue": [ 0.0, 0.0 ] + "defaultValue": [ 0.5, 0.5 ] }, { "id": "tileU", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype index 101a03b907..044b267645 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype @@ -909,7 +909,7 @@ "description": "Center point for scaling and rotation transformations.", "type": "vector2", "vectorLabels": [ "U", "V" ], - "defaultValue": [ 0.0, 0.0 ] + "defaultValue": [ 0.5, 0.5 ] }, { "id": "tileU", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype index 05ba40ddae..ec1298ae77 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype @@ -444,7 +444,7 @@ "description": "Center point for scaling and rotation transformations.", "type": "vector2", "vectorLabels": [ "U", "V" ], - "defaultValue": [ 0.0, 0.0 ] + "defaultValue": [ 0.5, 0.5 ] }, { "id": "tileU", @@ -1169,7 +1169,7 @@ "description": "Center point for scaling and rotation transformations.", "type": "vector2", "vectorLabels": [ "U", "V" ], - "defaultValue": [ 0.0, 0.0 ] + "defaultValue": [ 0.5, 0.5 ] }, { "id": "tileU", @@ -1875,7 +1875,7 @@ "description": "Center point for scaling and rotation transformations.", "type": "vector2", "vectorLabels": [ "U", "V" ], - "defaultValue": [ 0.0, 0.0 ] + "defaultValue": [ 0.5, 0.5 ] }, { "id": "tileU", @@ -2581,7 +2581,7 @@ "description": "Center point for scaling and rotation transformations.", "type": "vector2", "vectorLabels": [ "U", "V" ], - "defaultValue": [ 0.0, 0.0 ] + "defaultValue": [ 0.5, 0.5 ] }, { "id": "tileU", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index 2d848b2774..04e6c0f501 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -669,7 +669,7 @@ "description": "Center point for scaling and rotation transformations.", "type": "vector2", "vectorLabels": [ "U", "V" ], - "defaultValue": [ 0.0, 0.0 ] + "defaultValue": [ 0.5, 0.5 ] }, { "id": "tileU", From b72cb2c60157896530b61d971e2d437eff9824df Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Wed, 26 May 2021 14:41:08 -0500 Subject: [PATCH 164/811] SPEC-6685: Updating/adding test summaries for TestRail decoupling effort --- ...rfaceMaskFilter_BasicSurfaceTagCreation.py | 19 ++++++++ ...getationInstances_DespawnWhenOutOfRange.py | 19 ++++++++ .../GradientGenerators_Incompatibilities.py | 17 ++++++- .../GradientModifiers_Incompatibilities.py | 17 ++++++- ...ClearingPinnedEntitySetsPreviewToOrigin.py | 13 ----- .../AreaNodes_DependentComponentsAdded.py | 20 ++++++++ .../AreaNodes_EntityCreatedOnNodeAdd.py | 18 +++++++ .../AreaNodes_EntityRemovedOnNodeDelete.py | 19 ++++++++ .../ComponentUpdates_UpdateGraph.py | 48 ++++++++++++------- .../EditorScripts/CreateNewGraph.py | 19 ++++++++ .../Edit_DisabledNodeDuplication.py | 18 +++++++ .../Edit_UndoNodeDelete_SliceEntity.py | 30 +++++++----- .../GradientMixer_NodeConstruction.py | 21 ++++++++ ...entModifierNodes_EntityCreatedOnNodeAdd.py | 19 ++++++++ ...ModifierNodes_EntityRemovedOnNodeDelete.py | 19 ++++++++ .../GradientNodes_DependentComponentsAdded.py | 21 ++++++++ .../GradientNodes_EntityCreatedOnNodeAdd.py | 19 ++++++++ ...GradientNodes_EntityRemovedOnNodeDelete.py | 20 ++++++++ .../GraphClosed_OnEntityDelete.py | 20 ++++++++ .../GraphClosed_OnLevelChange.py | 19 ++++++++ .../EditorScripts/GraphClosed_TabbedGraph.py | 20 ++++++++ .../GraphUpdates_UpdateComponents.py | 40 ++++++++++------ .../LandscapeCanvasComponent_AddedRemoved.py | 20 ++++++++ .../LandscapeCanvas_SliceCreateInstantiate.py | 15 ++++-- .../LayerBlender_NodeConstruction.py | 21 ++++++++ .../LayerExtenderNodes_ComponentEntitySync.py | 19 ++++++++ .../ShapeNodes_EntityCreatedOnNodeAdd.py | 19 ++++++++ .../ShapeNodes_EntityRemovedOnNodeDelete.py | 22 ++++++++- ...otConnections_UpdateComponentReferences.py | 21 ++++++++ 29 files changed, 547 insertions(+), 65 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py index 4f58a23a19..730a557a9e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py @@ -23,6 +23,25 @@ class TestSurfaceMaskFilter_BasicSurfaceTagCreation(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="TestSurfaceMaskFilter_BasicSurfaceTagCreation", args=["level"]) def run_test(self): + """ + Summary: + Verifies basic surface tag value equality + + Expected Behavior: + Surface tags of the same name are equal, and different names aren't. + + Test Steps: + 1) Open level + 2) Create 2 new surface tags of identical names and verify they resolve as equal. + 3) Create another new tag of a different name and verify they resolve as different. + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ self.log("SurfaceTag test started") # Create a level diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py index c25761d655..46c5483988 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py @@ -33,6 +33,25 @@ class TestVegetationInstances_DespawnWhenOutOfRange(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix='VegetationInstances_DespawnWhenOutOfRange', args=['level']) def run_test(self): + """ + Summary: + Verifies that vegetation instances properly spawn/despawn based on camera range. + + Expected Behavior: + Vegetation instances despawn when out of camera range. + + Test Steps: + 1) Create a new level + 2) Create a simple vegetation area, and set the view position near the spawner. Verify instances plant. + 3) Move the view position away from the spawner. Verify instances despawn. + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ # Create a new level self.test_success = self.create_level( diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py index cc9a15bba0..c37bc9780f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py @@ -28,8 +28,21 @@ class TestGradientGeneratorIncompatibilities(EditorTestHelper): def run_test(self): """ Summary: - Verify that Entities are not active when a Gradient Generator and incompatible component are both present - on the same Entity. + This test verifies that components are disabled when conflicting components are present on the same entity. + + Expected Behavior: + Gradient Generator components are incompatible with Vegetation area components. + + Test Steps: + 1) Create a new level + 2) Create a new entity in the level + 3) Add each Gradient Generator component to an entity, and add a Vegetation Area component to the same entity + 4) Verify that components are only enabled when entity is free of a conflicting component + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. :return: None """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py index b7d12d074a..f2edc2924e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py @@ -28,8 +28,21 @@ class TestGradientModifiersIncompatibilities(EditorTestHelper): def run_test(self): """ Summary: - Verify that Entities are not active when a Gradient Modifier and incompatible component are both present - on the same Entity. + This test verifies that components are disabled when conflicting components are present on the same entity. + + Expected Behavior: + Gradient Modifier components are incompatible with Vegetation area components. + + Test Steps: + 1) Create a new level + 2) Create a new entity in the level + 3) Add each Gradient Modifier component to an entity, and add a Vegetation Area component to the same entity + 4) Verify that components are only enabled when entity is free of a conflicting component + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. :return: None """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py index c37ee36265..45da74d6cd 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py @@ -9,19 +9,6 @@ remove or modify any license notices. This file is distributed on an "AS IS" BAS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ -""" -The below cases are combined in this script -C2676829 -C3961326 -C3980659 -C3980664 -C3980669 -C3416548 -C2676823 -C3961321 -C2676826 -""" - import os import sys diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py index d1e0b68ef4..c41d153cfa 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py @@ -33,6 +33,26 @@ class TestAreaNodeComponentDependency(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="AreaNodeComponentDependency", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities with + proper dependent components. + + Expected Behavior: + All expected component dependencies are met when adding an area node to a graph. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the area nodes to the graph area, and ensure the proper dependent components are added + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newEntityId diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py index 4e429a192b..fb977b4987 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py @@ -33,7 +33,25 @@ class TestGradientNodeEntityCreate(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="AreaNodeEntityCreate", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. + Expected Behavior: + New entities are created when dragging area nodes to graph area. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the area nodes to the graph area, and ensure a new entity is created + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newEntityId newEntityId = parameters[0] diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py index 38f8641b4c..57ba8fc006 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py @@ -34,7 +34,26 @@ class TestAreaNodeEntityDelete(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="AreaNodeEntityDelete", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. + Expected Behavior: + Entities are removed when area nodes are deleted from a graph. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the area nodes to the graph area, and ensure a new entity is created + 4) Delete the nodes, and ensure the newly created entities are removed + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global createdEntityId createdEntityId = parameters[0] diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py index 26062c01f8..60527b64d2 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py @@ -9,24 +9,6 @@ remove or modify any license notices. This file is distributed on an "AS IS" BAS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ - -""" -C22602072 - Graph is updated when underlying components are added/removed - -1. Open Level. -2. Find LandscapeCanvas named entity. -3. Ensure Vegetation Distribution Component is present on the BushSpawner entity. -4. Open graph and ensure Distribution Filter wrapped node is present. -5. Delete the Vegetation Distribution Filter component from the BushSpawner entity via Entity Inspector. -6. Ensure the Vegetation Distribution Filter component was deleted from the BushSpawner entity and node is no longer -present in the graph. -7. Add Vegetation Altitude Filter to the BushSpawner entity through Entity Inspector. -8. Ensure Altitude Filter was added to the BushSpawner node in the open graph. -9. Add a new entity with unique name as a child of the Landscape Canvas entity. -10. Add a Box Shape component to the new child entity. -11. Ensure Box Shape node is present on the open graph. -""" - import os import sys @@ -50,6 +32,36 @@ class TestComponentUpdatesUpdateGraph(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="ComponentUpdatesUpdateGraph", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas graphs update properly when components are added/removed outside of + Landscape Canvas. + + Expected Behavior: + Graphs properly reflect component changes made to entities outside of Landscape Canvas. + + Test Steps: + 1. Open Level + 2. Find LandscapeCanvas named entity + 3. Ensure Vegetation Distribution Component is present on the BushSpawner entity + 4. Open graph and ensure Distribution Filter wrapped node is present + 5. Delete the Vegetation Distribution Filter component from the BushSpawner entity via Entity Inspector + 6. Ensure the Vegetation Distribution Filter component was deleted from the BushSpawner entity and node is + no longer present in the graph + 7. Add Vegetation Altitude Filter to the BushSpawner entity through Entity Inspector + 8. Ensure Altitude Filter was added to the BushSpawner node in the open graph + 9. Add a new entity with unique name as a child of the Landscape Canvas entity + 10. Add a Box Shape component to the new child entity + 11. Ensure Box Shape node is present on the open graph + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + # Create a new empty level and instantiate LC_BushFlowerBlender.slice self.test_success = self.create_level( self.args["level"], diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py index 5fed13985d..4b5e03abbc 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py @@ -37,6 +37,25 @@ class TestCreateNewGraph(EditorTestHelper): print("New root entity created") def run_test(self): + """ + Summary: + This test verifies that new graphs can be created in Landscape Canvas. + + Expected Behavior: + New graphs can be created, and proper entity is created to hold graph data with a Landscape Canvas component. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Ensures the root entity created contains a Landscape Canvas component + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ self.test_success = self.create_level( self.args["level"], heightmap_resolution=128, diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py index 7fd3f075e0..81e24b20e1 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py @@ -33,7 +33,25 @@ class TestDisabledNodeDuplication(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="DisabledNodeDuplication", args=["level"]) def run_test(self): + """ + Summary: + This test verifies Editor stability after duplicating disabled Landscape Canvas nodes. + Expected Behavior: + Editor remains stable and free of crashes. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Create several new nodes, disable the nodes via disabling/deleting components, and duplicate the nodes + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newEntityId newEntityId = parameters[0] diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py index 27ab6fded3..61c4cf9ac2 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py @@ -9,17 +9,6 @@ remove or modify any license notices. This file is distributed on an "AS IS" BAS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ - -""" -C30813586 - Editor remains stable after Undoing deletion of a node on a slice entity - -1. Open level with instantiated slice. -2. Open the graph. -3. Find the BushSpawner's Vegetation Layer Spawner node. -4. Delete the node. -5. Undo to restore the node. -""" - import os import sys @@ -44,7 +33,26 @@ class TestUndoNodeDeleteSlice(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="UndoNodeDeleteSlice", args=["level"]) def run_test(self): + """ + Summary: + This test verifies Editor stability after undoing the deletion of nodes on a slice entity. + Expected Behavior: + Editor remains stable and free of crashes. + + Test Steps: + 1) Create a new level + 2) Instantiate a slice with a Landscape Canvas setup + 3) Find a specific node on the graph, and delete it + 4) Restore the node with Undo + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ # Create a new empty level and instantiate LC_BushFlowerBlender.slice self.test_success = self.create_level( self.args["level"], diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py index ca3bc04f47..124baf9d2e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py @@ -34,6 +34,27 @@ class TestGradientMixerNodeConstruction(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="GradientMixerNodeConstruction", args=["level"]) def run_test(self): + """ + Summary: + This test verifies a Gradient Mixer vegetation setup can be constructed through Landscape Canvas. + + Expected Behavior: + Entities contain all required components and component references after creating nodes and setting connections + on a Landscape Canvas graph. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Add all necessary nodes to the graph and set connections to form a Gradient Mixer setup + 4) Verify all components and component references were properly set during graph construction + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newEntityId diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py index d40b19e7db..aa98eb3dc3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py @@ -33,6 +33,25 @@ class TestGradientModifierNodeEntityCreate(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="GradientModifierNodeEntityCreate", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. + + Expected Behavior: + New entities are created when dragging Gradient Modifier nodes to graph area. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the Gradient Modifier nodes to the graph area, and ensure a new entity is created + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newEntityId diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py index dc263924d1..6a82b05039 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py @@ -34,7 +34,26 @@ class TestGradientModifierNodeEntityDelete(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="GradientModifierNodeEntityDelete", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. + Expected Behavior: + Entities are removed when Gradient Modifier nodes are deleted from a graph. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the Gradient Modifier nodes to the graph area, and ensure a new entity is created + 4) Delete the nodes, and ensure the newly created entities are removed + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global createdEntityId createdEntityId = parameters[0] diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py index 5e203e1892..f9360fe356 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py @@ -33,6 +33,27 @@ class TestGradientNodeComponentDependency(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="GradientNodeComponentDependency", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities with + proper dependent components. + + Expected Behavior: + All expected component dependencies are met when adding a Gradient Modifier node to a graph. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the Gradient Modifier nodes to the graph area, and ensure the proper dependent components are + added + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newEntityId diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py index 6d4a2f58a7..8aaad9b81d 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py @@ -32,6 +32,25 @@ class TestGradientNodeEntityCreate(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="GradientNodeEntityCreate", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. + + Expected Behavior: + New entities are created when dragging Gradient nodes to graph area. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the Gradient nodes to the graph area, and ensure a new entity is created + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newEntityId diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py index 2b49e3a911..d74b86d0bf 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py @@ -34,6 +34,26 @@ class TestGradientNodeEntityDelete(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="GradientNodeEntityDelete", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. + + Expected Behavior: + Entities are removed when Gradient nodes are deleted from a graph. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the Gradient nodes to the graph area, and ensure a new entity is created + 4) Delete the nodes, and ensure the newly created entities are removed + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global createdEntityId diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py index d3ad5c1c1e..6aa539b554 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py @@ -31,6 +31,26 @@ class TestGraphClosedOnEntityDelete(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="GraphClosedOnEntityDelete", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that Landscape Canvas graphs are auto-closed when the corresponding entity is deleted. + + Expected Behavior: + When a Landscape Canvas root entity is deleted, the corresponding graph automatically closes. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Delete the automatically created entity + 4) Verify the open graph is closed + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newRootEntityId diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py index b7b0008eb2..ebc75ab621 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py @@ -29,7 +29,26 @@ class TestGraphClosedOnLevelChange(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="GraphClosedOnLevelChange", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that Landscape Canvas graphs are auto-closed when the currently open level changes. + Expected Behavior: + When a new level is loaded in the Editor, open Landscape Canvas graphs are automatically closed. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Open a different level + 4) Verify the open graph is closed + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ # Create a new empty level self.test_success = self.create_level( self.args["level"], diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py index efd1cc5a55..4b018aeb45 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py @@ -29,6 +29,26 @@ class TestGraphClosedTabbedGraph(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="GraphClosedTabbedGraph", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that Landscape Canvas tabbed graphs can be independently closed. + + Expected Behavior: + Closing a tabbed graph only closes the appropriate graph. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create several new graphs + 3) Close one of the open graphs + 4) Ensure the graph properly closed, and other open graphs remain open + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ # Create a new empty level self.test_success = self.create_level( diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py index f350d37178..f94a6c2e3a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py @@ -9,21 +9,6 @@ remove or modify any license notices. This file is distributed on an "AS IS" BAS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ - -""" -C22715182 - Components are updated when nodes are added/removed/updated - -1. Open Level. -2. Open the graph on LC_BushFlowerBlender.slice -3. Find the Rotation Modifier node on the BushSpawner entity -4. Delete the Rotation Modifier node -5. Ensure the Vegetation Rotation Modifier component is removed from the BushSpawner entity -6. Delete the Vegetation Layer Spawner node from the graph -7. Ensure BushSpawner entity is deleted -8. Change connection from second Rotation Modifier node to a different Gradient -9. Ensure Gradient reference on component is updated -""" - import os import sys @@ -50,6 +35,31 @@ class TestGraphUpdatesUpdateComponents(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="GraphUpdatesUpdateComponents", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that components are properly updated as nodes are added/removed/updated. + + Expected Behavior: + Landscape Canvas node CRUD properly updates component entities. + + Test Steps: + 1. Open Level. + 2. Open the graph on LC_BushFlowerBlender.slice + 3. Find the Rotation Modifier node on the BushSpawner entity + 4. Delete the Rotation Modifier node + 5. Ensure the Vegetation Rotation Modifier component is removed from the BushSpawner entity + 6. Delete the Vegetation Layer Spawner node from the graph + 7. Ensure BushSpawner entity is deleted + 8. Change connection from second Rotation Modifier node to a different Gradient + 9. Ensure Gradient reference on component is updated + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ # Create a new empty level and instantiate LC_BushFlowerBlender.slice self.test_success = self.create_level( self.args["level"], diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py index 176429885f..c3857e1393 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py @@ -30,6 +30,26 @@ class TestLandscapeCanvasComponentAddedRemoved(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="LandscapeCanvasComponentAddedRemoved", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas component can be added to/removed from an entity. + + Expected Behavior: + Closing a tabbed graph only closes the appropriate graph. + + Test Steps: + 1) Create a new level + 2) Create a new entity + 3) Add a Landscape Canvas component to the entity + 4) Remove the Landscape Canvas component from the entity + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ # Create a new empty level self.test_success = self.create_level( diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py index e0f13adaa9..f174a52610 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py @@ -30,12 +30,21 @@ class TestLandscapeCanvasSliceCreateInstantiate(EditorTestHelper): def run_test(self): """ Summary: - C22602016 A slice containing the LandscapeCanvas component can be created/instantiated. + A slice containing the LandscapeCanvas component can be created/instantiated. Expected Result: - Slice is created and processed successfully and free of errors/warnings. - Another copy of the slice is instantiated. + Slice is created/processed/instantiated successfully and free of errors/warnings. + Test Steps: + 1) Create a new level + 2) Create a new entity with a Landscape Canvas component + 3) Create a slice of the new entity + 4) Instantiate a new copy of the slice + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. :return: None """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py index ecc529b9b4..82a2abf5ea 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py @@ -34,6 +34,27 @@ class TestLayerBlenderNodeConstruction(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="LayerBlenderNodeConstruction", args=["level"]) def run_test(self): + """ + Summary: + This test verifies a Layer Blender vegetation setup can be constructed through Landscape Canvas. + + Expected Behavior: + Entities contain all required components and component references after creating nodes and setting connections + on a Landscape Canvas graph. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Add all necessary nodes to the graph and set connections to form a Layer Blender setup + 4) Verify all components and component references were properly set during graph construction + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newEntityId diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py index 00fcb5170c..df3c549fff 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py @@ -34,6 +34,25 @@ class TestLayerExtenderNodeComponentEntitySync(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="LayerExtenderNodeComponentEntitySync", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that all wrapped nodes can be successfully added to/removed from parent nodes. + + Expected Behavior: + All wrapped extender nodes can be added to/removed from appropriate parent nodes. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Add Area Blender and Layer Spawner nodes to the graph, and add/remove each extender node to/from each + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newEntityId diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py index bd10e5f4c6..cd4915ea24 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py @@ -33,6 +33,25 @@ class TestShapeNodeEntityCreate(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="ShapeNodeEntityCreate", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. + + Expected Behavior: + New entities are created when dragging shape nodes to graph area. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the shape nodes to the graph area, and ensure a new entity is created + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ def onEntityCreated(parameters): global newEntityId diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py index f71f5ae906..fcfbe03576 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py @@ -34,7 +34,27 @@ class TestShapeNodeEntityDelete(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="ShapeNodeEntityDelete", args=["level"]) def run_test(self): - + """ + Summary: + This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. + + Expected Behavior: + Entities are removed when shape nodes are deleted from a graph. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the shape nodes to the graph area, and ensure a new entity is created + 4) Delete the nodes, and ensure the newly created entities are removed + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + def onEntityCreated(parameters): global createdEntityId createdEntityId = parameters[0] diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py index 968f39c64d..183c3f7ccb 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py @@ -33,6 +33,27 @@ class TestSlotConnectionsUpdateComponents(EditorTestHelper): EditorTestHelper.__init__(self, log_prefix="SlotConnectionsUpdateComponents", args=["level"]) def run_test(self): + """ + Summary: + This test verifies that the Landscape Canvas slot connections properly update component references. + + Expected Behavior: + A reference created through slot connections in Landscape Canvas is reflected in the Entity Inspector. + + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Several nodes are added to a graph, and connections are set between the nodes + 4) Component references are verified via Entity Inspector + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + # Retrieve the proper component TypeIds per component name componentNames = [ 'Random Noise Gradient', From b68b9000a380244de730230cd19a1ecf500f03c4 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Wed, 26 May 2021 14:55:38 -0500 Subject: [PATCH 165/811] Fixed extra qualification causing compile error on Mac. --- Code/Tools/SerializeContextTools/SliceConverter.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Tools/SerializeContextTools/SliceConverter.h b/Code/Tools/SerializeContextTools/SliceConverter.h index 8dba6a0e55..a977095f02 100644 --- a/Code/Tools/SerializeContextTools/SliceConverter.h +++ b/Code/Tools/SerializeContextTools/SliceConverter.h @@ -52,7 +52,7 @@ namespace AZ static bool ConvertNestedSlices( SliceComponent* sliceComponent, AzToolsFramework::Prefab::Instance* sourceInstance, AZ::SerializeContext* serializeContext, bool isDryRun); - static bool SliceConverter::ConvertSliceInstance( + static bool ConvertSliceInstance( AZ::SliceComponent::SliceInstance& instance, AZ::Data::Asset& sliceAsset, AzToolsFramework::Prefab::TemplateReference nestedTemplate, AzToolsFramework::Prefab::Instance* topLevelInstance); static void PrintPrefab(AzToolsFramework::Prefab::TemplateId templateId); From da24f4ccde790f32e76fda0aa9be25fe37305534 Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Wed, 26 May 2021 13:17:16 -0700 Subject: [PATCH 166/811] Launch editor from Project Manager --- .../Resources/ProjectManager.qss | 7 +++ .../Source/ProjectButtonWidget.cpp | 30 ++++++++++- .../Source/ProjectButtonWidget.h | 10 ++++ .../Source/ProjectsHomeScreen.cpp | 52 ++++++++++++++++++- 4 files changed, 96 insertions(+), 3 deletions(-) diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qss b/Code/Tools/ProjectManager/Resources/ProjectManager.qss index 16ef48ee7c..849c9cbf5c 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qss +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qss @@ -71,3 +71,10 @@ QPushButton:focus { margin: 10px 0 10px 30px; } +#labelButtonOverlay { + background-color: rgba(50,50,50,200); + min-width:210px; + max-width:210px;; + min-height:278px; + max-height:278px; +} diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp index ec1acdad61..dada54b1a2 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp @@ -31,11 +31,30 @@ namespace O3DE::ProjectManager LabelButton::LabelButton(QWidget* parent) : QLabel(parent) { + m_overlayLabel = new QLabel("", this); + m_overlayLabel->setObjectName("labelButtonOverlay"); + m_overlayLabel->setWordWrap(true); + m_overlayLabel->setAlignment(Qt::AlignCenter); + m_overlayLabel->setVisible(false); } void LabelButton::mousePressEvent([[maybe_unused]] QMouseEvent* event) { - emit triggered(); + if(m_enabled) + { + emit triggered(); + } + } + + void LabelButton::SetEnabled(bool enabled) + { + m_enabled = enabled; + m_overlayLabel->setVisible(!enabled); + } + + void LabelButton::SetOverlayText(const QString& text) + { + m_overlayLabel->setText(text); } ProjectButton::ProjectButton(const QString& projectName, QWidget* parent) @@ -99,4 +118,13 @@ namespace O3DE::ProjectManager #endif } + void ProjectButton::SetButtonEnabled(bool enabled) + { + m_projectImageLabel->SetEnabled(enabled); + } + + void ProjectButton::SetButtonOverlayText(const QString& text) + { + m_projectImageLabel->SetOverlayText(text); + } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h index c1aee8e63e..43efaa1136 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h @@ -32,11 +32,18 @@ namespace O3DE::ProjectManager explicit LabelButton(QWidget* parent = nullptr); ~LabelButton() = default; + void SetEnabled(bool enabled); + void SetOverlayText(const QString& text); + signals: void triggered(); public slots: void mousePressEvent(QMouseEvent* event) override; + + private: + QLabel* m_overlayLabel; + bool m_enabled = true; }; class ProjectButton @@ -49,6 +56,9 @@ namespace O3DE::ProjectManager explicit ProjectButton(const QString& projectName, const QString& projectImage, QWidget* parent = nullptr); ~ProjectButton() = default; + void SetButtonEnabled(bool enabled); + void SetButtonOverlayText(const QString& text); + signals: void OpenProject(const QString& projectName); void EditProject(const QString& projectName); diff --git a/Code/Tools/ProjectManager/Source/ProjectsHomeScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectsHomeScreen.cpp index 411b46c55d..6c60685358 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsHomeScreen.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectsHomeScreen.cpp @@ -14,6 +14,12 @@ #include #include +#include +#include +#include +#include +#include +#include #include #include @@ -27,6 +33,8 @@ #include #include #include +#include +#include namespace O3DE::ProjectManager { @@ -127,8 +135,48 @@ namespace O3DE::ProjectManager } void ProjectsHomeScreen::HandleOpenProject(const QString& projectPath) { - // Open the editor with this project open - emit NotifyCurrentProject(projectPath); + if (!projectPath.isEmpty()) + { + AZ::IO::FixedMaxPath executableDirectory = AZ::Utils::GetExecutableDirectory(); + AZStd::string executableFilename = "Editor"; + AZ::IO::FixedMaxPath editorExecutablePath = executableDirectory / (executableFilename + AZ_TRAIT_OS_EXECUTABLE_EXTENSION); + auto cmdPath = AZ::IO::FixedMaxPathString::format("%s -regset=\"/Amazon/AzCore/Bootstrap/project_path=%s\"", editorExecutablePath.c_str(), projectPath.toStdString().c_str()); + + AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; + processLaunchInfo.m_commandlineParameters = cmdPath; + bool launchSucceeded = AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo); + if (!launchSucceeded) + { + AZ_Error("ProjectManager", false, "Failed to launch editor"); + QMessageBox::critical( this, tr("Error"), tr("Failed to launch the Editor, please verify the project settings are valid.")); + } + else + { + // prevent the user from accidentally pressing the button while the editor is launching + // and let them know what's happening + ProjectButton* button = qobject_cast(sender()); + if (button) + { + button->SetButtonEnabled(false); + button->SetButtonOverlayText(tr("Opening Editor...")); + } + + // enable the button after 3 seconds + constexpr int waitTimeInMs = 3000; + QTimer::singleShot(waitTimeInMs, this, [this, button] { + if (button) + { + button->SetButtonEnabled(true); + } + }); + } + } + else + { + AZ_Error("ProjectManager", false, "Cannot open editor because an empty project path was provided"); + QMessageBox::critical( this, tr("Error"), tr("Failed to launch the Editor because the project path is invalid.")); + } + } void ProjectsHomeScreen::HandleEditProject(const QString& projectPath) { From 0678dec64ef62f23cc49b3ce783ec55594684c5f Mon Sep 17 00:00:00 2001 From: galibzon <66021303+galibzon@users.noreply.github.com> Date: Wed, 26 May 2021 15:23:11 -0500 Subject: [PATCH 167/811] =?UTF-8?q?[ATOM-15618]=20Shader=20Build=20Pipelin?= =?UTF-8?q?e:=20Add=20UnitTest=20To=20Validate=20Shader=20C=E2=80=A6=20(#9?= =?UTF-8?q?18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [ATOM-15618] Shader Build Pipeline: Add UnitTest To Validate Shader Compiler Argument Processing Introduced With The New Supervariant System - Added new test suite in Gems/Atom/Asset/Shader/Code/Tests/SupervariantCmdArgumentTests.cpp - Refactored and improved the previously existing classes: GlobalBuildOptions, PreprocessorOptions and ShaderCompilerArguments to work well with the new ShaderSourceData::SupervariantInfo. - Moved command line argument processing function out of ShaderCompilerArguments and into its own utility namespace in Atom/RHI.Edit/Utils.h Signed-off-by: garrieta --- Gems/Atom/Asset/Shader/Code/CMakeLists.txt | 33 ++ .../Editor/CommonFiles/Preprocessor.cpp | 34 +- .../Source/Editor/ShaderAssetBuilder2.cpp | 3 +- .../Tests/Common/ShaderBuilderTestFixture.cpp | 41 ++ .../Tests/Common/ShaderBuilderTestFixture.h | 34 ++ .../Tests/SupervariantCmdArgumentTests.cpp | 523 ++++++++++++++++++ ...om_asset_shader_builders_tests_files.cmake | 16 + .../Atom/RHI.Edit/ShaderCompilerArguments.h | 9 + .../RHI/Code/Include/Atom/RHI.Edit/Utils.h | 40 ++ .../RHI.Edit/ShaderCompilerArguments.cpp | 14 +- Gems/Atom/RHI/Code/Source/RHI.Edit/Utils.cpp | 59 ++ Gems/Atom/RPI/Code/CMakeLists.txt | 1 + .../RPI.Edit/Shader/ShaderSourceData.cpp | 87 ++- 13 files changed, 820 insertions(+), 74 deletions(-) create mode 100644 Gems/Atom/Asset/Shader/Code/Tests/Common/ShaderBuilderTestFixture.cpp create mode 100644 Gems/Atom/Asset/Shader/Code/Tests/Common/ShaderBuilderTestFixture.h create mode 100644 Gems/Atom/Asset/Shader/Code/Tests/SupervariantCmdArgumentTests.cpp create mode 100644 Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake diff --git a/Gems/Atom/Asset/Shader/Code/CMakeLists.txt b/Gems/Atom/Asset/Shader/Code/CMakeLists.txt index a06aa79d24..dd8afec534 100644 --- a/Gems/Atom/Asset/Shader/Code/CMakeLists.txt +++ b/Gems/Atom/Asset/Shader/Code/CMakeLists.txt @@ -101,3 +101,36 @@ ly_add_target( 3rdParty::SPIRVCross 3rdParty::azslc ) + +################################################################################ +# Tests +################################################################################ +if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) + + ly_add_target( + NAME Atom_Asset_Shader.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAMESPACE Gem + FILES_CMAKE + atom_asset_shader_builders_tests_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + . + Source/Editor + Tests + BUILD_DEPENDENCIES + PRIVATE + AZ::AtomCore + AZ::AzTest + AZ::AzFramework + AZ::AzToolsFramework + Legacy::CryCommon + Gem::Atom_RPI.Public + Gem::Atom_RHI.Public + Gem::Atom_RPI.Edit + Gem::Atom_Asset_Shader.Static + ) + ly_add_googletest( + NAME Gem::Atom_Asset_Shader.Tests + ) + +endif() diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.cpp index 1e471f8644..14193d774f 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.cpp @@ -60,33 +60,31 @@ namespace AZ void PreprocessorOptions::RemovePredefinedMacros(const AZStd::vector& macroNames) { + for (const auto& macroName : macroNames) + { m_predefinedMacros.erase( AZStd::remove_if( m_predefinedMacros.begin(), m_predefinedMacros.end(), - [&](const AZStd::string& predefinedMacro) - { - for (const auto& macroName : macroNames) + [&](const AZStd::string& predefinedMacro) { + // Haystack, needle, bCaseSensitive + if (!AzFramework::StringFunc::StartsWith(predefinedMacro, macroName, true)) { - // Haystack, needle, bCaseSensitive - if (!AzFramework::StringFunc::StartsWith(predefinedMacro, macroName, true)) - { - return false; - } - // If found, let's make sure it is not just a substring. - if (predefinedMacro.size() == macroName.size()) - { - return true; - } - // The predefinedMacro can be a string like "macro=value". If we find '=' it is a match. - if (predefinedMacro.c_str()[macroName.size()] == '=') - { - return true; - } return false; } + // If found, let's make sure it is not just a substring. + if (predefinedMacro.size() == macroName.size()) + { + return true; + } + // The predefinedMacro can be a string like "macro=value". If we find '=' it is a match. + if (predefinedMacro.c_str()[macroName.size()] == '=') + { + return true; + } return false; }), m_predefinedMacros.end()); + } } //! Binder helper to Matsui C-Pre-Processor library diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder2.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder2.cpp index 1668b57866..5758db1da2 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder2.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder2.cpp @@ -344,8 +344,7 @@ namespace AZ AZStd::string prependedAzslFilePath = RHI::PrependFile(args); if (prependedAzslFilePath == azslFullPath) { - // For some reason the combined azsl file was not created in the temporary - // directory assigned to this job. + // The specific error is already reported by RHI::PrependFile(). response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed; return; } diff --git a/Gems/Atom/Asset/Shader/Code/Tests/Common/ShaderBuilderTestFixture.cpp b/Gems/Atom/Asset/Shader/Code/Tests/Common/ShaderBuilderTestFixture.cpp new file mode 100644 index 0000000000..276c225e05 --- /dev/null +++ b/Gems/Atom/Asset/Shader/Code/Tests/Common/ShaderBuilderTestFixture.cpp @@ -0,0 +1,41 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include "ShaderBuilderTestFixture.h" + +#include +#include + +namespace UnitTest +{ + void ShaderBuilderTestFixture::SetUp() + { + AllocatorsTestFixture::SetUp(); + + AZ::AllocatorInstance::Create(); + AZ::AllocatorInstance::Create(); + + AZ::NameDictionary::Create(); + } + + void ShaderBuilderTestFixture::TearDown() + { + AZ::NameDictionary::Destroy(); + + AZ::AllocatorInstance::Destroy(); + AZ::AllocatorInstance::Destroy(); + + AllocatorsTestFixture::TearDown(); + } + +} + diff --git a/Gems/Atom/Asset/Shader/Code/Tests/Common/ShaderBuilderTestFixture.h b/Gems/Atom/Asset/Shader/Code/Tests/Common/ShaderBuilderTestFixture.h new file mode 100644 index 0000000000..450cc6bde5 --- /dev/null +++ b/Gems/Atom/Asset/Shader/Code/Tests/Common/ShaderBuilderTestFixture.h @@ -0,0 +1,34 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include + +namespace UnitTest +{ + /** + * Unit test fixture for setting up memory allocation pools and the AZ::Name dictionary. + * In the future will be extended as needed. + */ + class ShaderBuilderTestFixture + : public AllocatorsTestFixture + { + protected: + /////////////////////////////////////////////////////////////////////// + // AllocatorsTestFixture overrides + void SetUp() override; + void TearDown() override; + /////////////////////////////////////////////////////////////////////// + }; +} // namespace UnitTest + diff --git a/Gems/Atom/Asset/Shader/Code/Tests/SupervariantCmdArgumentTests.cpp b/Gems/Atom/Asset/Shader/Code/Tests/SupervariantCmdArgumentTests.cpp new file mode 100644 index 0000000000..2e5ee3fc09 --- /dev/null +++ b/Gems/Atom/Asset/Shader/Code/Tests/SupervariantCmdArgumentTests.cpp @@ -0,0 +1,523 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include + +#include +#include +#include + +#include + +#include "Common/ShaderBuilderTestFixture.h" + +namespace UnitTest +{ + using namespace AZ; + + struct KeyValueView + { + AZStd::string_view m_key; + AZStd::string_view m_value; + }; + + class SupervariantCmdArgumentTests : public ShaderBuilderTestFixture + { + protected: + static constexpr char MCPP_MACRO1[] = "MACRO1"; + static constexpr char MCPP_VALUE1[] = "VALUE1a"; + static constexpr char MCPP_NEW_VALUE1[] = "VALUE1b"; // Missing A is not a typo + + static constexpr char MCPP_MACRO2[] = "MACRO2"; + static constexpr char MCPP_VALUE2[] = "VALUE2"; + + static constexpr char MCPP_MACRO3[] = "MACRO3"; + static constexpr char MCPP_VALUE3[] = "VALUE3a"; + static constexpr char MCPP_NEW_VALUE3[] = "VALUE3b"; + + static constexpr char MCPP_MACRO4[] = "MACRO4"; + + static constexpr char MCPP_MACRO5[] = "MACRO5"; + + static constexpr char MCPP_MACRO6[] = "MACRO6"; + static constexpr char MCPP_VALUE6[] = "VALUE6"; + + static constexpr char AZSLC_ARG1[] = "--azsl1"; + + static constexpr char AZSLC_ARG2[] = "--azsl2"; + static constexpr char AZSLC_VAL2[] = "open,source"; + static constexpr char AZSLC_NEW_VAL2a[] = "closed,binary"; + static constexpr char AZSLC_NEW_VAL2b[] = "closed,source"; + + static constexpr char AZSLC_ARG3[] = "--azsl3"; + static constexpr char AZSLC_VAL3[] = "blue"; + + static constexpr char AZSLC_ARG4[] = "-azsl4"; + + static constexpr char AZSLC_ARG5[] = "--azsl5"; + static constexpr char AZSLC_VAL5[] = "smith,wick,john,45,-1,-1"; + static constexpr char AZSLC_NEW_VAL5[] = "apple,seed,crisp,-1,2,0"; + + static constexpr char AZSLC_ARG6[] = "--azsl6"; + + static constexpr char AZSLC_ARG7[] = "--azsl7"; + + //! Helper function. + //! Given an input list of {Key, Value} pairs returns a list of strings where each string is of the form: "Key=Value". + AZStd::vector CreateListOfStringsFromListOfKeyValues(AZStd::array_view listOfKeyValues) const + { + AZStd::vector listOfStrings; + for (const auto& keyValue : listOfKeyValues) + { + if (keyValue.m_value.empty()) + { + listOfStrings.push_back(keyValue.m_key); + } + else + { + listOfStrings.push_back(AZStd::string::format("%s=%s", keyValue.m_key.data(), keyValue.m_value.data())); + } + } + return listOfStrings; + } + + //! Helper function. + //! Given an input list of {Key, Value} pairs returns a list of strings where each string is of the form: "Key1", "Value1", "Key2", "Value2". + AZStd::vector CreateListOfSingleStringsFromListOfKeyValues(AZStd::array_view listOfKeyValues) const + { + AZStd::vector listOfStrings; + for (const auto& keyValue : listOfKeyValues) + { + listOfStrings.push_back(keyValue.m_key); + if (!keyValue.m_value.empty()) + { + listOfStrings.push_back(keyValue.m_value); + } + } + return listOfStrings; + } + + //! Helper function. + //! @param outputString: [out] The string " @argName" gets appended to it (The space is intentional). + //! Alternatively, if @argValue is NOT empty, then the string " @argName=@argValue" is + //! appended to it. + //! @param argName: A typical command line argument. "-p" or "--some". + //! @param argValue: A string representing the value that should be appended to @argName. + void AppendCmdLineArgument(AZStd::string& outputString, AZStd::string_view argName, AZStd::string_view argValue) const + { + if (argValue.empty()) + { + outputString += AZStd::string::format(" %s", argName.data()); + } + else + { + outputString += AZStd::string::format(" %s=%s", argName.data(), argValue.data()); + } + } + + //! Helper function. + //! Similar to above, but assumes that @argName refers to just the name of a macro definition so the appended string will always start + //! with "-D". + void AppendMacroDefinitionArgument(AZStd::string& outputString, AZStd::string_view argName, AZStd::string_view argValue) const + { + AppendCmdLineArgument(outputString, AZStd::string::format("-D%s", argName.data()), argValue); + } + + //! A helper made of helpers. + //! Returns a command line string that results of concatenating the input list of {Key, Value} pairs (with '='). + //! Example of a returned string: + //! "key1=value1 key2 key3 key4=value" + AZStd::string CreateCmdLineStringFromListOfKeyValues(AZStd::array_view listOfKeyValues) const + { + AZStd::string cmdLineString; + for (const auto& keyValueView : listOfKeyValues) + { + AppendCmdLineArgument(cmdLineString, keyValueView.m_key, keyValueView.m_value); + } + return cmdLineString; + } + + //! A helper made of helpers. + //! Returns a command line string of macro definitions that results of concatenating the input list of {Key, Value} pairs. + //! Example of a returned string: + //! "-Dkey1=value1 -Dkey2 -Dkey3 -Dkey4=value" + AZStd::string CreateMacroDefinitionCmdLineStringFromListOfKeyValues(AZStd::array_view listOfKeyValues) const + { + AZStd::string cmdLineString; + for (const auto& keyValueView : listOfKeyValues) + { + AppendMacroDefinitionArgument(cmdLineString, keyValueView.m_key, keyValueView.m_value); + } + return cmdLineString; + } + + //! @param includePaths A List of folder paths + //! @param predefinedMacros A List of strings with format: "name[=value]" + ShaderBuilder::PreprocessorOptions CreatePreprocessorOptions( + AZStd::array_view includePaths, AZStd::array_view predefinedMacros) const + { + ShaderBuilder::PreprocessorOptions preprocessorOptions; + + preprocessorOptions.m_projectIncludePaths.reserve(includePaths.size()); + for (const auto& path : includePaths) + { + preprocessorOptions.m_projectIncludePaths.push_back(path); + } + + preprocessorOptions.m_predefinedMacros.reserve(predefinedMacros.size()); + for (const auto& macro : predefinedMacros) + { + preprocessorOptions.m_predefinedMacros.push_back(macro); + } + + return preprocessorOptions; + } + + //! @param azslcAdditionalFreeArguments: A string representing series of command line arguments for AZSLc. + //! @param dxcAdditionalFreeArguments: A string representing series of command line arguments for DXC. + RHI::ShaderCompilerArguments CreateShaderCompilerArguments( + AZStd::string_view azslcAdditionalFreeArguments, AZStd::string_view dxcAdditionalFreeArguments) const + { + RHI::ShaderCompilerArguments shaderCompilerArguments; + shaderCompilerArguments.m_azslcWarningLevel = 1; + shaderCompilerArguments.m_azslcAdditionalFreeArguments = azslcAdditionalFreeArguments; + shaderCompilerArguments.m_defaultMatrixOrder = RHI::MatrixOrder::Row; + shaderCompilerArguments.m_dxcAdditionalFreeArguments = dxcAdditionalFreeArguments; + + return shaderCompilerArguments; + } + + + //! @param includePaths A List of folder paths + //! @param predefinedMacros A List of strings with format: "name[=value]" + //! @param azslcAdditionalFreeArguments A string representing series of command line arguments for AZSLc. + //! @param dxcAdditionalFreeArguments: A string representing series of command line arguments for DXC. + ShaderBuilder::GlobalBuildOptions CreateGlobalBuildOptions( + AZStd::array_view includePaths, + AZStd::array_view predefinedMacros, + AZStd::string_view azslcAdditionalFreeArguments, + AZStd::string_view dxcAdditionalFreeArguments) const + { + ShaderBuilder::GlobalBuildOptions globalBuildOptions; + globalBuildOptions.m_preprocessorSettings = CreatePreprocessorOptions(includePaths, predefinedMacros); + globalBuildOptions.m_compilerArguments = + CreateShaderCompilerArguments(azslcAdditionalFreeArguments, dxcAdditionalFreeArguments); + return globalBuildOptions; + } + + //! @param name Name of the supervariant. + //! @param plusArguments A string with command line arguments that contains both C-preprocessor macro definitions + //! and other command line arguments for AZSLc. + //! @param minusArguments A string with command line arguments that should be removed from the finalized command line arguments. + //! it can contain both, C-preprocessor macro definitions and other command line arguments for AZSLc. + RPI::ShaderSourceData::SupervariantInfo CreateSupervariantInfo( + AZStd::string_view name, AZStd::string_view plusArguments, AZStd::string_view minusArguments) const + { + RPI::ShaderSourceData::SupervariantInfo supervariantInfo; + supervariantInfo.m_name = name; + supervariantInfo.m_plusArguments = plusArguments; + supervariantInfo.m_minusArguments = minusArguments; + return supervariantInfo; + } + + bool StringContainsAllSubstrings(AZStd::string_view haystack, AZStd::array_view substrings) + { + return AZStd::all_of(AZ_BEGIN_END(substrings), + [&](AZStd::string_view needle) -> bool + { + return (haystack.find(needle) != AZStd::string::npos); + } + ); + } + + bool StringDoesNotContainAnyOneOfTheSubstrings(AZStd::string_view haystack, AZStd::array_view substrings) + { + return AZStd::all_of(AZ_BEGIN_END(substrings), [&](AZStd::string_view needle) -> bool { + return (haystack.find(needle) == AZStd::string::npos); + }); + } + + //! @returns: True if all strings in @substring appear in @vectorOfString. + //! @remark: Keep in mind that this is not the same as saying that all strings in @vectorOfStrings appear in @substrings. + bool VectorContainsAllSubstrings( + AZStd::array_view vectorOfStrings, AZStd::array_view substrings) + { + return AZStd::all_of( + AZ_BEGIN_END(substrings), + [&](AZStd::string_view needle) -> bool { + bool res = AZStd::any_of(AZ_BEGIN_END(vectorOfStrings), + [&](AZStd::string_view haystack) -> bool + { + return haystack.find(needle) != AZStd::string::npos; + } + ); + return res; + } + ); + } + + //! @returns: True only if None of the strings in @vectorOfStrings contains any of the strings in @substrings. + bool VectorDoesNotContainAnyOneOfTheSubstrings(AZStd::array_view vectorOfStrings, AZStd::array_view substrings) + { + return AZStd::all_of(AZ_BEGIN_END(vectorOfStrings), [&](AZStd::string_view haystack) -> bool { + return StringDoesNotContainAnyOneOfTheSubstrings(haystack, substrings); + }); + } + + }; // class SupervariantCmdArgumentTests + + + TEST_F(SupervariantCmdArgumentTests, CommandLineArgumentUtils_ValidateHelperFunctions) + { + // In this test the idea is to validate the static helper functions in AZ::RHI::ShaderCompilerArguments class + // that are useful for command line argument manipulation, etc. + AZStd::vector argumentList = { + {AZSLC_ARG1, ""}, {AZSLC_ARG2, AZSLC_VAL2}, {AZSLC_ARG3, AZSLC_VAL3}, {AZSLC_ARG4, ""}, {AZSLC_ARG5, AZSLC_VAL5}, + }; + + auto argumentsAsString = CreateCmdLineStringFromListOfKeyValues(argumentList); + auto listOfArgumentNames = AZ::RHI::CommandLineArgumentUtils::GetListOfArgumentNames(argumentsAsString); + + EXPECT_TRUE(AZStd::all_of(AZ_BEGIN_END(argumentList), [&](const KeyValueView& needle) -> bool { + return (AZStd::find(AZ_BEGIN_END(listOfArgumentNames), needle.m_key) != listOfArgumentNames.end()) && + // Make sure the values did not make into the expected list of keys. + (AZStd::find(AZ_BEGIN_END(listOfArgumentNames), needle.m_value) == listOfArgumentNames.end()); + })); + + AZStd::vector listOfArgumentsToRemove = { AZSLC_ARG4, AZSLC_ARG2 }; + auto stringWithRemovedArguments = + AZ::RHI::CommandLineArgumentUtils::RemoveArgumentsFromCommandLineString(listOfArgumentsToRemove, argumentsAsString); + EXPECT_TRUE(AZStd::all_of(AZ_BEGIN_END(listOfArgumentsToRemove), [&](const AZStd::string& needle) -> bool { + return stringWithRemovedArguments.find(needle) == AZStd::string::npos; + })); + + AZStd::vector listOfSurvivingArguments = {AZSLC_ARG1, AZSLC_ARG3, AZSLC_ARG5}; + EXPECT_TRUE(AZStd::all_of(AZ_BEGIN_END(listOfSurvivingArguments), [&](const AZStd::string& needle) -> bool { + return stringWithRemovedArguments.find(needle) != AZStd::string::npos; + })); + + auto stringWithoutExtraSpaces = + AZ::RHI::CommandLineArgumentUtils::RemoveExtraSpaces(" --arg1 -arg2 --arg3=foo --arg4=bar "); + EXPECT_EQ(stringWithoutExtraSpaces, AZStd::string("--arg1 -arg2 --arg3=foo --arg4=bar")); + + auto stringAsMergedArguments = + AZ::RHI::CommandLineArgumentUtils::MergeCommandLineArguments("--arg1 -arg2 --arg3=foo", "--arg3=bar --arg4"); + EXPECT_EQ(stringAsMergedArguments, AZStd::string("--arg1 -arg2 --arg3=bar --arg4")); + + EXPECT_TRUE(AZ::RHI::CommandLineArgumentUtils::HasMacroDefinitions("-DMACRO")); + EXPECT_TRUE(AZ::RHI::CommandLineArgumentUtils::HasMacroDefinitions("-D MACRO")); + EXPECT_TRUE(AZ::RHI::CommandLineArgumentUtils::HasMacroDefinitions("--help -D MACRO")); + EXPECT_TRUE(AZ::RHI::CommandLineArgumentUtils::HasMacroDefinitions("--help -p -DMACRO --more")); + EXPECT_TRUE(AZ::RHI::CommandLineArgumentUtils::HasMacroDefinitions("--help -p -D MACRO=VALUE --more")); + EXPECT_FALSE(AZ::RHI::CommandLineArgumentUtils::HasMacroDefinitions("--help -p --more")); + EXPECT_FALSE(AZ::RHI::CommandLineArgumentUtils::HasMacroDefinitions("--help -p --more --DFAKE")); + EXPECT_FALSE(AZ::RHI::CommandLineArgumentUtils::HasMacroDefinitions("--DFAKE1 --help -p --more --D FAKE2")); + } + + TEST_F(SupervariantCmdArgumentTests, ShaderCompilerArguments_ValidateCommandLineArgumentsMerge) + { + // In this test we validate that AZ::RHI::ShaderCompilerArguments::Merge() works as expected + // by merging AZSLC & DXC arguments giving higher priority to the arguments in the "right". + + auto shaderCompilerArgumentsLeft = CreateShaderCompilerArguments( + "--azsl1 --azsl2=avalue2a -azsl3 --azsl4=avalue4a", + "--dxc1=dvalue1a -dxc2 --dxc3=dvalue3a --dxc4"); + auto shaderCompilerArgumentsRight = CreateShaderCompilerArguments( + "--azsl1 --azsl2=avalue2b -azsl3 --azsl4=avalue4a --azsl5", + "--dxc1=dvalue1a -dxc2 --dxc3=dvalue3b --dxc4 --dxc5=dvalue5a"); + + shaderCompilerArgumentsLeft.Merge(shaderCompilerArgumentsRight); + EXPECT_EQ(shaderCompilerArgumentsLeft.m_azslcAdditionalFreeArguments, "--azsl1 --azsl2=avalue2b -azsl3 --azsl4=avalue4a --azsl5"); + EXPECT_EQ(shaderCompilerArgumentsLeft.m_dxcAdditionalFreeArguments, "--dxc1=dvalue1a -dxc2 --dxc3=dvalue3b --dxc4 --dxc5=dvalue5a"); + } + + + TEST_F(SupervariantCmdArgumentTests, SupervariantInfo_ValidateMemberFunctions) + { + // In this test all member functions of the ShaderSourceData::SupervariantInfo class + // are validated. + + AZStd::vector mcppMacrosList = { + {MCPP_MACRO1, MCPP_VALUE1}, + {MCPP_MACRO2, MCPP_VALUE2}, + {MCPP_MACRO3, MCPP_VALUE3}, + {MCPP_MACRO4, ""}, + }; + + AZStd::string argumentsToAddOrReplace; + AppendMacroDefinitionArgument(argumentsToAddOrReplace, MCPP_MACRO3, MCPP_NEW_VALUE3); + AppendCmdLineArgument(argumentsToAddOrReplace, AZSLC_ARG2, AZSLC_NEW_VAL2a); + AppendMacroDefinitionArgument(argumentsToAddOrReplace, MCPP_MACRO1, MCPP_NEW_VALUE1); + AppendCmdLineArgument(argumentsToAddOrReplace, AZSLC_ARG5, AZSLC_NEW_VAL5); + AppendMacroDefinitionArgument(argumentsToAddOrReplace, MCPP_MACRO5, ""); + AppendCmdLineArgument(argumentsToAddOrReplace, AZSLC_ARG6, ""); + + AZStd::string argumentsToRemove; + AppendCmdLineArgument(argumentsToRemove, AZSLC_ARG3, ""); + AppendMacroDefinitionArgument(argumentsToRemove, MCPP_MACRO2, ""); + AppendCmdLineArgument(argumentsToRemove, AZSLC_ARG4, ""); + AppendMacroDefinitionArgument(argumentsToRemove, MCPP_MACRO4, ""); + + auto supervariantInfo = CreateSupervariantInfo("Dummy", argumentsToAddOrReplace, argumentsToRemove); + + auto macroListToRemove = supervariantInfo.GetCombinedListOfMacroDefinitionNamesToRemove(); + AZStd::vector macroNamesToRemoveThatMustBePresent = { MCPP_MACRO1, MCPP_MACRO2, MCPP_MACRO3, MCPP_MACRO4, MCPP_MACRO5 }; + EXPECT_EQ(macroListToRemove.size(), macroNamesToRemoveThatMustBePresent.size()); + EXPECT_TRUE( + VectorContainsAllSubstrings(macroListToRemove, macroNamesToRemoveThatMustBePresent) + ); + + auto macroListToAdd = supervariantInfo.GetMacroDefinitionsToAdd(); + AZStd::vector macroNamesToAddThatMustBePresent = {MCPP_MACRO1, MCPP_MACRO3, MCPP_MACRO5}; + EXPECT_EQ(macroListToAdd.size(), macroNamesToAddThatMustBePresent.size()); + EXPECT_TRUE(VectorContainsAllSubstrings(macroListToAdd, macroNamesToAddThatMustBePresent)); + + // The result of GetCustomizedArgumentsForAzslc() is the most important value to test + AZStd::vector freeAzslcArgumentList = { + {AZSLC_ARG1, ""}, {AZSLC_ARG2, AZSLC_VAL2}, {AZSLC_ARG3, AZSLC_VAL3}, {AZSLC_ARG4, ""}, {AZSLC_ARG5, AZSLC_VAL5}, + }; + AZStd::string azslcArgs = CreateCmdLineStringFromListOfKeyValues(freeAzslcArgumentList); + AZStd::string customizedAzslcArgs = supervariantInfo.GetCustomizedArgumentsForAzslc(azslcArgs); + + AZStd::vector stringsThatMustBePresent = { + AZSLC_ARG1, AZSLC_ARG2, AZSLC_NEW_VAL2a, AZSLC_ARG5, AZSLC_NEW_VAL5, AZSLC_ARG6}; + EXPECT_TRUE(StringContainsAllSubstrings(customizedAzslcArgs, stringsThatMustBePresent)); + + AZStd::vector stringsThatCanNotBePresent = { AZSLC_ARG3, AZSLC_VAL3, AZSLC_ARG4, + // Because GetCustomizedArgumentsForAzslc() only returns arguments for AZSLc, none of the macro related + // arguments can be present + MCPP_MACRO1, MCPP_VALUE1, MCPP_NEW_VALUE1, + MCPP_MACRO2, MCPP_VALUE2, + MCPP_MACRO3, MCPP_VALUE3, MCPP_NEW_VALUE3, + MCPP_MACRO4, + MCPP_MACRO5 + }; + + EXPECT_TRUE( + StringDoesNotContainAnyOneOfTheSubstrings(customizedAzslcArgs, stringsThatCanNotBePresent) + ); + } + + + TEST_F(SupervariantCmdArgumentTests, ShaderAssetBuilder_ValidateInfluenceOfSupervariantInfoOnGlobalBuildOptions) + { + // In this test we validate how the ShaderAssetBuilder configure the commmand line arguments it passes + // to MCPP, AZSLc & DXC. It basically starts with a GlobalBuildOptions, that gets further customized by + // the ShaderCompilerArguments from ShaderSourceData(.shader file) and later further customized + // by each SupervariantInfo in ShaderSourceData. + + // The first step is to define the initial values of the GlobalBuildOptions. + AZStd::vector globalMcppMacrosList = { + {MCPP_MACRO1, MCPP_VALUE1}, + {MCPP_MACRO2, MCPP_VALUE2}, + {MCPP_MACRO3, MCPP_VALUE3}, + {MCPP_MACRO4, ""}, + }; + + AZStd::vector globalAzslArguments = { + {AZSLC_ARG1, ""}, + {AZSLC_ARG2, AZSLC_VAL2}, + {AZSLC_ARG3, AZSLC_VAL3}, + {AZSLC_ARG4, ""}, + {AZSLC_ARG5, AZSLC_VAL5}, + }; + + auto globalBuildOptions = CreateGlobalBuildOptions( + AZStd::vector(), CreateListOfStringsFromListOfKeyValues(globalMcppMacrosList), + CreateCmdLineStringFromListOfKeyValues(globalAzslArguments), + "" /* Don't care about DXC in this test */); + + // The second step is to load the Shader Compiler Arguments from the .shader file. + // These arguments will be merged in @globalBuildOptions, but the .shader arguments have + // higher priority. + AZStd::vector shaderAzslArguments = { + {AZSLC_ARG2, AZSLC_NEW_VAL2a}, + {AZSLC_ARG6, ""}, + }; + auto shaderCompilerArguments = CreateShaderCompilerArguments( + CreateCmdLineStringFromListOfKeyValues(shaderAzslArguments), "" /* Don't care about DXC in this test */); + globalBuildOptions.m_compilerArguments.Merge(shaderCompilerArguments); + + // Let's create the dummy supervariant. It will have some MCPP & AZSLc arguments to be added/replaced AND other MCPP & AZSLc arguments to be removed. + AZStd::vector supervariantAzslArgumentsToAdd = { + {AZSLC_ARG2, AZSLC_NEW_VAL2b}, + {AZSLC_ARG7, ""}, + }; + AZStd::vector supervariantMacroDefinitionsToAdd = { + {MCPP_MACRO1, MCPP_NEW_VALUE1}, + {MCPP_MACRO3, MCPP_NEW_VALUE3}, + {MCPP_MACRO5, ""}, + }; + auto supervariantArgumentsToAdd = CreateCmdLineStringFromListOfKeyValues(supervariantAzslArgumentsToAdd) + + CreateMacroDefinitionCmdLineStringFromListOfKeyValues(supervariantMacroDefinitionsToAdd); + + AZStd::vector supervariantAzslArgumentsToRemove = { + {AZSLC_ARG4, ""}, + {AZSLC_ARG1, ""}, + }; + AZStd::vector supervariantMacrosToRemove = { + {MCPP_MACRO2, ""}, + {MCPP_MACRO4, ""}, + }; + auto supervariantArgumentsToRemove = CreateCmdLineStringFromListOfKeyValues(supervariantAzslArgumentsToRemove) + + CreateMacroDefinitionCmdLineStringFromListOfKeyValues(supervariantMacrosToRemove); + + //CreateMacroDefinitionCmdLineStringFromListOfKeyValues + auto supervariantInfo = CreateSupervariantInfo("Dummy", + supervariantArgumentsToAdd, // These arguments will be added or replace existing ones. + supervariantArgumentsToRemove); // These arguments must be removed. + + AZStd::vector macroDefinitionNamesToRemove = supervariantInfo.GetCombinedListOfMacroDefinitionNamesToRemove(); + globalBuildOptions.m_preprocessorSettings.RemovePredefinedMacros(macroDefinitionNamesToRemove); + AZStd::vector macroDefinitionsToAdd = supervariantInfo.GetMacroDefinitionsToAdd(); + globalBuildOptions.m_preprocessorSettings.m_predefinedMacros.insert( + globalBuildOptions.m_preprocessorSettings.m_predefinedMacros.end(), macroDefinitionsToAdd.begin(), macroDefinitionsToAdd.end()); + + // Validate macro definitions that must be present. + EXPECT_TRUE( + VectorContainsAllSubstrings( + globalBuildOptions.m_preprocessorSettings.m_predefinedMacros, + AZStd::vector({MCPP_MACRO1, MCPP_NEW_VALUE1, MCPP_MACRO3, MCPP_NEW_VALUE3, MCPP_MACRO5})) + ); + + // Validate macro definitions that can't be present. + EXPECT_TRUE( + VectorDoesNotContainAnyOneOfTheSubstrings( + globalBuildOptions.m_preprocessorSettings.m_predefinedMacros, + AZStd::vector({MCPP_MACRO2, MCPP_VALUE3, MCPP_MACRO4})) + ); + + AZStd::string azslcArgsFromGlobalBuildOptions = globalBuildOptions.m_compilerArguments.MakeAdditionalAzslcCommandLineString(); + + // The result of GetCustomizedArgumentsForAzslc() is the most important value to test + AZStd::string customizedAzslcArgs = supervariantInfo.GetCustomizedArgumentsForAzslc(azslcArgsFromGlobalBuildOptions); + + EXPECT_TRUE( + StringContainsAllSubstrings(customizedAzslcArgs, CreateListOfSingleStringsFromListOfKeyValues(supervariantAzslArgumentsToAdd)) + ); + + EXPECT_TRUE( + StringDoesNotContainAnyOneOfTheSubstrings(customizedAzslcArgs, CreateListOfSingleStringsFromListOfKeyValues(supervariantAzslArgumentsToRemove)) + ); + + EXPECT_TRUE( + StringContainsAllSubstrings(customizedAzslcArgs, AZStd::vector({AZSLC_ARG3, AZSLC_VAL3, AZSLC_ARG5, AZSLC_VAL5})) + ); + } + + +} //namespace UnitTest + +AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); + diff --git a/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake b/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake new file mode 100644 index 0000000000..9f22f9f632 --- /dev/null +++ b/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake @@ -0,0 +1,16 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(FILES + Tests/Common/ShaderBuilderTestFixture.h + Tests/Common/ShaderBuilderTestFixture.cpp + Tests/SupervariantCmdArgumentTests.cpp +) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/ShaderCompilerArguments.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/ShaderCompilerArguments.h index 2073c48d25..a5d8f53573 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/ShaderCompilerArguments.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/ShaderCompilerArguments.h @@ -13,6 +13,8 @@ #include #include +#include +#include namespace AZ { @@ -30,9 +32,16 @@ namespace AZ static void Reflect(ReflectContext* context); + //! Returns true if either @m_azslcAdditionalFreeArguments or @m_dxcAdditionalFreeArguments contain + //! macro definitions, e.g. "-D MACRO" or "-D MACRO=VALUE" or "-DMACRO", "-DMACRO=VALUE". + //! It is used for validation to forbid macro definitions, because the idea is that this struct + //! is used inside GlobalBuildOptions which has a dedicated variable for macro definitions. + bool HasMacroDefinitionsInCommandLineArguments(); + //! Mix two instances of arguments, by or-ing bools, or by "if different, right hand side wins" void Merge(const ShaderCompilerArguments& right); + //! [GFX TODO] [ATOM-15472] Remove this function. //! Determine whether there is a rebuild-worthy difference in arguments for AZSLc bool HasDifferentAzslcArguments(const ShaderCompilerArguments& right) const; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/Utils.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/Utils.h index 3e593794af..6f884eb358 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/Utils.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/Utils.h @@ -110,6 +110,46 @@ namespace AZ AZStd::string BuildFileNameWithExtension(const AZStd::string& shaderSourceFile, const AZStd::string& tempFolder, const char* outputExtension); + + namespace CommandLineArgumentUtils + { + //! @param commandLineString: A string with command line arguments of the form: + //! "- -- --[=] ..." + //! Example: "--use-spaces --namespace=vk -W1" + //! Returns: A list with just the [-|--]: + //! ["-", "--", "--arg3"] + //! For the example shown above it will return this vector: + //! ["--use-spaces", "--namespace", "-W1] + AZStd::vector GetListOfArgumentNames(AZStd::string_view commandLineString); + + //! Takes a list of names of command line arguments and removes those arguments from @commandLineString. + //! The core functionality of this function is that it searches by name in @commandLineString and removes + //! name and value if the name is found. + //! @param listOfArguments: This is a list of strings, usually generated by the helper function + //! ShaderCompilerArguments::GetListOfArgumentNames() + //! @param commandLineString: A single string made of several command line arguments + //! @returns A new string based on @commandLineString but with the matching arguments and their values + //! removed from it. + AZStd::string RemoveArgumentsFromCommandLineString( + AZStd::array_view listOfArguments, AZStd::string_view commandLineString); + + //! @param commandLineString: " --arg1 -arg2 --arg3=foo --arg4=bar " + //! @returns "--arg1 -arg2 --arg3=foo --arg4=bar" + AZStd::string RemoveExtraSpaces(AZStd::string_view commandLineString); + + //! Accepts two arbitrary strings that contain typical command line arguments and returns + //! a new string that combines the arguments were the arguments on the @right have precedence. + //! Example: + //! @param left: "--arg1 -arg2 --arg3=foo" + //! @param right: "--arg3=bar --arg4" + //! @returns: "--arg1 -arg2 --arg3=bar --arg4" + AZStd::string MergeCommandLineArguments(AZStd::string_view left, AZStd::string_view right); + + //! @param commandLineString: A string that contains a series of command line arguments. + //! @returns: true if @commandLineString contains macro definitions, e.g: + //! "-D MACRO" or "-D MACRO=VALUE" or "-DMACRO", "-DMACRO=VALUE". + bool HasMacroDefinitions(AZStd::string_view commandLineString); + } } } diff --git a/Gems/Atom/RHI/Code/Source/RHI.Edit/ShaderCompilerArguments.cpp b/Gems/Atom/RHI/Code/Source/RHI.Edit/ShaderCompilerArguments.cpp index 7304a351d4..3a04bf6b88 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Edit/ShaderCompilerArguments.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Edit/ShaderCompilerArguments.cpp @@ -12,6 +12,9 @@ #include #include +#include + +#include namespace AZ { @@ -49,6 +52,12 @@ namespace AZ } } + bool ShaderCompilerArguments::HasMacroDefinitionsInCommandLineArguments() + { + return CommandLineArgumentUtils::HasMacroDefinitions(m_azslcAdditionalFreeArguments) || + CommandLineArgumentUtils::HasMacroDefinitions(m_dxcAdditionalFreeArguments); + } + void ShaderCompilerArguments::Merge(const ShaderCompilerArguments& right) { if (right.m_azslcWarningLevel != LevelUnset) @@ -56,7 +65,7 @@ namespace AZ m_azslcWarningLevel = right.m_azslcWarningLevel; } m_azslcWarningAsError = m_azslcWarningAsError || right.m_azslcWarningAsError; - m_azslcAdditionalFreeArguments += " " + right.m_azslcAdditionalFreeArguments; + m_azslcAdditionalFreeArguments = CommandLineArgumentUtils::MergeCommandLineArguments(m_azslcAdditionalFreeArguments, right.m_azslcAdditionalFreeArguments); m_dxcDisableWarnings = m_dxcDisableWarnings || right.m_dxcDisableWarnings; m_dxcWarningAsError = m_dxcWarningAsError || right.m_dxcWarningAsError; m_dxcDisableOptimizations = m_dxcDisableOptimizations || right.m_dxcDisableOptimizations; @@ -65,13 +74,14 @@ namespace AZ { m_dxcOptimizationLevel = right.m_dxcOptimizationLevel; } - m_dxcAdditionalFreeArguments += " " + right.m_dxcAdditionalFreeArguments; + m_dxcAdditionalFreeArguments = CommandLineArgumentUtils::MergeCommandLineArguments(m_dxcAdditionalFreeArguments, right.m_dxcAdditionalFreeArguments); if (right.m_defaultMatrixOrder != MatrixOrder::Default) { m_defaultMatrixOrder = right.m_defaultMatrixOrder; } } + //! [GFX TODO] [ATOM-15472] Remove this function. bool ShaderCompilerArguments::HasDifferentAzslcArguments(const ShaderCompilerArguments& right) const { auto isSet = +[](uint8_t level) { return level != LevelUnset; }; diff --git a/Gems/Atom/RHI/Code/Source/RHI.Edit/Utils.cpp b/Gems/Atom/RHI/Code/Source/RHI.Edit/Utils.cpp index 00b5dada69..dc0efb7e9a 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Edit/Utils.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Edit/Utils.cpp @@ -494,5 +494,64 @@ namespace AZ AzFramework::StringFunc::Path::ReplaceExtension(outputFile, outputExtension); return outputFile; } + + namespace CommandLineArgumentUtils + { + AZStd::vector GetListOfArgumentNames(AZStd::string_view commandLineString) + { + AZStd::vector listOfTokens; + AzFramework::StringFunc::Tokenize(commandLineString, listOfTokens, " \t\n"); + AZStd::vector listOfArguments; + for (const AZStd::string& token : listOfTokens) + { + AZStd::vector splitArguments; + AzFramework::StringFunc::Tokenize(token, splitArguments, "="); + listOfArguments.push_back(splitArguments[0]); + } + return listOfArguments; + } + + AZStd::string RemoveArgumentsFromCommandLineString( + AZStd::array_view listOfArgumentsToRemove, AZStd::string_view commandLineString) + { + AZStd::string customizedArguments = commandLineString; + for (const AZStd::string& azslcArgumentName : listOfArgumentsToRemove) + { + AZStd::string regexStr = AZStd::string::format("%s(=\\S+)?", azslcArgumentName.c_str()); + AZStd::regex replaceRegex(regexStr, AZStd::regex::ECMAScript); + customizedArguments = AZStd::regex_replace(customizedArguments, replaceRegex, ""); + } + return customizedArguments; + } + + AZStd::string RemoveExtraSpaces(AZStd::string_view commandLineString) + { + AZStd::vector argumentList; + AzFramework::StringFunc::Tokenize(commandLineString, argumentList, " \t\n"); + AZStd::string cleanStringWithArguments; + AzFramework::StringFunc::Join(cleanStringWithArguments, argumentList.begin(), argumentList.end(), " "); + return cleanStringWithArguments; + } + + AZStd::string MergeCommandLineArguments(AZStd::string_view left, AZStd::string_view right) + { + auto listOfArgumentNamesFromRight = GetListOfArgumentNames(right); + auto leftWithRightArgumentsRemoved = RemoveArgumentsFromCommandLineString(listOfArgumentNamesFromRight, left); + AZStd::string combinedArguments = AZStd::string::format("%s %s", leftWithRightArgumentsRemoved.c_str(), right.data()); + return RemoveExtraSpaces(combinedArguments); + } + + bool HasMacroDefinitions(AZStd::string_view commandLineString) + { + const AZStd::regex macroRegex(R"((^-D\s*(\w+))|(\s+-D\s*(\w+)))", AZStd::regex::ECMAScript); + + AZStd::smatch match; + if (AZStd::regex_search(commandLineString.data(), match, macroRegex)) + { + return (match.size() >= 1); + } + return false; + } + } //namespace CommandLineArgumentUtils } // namespace RHI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/CMakeLists.txt b/Gems/Atom/RPI/Code/CMakeLists.txt index f92213d9d7..d2b7fba071 100644 --- a/Gems/Atom/RPI/Code/CMakeLists.txt +++ b/Gems/Atom/RPI/Code/CMakeLists.txt @@ -69,6 +69,7 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) PRIVATE AZ::AtomCore AZ::AzToolsFramework + Gem::Atom_RHI.Edit Gem::Atom_RPI.Public ) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Shader/ShaderSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Shader/ShaderSourceData.cpp index aac81a6e26..376399ff84 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Shader/ShaderSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Shader/ShaderSourceData.cpp @@ -11,6 +11,8 @@ */ #include +#include +#include #include #include @@ -57,7 +59,7 @@ namespace AZ bool ShaderSourceData::IsRhiBackendDisabled(const AZ::Name& rhiName) const { - return AZStd::any_of(m_disabledRhiBackends.begin(), m_disabledRhiBackends.end(), [&](const AZStd::string& currentRhiName) + return AZStd::any_of(AZ_BEGIN_END(m_disabledRhiBackends), [&](const AZStd::string& currentRhiName) { return currentRhiName == rhiName.GetStringView(); }); @@ -72,19 +74,32 @@ namespace AZ static void GetListOfMacroDefinitionNames( const AZStd::string& stringWithArguments, AZStd::vector& macroDefinitionNames) { - static const AZStd::regex macroRegex("-D\\s*(\\w+)", AZStd::regex::ECMAScript); + const AZStd::regex macroRegex(R"(-D\s*(\w+))", AZStd::regex::ECMAScript); - AZStd::cmatch match; - if (AZStd::regex_search(stringWithArguments.c_str(), match, macroRegex)) + AZStd::string hayStack(stringWithArguments); + AZStd::smatch match; + while (AZStd::regex_search(hayStack.c_str(), match, macroRegex)) { // First pattern is always the entire string for (unsigned i = 1; i < match.size(); ++i) { if (match[i].matched) { - macroDefinitionNames.push_back(match[i].str().c_str()); + AZStd::string macroToAdd(match[i].str().c_str()); + const bool isPresent = AZStd::any_of(AZ_BEGIN_END(macroDefinitionNames), + [&](AZStd::string_view macroName) -> bool + { + return macroToAdd == macroName; + } + ); + if (isPresent) + { + continue; + } + macroDefinitionNames.push_back(macroToAdd); } } + hayStack = match.suffix(); } } @@ -103,19 +118,22 @@ namespace AZ static void GetListOfMacroDefinitions( const AZStd::string& stringWithArguments, AZStd::vector& macroDefinitions) { - static const AZStd::regex macroRegex("-D\\s*(\\w+(=\\w+)?)", AZStd::regex::ECMAScript); + const AZStd::regex macroRegex(R"(-D\s*(\w+)(=\w+)?)", AZStd::regex::ECMAScript); - AZStd::cmatch match; - if (AZStd::regex_search(stringWithArguments.c_str(), match, macroRegex)) + AZStd::string hayStack(stringWithArguments); + AZStd::smatch match; + while (AZStd::regex_search(hayStack.c_str(), match, macroRegex)) { - // First pattern is always the entire string - for (unsigned i = 1; i < match.size(); ++i) + if (match.size() > 1) { - if (match[i].matched) + AZStd::string macro(match[1].str().c_str()); + if (match.size() > 2) { - macroDefinitions.push_back(match[i].str().c_str()); + macro += match[2].str().c_str(); } + macroDefinitions.push_back(macro); } + hayStack = match.suffix(); } } @@ -126,62 +144,27 @@ namespace AZ return parsedMacroDefinitions; } - - // Helper. - // @arguments: A string with command line arguments for a console application of the form: - // "- -- --[=] ..." - // Example: "--use-spaces --namespace=vk" - // Returns: A list with just the [-|--]: - // ["-", "--", "--arg3"] - // For the example shown above it will return this vector: - // ["--use-spaces", "--namespace"] - AZStd::vector GetListOfArgumentNames(const AZStd::string& arguments) - { - AZStd::vector listOfTokens; - AzFramework::StringFunc::Tokenize(arguments, listOfTokens); - AZStd::vector listOfArguments; - for (const AZStd::string& token : listOfTokens) - { - AZStd::vector splitArguments; - AzFramework::StringFunc::Tokenize(token, splitArguments, "="); - listOfArguments.push_back(splitArguments[0]); - } - return listOfArguments; - } - AZStd::string ShaderSourceData::SupervariantInfo::GetCustomizedArgumentsForAzslc( const AZStd::string& initialAzslcCompilerArguments) const { - static const AZStd::regex macroRegex("-D\\s*(\\w+(=\\S+)?)", AZStd::regex::ECMAScript); + const AZStd::regex macroRegex(R"(-D\s*(\w+(=\S+)?))", AZStd::regex::ECMAScript); // We are only concerned with AZSLc arguments. Let's remove the C-Preprocessor macro definitions // from @minusArguments. const AZStd::string minusArguments = AZStd::regex_replace(m_minusArguments, macroRegex, ""); const AZStd::string plusArguments = AZStd::regex_replace(m_plusArguments, macroRegex, ""); AZStd::string azslcArgumentsToRemove = minusArguments + " " + plusArguments; - AZStd::vector azslcArgumentNamesToRemove = GetListOfArgumentNames(azslcArgumentsToRemove); + AZStd::vector azslcArgumentNamesToRemove = RHI::CommandLineArgumentUtils::GetListOfArgumentNames(azslcArgumentsToRemove); // At this moment @azslcArgumentsToRemove contains arguments for AZSLc that can be of the form: // - // --[=] // We need to remove those from @initialAzslcCompilerArguments. - AZStd::string customizedArguments = initialAzslcCompilerArguments; - for (const AZStd::string& azslcArgumentName : azslcArgumentNamesToRemove) - { - AZStd::string regexStr = AZStd::string::format("%s(=\\S+)?", azslcArgumentName.c_str()); - AZStd::regex replaceRegex(regexStr, AZStd::regex::ECMAScript); - customizedArguments = AZStd::regex_replace(customizedArguments, replaceRegex, ""); - } - + AZStd::string customizedArguments = RHI::CommandLineArgumentUtils::RemoveArgumentsFromCommandLineString( + azslcArgumentNamesToRemove, initialAzslcCompilerArguments); customizedArguments += " " + plusArguments; - // Will contain the results that will be joined by a space. - // This is used to get a clean string to return without excess spaces. - AZStd::vector argumentList; - AzFramework::StringFunc::Tokenize(customizedArguments, argumentList, " \t\n"); - customizedArguments.clear(); // Need to clear because Join appends. - AzFramework::StringFunc::Join(customizedArguments, argumentList.begin(), argumentList.end(), " "); - return customizedArguments; + return RHI::CommandLineArgumentUtils::RemoveExtraSpaces(customizedArguments); } From 6c17c7bfb3019812181785d0ab3549baf1c7ef40 Mon Sep 17 00:00:00 2001 From: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> Date: Wed, 26 May 2021 15:30:21 -0500 Subject: [PATCH 168/811] Add new API to convert absolute source paths to relative paths. (#930) There are already APIs for getting a relative product path from an absolute source path, or getting a relative source path for an *existing* source file, but there were no APIs for getting a relative source path for a *new* source file. Prefabs will need this ability to be able to correctly generate a relative source path inside the prefab file before the file has been saved. The logic for relative source paths is a little bit tricky because the paths are relative to the watch folders, and the watch folders can be nested, with different priorities to explain which should take precedence. The input paths can also include specifiers like "." and "..", which need to be reconciled before creating the final correct relative path. The included unit tests test all of the tricky edge cases that I was able to identify. --- .../Asset/AssetProcessorMessages.cpp | 50 +++++ .../Asset/AssetProcessorMessages.h | 39 ++++ .../Asset/AssetSystemComponent.cpp | 2 + .../API/EditorAssetSystemAPI.h | 12 +- .../Asset/AssetSystemComponent.cpp | 24 +++ .../Asset/AssetSystemComponent.h | 2 + .../AzToolsFramework/Tests/AssetSystemMocks.h | 2 + .../SliceStabilityTestFramework.h | 3 + .../native/AssetManager/AssetCatalog.cpp | 74 +++++++ .../native/AssetManager/AssetCatalog.h | 6 + .../AssetManager/AssetRequestHandler.cpp | 22 ++ .../AssetManager/assetProcessorManager.h | 5 + .../AssetCatalog/AssetCatalogUnitTests.cpp | 194 +++++++++++++++++- .../tests/AssetProcessorMessagesTests.cpp | 3 + .../AssetProcessorManagerUnitTests.cpp | 2 + .../RPI/Code/Tests/Common/AssetSystemStub.cpp | 10 +- .../RPI/Code/Tests/Common/AssetSystemStub.h | 2 + .../Builders/CopyDependencyBuilderTest.cpp | 3 + 18 files changed, 446 insertions(+), 9 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.cpp b/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.cpp index 020feffc47..7280c4af5c 100644 --- a/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.cpp +++ b/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.cpp @@ -308,6 +308,56 @@ namespace AzFramework } } + //--------------------------------------------------------------------- + GenerateRelativeSourcePathRequest::GenerateRelativeSourcePathRequest(const AZ::OSString& sourcePath) + { + AZ_Assert(!sourcePath.empty(), "GenerateRelativeSourcePathRequest: asset path is empty"); + m_sourcePath = sourcePath; + } + + unsigned int GenerateRelativeSourcePathRequest::GetMessageType() const + { + return MessageType; + } + + void GenerateRelativeSourcePathRequest::Reflect(AZ::ReflectContext* context) + { + auto serialize = azrtti_cast(context); + if (serialize) + { + serialize->Class() + ->Version(1) + ->Field("SourcePath", &GenerateRelativeSourcePathRequest::m_sourcePath); + } + } + + //--------------------------------------------------------------------- + GenerateRelativeSourcePathResponse::GenerateRelativeSourcePathResponse( + bool resolved, const AZ::OSString& relativeSourcePath, const AZ::OSString& rootFolder) + { + m_relativeSourcePath = relativeSourcePath; + m_resolved = resolved; + m_rootFolder = rootFolder; + } + + unsigned int GenerateRelativeSourcePathResponse::GetMessageType() const + { + return GenerateRelativeSourcePathRequest::MessageType; + } + + void GenerateRelativeSourcePathResponse::Reflect(AZ::ReflectContext* context) + { + auto serialize = azrtti_cast(context); + if (serialize) + { + serialize->Class() + ->Version(1) + ->Field("RelativeSourcePath", &GenerateRelativeSourcePathResponse::m_relativeSourcePath) + ->Field("RootFolder", &GenerateRelativeSourcePathResponse::m_rootFolder) + ->Field("Resolved", &GenerateRelativeSourcePathResponse::m_resolved); + } + } + //--------------------------------------------------------------------- GetFullSourcePathFromRelativeProductPathRequest::GetFullSourcePathFromRelativeProductPathRequest(const AZ::OSString& relativeProductPath) { diff --git a/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.h b/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.h index 9661e61828..c15f75e3e7 100644 --- a/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.h +++ b/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.h @@ -288,6 +288,45 @@ namespace AzFramework bool m_resolved; }; + ////////////////////////////////////////////////////////////////////////// + class GenerateRelativeSourcePathRequest : public BaseAssetProcessorMessage + { + public: + AZ_CLASS_ALLOCATOR(GenerateRelativeSourcePathRequest, AZ::OSAllocator, 0); + AZ_RTTI(GenerateRelativeSourcePathRequest, "{B3865033-F5A3-4749-8147-7B1AB04D5F6D}", + BaseAssetProcessorMessage); + static void Reflect(AZ::ReflectContext* context); + + // For people that are debugging the network messages and just see MessageType as a value, + // the CRC value below is 739777771 (0x2C181CEB) + static constexpr unsigned int MessageType = + AZ_CRC_CE("AssetSystem::GenerateRelativeSourcePathRequest"); + + GenerateRelativeSourcePathRequest() = default; + GenerateRelativeSourcePathRequest(const AZ::OSString& sourcePath); + unsigned int GetMessageType() const override; + + AZ::OSString m_sourcePath; + }; + + class GenerateRelativeSourcePathResponse : public BaseAssetProcessorMessage + { + public: + AZ_CLASS_ALLOCATOR(GenerateRelativeSourcePathResponse, AZ::OSAllocator, 0); + AZ_RTTI(GenerateRelativeSourcePathResponse, "{938D33DB-C8F6-4FA4-BC81-2F139A9BE1D7}", + BaseAssetProcessorMessage); + static void Reflect(AZ::ReflectContext* context); + + GenerateRelativeSourcePathResponse() = default; + GenerateRelativeSourcePathResponse( + bool resolved, const AZ::OSString& relativeSourcePath, const AZ::OSString& rootFolder); + unsigned int GetMessageType() const override; + + AZ::OSString m_relativeSourcePath; + AZ::OSString m_rootFolder; ///< This is the folder it was found in (the watched/scanned folder, such as gems /assets/ folder) + bool m_resolved; + }; + ////////////////////////////////////////////////////////////////////////// class GetFullSourcePathFromRelativeProductPathRequest : public BaseAssetProcessorMessage diff --git a/Code/Framework/AzFramework/AzFramework/Asset/AssetSystemComponent.cpp b/Code/Framework/AzFramework/AzFramework/Asset/AssetSystemComponent.cpp index 83c4907468..6b19084c2a 100644 --- a/Code/Framework/AzFramework/AzFramework/Asset/AssetSystemComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Asset/AssetSystemComponent.cpp @@ -202,6 +202,7 @@ namespace AzFramework // Requests GetUnresolvedDependencyCountsRequest::Reflect(context); GetRelativeProductPathFromFullSourceOrProductPathRequest::Reflect(context); + GenerateRelativeSourcePathRequest::Reflect(context); GetFullSourcePathFromRelativeProductPathRequest::Reflect(context); SourceAssetInfoRequest::Reflect(context); AssetInfoRequest::Reflect(context); @@ -234,6 +235,7 @@ namespace AzFramework // Responses GetUnresolvedDependencyCountsResponse::Reflect(context); GetRelativeProductPathFromFullSourceOrProductPathResponse::Reflect(context); + GenerateRelativeSourcePathResponse::Reflect(context); GetFullSourcePathFromRelativeProductPathResponse::Reflect(context); SourceAssetInfoResponse::Reflect(context); AssetInfoResponse::Reflect(context); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorAssetSystemAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorAssetSystemAPI.h index 98e4c6b5eb..1599d29589 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorAssetSystemAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorAssetSystemAPI.h @@ -60,10 +60,20 @@ namespace AzToolsFramework //! and is generally checked into source control. virtual const char* GetAbsoluteDevRootFolderPath() = 0; - /// Convert a full source path like "c:\\dev\gamename\\blah\\test.tga" into a relative product path. + /// Convert a full source path like "c:\\dev\\gamename\\blah\\test.tga" into a relative product path. /// asset paths never mention their alias and are relative to the asset cache root virtual bool GetRelativeProductPathFromFullSourceOrProductPath(const AZStd::string& fullPath, AZStd::string& relativeProductPath) = 0; + /** Convert a source path like "c:\\dev\\gamename\\blah\\test.tga" into a relative source path, like "blah/test.tga". + * If no valid relative path could be created, the input source path will be returned in relativePath. + * @param sourcePath partial or full path to a source file. (The file doesn't need to exist) + * @param relativePath the output relative path for the source file, if a valid one could be created + * @param rootFilePath the root path that relativePath is relative to + * @return true if a valid relative path was created, false if it wasn't + */ + virtual bool GenerateRelativeSourcePath( + const AZStd::string& sourcePath, AZStd::string& relativePath, AZStd::string& rootFilePath) = 0; + /// Convert a relative asset path like "blah/test.tga" to a full source path path. /// Once the asset processor has finished building, this function is capable of handling even when the extension changes /// or when the source is in a different folder or in a different location (such as inside gems) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetSystemComponent.cpp index 5529829913..4966d9cce9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetSystemComponent.cpp @@ -265,6 +265,30 @@ namespace AzToolsFramework return response.m_resolved; } + bool AssetSystemComponent::GenerateRelativeSourcePath( + const AZStd::string& sourcePath, AZStd::string& relativePath, AZStd::string& rootFilePath) + { + AzFramework::SocketConnection* engineConnection = AzFramework::SocketConnection::GetInstance(); + if (!engineConnection || !engineConnection->IsConnected()) + { + relativePath = sourcePath; + return false; + } + + AzFramework::AssetSystem::GenerateRelativeSourcePathRequest request(sourcePath); + AzFramework::AssetSystem::GenerateRelativeSourcePathResponse response; + if (!SendRequest(request, response)) + { + AZ_Error("Editor", false, "Failed to send GenerateRelativeSourcePath request for %s", sourcePath.c_str()); + relativePath = sourcePath; + return false; + } + + relativePath = response.m_relativeSourcePath; + rootFilePath = response.m_rootFolder; + return response.m_resolved; + } + bool AssetSystemComponent::GetFullSourcePathFromRelativeProductPath(const AZStd::string& relPath, AZStd::string& fullPath) { auto foundIt = m_assetSourceRelativePathToFullPathCache.find(relPath); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetSystemComponent.h index 399ee1ac9d..9d839c60f5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetSystemComponent.h @@ -63,6 +63,8 @@ namespace AzToolsFramework const char* GetAbsoluteDevGameFolderPath() override; const char* GetAbsoluteDevRootFolderPath() override; bool GetRelativeProductPathFromFullSourceOrProductPath(const AZStd::string& fullPath, AZStd::string& outputPath) override; + bool GenerateRelativeSourcePath( + const AZStd::string& sourcePath, AZStd::string& outputPath, AZStd::string& watchFolder) override; bool GetFullSourcePathFromRelativeProductPath(const AZStd::string& relPath, AZStd::string& fullPath) override; bool GetAssetInfoById(const AZ::Data::AssetId& assetId, const AZ::Data::AssetType& assetType, const AZStd::string& platformName, AZ::Data::AssetInfo& assetInfo, AZStd::string& rootFilePath) override; bool GetSourceInfoBySourcePath(const char* sourcePath, AZ::Data::AssetInfo& assetInfo, AZStd::string& watchFolder) override; diff --git a/Code/Framework/AzToolsFramework/Tests/AssetSystemMocks.h b/Code/Framework/AzToolsFramework/Tests/AssetSystemMocks.h index 1e01229d73..8a394d3ab5 100644 --- a/Code/Framework/AzToolsFramework/Tests/AssetSystemMocks.h +++ b/Code/Framework/AzToolsFramework/Tests/AssetSystemMocks.h @@ -25,6 +25,8 @@ namespace UnitTests MOCK_METHOD0(GetAbsoluteDevGameFolderPath, const char* ()); MOCK_METHOD0(GetAbsoluteDevRootFolderPath, const char* ()); MOCK_METHOD2(GetRelativeProductPathFromFullSourceOrProductPath, bool(const AZStd::string& fullPath, AZStd::string& relativeProductPath)); + MOCK_METHOD3(GenerateRelativeSourcePath, + bool(const AZStd::string& sourcePath, AZStd::string& relativePath, AZStd::string& watchFolder)); MOCK_METHOD2(GetFullSourcePathFromRelativeProductPath, bool(const AZStd::string& relPath, AZStd::string& fullSourcePath)); MOCK_METHOD5(GetAssetInfoById, bool(const AZ::Data::AssetId& assetId, const AZ::Data::AssetType& assetType, const AZStd::string& platformName, AZ::Data::AssetInfo& assetInfo, AZStd::string& rootFilePath)); MOCK_METHOD3(GetSourceInfoBySourcePath, bool(const char* sourcePath, AZ::Data::AssetInfo& assetInfo, AZStd::string& watchFolder)); diff --git a/Code/Framework/AzToolsFramework/Tests/SliceStabilityTests/SliceStabilityTestFramework.h b/Code/Framework/AzToolsFramework/Tests/SliceStabilityTests/SliceStabilityTestFramework.h index 57ac16673d..7d3d312cdb 100644 --- a/Code/Framework/AzToolsFramework/Tests/SliceStabilityTests/SliceStabilityTestFramework.h +++ b/Code/Framework/AzToolsFramework/Tests/SliceStabilityTests/SliceStabilityTestFramework.h @@ -149,6 +149,9 @@ namespace UnitTest const char* GetAbsoluteDevGameFolderPath() override { return ""; } const char* GetAbsoluteDevRootFolderPath() override { return ""; } bool GetRelativeProductPathFromFullSourceOrProductPath([[maybe_unused]] const AZStd::string& fullPath, [[maybe_unused]] AZStd::string& relativeProductPath) override { return false; } + bool GenerateRelativeSourcePath( + [[maybe_unused]] const AZStd::string& sourcePath, [[maybe_unused]] AZStd::string& relativePath, + [[maybe_unused]] AZStd::string& watchFolder) override { return false; } bool GetFullSourcePathFromRelativeProductPath([[maybe_unused]] const AZStd::string& relPath, [[maybe_unused]] AZStd::string& fullSourcePath) override { return false; } bool GetAssetInfoById([[maybe_unused]] const AZ::Data::AssetId& assetId, [[maybe_unused]] const AZ::Data::AssetType& assetType, [[maybe_unused]] const AZStd::string& platformName, [[maybe_unused]] AZ::Data::AssetInfo& assetInfo, [[maybe_unused]] AZStd::string& rootFilePath) override { return false; } bool GetSourceInfoBySourcePath(const char* sourcePath, AZ::Data::AssetInfo& assetInfo, AZStd::string& watchFolder) override; diff --git a/Code/Tools/AssetProcessor/native/AssetManager/AssetCatalog.cpp b/Code/Tools/AssetProcessor/native/AssetManager/AssetCatalog.cpp index 196f6b0543..8bc6d0b6f7 100644 --- a/Code/Tools/AssetProcessor/native/AssetManager/AssetCatalog.cpp +++ b/Code/Tools/AssetProcessor/native/AssetManager/AssetCatalog.cpp @@ -655,6 +655,80 @@ namespace AssetProcessor return true; } + bool AssetCatalog::GenerateRelativeSourcePath( + const AZStd::string& sourcePath, AZStd::string& relativePath, AZStd::string& rootFolder) + { + QString normalizedSourcePath = AssetUtilities::NormalizeFilePath(sourcePath.c_str()); + QDir inputPath(normalizedSourcePath); + QString scanFolder; + QString relativeName; + + bool validResult = false; + + AZ_TracePrintf(AssetProcessor::DebugChannel, "ProcessGenerateRelativeSourcePathRequest: %s...\n", sourcePath.c_str()); + + if (sourcePath.empty()) + { + // For an empty input path, do nothing, we'll return an empty, invalid result. + // (We check fullPath instead of inputPath, because an empty fullPath actually produces "." for inputPath) + } + else if (inputPath.isAbsolute()) + { + // For an absolute path, try to convert it to a relative path, based on the existing scan folders. + // To get the inputPath, we use absolutePath() instead of path() so that any . or .. entries get collapsed. + validResult = m_platformConfig->ConvertToRelativePath(inputPath.absolutePath(), relativeName, scanFolder); + } + else if (inputPath.isRelative()) + { + // For a relative path, concatenate it with each scan folder, and see if a valid relative path emerges. + int scanFolders = m_platformConfig->GetScanFolderCount(); + for (int scanIdx = 0; scanIdx < scanFolders; scanIdx++) + { + auto& scanInfo = m_platformConfig->GetScanFolderAt(scanIdx); + QDir possibleRoot(scanInfo.ScanPath()); + QDir possibleAbsolutePath = possibleRoot.filePath(normalizedSourcePath); + // To get the inputPath, we use absolutePath() instead of path() so that any . or .. entries get collapsed. + if (m_platformConfig->ConvertToRelativePath(possibleAbsolutePath.absolutePath(), relativeName, scanFolder)) + { + validResult = true; + break; + } + } + } + + // The input has produced a valid relative path. However, the path might match multiple nested scan folders, + // so look to see if a higher-priority folder has a better match. + if (validResult) + { + QString overridingFile = m_platformConfig->GetOverridingFile(relativeName, scanFolder); + + if (!overridingFile.isEmpty()) + { + overridingFile = AssetUtilities::NormalizeFilePath(overridingFile); + validResult = m_platformConfig->ConvertToRelativePath(overridingFile, relativeName, scanFolder); + } + } + + if (!validResult) + { + // if we are here it means we have failed to determine the relativePath, so we will send back the original path + AZ_TracePrintf(AssetProcessor::DebugChannel, + "GenerateRelativeSourcePath found no valid result, returning original path: %s...\n", sourcePath.c_str()); + + rootFolder.clear(); + relativePath.clear(); + relativePath = sourcePath; + return false; + } + + relativePath = relativeName.toUtf8().data(); + rootFolder = scanFolder.toUtf8().data(); + + AZ_Assert(!relativePath.empty(), "ConvertToRelativePath returned true, but relativePath is empty"); + + return true; + } + bool AssetCatalog::GetFullSourcePathFromRelativeProductPath(const AZStd::string& relPath, AZStd::string& fullSourcePath) { ProcessGetFullSourcePathFromRelativeProductPathRequest(relPath, fullSourcePath); diff --git a/Code/Tools/AssetProcessor/native/AssetManager/AssetCatalog.h b/Code/Tools/AssetProcessor/native/AssetManager/AssetCatalog.h index f515fa3658..13dc7892b1 100644 --- a/Code/Tools/AssetProcessor/native/AssetManager/AssetCatalog.h +++ b/Code/Tools/AssetProcessor/native/AssetManager/AssetCatalog.h @@ -95,6 +95,12 @@ namespace AssetProcessor const char* GetAbsoluteDevGameFolderPath() override; const char* GetAbsoluteDevRootFolderPath() override; bool GetRelativeProductPathFromFullSourceOrProductPath(const AZStd::string& fullPath, AZStd::string& relativeProductPath) override; + + //! Given a partial or full source file path, respond with its relative path and the watch folder it is relative to. + //! The input source path does not need to exist, so this can be used for new files that haven't been saved yet. + bool GenerateRelativeSourcePath( + const AZStd::string& sourcePath, AZStd::string& relativePath, AZStd::string& watchFolder) override; + bool GetFullSourcePathFromRelativeProductPath(const AZStd::string& relPath, AZStd::string& fullSourcePath) override; bool GetAssetInfoById(const AZ::Data::AssetId& assetId, const AZ::Data::AssetType& assetType, const AZStd::string& platformName, AZ::Data::AssetInfo& assetInfo, AZStd::string& rootFilePath) override; bool GetSourceInfoBySourcePath(const char* sourcePath, AZ::Data::AssetInfo& assetInfo, AZStd::string& watchFolder) override; diff --git a/Code/Tools/AssetProcessor/native/AssetManager/AssetRequestHandler.cpp b/Code/Tools/AssetProcessor/native/AssetManager/AssetRequestHandler.cpp index 97b28691dc..2d22d3d136 100644 --- a/Code/Tools/AssetProcessor/native/AssetManager/AssetRequestHandler.cpp +++ b/Code/Tools/AssetProcessor/native/AssetManager/AssetRequestHandler.cpp @@ -104,6 +104,27 @@ namespace return GetRelativeProductPathFromFullSourceOrProductPathResponse(relPathFound, relProductPath); } + GenerateRelativeSourcePathResponse HandleGenerateRelativeSourcePathRequest( + MessageData messageData) + { + bool relPathFound = false; + AZStd::string relPath; + AZStd::string watchFolder; + + AzToolsFramework::AssetSystemRequestBus::BroadcastResult( + relPathFound, &AzToolsFramework::AssetSystemRequestBus::Events::GenerateRelativeSourcePath, + messageData.m_message->m_sourcePath, relPath, watchFolder); + + if (!relPathFound) + { + AZ_TracePrintf( + AssetProcessor::ConsoleChannel, "Could not find relative source path for the source file (%s).", + messageData.m_message->m_sourcePath.c_str()); + } + + return GenerateRelativeSourcePathResponse(relPathFound, relPath, watchFolder); + } + SourceAssetInfoResponse HandleSourceAssetInfoRequest(MessageData messageData) { SourceAssetInfoResponse response; @@ -407,6 +428,7 @@ AssetRequestHandler::AssetRequestHandler() m_requestRouter.RegisterMessageHandler(&HandleGetFullSourcePathFromRelativeProductPathRequest); m_requestRouter.RegisterMessageHandler(&HandleGetRelativeProductPathFromFullSourceOrProductPathRequest); + m_requestRouter.RegisterMessageHandler(&HandleGenerateRelativeSourcePathRequest); m_requestRouter.RegisterMessageHandler(&HandleSourceAssetInfoRequest); m_requestRouter.RegisterMessageHandler(&HandleSourceAssetProductsInfoRequest); m_requestRouter.RegisterMessageHandler(&HandleGetScanFoldersRequest); diff --git a/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.h b/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.h index 88f74c886b..3dc8bd7a00 100644 --- a/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.h +++ b/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.h @@ -57,6 +57,9 @@ namespace AzFramework class GetRelativeProductPathFromFullSourceOrProductPathRequest; class GetRelativeProductPathFromFullSourceOrProductPathResponse; + class GenerateRelativeSourcePathRequest; + class GenerateRelativeSourcePathResponse; + class GetFullSourcePathFromRelativeProductPathRequest; class GetFullSourcePathFromRelativeProductPathResponse; class AssetNotificationMessage; @@ -104,6 +107,8 @@ namespace AssetProcessor using GetAbsoluteAssetDatabaseLocationResponse = AzToolsFramework::AssetSystem::GetAbsoluteAssetDatabaseLocationResponse; using GetRelativeProductPathFromFullSourceOrProductPathRequest = AzFramework::AssetSystem::GetRelativeProductPathFromFullSourceOrProductPathRequest; using GetRelativeProductPathFromFullSourceOrProductPathResponse = AzFramework::AssetSystem::GetRelativeProductPathFromFullSourceOrProductPathResponse; + using GenerateRelativeSourcePathRequest = AzFramework::AssetSystem::GenerateRelativeSourcePathRequest; + using GenerateRelativeSourcePathResponse = AzFramework::AssetSystem::GenerateRelativeSourcePathResponse; using GetFullSourcePathFromRelativeProductPathRequest = AzFramework::AssetSystem::GetFullSourcePathFromRelativeProductPathRequest; using GetFullSourcePathFromRelativeProductPathResponse = AzFramework::AssetSystem::GetFullSourcePathFromRelativeProductPathResponse; diff --git a/Code/Tools/AssetProcessor/native/tests/AssetCatalog/AssetCatalogUnitTests.cpp b/Code/Tools/AssetProcessor/native/tests/AssetCatalog/AssetCatalogUnitTests.cpp index 3d9ecd3f5e..52bedc7744 100644 --- a/Code/Tools/AssetProcessor/native/tests/AssetCatalog/AssetCatalogUnitTests.cpp +++ b/Code/Tools/AssetProcessor/native/tests/AssetCatalog/AssetCatalogUnitTests.cpp @@ -224,6 +224,18 @@ namespace AssetProcessor dbConn->SetScanFolder(newScanFolder); } + virtual void AddScanFolders( + const QDir& tempPath, AssetDatabaseConnection* dbConn, PlatformConfiguration& config, + const AZStd::vector& platforms) + { + // PATH DisplayName PortKey root recurse platforms order + AddScanFolder(ScanFolderInfo(tempPath.filePath("subfolder4"), "subfolder4", "subfolder4", false, false, platforms, -6), config, dbConn); // subfolder 4 overrides subfolder3 + AddScanFolder(ScanFolderInfo(tempPath.filePath("subfolder3"), "subfolder3", "subfolder3", false, false, platforms, -5), config, dbConn); // subfolder 3 overrides subfolder2 + AddScanFolder(ScanFolderInfo(tempPath.filePath("subfolder2"), "subfolder2", "subfolder2", false, true, platforms, -2), config, dbConn); // subfolder 2 overrides subfolder1 + AddScanFolder(ScanFolderInfo(tempPath.filePath("subfolder1"), "subfolder1", "subfolder1", false, true, platforms, -1), config, dbConn); // subfolder1 overrides root + AddScanFolder(ScanFolderInfo(tempPath.absolutePath(), "temp", "tempfolder", true, false, platforms, 0), config, dbConn); // add the root + } + // build some default configs. void BuildConfig(const QDir& tempPath, AssetDatabaseConnection* dbConn, PlatformConfiguration& config) { @@ -232,12 +244,8 @@ namespace AssetProcessor config.EnablePlatform({ "fandango" ,{ "console", "renderer" } }, false); AZStd::vector platforms; config.PopulatePlatformsForScanFolder(platforms); - // PATH DisplayName PortKey root recurse platforms order - AddScanFolder(ScanFolderInfo(tempPath.filePath("subfolder4"), "subfolder4", "subfolder4", false, false, platforms, -6), config, dbConn); // subfolder 4 overrides subfolder3 - AddScanFolder(ScanFolderInfo(tempPath.filePath("subfolder3"), "subfolder3", "subfolder3", false, false, platforms, -5), config, dbConn); // subfolder 3 overrides subfolder2 - AddScanFolder(ScanFolderInfo(tempPath.filePath("subfolder2"), "subfolder2", "subfolder2", false, true, platforms, -2), config, dbConn); // subfolder 2 overrides subfolder1 - AddScanFolder(ScanFolderInfo(tempPath.filePath("subfolder1"), "subfolder1", "subfolder1", false, true, platforms, -1), config, dbConn); // subfolder1 overrides root - AddScanFolder(ScanFolderInfo(tempPath.absolutePath(), "temp", "tempfolder", true, false, platforms, 0), config, dbConn); // add the root + + AddScanFolders(tempPath, dbConn, config, platforms); config.AddMetaDataType("exportsettings", QString()); @@ -359,7 +367,8 @@ namespace AssetProcessor return false; } - // Calls the GetFullSourcePathFromRelativeProductPath function and checks the return results, returning true if it matches both of the expected results + // Calls the GetFullSourcePathFromRelativeProductPath function and checks the return results, returning true if it matches both of + // the expected results bool TestGetFullSourcePath(const QString& fileToCheck, const QDir& tempPath, bool expectToFind, const char* expectedPath) { bool fullPathfound = false; @@ -531,6 +540,177 @@ namespace AssetProcessor ASSERT_TRUE(TestGetRelativeProductPath(fileToCheck, true, { "aaa/basefile.txt" })); } + class AssetCatalogTestRelativeSourcePath : public AssetCatalogTest + { + public: + QDir GetRoot() + { + // Return an OS-friendly absolute root directory for our tests ("C:/sourceRoot" or "/sourceRoot"). It doesn't + // need to exist, it just needs to be an absolute path. + return QDir::root().filePath("sourceRoot"); + } + + // Set up custom scan folders for the "relative source path" tests, so that we can try out specific combinations of watch folders + void AddScanFolders( + [[maybe_unused]] const QDir& tempPath, AssetDatabaseConnection* dbConn, PlatformConfiguration& config, + const AZStd::vector& platforms) override + { + QDir root = GetRoot(); + + // This will set up the following watch folders, in highest to lowest priority: + + // /sourceRoot/recurseNested/nested (recurse) + // /sourceRoot/noRecurse (no recurse) + // /sourceRoot/recurseNotNested (recurse) + // /sourceRoot/recurseNested (recurse) + + AddScanFolder( + ScanFolderInfo(root.filePath("recurseNested/nested"), "nested", "nested", false, true, platforms, -4), config, dbConn); + AddScanFolder( + ScanFolderInfo(root.filePath("noRecurse"), "noRecurse", "noRecurse", false, false, platforms, -3), config, dbConn); + AddScanFolder( + ScanFolderInfo(root.filePath("recurseNotNested"), "recurseNotNested", "recurseNotNested", false, true, platforms, -2), + config, dbConn); + AddScanFolder( + ScanFolderInfo(root.filePath("recurseNested"), "recurseNested", "recurseNested", false, true, platforms, -1), + config, dbConn); + } + + // Calls the GenerateRelativeSourcePath function and validates that the results match the expected inputs. + void TestGetRelativeSourcePath( + const AZStd::string& sourcePath, bool expectedToFind, const AZStd::string& expectedPath, const AZStd::string& expectedRoot) + { + bool relPathFound = false; + AZStd::string relPath; + AZStd::string rootFolder; + + AzToolsFramework::AssetSystemRequestBus::BroadcastResult( + relPathFound, &AzToolsFramework::AssetSystem::AssetSystemRequest::GenerateRelativeSourcePath, sourcePath, + relPath, rootFolder); + + EXPECT_EQ(relPathFound, expectedToFind); + EXPECT_EQ(relPath, expectedPath); + EXPECT_EQ(rootFolder, expectedRoot); + } + }; + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_EmptySourcePath_ReturnsNoMatch) + { + // Test passes in an empty source path, which shouldn't produce a valid result. + // Input: empty source path + // Output: empty, not found result + TestGetRelativeSourcePath("", false, "", ""); + } + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_AbsolutePathOutsideWatchFolders_ReturnsNoMatch) + { + // Test passes in an invalid absolute source path, which shouldn't produce a valid result. + // Input: "/sourceRoot/noWatchFolder/test.txt" + // Output: not found result, which also returns the input as the relative file name + QDir watchFolder = GetRoot().filePath("noWatchFolder/"); + QString fileToCheck = watchFolder.filePath("test.txt"); + + TestGetRelativeSourcePath(fileToCheck.toUtf8().constData(), false, fileToCheck.toUtf8().constData(), ""); + } + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_AbsolutePathUnderWatchFolder_ReturnsRelativePath) + { + // Test passes in a valid absolute source path, which should produce a valid relative path + // Input: "/sourceRoot/noRecurse/test.txt" + // Output: "test.txt" in folder "/sourceRoot/noRecurse/" + QDir watchFolder = GetRoot().filePath("noRecurse/"); + QString fileToCheck = watchFolder.filePath("test.txt"); + + TestGetRelativeSourcePath(fileToCheck.toUtf8().constData(), true, "test.txt", watchFolder.path().toUtf8().constData()); + } + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_AbsolutePathUnderNestedWatchFolders_ReturnsRelativePath) + { + // Test passes in a valid absolute source path that matches a watch folder and a nested watch folder. + // The output relative path should match the nested folder, because the nested folder has a higher priority registered with the AP. + // Input: "/sourceRoot/recurseNested/nested/test.txt" + // Output: "test.txt" in folder "/sourceRoot/recurseNested/nested/" + QDir watchFolder = GetRoot().filePath("recurseNested/nested/"); + QString fileToCheck = watchFolder.filePath("test.txt"); + + TestGetRelativeSourcePath(fileToCheck.toUtf8().constData(), true, "test.txt", watchFolder.path().toUtf8().constData()); + } + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_BareFileNameValidInWatchFolder_ReturnsHighestPriorityWatchFolder) + { + // Test passes in a simple file name. The output should be relative to the highest-priority watch folder. + // Input: "test.txt" + // Output: "test.txt" in folder "/sourceRoot/recurseNested/nested/" + QDir watchFolder = GetRoot().filePath("recurseNested/nested/"); + + TestGetRelativeSourcePath("test.txt", true, "test.txt", watchFolder.path().toUtf8().constData()); + } + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_RelativePathValidInWatchFolder_ReturnsHighestPriorityWatchFolder) + { + // Test passes in a relative path. The output should preserve the relative path, but list it as relative to the highest-priority + // watch folder. + // Input: "a/b/c/test.txt" + // Output: "a/b/c/test.txt" in folder "/sourceRoot/recurseNested/nested/" + QDir watchFolder = GetRoot().filePath("recurseNested/nested/"); + + TestGetRelativeSourcePath("a/b/c/test.txt", true, "a/b/c/test.txt", watchFolder.path().toUtf8().constData()); + } + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_RelativePathNotInWatchFolder_ReturnsNoMatch) + { + // Test passes in a relative path that "backs up" two directories. This will be invalid, because no matter which watch directory + // we start at, the result will be outside of any watch directory. + // Input: "../../test.txt" + // Output: not found result, which also returns the input as the relative file name + TestGetRelativeSourcePath("../../test.txt", false, "../../test.txt", ""); + } + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_RelativePathValidFromNestedWatchFolder_ReturnsOuterFolder) + { + // Test passes in a relative path that "backs up" one directory. This will produce a valid result, because we can back up from + // the "recurseNested/nested/" watch folder to "recurseNested", which is also a valid watch folder. + // Input: "../test.txt" + // Output: "test.txt" in folder "/sourceRoot/recurseNested" + QDir watchFolder = GetRoot().filePath("recurseNested/"); + TestGetRelativeSourcePath("../test.txt", true, "test.txt", watchFolder.path().toUtf8().constData()); + } + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_RelativePathMovesToParentWatchFolder_ReturnsOuterFolder) + { + // Test passes in a relative path that backs up one directory and then forward into a directory. This will produce a valid + // result, because it can validly start in the highest-priority watch folder (recurseNested/nested), move back one into the + // outer watch folder (recurseNested), and then have a subdirectory within it. + // Note that it would also be valid to move from recurseNested to recurseNotNested, but that won't be the result of this test + // because that's a lower-priority match. + // Input: "../recurseNotNested/test.txt" + // Output: "recurseNotNested/test.txt" in folder "/sourceRoot/recurseNested/" + QDir watchFolder = GetRoot().filePath("recurseNested/"); + + TestGetRelativeSourcePath("../recurseNotNested/test.txt", true, "recurseNotNested/test.txt", watchFolder.path().toUtf8().constData()); + } + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_RelativePathMovesToSiblingWatchFolder_ReturnsSiblingFolder) + { + // Test passes in a relative path that backs up two directories and then forward into a directory. This will produce a valid + // result, because it can validly start in the recurseNested/nested folder, move back two folders, then forward into the sibling + // recurseNotNested folder. The result will be a relative path to the sibling folder. + // Input: "../../recurseNotNested/test.txt" + // Output: "test.txt" in folder "/sourceRoot/recurseNotNested/" + QDir watchFolder = GetRoot().filePath("recurseNotNested/"); + + TestGetRelativeSourcePath("../../recurseNotNested/test.txt", true, "test.txt", watchFolder.path().toUtf8().constData()); + } + + TEST_F(AssetCatalogTestRelativeSourcePath, GenerateRelativeSourcePath_RelativePathBacksOutOfWatchFolder_ReturnsNoMatch) + { + // Test passes in a relative path that adds a directory, then "backs up" three directories. This will be invalid, because no + // matter which watch directory we start at, the result will be outside of any watch directory. + // Input: "../test.txt" + // Output: "test.txt" in folder "/sourceRoot/recurseNested" + TestGetRelativeSourcePath("a/../../../test.txt", false, "a/../../../test.txt", ""); + } + class AssetCatalogTest_GetFullSourcePath : public AssetCatalogTest { diff --git a/Code/Tools/AssetProcessor/native/tests/AssetProcessorMessagesTests.cpp b/Code/Tools/AssetProcessor/native/tests/AssetProcessorMessagesTests.cpp index c33943f9a7..04949c82a9 100644 --- a/Code/Tools/AssetProcessor/native/tests/AssetProcessorMessagesTests.cpp +++ b/Code/Tools/AssetProcessor/native/tests/AssetProcessorMessagesTests.cpp @@ -265,6 +265,9 @@ namespace AssetProcessorMessagesTests addPairFunc(new GetFullSourcePathFromRelativeProductPathRequest(), new GetFullSourcePathFromRelativeProductPathResponse()); addPairFunc(new GetRelativeProductPathFromFullSourceOrProductPathRequest(), new GetRelativeProductPathFromFullSourceOrProductPathResponse()); + addPairFunc( + new GenerateRelativeSourcePathRequest(), + new GenerateRelativeSourcePathResponse()); addPairFunc(new SourceAssetInfoRequest(), new SourceAssetInfoResponse()); addPairFunc(new SourceAssetProductsInfoRequest(), new SourceAssetProductsInfoResponse()); addPairFunc(new GetScanFoldersRequest(), new GetScanFoldersResponse()); diff --git a/Code/Tools/AssetProcessor/native/unittests/AssetProcessorManagerUnitTests.cpp b/Code/Tools/AssetProcessor/native/unittests/AssetProcessorManagerUnitTests.cpp index 5940caadb7..c632dc8a7a 100644 --- a/Code/Tools/AssetProcessor/native/unittests/AssetProcessorManagerUnitTests.cpp +++ b/Code/Tools/AssetProcessor/native/unittests/AssetProcessorManagerUnitTests.cpp @@ -51,6 +51,8 @@ namespace AssetProcessor public: using GetRelativeProductPathFromFullSourceOrProductPathRequest = AzFramework::AssetSystem::GetRelativeProductPathFromFullSourceOrProductPathRequest; using GetRelativeProductPathFromFullSourceOrProductPathResponse = AzFramework::AssetSystem::GetRelativeProductPathFromFullSourceOrProductPathResponse; + using GenerateRelativeSourcePathRequest = AzFramework::AssetSystem::GenerateRelativeSourcePathRequest; + using GenerateRelativeSourcePathResponse = AzFramework::AssetSystem::GenerateRelativeSourcePathResponse; using GetFullSourcePathFromRelativeProductPathRequest = AzFramework::AssetSystem::GetFullSourcePathFromRelativeProductPathRequest; using GetFullSourcePathFromRelativeProductPathResponse = AzFramework::AssetSystem::GetFullSourcePathFromRelativeProductPathResponse; }; diff --git a/Gems/Atom/RPI/Code/Tests/Common/AssetSystemStub.cpp b/Gems/Atom/RPI/Code/Tests/Common/AssetSystemStub.cpp index 84e8a4ba65..6b9c503ec2 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/AssetSystemStub.cpp +++ b/Gems/Atom/RPI/Code/Tests/Common/AssetSystemStub.cpp @@ -72,7 +72,15 @@ namespace UnitTest return false; } - bool AssetSystemStub::GetFullSourcePathFromRelativeProductPath([[maybe_unused]] const AZStd::string& relPath, [[maybe_unused]] AZStd::string& fullSourcePath) + bool AssetSystemStub::GenerateRelativeSourcePath( + [[maybe_unused]] const AZStd::string& sourcePath, [[maybe_unused]] AZStd::string& relativePath, + [[maybe_unused]] AZStd::string& watchFolder) + { + return false; + } + + bool AssetSystemStub::GetFullSourcePathFromRelativeProductPath( + [[maybe_unused]] const AZStd::string& relPath, [[maybe_unused]] AZStd::string& fullSourcePath) { return false; } diff --git a/Gems/Atom/RPI/Code/Tests/Common/AssetSystemStub.h b/Gems/Atom/RPI/Code/Tests/Common/AssetSystemStub.h index c6f4ac891f..48609ed0cb 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/AssetSystemStub.h +++ b/Gems/Atom/RPI/Code/Tests/Common/AssetSystemStub.h @@ -63,6 +63,8 @@ namespace UnitTest const char* GetAbsoluteDevGameFolderPath() override; const char* GetAbsoluteDevRootFolderPath() override; bool GetRelativeProductPathFromFullSourceOrProductPath(const AZStd::string& fullPath, AZStd::string& relativeProductPath) override; + bool GenerateRelativeSourcePath( + const AZStd::string& sourcePath, AZStd::string& relativePath, AZStd::string& watchFolder) override; bool GetFullSourcePathFromRelativeProductPath(const AZStd::string& relPath, AZStd::string& fullSourcePath) override; bool GetAssetInfoById(const AZ::Data::AssetId& assetId, const AZ::Data::AssetType& assetType, const AZStd::string& platformName, AZ::Data::AssetInfo& assetInfo, AZStd::string& rootFilePath) override; bool GetSourceInfoBySourceUUID(const AZ::Uuid& sourceUuid, AZ::Data::AssetInfo& assetInfo, AZStd::string& watchFolder) override; diff --git a/Gems/LmbrCentral/Code/Tests/Builders/CopyDependencyBuilderTest.cpp b/Gems/LmbrCentral/Code/Tests/Builders/CopyDependencyBuilderTest.cpp index f082ef74f9..44fe70af80 100644 --- a/Gems/LmbrCentral/Code/Tests/Builders/CopyDependencyBuilderTest.cpp +++ b/Gems/LmbrCentral/Code/Tests/Builders/CopyDependencyBuilderTest.cpp @@ -217,6 +217,9 @@ protected: const char* GetAbsoluteDevGameFolderPath() override { return ""; } const char* GetAbsoluteDevRootFolderPath() override { return ""; } bool GetRelativeProductPathFromFullSourceOrProductPath([[maybe_unused]] const AZStd::string& fullPath, [[maybe_unused]] AZStd::string& relativeProductPath) { return true; } + bool GenerateRelativeSourcePath( + [[maybe_unused]] const AZStd::string& sourcePath, [[maybe_unused]] AZStd::string& relativePath, + [[maybe_unused]] AZStd::string& watchFolder) { return true; } bool GetFullSourcePathFromRelativeProductPath([[maybe_unused]] const AZStd::string& relPath, [[maybe_unused]] AZStd::string& fullSourcePath) { return true; } bool GetAssetInfoById([[maybe_unused]] const AZ::Data::AssetId& assetId, [[maybe_unused]] const AZ::Data::AssetType& assetType, [[maybe_unused]] const AZStd::string& platformName, [[maybe_unused]] AZ::Data::AssetInfo& assetInfo, [[maybe_unused]] AZStd::string& rootFilePath) { return true; } bool GetSourceInfoBySourcePath([[maybe_unused]] const char* sourcePath, [[maybe_unused]] AZ::Data::AssetInfo& assetInfo, [[maybe_unused]] AZStd::string& watchFolder) { return true; } From 7830955680f15d1b883aec1cdded178b04b65ef0 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Wed, 26 May 2021 13:45:12 -0700 Subject: [PATCH 169/811] Add units for Rewindable containers and rework RewindableFixedVector to properly handle rewinding --- .../NetworkTime/RewindableFixedVector.h | 2 +- .../NetworkTime/RewindableFixedVector.inl | 60 +++++----- .../Code/Tests/RewindableContainerTests.cpp | 112 ++++++++++++++++++ .../Code/multiplayer_tests_files.cmake | 1 + 4 files changed, 147 insertions(+), 28 deletions(-) create mode 100644 Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h index 06e0655a9c..a9e365f5f9 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h @@ -118,7 +118,7 @@ namespace Multiplayer constexpr iterator end() { return m_container.end(); } private: - AZStd::fixed_vector, SIZE> m_container; + AZStd::array, SIZE> m_container; // Synchronized value for vector size, prefer using size() locally which checks m_container.size() RewindableObject m_rewindableSize; }; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl index 3353877478..5690e51c35 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.inl @@ -17,8 +17,8 @@ namespace Multiplayer template constexpr RewindableFixedVector::RewindableFixedVector(const TYPE& initialValue, uint32_t count) { - m_container.resize(count, initialValue); - m_rewindableSize = m_container.size(); + m_container.fill(initialValue); + m_rewindableSize = count; } template @@ -30,15 +30,14 @@ namespace Multiplayer template bool RewindableFixedVector::Serialize(AzNetworking::ISerializer& serializer) { - m_rewindableSize = m_container.size(); - if(!m_rewindableSize.Serialize(serializer) && !resize(m_rewindableSize)) + if(!m_rewindableSize.Serialize(serializer)) { return false; } - for (uint32_t i = 0; i < size(); ++i) + for (uint32_t idx = 0; idx < size(); ++idx) { - if(!m_container[i].Serialize(serializer)) + if(!m_container[idx].Serialize(serializer)) { return false; } @@ -53,8 +52,7 @@ namespace Multiplayer if (deltaRecord.GetBit(SIZE)) { const uint32_t origSize = m_rewindableSize; - m_rewindableSize = m_container.size(); - if(!m_rewindableSize.Serialize(serializer) && !resize(m_rewindableSize)) + if(!m_rewindableSize.Serialize(serializer)) { return false; } @@ -64,19 +62,19 @@ namespace Multiplayer deltaRecord.SetBit(SIZE, false); } } - for (uint32_t i = 0; i < size(); ++i) + for (uint32_t idx = 0; idx < size(); ++idx) { - if (deltaRecord.GetBit(i)) + if (deltaRecord.GetBit(idx)) { serializer.ClearTrackedChangesFlag(); - if(!m_container[i].Serialize(serializer)) + if(!m_container[idx].Serialize(serializer)) { return false; } if ((serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) && !serializer.GetTrackedChangesFlag()) { - deltaRecord.SetBit(i, false); + deltaRecord.SetBit(idx, false); } } } @@ -92,7 +90,7 @@ namespace Multiplayer return false; } - for (uint32_t idx = 0; idx < bufferSize; ++i) + for (uint32_t idx = 0; idx < bufferSize; ++idx) { m_container[idx] = buffer[idx]; } @@ -104,9 +102,9 @@ namespace Multiplayer constexpr RewindableFixedVector& RewindableFixedVector::operator=(const RewindableFixedVector& rhs) { resize(rhs.size()); - for (uint32_t idx = 0; idx < size(); ++i) + for (uint32_t idx = 0; idx < size(); ++idx) { - m_container[idx] = rhs.m_container[idx]; + m_container[idx] = rhs.m_container[idx].Get(); } return *this; } @@ -136,8 +134,14 @@ namespace Multiplayer return true; } - m_container.resize(count, TYPE()); - m_rewindableSize = m_container.size(); + if (count > size()) + { + for (uint32_t idx = size(); idx < count; ++idx) + { + m_container[idx] = TYPE(); + } + } + m_rewindableSize = count; return true; } @@ -150,8 +154,7 @@ namespace Multiplayer return false; } - m_container.resize_no_construct(count); - m_rewindableSize = m_container.size(); + m_rewindableSize = count; return true; } @@ -159,8 +162,11 @@ namespace Multiplayer template constexpr void RewindableFixedVector::clear() { - m_container.clear(); - m_rewindableSize = m_container.size(); + for (uint32_t idx = 0; idx < SIZE; ++idx) + { + m_container[idx] = TYPE(); + } + m_rewindableSize = 0; } template @@ -182,8 +188,8 @@ namespace Multiplayer { if (size() < SIZE) { - m_container.push_back(value); - m_rewindableSize = m_container.size(); + m_container[m_rewindableSize] = value; + m_rewindableSize = m_rewindableSize + 1; return true; } @@ -195,8 +201,8 @@ namespace Multiplayer { if (size() > 0) { - m_container.pop_back(); - m_rewindableSize = m_container.size(); + m_rewindableSize = m_rewindableSize - 1; + m_container[m_rewindableSize] = TYPE(); return true; } @@ -206,14 +212,14 @@ namespace Multiplayer template constexpr bool RewindableFixedVector::empty() const { - return m_container.empty(); + return m_rewindableSize.Get() == 0; } template constexpr const TYPE& RewindableFixedVector::back() const { AZ_Assert(size() > 0, "Attempted to get back element of an empty RewindableFixedVector"); - return m_container.back().Get(); + return m_container[m_rewindableSize - 1].Get(); } template diff --git a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp new file mode 100644 index 0000000000..af39dd8c1a --- /dev/null +++ b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp @@ -0,0 +1,112 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace UnitTest +{ + class RewindableContainerTests + : public AllocatorsFixture + { + public: + Multiplayer::NetworkTime m_networkTime; + AZ::LoggerSystemComponent m_loggerComponent; + AZ::TimeSystemComponent m_timeComponent; + }; + + static constexpr uint32_t RewindableContainerSize = 7; + static constexpr uint32_t RewindableBufferFrames = 32; + + TEST_F(RewindableContainerTests, BasicVectorTest) + { + Multiplayer::RewindableFixedVector test(0, 0); + + // Test push_back + for (uint32_t idx = 0; idx < RewindableContainerSize; ++idx) + { + test.push_back(idx); + EXPECT_EQ(idx, test[idx]); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); + } + + // Test rewind for all pushed values and overall size + for (uint32_t idx = 0; idx < RewindableContainerSize; ++idx) + { + Multiplayer::ScopedAlterTime time(static_cast(idx), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + EXPECT_EQ(idx + 1, test.size()); + EXPECT_EQ(idx, test.back()); + } + + // Test pop_back + test.pop_back(); + EXPECT_EQ(RewindableContainerSize - 1, test.size()); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); + + // Test clear and empty + test.clear(); + EXPECT_EQ(0, test.size()); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); + EXPECT_TRUE(test.empty()); + + // Test rewind for pop_back and clear + Multiplayer::ScopedAlterTime pop_time(static_cast(RewindableContainerSize), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + EXPECT_EQ(RewindableContainerSize - 1, test.size()); + Multiplayer::ScopedAlterTime clear_time(static_cast(RewindableContainerSize + 1), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + EXPECT_EQ(0, test.size()); + + // Test copy_values and resize_no_construct + test.resize_no_construct(RewindableContainerSize); + test.copy_values(&test[RewindableContainerSize-1], 1); + EXPECT_EQ(1, test.size()); + test.resize_no_construct(RewindableContainerSize); + EXPECT_EQ(test[0], test[RewindableContainerSize - 1]); + } + + TEST_F(RewindableContainerTests, BasicArrayTest) + { + Multiplayer::RewindableArray test; + + test.fill(0); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); + // Test push_back + for (uint32_t idx = 0; idx < RewindableContainerSize; ++idx) + { + test[idx] = idx; + EXPECT_EQ(idx, test[idx].Get()); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); + } + + // Test rewind for all values and overall size + for (uint32_t idx = 1; idx <= RewindableContainerSize; ++idx) + { + Multiplayer::ScopedAlterTime time(static_cast(idx), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + for (uint32_t testIdx = 0; testIdx < RewindableContainerSize; ++testIdx) + { + if (testIdx < idx) + { + EXPECT_EQ(testIdx, test[testIdx].Get()); + } + else + { + EXPECT_EQ(0, test[testIdx].Get()); + } + } + } + } +} diff --git a/Gems/Multiplayer/Code/multiplayer_tests_files.cmake b/Gems/Multiplayer/Code/multiplayer_tests_files.cmake index fe1ca38186..0731c25d3b 100644 --- a/Gems/Multiplayer/Code/multiplayer_tests_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_tests_files.cmake @@ -13,5 +13,6 @@ set(FILES Tests/Main.cpp Tests/IMultiplayerConnectionMock.h Tests/MultiplayerSystemTests.cpp + Tests/RewindableContainerTests.cpp Tests/RewindableObjectTests.cpp ) From d99fea7a98554fa633e2ac95993acfec1da70178 Mon Sep 17 00:00:00 2001 From: Brian Herrera Date: Wed, 26 May 2021 13:54:39 -0700 Subject: [PATCH 170/811] [Inclusion] Rename parameter for retry config Parameter was renamed to allowed_methods in urllib3 1.26.0. Both options are currently available in the version we are using now. --- scripts/build/lambda/trigger_first_build.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build/lambda/trigger_first_build.py b/scripts/build/lambda/trigger_first_build.py index 6ebe09f7ee..3b4587e737 100755 --- a/scripts/build/lambda/trigger_first_build.py +++ b/scripts/build/lambda/trigger_first_build.py @@ -53,7 +53,7 @@ def lambda_handler(event, context): backoff = 30 status_list = [404] # Retry if the branch doesn't exist yet and provide time for Jenkins to discover it. method_list = ['POST'] - retry_config = Retry(total=retries, backoff_factor=backoff, status_forcelist=status_list, method_whitelist=method_list) + retry_config = Retry(total=retries, backoff_factor=backoff, status_forcelist=status_list, allowed_methods=method_list) session = requests.Session() session.mount('https://', HTTPAdapter(max_retries=retry_config)) From 95963aa198c7bea23361b6b2a72bd9944335fd72 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Wed, 26 May 2021 14:11:09 -0700 Subject: [PATCH 171/811] Update iterators to account for rewindable size --- .../Include/Multiplayer/NetworkTime/RewindableFixedVector.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h index a9e365f5f9..c05fb98f72 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableFixedVector.h @@ -112,10 +112,10 @@ namespace Multiplayer typedef const RewindableObject* const_iterator; const_iterator begin() const { return m_container.cbegin(); } - const_iterator end() const { return m_container.cend(); } + const_iterator end() const { return m_container.cbegin() + aznumeric_cast(size()); } typedef RewindableObject* iterator; constexpr iterator begin() { return m_container.begin(); } - constexpr iterator end() { return m_container.end(); } + constexpr iterator end() { return m_container.begin() + aznumeric_cast(size()); } private: AZStd::array, SIZE> m_container; From 9103135275622947ae7e8265facd68b144ec29e9 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Wed, 26 May 2021 14:14:46 -0700 Subject: [PATCH 172/811] Add iterator test for RewindableFixedVector --- Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp index af39dd8c1a..2283f86267 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp @@ -58,6 +58,15 @@ namespace UnitTest EXPECT_EQ(RewindableContainerSize - 1, test.size()); Multiplayer::GetNetworkTime()->IncrementHostFrameId(); + uint32_t iterCount = 0; + auto iter = test.begin(); + while (iter != test.end()) + { + ++iterCount; + ++iter; + } + EXPECT_EQ(RewindableContainerSize - 1, iterCount); + // Test clear and empty test.clear(); EXPECT_EQ(0, test.size()); From 023dce00ffe485ac075e6712b9846390a97eec7c Mon Sep 17 00:00:00 2001 From: puvvadar Date: Wed, 26 May 2021 14:19:54 -0700 Subject: [PATCH 173/811] Fix syntax error in RewindableArray --- .../Code/Include/Multiplayer/NetworkTime/RewindableArray.inl | 4 ++-- Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.inl index b3fe18dd79..6e496ae4ea 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.inl +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableArray.inl @@ -17,7 +17,7 @@ namespace Multiplayer template bool RewindableArray::Serialize(AzNetworking::ISerializer& serializer) { - for (uint32_t i = 0; i < size(); ++i) + for (uint32_t i = 0; i < SIZE; ++i) { if(!this[i].Serialize(serializer)) { @@ -31,7 +31,7 @@ namespace Multiplayer template bool RewindableArray::Serialize(AzNetworking::ISerializer& serializer, AzNetworking::IBitset& deltaRecord) { - for (uint32_t i = 0; i < size(); ++i) + for (uint32_t i = 0; i < SIZE; ++i) { if (deltaRecord.GetBit(i)) { diff --git a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp index 2283f86267..e2e5afe6ed 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp @@ -58,6 +58,7 @@ namespace UnitTest EXPECT_EQ(RewindableContainerSize - 1, test.size()); Multiplayer::GetNetworkTime()->IncrementHostFrameId(); + // Test iterator uint32_t iterCount = 0; auto iter = test.begin(); while (iter != test.end()) From 37b53c06800f5eb4dcb4a86de53abb2bea51645b Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Tue, 25 May 2021 09:13:11 -0700 Subject: [PATCH 174/811] Spawnables can no longer be moved. Spawnables had support for moving, but as the base class AZ::Data::AssetData doesn't support moving this was causing subtle issues. Moving spawnables wasn't used so it was removed. --- .../AzFramework/Spawnable/Spawnable.cpp | 16 ---------------- .../AzFramework/Spawnable/Spawnable.h | 4 ++-- .../Prefab/Spawnable/SpawnableUtils.cpp | 11 ----------- .../Prefab/Spawnable/SpawnableUtils.h | 1 - 4 files changed, 2 insertions(+), 30 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/Spawnable.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/Spawnable.cpp index 7ab2d48814..46b3dfe87c 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/Spawnable.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/Spawnable.cpp @@ -21,22 +21,6 @@ namespace AzFramework { } - Spawnable::Spawnable(Spawnable&& other) - : m_entities(AZStd::move(other.m_entities)) - { - } - - - Spawnable& Spawnable::operator=(Spawnable&& other) - { - if (this != &other) - { - m_entities = AZStd::move(other.m_entities); - } - - return *this; - } - const Spawnable::EntityList& Spawnable::GetEntities() const { return m_entities; diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/Spawnable.h b/Code/Framework/AzFramework/AzFramework/Spawnable/Spawnable.h index 79cea647e4..677f0326cf 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/Spawnable.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/Spawnable.h @@ -41,11 +41,11 @@ namespace AzFramework Spawnable() = default; explicit Spawnable(const AZ::Data::AssetId& id, AssetStatus status = AssetStatus::NotLoaded); Spawnable(const Spawnable& rhs) = delete; - Spawnable(Spawnable&& other); + Spawnable(Spawnable&& other) = delete; ~Spawnable() override = default; Spawnable& operator=(const Spawnable& rhs) = delete; - Spawnable& operator=(Spawnable&& other); + Spawnable& operator=(Spawnable&& other) = delete; const EntityList& GetEntities() const; EntityList& GetEntities(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp index 716c3098d9..3c91f99b05 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp @@ -24,17 +24,6 @@ namespace AzToolsFramework::Prefab::SpawnableUtils { - - AzFramework::Spawnable CreateSpawnable(const PrefabDom& prefabDom) - { - AzFramework::Spawnable spawnable; - AZStd::vector> referencedAssets; - [[maybe_unused]] bool result = CreateSpawnable(spawnable, prefabDom, referencedAssets); - AZ_Assert(result, - "Failed to Load Prefab Instance from given Prefab DOM while Spawnable creation."); - return spawnable; - } - bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom) { AZStd::vector> referencedAssets; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h index 3b5ea488cb..cdf07346d0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h @@ -17,7 +17,6 @@ namespace AzToolsFramework::Prefab::SpawnableUtils { - AzFramework::Spawnable CreateSpawnable(const PrefabDom& prefabDom); bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom); bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets); From 76827ff95eab5bfbba5e2b763fb46ef4156db9aa Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Wed, 26 May 2021 09:23:53 -0700 Subject: [PATCH 175/811] Added support for a priority lane for entity spawning It's now possible to have high and normal priority calls on the spawnable entities manager. This allows for events like (de)spawning and retrieving information to be executed before already queued requests, though requests cannot be reordered on the same ticket. High priority calls are executed twice per frame, while normal priority calls are called only once. --- .../Spawnable/SpawnableEntitiesContainer.cpp | 18 ++- .../Spawnable/SpawnableEntitiesInterface.h | 58 ++++++-- .../Spawnable/SpawnableEntitiesManager.cpp | 127 +++++++++--------- .../Spawnable/SpawnableEntitiesManager.h | 64 ++++++--- .../Spawnable/SpawnableSystemComponent.cpp | 18 ++- .../Spawnable/SpawnableSystemComponent.h | 8 ++ .../SpawnableEntitiesManagerTests.cpp | 84 ++++++++++-- 7 files changed, 266 insertions(+), 111 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp index 673701cac4..e9a78dccde 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp @@ -38,19 +38,20 @@ namespace AzFramework void SpawnableEntitiesContainer::SpawnAllEntities() { AZ_Assert(m_threadData, "Calling SpawnAllEntities on a Spawnable container that's not set."); - SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_threadData->m_spawnedEntitiesTicket); + SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_threadData->m_spawnedEntitiesTicket, SpawnablePriorty_Default); } void SpawnableEntitiesContainer::SpawnEntities(AZStd::vector entityIndices) { AZ_Assert(m_threadData, "Calling SpawnEntities on a Spawnable container that's not set."); - SpawnableEntitiesInterface::Get()->SpawnEntities(m_threadData->m_spawnedEntitiesTicket, AZStd::move(entityIndices)); + SpawnableEntitiesInterface::Get()->SpawnEntities( + m_threadData->m_spawnedEntitiesTicket, SpawnablePriorty_Default, AZStd::move(entityIndices)); } void SpawnableEntitiesContainer::DespawnAllEntities() { AZ_Assert(m_threadData, "Calling DespawnEntities on a Spawnable container that's not set."); - SpawnableEntitiesInterface::Get()->DespawnAllEntities(m_threadData->m_spawnedEntitiesTicket); + SpawnableEntitiesInterface::Get()->DespawnAllEntities(m_threadData->m_spawnedEntitiesTicket, SpawnablePriorty_Default); } void SpawnableEntitiesContainer::Reset(AZ::Data::Asset spawnable) @@ -66,7 +67,9 @@ namespace AzFramework m_monitor.Disconnect(); m_monitor.m_threadData.reset(); - SpawnableEntitiesInterface::Get()->Barrier(m_threadData->m_spawnedEntitiesTicket, + SpawnableEntitiesInterface::Get()->Barrier( + m_threadData->m_spawnedEntitiesTicket, + SpawnablePriorty_Default, [threadData = m_threadData](EntitySpawnTicket&) mutable { threadData.reset(); @@ -83,7 +86,9 @@ namespace AzFramework void SpawnableEntitiesContainer::Alert(AlertCallback callback) { AZ_Assert(m_threadData, "Calling DespawnEntities on a Spawnable container that's not set."); - SpawnableEntitiesInterface::Get()->Barrier(m_threadData->m_spawnedEntitiesTicket, + SpawnableEntitiesInterface::Get()->Barrier( + m_threadData->m_spawnedEntitiesTicket, + SpawnablePriorty_Default, [generation = m_threadData->m_generation, callback = AZStd::move(callback)](EntitySpawnTicket&) { callback(generation); @@ -110,6 +115,7 @@ namespace AzFramework AZ_Assert(m_threadData, "SpawnableEntitiesContainer is monitoring a spawnable, but doesn't have the associated data."); AZ_TracePrintf("Spawnables", "Reloading spawnable '%s'.\n", replacementAsset.GetHint().c_str()); - SpawnableEntitiesInterface::Get()->ReloadSpawnable(m_threadData->m_spawnedEntitiesTicket, AZStd::move(replacementAsset)); + SpawnableEntitiesInterface::Get()->ReloadSpawnable( + m_threadData->m_spawnedEntitiesTicket, SpawnablePriorty_Default, AZStd::move(replacementAsset)); } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index 69bca8e111..97d06e1f37 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -24,6 +25,14 @@ namespace AZ namespace AzFramework { + AZ_TYPE_SAFE_INTEGRAL(SpawnablePriority, uint8_t); + + inline static constexpr SpawnablePriority SpawnablePriorty_Highest { 0 }; + inline static constexpr SpawnablePriority SpawnablePriorty_High { 32 }; + inline static constexpr SpawnablePriority SpawnablePriorty_Default { 128 }; + inline static constexpr SpawnablePriority SpawnablePriorty_Low { 192 }; + inline static constexpr SpawnablePriority SpawnablePriorty_Lowest { 255 }; + class SpawnableEntityContainerView { public: @@ -124,10 +133,10 @@ namespace AzFramework SpawnableIndexEntityIterator m_end; }; - //! Requests to the SpawnableEntitiesInterface require a ticket with a valid spawnable that be used as a template. A ticket can - //! be reused for multiple calls on the same spawnable and is safe to use by multiple threads at the same time. Entities created + //! Requests to the SpawnableEntitiesInterface require a ticket with a valid spawnable that is used as a template. A ticket can + //! be reused for multiple calls on the same spawnable and is safe to be used by multiple threads at the same time. Entities created //! from the spawnable may be tracked by the ticket and so using the same ticket is needed to despawn the exact entities created - //! by a call so spawn entities. The life cycle of the spawned entities is tied to the ticket and all entities spawned using a + //! by a call to spawn entities. The life cycle of the spawned entities is tied to the ticket and all entities spawned using a //! ticket will be despawned when it's deleted. class EntitySpawnTicket { @@ -159,10 +168,19 @@ namespace AzFramework using BarrierCallback = AZStd::function; //! Interface definition to (de)spawn entities from a spawnable into the game world. + //! //! While the callbacks of the individual calls are being processed they will block processing any other request. Callbacks can be //! issued from threads other than the one that issued the call, including the main thread. + //! //! Calls on the same ticket are guaranteed to be executed in the order they are issued. Note that when issuing requests from //! multiple threads on the same ticket the order in which the requests are assigned to the ticket is not guaranteed. + //! + //! Most calls have a priority where values closer to 0 mean higher priority than values closer to 255. The implementation of this + //! interface may choose to use priority lanes which doesn't guarantee that higher priority requests happen before lower priority + //! requests if they don't pass the priority lane threshold. Priority lanes and their thresholds are implementation specific and may + //! differ between platforms. Note that if a call happened on a ticket with lower priority followed by a one with a higher priority + //! the first lower priority call will still needs to complete before the second higher priority call can be executed and the priority + //! of the first call will not be updated. class SpawnableEntitiesDefinition { public: @@ -173,40 +191,48 @@ namespace AzFramework virtual ~SpawnableEntitiesDefinition() = default; //! Spawn instances of all entities in the spawnable. - //! @param spawnable The Spawnable asset that will be used to create entity instances from. //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. + //! @param priority The priority at which this call will be executed. //! @param completionCallback Optional callback that's called when spawning entities has completed. This can be called from //! a different thread than the one that made the function call. The returned list of entities contains all the newly //! created entities. - virtual void SpawnAllEntities(EntitySpawnTicket& ticket, EntityPreInsertionCallback preInsertionCallback = {}, + virtual void SpawnAllEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, EntityPreInsertionCallback preInsertionCallback = {}, EntitySpawnCallback completionCallback = {}) = 0; //! Spawn instances of some entities in the spawnable. //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. + //! @param priority The priority at which this call will be executed. //! @param entityIndices The indices into the template entities stored in the spawnable that will be used to spawn entities from. //! @param completionCallback Optional callback that's called when spawning entities has completed. This can be called from //! a different thread than the one that made this function call. The returned list of entities contains all the newly //! created entities. - virtual void SpawnEntities(EntitySpawnTicket& ticket, AZStd::vector entityIndices, + virtual void SpawnEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, AZStd::vector entityIndices, EntityPreInsertionCallback preInsertionCallback = {}, EntitySpawnCallback completionCallback = {}) = 0; //! Removes all entities in the provided list from the environment. //! @param ticket The ticket previously used to spawn entities with. + //! @param priority The priority at which this call will be executed. //! @param completionCallback Optional callback that's called when despawning entities has completed. This can be called from //! a different thread than the one that made this function call. - virtual void DespawnAllEntities(EntitySpawnTicket& ticket, EntityDespawnCallback completionCallback = {}) = 0; + virtual void DespawnAllEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, EntityDespawnCallback completionCallback = {}) = 0; //! Removes all entities in the provided list from the environment and reconstructs the entities from the provided spawnable. - //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. + //! @param ticket Holds the information on the entities to reload. + //! @param priority The priority at which this call will be executed. //! @param spawnable The spawnable that will replace the existing spawnable. Both need to have the same asset id. //! @param completionCallback Optional callback that's called when the entities have been reloaded. This can be called from //! a different thread than the one that made this function call. The returned list of entities contains all the replacement //! entities. - virtual void ReloadSpawnable(EntitySpawnTicket& ticket, AZ::Data::Asset spawnable, + virtual void ReloadSpawnable( + EntitySpawnTicket& ticket, SpawnablePriority priority, AZ::Data::Asset spawnable, ReloadSpawnableCallback completionCallback = {}) = 0; //! List all entities that are spawned using this ticket. //! @param ticket Only the entities associated with this ticket will be listed. + //! @param priority The priority at which this call will be executed. //! @param listCallback Required callback that will be called to list the entities on. - virtual void ListEntities(EntitySpawnTicket& ticket, ListEntitiesCallback listCallback) = 0; + virtual void ListEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ListEntitiesCallback listCallback) = 0; //! List all entities that are spawned using this ticket with their spawnable index. //! Spawnables contain a flat list of entities, which are used as templates to spawn entities from. For every spawned entity //! the index of the entity in the spawnable that was used as a template is stored. This version of ListEntities will return @@ -214,17 +240,23 @@ namespace AzFramework //! the same index may appear multiple times as there are no restriction on how many instance of a specific entity can be //! created. //! @param ticket Only the entities associated with this ticket will be listed. + //! @param priority The priority at which this call will be executed. //! @param listCallback Required callback that will be called to list the entities and indices on. - virtual void ListIndicesAndEntities(EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback) = 0; + virtual void ListIndicesAndEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, ListIndicesEntitiesCallback listCallback) = 0; //! Claim all entities that are spawned using this ticket. Ownership of the entities is transferred from the ticket to the //! caller through the callback. After this call the ticket will have no entities associated with it. The caller of //! this function will need to manage the entities after this call. //! @param ticket Only the entities associated with this ticket will be released. + //! @param priority The priority at which this call will be executed. //! @param listCallback Required callback that will be called to transfer the entities through. - virtual void ClaimEntities(EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback) = 0; + virtual void ClaimEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ClaimEntitiesCallback listCallback) = 0; //! Blocks until all operations made on the provided ticket before the barrier call have completed. - virtual void Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback) = 0; + //! @param ticket The ticket to monitor. + //! @param priority The priority at which this call will be executed. + //! @param completionCallback Required callback that will be called as soon as the barrier has been reached. + virtual void Barrier(EntitySpawnTicket& ticket, SpawnablePriority priority, BarrierCallback completionCallback) = 0; //! Register a handler for OnSpawned events. virtual void AddOnSpawnedHandler(AZ::Event>::Handler& handler) = 0; diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp index 7e20f7b265..959d2ab64f 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp @@ -22,7 +22,19 @@ namespace AzFramework { - void SpawnableEntitiesManager::SpawnAllEntities(EntitySpawnTicket& ticket, EntityPreInsertionCallback preInsertionCallback, + template + void SpawnableEntitiesManager::QueueRequest(EntitySpawnTicket& ticket, SpawnablePriority priority, T&& request) + { + Queue& queue = priority <= HighPriorityThreshold ? m_highPriorityQueue : m_regularPriorityQueue; + { + AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); + request.m_ticketId = GetTicketPayload(ticket).m_nextTicketId++; + queue.m_pendingRequest.push(AZStd::move(request)); + } + } + + void SpawnableEntitiesManager::SpawnAllEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, EntityPreInsertionCallback preInsertionCallback, EntitySpawnCallback completionCallback) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnAllEntities hasn't been initialized."); @@ -31,15 +43,11 @@ namespace AzFramework queueEntry.m_ticket = &ticket; queueEntry.m_completionCallback = AZStd::move(completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(preInsertionCallback); - { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); - queueEntry.m_ticketId = GetTicketPayload(ticket).m_nextTicketId++; - m_pendingRequestQueue.push(AZStd::move(queueEntry)); - } + QueueRequest(ticket, priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::SpawnEntities( - EntitySpawnTicket& ticket, AZStd::vector entityIndices, + EntitySpawnTicket& ticket, SpawnablePriority priority, AZStd::vector entityIndices, EntityPreInsertionCallback preInsertionCallback, EntitySpawnCallback completionCallback) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnEntities hasn't been initialized."); @@ -49,28 +57,22 @@ namespace AzFramework queueEntry.m_entityIndices = AZStd::move(entityIndices); queueEntry.m_completionCallback = AZStd::move(completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(preInsertionCallback); - { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); - queueEntry.m_ticketId = GetTicketPayload(ticket).m_nextTicketId++; - m_pendingRequestQueue.push(AZStd::move(queueEntry)); - } + QueueRequest(ticket, priority, AZStd::move(queueEntry)); } - void SpawnableEntitiesManager::DespawnAllEntities(EntitySpawnTicket& ticket, EntityDespawnCallback completionCallback) + void SpawnableEntitiesManager::DespawnAllEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, EntityDespawnCallback completionCallback) { AZ_Assert(ticket.IsValid(), "Ticket provided to DespawnAllEntities hasn't been initialized."); DespawnAllEntitiesCommand queueEntry; queueEntry.m_ticket = &ticket; queueEntry.m_completionCallback = AZStd::move(completionCallback); - { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); - queueEntry.m_ticketId = GetTicketPayload(ticket).m_nextTicketId++; - m_pendingRequestQueue.push(AZStd::move(queueEntry)); - } + QueueRequest(ticket, priority, AZStd::move(queueEntry)); } - void SpawnableEntitiesManager::ReloadSpawnable(EntitySpawnTicket& ticket, AZ::Data::Asset spawnable, + void SpawnableEntitiesManager::ReloadSpawnable( + EntitySpawnTicket& ticket, SpawnablePriority priority, AZ::Data::Asset spawnable, ReloadSpawnableCallback completionCallback) { AZ_Assert(ticket.IsValid(), "Ticket provided to ReloadSpawnable hasn't been initialized."); @@ -79,14 +81,10 @@ namespace AzFramework queueEntry.m_ticket = &ticket; queueEntry.m_spawnable = AZStd::move(spawnable); queueEntry.m_completionCallback = AZStd::move(completionCallback); - { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); - queueEntry.m_ticketId = GetTicketPayload(ticket).m_nextTicketId++; - m_pendingRequestQueue.push(AZStd::move(queueEntry)); - } + QueueRequest(ticket, priority, AZStd::move(queueEntry)); } - void SpawnableEntitiesManager::ListEntities(EntitySpawnTicket& ticket, ListEntitiesCallback listCallback) + void SpawnableEntitiesManager::ListEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ListEntitiesCallback listCallback) { AZ_Assert(listCallback, "ListEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized."); @@ -94,14 +92,11 @@ namespace AzFramework ListEntitiesCommand queueEntry; queueEntry.m_ticket = &ticket; queueEntry.m_listCallback = AZStd::move(listCallback); - { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); - queueEntry.m_ticketId = GetTicketPayload(ticket).m_nextTicketId++; - m_pendingRequestQueue.push(AZStd::move(queueEntry)); - } + QueueRequest(ticket, priority, AZStd::move(queueEntry)); } - void SpawnableEntitiesManager::ListIndicesAndEntities(EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback) + void SpawnableEntitiesManager::ListIndicesAndEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, ListIndicesEntitiesCallback listCallback) { AZ_Assert(listCallback, "ListEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized."); @@ -109,14 +104,10 @@ namespace AzFramework ListIndicesEntitiesCommand queueEntry; queueEntry.m_ticket = &ticket; queueEntry.m_listCallback = AZStd::move(listCallback); - { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); - queueEntry.m_ticketId = GetTicketPayload(ticket).m_nextTicketId++; - m_pendingRequestQueue.push(AZStd::move(queueEntry)); - } + QueueRequest(ticket, priority, AZStd::move(queueEntry)); } - void SpawnableEntitiesManager::ClaimEntities(EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback) + void SpawnableEntitiesManager::ClaimEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ClaimEntitiesCallback listCallback) { AZ_Assert(listCallback, "ClaimEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ClaimEntities hasn't been initialized."); @@ -124,14 +115,10 @@ namespace AzFramework ClaimEntitiesCommand queueEntry; queueEntry.m_ticket = &ticket; queueEntry.m_listCallback = AZStd::move(listCallback); - { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); - queueEntry.m_ticketId = GetTicketPayload(ticket).m_nextTicketId++; - m_pendingRequestQueue.push(AZStd::move(queueEntry)); - } + QueueRequest(ticket, priority, AZStd::move(queueEntry)); } - void SpawnableEntitiesManager::Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback) + void SpawnableEntitiesManager::Barrier(EntitySpawnTicket& ticket, SpawnablePriority priority, BarrierCallback completionCallback) { AZ_Assert(completionCallback, "Barrier on spawnable entities called without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to Barrier hasn't been initialized."); @@ -139,11 +126,7 @@ namespace AzFramework BarrierCommand queueEntry; queueEntry.m_ticket = &ticket; queueEntry.m_completionCallback = AZStd::move(completionCallback); - { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); - queueEntry.m_ticketId = GetTicketPayload(ticket).m_nextTicketId++; - m_pendingRequestQueue.push(AZStd::move(queueEntry)); - } + QueueRequest(ticket, priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::AddOnSpawnedHandler(AZ::Event>::Handler& handler) @@ -156,34 +139,54 @@ namespace AzFramework handler.Connect(m_onDespawnedEvent); } - auto SpawnableEntitiesManager::ProcessQueue() -> CommandQueueStatus + auto SpawnableEntitiesManager::ProcessQueue(CommandQueuePriority priority) -> CommandQueueStatus + { + CommandQueueStatus result = CommandQueueStatus::NoCommandsLeft; + if ((priority & CommandQueuePriority::High) == CommandQueuePriority::High) + { + if (ProcessQueue(m_highPriorityQueue) == CommandQueueStatus::HasCommandsLeft) + { + result = CommandQueueStatus::HasCommandsLeft; + } + } + if ((priority & CommandQueuePriority::Regular) == CommandQueuePriority::Regular) + { + if (ProcessQueue(m_regularPriorityQueue) == CommandQueueStatus::HasCommandsLeft) + { + result = CommandQueueStatus::HasCommandsLeft; + } + } + return result; + } + + auto SpawnableEntitiesManager::ProcessQueue(Queue& queue) -> CommandQueueStatus { AZStd::queue pendingRequestQueue; { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); - m_pendingRequestQueue.swap(pendingRequestQueue); + AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); + queue.m_pendingRequest.swap(pendingRequestQueue); } - if (!pendingRequestQueue.empty() || !m_delayedQueue.empty()) + if (!pendingRequestQueue.empty() || !queue.m_delayed.empty()) { AZ::SerializeContext* serializeContext = nullptr; AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); AZ_Assert(serializeContext, "Failed to retrieve serialization context."); // Only process the requests that are currently in this queue, not the ones that could be re-added if they still can't complete. - size_t delayedSize = m_delayedQueue.size(); + size_t delayedSize = queue.m_delayed.size(); for (size_t i = 0; i < delayedSize; ++i) { - Requests& request = m_delayedQueue.front(); + Requests& request = queue.m_delayed.front(); bool result = AZStd::visit([this, serializeContext](auto&& args) -> bool { return ProcessRequest(args, *serializeContext); }, request); if (!result) { - m_delayedQueue.emplace_back(AZStd::move(request)); + queue.m_delayed.emplace_back(AZStd::move(request)); } - m_delayedQueue.pop_front(); + queue.m_delayed.pop_front(); } do @@ -197,7 +200,7 @@ namespace AzFramework }, request); if (!result) { - m_delayedQueue.emplace_back(AZStd::move(request)); + queue.m_delayed.emplace_back(AZStd::move(request)); } pendingRequestQueue.pop(); } @@ -205,13 +208,13 @@ namespace AzFramework // Spawning entities can result in more entities being queued to spawn. Repeat spawning until the queue is // empty to avoid a chain of entity spawning getting dragged out over multiple frames. { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); - m_pendingRequestQueue.swap(pendingRequestQueue); + AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); + queue.m_pendingRequest.swap(pendingRequestQueue); } } while (!pendingRequestQueue.empty()); } - return m_delayedQueue.empty() ? CommandQueueStatus::NoCommandLeft : CommandQueueStatus::HasCommandsLeft; + return queue.m_delayed.empty() ? CommandQueueStatus::NoCommandsLeft : CommandQueueStatus::HasCommandsLeft; } void* SpawnableEntitiesManager::CreateTicket(AZ::Data::Asset&& spawnable) @@ -226,9 +229,9 @@ namespace AzFramework DestroyTicketCommand queueEntry; queueEntry.m_ticket = reinterpret_cast(ticket); { - AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex); + AZStd::scoped_lock queueLock(m_regularPriorityQueue.m_pendingRequestMutex); queueEntry.m_ticketId = reinterpret_cast(ticket)->m_nextTicketId++; - m_pendingRequestQueue.push(AZStd::move(queueEntry)); + m_regularPriorityQueue.m_pendingRequest.push(AZStd::move(queueEntry)); } } diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h index 3481ab180a..137376ac7b 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h @@ -29,8 +29,6 @@ namespace AZ namespace AzFramework { - using EntityIdMap = AZStd::unordered_map; - class SpawnableEntitiesManager : public SpawnableEntitiesInterface::Registrar { @@ -38,31 +36,48 @@ namespace AzFramework AZ_RTTI(AzFramework::SpawnableEntitiesManager, "{6E14333F-128C-464C-94CA-A63B05A5E51C}"); AZ_CLASS_ALLOCATOR(SpawnableEntitiesManager, AZ::SystemAllocator, 0); + using EntityIdMap = AZStd::unordered_map; + enum class CommandQueueStatus : bool { HasCommandsLeft, - NoCommandLeft + NoCommandsLeft }; + enum class CommandQueuePriority + { + High = 1 << 0, + Regular = 1 << 1 + }; + + static constexpr SpawnablePriority HighPriorityThreshold = SpawnablePriority { 64 }; + ~SpawnableEntitiesManager() override = default; // // The following functions are thread safe // - void SpawnAllEntities(EntitySpawnTicket& ticket, EntityPreInsertionCallback preInsertionCallback = {}, EntitySpawnCallback completionCallback = {}) override; - void SpawnEntities(EntitySpawnTicket& ticket, AZStd::vector entityIndices, EntityPreInsertionCallback preInsertionCallback = {}, + void SpawnAllEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, EntityPreInsertionCallback preInsertionCallback = {}, EntitySpawnCallback completionCallback = {}) override; - void DespawnAllEntities(EntitySpawnTicket& ticket, EntityDespawnCallback completionCallback = {}) override; + void SpawnEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, AZStd::vector entityIndices, + EntityPreInsertionCallback preInsertionCallback = {}, + EntitySpawnCallback completionCallback = {}) override; + void DespawnAllEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, EntityDespawnCallback completionCallback = {}) override; - void ReloadSpawnable(EntitySpawnTicket& ticket, AZ::Data::Asset spawnable, + void ReloadSpawnable( + EntitySpawnTicket& ticket, SpawnablePriority priority, AZ::Data::Asset spawnable, ReloadSpawnableCallback completionCallback = {}) override; - void ListEntities(EntitySpawnTicket& ticket, ListEntitiesCallback listCallback) override; - void ListIndicesAndEntities(EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback) override; - void ClaimEntities(EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback) override; + void ListEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ListEntitiesCallback listCallback) override; + void ListIndicesAndEntities( + EntitySpawnTicket& ticket, SpawnablePriority priority, ListIndicesEntitiesCallback listCallback) override; + void ClaimEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ClaimEntitiesCallback listCallback) override; - void Barrier(EntitySpawnTicket& spawnInfo, BarrierCallback completionCallback) override; + void Barrier(EntitySpawnTicket& spawnInfo, SpawnablePriority priority, BarrierCallback completionCallback) override; void AddOnSpawnedHandler(AZ::Event>::Handler& handler) override; void AddOnDespawnedHandler(AZ::Event>::Handler& handler) override; @@ -71,13 +86,9 @@ namespace AzFramework // The following function is thread safe but intended to be run from the main thread. // - CommandQueueStatus ProcessQueue(); + CommandQueueStatus ProcessQueue(CommandQueuePriority priority); protected: - void* CreateTicket(AZ::Data::Asset&& spawnable) override; - void DestroyTicket(void* ticket) override; - - private: struct Ticket { AZ_CLASS_ALLOCATOR(Ticket, AZ::ThreadPoolAllocator, 0); @@ -153,6 +164,20 @@ namespace AzFramework SpawnAllEntitiesCommand, SpawnEntitiesCommand, DespawnAllEntitiesCommand, ReloadSpawnableCommand, ListEntitiesCommand, ListIndicesEntitiesCommand, ClaimEntitiesCommand, BarrierCommand, DestroyTicketCommand>; + struct Queue + { + AZStd::deque m_delayed; //!< Requests that were processed before, but couldn't be completed. + AZStd::queue m_pendingRequest; //!< Requests waiting to be processed for the first time. + AZStd::mutex m_pendingRequestMutex; + }; + + template + void QueueRequest(EntitySpawnTicket& ticket, SpawnablePriority priority, T&& request); + void* CreateTicket(AZ::Data::Asset&& spawnable) override; + void DestroyTicket(void* ticket) override; + + CommandQueueStatus ProcessQueue(Queue& queue); + AZ::Entity* SpawnSingleEntity(const AZ::Entity& entityTemplate, AZ::SerializeContext& serializeContext); @@ -174,11 +199,12 @@ namespace AzFramework [[nodiscard]] static bool IsEqualTicket(const EntitySpawnTicket* lhs, const Ticket* rhs); [[nodiscard]] static bool IsEqualTicket(const Ticket* lhs, const Ticket* rhs); - AZStd::deque m_delayedQueue; //!< Requests that were processed before, but couldn't be completed. - AZStd::queue m_pendingRequestQueue; - AZStd::mutex m_pendingRequestQueueMutex; + Queue m_highPriorityQueue; + Queue m_regularPriorityQueue; AZ::Event> m_onSpawnedEvent; AZ::Event> m_onDespawnedEvent; }; + + AZ_DEFINE_ENUM_BITWISE_OPERATORS(AzFramework::SpawnableEntitiesManager::CommandQueuePriority); } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp index 262f006f15..32cc61914e 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp @@ -48,10 +48,23 @@ namespace AzFramework void SpawnableSystemComponent::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) { - m_entitiesManager.ProcessQueue(); + m_entitiesManager.ProcessQueue( + SpawnableEntitiesManager::CommandQueuePriority::High | SpawnableEntitiesManager::CommandQueuePriority::Regular); RootSpawnableNotificationBus::ExecuteQueuedEvents(); } + int SpawnableSystemComponent::GetTickOrder() + { + return AZ::ComponentTickBus::TICK_GAME; + } + + void SpawnableSystemComponent::OnSystemTick() + { + // Handle only high priority spawning events such as those created from network. These need to happen even if the server + // doesn't have focus to avoid + m_entitiesManager.ProcessQueue(SpawnableEntitiesManager::CommandQueuePriority::High); + } + void SpawnableSystemComponent::OnCatalogLoaded([[maybe_unused]] const char* catalogFile) { if (!m_catalogAvailable) @@ -168,7 +181,8 @@ namespace AzFramework SpawnableEntitiesManager::CommandQueueStatus queueStatus; do { - queueStatus = m_entitiesManager.ProcessQueue(); + queueStatus = m_entitiesManager.ProcessQueue( + SpawnableEntitiesManager::CommandQueuePriority::High | SpawnableEntitiesManager::CommandQueuePriority::Regular); } while (queueStatus == SpawnableEntitiesManager::CommandQueueStatus::HasCommandsLeft); } diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.h index b29fbea5e4..1549b86385 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.h @@ -28,6 +28,7 @@ namespace AzFramework class SpawnableSystemComponent : public AZ::Component , public AZ::TickBus::Handler + , public AZ::SystemTickBus::Handler , public AssetCatalogEventBus::Handler , public RootSpawnableInterface::Registrar , public RootSpawnableNotificationBus::Handler @@ -58,6 +59,13 @@ namespace AzFramework // void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + int GetTickOrder() override; + + // + // SystemTickBus + // + + void OnSystemTick() override; // // AssetCatalogEventBus diff --git a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp index 1fa50fff52..191b14c31d 100644 --- a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp +++ b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp @@ -55,7 +55,11 @@ namespace UnitTest delete m_ticket; m_ticket = nullptr; // One more tick on the spawnable entities manager in order to delete the ticket fully. - m_manager->ProcessQueue(); + while (m_manager->ProcessQueue( + AzFramework::SpawnableEntitiesManager::CommandQueuePriority::High | + AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular) != + AzFramework::SpawnableEntitiesManager::CommandQueueStatus::NoCommandsLeft) + ; delete m_spawnableAsset; m_spawnableAsset = nullptr; @@ -96,8 +100,8 @@ namespace UnitTest { spawnedEntitiesCount += entities.size(); }; - m_manager->SpawnAllEntities(*m_ticket, {}, AZStd::move(callback)); - m_manager->ProcessQueue(); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, {}, AZStd::move(callback)); + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); EXPECT_EQ(NumEntities, spawnedEntitiesCount); } @@ -119,9 +123,9 @@ namespace UnitTest spawnedEntitiesCount += entities.size(); }; - m_manager->SpawnAllEntities(*m_ticket); - m_manager->ListEntities(*m_ticket, AZStd::move(callback)); - m_manager->ProcessQueue(); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default); + m_manager->ListEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); EXPECT_TRUE(allValidEntityIds); EXPECT_EQ(NumEntities, spawnedEntitiesCount); @@ -148,11 +152,73 @@ namespace UnitTest } }; - m_manager->SpawnAllEntities(*m_ticket); - m_manager->ListIndicesAndEntities(*m_ticket, AZStd::move(callback)); - m_manager->ProcessQueue(); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default); + m_manager->ListIndicesAndEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); EXPECT_TRUE(allValidEntityIds); EXPECT_EQ(NumEntities, spawnedEntitiesCount); } + + TEST_F(SpawnableEntitiesManagerTest, Priority_HighBeforeDefault_HigherPriorityCallHappensBeforeDefaultPriorityEvenWhenQueuedLater) + { + static constexpr size_t NumEntities = 4; + FillSpawnable(NumEntities); + + AzFramework::EntitySpawnTicket highPriorityTicket(*m_spawnableAsset); + + size_t callCounter = 1; + size_t highPriorityCallId = 0; + size_t defaultPriorityCallId = 0; + auto highCallback = [&callCounter, &highPriorityCallId] + (AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstEntityContainerView) + { + highPriorityCallId = callCounter++; + }; + auto defaultCallback = [&callCounter, &defaultPriorityCallId] + (AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstEntityContainerView) + { + defaultPriorityCallId = callCounter++; + }; + + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, {}, AZStd::move(defaultCallback)); + m_manager->SpawnAllEntities(highPriorityTicket, AzFramework::SpawnablePriorty_High, {}, AZStd::move(highCallback)); + m_manager->ProcessQueue( + AzFramework::SpawnableEntitiesManager::CommandQueuePriority::High | + AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + + EXPECT_LT(highPriorityCallId, defaultPriorityCallId); + } + + TEST_F(SpawnableEntitiesManagerTest, Priority_SameTicket_DefaultPriorityCallHappensBeforeHighPriority) + { + static constexpr size_t NumEntities = 4; + FillSpawnable(NumEntities); + + size_t callCounter = 1; + size_t highPriorityCallId = 0; + size_t defaultPriorityCallId = 0; + auto highCallback = + [&callCounter, &highPriorityCallId](AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstEntityContainerView) + { + highPriorityCallId = callCounter++; + }; + auto defaultCallback = + [&callCounter, &defaultPriorityCallId](AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstEntityContainerView) + { + defaultPriorityCallId = callCounter++; + }; + + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, {}, AZStd::move(defaultCallback)); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_High, {}, AZStd::move(highCallback)); + m_manager->ProcessQueue( + AzFramework::SpawnableEntitiesManager::CommandQueuePriority::High | + AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + // Run a second time as the high priority task will be pending at this point. + m_manager->ProcessQueue( + AzFramework::SpawnableEntitiesManager::CommandQueuePriority::High | + AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + + EXPECT_LT(defaultPriorityCallId, highPriorityCallId); + } } // namespace UnitTest From e0948a26bc1cd169de8ae5a2f82bc8d69794aa1e Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Wed, 26 May 2021 14:26:16 -0700 Subject: [PATCH 176/811] Fixed early ticket delete crash This commit fixes a crash that could happen when a spawnable ticket was deleted before all requests in the queue had completed. Because of this crash the requests now only hold on to the payload of the ticket but not the ticket itself. As a side effect, callbacks can no longer provide the ticket itself so instead a unique id for the ticket is returned. --- .../Spawnable/SpawnableEntitiesContainer.cpp | 4 +- .../Spawnable/SpawnableEntitiesInterface.cpp | 13 +- .../Spawnable/SpawnableEntitiesInterface.h | 22 +-- .../Spawnable/SpawnableEntitiesManager.cpp | 101 ++++++------ .../Spawnable/SpawnableEntitiesManager.h | 48 +++--- .../SpawnableEntitiesManagerTests.cpp | 150 ++++++++++++++++-- 6 files changed, 242 insertions(+), 96 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp index e9a78dccde..9b06eb1f20 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp @@ -70,7 +70,7 @@ namespace AzFramework SpawnableEntitiesInterface::Get()->Barrier( m_threadData->m_spawnedEntitiesTicket, SpawnablePriorty_Default, - [threadData = m_threadData](EntitySpawnTicket&) mutable + [threadData = m_threadData](EntitySpawnTicket::Id) mutable { threadData.reset(); }); @@ -89,7 +89,7 @@ namespace AzFramework SpawnableEntitiesInterface::Get()->Barrier( m_threadData->m_spawnedEntitiesTicket, SpawnablePriorty_Default, - [generation = m_threadData->m_generation, callback = AZStd::move(callback)](EntitySpawnTicket&) + [generation = m_threadData->m_generation, callback = AZStd::move(callback)](EntitySpawnTicket::Id) { callback(generation); }); diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp index 97169ebeb3..26a10933b5 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp @@ -239,7 +239,9 @@ namespace AzFramework { auto manager = SpawnableEntitiesInterface::Get(); AZ_Assert(manager, "Attempting to create an entity spawn ticket while the SpawnableEntitiesInterface has no implementation."); - m_payload = manager->CreateTicket(AZStd::move(spawnable)); + AZStd::pair result = manager->CreateTicket(AZStd::move(spawnable)); + m_id = result.first; + m_payload = result.second; } EntitySpawnTicket::~EntitySpawnTicket() @@ -250,6 +252,7 @@ namespace AzFramework AZ_Assert(manager, "Attempting to destroy an entity spawn ticket while the SpawnableEntitiesInterface has no implementation."); manager->DestroyTicket(m_payload); m_payload = nullptr; + m_id = 0; } } @@ -263,12 +266,20 @@ namespace AzFramework AZ_Assert(manager, "Attempting to destroy an entity spawn ticket while the SpawnableEntitiesInterface has no implementation."); manager->DestroyTicket(m_payload); } + m_id = rhs.m_id; + rhs.m_id = 0; + m_payload = rhs.m_payload; rhs.m_payload = nullptr; } return *this; } + uint64_t EntitySpawnTicket::GetId() const + { + return m_id; + } + bool EntitySpawnTicket::IsValid() const { return m_payload != nullptr; diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index 97d06e1f37..b40136def7 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -143,6 +143,8 @@ namespace AzFramework public: friend class SpawnableEntitiesDefinition; + using Id = uint64_t; + EntitySpawnTicket() = default; EntitySpawnTicket(const EntitySpawnTicket&) = delete; EntitySpawnTicket(EntitySpawnTicket&& rhs); @@ -152,20 +154,22 @@ namespace AzFramework EntitySpawnTicket& operator=(const EntitySpawnTicket&) = delete; EntitySpawnTicket& operator=(EntitySpawnTicket&& rhs); + uint64_t GetId() const; bool IsValid() const; private: void* m_payload{ nullptr }; + Id m_id { 0 }; //!< An id that uniquely identifies a ticket. }; - using EntitySpawnCallback = AZStd::function; - using EntityPreInsertionCallback = AZStd::function; - using EntityDespawnCallback = AZStd::function; - using ReloadSpawnableCallback = AZStd::function; - using ListEntitiesCallback = AZStd::function; - using ListIndicesEntitiesCallback = AZStd::function; - using ClaimEntitiesCallback = AZStd::function; - using BarrierCallback = AZStd::function; + using EntitySpawnCallback = AZStd::function; + using EntityPreInsertionCallback = AZStd::function; + using EntityDespawnCallback = AZStd::function; + using ReloadSpawnableCallback = AZStd::function; + using ListEntitiesCallback = AZStd::function; + using ListIndicesEntitiesCallback = AZStd::function; + using ClaimEntitiesCallback = AZStd::function; + using BarrierCallback = AZStd::function; //! Interface definition to (de)spawn entities from a spawnable into the game world. //! @@ -265,7 +269,7 @@ namespace AzFramework virtual void AddOnDespawnedHandler(AZ::Event>::Handler& handler) = 0; protected: - [[nodiscard]] virtual void* CreateTicket(AZ::Data::Asset&& spawnable) = 0; + [[nodiscard]] virtual AZStd::pair CreateTicket(AZ::Data::Asset&& spawnable) = 0; virtual void DestroyTicket(void* ticket) = 0; template diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp index 959d2ab64f..caf1112e9b 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp @@ -25,10 +25,11 @@ namespace AzFramework template void SpawnableEntitiesManager::QueueRequest(EntitySpawnTicket& ticket, SpawnablePriority priority, T&& request) { + request.m_ticket = &GetTicketPayload(ticket); Queue& queue = priority <= HighPriorityThreshold ? m_highPriorityQueue : m_regularPriorityQueue; { AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); - request.m_ticketId = GetTicketPayload(ticket).m_nextTicketId++; + request.m_requestId = GetTicketPayload(ticket).m_nextRequestId++; queue.m_pendingRequest.push(AZStd::move(request)); } } @@ -40,7 +41,7 @@ namespace AzFramework AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnAllEntities hasn't been initialized."); SpawnAllEntitiesCommand queueEntry; - queueEntry.m_ticket = &ticket; + queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(preInsertionCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); @@ -53,7 +54,7 @@ namespace AzFramework AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnEntities hasn't been initialized."); SpawnEntitiesCommand queueEntry; - queueEntry.m_ticket = &ticket; + queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_entityIndices = AZStd::move(entityIndices); queueEntry.m_completionCallback = AZStd::move(completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(preInsertionCallback); @@ -66,7 +67,7 @@ namespace AzFramework AZ_Assert(ticket.IsValid(), "Ticket provided to DespawnAllEntities hasn't been initialized."); DespawnAllEntitiesCommand queueEntry; - queueEntry.m_ticket = &ticket; + queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(completionCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); } @@ -78,7 +79,7 @@ namespace AzFramework AZ_Assert(ticket.IsValid(), "Ticket provided to ReloadSpawnable hasn't been initialized."); ReloadSpawnableCommand queueEntry; - queueEntry.m_ticket = &ticket; + queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_spawnable = AZStd::move(spawnable); queueEntry.m_completionCallback = AZStd::move(completionCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); @@ -90,7 +91,7 @@ namespace AzFramework AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized."); ListEntitiesCommand queueEntry; - queueEntry.m_ticket = &ticket; + queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); } @@ -102,7 +103,7 @@ namespace AzFramework AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized."); ListIndicesEntitiesCommand queueEntry; - queueEntry.m_ticket = &ticket; + queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); } @@ -113,7 +114,7 @@ namespace AzFramework AZ_Assert(ticket.IsValid(), "Ticket provided to ClaimEntities hasn't been initialized."); ClaimEntitiesCommand queueEntry; - queueEntry.m_ticket = &ticket; + queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); } @@ -124,7 +125,7 @@ namespace AzFramework AZ_Assert(ticket.IsValid(), "Ticket provided to Barrier hasn't been initialized."); BarrierCommand queueEntry; - queueEntry.m_ticket = &ticket; + queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(completionCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); } @@ -217,11 +218,13 @@ namespace AzFramework return queue.m_delayed.empty() ? CommandQueueStatus::NoCommandsLeft : CommandQueueStatus::HasCommandsLeft; } - void* SpawnableEntitiesManager::CreateTicket(AZ::Data::Asset&& spawnable) + AZStd::pair SpawnableEntitiesManager::CreateTicket(AZ::Data::Asset&& spawnable) { + static AZStd::atomic_uint64_t idCounter { 1 }; + auto result = aznew Ticket(); result->m_spawnable = AZStd::move(spawnable); - return result; + return AZStd::make_pair(idCounter++, result); } void SpawnableEntitiesManager::DestroyTicket(void* ticket) @@ -230,7 +233,7 @@ namespace AzFramework queueEntry.m_ticket = reinterpret_cast(ticket); { AZStd::scoped_lock queueLock(m_regularPriorityQueue.m_pendingRequestMutex); - queueEntry.m_ticketId = reinterpret_cast(ticket)->m_nextTicketId++; + queueEntry.m_requestId = reinterpret_cast(ticket)->m_nextRequestId++; m_regularPriorityQueue.m_pendingRequest.push(AZStd::move(queueEntry)); } } @@ -254,8 +257,8 @@ namespace AzFramework bool SpawnableEntitiesManager::ProcessRequest(SpawnAllEntitiesCommand& request, AZ::SerializeContext& serializeContext) { - Ticket& ticket = GetTicketPayload(*request.m_ticket); - if (ticket.m_spawnable.IsReady() && request.m_ticketId == ticket.m_currentTicketId) + Ticket& ticket = *request.m_ticket; + if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { AZStd::vector& spawnedEntities = ticket.m_spawnedEntities; AZStd::vector& spawnedEntityIndices = ticket.m_spawnedEntityIndices; @@ -303,7 +306,7 @@ namespace AzFramework // Let other systems know about newly spawned entities for any pre-processing before adding to the scene/game context. if (request.m_preInsertionCallback) { - request.m_preInsertionCallback(*request.m_ticket, SpawnableEntityContainerView( + request.m_preInsertionCallback(request.m_ticketId, SpawnableEntityContainerView( ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end())); } @@ -317,13 +320,13 @@ namespace AzFramework // Let other systems know about newly spawned entities for any post-processing after adding to the scene/game context. if (request.m_completionCallback) { - request.m_completionCallback(*request.m_ticket, SpawnableConstEntityContainerView( + request.m_completionCallback(request.m_ticketId, SpawnableConstEntityContainerView( ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end())); } m_onSpawnedEvent.Signal(ticket.m_spawnable); - ticket.m_currentTicketId++; + ticket.m_currentRequestId++; return true; } else @@ -334,8 +337,8 @@ namespace AzFramework bool SpawnableEntitiesManager::ProcessRequest(SpawnEntitiesCommand& request, AZ::SerializeContext& serializeContext) { - Ticket& ticket = GetTicketPayload(*request.m_ticket); - if (ticket.m_spawnable.IsReady() && request.m_ticketId == ticket.m_currentTicketId) + Ticket& ticket = *request.m_ticket; + if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { AZStd::vector& spawnedEntities = ticket.m_spawnedEntities; AZStd::vector& spawnedEntityIndices = ticket.m_spawnedEntityIndices; @@ -370,9 +373,7 @@ namespace AzFramework // Let other systems know about newly spawned entities for any pre-processing before adding to the scene/game context. if (request.m_preInsertionCallback) { - request.m_preInsertionCallback( - *request.m_ticket, - SpawnableEntityContainerView( + request.m_preInsertionCallback(request.m_ticketId, SpawnableEntityContainerView( ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end())); } @@ -385,13 +386,13 @@ namespace AzFramework if (request.m_completionCallback) { - request.m_completionCallback(*request.m_ticket, SpawnableConstEntityContainerView( + request.m_completionCallback(request.m_ticketId, SpawnableConstEntityContainerView( ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end())); } m_onSpawnedEvent.Signal(ticket.m_spawnable); - ticket.m_currentTicketId++; + ticket.m_currentRequestId++; return true; } else @@ -403,8 +404,8 @@ namespace AzFramework bool SpawnableEntitiesManager::ProcessRequest(DespawnAllEntitiesCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) { - Ticket& ticket = GetTicketPayload(*request.m_ticket); - if (request.m_ticketId == ticket.m_currentTicketId) + Ticket& ticket = *request.m_ticket; + if (request.m_requestId == ticket.m_currentRequestId) { for (AZ::Entity* entity : ticket.m_spawnedEntities) { @@ -420,12 +421,12 @@ namespace AzFramework if (request.m_completionCallback) { - request.m_completionCallback(*request.m_ticket); + request.m_completionCallback(request.m_ticketId); } m_onDespawnedEvent.Signal(ticket.m_spawnable); - ticket.m_currentTicketId++; + ticket.m_currentRequestId++; return true; } else @@ -436,11 +437,11 @@ namespace AzFramework bool SpawnableEntitiesManager::ProcessRequest(ReloadSpawnableCommand& request, AZ::SerializeContext& serializeContext) { - Ticket& ticket = GetTicketPayload(*request.m_ticket); + Ticket& ticket = *request.m_ticket; AZ_Assert(ticket.m_spawnable.GetId() == request.m_spawnable.GetId(), "Spawnable is being reloaded, but the provided spawnable has a different asset id. " "This will likely result in unexpected entities being created."); - if (ticket.m_spawnable.IsReady() && request.m_ticketId == ticket.m_currentTicketId) + if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { // Delete the original entities. for (AZ::Entity* entity : ticket.m_spawnedEntities) @@ -496,11 +497,11 @@ namespace AzFramework if (request.m_completionCallback) { - request.m_completionCallback(*request.m_ticket, SpawnableConstEntityContainerView( + request.m_completionCallback(request.m_ticketId, SpawnableConstEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end())); } - ticket.m_currentTicketId++; + ticket.m_currentRequestId++; m_onSpawnedEvent.Signal(ticket.m_spawnable); @@ -514,12 +515,12 @@ namespace AzFramework bool SpawnableEntitiesManager::ProcessRequest(ListEntitiesCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) { - Ticket& ticket = GetTicketPayload(*request.m_ticket); - if (request.m_ticketId == ticket.m_currentTicketId) + Ticket& ticket = *request.m_ticket; + if (request.m_requestId == ticket.m_currentRequestId) { - request.m_listCallback(*request.m_ticket, SpawnableConstEntityContainerView( + request.m_listCallback(request.m_ticketId, SpawnableConstEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end())); - ticket.m_currentTicketId++; + ticket.m_currentRequestId++; return true; } else @@ -530,17 +531,15 @@ namespace AzFramework bool SpawnableEntitiesManager::ProcessRequest(ListIndicesEntitiesCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) { - Ticket& ticket = GetTicketPayload(*request.m_ticket); - if (request.m_ticketId == ticket.m_currentTicketId) + Ticket& ticket = *request.m_ticket; + if (request.m_requestId == ticket.m_currentRequestId) { AZ_Assert( ticket.m_spawnedEntities.size() == ticket.m_spawnedEntityIndices.size(), "Entities and indices on spawnable ticket have gone out of sync."); - request.m_listCallback( - *request.m_ticket, - SpawnableConstIndexEntityContainerView( + request.m_listCallback(request.m_ticketId, SpawnableConstIndexEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntityIndices.begin(), ticket.m_spawnedEntities.size())); - ticket.m_currentTicketId++; + ticket.m_currentRequestId++; return true; } else @@ -551,16 +550,16 @@ namespace AzFramework bool SpawnableEntitiesManager::ProcessRequest(ClaimEntitiesCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) { - Ticket& ticket = GetTicketPayload(*request.m_ticket); - if (request.m_ticketId == ticket.m_currentTicketId) + Ticket& ticket = *request.m_ticket; + if (request.m_requestId == ticket.m_currentRequestId) { - request.m_listCallback(*request.m_ticket, SpawnableEntityContainerView( + request.m_listCallback(request.m_ticketId, SpawnableEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end())); ticket.m_spawnedEntities.clear(); ticket.m_spawnedEntityIndices.clear(); - ticket.m_currentTicketId++; + ticket.m_currentRequestId++; return true; } else @@ -571,15 +570,15 @@ namespace AzFramework bool SpawnableEntitiesManager::ProcessRequest(BarrierCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) { - Ticket& ticket = GetTicketPayload(*request.m_ticket); - if (request.m_ticketId == ticket.m_currentTicketId) + Ticket& ticket = *request.m_ticket; + if (request.m_requestId == ticket.m_currentRequestId) { if (request.m_completionCallback) { - request.m_completionCallback(*request.m_ticket); + request.m_completionCallback(request.m_ticketId); } - ticket.m_currentTicketId++; + ticket.m_currentRequestId++; return true; } else @@ -590,7 +589,7 @@ namespace AzFramework bool SpawnableEntitiesManager::ProcessRequest(DestroyTicketCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) { - if (request.m_ticketId == request.m_ticket->m_currentTicketId) + if (request.m_requestId == request.m_ticket->m_currentRequestId) { for (AZ::Entity* entity : request.m_ticket->m_spawnedEntities) { diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h index 137376ac7b..b98be60145 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h @@ -97,8 +97,8 @@ namespace AzFramework AZStd::vector m_spawnedEntities; AZStd::vector m_spawnedEntityIndices; AZ::Data::Asset m_spawnable; - uint32_t m_nextTicketId{ 0 }; //!< Next id for this ticket. - uint32_t m_currentTicketId{ 0 }; //!< The id for the command that should be executed. + uint32_t m_nextRequestId{ 0 }; //!< Next id for this ticket. + uint32_t m_currentRequestId { 0 }; //!< The id for the command that should be executed. bool m_loadAll{ true }; }; @@ -106,58 +106,66 @@ namespace AzFramework { EntitySpawnCallback m_completionCallback; EntityPreInsertionCallback m_preInsertionCallback; - EntitySpawnTicket* m_ticket; - uint32_t m_ticketId; + Ticket* m_ticket; + EntitySpawnTicket::Id m_ticketId; + uint32_t m_requestId; }; struct SpawnEntitiesCommand { AZStd::vector m_entityIndices; EntitySpawnCallback m_completionCallback; EntityPreInsertionCallback m_preInsertionCallback; - EntitySpawnTicket* m_ticket; - uint32_t m_ticketId; + Ticket* m_ticket; + EntitySpawnTicket::Id m_ticketId; + uint32_t m_requestId; }; struct DespawnAllEntitiesCommand { EntityDespawnCallback m_completionCallback; - EntitySpawnTicket* m_ticket; - uint32_t m_ticketId; + Ticket* m_ticket; + EntitySpawnTicket::Id m_ticketId; + uint32_t m_requestId; }; struct ReloadSpawnableCommand { AZ::Data::Asset m_spawnable; ReloadSpawnableCallback m_completionCallback; - EntitySpawnTicket* m_ticket; - uint32_t m_ticketId; + Ticket* m_ticket; + EntitySpawnTicket::Id m_ticketId; + uint32_t m_requestId; }; struct ListEntitiesCommand { ListEntitiesCallback m_listCallback; - EntitySpawnTicket* m_ticket; - uint32_t m_ticketId; + Ticket* m_ticket; + EntitySpawnTicket::Id m_ticketId; + uint32_t m_requestId; }; struct ListIndicesEntitiesCommand { ListIndicesEntitiesCallback m_listCallback; - EntitySpawnTicket* m_ticket; - uint32_t m_ticketId; + Ticket* m_ticket; + EntitySpawnTicket::Id m_ticketId; + uint32_t m_requestId; }; struct ClaimEntitiesCommand { ClaimEntitiesCallback m_listCallback; - EntitySpawnTicket* m_ticket; - uint32_t m_ticketId; + Ticket* m_ticket; + EntitySpawnTicket::Id m_ticketId; + uint32_t m_requestId; }; struct BarrierCommand { BarrierCallback m_completionCallback; - EntitySpawnTicket* m_ticket; - uint32_t m_ticketId; + Ticket* m_ticket; + EntitySpawnTicket::Id m_ticketId; + uint32_t m_requestId; }; struct DestroyTicketCommand { Ticket* m_ticket; - uint32_t m_ticketId; + uint32_t m_requestId; }; using Requests = AZStd::variant< @@ -173,7 +181,7 @@ namespace AzFramework template void QueueRequest(EntitySpawnTicket& ticket, SpawnablePriority priority, T&& request); - void* CreateTicket(AZ::Data::Asset&& spawnable) override; + AZStd::pair CreateTicket(AZ::Data::Asset&& spawnable) override; void DestroyTicket(void* ticket) override; CommandQueueStatus ProcessQueue(Queue& queue); diff --git a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp index 191b14c31d..320e2ec435 100644 --- a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp +++ b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp @@ -89,6 +89,10 @@ namespace UnitTest TestApplication* m_application { nullptr }; }; + // + // SpawnAllEntitities + // + TEST_F(SpawnableEntitiesManagerTest, SpawnAllEntities_Call_AllEntitiesSpawned) { static constexpr size_t NumEntities = 4; @@ -96,7 +100,7 @@ namespace UnitTest size_t spawnedEntitiesCount = 0; auto callback = - [&spawnedEntitiesCount](AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstEntityContainerView entities) + [&spawnedEntitiesCount](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) { spawnedEntitiesCount += entities.size(); }; @@ -106,6 +110,62 @@ namespace UnitTest EXPECT_EQ(NumEntities, spawnedEntitiesCount); } + TEST_F(SpawnableEntitiesManagerTest, SpawnAllEntities_DeleteTicketBeforeCall_NoCrash) + { + { + AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); + m_manager->SpawnAllEntities(ticket, AzFramework::SpawnablePriorty_Default); + } + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + + + // + // SpawnEntities + // + + TEST_F(SpawnableEntitiesManagerTest, SpawnEntities_DeleteTicketBeforeCall_NoCrash) + { + { + AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); + m_manager->SpawnEntities(ticket, AzFramework::SpawnablePriorty_Default, {}); + } + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + + + // + // DespawnAllEntities + // + + TEST_F(SpawnableEntitiesManagerTest, DespawnAllEntities_DeleteTicketBeforeCall_NoCrash) + { + { + AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); + m_manager->DespawnAllEntities(ticket, AzFramework::SpawnablePriorty_Default); + } + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + + + // + // ReloadSpawnable + // + + TEST_F(SpawnableEntitiesManagerTest, ReloadSpawnable_DeleteTicketBeforeCall_NoCrash) + { + { + AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); + m_manager->ReloadSpawnable(ticket, AzFramework::SpawnablePriorty_Default, *m_spawnableAsset); + } + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + + + // + // ListEntitities + // + TEST_F(SpawnableEntitiesManagerTest, ListEntities_Call_AllEntitiesAreReported) { static constexpr size_t NumEntities = 4; @@ -114,7 +174,7 @@ namespace UnitTest bool allValidEntityIds = true; size_t spawnedEntitiesCount = 0; auto callback = [&allValidEntityIds, &spawnedEntitiesCount] - (AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstEntityContainerView entities) + (AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) { for (auto&& entity : entities) { @@ -131,6 +191,22 @@ namespace UnitTest EXPECT_EQ(NumEntities, spawnedEntitiesCount); } + TEST_F(SpawnableEntitiesManagerTest, ListEntities_DeleteTicketBeforeCall_NoCrash) + { + auto callback = [](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView) {}; + + { + AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); + m_manager->ListEntities(ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + } + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + + + // + // ListIndicesAndEntities + // + TEST_F(SpawnableEntitiesManagerTest, ListIndicesAndEntities_Call_AllEntitiesAreReportedAndIncrementByOne) { static constexpr size_t NumEntities = 4; @@ -139,7 +215,7 @@ namespace UnitTest bool allValidEntityIds = true; size_t spawnedEntitiesCount = 0; auto callback = [&allValidEntityIds, &spawnedEntitiesCount] - (AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstIndexEntityContainerView entities) + (AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstIndexEntityContainerView entities) { for (auto&& indexEntityPair : entities) { @@ -160,6 +236,54 @@ namespace UnitTest EXPECT_EQ(NumEntities, spawnedEntitiesCount); } + TEST_F(SpawnableEntitiesManagerTest, ListIndicesAndEntities_DeleteTicketBeforeCall_NoCrash) + { + auto callback = [](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstIndexEntityContainerView) {}; + + { + AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); + m_manager->ListIndicesAndEntities(ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + } + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + + + // + // ClaimEntities + // + + TEST_F(SpawnableEntitiesManagerTest, ClaimEntities_DeleteTicketBeforeCall_NoCrash) + { + auto callback = [](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableEntityContainerView) {}; + + { + AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); + m_manager->ClaimEntities(ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + } + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + + + // + // Barrier + // + + TEST_F(SpawnableEntitiesManagerTest, Barrier_DeleteTicketBeforeCall_NoCrash) + { + auto callback = [](AzFramework::EntitySpawnTicket::Id) {}; + + { + AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); + m_manager->Barrier(ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + } + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + + + // + // Misc. - Priority tests + // + TEST_F(SpawnableEntitiesManagerTest, Priority_HighBeforeDefault_HigherPriorityCallHappensBeforeDefaultPriorityEvenWhenQueuedLater) { static constexpr size_t NumEntities = 4; @@ -171,12 +295,12 @@ namespace UnitTest size_t highPriorityCallId = 0; size_t defaultPriorityCallId = 0; auto highCallback = [&callCounter, &highPriorityCallId] - (AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstEntityContainerView) + (AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView) { highPriorityCallId = callCounter++; }; auto defaultCallback = [&callCounter, &defaultPriorityCallId] - (AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstEntityContainerView) + (AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView) { defaultPriorityCallId = callCounter++; }; @@ -199,15 +323,15 @@ namespace UnitTest size_t highPriorityCallId = 0; size_t defaultPriorityCallId = 0; auto highCallback = - [&callCounter, &highPriorityCallId](AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstEntityContainerView) - { - highPriorityCallId = callCounter++; - }; + [&callCounter, &highPriorityCallId](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView) + { + highPriorityCallId = callCounter++; + }; auto defaultCallback = - [&callCounter, &defaultPriorityCallId](AzFramework::EntitySpawnTicket&, AzFramework::SpawnableConstEntityContainerView) - { - defaultPriorityCallId = callCounter++; - }; + [&callCounter, &defaultPriorityCallId](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView) + { + defaultPriorityCallId = callCounter++; + }; m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, {}, AZStd::move(defaultCallback)); m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_High, {}, AZStd::move(highCallback)); From 2c4ab59ee5b9cebedaabb68a4df64e4f10ce7131 Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 26 May 2021 14:38:26 -0700 Subject: [PATCH 177/811] clearing variable --- cmake/SettingsRegistry.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index 07ed89c218..63d67f7b2b 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -146,6 +146,7 @@ function(ly_delayed_generate_settings_registry) list(REMOVE_DUPLICATES all_gem_dependencies) # de-namespace them + unset(new_gem_dependencies) foreach(gem_target ${all_gem_dependencies}) ly_de_alias_target(${gem_target} stripped_gem_target) list(APPEND new_gem_dependencies ${stripped_gem_target}) From 4b16d34af8eca2226b1f2a154bfb5e67910daaf4 Mon Sep 17 00:00:00 2001 From: greerdv Date: Wed, 26 May 2021 23:00:01 +0100 Subject: [PATCH 178/811] update usages of vector scale on Transform to use uniform scale --- .../Code/EMotionFX/Rendering/Common/RenderUtil.cpp | 4 ++-- Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h | 2 +- .../Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp | 6 +++--- Gems/EMotionFX/Code/EMotionFX/Source/Transform.cpp | 2 +- Gems/EMotionFX/Code/MCore/Source/AzCoreConversions.h | 4 ++-- Gems/EMotionFX/Code/MCore/Source/OBB.cpp | 6 +++--- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp index 3a23241385..35f601a270 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp @@ -1298,10 +1298,10 @@ namespace MCommon // render a cube - void RenderUtil::RenderCube(const AZ::Vector3& size, const AZ::Vector3& position, const MCore::RGBAColor& color) + void RenderUtil::RenderCube(float size, const AZ::Vector3& position, const MCore::RGBAColor& color) { // setup the world space matrix of the cube - AZ::Transform cubeTransform = AZ::Transform::CreateScale(size); + AZ::Transform cubeTransform = AZ::Transform::CreateUniformScale(size); cubeTransform.SetTranslation(position); // render the cube diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h index 86e41e56ef..e674943e53 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h @@ -303,7 +303,7 @@ namespace MCommon * @param position The position of the center of the cube. * @param color The desired cube color. */ - void RenderCube(const AZ::Vector3& size, const AZ::Vector3& position, const MCore::RGBAColor& color); + void RenderCube(float size, const AZ::Vector3& position, const MCore::RGBAColor& color); /** * Render a triangle (CCW). diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp index 32b779f385..7fdec63f66 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp @@ -169,7 +169,7 @@ namespace MCommon if (mXAxisVisible) { renderUtil->RenderLine(mPosition, mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + 0.5f * mBaseRadius, 0.0f, 0.0f), xAxisColor); - //renderUtil->RenderCube( Vector3(mBaseRadius, mBaseRadius, mBaseRadius), mPosition + mSignX * Vector3(mScaledSize.x+mBaseRadius, 0, 0), ManipulatorColors::mRed ); + //renderUtil->RenderCube( mBaseRadius, mPosition + mSignX * Vector3(mScaledSize.x+mBaseRadius, 0, 0), ManipulatorColors::mRed ); AZ::Vector3 quadPos = MCore::Project(mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + mBaseRadius, 0, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight); renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::mRed, ManipulatorColors::mRed); @@ -186,7 +186,7 @@ namespace MCommon if (mYAxisVisible) { renderUtil->RenderLine(mPosition, mPosition + mSignY * AZ::Vector3(0.0f, mScaledSize.GetY(), 0.0f), yAxisColor); - //renderUtil->RenderCube( Vector3(mBaseRadius, mBaseRadius, mBaseRadius), mPosition + mSignY * Vector3(0, mScaledSize.y+0.5*mBaseRadius, 0), ManipulatorColors::mGreen ); + //renderUtil->RenderCube( mBaseRadius, mPosition + mSignY * Vector3(0, mScaledSize.y+0.5*mBaseRadius, 0), ManipulatorColors::mGreen ); AZ::Vector3 quadPos = MCore::Project(mPosition + mSignY * AZ::Vector3(0, mScaledSize.GetY() + 0.5f * mBaseRadius, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight); renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::mGreen, ManipulatorColors::mGreen); @@ -203,7 +203,7 @@ namespace MCommon if (mZAxisVisible) { renderUtil->RenderLine(mPosition, mPosition + mSignZ * AZ::Vector3(0.0f, 0.0f, mScaledSize.GetZ()), zAxisColor); - //renderUtil->RenderCube( Vector3(mBaseRadius, mBaseRadius, mBaseRadius), mPosition + mSignZ * Vector3(0, 0, mScaledSize.z+0.5*mBaseRadius), ManipulatorColors::mBlue ); + //renderUtil->RenderCube( mBaseRadius, mPosition + mSignZ * Vector3(0, 0, mScaledSize.z+0.5*mBaseRadius), ManipulatorColors::mBlue ); AZ::Vector3 quadPos = MCore::Project(mPosition + mSignZ * AZ::Vector3(0, 0, mScaledSize.GetZ() + 0.5f * mBaseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::mBlue, ManipulatorColors::mBlue); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Transform.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Transform.cpp index b2322b5379..e3195beba9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Transform.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Transform.cpp @@ -183,7 +183,7 @@ namespace EMotionFX { #ifndef EMFX_SCALE_DISABLED mPosition = transform.GetTranslation(); - mScale = transform.GetScale(); + mScale = AZ::Vector3(transform.GetUniformScale()); mRotation = transform.GetRotation(); #else mPosition = transform.GetTranslation(); diff --git a/Gems/EMotionFX/Code/MCore/Source/AzCoreConversions.h b/Gems/EMotionFX/Code/MCore/Source/AzCoreConversions.h index 519d44dace..fdead82491 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AzCoreConversions.h +++ b/Gems/EMotionFX/Code/MCore/Source/AzCoreConversions.h @@ -58,7 +58,7 @@ namespace MCore AZ::Transform transform = AZ::Transform::CreateFromQuaternionAndTranslation(emfxTransform.mRotation, emfxTransform.mPosition); EMFX_SCALECODE ( - transform.MultiplyByScale(emfxTransform.mScale); + transform.MultiplyByUniformScale(emfxTransform.mScale.GetMaxElement()); ) return transform; } @@ -386,7 +386,7 @@ namespace MCore AZ::Transform result; result.SetTranslation(translation); result.SetRotation(rotation); - result.SetScale(scale); + result.SetUniformScale(scale.GetMaxElement()); return result; } diff --git a/Gems/EMotionFX/Code/MCore/Source/OBB.cpp b/Gems/EMotionFX/Code/MCore/Source/OBB.cpp index bb73f9413b..e7a0011684 100644 --- a/Gems/EMotionFX/Code/MCore/Source/OBB.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/OBB.cpp @@ -96,9 +96,9 @@ namespace MCore // create the AABB of (box1 in space of box0) const AZ::Transform& mtx = _1in0.mRotation; - AZ::Vector3 transformedAxisX = mtx.GetScale() * (mtx.GetRotation().GetConjugate().TransformVector(AZ::Vector3::CreateAxisX())); - AZ::Vector3 transformedAxisY = mtx.GetScale() * (mtx.GetRotation().GetConjugate().TransformVector(AZ::Vector3::CreateAxisY())); - AZ::Vector3 transformedAxisZ = mtx.GetScale() * (mtx.GetRotation().GetConjugate().TransformVector(AZ::Vector3::CreateAxisZ())); + AZ::Vector3 transformedAxisX = mtx.GetUniformScale() * (mtx.GetRotation().GetConjugate().TransformVector(AZ::Vector3::CreateAxisX())); + AZ::Vector3 transformedAxisY = mtx.GetUniformScale() * (mtx.GetRotation().GetConjugate().TransformVector(AZ::Vector3::CreateAxisY())); + AZ::Vector3 transformedAxisZ = mtx.GetUniformScale() * (mtx.GetRotation().GetConjugate().TransformVector(AZ::Vector3::CreateAxisZ())); float f = transformedAxisX.GetAbs().Dot(mExtents) - box.mExtents.GetX(); if (f > _1in0.mCenter.GetX()) From 5fa67c23db520a88b667b14ac4f3b04317517193 Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Wed, 26 May 2021 17:18:29 -0500 Subject: [PATCH 179/811] SPEC-6685: Adding/updating more test summaries for TestRail decoupling effort --- ...tPreviewSettings_DefaultPinnedEntityIsSelf.py | 16 +++++++++++++++- ...entSurfaceTagEmitter_ComponentDependencies.py | 16 +++++++++++++--- .../GradientTransform_RequiresShape.py | 16 ++++++++++++++-- .../EditorScripts/ImageGradient_RequiresShape.py | 16 ++++++++++++++-- 4 files changed, 56 insertions(+), 8 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py index 5a758b9d89..b8f4114d30 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py @@ -44,7 +44,21 @@ class TestGradientPreviewSettings(EditorTestHelper): def run_test(self): """ Summary: - Verify if the current entity is set to the pin preview to shape entity by default for several components. + This test verifies default values for the pinned entity for Gradient Preview settings. + + Expected Behavior: + Pinned entity is self for all gradient generator/modifiers. + + Test Steps: + 1) Create a new level + 2) Create a new entity in the level + 3) Add each Gradient Generator component to an entity, and verify the Pin Preview to Shape property is set to + self + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. :return: None """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py index a16e37e0fc..8e2d0611af 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py @@ -31,11 +31,21 @@ class TestGradientSurfaceTagEmitterDependencies(EditorTestHelper): def run_test(self): """ Summary: - Component has a dependency on a Gradient component + This test verifies that the Gradient Surface Tag Emitter component is dependent on a gradient component. Expected Result: - Component is disabled until a Gradient Generator, Modifier or Gradient Reference component - (and any sub-dependencies) is added to the entity. + Gradient Surface Tag Emitter component is disabled until a Gradient Generator, Modifier or Gradient Reference + component (and any sub-dependencies) is added to the entity. + + Test Steps: + 1) Open level + 2) Create a new entity with a Gradient Surface Tag Emitter component + 3) Verify the component is disabled until a dependent component is also added to the entity + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. :return: None """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py index e1e901f2f7..2311363db9 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py @@ -28,8 +28,20 @@ class TestGradientTransformRequiresShape(EditorTestHelper): def run_test(self): """ Summary: - Verify that Gradient Transform Modifier component requires a - Shape component before the Entity can become active. + This test verifies that the Gradient Transform Modifier component is dependent on a shape component. + + Expected Result: + Gradient Transform Modifier component is disabled until a shape component is added to the entity. + + Test Steps: + 1) Open level + 2) Create a new entity with a Gradient Transform Modifier component + 3) Verify the component is disabled until a shape component is also added to the entity + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. :return: None """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py index dab8e6928a..a5d9632fd6 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py @@ -28,8 +28,20 @@ class TestImageGradientRequiresShape(EditorTestHelper): def run_test(self): """ Summary: - Verify that Image Gradient component requires a - Shape component before the Entity can become active. + This test verifies that the Image Gradient component is dependent on a shape component. + + Expected Result: + Gradient Transform Modifier component is disabled until a shape component is added to the entity. + + Test Steps: + 1) Open level + 2) Create a new entity with a Image Gradient component + 3) Verify the component is disabled until a shape component is also added to the entity + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. :return: None """ From ab0a1cee2fab3cc3643f1af80fa2ec9782961e34 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Wed, 26 May 2021 15:33:10 -0700 Subject: [PATCH 180/811] Fix inadvertent redefine in Test --- Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp index e2e5afe6ed..0653dd5e08 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp @@ -31,7 +31,6 @@ namespace UnitTest }; static constexpr uint32_t RewindableContainerSize = 7; - static constexpr uint32_t RewindableBufferFrames = 32; TEST_F(RewindableContainerTests, BasicVectorTest) { From 4b610058b5eadc9f2885885094eb2858cebb8db5 Mon Sep 17 00:00:00 2001 From: chiyteng Date: Wed, 26 May 2021 15:47:41 -0700 Subject: [PATCH 181/811] implement function DetachPrefabFromParent in PrefabPublicHandler --- .../Prefab/Instance/Instance.cpp | 12 + .../Prefab/Instance/Instance.h | 5 +- .../Instance/InstanceToTemplatePropagator.cpp | 5 + .../Prefab/PrefabPublicHandler.cpp | 224 +++++++++++++++++- .../Prefab/PrefabPublicHandler.h | 2 + .../Prefab/PrefabPublicInterface.h | 8 + .../UI/Prefab/PrefabIntegrationManager.cpp | 32 +++ .../UI/Prefab/PrefabIntegrationManager.h | 1 + 8 files changed, 275 insertions(+), 14 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp index c4cb3e0316..8c7604f680 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp @@ -401,6 +401,17 @@ namespace AzToolsFramework } } + InstancePtrOptionalReference Instance::GetNestedInstance(const InstanceAlias& instanceAlias) + { + auto nestedInstanceIterator = m_nestedInstances.find(instanceAlias); + if (nestedInstanceIterator != m_nestedInstances.end()) + { + return nestedInstanceIterator->second; + } + + return AZStd::nullopt; + } + void Instance::GetNestedInstances(const AZStd::function&)>& callback) { for (auto& [instanceAlias, instance] : m_nestedInstances) @@ -613,6 +624,7 @@ namespace AzToolsFramework AZStd::unique_ptr Instance::DetachContainerEntity() { + m_instanceEntityMapper->UnregisterEntity(m_containerEntity->GetId()); return AZStd::move(m_containerEntity); } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h index 821478b706..377be68753 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h @@ -48,6 +48,8 @@ namespace AzToolsFramework using EntityAliasOptionalReference = AZStd::optional>; using InstanceOptionalReference = AZStd::optional>; using InstanceOptionalConstReference = AZStd::optional>; + using InstancePtrOptionalReference = AZStd::optional>>; + using InstanceSet = AZStd::unordered_set; using InstanceSetConstReference = AZStd::optional>; using EntityOptionalReference = AZStd::optional>; @@ -85,6 +87,7 @@ namespace AzToolsFramework bool AddEntity(AZ::Entity& entity); bool AddEntity(AZ::Entity& entity, EntityAlias entityAlias); AZStd::unique_ptr DetachEntity(const AZ::EntityId& entityId); + void DetachEntities(const AZStd::function)>& callback); void DetachNestedEntities(const AZStd::function)>& callback); void RemoveNestedEntities(const AZStd::function&)>& filter); @@ -92,6 +95,7 @@ namespace AzToolsFramework Instance& AddInstance(AZStd::unique_ptr instance); AZStd::unique_ptr DetachNestedInstance(const InstanceAlias& instanceAlias); + InstancePtrOptionalReference GetNestedInstance(const InstanceAlias& instanceAlias); /** * Gets the aliases for the entities in the Instance DOM. @@ -182,7 +186,6 @@ namespace AzToolsFramework void ClearEntities(); - void DetachEntities(const AZStd::function)>& callback); void RemoveEntities(const AZStd::function&)>& filter); bool RegisterEntity(const AZ::EntityId& entityId, const EntityAlias& entityAlias); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index 6d3ddedd51..cd8fad1725 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -176,10 +176,15 @@ namespace AzToolsFramework { PrefabDom& templateDomReference = m_prefabSystemComponentInterface->FindTemplateDom(templateId); + PrefabDomUtils::PrintPrefabDomValue("providedPatch", providedPatch); + PrefabDomUtils::PrintPrefabDomValue("templateDomReference", templateDomReference); + //apply patch to template AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::ApplyPatch(templateDomReference, templateDomReference.GetAllocator(), providedPatch, AZ::JsonMergeApproach::JsonPatch); + PrefabDomUtils::PrintPrefabDomValue("templateDomReference(Patch applied)", templateDomReference); + //trigger propagation if (result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 0181050a32..315c7b5710 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -986,6 +987,216 @@ namespace AzToolsFramework return AZ::Success(); } + PrefabOperationResult PrefabPublicHandler::DetachPrefabFromParent(const AZ::EntityId& entityId) + { + if (!entityId.IsValid()) + { + return AZ::Failure(AZStd::string("Cannot detach Prefab Instance with invalid container entity.")); + } + + if (IsLevelInstanceContainerEntity(entityId)) + { + return AZ::Failure(AZStd::string("Cannot detach level Prefab Instance.")); + } + + InstanceOptionalReference owningInstance = GetOwnerInstanceByEntityId(entityId); + if (owningInstance->get().GetContainerEntityId() != entityId) + { + return AZ::Failure(AZStd::string("Input entity should be its owning Instance's container entity.")); + } + + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + + UndoSystem::URSequencePoint* currentUndoBatch = nullptr; + ToolsApplicationRequests::Bus::BroadcastResult(currentUndoBatch, &ToolsApplicationRequests::Bus::Events::GetCurrentUndoBatch); + + bool createdUndo = false; + if (!currentUndoBatch) + { + createdUndo = true; + ToolsApplicationRequests::Bus::BroadcastResult( + currentUndoBatch, &ToolsApplicationRequests::Bus::Events::BeginUndoBatch, "Detach Prefab"); + AZ_Assert(currentUndoBatch, "Failed to create new undo batch."); + } + + // In order to undo Prefab Instance detachment, we have to create a selection command which selects the current selection + // and then add the detach as children. + // Commands always execute themselves first and then their children (when going forwards) + // and do the opposite when going backwards. + EntityIdList selectedEntities; + ToolsApplicationRequestBus::BroadcastResult(selectedEntities, &ToolsApplicationRequests::GetSelectedEntities); + SelectionCommand* selCommand = aznew SelectionCommand(selectedEntities, "Detach Prefab"); + + // We insert a "deselect all" command before we detach the Prefab Instance. This ensures the detach operations aren't changing + // selection state, which triggers expensive UI updates. By deselecting up front, we are able to do those expensive + // UI updates once at the start instead of once for each entity. + { + EntityIdList deselection; + SelectionCommand* deselectAllCommand = aznew SelectionCommand(deselection, "Deselect Entities"); + deselectAllCommand->SetParent(selCommand); + } + + { + AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DetachPrefab:UndoCapture"); + + InstanceOptionalReference parentInstance = owningInstance->get().GetParentInstance(); + const auto parentTemplateId = parentInstance->get().GetTemplateId(); + + Prefab::PrefabDom instanceDomBefore; + m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, parentInstance->get()); + + { + auto getInstancePtrResult = parentInstance->get().GetNestedInstance(owningInstance->get().GetInstanceAlias()); + AZ_Assert(getInstancePtrResult, "Can't find selected container entity's owning Instance."); + + auto& instancePtr = getInstancePtrResult->get(); + + AZStd::unordered_map oldEntityAliases; + oldEntityAliases.emplace(entityId, instancePtr->GetEntityAlias(entityId)->get()); + + auto containerEntityPtr = instancePtr->DetachContainerEntity(); + auto& containerEntity = *containerEntityPtr.release(); + auto editorPrefabComponent = containerEntity.FindComponent(); + containerEntity.Deactivate(); + const bool editorPrefabComponentRemoved = containerEntity.RemoveComponent(editorPrefabComponent); + AZ_Assert(editorPrefabComponentRemoved, "Remove EditorPrefabComponent failed."); + delete editorPrefabComponent; + containerEntity.Activate(); + + const bool containerEntityAdded = parentInstance->get().AddEntity(containerEntity); + AZ_Assert(containerEntityAdded, "Add target Instance's container entity to its parent Instance failed."); + + EntityIdList entityIds; + entityIds.emplace_back(containerEntity.GetId()); + + instancePtr->GetEntities( + [&](AZStd::unique_ptr& entityPtr) + { + oldEntityAliases.emplace(entityPtr->GetId(), instancePtr->GetEntityAlias(entityPtr->GetId())->get()); + return true; + }); + + instancePtr->DetachEntities( + [&](AZStd::unique_ptr entityPtr) + { + auto& entity = *entityPtr.release(); + const bool entityAdded = parentInstance->get().AddEntity(entity); + AZ_Assert(entityAdded, "Add target Instance's entity to its parent Instance failed."); + + entityIds.emplace_back(entity.GetId()); + }); + + Prefab::PrefabDom instanceDomAfter; + m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomAfter, parentInstance->get()); + + PrefabUndoInstance* command = aznew PrefabUndoInstance("Instance detachment"); + command->Capture(instanceDomBefore, instanceDomAfter, parentTemplateId); + command->SetParent(selCommand); + + selCommand->SetParent(currentUndoBatch); + { + AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DetachPrefab:RunRedo"); + selCommand->RunRedo(); + } + + const auto instanceTemplateId = instancePtr->GetTemplateId(); + auto parentContainerEntityId = parentInstance->get().GetContainerEntityId(); + instancePtr->GetNestedInstances( + [&](AZStd::unique_ptr& nestedInstancePtr) + { + //get previous link patch + auto linkRef = m_prefabSystemComponentInterface->FindLink(nestedInstancePtr->GetLinkId()); + PrefabDomValueReference linkPatches = linkRef->get().GetLinkPatches(); + AZ_Assert( + linkPatches.has_value(), "Unable to get patches on link with id '%llu' during prefab creation.", + nestedInstancePtr->GetLinkId()); + + PrefabDom linkPatchesCopy; + linkPatchesCopy.CopyFrom(linkPatches->get(), linkPatchesCopy.GetAllocator()); + + RemoveLink(nestedInstancePtr, instanceTemplateId, currentUndoBatch); + + /*auto getNestedInstanceContainerEntityResult = nestedInstancePtr->GetContainerEntity(); + AZ_Assert(getNestedInstanceContainerEntityResult.has_value(), "Can't get nested instance container entitt."); + + auto& nestedInstanceContainerEntity = getNestedInstanceContainerEntityResult->get(); + auto nestedInstanceContainerEntityId = nestedInstanceContainerEntity.GetId(); + + PrefabDom containerEntityDomBefore; + m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomBefore, nestedInstanceContainerEntity); + + AZ::TransformBus::Event(nestedInstanceContainerEntityId, &AZ::TransformInterface::SetParent, containerEntity.GetId()); + + PrefabDom containerEntityDomAfter; + m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomAfter, nestedInstanceContainerEntity); + + PrefabDom reparentPatch; + m_instanceToTemplateInterface->GeneratePatch(reparentPatch, containerEntityDomBefore, containerEntityDomAfter); + m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(reparentPatch, nestedInstanceContainerEntityId);*/ + + PrefabDomUtils::PrintPrefabDomValue("linkPatchesCopy", linkPatchesCopy); + + //update aliases + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + linkPatchesCopy.Accept(writer); + QString previousPatchString(buffer.GetString()); + + for (AZ::EntityId entityId : entityIds) + { + AZStd::string oldEntityAlias = oldEntityAliases[entityId]; + EntityAliasOptionalReference newEntityAlias = parentInstance->get().GetEntityAlias(entityId); + AZ_Assert( + newEntityAlias.has_value(), + "Could not fetch entity alias for entity with id '%llu' during prefab creation.", + static_cast(entityId)); + ReplaceOldAliases(previousPatchString, oldEntityAlias, newEntityAlias->get()); + } + + linkPatchesCopy.Parse(previousPatchString.toUtf8().constData()); + + CreateLink(*nestedInstancePtr, parentTemplateId, currentUndoBatch, AZStd::move(linkPatchesCopy), true); + + //update links? + //// Update the cache - this prevents these changes from being stored in the regular undo/redo nodes as a separate step + //m_prefabUndoCache.Store(nestedInstanceContainerEntityId, AZStd::move(containerEntityDomAfter)); + + //// Save these changes as patches to the link + //PrefabUndoLinkUpdate* linkUpdate = aznew PrefabUndoLinkUpdate(AZStd::to_string(static_cast(nestedInstanceContainerEntityId))); + //linkUpdate->SetParent(undoBatch.GetUndoBatch()); + //linkUpdate->Capture(reparentPatch, nestedInstance->GetLinkId()); + + //linkUpdate->Redo(); + }); + + RemoveLink(instancePtr, parentTemplateId, currentUndoBatch); + + AzToolsFramework::ToolsApplicationRequestBus::Broadcast( + &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); + } + } + + if (createdUndo) + { + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::EndUndoBatch); + } + + return AZ::Success(); + } + + void PrefabPublicHandler::ReplaceOldAliases(QString& stringToReplace, AZStd::string_view oldAlias, AZStd::string_view newAlias) + { + QString oldAliasQuotes = QString("\"%1\"").arg(oldAlias.data()); + QString newAliasQuotes = QString("\"%1\"").arg(newAlias.data()); + + stringToReplace.replace(oldAliasQuotes, newAliasQuotes); + + QString oldAliasPathRef = QString("/%1").arg(oldAlias.data()); + QString newAliasPathRef = QString("/%1").arg(newAlias.data()); + + stringToReplace.replace(oldAliasPathRef, newAliasPathRef); + } + void PrefabPublicHandler::GenerateContainerEntityTransform(const EntityList& topLevelEntities, AZ::Vector3& translation, AZ::Quaternion& rotation) { @@ -1236,18 +1447,5 @@ namespace AzToolsFramework return true; } - - void PrefabPublicHandler::ReplaceOldAliases(QString& stringToReplace, AZStd::string_view oldAlias, AZStd::string_view newAlias) - { - QString oldAliasQuotes = QString("\"%1\"").arg(oldAlias.data()); - QString newAliasQuotes = QString("\"%1\"").arg(newAlias.data()); - - stringToReplace.replace(oldAliasQuotes, newAliasQuotes); - - QString oldAliasPathRef = QString("/%1").arg(oldAlias.data()); - QString newAliasPathRef = QString("/%1").arg(newAlias.data()); - - stringToReplace.replace(oldAliasPathRef, newAliasPathRef); - } } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 7e2357dd44..f1c32ee35c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -64,6 +64,8 @@ namespace AzToolsFramework PrefabOperationResult DeleteEntitiesAndAllDescendantsInInstance(const EntityIdList& entityIds) override; PrefabOperationResult DuplicateEntitiesInInstance(const EntityIdList& entityIds) override; + PrefabOperationResult DetachPrefabFromParent(const AZ::EntityId& entityId) override; + private: PrefabOperationResult DeleteFromInstance(const EntityIdList& entityIds, bool deleteDescendants); bool RetrieveAndSortPrefabEntitiesAndInstances(const EntityList& inputEntities, Instance& commonRootEntityOwningInstance, diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h index 0750c4d264..f12bc359f2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h @@ -150,6 +150,14 @@ namespace AzToolsFramework * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. */ virtual PrefabOperationResult DuplicateEntitiesInInstance(const EntityIdList& entityIds) = 0; + + /** + * Detaches target container entity's owning instance from its parent instance. + * Bails if the entity is not a container entity or belongs to the level prefab instance. + * @param entityId The container entity whose instance to detach. + * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. + */ + virtual PrefabOperationResult DetachPrefabFromParent(const AZ::EntityId& entityId) = 0; }; } // namespace Prefab diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index 3edc190fb7..090c7bdc54 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -237,6 +237,27 @@ namespace AzToolsFramework { deleteAction->setDisabled(true); } + + QAction* detachPrefabAction = menu->addAction(QObject::tr("Detach Prefab...")); + if (selectedEntities.size() != 1) + { + detachPrefabAction->setDisabled(true); + } + else + { + AZ::EntityId selectedEntity = selectedEntities[0]; + + if (s_prefabPublicInterface->IsInstanceContainerEntity(selectedEntity) && + !s_prefabPublicInterface->IsLevelInstanceContainerEntity(selectedEntity)) + { + QObject::connect(detachPrefabAction, &QAction::triggered, detachPrefabAction, + [this, selectedEntity] { ContextMenu_DetachPrefab(selectedEntity); }); + } + else + { + detachPrefabAction->setDisabled(true); + } + } } void PrefabIntegrationManager::HandleSourceFileType(AZStd::string_view sourceFilePath, AZ::EntityId parentId, AZ::Vector3 position) const @@ -392,6 +413,17 @@ namespace AzToolsFramework } } + void PrefabIntegrationManager::ContextMenu_DetachPrefab(AZ::EntityId containerEntity) + { + PrefabOperationResult detachPrefabResult = + s_prefabPublicInterface->DetachPrefabFromParent(containerEntity); + + if (!detachPrefabResult.IsSuccess()) + { + WarnUserOfError("Detach Prefab error", detachPrefabResult.GetError()); + } + } + void PrefabIntegrationManager::GenerateSuggestedFilenameFromEntities(const EntityIdList& entityIds, AZStd::string& outName) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.h index c9b846aa5b..69ec3013cc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.h @@ -93,6 +93,7 @@ namespace AzToolsFramework static void ContextMenu_EditPrefab(AZ::EntityId containerEntity); static void ContextMenu_SavePrefab(AZ::EntityId containerEntity); static void ContextMenu_DeleteSelected(); + static void ContextMenu_DetachPrefab(AZ::EntityId containerEntity); // Prompt and resolve dialogs static bool QueryUserForPrefabSaveLocation( From 5ed4454e8b3f5ed01d03e9d6a4af88b3f42d08cd Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Wed, 26 May 2021 17:52:34 -0500 Subject: [PATCH 182/811] Moved Create New Level logic out from SaveToStream (#967) --- .../PrefabEditorEntityOwnershipInterface.h | 2 + .../PrefabEditorEntityOwnershipService.cpp | 119 +++++++++++------- .../PrefabEditorEntityOwnershipService.h | 2 + Code/Sandbox/Editor/CryEdit.cpp | 10 ++ 4 files changed, 87 insertions(+), 46 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h index 8412361657..a26c3b0ecf 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h @@ -56,5 +56,7 @@ namespace AzToolsFramework virtual void StartPlayInEditor() = 0; virtual void StopPlayInEditor() = 0; + + virtual void CreateNewLevelPrefab(AZStd::string_view filename) = 0; }; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 97c3041de6..b2b36cc318 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -225,50 +225,19 @@ namespace AzToolsFramework m_rootInstance->SetTemplateSourcePath(relativePath); - bool newLevelFromTemplate = false; - if (templateId == AzToolsFramework::Prefab::InvalidTemplateId) { - AZStd::string watchFolder; - AZ::Data::AssetInfo assetInfo; - bool sourceInfoFound = false; - AzToolsFramework::AssetSystemRequestBus::BroadcastResult( - sourceInfoFound, &AzToolsFramework::AssetSystemRequestBus::Events::GetSourceInfoBySourcePath, DefaultLevelTemplateName, - assetInfo, watchFolder); + m_rootInstance->m_containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent()); + HandleEntitiesAdded({ m_rootInstance->m_containerEntity.get() }); - if (sourceInfoFound) + AzToolsFramework::Prefab::PrefabDom dom; + bool success = AzToolsFramework::Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(*m_rootInstance, dom); + if (!success) { - AZStd::string fullPath; - AZ::StringFunc::Path::Join(watchFolder.c_str(), assetInfo.m_relativePath.c_str(), fullPath); - - // Get the default prefab and copy the Dom over to the new template being saved - Prefab::TemplateId defaultId = m_loaderInterface->LoadTemplateFromFile(fullPath.c_str()); - Prefab::PrefabDom& dom = m_prefabSystemComponent->FindTemplateDom(defaultId); - - Prefab::PrefabDom levelDefaultDom; - levelDefaultDom.CopyFrom(dom, levelDefaultDom.GetAllocator()); - - Prefab::PrefabDomPath sourcePath("/Source"); - sourcePath.Set(levelDefaultDom, relativePath.c_str()); - - templateId = m_prefabSystemComponent->AddTemplate(relativePath, std::move(levelDefaultDom)); - newLevelFromTemplate = true; - } - else - { - // Create an empty level since we couldn't find the default template - m_rootInstance->m_containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent()); - HandleEntitiesAdded({ m_rootInstance->m_containerEntity.get() }); - - AzToolsFramework::Prefab::PrefabDom dom; - bool success = AzToolsFramework::Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(*m_rootInstance, dom); - if (!success) - { - AZ_Error("Prefab", false, "Failed to convert current root instance into a DOM when saving file '%.*s'", AZ_STRING_ARG(filename)); - return false; - } - templateId = m_prefabSystemComponent->AddTemplate(relativePath, std::move(dom)); + AZ_Error("Prefab", false, "Failed to convert current root instance into a DOM when saving file '%.*s'", AZ_STRING_ARG(filename)); + return false; } + templateId = m_prefabSystemComponent->AddTemplate(relativePath, AZStd::move(dom)); if (templateId == AzToolsFramework::Prefab::InvalidTemplateId) { @@ -286,13 +255,6 @@ namespace AzToolsFramework m_prefabSystemComponent->RemoveTemplate(prevTemplateId); } - // If we have a new level from a template, we need to make sure to propagate the changes here otherwise - // the entities from the new template won't show up - if (newLevelFromTemplate) - { - m_prefabSystemComponent->PropagateTemplateChanges(templateId); - } - AZStd::string out; if (m_loaderInterface->SaveTemplateToString(m_rootInstance->GetTemplateId(), out)) { @@ -303,6 +265,71 @@ namespace AzToolsFramework return false; } + void PrefabEditorEntityOwnershipService::CreateNewLevelPrefab(AZStd::string_view filename) + { + AZ::IO::Path relativePath = m_loaderInterface->GetRelativePathToProject(filename); + AzToolsFramework::Prefab::TemplateId templateId = m_prefabSystemComponent->GetTemplateIdFromFilePath(relativePath); + + m_rootInstance->SetTemplateSourcePath(relativePath); + + AZStd::string watchFolder; + AZ::Data::AssetInfo assetInfo; + bool sourceInfoFound = false; + AzToolsFramework::AssetSystemRequestBus::BroadcastResult( + sourceInfoFound, &AzToolsFramework::AssetSystemRequestBus::Events::GetSourceInfoBySourcePath, DefaultLevelTemplateName, + assetInfo, watchFolder); + + if (sourceInfoFound) + { + AZStd::string fullPath; + AZ::StringFunc::Path::Join(watchFolder.c_str(), assetInfo.m_relativePath.c_str(), fullPath); + + // Get the default prefab and copy the Dom over to the new template being saved + Prefab::TemplateId defaultId = m_loaderInterface->LoadTemplateFromFile(fullPath.c_str()); + Prefab::PrefabDom& dom = m_prefabSystemComponent->FindTemplateDom(defaultId); + + Prefab::PrefabDom levelDefaultDom; + levelDefaultDom.CopyFrom(dom, levelDefaultDom.GetAllocator()); + + Prefab::PrefabDomPath sourcePath("/Source"); + sourcePath.Set(levelDefaultDom, assetInfo.m_relativePath.c_str()); + + templateId = m_prefabSystemComponent->AddTemplate(relativePath, AZStd::move(levelDefaultDom)); + } + else + { + m_rootInstance->m_containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent()); + HandleEntitiesAdded({ m_rootInstance->m_containerEntity.get() }); + + AzToolsFramework::Prefab::PrefabDom dom; + bool success = AzToolsFramework::Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(*m_rootInstance, dom); + if (!success) + { + AZ_Error( + "Prefab", false, "Failed to convert current root instance into a DOM when saving file '%.*s'", AZ_STRING_ARG(filename)); + return; + } + templateId = m_prefabSystemComponent->AddTemplate(relativePath, std::move(dom)); + } + + if (templateId == AzToolsFramework::Prefab::InvalidTemplateId) + { + AZ_Error("Prefab", false, "Couldn't create new template id '%i' when creating new level '%.*s'", templateId, AZ_STRING_ARG(filename)); + return; + } + + Prefab::TemplateId prevTemplateId = m_rootInstance->GetTemplateId(); + m_rootInstance->SetTemplateId(templateId); + + if (prevTemplateId != Prefab::InvalidTemplateId && templateId != prevTemplateId) + { + // Make sure we only have one level template loaded at a time + m_prefabSystemComponent->RemoveTemplate(prevTemplateId); + } + + m_prefabSystemComponent->PropagateTemplateChanges(templateId); + } + Prefab::InstanceOptionalReference PrefabEditorEntityOwnershipService::CreatePrefab( const AZStd::vector& entities, AZStd::vector>&& nestedPrefabInstances, AZ::IO::PathView filePath, Prefab::InstanceOptionalReference instanceToParentUnder) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h index 606d5f495f..915cafd316 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h @@ -170,6 +170,8 @@ namespace AzToolsFramework void StartPlayInEditor() override; void StopPlayInEditor() override; + void CreateNewLevelPrefab(AZStd::string_view filename) override; + protected: AZ::SliceComponent::SliceInstanceAddress GetOwningSlice() override; diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index 0bbc48d5f9..5fd6eb2692 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -69,6 +69,7 @@ AZ_POP_DISABLE_WARNING #include #include #include +#include #include // AzQtComponents @@ -3105,6 +3106,15 @@ CCryEditApp::ECreateLevelResult CCryEditApp::CreateLevel(const QString& levelNam GetIEditor()->GetDocument()->SetPathName(fullyQualifiedLevelName); GetIEditor()->GetGameEngine()->SetLevelPath(levelPath); + if (usePrefabSystemForLevels) + { + auto* service = AZ::Interface::Get(); + if (service) + { + service->CreateNewLevelPrefab((const char*)fullyQualifiedLevelName.toUtf8()); + } + } + if (GetIEditor()->GetDocument()->Save()) { if (!usePrefabSystemForLevels) From 2ba645c2649914750156b577f3cd5fd2d30119d5 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 26 May 2021 16:13:14 -0700 Subject: [PATCH 183/811] [cpack_installer] post install hooks to install cmake and python --- cmake/LYWrappers.cmake | 3 +- cmake/Platform/Common/Install_common.cmake | 2 +- .../Windows/Packaging/PostInstallSetup.wxs | 67 +++++++++++++ .../Windows/Packaging/Template.wxs.in | 19 +++- .../Platform/Windows/Packaging_windows.cmake | 5 + scripts/setup.bat | 93 ------------------- 6 files changed, 92 insertions(+), 97 deletions(-) create mode 100644 cmake/Platform/Windows/Packaging/PostInstallSetup.wxs delete mode 100644 scripts/setup.bat diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index f6a36afc89..2f8349c840 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -334,7 +334,8 @@ function(ly_add_target) if(NOT ly_add_target_IMPORTED) if(NOT ly_add_target_INSTALL_COMPONENT) - set(ly_add_target_INSTALL_COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT}) + #set(ly_add_target_INSTALL_COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT}) + set(ly_add_target_INSTALL_COMPONENT ${ly_add_target_NAMESPACE}) endif() ly_install_target( diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 8fe2fe2c1c..46d23f7b91 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -286,7 +286,7 @@ endfunction() function(ly_setup_others) # List of directories we want to install relative to engine root - set(DIRECTORIES_TO_INSTALL Tools/LyTestTools Tools/RemoteConsole) + set(DIRECTORIES_TO_INSTALL Tools/LyTestTools Tools/RemoteConsole Tools/Redistributables/CMake) foreach(dir ${DIRECTORIES_TO_INSTALL}) get_filename_component(install_path ${dir} DIRECTORY) diff --git a/cmake/Platform/Windows/Packaging/PostInstallSetup.wxs b/cmake/Platform/Windows/Packaging/PostInstallSetup.wxs new file mode 100644 index 0000000000..ebcaa9502f --- /dev/null +++ b/cmake/Platform/Windows/Packaging/PostInstallSetup.wxs @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cmake/Platform/Windows/Packaging/Template.wxs.in b/cmake/Platform/Windows/Packaging/Template.wxs.in index 2900b96f41..e14e064fbc 100644 --- a/cmake/Platform/Windows/Packaging/Template.wxs.in +++ b/cmake/Platform/Windows/Packaging/Template.wxs.in @@ -17,8 +17,7 @@ - @@ -41,8 +40,24 @@ + + + + + + + NOT Installed Or REINSTALL + + + NOT Installed Or REINSTALL + + + NOT Installed Or REINSTALL + + + diff --git a/cmake/Platform/Windows/Packaging_windows.cmake b/cmake/Platform/Windows/Packaging_windows.cmake index ce73e9a07b..b7db250fda 100644 --- a/cmake/Platform/Windows/Packaging_windows.cmake +++ b/cmake/Platform/Windows/Packaging_windows.cmake @@ -83,9 +83,14 @@ set(CPACK_WIX_PRODUCT_ICON ${CPACK_SOURCE_DIR}/Platform/Windows/Packaging/produc set(CPACK_WIX_TEMPLATE "${CPACK_SOURCE_DIR}/Platform/Windows/Packaging/Template.wxs.in") set(CPACK_WIX_EXTRA_SOURCES + "${CPACK_SOURCE_DIR}/Platform/Windows/Packaging/PostInstallSetup.wxs" "${CPACK_SOURCE_DIR}/Platform/Windows/Packaging/Shortcuts.wxs" ) +set(CPACK_WIX_EXTENSIONS + WixUtilExtension +) + set(_embed_artifacts "yes") if(LY_INSTALLER_DOWNLOAD_URL) diff --git a/scripts/setup.bat b/scripts/setup.bat deleted file mode 100644 index 34251ad861..0000000000 --- a/scripts/setup.bat +++ /dev/null @@ -1,93 +0,0 @@ -@echo off -rem -rem All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -rem its licensors. -rem -rem For complete copyright and license terms please see the LICENSE at the root of this -rem distribution (the "License"). All use of this software is governed by the License, -rem or, if provided, by the license below or the license accompanying this file. Do not -rem remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -rem - -pushd %~dp0% - -pushd %~dp0.. -set ENGINE_ROOT=%CD% -popd - -set cmake_version=3.19.1 - -if not "%1"=="" ( - set LY_3RDPARTY_PATH=%1 -) -if "%LY_3RDPARTY_PATH%"=="" goto no_3rd_party - -if not exist %LY_3RDPARTY_PATH% mkdir %LY_3RDPARTY_PATH% -goto install_cmake - -:no_3rd_party -echo A path to where the 3rd party folder is required for setup. -echo Either supply one through the LY_3RDPARTY_PATH environment -echo variable or as an argument to this script -goto fail - - -:install_cmake -set cmake_install_path=%LY_3RDPARTY_PATH%\CMake\%cmake_version%\Windows -set cmake_archive_name=cmake-%cmake_version%-win64-x64 -set cmake_archive_path="%ENGINE_ROOT%\Tools\Redistributables\CMake\%cmake_archive_name%.zip" -if exist "%cmake_install_path%\bin\cmake.exe" goto install_python - -echo Installing CMake %cmake_version% to %cmake_install_path% -if not exist %cmake_install_path% mkdir %cmake_install_path% -powershell.exe -nologo -noprofile -command^ - "& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('%cmake_archive_path%', '%cmake_install_path%'); }" -if ERRORLEVEL 1 goto cmake_failed - -set cmake_extracted_path=%cmake_install_path%\%cmake_archive_name% -for /d %%a in ("%cmake_extracted_path%\*") do move "%%a" "%cmake_install_path%\" -rmdir %cmake_extracted_path% - -goto success - -if ERRORLEVEL 1 goto cmake_failed -set LY_CMAKE_PATH="%cmake_install_path%\bin" -goto install_python - -:cmake_failed -echo Failed to extract cmake to path %cmake_install_path% -goto fail - - -:install_python -echo Installing python... -call %ENGINE_ROOT%\python\get_python.bat -if ERRORLEVEL 1 goto python_failed -goto register_engine - -:python_failed -echo Failed to acquire python -goto fail - - -:register_engine -echo Registering engine... -call %ENGINE_ROOT%\scripts\o3de.bat register --this-engine -if ERRORLEVEL 1 goto registration_failed -goto success - -:registration_failed -echo Failed to register the engine -goto fail - - -:fail -echo O3DE setup failed -popd -exit /b 1 - -:success -echo O3DE setup complete -popd -exit /b %ERRORLEVEL% From cccb68fa38e479b1d0aa851718620384ff483ff2 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 26 May 2021 16:21:04 -0700 Subject: [PATCH 184/811] [cpack_installer] revert accidental debug change committed --- cmake/LYWrappers.cmake | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index f7290009de..8aba6ccb99 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -339,8 +339,7 @@ function(ly_add_target) if(NOT ly_add_target_IMPORTED) if(NOT ly_add_target_INSTALL_COMPONENT) - #set(ly_add_target_INSTALL_COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT}) - set(ly_add_target_INSTALL_COMPONENT ${ly_add_target_NAMESPACE}) + set(ly_add_target_INSTALL_COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT}) endif() ly_install_target( From 78616a7befd66119514d02c6c738b45fad731b3b Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Wed, 26 May 2021 16:21:52 -0700 Subject: [PATCH 185/811] Updated test materials to force UV center back to (0,0) since the default is now (0.5,0.5). This gets the screenshot tests in ASV working again. --- .../001_ManyFeatures.material | 8 ++++++++ .../005_UseDisplacement.material | 12 +++++++----- .../012_Parallax_POM_Cutout.material | 5 ++++- .../101_DetailMaps_LucyBaseNoDetailMaps.material | 14 ++++++++++---- .../102_DetailMaps_All.material | 14 +++++++++----- ...105_DetailMaps_BlendMaskUsingDetailUVs.material | 14 +++++++++----- 6 files changed, 47 insertions(+), 20 deletions(-) diff --git a/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/001_ManyFeatures.material b/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/001_ManyFeatures.material index 1c02f56af6..415bd36dcf 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/001_ManyFeatures.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/001_ManyFeatures.material @@ -86,6 +86,10 @@ "textureMap": "TestData/Textures/cc0/Lava004_1K_Roughness.jpg" }, "layer2_uv": { + "center": [ + 0.0, + 0.0 + ], "offsetU": 0.5, "offsetV": 0.25 }, @@ -128,6 +132,10 @@ "factor": 0.47474750876426699 }, "layer3_uv": { + "center": [ + 0.0, + 0.0 + ], "offsetU": 0.11999999731779099, "rotateDegrees": -57.599998474121097 }, diff --git a/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/005_UseDisplacement.material b/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/005_UseDisplacement.material index 55a4774d49..9163fe0a0c 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/005_UseDisplacement.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardMultilayerPbrTestCases/005_UseDisplacement.material @@ -46,8 +46,8 @@ }, "layer2_uv": { "center": [ - 0.5, - 0.5 + 0.0, + 0.0 ], "offsetU": 0.1599999964237213, "offsetV": 0.07999999821186066, @@ -67,13 +67,15 @@ "textureMap": "TestData/Textures/cc0/Rocks002_1K_Roughness.jpg" }, "layer3_uv": { + "center": [ + 0.0, + 0.0 + ], "scale": 3.4999988079071047 }, "parallax": { "algorithm": "Relief", - "enable": true, - "pdo": true, - "quality": "Low" + "pdo": true } } } \ No newline at end of file diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material index fb862dc5d3..21f873fe1a 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material @@ -13,13 +13,16 @@ "textureMap": "TestData/Textures/checker8x8_512.png" }, "parallax": { - "algorithm": "POM", "enable": true, "factor": 0.10000000149011612, "quality": "High", "textureMap": "TestData/Textures/TextureHaven/4k_castle_brick_02_red/4k_castle_brick_02_red_disp.png" }, "uv": { + "center": [ + 0.0, + 0.0 + ], "scale": 0.5 } } diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/101_DetailMaps_LucyBaseNoDetailMaps.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/101_DetailMaps_LucyBaseNoDetailMaps.material index 7b1f0ba6a9..6d77be5a49 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/101_DetailMaps_LucyBaseNoDetailMaps.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/101_DetailMaps_LucyBaseNoDetailMaps.material @@ -8,18 +8,24 @@ "textureMap": "Objects/Lucy/Lucy_bronze_BaseColor.png", "textureMapUv": "Unwrapped" }, + "detailUV": { + "center": [ + 0.0, + 0.0 + ] + }, "metallic": { - "textureMap": "Objects/Lucy/Lucy_bronze_metallic.png", + "textureMap": "Objects/Lucy/Lucy_bronze_Metallic.png", "textureMapUv": "Unwrapped" }, "normal": { "flipY": true, - "textureMap": "Objects/Lucy/Lucy_normal.png", + "textureMap": "Objects/Lucy/Lucy_Normal.png", "textureMapUv": "Unwrapped" }, "roughness": { - "textureMap": "Objects/Lucy/Lucy_bronze_roughness.png", + "textureMap": "Objects/Lucy/Lucy_bronze_Roughness.png", "textureMapUv": "Unwrapped" } } -} +} \ No newline at end of file diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/102_DetailMaps_All.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/102_DetailMaps_All.material index 55a01866b5..1a29f392c8 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/102_DetailMaps_All.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/102_DetailMaps_All.material @@ -5,7 +5,7 @@ "propertyLayoutVersion": 3, "properties": { "baseColor": { - "textureMap": "Objects/Lucy/Lucy_bronze_baseColor.png", + "textureMap": "Objects/Lucy/Lucy_bronze_BaseColor.png", "textureMapUv": "Unwrapped" }, "detailLayerGroup": { @@ -19,20 +19,24 @@ "normalDetailStrength": 1.5 }, "detailUV": { + "center": [ + 0.0, + 0.0 + ], "scale": 10.0 }, "metallic": { - "textureMap": "Objects/Lucy/Lucy_bronze_metallic.png", + "textureMap": "Objects/Lucy/Lucy_bronze_Metallic.png", "textureMapUv": "Unwrapped" }, "normal": { "flipY": true, - "textureMap": "Objects/Lucy/Lucy_normal.png", + "textureMap": "Objects/Lucy/Lucy_Normal.png", "textureMapUv": "Unwrapped" }, "roughness": { - "textureMap": "Objects/Lucy/Lucy_bronze_roughness.png", + "textureMap": "Objects/Lucy/Lucy_bronze_Roughness.png", "textureMapUv": "Unwrapped" } } -} +} \ No newline at end of file diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/105_DetailMaps_BlendMaskUsingDetailUVs.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/105_DetailMaps_BlendMaskUsingDetailUVs.material index 6193cf4eed..a69b72b623 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/105_DetailMaps_BlendMaskUsingDetailUVs.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/105_DetailMaps_BlendMaskUsingDetailUVs.material @@ -5,7 +5,7 @@ "propertyLayoutVersion": 3, "properties": { "baseColor": { - "textureMap": "Objects/Lucy/Lucy_bronze_baseColor.png", + "textureMap": "Objects/Lucy/Lucy_bronze_BaseColor.png", "textureMapUv": "Unwrapped" }, "detailLayerGroup": { @@ -18,20 +18,24 @@ "normalDetailStrength": 1.5 }, "detailUV": { + "center": [ + 0.0, + 0.0 + ], "scale": 10.0 }, "metallic": { - "textureMap": "Objects/Lucy/Lucy_bronze_metallic.png", + "textureMap": "Objects/Lucy/Lucy_bronze_Metallic.png", "textureMapUv": "Unwrapped" }, "normal": { "flipY": true, - "textureMap": "Objects/Lucy/Lucy_normal.png", + "textureMap": "Objects/Lucy/Lucy_Normal.png", "textureMapUv": "Unwrapped" }, "roughness": { - "textureMap": "Objects/Lucy/Lucy_bronze_roughness.png", + "textureMap": "Objects/Lucy/Lucy_bronze_Roughness.png", "textureMapUv": "Unwrapped" } } -} +} \ No newline at end of file From 79d66dd492b90ec17233f1beff1972b649ec8e28 Mon Sep 17 00:00:00 2001 From: sweeneys Date: Wed, 26 May 2021 16:22:32 -0700 Subject: [PATCH 186/811] Search for external project definition before searching for internal projects --- .../managers/abstract_resource_locator.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Tools/LyTestTools/ly_test_tools/_internal/managers/abstract_resource_locator.py b/Tools/LyTestTools/ly_test_tools/_internal/managers/abstract_resource_locator.py index 5a14ef9419..ec4b43b023 100755 --- a/Tools/LyTestTools/ly_test_tools/_internal/managers/abstract_resource_locator.py +++ b/Tools/LyTestTools/ly_test_tools/_internal/managers/abstract_resource_locator.py @@ -16,8 +16,10 @@ import pathlib import warnings from abc import ABCMeta, abstractmethod +import ly_test_tools._internal.pytest_plugin from ly_test_tools.environment.file_system import find_ancestor_file + def _find_engine_root(initial_path): # type: (str) -> str """ @@ -34,11 +36,9 @@ def _find_engine_root(initial_path): # Assumes folder structure similar to: engine_root/dev/Tools/.../ly_test_tools/builtin for _ in range(15): if os.path.exists(os.path.join(current_dir, root_file)): - # The parent of the directory containing the engineroot.txt is the root directory - engine_root = current_dir - return engine_root - # Using an explicit else to avoid aberrant behavior from following filesystem links - else: + # parent of the directory containing root_file + return current_dir + else: # explicit else avoids aberrant behavior from following filesystem links current_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir)) raise OSError(f"Unable to find engine root directory. Verify root file '{root_file}' exists") @@ -50,8 +50,10 @@ def _find_project_json(engine_root, project): Find the project.json file for this project. :return: Full path to the project.json file """ - project_json = find_ancestor_file('project.json') - if not project_json: + # First check relative to defined build directory, for external projects which configure through SDK settings + project_json = find_ancestor_file(target_file_name='project.json', + start_path=ly_test_tools._internal.pytest_plugin.build_directory) + if not project_json: # check internally for a project bundled with the engine project_json = os.path.join(engine_root, project, 'project.json') return project_json From 32919b1e7bd5514e75801eb7d889f8ffa0f07966 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 26 May 2021 18:34:25 -0500 Subject: [PATCH 187/811] Updating the AZ_DECLARE_MODULE_CLASS call in the Project's template code module to use the Gem_ prefix instead of Project_ since that is what the StaticModules.inl file geneates in it CreateStaticModules function when generating a monolithic solution --- Templates/DefaultProject/Template/Code/Source/${Name}Module.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Templates/DefaultProject/Template/Code/Source/${Name}Module.cpp b/Templates/DefaultProject/Template/Code/Source/${Name}Module.cpp index 003a984dd6..4f11828366 100644 --- a/Templates/DefaultProject/Template/Code/Source/${Name}Module.cpp +++ b/Templates/DefaultProject/Template/Code/Source/${Name}Module.cpp @@ -47,4 +47,4 @@ namespace ${Name} }; }// namespace ${Name} -AZ_DECLARE_MODULE_CLASS(Project_${Name}, ${Name}::${Name}Module) +AZ_DECLARE_MODULE_CLASS(Gem_${Name}, ${Name}::${Name}Module) From d1863c6c5b6e6fad5db498652110a0183919f96a Mon Sep 17 00:00:00 2001 From: Nicholas Van Sickle Date: Wed, 26 May 2021 16:36:54 -0700 Subject: [PATCH 188/811] Restore Editor viewport icon rendering (#879) This introduces an EditorViewportIconDisplayInterface that will eventually be used to outright remove CIconManager, it provides a simple interface for loading 2D image assets and rendering them on-screen. It also introduces AtomBridge::PerViewportDynamicDraw for getting a dynamic draw instance on a per-viewport basis --- .../API/EditorViewportIconDisplayInterface.h | 80 +++++ .../EditorEntityIconComponent.cpp | 4 +- .../ViewportSelection/EditorHelpers.cpp | 13 +- .../aztoolsframework_files.cmake | 1 + .../DynamicDraw/DynamicDrawContext.h | 8 + .../Include/Atom/RPI.Public/ViewportContext.h | 25 +- .../DynamicDraw/DynamicDrawContext.cpp | 36 ++ .../Source/RPI.Public/ViewportContext.cpp | 19 + .../AtomBridge/Code/CMakeLists.txt | 1 + .../PerViewportDynamicDrawInterface.h | 44 +++ .../Code/Source/AtomBridgeSystemComponent.cpp | 3 + .../Code/Source/AtomBridgeSystemComponent.h | 2 + .../Source/PerViewportDynamicDrawManager.cpp | 119 ++++++ .../Source/PerViewportDynamicDrawManager.h | 48 +++ .../AtomBridge/Code/atombridge_files.cmake | 7 +- .../Assets/Shaders/TexturedIcon.azsl | 77 ++++ .../Assets/Shaders/TexturedIcon.shader | 39 ++ .../AtomViewportDisplayIcons/CMakeLists.txt | 12 + .../Code/CMakeLists.txt | 35 ++ ...tomViewportDisplayIconsSystemComponent.cpp | 339 ++++++++++++++++++ .../AtomViewportDisplayIconsSystemComponent.h | 82 +++++ .../Code/Source/Module.cpp | 51 +++ .../Code/atomviewportdisplayicons_files.cmake | 16 + .../AtomViewportDisplayInfo/gem.json | 12 - Gems/AtomLyIntegration/CMakeLists.txt | 1 + 25 files changed, 1050 insertions(+), 24 deletions(-) create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorViewportIconDisplayInterface.h create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Include/AtomBridge/PerViewportDynamicDrawInterface.h create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/PerViewportDynamicDrawManager.cpp create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/PerViewportDynamicDrawManager.h create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayIcons/Assets/Shaders/TexturedIcon.azsl create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayIcons/Assets/Shaders/TexturedIcon.shader create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayIcons/CMakeLists.txt create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/CMakeLists.txt create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.cpp create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.h create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/Module.cpp create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/atomviewportdisplayicons_files.cmake delete mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorViewportIconDisplayInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorViewportIconDisplayInterface.h new file mode 100644 index 0000000000..a2264b5058 --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorViewportIconDisplayInterface.h @@ -0,0 +1,80 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include +#include +#include + +#include + +namespace AzToolsFramework +{ + //! An interface for loading simple icon assets and rendering them to screen on a per-viewport basis. + class EditorViewportIconDisplayInterface + { + public: + AZ_RTTI(EditorViewportIconDisplayInterface, "{D5190B58-2561-4F3F-B793-F1E7D454CDF2}"); + + using IconId = AZ::s32; + static constexpr IconId InvalidIconId = -1; + + enum class CoordinateSpace : AZ::u8 + { + ScreenSpace, + WorldSpace + }; + + //! These draw parameters control rendering for a single icon to a single viewport. + struct DrawParameters + { + //! The ViewportId to render to. + AzFramework::ViewportId m_viewport = AzFramework::InvalidViewportId; + //! The icon ID, retrieved from GetOrLoadIconForPath, to render to screen. + IconId m_icon = InvalidIconId; + //! The color, including opacity, to render the icon with. White will render the icon as opaque in its original color. + AZ::Color m_color = AZ::Colors::White; + //! The position to render the icon to, in world or screen space depending on m_positionSpace. + AZ::Vector3 m_position; + //! The coordinate system to use for m_position. + //! ScreenSpace will accept m_position in the form of [X, Y, Depth], where X & Y are screen coordinates in + //! pixels and Depth is a z-ordering depth value from 0.0f to 1.0f. + //! WorldSpace will accept a 3D vector in world space coordinates that will be translated back into screen + //! space when the icon is rendered. + CoordinateSpace m_positionSpace = CoordinateSpace::ScreenSpace; + //! The size to render the icon as, in pixels. + AZ::Vector2 m_size; + }; + + //! The current load status of an icon retrieved by GetOrLoadIconForPath. + enum class IconLoadStatus : AZ::u8 + { + Unloaded, + Loading, + Loaded, + Error + }; + + //! Draws an icon to a viewport given a set of draw parameters. + //! Requires an IconId retrieved from GetOrLoadIconForPath. + virtual void DrawIcon(const DrawParameters& drawParameters) = 0; + //! Retrieves a reusable IconId for an icon at a given path. + //! This will load the icon, if it has not already been loaded. + //! @param path should be a relative asset path to an icon image asset. + //! png and svg icons are currently supported. + virtual IconId GetOrLoadIconForPath(AZStd::string_view path) = 0; + //! Gets the current load status of an icon retrieved via GetOrLoadIconForPath. + virtual IconLoadStatus GetIconLoadStatus(IconId icon) = 0; + }; + + using EditorViewportIconDisplay = AZ::Interface; +} //namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorEntityIconComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorEntityIconComponent.cpp index 48a7a37487..c46bb158c6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorEntityIconComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorEntityIconComponent.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -313,8 +314,7 @@ namespace AzToolsFramework // if we do not yet have a valid texture id, request it using the entity icon path if (m_entityIconTextureId == 0) { - EditorRequestBus::BroadcastResult( - m_entityIconTextureId, &EditorRequests::GetIconTextureIdFromEntityIconPath, m_entityIconPath); + m_entityIconTextureId = EditorViewportIconDisplay::Get()->GetOrLoadIconForPath(m_entityIconPath); } return m_entityIconTextureId; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp index 5c62a2997b..31da01fadc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp @@ -21,6 +21,7 @@ #include #include #include +#include AZ_CVAR( bool, ed_visibility_showAggregateEntitySelectionBounds, false, nullptr, AZ::ConsoleFunctorFlags::Null, @@ -232,10 +233,14 @@ namespace AzToolsFramework return AZ::Color(1.0f, 1.0f, 1.0f, 1.0f); }(); - debugDisplay.SetColor(iconHighlight); - // debugDisplay.DrawTextureLabel( - // iconTextureId, entityPosition, iconSize, iconSize, - // /*DisplayContext::ETextureIconFlags::TEXICON_ON_TOP=*/ 0x0008); + EditorViewportIconDisplay::Get()->DrawIcon({ + viewportInfo.m_viewportId, + iconTextureId, + iconHighlight, + entityPosition, + EditorViewportIconDisplayInterface::CoordinateSpace::WorldSpace, + AZ::Vector2{iconSize, iconSize} + }); } } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index 45f52704bf..aaf5c86d33 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -46,6 +46,7 @@ set(FILES API/EditorWindowRequestBus.h API/EntityCompositionRequestBus.h API/EntityCompositionNotificationBus.h + API/EditorViewportIconDisplayInterface.h API/ViewPaneOptions.h Application/Ticker.h Application/Ticker.cpp diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawContext.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawContext.h index e4b9b91e81..2dd0865688 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawContext.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawContext.h @@ -87,6 +87,14 @@ namespace AZ //! Finalize and validate initialization. Any initialization functions should be called before EndInit is called. void EndInit(); + //! Set up the DynamicDrawContext for the input Scene. + //! This should be called after the last frame is done and before any draw calls. + void SetScene(Scene* scene); + + //! Set up the DynamicDrawContext for the input RenderPipeline. + //! This should be called after the last frame is done and before any draw calls. + void SetRenderPipeline(RenderPipeline* pipeline); + //! Return if this DynamicDrawContext is ready to add draw calls bool IsReady(); diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContext.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContext.h index 4f24a20f35..8075c6fc5d 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContext.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContext.h @@ -26,9 +26,9 @@ namespace AZ class ViewportContextManager; //! ViewportContext wraps a native window and represents a minimal viewport - //! in which a scene is rendered on-screen + //! in which a scene is rendered on-screen. //! ViewportContexts are registered on creation to allow consumers to listen to notifications - //! and manage the view stack for a given viewport + //! and manage the view stack for a given viewport. class ViewportContext : public SceneNotificationBus::Handler , public AzFramework::WindowNotificationBus::Handler @@ -61,11 +61,11 @@ namespace AZ //! Gets the current name of this ViewportContext. //! This name is used to tie this ViewportContext to its View stack, and ViewportContexts may be - //! renamed via AZ::Interface::Get()->RenameViewportContext. + //! renamed via AZ::RPI::ViewportContextRequests::Get()->RenameViewportContext(...). AZ::Name GetName() const; //! Gets the default view associated with this ViewportContext. - //! Alternatively, use AZ::Interface::Get()->GetCurrentView. + //! Alternatively, use AZ::RPI::ViewportContextRequests::Get()->GetCurrentView(). ViewPtr GetDefaultView(); ConstViewPtr GetDefaultView() const; @@ -99,6 +99,18 @@ namespace AZ //! Notifies consumers when the render scene has changed. void ConnectSceneChangedHandler(SceneChangedEvent::Handler& handler); + using PipelineChangedEvent = AZ::Event; + //! Notifies consumers when the current pipeline associated with our window has changed. + void ConnectCurrentPipelineChangedHandler(PipelineChangedEvent::Handler& handler); + + using ViewChangedEvent = AZ::Event; + //! Notifies consumers when the default view has changed. + void ConnectDefaultViewChangedHandler(ViewChangedEvent::Handler& handler); + + using ViewportIdEvent = AZ::Event; + //! Notifies consumers when this ViewportContext is about to be destroyed. + void ConnectAboutToBeDestroyedHandler(ViewportIdEvent::Handler& handler); + // ViewportRequestBus interface //! Gets the current camera's view matrix. const AZ::Matrix4x4& GetCameraViewMatrix() const override; @@ -123,12 +135,17 @@ namespace AZ WindowContextSharedPtr m_windowContext; ViewPtr m_defaultView; AzFramework::WindowSize m_viewportSize; + SizeChangedEvent m_sizeChangedEvent; MatrixChangedEvent m_viewMatrixChangedEvent; MatrixChangedEvent::Handler m_onViewMatrixChangedHandler; MatrixChangedEvent m_projectionMatrixChangedEvent; MatrixChangedEvent::Handler m_onProjectionMatrixChangedHandler; SceneChangedEvent m_sceneChangedEvent; + PipelineChangedEvent m_currentPipelineChangedEvent; + ViewChangedEvent m_defaultViewChangedEvent; + ViewportIdEvent m_aboutToBeDestroyedEvent; + ViewportContextManager* m_manager; RenderPipelinePtr m_currentPipeline; Name m_name; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp index b7ba7d4a32..4e4a7a5e71 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp @@ -211,6 +211,42 @@ namespace AZ m_rhiPipelineState = m_pipelineState->GetRHIPipelineState(); } + void DynamicDrawContext::SetScene(Scene* scene) + { + AZ_Assert(scene, "SetScene called with an invalid scene"); + if (!scene || m_scene == scene) + { + return; + } + m_scene = scene; + m_drawFilter = RHI::DrawFilterMaskDefaultValue; + // Reinitialize if it was initialized + if (m_initialized) + { + // Report warning if there were some draw data + AZ_Warning( + "DynamicDrawContext", m_cachedDrawItems.size() == 0, + "DynamicDrawContext::SetForScene should be called" + " when there is no cached draw data"); + // Clear some cached data + FrameEnd(); + m_cachedRhiPipelineStates.clear(); + // Reinitialize + EndInit(); + } + } + + void DynamicDrawContext::SetRenderPipeline(RenderPipeline* pipeline) + { + AZ_Assert(pipeline, "SetRenderPipeline called with an invalid pipeline"); + if (!pipeline) + { + return; + } + SetScene(pipeline->GetScene()); + m_drawFilter = pipeline->GetDrawFilterMask(); + } + bool DynamicDrawContext::IsReady() { return m_initialized; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp index 22287238e9..08f8ff0c5e 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp @@ -51,6 +51,8 @@ namespace AZ ViewportContext::~ViewportContext() { + m_aboutToBeDestroyedEvent.Signal(m_id); + AzFramework::WindowNotificationBus::Handler::BusDisconnect(); AzFramework::ViewportRequestBus::Handler::BusDisconnect(); @@ -171,6 +173,21 @@ namespace AZ handler.Connect(m_sceneChangedEvent); } + void ViewportContext::ConnectCurrentPipelineChangedHandler(PipelineChangedEvent::Handler& handler) + { + handler.Connect(m_currentPipelineChangedEvent); + } + + void ViewportContext::ConnectDefaultViewChangedHandler(ViewChangedEvent::Handler& handler) + { + handler.Connect(m_defaultViewChangedEvent); + } + + void ViewportContext::ConnectAboutToBeDestroyedHandler(ViewportIdEvent::Handler& handler) + { + handler.Connect(m_aboutToBeDestroyedEvent); + } + const AZ::Matrix4x4& ViewportContext::GetCameraViewMatrix() const { return GetDefaultView()->GetWorldToViewMatrix(); @@ -214,6 +231,7 @@ namespace AZ m_defaultView = view; UpdatePipelineView(); + m_defaultViewChangedEvent.Signal(view); m_viewMatrixChangedEvent.Signal(view->GetWorldToViewMatrix()); m_projectionMatrixChangedEvent.Signal(view->GetViewToClipMatrix()); @@ -232,6 +250,7 @@ namespace AZ if (!m_currentPipeline) { m_currentPipeline = m_rootScene ? m_rootScene->FindRenderPipelineForWindow(m_windowContext->GetWindowHandle()) : nullptr; + m_currentPipelineChangedEvent.Signal(m_currentPipeline); } if (auto pipeline = GetCurrentPipeline()) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt index c431746b40..0723ca46b7 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt @@ -106,5 +106,6 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::AtomFont Gem::AtomToolsFramework.Editor Gem::AtomViewportDisplayInfo + Gem::AtomViewportDisplayIcons.Editor ) endif() diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Include/AtomBridge/PerViewportDynamicDrawInterface.h b/Gems/AtomLyIntegration/AtomBridge/Code/Include/AtomBridge/PerViewportDynamicDrawInterface.h new file mode 100644 index 0000000000..f77e0b0b88 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Include/AtomBridge/PerViewportDynamicDrawInterface.h @@ -0,0 +1,44 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include +#include + +namespace AZ::AtomBridge +{ + //! A simple interface for allocating a DynamicDrawContext on-demand for every viewport, based on + //! a registered initialization function. + class PerViewportDynamicDrawInterface + { + public: + AZ_RTTI(PerViewportDynamicDrawInterface, "{1FF054F5-55FF-4ADB-A86D-640B15FA0395}"); + + using DrawContextFactory = AZStd::function)>; + //! Register a named dynamic draw context that can be retrieved on a per-viewport basis. + //! GetNamedDynamicDraw context can be called on a registered context name to retrieve a + //! valid DynamicDrawContext for a given viewport. + virtual void RegisterDynamicDrawContext(AZ::Name name, DrawContextFactory contextInitializer) = 0; + + //! Unregister a previously registered named per-viewport dynamic draw context. + //! This will dispose of all dynamic draw contexts currently associated with this name. + virtual void UnregisterDynamicDrawContext(AZ::Name name) = 0; + + //! Get a dynamic draw context associated with the specified viewport based on a factory registered with + //! RegisterNamedDynamicDrawContext. This dynamic draw context will be created if it does not already exist. + virtual RHI::Ptr GetDynamicDrawContextForViewport(AZ::Name name, AzFramework::ViewportId viewportId) = 0; + }; + + using PerViewportDynamicDraw = AZ::Interface; +} // namespace AZ::AtomBridge diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp index 4a19c08174..5116d8a228 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -104,10 +105,12 @@ namespace AZ AzFramework::GameEntityContextRequestBus::BroadcastResult(m_entityContextId, &AzFramework::GameEntityContextRequestBus::Events::GetGameEntityContextId); AZ::Render::Bootstrap::NotificationBus::Handler::BusConnect(); + m_dynamicDrawManager = AZStd::make_unique(); } void AtomBridgeSystemComponent::Deactivate() { + m_dynamicDrawManager.reset(); AZ::RPI::ViewportContextManagerNotificationsBus::Handler::BusDisconnect(); RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get(); // Check if scene is emptry since scene might be released already when running AtomSampleViewer diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h index da75d3c35c..4d05ba9285 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h @@ -33,6 +33,7 @@ namespace AZ { // forward declares class AtomDebugDisplayViewportInterface; + class PerViewportDynamicDrawManager; class AtomBridgeSystemComponent : public Component @@ -82,6 +83,7 @@ namespace AZ RPI::ViewPtr m_view = nullptr; AZStd::unordered_map > m_activeViewportsList; + AZStd::unique_ptr m_dynamicDrawManager; }; } } // namespace AZ diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/PerViewportDynamicDrawManager.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/PerViewportDynamicDrawManager.cpp new file mode 100644 index 0000000000..b6ff116a86 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/PerViewportDynamicDrawManager.cpp @@ -0,0 +1,119 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include "PerViewportDynamicDrawManager.h" + +#include +#include + +namespace AZ::AtomBridge +{ + PerViewportDynamicDrawManager::PerViewportDynamicDrawManager() + { + PerViewportDynamicDraw::Register(this); + } + + PerViewportDynamicDrawManager::~PerViewportDynamicDrawManager() + { + PerViewportDynamicDraw::Unregister(this); + } + + void PerViewportDynamicDrawManager::RegisterDynamicDrawContext(AZ::Name name, DrawContextFactory contextInitializer) + { + AZStd::lock_guard lock(m_mutexDrawContexts); + + const bool alreadyRegistered = m_registeredDrawContexts.find(name) != m_registeredDrawContexts.end(); + AZ_Error("AtomBridge", !alreadyRegistered, "Attempted to call RegisterDynamicDrawContext for already registered name: \"%s\"", name.GetCStr()); + if (alreadyRegistered) + { + return; + } + m_registeredDrawContexts[name] = contextInitializer; + } + + void PerViewportDynamicDrawManager::UnregisterDynamicDrawContext(AZ::Name name) + { + AZStd::lock_guard lock(m_mutexDrawContexts); + + auto drawContextFactoryIt = m_registeredDrawContexts.find(name); + const bool registered = drawContextFactoryIt != m_registeredDrawContexts.end(); + AZ_Error("AtomBridge", registered, "Attempted to call UnregisterDynamicDrawContext for unregistered name: \"%s\"", name.GetCStr()); + if (!registered) + { + return; + } + m_registeredDrawContexts.erase(drawContextFactoryIt); + + for (auto& viewportData : m_viewportData) + { + viewportData.second.m_dynamicDrawContexts.erase(name); + } + } + + RHI::Ptr PerViewportDynamicDrawManager::GetDynamicDrawContextForViewport( + AZ::Name name, AzFramework::ViewportId viewportId) + { + AZStd::lock_guard lock(m_mutexDrawContexts); + + auto contextFactoryIt = m_registeredDrawContexts.find(name); + if (contextFactoryIt == m_registeredDrawContexts.end()) + { + return nullptr; + } + + auto viewportContextManager = RPI::ViewportContextRequests::Get(); + RPI::ViewportContextPtr viewportContext = viewportContextManager->GetViewportContextById(viewportId); + if (viewportContext == nullptr) + { + return nullptr; + } + + // Get or create a ViewportData if one doesn't already exist + ViewportData& viewportData = m_viewportData[viewportId]; + if (!viewportData.m_initialized) + { + viewportData.m_pipelineChangedHandler = AZ::Event::Handler([this, viewportId](RPI::RenderPipelinePtr pipeline) + { + AZStd::lock_guard lock(m_mutexDrawContexts); + ViewportData& viewportData = m_viewportData[viewportId]; + for (auto& context : viewportData.m_dynamicDrawContexts) + { + context.second->SetRenderPipeline(pipeline.get()); + } + }); + viewportData.m_viewportDestroyedHandler = AZ::Event::Handler([this, viewportId](AzFramework::ViewportId id) + { + AZStd::lock_guard lock(m_mutexDrawContexts); + m_viewportData.erase(id); + }); + + viewportContext->ConnectCurrentPipelineChangedHandler(viewportData.m_pipelineChangedHandler); + viewportContext->ConnectAboutToBeDestroyedHandler(viewportData.m_viewportDestroyedHandler); + + viewportData.m_initialized = true; + } + + RHI::Ptr& context = viewportData.m_dynamicDrawContexts[name]; + if (context == nullptr) + { + auto pipeline = viewportContext->GetCurrentPipeline().get(); + if (pipeline == nullptr) + { + return nullptr; + } + context = RPI::DynamicDrawInterface::Get()->CreateDynamicDrawContext(pipeline); + contextFactoryIt->second(context); + } + + return context; + } +} //namespace AZ::AtomBridge diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/PerViewportDynamicDrawManager.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/PerViewportDynamicDrawManager.h new file mode 100644 index 0000000000..e2b442915c --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/PerViewportDynamicDrawManager.h @@ -0,0 +1,48 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include + +namespace AZ::AtomBridge +{ + class PerViewportDynamicDrawManager final : public PerViewportDynamicDrawInterface + { + public: + AZ_TYPE_INFO(PerViewportDynamicDrawManager, "{BED66185-00A7-43F7-BD28-C56BC8E4C535}"); + + PerViewportDynamicDrawManager(); + ~PerViewportDynamicDrawManager(); + + // PerViewportDynamicDrawInterface overrides... + void RegisterDynamicDrawContext(AZ::Name name, DrawContextFactory contextInitializer) override; + void UnregisterDynamicDrawContext(AZ::Name name) override; + RHI::Ptr GetDynamicDrawContextForViewport(AZ::Name name, AzFramework::ViewportId viewportId) override; + + private: + struct ViewportData + { + AZStd::unordered_map> m_dynamicDrawContexts; + + // Event handlers + AZ::Event::Handler m_pipelineChangedHandler; + AZ::Event::Handler m_viewportDestroyedHandler; + + // Cached state + bool m_initialized = false; + }; + AZStd::map m_viewportData; + AZStd::unordered_map m_registeredDrawContexts; + AZStd::mutex m_mutexDrawContexts; + }; +} //namespace AZ::AtomBridge diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_files.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_files.cmake index f272d323ae..969030f922 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_files.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_files.cmake @@ -12,10 +12,13 @@ set(FILES Include/AtomBridge/AtomBridgeBus.h Include/AtomBridge/FlyCameraInputBus.h + Include/AtomBridge/PerViewportDynamicDrawInterface.h Source/AtomBridgeSystemComponent.cpp Source/AtomBridgeSystemComponent.h - Source/FlyCameraInputComponent.cpp - Source/FlyCameraInputComponent.h Source/AtomDebugDisplayViewportInterface.cpp Source/AtomDebugDisplayViewportInterface.h + Source/FlyCameraInputComponent.cpp + Source/FlyCameraInputComponent.h + Source/PerViewportDynamicDrawManager.cpp + Source/PerViewportDynamicDrawManager.h ) diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Assets/Shaders/TexturedIcon.azsl b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Assets/Shaders/TexturedIcon.azsl new file mode 100644 index 0000000000..c4367efe6b --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Assets/Shaders/TexturedIcon.azsl @@ -0,0 +1,77 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + + #include + +ShaderResourceGroup InstanceSrg : SRG_PerDraw +{ + float2 m_viewportSize; + Texture2D m_texture; + + Sampler m_sampler + { + MaxAnisotropy = 16; + AddressU = Clamp; + AddressV = Clamp; + AddressW = Clamp; + }; +}; + +struct VSInput +{ + float3 m_position : POSITION; + float4 m_color : COLOR0; + float2 m_uv : TEXCOORD0; +}; + +struct VSOutput +{ + float4 m_position : SV_Position; + float4 m_color : COLOR0; + float2 m_uv : TEXCOORD0; +}; + +VSOutput MainVS(VSInput IN) +{ + // Convert from screen space to clip space + float2 posXY = float2(IN.m_position.xy) / InstanceSrg::m_viewportSize * 2.0f - float2(1.0f, 1.0f); + posXY.y *= -1.0f; + float4 posPS = float4(posXY, IN.m_position.z, 1.0f); + + VSOutput OUT; + OUT.m_position = posPS; + OUT.m_color = IN.m_color; + OUT.m_uv = IN.m_uv; + return OUT; +}; + +struct PSOutput +{ + float4 m_color : SV_Target0; +}; + +PSOutput MainPS(VSOutput IN) +{ + PSOutput OUT; + + float4 tex; + + tex = InstanceSrg::m_texture.Sample(InstanceSrg::m_sampler, IN.m_uv); + float opacity = IN.m_color.a * tex.a; + + // We use pre-multiplied alpha here since it is more flexible. For example, it enables alpha-blended rendering to + // a render target and then alpha blending that render target into another render target + OUT.m_color.rgb = IN.m_color.rgb * tex.rgb * opacity; + + OUT.m_color.a = opacity; + return OUT; +}; diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Assets/Shaders/TexturedIcon.shader b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Assets/Shaders/TexturedIcon.shader new file mode 100644 index 0000000000..601a2664b5 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Assets/Shaders/TexturedIcon.shader @@ -0,0 +1,39 @@ +{ + "Source" : "TexturedIcon", + + "DepthStencilState" : { + "Depth" : { + "Enable" : false, + "CompareFunc" : "Always" + } + }, + + "RasterState" : { + "DepthClipEnable" : false, + "CullMode" : "None" + }, + + "BlendState" : { + "Enable" : true, + "BlendSource" : "One", + "BlendDest" : "AlphaSourceInverse", + "BlendOp" : "Add" + }, + + "DrawList" : "2dpass", + + "ProgramSettings": + { + "EntryPoints": + [ + { + "name": "MainVS", + "type": "Vertex" + }, + { + "name": "MainPS", + "type": "Fragment" + } + ] + } +} diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/CMakeLists.txt b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/CMakeLists.txt new file mode 100644 index 0000000000..20a680bce9 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/CMakeLists.txt @@ -0,0 +1,12 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +add_subdirectory(Code) diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/CMakeLists.txt new file mode 100644 index 0000000000..b3e176c7a3 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/CMakeLists.txt @@ -0,0 +1,35 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +if(PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_target( + NAME AtomViewportDisplayIcons.Editor ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} + NAMESPACE Gem + FILES_CMAKE + atomviewportdisplayicons_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Source + BUILD_DEPENDENCIES + PRIVATE + AZ::AzCore + AZ::AzFramework + AZ::AzToolsFramework + AZ::AtomCore + 3rdParty::Qt::Core + 3rdParty::Qt::Gui + 3rdParty::Qt::Svg + Gem::Atom_RHI.Reflect + Gem::Atom_RPI.Public + Gem::Atom_Bootstrap.Headers + Gem::Atom_AtomBridge.Static + ) +endif() diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.cpp new file mode 100644 index 0000000000..dce83c3072 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.cpp @@ -0,0 +1,339 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include "AtomViewportDisplayIconsSystemComponent.h" + +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace AZ::Render +{ + void AtomViewportDisplayIconsSystemComponent::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serialize = azrtti_cast(context)) + { + serialize->Class() + ->Version(0) + ; + + if (AZ::EditContext* ec = serialize->GetEditContext()) + { + ec->Class("Viewport Display Icons", "Provides an interface for drawing simple icons to the Editor viewport") + ->ClassElement(Edit::ClassElements::EditorData, "") + ->Attribute(Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) + ->Attribute(Edit::Attributes::AutoExpand, true) + ; + } + } + } + + void AtomViewportDisplayIconsSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC("ViewportDisplayIconsService")); + } + + void AtomViewportDisplayIconsSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC("ViewportDisplayIconsService")); + } + + void AtomViewportDisplayIconsSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + required.push_back(AZ_CRC("RPISystem", 0xf2add773)); + required.push_back(AZ_CRC("AtomBridgeService", 0xdb816a99)); + } + + void AtomViewportDisplayIconsSystemComponent::GetDependentServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + } + + void AtomViewportDisplayIconsSystemComponent::Activate() + { + AzToolsFramework::EditorViewportIconDisplay::Register(this); + + Bootstrap::NotificationBus::Handler::BusConnect(); + } + + void AtomViewportDisplayIconsSystemComponent::Deactivate() + { + Bootstrap::NotificationBus::Handler::BusDisconnect(); + + auto perViewportDynamicDrawInterface = AtomBridge::PerViewportDynamicDraw::Get(); + if (!perViewportDynamicDrawInterface) + { + return; + } + if (perViewportDynamicDrawInterface) + { + perViewportDynamicDrawInterface->UnregisterDynamicDrawContext(m_drawContextName); + } + + AzToolsFramework::EditorViewportIconDisplay::Unregister(this); + } + + void AtomViewportDisplayIconsSystemComponent::DrawIcon(const DrawParameters& drawParameters) + { + // Ensure we have a valid viewport context & dynamic draw interface + auto viewportContext = RPI::ViewportContextRequests::Get()->GetViewportContextById(drawParameters.m_viewport); + if (viewportContext == nullptr) + { + return; + } + + auto perViewportDynamicDrawInterface = + AtomBridge::PerViewportDynamicDraw::Get(); + if (!perViewportDynamicDrawInterface) + { + return; + } + + RHI::Ptr dynamicDraw = + perViewportDynamicDrawInterface->GetDynamicDrawContextForViewport(m_drawContextName, drawParameters.m_viewport); + if (dynamicDraw == nullptr) + { + return; + } + + // Find our icon, falling back on a grey placeholder if its image is unavailable + AZ::Data::Instance image = AZ::RPI::ImageSystemInterface::Get()->GetSystemImage(AZ::RPI::SystemImage::Grey); + if (auto iconIt = m_iconData.find(drawParameters.m_icon); iconIt != m_iconData.end()) + { + auto& iconData = iconIt->second; + if (iconData.m_image) + { + image = iconData.m_image; + } + } + else + { + return; + } + + // Initialize our shader + auto viewportSize = viewportContext->GetViewportSize(); + AZ::Data::Instance drawSrg = dynamicDraw->NewDrawSrg(); + drawSrg->SetConstant(m_viewportSizeIndex, AZ::Vector2(aznumeric_cast(viewportSize.m_width), aznumeric_cast(viewportSize.m_height))); + drawSrg->SetImageView(m_textureParameterIndex, image->GetImageView()); + drawSrg->Compile(); + + AZ::Vector3 screenPosition; + if (drawParameters.m_positionSpace == CoordinateSpace::ScreenSpace) + { + screenPosition = drawParameters.m_position; + } + else if (drawParameters.m_positionSpace == CoordinateSpace::WorldSpace) + { + using ViewportRequestBus = AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus; + AzFramework::ScreenPoint position; + ViewportRequestBus::EventResult(position, drawParameters.m_viewport, &ViewportRequestBus::Events::ViewportWorldToScreen, drawParameters.m_position); + screenPosition.SetX(aznumeric_cast(position.m_x)); + screenPosition.SetY(aznumeric_cast(position.m_y)); + } + + struct Vertex + { + float m_position[3]; + AZ::u32 m_color; + float m_uv[2]; + }; + using Indice = AZ::u16; + + // Create a vertex offset from the position to draw from based on the icon size + // Vertex positions are in screen space coordinates + auto createVertex = [&](float offsetX, float offsetY, float u, float v) -> Vertex + { + Vertex vertex; + screenPosition.StoreToFloat3(vertex.m_position); + vertex.m_position[0] += offsetX * drawParameters.m_size.GetX(); + vertex.m_position[1] += offsetY * drawParameters.m_size.GetY(); + vertex.m_color = drawParameters.m_color.ToU32(); + vertex.m_uv[0] = u; + vertex.m_uv[1] = v; + return vertex; + }; + + AZStd::array vertices = { + createVertex(-0.5f, -0.5f, 0.f, 0.f), + createVertex(0.5f, -0.5f, 1.f, 0.f), + createVertex(0.5f, 0.5f, 1.f, 1.f), + createVertex(-0.5f, 0.5f, 0.f, 1.f) + }; + AZStd::array indices = {0, 1, 2, 0, 2, 3}; + dynamicDraw->DrawIndexed(&vertices, vertices.size(), &indices, indices.size(), RHI::IndexFormat::Uint16, drawSrg); + } + + QString AtomViewportDisplayIconsSystemComponent::FindAssetPath(const QString& sourceRelativePath) const + { + bool found = false; + AZStd::vector scanFolders; + AzToolsFramework::AssetSystemRequestBus::BroadcastResult( + found, &AzToolsFramework::AssetSystemRequestBus::Events::GetScanFolders, scanFolders); + if (!found) + { + AZ_Error("AtomViewportDisplayIconSystemComponent", false, "Failed to load asset scan folders"); + return QString(); + } + + for (const auto& folder : scanFolders) + { + QDir dir(folder.data()); + if (dir.exists(sourceRelativePath)) + { + return dir.absoluteFilePath(sourceRelativePath); + } + } + + return QString(); + } + + QImage AtomViewportDisplayIconsSystemComponent::RenderSvgToImage(const QString& svgPath) const + { + // Set up our SVG renderer + QSvgRenderer renderer(svgPath); + renderer.setAspectRatioMode(Qt::KeepAspectRatio); + + // Set up our target image + QSize size = renderer.defaultSize().expandedTo(MinimumRenderedSvgSize); + QImage image(size, QtImageFormat); + image.fill(0x00000000); + + // Render the SVG + QPainter painter(&image); + renderer.render(&painter); + return image; + } + + AZ::Data::Instance AtomViewportDisplayIconsSystemComponent::ConvertToAtomImage(AZ::Uuid assetId, QImage image) const + { + // Ensure our image is in the correct pixel format so we can memcpy it to our renderer image + image.convertTo(QtImageFormat); + Data::Instance streamingImagePool = RPI::ImageSystemInterface::Get()->GetSystemStreamingPool(); + return RPI::StreamingImage::CreateFromCpuData( + *streamingImagePool.get(), + RHI::ImageDimension::Image2D, + RHI::Size(image.width(), image.height(), 1), + RHI::Format::R8G8B8A8_UNORM_SRGB, + image.bits(), + image.sizeInBytes(), + assetId); + } + + AzToolsFramework::EditorViewportIconDisplayInterface::IconId AtomViewportDisplayIconsSystemComponent::GetOrLoadIconForPath( + AZStd::string_view path) + { + AZ_Error( + "AtomViewportDisplayIconsSystemComponent", AzFramework::StringFunc::Path::IsRelative(path.data()), + "GetOrLoadIconForPath assumes that it will always be given a relative path, but got '%s'", path.data()); + + // Check our cache to see if the image is already loaded + auto existingEntryIt = AZStd::find_if(m_iconData.begin(), m_iconData.end(), [&path](const auto& iconData) + { + return iconData.second.m_path == path; + }); + if (existingEntryIt != m_iconData.end()) + { + return existingEntryIt->first; + } + + AZ::Uuid assetId = AZ::Uuid::CreateName(path.data()); + + // Find the asset to load on disk + QString assetPath = FindAssetPath(path.data()); + if (assetPath.isEmpty()) + { + AZ_Error("AtomViewportDisplayIconSystemComponent", false, "Failed to locate icon on disk: \"%s\"", path.data()); + return InvalidIconId; + } + + QImage loadedImage; + + AZStd::string extension; + AzFramework::StringFunc::Path::GetExtension(path.data(), extension, false); + // For SVGs, we need to actually rasterize to an image + if (extension == "svg") + { + loadedImage = RenderSvgToImage(assetPath); + } + // For everything else, we can just load it through QImage via its image plugins + else + { + const bool loaded = loadedImage.load(assetPath); + if (!loaded) + { + AZ_Error("AtomViewportDisplayIconSystemComponent", false, "Failed to load icon: \"%s\"", assetPath.toUtf8().constData()); + return InvalidIconId; + } + } + + // Cache our loaded icon + IconId id = m_currentId++; + IconData& iconData = m_iconData[id]; + iconData.m_path = path; + iconData.m_image = ConvertToAtomImage(assetId, loadedImage); + return id; + } + + AzToolsFramework::EditorViewportIconDisplayInterface::IconLoadStatus AtomViewportDisplayIconsSystemComponent::GetIconLoadStatus( + IconId icon) + { + auto iconIt = m_iconData.find(icon); + if (iconIt == m_iconData.end()) + { + return IconLoadStatus::Unloaded; + } + if (iconIt->second.m_image) + { + return IconLoadStatus::Loaded; + } + return IconLoadStatus::Error; + } + + void AtomViewportDisplayIconsSystemComponent::OnBootstrapSceneReady([[maybe_unused]]AZ::RPI::Scene* bootstrapScene) + { + AtomBridge::PerViewportDynamicDraw::Get()->RegisterDynamicDrawContext(m_drawContextName, [](RPI::Ptr drawContext) + { + auto shader = RPI::LoadShader(DrawContextShaderPath); + drawContext->InitShader(shader); + drawContext->InitVertexFormat( + {{"POSITION", RHI::Format::R32G32B32_FLOAT}, + {"COLOR", RHI::Format::R8G8B8A8_UNORM}, + {"TEXCOORD", RHI::Format::R32G32_FLOAT}}); + drawContext->EndInit(); + }); + } +} // namespace AZ::Render diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.h b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.h new file mode 100644 index 0000000000..0c7366f23b --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.h @@ -0,0 +1,82 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ +#pragma once + +#include + +#include + +#include +#include + +#include +#include +#include + +namespace AZ +{ + class TickRequests; + + namespace Render + { + class AtomViewportDisplayIconsSystemComponent + : public AZ::Component + , public AzToolsFramework::EditorViewportIconDisplayInterface + , public AZ::Render::Bootstrap::NotificationBus::Handler + { + public: + AZ_COMPONENT(AtomViewportDisplayIconsSystemComponent, "{AEC1D3E1-1D9A-437A-B4C6-CFAEE620C160}"); + + static void Reflect(AZ::ReflectContext* context); + + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); + + protected: + // AZ::Component overrides... + void Activate() override; + void Deactivate() override; + + // AzToolsFramework::EditorViewportIconDisplayInterface overrides... + void DrawIcon(const DrawParameters& drawParameters) override; + IconId GetOrLoadIconForPath(AZStd::string_view path) override; + IconLoadStatus GetIconLoadStatus(IconId icon) override; + + // AZ::Render::Bootstrap::NotificationBus::Handler overrides... + void OnBootstrapSceneReady(AZ::RPI::Scene* bootstrapScene) override; + + private: + static constexpr const char* DrawContextShaderPath = "Shaders/TexturedIcon.azshader"; + static constexpr QSize MinimumRenderedSvgSize = QSize(128, 128); + static constexpr QImage::Format QtImageFormat = QImage::Format_RGBA8888; + + QString FindAssetPath(const QString& sourceRelativePath) const; + QImage RenderSvgToImage(const QString& svgPath) const; + AZ::Data::Instance ConvertToAtomImage(AZ::Uuid assetId, QImage image) const; + + Name m_drawContextName = Name("ViewportIconDisplay"); + bool m_shaderIndexesInitialized = false; + RHI::ShaderInputNameIndex m_textureParameterIndex = "m_texture"; + RHI::ShaderInputNameIndex m_viewportSizeIndex = "m_viewportSize"; + + struct IconData + { + AZStd::string m_path; + AZ::Data::Instance m_image = nullptr; + }; + AZStd::unordered_map m_iconData; + IconId m_currentId = 0; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/Module.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/Module.cpp new file mode 100644 index 0000000000..db7672186a --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/Module.cpp @@ -0,0 +1,51 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include +#include +#include + +#include "AtomViewportDisplayIconsSystemComponent.h" + +namespace AZ +{ + namespace Render + { + class AtomViewportDisplayInfoModule + : public AZ::Module + { + public: + AZ_RTTI(AtomViewportDisplayInfoModule, "{8D72F14E-958D-4225-B3BC-C5C87BDDD426}", AZ::Module); + AZ_CLASS_ALLOCATOR(AtomViewportDisplayInfoModule, AZ::SystemAllocator, 0); + + AtomViewportDisplayInfoModule() + : AZ::Module() + { + m_descriptors.insert(m_descriptors.end(), { + AtomViewportDisplayIconsSystemComponent::CreateDescriptor(), + }); + } + + AZ::ComponentTypeList GetRequiredSystemComponents() const override + { + return AZ::ComponentTypeList{ + azrtti_typeid(), + }; + } + }; + } // namespace Render +} // namespace AZ + +// DO NOT MODIFY THIS LINE UNLESS YOU RENAME THE GEM +// The first parameter should be GemName_GemIdLower +// The second should be the fully qualified name of the class above +AZ_DECLARE_MODULE_CLASS(Gem_AtomViewportDisplayInfo, AZ::Render::AtomViewportDisplayInfoModule) diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/atomviewportdisplayicons_files.cmake b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/atomviewportdisplayicons_files.cmake new file mode 100644 index 0000000000..f02aed0856 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/atomviewportdisplayicons_files.cmake @@ -0,0 +1,16 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(FILES + Source/AtomViewportDisplayIconsSystemComponent.cpp + Source/AtomViewportDisplayIconsSystemComponent.h + Source/Module.cpp +) diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json deleted file mode 100644 index dd92a99ea9..0000000000 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "gem_name": "AtomLyIntegration_AtomViewportDisplayInfo", - "display_name": "Atom Viewport Display Info Overlay", - "summary": "Provides a diagnostic viewport overlay for the default O3DE Atom viewport.", - "canonical_tags": [ - "Gem" - ], - "user_tags": [ - "AtomLyIntegration", - "AtomViewportDisplayInfo" - ] -} \ No newline at end of file diff --git a/Gems/AtomLyIntegration/CMakeLists.txt b/Gems/AtomLyIntegration/CMakeLists.txt index 35022e643b..ff6800a7ff 100644 --- a/Gems/AtomLyIntegration/CMakeLists.txt +++ b/Gems/AtomLyIntegration/CMakeLists.txt @@ -17,3 +17,4 @@ add_subdirectory(AtomFont) add_subdirectory(TechnicalArt) add_subdirectory(AtomBridge) add_subdirectory(AtomViewportDisplayInfo) +add_subdirectory(AtomViewportDisplayIcons) From 1248dc5fb43889530de28bc38feca79fd75ca414 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Wed, 26 May 2021 16:39:24 -0700 Subject: [PATCH 189/811] Spawning priority threshold through SetReg The priority threshold to consider a task high priority can now be configured through the Settings Registry under key "/O3DE/AzFramework/Spawnables/HighPriorityThreshold". --- .../Spawnable/SpawnableEntitiesManager.cpp | 34 +++++++------------ .../Spawnable/SpawnableEntitiesManager.h | 10 ++---- Registry/prefab.setreg | 14 ++++++++ 3 files changed, 30 insertions(+), 28 deletions(-) create mode 100644 Registry/prefab.setreg diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp index caf1112e9b..2c80aa8cbd 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp @@ -10,9 +10,11 @@ * */ +#include #include #include #include +#include #include #include #include @@ -26,7 +28,7 @@ namespace AzFramework void SpawnableEntitiesManager::QueueRequest(EntitySpawnTicket& ticket, SpawnablePriority priority, T&& request) { request.m_ticket = &GetTicketPayload(ticket); - Queue& queue = priority <= HighPriorityThreshold ? m_highPriorityQueue : m_regularPriorityQueue; + Queue& queue = priority <= m_highPriorityThreshold ? m_highPriorityQueue : m_regularPriorityQueue; { AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); request.m_requestId = GetTicketPayload(ticket).m_nextRequestId++; @@ -34,6 +36,16 @@ namespace AzFramework } } + SpawnableEntitiesManager::SpawnableEntitiesManager() + { + if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + { + AZ::u64 value = 64; + settingsRegistry->Get(value, "/O3DE/AzFramework/Spawnables/HighPriorityThreshold"); + m_highPriorityThreshold = aznumeric_cast(AZStd::clamp(value, 0llu, 255llu)); + } + } + void SpawnableEntitiesManager::SpawnAllEntities( EntitySpawnTicket& ticket, SpawnablePriority priority, EntityPreInsertionCallback preInsertionCallback, EntitySpawnCallback completionCallback) @@ -608,24 +620,4 @@ namespace AzFramework return false; } } - - bool SpawnableEntitiesManager::IsEqualTicket(const EntitySpawnTicket* lhs, const EntitySpawnTicket* rhs) - { - return GetTicketPayload(lhs) == GetTicketPayload(rhs); - } - - bool SpawnableEntitiesManager::IsEqualTicket(const Ticket* lhs, const EntitySpawnTicket* rhs) - { - return lhs == GetTicketPayload(rhs); - } - - bool SpawnableEntitiesManager::IsEqualTicket(const EntitySpawnTicket* lhs, const Ticket* rhs) - { - return GetTicketPayload(lhs) == rhs; - } - - bool SpawnableEntitiesManager::IsEqualTicket(const Ticket* lhs, const Ticket* rhs) - { - return lhs = rhs; - } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h index b98be60145..373a4db9cb 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h @@ -50,8 +50,7 @@ namespace AzFramework Regular = 1 << 1 }; - static constexpr SpawnablePriority HighPriorityThreshold = SpawnablePriority { 64 }; - + SpawnableEntitiesManager(); ~SpawnableEntitiesManager() override = default; // @@ -202,16 +201,13 @@ namespace AzFramework bool ProcessRequest(BarrierCommand& request, AZ::SerializeContext& serializeContext); bool ProcessRequest(DestroyTicketCommand& request, AZ::SerializeContext& serializeContext); - [[nodiscard]] static bool IsEqualTicket(const EntitySpawnTicket* lhs, const EntitySpawnTicket* rhs); - [[nodiscard]] static bool IsEqualTicket(const Ticket* lhs, const EntitySpawnTicket* rhs); - [[nodiscard]] static bool IsEqualTicket(const EntitySpawnTicket* lhs, const Ticket* rhs); - [[nodiscard]] static bool IsEqualTicket(const Ticket* lhs, const Ticket* rhs); - Queue m_highPriorityQueue; Queue m_regularPriorityQueue; AZ::Event> m_onSpawnedEvent; AZ::Event> m_onDespawnedEvent; + + SpawnablePriority m_highPriorityThreshold { 64 }; }; AZ_DEFINE_ENUM_BITWISE_OPERATORS(AzFramework::SpawnableEntitiesManager::CommandQueuePriority); diff --git a/Registry/prefab.setreg b/Registry/prefab.setreg new file mode 100644 index 0000000000..903dc0c4f8 --- /dev/null +++ b/Registry/prefab.setreg @@ -0,0 +1,14 @@ +{ + "O3DE": + { + "AzFramework": + { + "Spawnables": + { + // Any requests with a priorty value equal or smaller than this will be considered a high priority request. + // The range for this value is between 0 and 255. + "HighPriorityThreshold" : 64 + } + } + } +} \ No newline at end of file From b5599ca739627e94e75b139f3177267d1fbdcae2 Mon Sep 17 00:00:00 2001 From: sconel Date: Wed, 26 May 2021 16:45:04 -0700 Subject: [PATCH 190/811] Add asset picker support to spawn SC node and thread safety measures --- .../Serialization/EditContextConstants.inl | 1 + .../Spawnable/SpawnableAssetHandler.cpp | 7 ++ .../Spawnable/SpawnableAssetHandler.h | 1 + .../Prefab/Spawnable/ProcesedObjectStore.cpp | 5 +- .../UI/PropertyEditor/PropertyAssetCtrl.cpp | 46 +++++++++- .../UI/PropertyEditor/PropertyAssetCtrl.hxx | 7 ++ .../SpawnNodeable.ScriptCanvasNodeable.xml | 13 +++ .../Libraries/Spawning/SpawnNodeable.cpp | 90 ++++++++++++++----- .../Libraries/Spawning/SpawnNodeable.h | 18 +++- 9 files changed, 158 insertions(+), 30 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl b/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl index 1016027966..dfd0707ed2 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl +++ b/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl @@ -123,6 +123,7 @@ namespace AZ const static AZ::Crc32 NameLabelOverride = AZ_CRC("NameLabelOverride", 0x9ff79cab); const static AZ::Crc32 AssetPickerTitle = AZ_CRC_CE("AssetPickerTitle"); + const static AZ::Crc32 HideProductFilesInAssetPicker = AZ_CRC_CE("HideProductFilesInAssetPicker"); const static AZ::Crc32 ChildNameLabelOverride = AZ_CRC("ChildNameLabelOverride", 0x73dd2909); //! Container attribute that is used to override labels for its elements given the index of the element const static AZ::Crc32 IndexedChildNameLabelOverride = AZ_CRC("IndexedChildNameLabelOverride", 0x5f313ac2); diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableAssetHandler.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableAssetHandler.cpp index b3ba1568bd..da046ff172 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableAssetHandler.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableAssetHandler.cpp @@ -10,6 +10,7 @@ * */ +#include #include #include #include @@ -88,4 +89,10 @@ namespace AzFramework { extensions.push_back(Spawnable::FileExtension); } + + uint32_t SpawnableAssetHandler::BuildSubId(AZStd::string_view id) + { + AZ::Uuid subIdHash = AZ::Uuid::CreateData(id.data(), id.size()); + return azlossy_caster(subIdHash.GetHash()); + } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableAssetHandler.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableAssetHandler.h index deef314955..78268bf71a 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableAssetHandler.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableAssetHandler.h @@ -47,6 +47,7 @@ namespace AzFramework const char* GetGroup() const override; const char* GetBrowserIcon() const override; void GetAssetTypeExtensions(AZStd::vector& extensions) override; + static uint32_t BuildSubId(AZStd::string_view id); protected: LoadResult LoadAssetData( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.cpp index 78d1332a71..050afd813d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include namespace AzToolsFramework::Prefab::PrefabConversionUtils @@ -73,8 +73,7 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils uint32_t ProcessedObjectStore::BuildSubId(AZStd::string_view id) { - AZ::Uuid subIdHash = AZ::Uuid::CreateData(id.data(), id.size()); - return azlossy_caster(subIdHash.GetHash()); + return AzFramework::SpawnableAssetHandler::BuildSubId(id); } const AZStd::string& ProcessedObjectStore::GetId() const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp index 23f8378df5..4bf261122d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp @@ -777,6 +777,23 @@ namespace AzToolsFramework selection.SetDefaultDirectory(defaultDirectory); } + if (m_hideProductFilesInAssetPicker) + { + FilterConstType displayFilter = selection.GetDisplayFilter(); + + EntryTypeFilter* productsFilter = new EntryTypeFilter(); + productsFilter->SetEntryType(AssetBrowserEntry::AssetEntryType::Product); + + InverseFilter* noProductsFilter = new InverseFilter(); + noProductsFilter->SetFilter(FilterConstType(productsFilter)); + + CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND); + compFilter->AddFilter(FilterConstType(displayFilter)); + compFilter->AddFilter(FilterConstType(noProductsFilter)); + + selection.SetDisplayFilter(FilterConstType(compFilter)); + } + AssetBrowserComponentRequestBus::Broadcast(&AssetBrowserComponentRequests::PickAssets, selection, parentWidget()); if (selection.IsValid()) { @@ -785,7 +802,16 @@ namespace AzToolsFramework AZ_Assert(product || folder, "Incorrect entry type selected. Expected product or folder."); if (product) { - SetSelectedAssetID(product->GetAssetId()); + AZ::Data::AssetId selectedAssetId = product->GetAssetId(); + + // If we hid the product files a source asset was picked + // Clear the sub id as a source could have N products with different sub ids + if (m_hideProductFilesInAssetPicker) + { + selectedAssetId.m_subId = 0; + } + + SetSelectedAssetID(selectedAssetId); } else if (folder) { @@ -1172,6 +1198,16 @@ namespace AzToolsFramework return m_showProductAssetName; } + void PropertyAssetCtrl::SetHideProductFilesInAssetPicker(bool hide) + { + m_hideProductFilesInAssetPicker = hide; + } + + bool PropertyAssetCtrl::GetHideProductFilesInAssetPicker() const + { + return m_hideProductFilesInAssetPicker; + } + void PropertyAssetCtrl::SetShowThumbnail(bool enable) { m_showThumbnail = enable; @@ -1297,6 +1333,14 @@ namespace AzToolsFramework GUI->SetShowProductAssetName(showProductAssetName); } } + else if(attrib == AZ::Edit::Attributes::HideProductFilesInAssetPicker) + { + bool hideProductFilesInAssetPicker = false; + if (attrValue->Read(hideProductFilesInAssetPicker)) + { + GUI->SetHideProductFilesInAssetPicker(hideProductFilesInAssetPicker); + } + } else if (attrib == AZ::Edit::Attributes::ClearNotify) { PropertyAssetCtrl::ClearCallbackType* func = azdynamic_cast(attrValue->GetAttribute()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx index 37af3d0594..5a6310eb35 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx @@ -158,6 +158,10 @@ namespace AzToolsFramework //! Assets can be either source or product assets generated from source assets. By default, source assets are shown in the property asset. You can override that with this flag. bool m_showProductAssetName = true; + //! Assets can be either source or product assets generated from source assets. + //! By default the asset picker shows both on an AZ::Asset<> property. You can hide product assets with this flag. + bool m_hideProductFilesInAssetPicker = false; + bool m_showThumbnail = false; bool m_showThumbnailDropDownButton = false; EditCallbackType* m_thumbnailCallback = nullptr; @@ -211,6 +215,9 @@ namespace AzToolsFramework void SetShowProductAssetName(bool enable); bool GetShowProductAssetName() const; + void SetHideProductFilesInAssetPicker(bool hide); + bool GetHideProductFilesInAssetPicker() const; + void SetShowThumbnail(bool enable); bool GetShowThumbnail() const; void SetShowThumbnailDropDownButton(bool enable); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml index b2f48fae5f..d0c4cfd806 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml @@ -7,6 +7,7 @@ Base="ScriptCanvas::Nodeable" Icon="Icons/ScriptCanvas/Placeholder.png" Category="Spawning" + Version="0" GeneratePropertyFriend="True" Namespace="ScriptCanvas" Description="Spawn"> @@ -21,5 +22,17 @@ /> + + + + + + + + + diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index 0e067b65bf..93a248de5d 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -14,6 +14,7 @@ #include #include +#include namespace ScriptCanvas { @@ -23,9 +24,6 @@ namespace ScriptCanvas { SpawnNodeable::SpawnNodeable() { - AZ::Data::AssetId cubeAssetId("{90552CB9-2F29-5A2E-976C-61BF7ADACB81}", 272062881); - m_spawnableAsset = AZ::Data::AssetManager::Instance().GetAsset(cubeAssetId, AZ::Data::AssetLoadBehavior::PreLoad); - AZ::Data::AssetManager::Instance().BlockUntilLoadComplete(m_spawnableAsset); } SpawnNodeable::SpawnNodeable(const SpawnNodeable& rhs) @@ -35,35 +33,85 @@ namespace ScriptCanvas void SpawnNodeable::OnInitializeExecutionState() { + if (!AZ::TickBus::Handler::BusIsConnected()) + { + AZ::TickBus::Handler::BusConnect(); + } + + m_spawnTicket.IsValid(); m_spawnTicket = AzFramework::EntitySpawnTicket(m_spawnableAsset); } void SpawnNodeable::OnDeactivate() { + if (AZ::TickBus::Handler::BusIsConnected()) + { + AZ::TickBus::Handler::BusDisconnect(); + } + m_spawnTicket = AzFramework::EntitySpawnTicket(); } - //void SpawnNodeable::Translation(Data::Vector3Type translation) - //{ - // m_translation = translation; - //} + void SpawnNodeable::OnTick([[maybe_unused]] float delta, [[maybe_unused]] AZ::ScriptTimePoint timePoint) + { + AZStd::vector swappedSpawnedEntityList; + AZStd::vector swappedSpawnBatchSizes; + { + AZStd::lock_guard lock(m_recursiveMutex); - //void SpawnNodeable::Rotation(Data::Vector3Type rotation) - //{ - // m_rotation = rotation; - //} + swappedSpawnedEntityList.swap(m_spawnedEntityList); + swappedSpawnBatchSizes.swap(m_spawnBatchSizes); + } - //void SpawnNodeable::Scale(Data::Vector3Type scale) - //{ - // m_scale = scale; - //} + AZ::EntityId* batchBegin = swappedSpawnedEntityList.data(); + for (size_t batchSize : swappedSpawnBatchSizes) + { + if (batchSize == 0) + { + continue; + } + + AZStd::vector spawnedEntitiesBatch( + batchBegin, batchBegin + batchSize); + + CallOnSpawn(AZStd::move(spawnedEntitiesBatch)); + + batchBegin += batchSize; + } + } + + void SpawnNodeable::OnSpawnAssetChanged() + { + if (m_spawnableAsset.GetId().IsValid()) + { + AZStd::string rootSpawnableFile; + AzFramework::StringFunc::Path::GetFileName(m_spawnableAsset.GetHint().c_str(), rootSpawnableFile); + + rootSpawnableFile += AzFramework::Spawnable::DotFileExtension; + + AZ::u32 rootSubId = AzFramework::SpawnableAssetHandler::BuildSubId(AZStd::move(rootSpawnableFile)); + + if (m_spawnableAsset.GetId().m_subId != rootSubId) + { + AZ::Data::AssetId rootAssetId = m_spawnableAsset.GetId(); + rootAssetId.m_subId = rootSubId; + + m_spawnableAsset = AZ::Data::AssetManager::Instance(). + FindOrCreateAsset(rootAssetId, AZ::Data::AssetLoadBehavior::Default); + } + } + } void SpawnNodeable::RequestSpawn(Data::Vector3Type translation, Data::Vector3Type rotation, Data::NumberType scale) { + if (!m_spawnableAsset.IsReady()) + { + return; + } + auto preSpawnCB = [this, translation, rotation, scale]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, AzFramework::SpawnableEntityContainerView view) { - AZ::Entity* rootEntity = *view.begin(); AzFramework::TransformComponent* entityTransform = @@ -81,15 +129,13 @@ namespace ScriptCanvas auto spawnCompleteCB = [this]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, AzFramework::SpawnableConstEntityContainerView view) { - AZStd::vector spawnedEntities; - spawnedEntities.resize(view.size()); - + AZStd::lock_guard lock(m_recursiveMutex); + m_spawnedEntityList.reserve(m_spawnedEntityList.size() + view.size()); for (const AZ::Entity* entity : view) { - spawnedEntities.emplace_back(entity->GetId()); + m_spawnedEntityList.emplace_back(entity->GetId()); } - - CallOnSpawn(spawnedEntities); + m_spawnBatchSizes.push_back(view.size()); }; AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_spawnTicket, preSpawnCB, spawnCompleteCB); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h index 4d73449d58..25cb92742e 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h @@ -14,7 +14,10 @@ #include +#include + #include + #include #include #include @@ -26,21 +29,28 @@ namespace ScriptCanvas namespace Spawning { class SpawnNodeable - : public ScriptCanvas::Nodeable + : public ScriptCanvas::Nodeable, + public AZ::TickBus::Handler { SCRIPTCANVAS_NODE(SpawnNodeable); public: SpawnNodeable(); - SpawnNodeable(const SpawnNodeable& rhs); void OnInitializeExecutionState() override; - void OnDeactivate() override; + //TickBus + void OnTick(float delta, AZ::ScriptTimePoint timePoint) override; + + void OnSpawnAssetChanged(); + private: - AZ::Data::Asset m_spawnableAsset; AzFramework::EntitySpawnTicket m_spawnTicket; + + AZStd::vector m_spawnedEntityList; + AZStd::vector m_spawnBatchSizes; + AZStd::recursive_mutex m_recursiveMutex; }; } } From 4fc7d72b2b755fc8ccd7a1f4baee601015a96f4d Mon Sep 17 00:00:00 2001 From: chiyteng Date: Wed, 26 May 2021 16:49:09 -0700 Subject: [PATCH 191/811] modify DetachPrefabFromParent function for debugging --- .../Prefab/PrefabPublicHandler.cpp | 44 +++---------------- 1 file changed, 6 insertions(+), 38 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 315c7b5710..d3553c78e1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -1042,14 +1042,14 @@ namespace AzToolsFramework InstanceOptionalReference parentInstance = owningInstance->get().GetParentInstance(); const auto parentTemplateId = parentInstance->get().GetTemplateId(); - Prefab::PrefabDom instanceDomBefore; - m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, parentInstance->get()); - { - auto getInstancePtrResult = parentInstance->get().GetNestedInstance(owningInstance->get().GetInstanceAlias()); - AZ_Assert(getInstancePtrResult, "Can't find selected container entity's owning Instance."); + auto instancePtr = parentInstance->get().DetachNestedInstance(owningInstance->get().GetInstanceAlias()); + AZ_Assert(instancePtr, "Can't detach selected Instance from its parent Instance."); - auto& instancePtr = getInstancePtrResult->get(); + RemoveLink(instancePtr, parentTemplateId, currentUndoBatch); + + Prefab::PrefabDom instanceDomBefore; + m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, parentInstance->get()); AZStd::unordered_map oldEntityAliases; oldEntityAliases.emplace(entityId, instancePtr->GetEntityAlias(entityId)->get()); @@ -1115,25 +1115,6 @@ namespace AzToolsFramework linkPatchesCopy.CopyFrom(linkPatches->get(), linkPatchesCopy.GetAllocator()); RemoveLink(nestedInstancePtr, instanceTemplateId, currentUndoBatch); - - /*auto getNestedInstanceContainerEntityResult = nestedInstancePtr->GetContainerEntity(); - AZ_Assert(getNestedInstanceContainerEntityResult.has_value(), "Can't get nested instance container entitt."); - - auto& nestedInstanceContainerEntity = getNestedInstanceContainerEntityResult->get(); - auto nestedInstanceContainerEntityId = nestedInstanceContainerEntity.GetId(); - - PrefabDom containerEntityDomBefore; - m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomBefore, nestedInstanceContainerEntity); - - AZ::TransformBus::Event(nestedInstanceContainerEntityId, &AZ::TransformInterface::SetParent, containerEntity.GetId()); - - PrefabDom containerEntityDomAfter; - m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomAfter, nestedInstanceContainerEntity); - - PrefabDom reparentPatch; - m_instanceToTemplateInterface->GeneratePatch(reparentPatch, containerEntityDomBefore, containerEntityDomAfter); - m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(reparentPatch, nestedInstanceContainerEntityId);*/ - PrefabDomUtils::PrintPrefabDomValue("linkPatchesCopy", linkPatchesCopy); //update aliases @@ -1156,21 +1137,8 @@ namespace AzToolsFramework linkPatchesCopy.Parse(previousPatchString.toUtf8().constData()); CreateLink(*nestedInstancePtr, parentTemplateId, currentUndoBatch, AZStd::move(linkPatchesCopy), true); - - //update links? - //// Update the cache - this prevents these changes from being stored in the regular undo/redo nodes as a separate step - //m_prefabUndoCache.Store(nestedInstanceContainerEntityId, AZStd::move(containerEntityDomAfter)); - - //// Save these changes as patches to the link - //PrefabUndoLinkUpdate* linkUpdate = aznew PrefabUndoLinkUpdate(AZStd::to_string(static_cast(nestedInstanceContainerEntityId))); - //linkUpdate->SetParent(undoBatch.GetUndoBatch()); - //linkUpdate->Capture(reparentPatch, nestedInstance->GetLinkId()); - - //linkUpdate->Redo(); }); - RemoveLink(instancePtr, parentTemplateId, currentUndoBatch); - AzToolsFramework::ToolsApplicationRequestBus::Broadcast( &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); } From 44c8a19bcee970dee0052f328e9a7f6722ffb9b9 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 26 May 2021 19:05:33 -0500 Subject: [PATCH 192/811] Fix Python TypeError in the engine_template.py create-project command --- scripts/o3de/o3de/engine_template.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/o3de/o3de/engine_template.py b/scripts/o3de/o3de/engine_template.py index f4d2b63cff..63dec3e765 100755 --- a/scripts/o3de/o3de/engine_template.py +++ b/scripts/o3de/o3de/engine_template.py @@ -1338,6 +1338,10 @@ def create_project(project_path: str, if template_name and not template_path: template_path = manifest.get_registered(template_name=template_name) + if not template_path: + logger.error(f'Could not find the template path using name {template_name}.\n' + f'Has the engine been registered yet. It can be registered via the "o3de.py register --this-engine" command') + return 1 if not os.path.isdir(template_path): logger.error(f'Could not find the template {template_name}=>{template_path}') return 1 From 9b1be43367876ba1b35b19de6c7733bd3a497563 Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Wed, 26 May 2021 19:17:17 -0500 Subject: [PATCH 193/811] Renamed osx_gl to mac and es3 to android for cache folders (#949) --- .../grass_atlas_diff.tif.exportsettings | 2 +- .../grass_atlas_sss.tif.exportsettings | 2 +- .../ap_all_platforms_setup_fixture.py | 6 +- .../bundler_batch_setup_fixture.py | 6 +- .../asset_bundler_batch_tests.py | 72 ++--- .../asset_processor_batch_tests.py | 2 +- .../ProxyGray_ddna.tif.exportsettings | 2 +- Code/CryEngine/CryCommon/ISystem.h | 2 +- Code/CryEngine/CrySystem/System.h | 2 +- .../AzCore/PlatformId/PlatformDefaults.cpp | 14 +- .../AzCore/PlatformId/PlatformDefaults.h | 14 +- .../AzCore/AzCore/PlatformId/PlatformId.cpp | 4 +- .../AzCore/AzCore/PlatformId/PlatformId.h | 2 +- .../AzCore/Script/ScriptSystemComponent.cpp | 2 +- .../Tests/SettingsRegistryMergeUtilsTests.cpp | 18 +- .../API/EditorAssetSystemAPI.h | 6 +- .../Tests/AssetSeedManager.cpp | 82 +++--- .../PlatformAddressedAssetCatalogTests.cpp | 16 +- Code/Framework/Tests/PlatformHelper.cpp | 8 +- Code/Sandbox/Editor/CryEditPy.cpp | 2 +- .../tests/AssetProcessorPlatformConfig.setreg | 2 +- .../tests/applicationManagerTests.cpp | 2 +- Code/Tools/AssetBundler/tests/tests_main.cpp | 8 +- .../AssetBuilderSDK/AssetBuilderSDK.cpp | 16 +- .../AssetBuilderSDK/AssetBuilderSDK.h | 8 +- .../AssetCatalog/AssetCatalogUnitTests.cpp | 20 +- .../assetBuilderSDK/assetBuilderSDKTest.cpp | 36 +-- .../AssetProcessorManagerTest.cpp | 14 +- .../platformconfigurationtests.cpp | 46 ++-- .../AssetProcessorManagerUnitTests.cpp | 252 +++++++++--------- .../native/unittests/ConnectionUnitTests.cpp | 8 +- .../native/unittests/MockConnectionHandler.h | 4 +- .../PlatformConfigurationUnitTests.cpp | 10 +- .../unittests/RCcontrollerUnitTests.cpp | 6 +- .../native/unittests/UnitTestRunner.cpp | 2 +- .../AssetProcessorPlatformConfig.setreg | 4 +- .../AssetProcessorPlatformConfig.setreg | 2 +- .../AssetProcessorPlatformConfig.setreg | 2 +- .../AssetProcessorPlatformConfig.setreg | 10 +- .../AssetProcessorPlatformConfig.setreg | 14 +- Code/Tools/GridHub/GridHub/gridhub.cpp | 2 +- .../Code/Source/Editor/EditorCommon.cpp | 4 +- .../Platform/Mac/ImageProcessing_Traits_Mac.h | 2 +- .../Platform/iOS/ImageProcessing_Traits_iOS.h | 2 +- .../1024x1024_24bit.tif.exportsettings | 2 +- .../ImageProcessingAtom/Config/Albedo.preset | 4 +- .../Config/AlbedoWithCoverage.preset | 4 +- .../Config/AlbedoWithGenericAlpha.preset | 4 +- .../Config/AlbedoWithOpacity.preset | 4 +- .../Config/AmbientOcclusion.preset | 4 +- .../Config/CloudShadows.preset | 4 +- .../Config/ColorChart.preset | 4 +- .../Config/ConvolvedCubemap.preset | 4 +- .../Config/Decal_AlbedoWithOpacity.preset | 4 +- ...etail_MergedAlbedoNormalsSmoothness.preset | 4 +- ...gedAlbedoNormalsSmoothness_Lossless.preset | 4 +- .../Config/Displacement.preset | 4 +- .../Config/Emissive.preset | 4 +- .../Config/Gradient.preset | 4 +- .../Config/Greyscale.preset | 4 +- .../Config/IBLDiffuse.preset | 4 +- .../Config/IBLSkybox.preset | 4 +- .../Config/IBLSpecular.preset | 4 +- .../Config/ImageBuilder.settings | 4 +- .../Config/LUT_RG16.preset | 4 +- .../Config/LUT_RG32F.preset | 4 +- .../ImageProcessingAtom/Config/LUT_RG8.preset | 4 +- .../Config/LUT_RGBA32F.preset | 4 +- .../Config/LUT_RGBA8.preset | 4 +- .../Config/LayerMask.preset | 4 +- .../Config/LensOptics.preset | 4 +- .../Config/LightProjector.preset | 4 +- .../Config/LoadingScreen.preset | 4 +- .../ImageProcessingAtom/Config/Minimap.preset | 4 +- .../Config/MuzzleFlash.preset | 4 +- .../ImageProcessingAtom/Config/Normals.preset | 4 +- .../Config/NormalsFromDisplacement.preset | 4 +- .../Config/NormalsWithSmoothness.preset | 4 +- .../NormalsWithSmoothness_Legacy.preset | 4 +- .../ImageProcessingAtom/Config/Opacity.preset | 4 +- .../Config/ReferenceImage.preset | 4 +- .../Config/ReferenceImage_HDRLinear.preset | 4 +- ...eferenceImage_HDRLinearUncompressed.preset | 4 +- .../Config/ReferenceImage_Linear.preset | 4 +- .../Config/Reflectance.preset | 4 +- .../ReflectanceWithSmoothness_Legacy.preset | 4 +- .../Config/Reflectance_Linear.preset | 4 +- .../ImageProcessingAtom/Config/SF_Font.preset | 4 +- .../Config/SF_Gradient.preset | 4 +- .../Config/SF_Image.preset | 4 +- .../Config/SF_Image_nonpower2.preset | 4 +- .../ImageProcessingAtom/Config/Skybox.preset | 4 +- .../Config/Terrain_Albedo.preset | 4 +- .../Config/Terrain_Albedo_HighPassed.preset | 4 +- .../Config/Uncompressed.preset | 4 +- .../Config/UserInterface_Compressed.preset | 4 +- .../Config/UserInterface_Lossless.preset | 4 +- .../Source/Editor/ShaderBuilderUtility.cpp | 16 +- .../PostProcessing/AreaTex.dds.assetinfo | 4 +- .../PostProcessing/SearchTex.dds.assetinfo | 4 +- .../PaperMill_E_3k.exr.assetinfo | 4 +- .../RHI.Builders/ShaderPlatformInterface.cpp | 2 +- .../Foliage_Leaves_0_BaseColor.dds.assetinfo | 4 +- .../Builder/AudioControlBuilderWorker.cpp | 4 +- .../Code/Source/Engine/Config_wwise.h | 2 +- .../Android/wwise_config_android.json | 2 +- .../Platform/Mac/wwise_config_mac.json | 2 +- .../Viewport/Canvas_Background.tif.assetinfo | 4 +- .../LyShineExamples/CircleFrame.tif.assetinfo | 4 +- .../CircleGradient.png.assetinfo | 4 +- .../Circle_Shadow.tif.assetinfo | 4 +- .../LyShineExamples/ColorTest.tif.assetinfo | 4 +- .../ColorTestPow2.tif.assetinfo | 4 +- .../ParticleGlow.tif.assetinfo | 4 +- .../LyShineExamples/button.tif.assetinfo | 4 +- .../buttonPressed.tif.assetinfo | 4 +- .../buttonSlider.tif.assetinfo | 4 +- .../checkbox_spritesheet.tif.assetinfo | 4 +- .../LyShineExamples/checkered3.tif.assetinfo | 4 +- .../LyShineExamples/empty_icon.tif.assetinfo | 4 +- .../LyShineExamples/fixed_image.tif.assetinfo | 4 +- .../flipbook_walking.tif.assetinfo | 4 +- .../LyShineExamples/mask.tif.assetinfo | 4 +- .../LyShineExamples/outline.tif.assetinfo | 4 +- .../outlineRounded.tif.assetinfo | 4 +- .../LyShineExamples/panelBkgd.tif.assetinfo | 4 +- .../pattern02_big.tif.assetinfo | 4 +- .../pattern02vertical.tif.assetinfo | 4 +- .../pattern02vertical_big.tif.assetinfo | 4 +- .../LyShineExamples/pattern03.tif.assetinfo | 4 +- .../pattern03_big.tif.assetinfo | 4 +- .../scroll_box_icon_1.tif.assetinfo | 4 +- .../scroll_box_icon_10.tif.assetinfo | 4 +- .../scroll_box_icon_2.tif.assetinfo | 4 +- .../scroll_box_icon_3.tif.assetinfo | 4 +- .../scroll_box_icon_4.tif.assetinfo | 4 +- .../scroll_box_icon_5.tif.assetinfo | 4 +- .../scroll_box_icon_6.tif.assetinfo | 4 +- .../scroll_box_icon_7.tif.assetinfo | 4 +- .../scroll_box_icon_8.tif.assetinfo | 4 +- .../scroll_box_icon_9.tif.assetinfo | 4 +- .../scroll_box_map.tif.assetinfo | 4 +- .../LyShineExamples/selected.tif.assetinfo | 4 +- .../shadowInside2.tif.assetinfo | 4 +- .../shadowInsideSquare.tif.assetinfo | 4 +- .../Actor/chicken_diff.png.imagesettings | 4 +- .../anodized_metal_diff.tif.exportsettings | 2 +- .../brushed_steel_ddna.tif.exportsettings | 2 +- .../dark_leather_diff.tif.exportsettings | 2 +- .../galvanized_steel_spec.tif.exportsettings | 2 +- .../leather_ddna.tif.exportsettings | 2 +- .../light_leather_diff.tif.exportsettings | 2 +- .../mixed_stones_ddna.tif.exportsettings | 2 +- .../mixed_stones_diff.tif.exportsettings | 2 +- .../pbs_reference/red_diff.tif.exportsettings | 2 +- ...tary_brushed_steel_ddna.tif.exportsettings | 2 +- .../rust_ddna.tif.exportsettings | 2 +- .../rust_diff.tif.exportsettings | 2 +- .../wood_planks_ddna.tif.exportsettings | 2 +- .../Code/Source/Pipeline/MeshExporter.cpp | 2 +- .../Textures/Cowboy_01_ddna.tif.imagesettings | 4 +- .../Textures/Cowboy_01_spec.tif.imagesettings | 4 +- .../Basic/Button_Sliced_Normal.tif.assetinfo | 4 +- .../Basic/Button_Sliced_Pressed.tif.assetinfo | 4 +- .../Button_Sliced_Selected.tif.assetinfo | 4 +- .../Button_Stretched_Normal.tif.assetinfo | 4 +- .../Button_Stretched_Pressed.tif.assetinfo | 4 +- .../Button_Stretched_Selected.tif.assetinfo | 4 +- .../Basic/CheckBox_Check.tif.assetinfo | 4 +- .../CheckBox_Check_Background.tif.assetinfo | 4 +- .../Basic/CheckBox_Cross.tif.assetinfo | 4 +- .../Textures/Basic/CheckBox_Off.tif.assetinfo | 4 +- .../Textures/Basic/CheckBox_On.tif.assetinfo | 4 +- ...Checkbox_Background_Disabled.tif.assetinfo | 4 +- .../Checkbox_Background_Hover.tif.assetinfo | 4 +- .../Checkbox_Background_Normal.tif.assetinfo | 4 +- .../Textures/Basic/Checkered.tif.assetinfo | 4 +- .../Slider_Background_Disabled.tif.assetinfo | 4 +- .../Slider_Background_Hover.tif.assetinfo | 4 +- .../Slider_Background_Normal.tif.assetinfo | 4 +- .../Basic/Slider_Fill_Sliced.tif.assetinfo | 4 +- .../Basic/Slider_Fill_Stretch.tif.assetinfo | 4 +- .../Basic/Slider_Manipulator.tif.assetinfo | 4 +- .../Basic/Slider_Track_Sliced.tif.assetinfo | 4 +- .../Basic/Slider_Track_Stretch.tif.assetinfo | 4 +- .../Text_Input_Sliced_Normal.tif.assetinfo | 4 +- .../Text_Input_Sliced_Pressed.tif.assetinfo | 4 +- .../Text_Input_Sliced_Selected.tif.assetinfo | 4 +- .../Prefab/Dropdown_Arrow.tif.assetinfo | 4 +- .../Prefab/Dropdown_ArrowL.tif.assetinfo | 4 +- .../Prefab/Dropdown_ArrowR.tif.assetinfo | 4 +- .../Prefab/Dropdown_ArrowU.tif.assetinfo | 4 +- .../Prefab/Dropdown_Button.tif.assetinfo | 4 +- .../Prefab/Dropdown_Menu.tif.assetinfo | 4 +- ...ioButton_Background_Disabled.tif.assetinfo | 4 +- ...RadioButton_Background_Hover.tif.assetinfo | 4 +- ...adioButton_Background_Normal.tif.assetinfo | 4 +- .../Prefab/RadioButton_Dot.tif.assetinfo | 4 +- .../Prefab/button_disabled.tif.assetinfo | 4 +- .../Prefab/button_normal.tif.assetinfo | 4 +- .../checkbox_box_disabled.tif.assetinfo | 4 +- .../Prefab/checkbox_box_hover.tif.assetinfo | 4 +- .../Prefab/checkbox_box_normal.tif.assetinfo | 6 +- .../Prefab/checkbox_check.tif.assetinfo | 4 +- .../Prefab/scrollbar_handle.tif.assetinfo | 4 +- .../scrollbar_horiz_track.tif.assetinfo | 4 +- .../Prefab/scrollbar_vert_track.tif.assetinfo | 4 +- .../Prefab/slider_fill_disabled.tif.assetinfo | 4 +- .../Prefab/slider_fill_normal.tif.assetinfo | 4 +- .../slider_handle_disabled.tif.assetinfo | 4 +- .../Prefab/slider_handle_normal.tif.assetinfo | 4 +- .../slider_track_disabled.tif.assetinfo | 4 +- .../Prefab/slider_track_normal.tif.assetinfo | 4 +- .../Prefab/textinput_disabled.tif.assetinfo | 4 +- .../Prefab/textinput_hover.tif.assetinfo | 4 +- .../Prefab/textinput_normal.tif.assetinfo | 4 +- .../Prefab/tooltip_sliced.tif.assetinfo | 4 +- Registry/AssetProcessorPlatformConfig.setreg | 14 +- Registry/bootstrap.setreg | 4 +- .../_internal/managers/platforms/mac.py | 6 +- .../_internal/managers/platforms/windows.py | 2 +- .../ly_test_tools/o3de/asset_processor.py | 4 +- cmake/Platform/Android/PAL_android.cmake | 2 +- cmake/Platform/Mac/PAL_mac.cmake | 2 +- .../Platform/Android/android_deployment.py | 2 +- .../Android/generate_android_project.py | 2 +- .../Android/unit_test_android_deployment.py | 10 +- .../build/Platform/Android/build_config.json | 2 +- scripts/build/Platform/Mac/build_config.json | 2 +- scripts/bundler/gen_shaders.py | 4 +- ...roid_es3.cfg => system_android_android.cfg | 2 +- system_mac_osx_gl.cfg => system_mac_mac.cfg | 0 232 files changed, 733 insertions(+), 733 deletions(-) rename system_android_es3.cfg => system_android_android.cfg (93%) rename system_mac_osx_gl.cfg => system_mac_mac.cfg (100%) diff --git a/AutomatedTesting/Assets/Objects/Foliage/Textures/grass_atlas_diff.tif.exportsettings b/AutomatedTesting/Assets/Objects/Foliage/Textures/grass_atlas_diff.tif.exportsettings index 5c4c862583..b65133fbb0 100644 --- a/AutomatedTesting/Assets/Objects/Foliage/Textures/grass_atlas_diff.tif.exportsettings +++ b/AutomatedTesting/Assets/Objects/Foliage/Textures/grass_atlas_diff.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /preset=AlbedoWithGenericAlpha /reduce="es3:2,ios:2,osx_gl:0,pc:0,provo:0" \ No newline at end of file +/autooptimizefile=0 /preset=AlbedoWithGenericAlpha /reduce="android:2,ios:2,mac:0,pc:0,provo:0" \ No newline at end of file diff --git a/AutomatedTesting/Assets/Objects/Foliage/Textures/grass_atlas_sss.tif.exportsettings b/AutomatedTesting/Assets/Objects/Foliage/Textures/grass_atlas_sss.tif.exportsettings index 441a11bc68..e8da408b36 100644 --- a/AutomatedTesting/Assets/Objects/Foliage/Textures/grass_atlas_sss.tif.exportsettings +++ b/AutomatedTesting/Assets/Objects/Foliage/Textures/grass_atlas_sss.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /preset=Albedo /reduce="es3:3,ios:3,osx_gl:0,pc:0,provo:0" \ No newline at end of file +/autooptimizefile=0 /preset=Albedo /reduce="android:3,ios:3,mac:0,pc:0,provo:0" \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_all_platforms_setup_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_all_platforms_setup_fixture.py index e729ee9882..9a5b93ca80 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_all_platforms_setup_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_all_platforms_setup_fixture.py @@ -34,10 +34,10 @@ def ap_all_platforms_setup_fixture(request, workspace, ap_setup_fixture) -> Dict # Specific platform cache locations resources["pc_cache_location"] = os.path.join(cache_dir, "pc") - resources["es3_cache_location"] = os.path.join(cache_dir, "es3") + resources["android_cache_location"] = os.path.join(cache_dir, "android") resources["ios_cache_location"] = os.path.join(cache_dir, "ios") - resources["osx_gl_cache_location"] = os.path.join(cache_dir, "osx_gl") + resources["mac_cache_location"] = os.path.join(cache_dir, "mac") resources["provo_cache_location"] = os.path.join(cache_dir, "provo") - resources["all_platforms"] = ["pc", "es3", "ios", "osx_gl", "provo"] + resources["all_platforms"] = ["pc", "android", "ios", "mac", "provo"] return resources diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py index 580816e7b5..7a85cb1813 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py @@ -54,7 +54,7 @@ def bundler_batch_setup_fixture(request, workspace, asset_processor, timeout) -> platforms = [platform.strip() for platform in platforms.split(",")] else: # No commandline argument provided, default to mac and pc - platforms = ["pc", "osx_gl"] + platforms = ["pc", "mac"] class BundlerBatchFixture: """ @@ -241,11 +241,11 @@ def bundler_batch_setup_fixture(request, workspace, asset_processor, timeout) -> def get_platform_flag(self, platform_name: str) -> int: if (platform_name == "pc"): return 1 - elif (platform_name == "es3"): + elif (platform_name == "android"): return 2 elif (platform_name == "ios"): return 4 - elif (platform_name == "osx_gl"): + elif (platform_name == "mac"): return 8 elif (platform_name == "server"): return 128 diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py index d236e87aa2..8738e8acdf 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py @@ -460,9 +460,9 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): """ helper = bundler_batch_helper # fmt:off - assert "pc" in helper["platforms"] and "osx_gl" in helper["platforms"], \ + assert "pc" in helper["platforms"] and "mac" in helper["platforms"], \ "This test requires both PC and MAC platforms to be enabled. " \ - "Please rerun with commandline option: '--bundle_platforms=pc,osx_gl'" + "Please rerun with commandline option: '--bundle_platforms=pc,mac'" # fmt:on seed_list = os.path.join(workspace.paths.engine_root(), "Engine", "SeedAssetList.seed") # Engine seed list @@ -502,7 +502,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): for bundle_file in bundle_files.values(): assert os.path.isfile(bundle_file) - # This asset is created on osx_gl platform but not on windows + # This asset is created on mac platform but not on windows file_to_check = b"engineassets/shading/defaultprobe_cm.dds.5" # [use byte str because file is in binary] # Extract the delta catalog file from pc archive. {file_to_check} SHOULD NOT be present for PC @@ -512,11 +512,11 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): f"{file_to_check} was found in DeltaCatalog.xml in pc bundle file {bundle_files['pc']}" # fmt:on - # Extract the delta catalog file from osx_gl archive. {file_to_check} SHOULD be present for MAC - file_contents = helper.extract_file_content(bundle_files["osx_gl"], "DeltaCatalog.xml") + # Extract the delta catalog file from mac archive. {file_to_check} SHOULD be present for MAC + file_contents = helper.extract_file_content(bundle_files["mac"], "DeltaCatalog.xml") # fmt:off assert file_to_check in file_contents, \ - f"{file_to_check} was not found in DeltaCatalog.xml in darwin bundle file {bundle_files['osx_gl']}" + f"{file_to_check} was not found in DeltaCatalog.xml in darwin bundle file {bundle_files['mac']}" # fmt:on # Gather checksums for first set of bundles @@ -613,7 +613,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): helper.call_seeds( seedListFile=helper["seed_list_file"], addSeed=test_asset, - platform="pc,osx_gl", + platform="pc,mac", ) # Validate both mac and pc are activated for seed @@ -626,7 +626,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): helper.call_seeds( seedListFile=helper["seed_list_file"], removePlatformFromSeeds="", - platform="osx_gl", + platform="mac", ) # Validate only pc platform for seed. Save file contents to variable all_lines = check_seed_platform(helper["seed_list_file"], test_asset, helper["platform_values"]["pc"]) @@ -646,7 +646,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): helper.call_seeds( seedListFile=helper["seed_list_file"], addPlatformToSeeds="", - platform="osx_gl", + platform="mac", ) # Validate Mac platform was added back on. Save file contents # fmt:off @@ -670,7 +670,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): helper.call_seeds( seedListFile=helper["seed_list_file"], removeSeed=test_asset, - platform="pc,osx_gl", + platform="pc,mac", ) # Validate seed was removed from file @@ -697,9 +697,9 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): env = ap_setup_fixture # fmt:off - assert "pc" in helper["platforms"] and "osx_gl" in helper["platforms"], \ + assert "pc" in helper["platforms"] and "mac" in helper["platforms"], \ "This test requires both PC and MAC platforms to be enabled. " \ - "Please rerun with commandline option: '--bundle_platforms=pc,osx_gl'" + "Please rerun with commandline option: '--bundle_platforms=pc,mac'" # fmt:on # Test assets arranged in common lists: six (0-5) .txt files and .dat files @@ -717,16 +717,16 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): file_platforms = { "txtfile_0.txt": "pc", "txtfile_1.txt": "pc", - "txtfile_2.txt": "pc,osx_gl", - "txtfile_3.txt": "pc,osx_gl", - "txtfile_4.txt": "osx_gl", - "txtfile_5.txt": "osx_gl", + "txtfile_2.txt": "pc,mac", + "txtfile_3.txt": "pc,mac", + "txtfile_4.txt": "mac", + "txtfile_5.txt": "mac", "datfile_0.dat": "pc", "datfile_1.dat": "pc", - "datfile_2.dat": "pc,osx_gl", - "datfile_3.dat": "pc,osx_gl", - "datfile_4.dat": "osx_gl", - "datfile_5.dat": "osx_gl", + "datfile_2.dat": "pc,mac", + "datfile_3.dat": "pc,mac", + "datfile_4.dat": "mac", + "datfile_5.dat": "mac", } # Comparison rules files and their associated 'comparisonType' flags @@ -741,7 +741,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): # Get our test assets ready and processed utils.prepare_test_assets(env["tests_dir"], "C16877178", env["project_test_assets_dir"]) - asset_processor.batch_process(timeout=timeout, fastscan=False, platforms="pc,osx_gl") + asset_processor.batch_process(timeout=timeout, fastscan=False, platforms="pc,mac") # *** Some helper functions *** # @@ -759,7 +759,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): helper.call_assetLists( assetListFile=os.path.join(helper["test_dir"], asset_list_file_name), seedListFile=os.path.join(helper["test_dir"], seed_file_name), - platform="pc,osx_gl", + platform="pc,mac", ) def get_platform_assets(asset_name_list: List[str]) -> Dict[str, List[str]]: @@ -769,7 +769,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): for asset_name in asset_name_list: if "pc" in file_platforms[asset_name]: win_assets.append(asset_name) - if "osx_gl" in file_platforms[asset_name]: + if "mac" in file_platforms[asset_name]: mac_assets.append(asset_name) return {"win": win_assets, "mac": mac_assets} @@ -798,7 +798,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): # Get platform result file names win_asset_list_file = helper.platform_file_name(request_file, platforms["pc"]) - mac_asset_list_file = helper.platform_file_name(request_file, platforms["osx_gl"]) + mac_asset_list_file = helper.platform_file_name(request_file, platforms["mac"]) # Get expected platforms for each asset in asset_names platform_files = get_platform_assets(asset_names) @@ -879,14 +879,14 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): # fmt:on # End verify_asset_list_contents() - def run_compare_command_and_verify(platform_arg: str, expect_pc_output: bool, expect_osx_gl_output: bool) -> None: + def run_compare_command_and_verify(platform_arg: str, expect_pc_output: bool, expect_mac_output: bool) -> None: # Expected asset list to equal result of comparison expected_pc_asset_list = None - expected_osx_gl_asset_list = None + expected_mac_asset_list = None # Last output file. Use this for comparison to 'expected' output_pc_asset_list = None - output_osx_gl_asset_list = None + output_mac_asset_list = None # Add the platform to the file name to match what the Bundler will create last_output_arg = output_arg.split(",")[-1] @@ -895,10 +895,10 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): expected_pc_asset_list = os.path.join(helper["test_dir"], helper.platform_file_name(expected_asset_list, platform)) output_pc_asset_list = helper.platform_file_name(last_output_arg, platform) - if expect_osx_gl_output: - platform = platforms["osx_gl"] - expected_osx_gl_asset_list = os.path.join(helper["test_dir"], helper.platform_file_name(expected_asset_list, platform)) - output_osx_gl_asset_list = helper.platform_file_name(last_output_arg, platform) + if expect_mac_output: + platform = platforms["mac"] + expected_mac_asset_list = os.path.join(helper["test_dir"], helper.platform_file_name(expected_asset_list, platform)) + output_mac_asset_list = helper.platform_file_name(last_output_arg, platform) # Build execution command cmd = generate_compare_command(platform_arg) @@ -911,15 +911,15 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): verify_asset_list_contents(expected_pc_asset_list, output_pc_asset_list) fs.delete([output_pc_asset_list], True, True) - if expect_osx_gl_output: - verify_asset_list_contents(expected_osx_gl_asset_list, output_osx_gl_asset_list) - fs.delete([output_osx_gl_asset_list], True, True) + if expect_mac_output: + verify_asset_list_contents(expected_mac_asset_list, output_mac_asset_list) + fs.delete([output_mac_asset_list], True, True) # End run_compare_command_and_verify() # Generate command, run and validate for each platform run_compare_command_and_verify("pc", True, False) - run_compare_command_and_verify("osx_gl", False, True) - run_compare_command_and_verify("pc,osx_gl", True, True) + run_compare_command_and_verify("mac", False, True) + run_compare_command_and_verify("pc,mac", True, True) #run_compare_command_and_verify(None, True, True) # End compare_and_check() diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py index 50b3af1438..0d830b39e2 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py @@ -102,7 +102,7 @@ class TestsAssetProcessorBatch_AllPlatforms(object): def test_RunAPBatch_TwoPlatforms_ExitCodeZero(self, asset_processor): asset_processor.create_temp_asset_root() asset_processor.enable_asset_processor_platform("pc") - asset_processor.enable_asset_processor_platform("osx_gl") + asset_processor.enable_asset_processor_platform("mac") result, _ = asset_processor.batch_process() assert result, "AP Batch failed" diff --git a/AutomatedTesting/Objects/LumberTank/ProxyGray_ddna.tif.exportsettings b/AutomatedTesting/Objects/LumberTank/ProxyGray_ddna.tif.exportsettings index 013c774e9e..a4e1a9a3c5 100644 --- a/AutomatedTesting/Objects/LumberTank/ProxyGray_ddna.tif.exportsettings +++ b/AutomatedTesting/Objects/LumberTank/ProxyGray_ddna.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="es3:1,ios:1,osx_gl:0,pc:0,provo:0" \ No newline at end of file +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="android:1,ios:1,mac:0,pc:0,provo:0" \ No newline at end of file diff --git a/Code/CryEngine/CryCommon/ISystem.h b/Code/CryEngine/CryCommon/ISystem.h index f863804f3d..653776f55b 100644 --- a/Code/CryEngine/CryCommon/ISystem.h +++ b/Code/CryEngine/CryCommon/ISystem.h @@ -125,7 +125,7 @@ enum ESystemConfigPlatform { CONFIG_INVALID_PLATFORM = 0, CONFIG_PC = 1, - CONFIG_OSX_GL = 2, + CONFIG_MAC = 2, CONFIG_OSX_METAL = 3, CONFIG_ANDROID = 4, CONFIG_IOS = 5, diff --git a/Code/CryEngine/CrySystem/System.h b/Code/CryEngine/CrySystem/System.h index b91b1ba059..a258030f70 100644 --- a/Code/CryEngine/CrySystem/System.h +++ b/Code/CryEngine/CrySystem/System.h @@ -729,7 +729,7 @@ protected: // ------------------------------------------------------------- CCmdLine* m_pCmdLine; string m_currentLanguageAudio; - string m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_es3.cfg or system_android_opengl.cfg or system_windows_pc.cfg + string m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_android.cfg or system_windows_pc.cfg std::vector< std::pair > m_updateTimes; diff --git a/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp index 63aad1ecf4..c3f6357706 100644 --- a/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp +++ b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp @@ -19,7 +19,7 @@ namespace AZ { inline namespace PlatformDefaults { - static const char* PlatformNames[PlatformId::NumPlatformIds] = { PlatformPC, PlatformES3, PlatformIOS, PlatformOSX, PlatformProvo, PlatformSalem, PlatformJasper, PlatformServer, PlatformAll, PlatformAllClient }; + static const char* PlatformNames[PlatformId::NumPlatformIds] = { PlatformPC, PlatformAndroid, PlatformIOS, PlatformMac, PlatformProvo, PlatformSalem, PlatformJasper, PlatformServer, PlatformAll, PlatformAllClient }; const char* PlatformIdToPalFolder(AZ::PlatformId platform) { @@ -31,11 +31,11 @@ namespace AZ { case AZ::PC: return "PC"; - case AZ::ES3: + case AZ::ANDROID_ID: return "Android"; case AZ::IOS: return "iOS"; - case AZ::OSX: + case AZ::MAC: return "Mac"; case AZ::PROVO: return "Provo"; @@ -66,11 +66,11 @@ namespace AZ } else if (osPlatform == PlatformCodeNameMac) { - return PlatformOSX; + return PlatformMac; } else if (osPlatform == PlatformCodeNameAndroid) { - return PlatformES3; + return PlatformAndroid; } else if (osPlatform == PlatformCodeNameiOS) { @@ -207,13 +207,13 @@ namespace AZ platformCodes.emplace_back(PlatformCodeNameWindows); platformCodes.emplace_back(PlatformCodeNameLinux); break; - case PlatformId::ES3: + case PlatformId::ANDROID_ID: platformCodes.emplace_back(PlatformCodeNameAndroid); break; case PlatformId::IOS: platformCodes.emplace_back(PlatformCodeNameiOS); break; - case PlatformId::OSX: + case PlatformId::MAC: platformCodes.emplace_back(PlatformCodeNameMac); break; case PlatformId::PROVO: diff --git a/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h index 2d67c860cd..93477ebeb9 100644 --- a/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h +++ b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h @@ -27,9 +27,9 @@ namespace AZ inline namespace PlatformDefaults { constexpr char PlatformPC[] = "pc"; - constexpr char PlatformES3[] = "es3"; + constexpr char PlatformAndroid[] = "android"; constexpr char PlatformIOS[] = "ios"; - constexpr char PlatformOSX[] = "osx_gl"; + constexpr char PlatformMac[] = "mac"; constexpr char PlatformProvo[] = "provo"; constexpr char PlatformSalem[] = "salem"; constexpr char PlatformJasper[] = "jasper"; @@ -54,9 +54,9 @@ namespace AZ AZ_ENUM_WITH_UNDERLYING_TYPE(PlatformId, int, (Invalid, -1), PC, - ES3, + ANDROID_ID, IOS, - OSX, + MAC, PROVO, SALEM, JASPER, @@ -73,9 +73,9 @@ namespace AZ { Platform_NONE = 0x00, Platform_PC = 1 << PlatformId::PC, - Platform_ES3 = 1 << PlatformId::ES3, + Platform_ANDROID = 1 << PlatformId::ANDROID_ID, Platform_IOS = 1 << PlatformId::IOS, - Platform_OSX = 1 << PlatformId::OSX, + Platform_MAC = 1 << PlatformId::MAC, Platform_PROVO = 1 << PlatformId::PROVO, Platform_SALEM = 1 << PlatformId::SALEM, Platform_JASPER = 1 << PlatformId::JASPER, @@ -87,7 +87,7 @@ namespace AZ // A special platform that will always correspond to all non-server platforms, even if new ones are added Platform_ALL_CLIENT = 1ULL << 31, - AllNamedPlatforms = Platform_PC | Platform_ES3 | Platform_IOS | Platform_OSX | Platform_PROVO | Platform_SALEM | Platform_JASPER | Platform_SERVER, + AllNamedPlatforms = Platform_PC | Platform_ANDROID | Platform_IOS | Platform_MAC | Platform_PROVO | Platform_SALEM | Platform_JASPER | Platform_SERVER, }; AZ_DEFINE_ENUM_BITWISE_OPERATORS(PlatformFlags); diff --git a/Code/Framework/AzCore/AzCore/PlatformId/PlatformId.cpp b/Code/Framework/AzCore/AzCore/PlatformId/PlatformId.cpp index 0258869a0c..d56140be28 100644 --- a/Code/Framework/AzCore/AzCore/PlatformId/PlatformId.cpp +++ b/Code/Framework/AzCore/AzCore/PlatformId/PlatformId.cpp @@ -28,8 +28,8 @@ namespace AZ return "Android64"; case PlatformID::PLATFORM_APPLE_IOS: return "iOS"; - case PlatformID::PLATFORM_APPLE_OSX: - return "OSX"; + case PlatformID::PLATFORM_APPLE_MAC: + return "Mac"; #if defined(AZ_EXPAND_FOR_RESTRICTED_PLATFORM) || defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) #define AZ_RESTRICTED_PLATFORM_EXPANSION(CodeName, CODENAME, codename, PrivateName, PRIVATENAME, privatename, PublicName, PUBLICNAME, publicname, PublicAuxName1, PublicAuxName2, PublicAuxName3)\ case PlatformID::PLATFORM_##PUBLICNAME:\ diff --git a/Code/Framework/AzCore/AzCore/PlatformId/PlatformId.h b/Code/Framework/AzCore/AzCore/PlatformId/PlatformId.h index ce1a11d8ce..e8e7cef6dd 100644 --- a/Code/Framework/AzCore/AzCore/PlatformId/PlatformId.h +++ b/Code/Framework/AzCore/AzCore/PlatformId/PlatformId.h @@ -23,7 +23,7 @@ namespace AZ PLATFORM_WINDOWS_64, PLATFORM_LINUX_64, PLATFORM_APPLE_IOS, - PLATFORM_APPLE_OSX, + PLATFORM_APPLE_MAC, PLATFORM_ANDROID_64, // ARMv8 / 64-bit #if defined(AZ_EXPAND_FOR_RESTRICTED_PLATFORM) || defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) #define AZ_RESTRICTED_PLATFORM_EXPANSION(CodeName, CODENAME, codename, PrivateName, PRIVATENAME, privatename, PublicName, PUBLICNAME, publicname, PublicAuxName1, PublicAuxName2, PublicAuxName3)\ diff --git a/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp b/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp index 015554538f..11d4db2e07 100644 --- a/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp +++ b/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp @@ -937,7 +937,7 @@ void ScriptSystemComponent::Reflect(ReflectContext* reflection) ->Enum(PlatformID::PLATFORM_LINUX_64)>("Linux") ->Enum(PlatformID::PLATFORM_ANDROID_64)>("Android64") ->Enum(PlatformID::PLATFORM_APPLE_IOS)>("iOS") - ->Enum(PlatformID::PLATFORM_APPLE_OSX)>("OSX") + ->Enum(PlatformID::PLATFORM_APPLE_MAC)>("Mac") #if defined(AZ_EXPAND_FOR_RESTRICTED_PLATFORM) || defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) #define AZ_RESTRICTED_PLATFORM_EXPANSION(CodeName, CODENAME, codename, PrivateName, PRIVATENAME, privatename, PublicName, PUBLICNAME, publicname, PublicAuxName1, PublicAuxName2, PublicAuxName3)\ ->Enum(PlatformID::PLATFORM_##PUBLICNAME)>(#CodeName) diff --git a/Code/Framework/AzCore/Tests/SettingsRegistryMergeUtilsTests.cpp b/Code/Framework/AzCore/Tests/SettingsRegistryMergeUtilsTests.cpp index 36b9757ce3..751d9ded6c 100644 --- a/Code/Framework/AzCore/Tests/SettingsRegistryMergeUtilsTests.cpp +++ b/Code/Framework/AzCore/Tests/SettingsRegistryMergeUtilsTests.cpp @@ -372,15 +372,15 @@ mac_remote_filesystem=0 -- We need to know this before we establish VFS because different platform assets -- are stored in different root folders in the cache. These correspond to the names -- In the asset processor config file. This value also controls what config file is read --- when you read system_xxxx_xxxx.cfg (for example, system_windows_pc.cfg or system_android_es3.cfg) +-- when you read system_xxxx_xxxx.cfg (for example, system_windows_pc.cfg or system_android_android.cfg) -- by default, pc assets (in the 'pc' folder) are used, with RC being fed 'pc' as the platform -- by default on console we use the default assets=pc for better iteration times -- we should turn on console specific assets only when in release and/or testing assets and/or loading performance -- that way most people will not need to have 3 different caches taking up disk space assets = pc -android_assets = es3 +android_assets = android ios_assets = ios -mac_assets = osx_gl +mac_assets = mac -- Add the IP address of your console to the white list that will connect to the asset processor here -- You can list addresses or CIDR's. CIDR's are helpful if you are using DHCP. A CIDR looks like an ip address with @@ -438,9 +438,9 @@ mac_wait_for_connect=0 ConfigFileParams::SettingsKeyValuePair{"/ios_remote_filesystem", AZ::s64{0}}, ConfigFileParams::SettingsKeyValuePair{"/mac_remote_filesystem", AZ::s64{0}}, ConfigFileParams::SettingsKeyValuePair{"/assets", AZStd::string_view{"pc"}}, - ConfigFileParams::SettingsKeyValuePair{"/android_assets", AZStd::string_view{"es3"}}, + ConfigFileParams::SettingsKeyValuePair{"/android_assets", AZStd::string_view{"android"}}, ConfigFileParams::SettingsKeyValuePair{"/ios_assets", AZStd::string_view{"ios"}}, - ConfigFileParams::SettingsKeyValuePair{"/mac_assets", AZStd::string_view{"osx_gl"}}, + ConfigFileParams::SettingsKeyValuePair{"/mac_assets", AZStd::string_view{"mac"}}, ConfigFileParams::SettingsKeyValuePair{"/connect_to_remote", AZ::s64{0}}, ConfigFileParams::SettingsKeyValuePair{"/windows_connect_to_remote", AZ::s64{1}}, ConfigFileParams::SettingsKeyValuePair{"/android_connect_to_remote", AZ::s64{0}}, @@ -478,20 +478,20 @@ test_asset_processor_tag = test_value [Platform pc] tags=tools,renderer,dx12,vulkan -[Platform es3] +[Platform android] tags=android,mobile,renderer,vulkan ; With Comments at the end [Platform ios] tags=mobile,renderer,metal -[Platform osx_gl] +[Platform mac] tags=tools,renderer,metal)" , AZStd::fixed_vector{ ConfigFileParams::SettingsKeyValuePair{"/test_asset_processor_tag", AZStd::string_view{"test_value"}}, ConfigFileParams::SettingsKeyValuePair{"/Platform pc/tags", AZStd::string_view{"tools,renderer,dx12,vulkan"}}, - ConfigFileParams::SettingsKeyValuePair{"/Platform es3/tags", AZStd::string_view{"android,mobile,renderer,vulkan"}}, + ConfigFileParams::SettingsKeyValuePair{"/Platform android/tags", AZStd::string_view{"android,mobile,renderer,vulkan"}}, ConfigFileParams::SettingsKeyValuePair{"/Platform ios/tags", AZStd::string_view{"mobile,renderer,metal"}}, - ConfigFileParams::SettingsKeyValuePair{"/Platform osx_gl/tags", AZStd::string_view{"tools,renderer,metal"}}, + ConfigFileParams::SettingsKeyValuePair{"/Platform mac/tags", AZStd::string_view{"tools,renderer,metal"}}, }} ) ); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorAssetSystemAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorAssetSystemAPI.h index 1599d29589..715de30bfa 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorAssetSystemAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorAssetSystemAPI.h @@ -120,14 +120,14 @@ namespace AzToolsFramework /** * Query to see if a specific asset platform is enabled - * @param platform the asset platform to check e.g. es3, ios, etc. + * @param platform the asset platform to check e.g. android, ios, etc. * @return true if enabled, false otherwise */ virtual bool IsAssetPlatformEnabled(const char* platform) = 0; /** * Get the total number of pending assets left to process for a specific asset platform - * @param platform the asset platform to check e.g. es3, ios, etc. + * @param platform the asset platform to check e.g. android, ios, etc. * @return -1 if the process fails, a positive number otherwise */ virtual int GetPendingAssetsForPlatform(const char* platform) = 0; @@ -312,7 +312,7 @@ namespace AzToolsFramework inline const char* GetHostAssetPlatform() { #if defined(AZ_PLATFORM_MAC) - return "osx_gl"; + return "mac"; #elif defined(AZ_PLATFORM_WINDOWS) return "pc"; #elif defined(AZ_PLATFORM_LINUX) diff --git a/Code/Framework/AzToolsFramework/Tests/AssetSeedManager.cpp b/Code/Framework/AzToolsFramework/Tests/AssetSeedManager.cpp index 3d45c10fca..33009bc0da 100644 --- a/Code/Framework/AzToolsFramework/Tests/AssetSeedManager.cpp +++ b/Code/Framework/AzToolsFramework/Tests/AssetSeedManager.cpp @@ -82,7 +82,7 @@ namespace UnitTest } m_testPlatforms[0] = AzFramework::PlatformId::PC; - m_testPlatforms[1] = AzFramework::PlatformId::ES3; + m_testPlatforms[1] = AzFramework::PlatformId::ANDROID_ID; int platformCount = 0; for(auto thisPlatform : m_testPlatforms) @@ -170,20 +170,20 @@ namespace UnitTest AzFramework::AssetCatalog assetCatalog(useRequestBus); AZStd::string pcCatalogFile = AzToolsFramework::PlatformAddressedAssetCatalog::GetCatalogRegistryPathForPlatform(AzFramework::PlatformId::PC); - AZStd::string es3CatalogFile = AzToolsFramework::PlatformAddressedAssetCatalog::GetCatalogRegistryPathForPlatform(AzFramework::PlatformId::ES3); + AZStd::string androidCatalogFile = AzToolsFramework::PlatformAddressedAssetCatalog::GetCatalogRegistryPathForPlatform(AzFramework::PlatformId::ANDROID_ID); if (!assetCatalog.SaveCatalog(pcCatalogFile.c_str(), m_assetRegistry)) { GTEST_FATAL_FAILURE_(AZStd::string::format("Unable to save the asset catalog (PC) file.\n").c_str()); } - if (!assetCatalog.SaveCatalog(es3CatalogFile.c_str(), m_assetRegistry)) + if (!assetCatalog.SaveCatalog(androidCatalogFile.c_str(), m_assetRegistry)) { - GTEST_FATAL_FAILURE_(AZStd::string::format("Unable to save the asset catalog (ES3) file.\n").c_str()); + GTEST_FATAL_FAILURE_(AZStd::string::format("Unable to save the asset catalog (ANDROID) file.\n").c_str()); } m_pcCatalog = new AzToolsFramework::PlatformAddressedAssetCatalog(AzFramework::PlatformId::PC); - m_es3Catalog = new AzToolsFramework::PlatformAddressedAssetCatalog(AzFramework::PlatformId::ES3); + m_androidCatalog = new AzToolsFramework::PlatformAddressedAssetCatalog(AzFramework::PlatformId::ANDROID_ID); const AZStd::string engroot = AZ::Test::GetEngineRootPath(); AZ::IO::FileIOBase::GetInstance()->SetAlias("@engroot@", engroot.c_str()); @@ -227,21 +227,21 @@ namespace UnitTest } auto pcCatalogFile = AzToolsFramework::PlatformAddressedAssetCatalog::GetCatalogRegistryPathForPlatform(AzFramework::PlatformId::PC); - auto es3CatalogFile = AzToolsFramework::PlatformAddressedAssetCatalog::GetCatalogRegistryPathForPlatform(AzFramework::PlatformId::ES3); + auto androidCatalogFile = AzToolsFramework::PlatformAddressedAssetCatalog::GetCatalogRegistryPathForPlatform(AzFramework::PlatformId::ANDROID_ID); if (fileIO->Exists(pcCatalogFile.c_str())) { fileIO->Remove(pcCatalogFile.c_str()); } - if (fileIO->Exists(es3CatalogFile.c_str())) + if (fileIO->Exists(androidCatalogFile.c_str())) { - fileIO->Remove(es3CatalogFile.c_str()); + fileIO->Remove(androidCatalogFile.c_str()); } delete m_assetSeedManager; delete m_assetRegistry; delete m_pcCatalog; - delete m_es3Catalog; + delete m_androidCatalog; m_application->Stop(); delete m_application; } @@ -342,10 +342,10 @@ namespace UnitTest m_assetSeedManager->AddSeedAsset(assets[2], AzFramework::PlatformFlags::Platform_PC); // Step we are testing - m_assetSeedManager->AddPlatformToAllSeeds(AzFramework::PlatformId::ES3); + m_assetSeedManager->AddPlatformToAllSeeds(AzFramework::PlatformId::ANDROID_ID); // Verification - AzFramework::PlatformFlags expectedPlatformFlags = AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ES3; + AzFramework::PlatformFlags expectedPlatformFlags = AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ANDROID; for (const auto& seedInfo : m_assetSeedManager->GetAssetSeedList()) { EXPECT_EQ(seedInfo.m_platformFlags, expectedPlatformFlags); @@ -358,14 +358,14 @@ namespace UnitTest m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC); m_assetSeedManager->AddSeedAsset(assets[1], AzFramework::PlatformFlags::Platform_PC); - m_es3Catalog->UnregisterAsset(assets[2]); + m_androidCatalog->UnregisterAsset(assets[2]); m_assetSeedManager->AddSeedAsset(assets[2], AzFramework::PlatformFlags::Platform_PC); // Step we are testing - m_assetSeedManager->AddPlatformToAllSeeds(AzFramework::PlatformId::ES3); + m_assetSeedManager->AddPlatformToAllSeeds(AzFramework::PlatformId::ANDROID_ID); // Verification - AzFramework::PlatformFlags expectedPlatformFlags = AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ES3; + AzFramework::PlatformFlags expectedPlatformFlags = AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ANDROID; for (const auto& seedInfo : m_assetSeedManager->GetAssetSeedList()) { if (seedInfo.m_assetId == assets[2]) @@ -383,14 +383,14 @@ namespace UnitTest { // Setup m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC); - m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_ES3); + m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_ANDROID); m_assetSeedManager->AddSeedAsset(assets[1], AzFramework::PlatformFlags::Platform_PC); - m_assetSeedManager->AddSeedAsset(assets[1], AzFramework::PlatformFlags::Platform_ES3); + m_assetSeedManager->AddSeedAsset(assets[1], AzFramework::PlatformFlags::Platform_ANDROID); m_assetSeedManager->AddSeedAsset(assets[2], AzFramework::PlatformFlags::Platform_PC); - m_assetSeedManager->AddSeedAsset(assets[2], AzFramework::PlatformFlags::Platform_ES3); + m_assetSeedManager->AddSeedAsset(assets[2], AzFramework::PlatformFlags::Platform_ANDROID); // Step we are testing - m_assetSeedManager->RemovePlatformFromAllSeeds(AzFramework::PlatformId::ES3); + m_assetSeedManager->RemovePlatformFromAllSeeds(AzFramework::PlatformId::ANDROID_ID); // Verification for (const auto& seedInfo : m_assetSeedManager->GetAssetSeedList()) @@ -514,8 +514,8 @@ namespace UnitTest void DependencyValidation_MultipleAssetSeeds_MultiplePlatformFlags_ListValid() { - m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ES3); - m_assetSeedManager->AddSeedAsset(assets[5], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ES3); + m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ANDROID); + m_assetSeedManager->AddSeedAsset(assets[5], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ANDROID); AzToolsFramework::AssetFileInfoList assetList = m_assetSeedManager->GetDependencyList(AzFramework::PlatformId::PC); @@ -531,7 +531,7 @@ namespace UnitTest assetList.m_fileInfoList.clear(); - m_assetSeedManager->AddSeedAsset(assets[8], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ES3); + m_assetSeedManager->AddSeedAsset(assets[8], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ANDROID); assetList = m_assetSeedManager->GetDependencyList(AzFramework::PlatformId::PC); @@ -547,7 +547,7 @@ namespace UnitTest EXPECT_TRUE(Search(assetList, assets[8])); assetList.m_fileInfoList.clear(); - m_assetSeedManager->RemoveSeedAsset(assets[5], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ES3); + m_assetSeedManager->RemoveSeedAsset(assets[5], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ANDROID); assetList = m_assetSeedManager->GetDependencyList(AzFramework::PlatformId::PC); @@ -562,7 +562,7 @@ namespace UnitTest EXPECT_TRUE(Search(assetList, assets[8])); // Removing the android flag from the asset should still produce the same result - m_assetSeedManager->RemoveSeedAsset(assets[8], AzFramework::PlatformFlags::Platform_ES3); + m_assetSeedManager->RemoveSeedAsset(assets[8], AzFramework::PlatformFlags::Platform_ANDROID); assetList = m_assetSeedManager->GetDependencyList(AzFramework::PlatformId::PC); @@ -576,7 +576,7 @@ namespace UnitTest EXPECT_TRUE(Search(assetList, assets[7])); EXPECT_TRUE(Search(assetList, assets[8])); - assetList = m_assetSeedManager->GetDependencyList(AzFramework::PlatformId::ES3); + assetList = m_assetSeedManager->GetDependencyList(AzFramework::PlatformId::ANDROID_ID); EXPECT_EQ(assetList.m_fileInfoList.size(), 5); EXPECT_TRUE(Search(assetList, assets[0])); @@ -586,8 +586,8 @@ namespace UnitTest EXPECT_TRUE(Search(assetList, assets[4])); // Adding the android flag again to the asset - m_assetSeedManager->AddSeedAsset(assets[8], AzFramework::PlatformFlags::Platform_ES3); - assetList = m_assetSeedManager->GetDependencyList(AzFramework::PlatformId::ES3); + m_assetSeedManager->AddSeedAsset(assets[8], AzFramework::PlatformFlags::Platform_ANDROID); + assetList = m_assetSeedManager->GetDependencyList(AzFramework::PlatformId::ANDROID_ID); EXPECT_EQ(assetList.m_fileInfoList.size(), 8); EXPECT_TRUE(Search(assetList, assets[0])); @@ -773,7 +773,7 @@ namespace UnitTest AzFramework::AssetRegistry* m_assetRegistry; ToolsTestApplication* m_application; AzToolsFramework::PlatformAddressedAssetCatalog* m_pcCatalog; - AzToolsFramework::PlatformAddressedAssetCatalog* m_es3Catalog; + AzToolsFramework::PlatformAddressedAssetCatalog* m_androidCatalog; AZ::IO::FileIOStream m_fileStreams[s_totalTestPlatforms][s_totalAssets]; AzFramework::PlatformId m_testPlatforms[s_totalTestPlatforms]; AZStd::string m_assetsPath[s_totalAssets]; @@ -936,7 +936,7 @@ namespace UnitTest TEST_F(AssetSeedManagerTest, AddSeedAssetForValidPlatforms_AllPlatformsValid_SeedAddedForEveryInputPlatform) { using namespace AzFramework; - PlatformFlags validPlatforms = PlatformFlags::Platform_PC | PlatformFlags::Platform_ES3; + PlatformFlags validPlatforms = PlatformFlags::Platform_PC | PlatformFlags::Platform_ANDROID; AZStd::pair result = m_assetSeedManager->AddSeedAssetForValidPlatforms(TestDynamicSliceAssetPath, validPlatforms); // Verify the function outputs @@ -953,8 +953,8 @@ namespace UnitTest TEST_F(AssetSeedManagerTest, AddSeedAssetForValidPlatforms_SomePlatformsValid_SeedAddedForEveryValidPlatform) { using namespace AzFramework; - PlatformFlags validPlatforms = PlatformFlags::Platform_PC | PlatformFlags::Platform_ES3; - PlatformFlags inputPlatforms = validPlatforms | PlatformFlags::Platform_OSX; + PlatformFlags validPlatforms = PlatformFlags::Platform_PC | PlatformFlags::Platform_ANDROID; + PlatformFlags inputPlatforms = validPlatforms | PlatformFlags::Platform_MAC; AZStd::pair result = m_assetSeedManager->AddSeedAssetForValidPlatforms(TestDynamicSliceAssetPath, inputPlatforms); // Verify the function outputs @@ -971,7 +971,7 @@ namespace UnitTest TEST_F(AssetSeedManagerTest, AddSeedAssetForValidPlatforms_NoPlatformsValid_NoSeedAdded) { using namespace AzFramework; - PlatformFlags inputPlatforms = PlatformFlags::Platform_OSX; + PlatformFlags inputPlatforms = PlatformFlags::Platform_MAC; AZStd::pair result = m_assetSeedManager->AddSeedAssetForValidPlatforms(TestDynamicSliceAssetPath, inputPlatforms); // Verify the function outputs @@ -985,30 +985,30 @@ namespace UnitTest TEST_F(AssetSeedManagerTest, Valid_Seed_Remove_ForAllPlatform_OK) { - m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_MAC); - m_assetSeedManager->RemoveSeedAsset(assets[0].ToString(), AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->RemoveSeedAsset(assets[0].ToString(), AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_MAC); const AzFramework::AssetSeedList& seedList = m_assetSeedManager->GetAssetSeedList(); EXPECT_EQ(seedList.size(), 0); - m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_MAC); - m_assetSeedManager->RemoveSeedAsset("asset0.txt", AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->RemoveSeedAsset("asset0.txt", AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_MAC); const AzFramework::AssetSeedList& secondSeedList = m_assetSeedManager->GetAssetSeedList(); EXPECT_EQ(secondSeedList.size(), 0); } TEST_F(AssetSeedManagerTest, Valid_Seed_Remove_ForSpecificPlatform_OK) { - m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_MAC); - m_assetSeedManager->RemoveSeedAsset(assets[0].ToString(), AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->RemoveSeedAsset(assets[0].ToString(), AzFramework::PlatformFlags::Platform_MAC); const AzFramework::AssetSeedList& seedList = m_assetSeedManager->GetAssetSeedList(); EXPECT_EQ(seedList.size(), 1); - m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_MAC); m_assetSeedManager->RemoveSeedAsset("asset0.txt", AzFramework::PlatformFlags::Platform_PC); const AzFramework::AssetSeedList& secondSeedList = m_assetSeedManager->GetAssetSeedList(); @@ -1017,14 +1017,14 @@ namespace UnitTest TEST_F(AssetSeedManagerTest, Invalid_NotRemove_SeedForAllPlatform_Ok) { - m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_MAC); - m_assetSeedManager->RemoveSeedAsset(assets[1].ToString(), AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->RemoveSeedAsset(assets[1].ToString(), AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_MAC); const AzFramework::AssetSeedList& seedList = m_assetSeedManager->GetAssetSeedList(); EXPECT_EQ(seedList.size(), 1); - m_assetSeedManager->RemoveSeedAsset("asset1.txt", AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->RemoveSeedAsset("asset1.txt", AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_MAC); const AzFramework::AssetSeedList& secondSeedList = m_assetSeedManager->GetAssetSeedList(); EXPECT_EQ(secondSeedList.size(), 1); } diff --git a/Code/Framework/AzToolsFramework/Tests/PlatformAddressedAssetCatalogTests.cpp b/Code/Framework/AzToolsFramework/Tests/PlatformAddressedAssetCatalogTests.cpp index 4cc98106d6..0b705338d9 100644 --- a/Code/Framework/AzToolsFramework/Tests/PlatformAddressedAssetCatalogTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/PlatformAddressedAssetCatalogTests.cpp @@ -184,13 +184,13 @@ namespace UnitTest TEST_F(PlatformAddressedAssetCatalogManagerTest, PlatformAddressedAssetCatalogManager_CatalogExistsChecks_Success) { - EXPECT_EQ(AzToolsFramework::PlatformAddressedAssetCatalog::CatalogExists(AzFramework::PlatformId::ES3), true); - AZStd::string es3CatalogPath = AzToolsFramework::PlatformAddressedAssetCatalog::GetCatalogRegistryPathForPlatform(AzFramework::PlatformId::ES3); - if (AZ::IO::FileIOBase::GetInstance()->Exists(es3CatalogPath.c_str())) + EXPECT_EQ(AzToolsFramework::PlatformAddressedAssetCatalog::CatalogExists(AzFramework::PlatformId::ANDROID_ID), true); + AZStd::string androidCatalogPath = AzToolsFramework::PlatformAddressedAssetCatalog::GetCatalogRegistryPathForPlatform(AzFramework::PlatformId::ANDROID_ID); + if (AZ::IO::FileIOBase::GetInstance()->Exists(androidCatalogPath.c_str())) { - AZ::IO::FileIOBase::GetInstance()->Remove(es3CatalogPath.c_str()); + AZ::IO::FileIOBase::GetInstance()->Remove(androidCatalogPath.c_str()); } - EXPECT_EQ(AzToolsFramework::PlatformAddressedAssetCatalog::CatalogExists(AzFramework::PlatformId::ES3), false); + EXPECT_EQ(AzToolsFramework::PlatformAddressedAssetCatalog::CatalogExists(AzFramework::PlatformId::ANDROID_ID), false); } class PlatformAddressedAssetCatalogMessageTest : public AzToolsFramework::PlatformAddressedAssetCatalog @@ -251,7 +251,7 @@ namespace UnitTest AzFramework::AssetSystem::NetworkAssetUpdateInterface* notificationInterface = AZ::Interface::Get(); EXPECT_NE(notificationInterface, nullptr); - auto* mockCatalog = new ::testing::NiceMock(AzFramework::PlatformId::ES3); + auto* mockCatalog = new ::testing::NiceMock(AzFramework::PlatformId::ANDROID_ID); AZStd::unique_ptr< ::testing::NiceMock> catalogHolder; catalogHolder.reset(mockCatalog); @@ -259,7 +259,7 @@ namespace UnitTest EXPECT_CALL(*mockCatalog, AssetChanged(testing::_)).Times(0); notificationInterface->AssetChanged(testMessage); - testMessage.m_platform = "es3"; + testMessage.m_platform = "android"; EXPECT_CALL(*mockCatalog, AssetChanged(testing::_)).Times(1); notificationInterface->AssetChanged(testMessage); @@ -270,7 +270,7 @@ namespace UnitTest EXPECT_CALL(*mockCatalog, AssetRemoved(testing::_)).Times(0); notificationInterface->AssetRemoved(testMessage); - testMessage.m_platform = "es3"; + testMessage.m_platform = "android"; EXPECT_CALL(*mockCatalog, AssetRemoved(testing::_)).Times(1); notificationInterface->AssetRemoved(testMessage); } diff --git a/Code/Framework/Tests/PlatformHelper.cpp b/Code/Framework/Tests/PlatformHelper.cpp index 1ad7794c58..9a23fb8d25 100644 --- a/Code/Framework/Tests/PlatformHelper.cpp +++ b/Code/Framework/Tests/PlatformHelper.cpp @@ -30,11 +30,11 @@ TEST_F(PlatformHelperTest, SinglePlatformFlags_PlatformId_Valid) TEST_F(PlatformHelperTest, MultiplePlatformFlags_PlatformId_Valid) { - AzFramework::PlatformFlags platformFlags = AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ES3; + AzFramework::PlatformFlags platformFlags = AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_ANDROID; auto platforms = AzFramework::PlatformHelper::GetPlatforms(platformFlags); EXPECT_EQ(platforms.size(), 2); EXPECT_EQ(platforms[0], "pc"); - EXPECT_EQ(platforms[1], "es3"); + EXPECT_EQ(platforms[1], "android"); } TEST_F(PlatformHelperTest, SpecialAllFlag_PlatformId_Valid) @@ -42,7 +42,7 @@ TEST_F(PlatformHelperTest, SpecialAllFlag_PlatformId_Valid) AzFramework::PlatformFlags platformFlags = AzFramework::PlatformFlags::Platform_ALL; auto platforms = AzFramework::PlatformHelper::GetPlatformsInterpreted(platformFlags); EXPECT_EQ(platforms.size(), AzFramework::NumPlatforms); - EXPECT_THAT(platforms, testing::UnorderedElementsAre("pc", "es3", "ios", "osx_gl", "provo", "salem", "jasper", "server")); + EXPECT_THAT(platforms, testing::UnorderedElementsAre("pc", "android", "ios", "mac", "provo", "salem", "jasper", "server")); } TEST_F(PlatformHelperTest, SpecialAllClientFlag_PlatformId_Valid) @@ -50,7 +50,7 @@ TEST_F(PlatformHelperTest, SpecialAllClientFlag_PlatformId_Valid) AzFramework::PlatformFlags platformFlags = AzFramework::PlatformFlags::Platform_ALL_CLIENT; auto platforms = AzFramework::PlatformHelper::GetPlatformsInterpreted(platformFlags); EXPECT_EQ(platforms.size(), AzFramework::NumClientPlatforms); - EXPECT_THAT(platforms, testing::UnorderedElementsAre("pc", "es3", "ios", "osx_gl", "provo", "salem", "jasper")); + EXPECT_THAT(platforms, testing::UnorderedElementsAre("pc", "android", "ios", "mac", "provo", "salem", "jasper")); } TEST_F(PlatformHelperTest, InvalidPlatformFlags_PlatformId_Empty) diff --git a/Code/Sandbox/Editor/CryEditPy.cpp b/Code/Sandbox/Editor/CryEditPy.cpp index 135dd9878c..edbeccb04f 100644 --- a/Code/Sandbox/Editor/CryEditPy.cpp +++ b/Code/Sandbox/Editor/CryEditPy.cpp @@ -533,7 +533,7 @@ namespace AzToolsFramework ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation); behaviorContext->EnumProperty("SystemConfigPlatform_Pc") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation); - behaviorContext->EnumProperty("SystemConfigPlatform_OsxGl") + behaviorContext->EnumProperty("SystemConfigPlatform_Mac") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation); behaviorContext->EnumProperty("SystemConfigPlatform_OsxMetal") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation); diff --git a/Code/Tools/AssetBundler/tests/AssetProcessorPlatformConfig.setreg b/Code/Tools/AssetBundler/tests/AssetProcessorPlatformConfig.setreg index 81fcdbcf12..ac546d4f39 100644 --- a/Code/Tools/AssetBundler/tests/AssetProcessorPlatformConfig.setreg +++ b/Code/Tools/AssetBundler/tests/AssetProcessorPlatformConfig.setreg @@ -3,7 +3,7 @@ "AssetProcessor": { "Settings": { "Platforms": { - "es3": "enabled" + "android": "enabled" } } } diff --git a/Code/Tools/AssetBundler/tests/applicationManagerTests.cpp b/Code/Tools/AssetBundler/tests/applicationManagerTests.cpp index f2477782d0..be6cf61c29 100644 --- a/Code/Tools/AssetBundler/tests/applicationManagerTests.cpp +++ b/Code/Tools/AssetBundler/tests/applicationManagerTests.cpp @@ -150,7 +150,7 @@ namespace AssetBundler AzFramework::PlatformFlags platformFlags = GetEnabledPlatformFlags(m_data->m_testEngineRoot.c_str(), m_data->m_testEngineRoot.c_str(), DummyProjectName); AzFramework::PlatformFlags hostPlatformFlag = AzFramework::PlatformHelper::GetPlatformFlag(AzToolsFramework::AssetSystem::GetHostAssetPlatform()); - AzFramework::PlatformFlags expectedFlags = AzFramework::PlatformFlags::Platform_ES3 | AzFramework::PlatformFlags::Platform_IOS | AzFramework::PlatformFlags::Platform_PROVO | hostPlatformFlag; + AzFramework::PlatformFlags expectedFlags = AzFramework::PlatformFlags::Platform_ANDROID | AzFramework::PlatformFlags::Platform_IOS | AzFramework::PlatformFlags::Platform_PROVO | hostPlatformFlag; ASSERT_EQ(platformFlags, expectedFlags); } diff --git a/Code/Tools/AssetBundler/tests/tests_main.cpp b/Code/Tools/AssetBundler/tests/tests_main.cpp index 53b19c5eb4..71046a576a 100644 --- a/Code/Tools/AssetBundler/tests/tests_main.cpp +++ b/Code/Tools/AssetBundler/tests/tests_main.cpp @@ -40,14 +40,14 @@ namespace AssetBundler TEST_F(AssetBundlerBatchUtilsTest, SplitFilename_MacFile_OutputBaseNameAndPlatform) { - AZStd::string filePath = "assetInfoFile_osx_gl.xml"; + AZStd::string filePath = "assetInfoFile_mac.xml"; AZStd::string baseFilename; AZStd::string platformIdentifier; AzToolsFramework::SplitFilename(filePath, baseFilename, platformIdentifier); ASSERT_EQ(baseFilename, "assetInfoFile"); - ASSERT_EQ(platformIdentifier, "osx_gl"); + ASSERT_EQ(platformIdentifier, "mac"); } TEST_F(AssetBundlerBatchUtilsTest, SplitFilename_PcFile_OutputBaseNameAndPlatform) @@ -64,14 +64,14 @@ namespace AssetBundler TEST_F(AssetBundlerBatchUtilsTest, SplitFilename_MacFileWithUnderScoreInFileName_OutputBaseNameAndPlatform) { - AZStd::string filePath = "assetInfoFile_test_osx_gl.xml"; + AZStd::string filePath = "assetInfoFile_test_mac.xml"; AZStd::string baseFilename; AZStd::string platformIdentifier; AzToolsFramework::SplitFilename(filePath, baseFilename, platformIdentifier); ASSERT_EQ(baseFilename, "assetInfoFile_test"); - ASSERT_EQ(platformIdentifier, "osx_gl"); + ASSERT_EQ(platformIdentifier, "mac"); } TEST_F(AssetBundlerBatchUtilsTest, SplitFilename_PcFileWithUnderScoreInFileName_OutputBaseNameAndPlatform) diff --git a/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.cpp b/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.cpp index c477ec2c9e..4f8b4b9144 100644 --- a/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.cpp +++ b/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.cpp @@ -78,17 +78,17 @@ namespace AssetBuilderSDK { return AssetBuilderSDK::Platform_PC; } - if (azstricmp(newPlatformName, "es3") == 0) + if (azstricmp(newPlatformName, "android") == 0) { - return AssetBuilderSDK::Platform_ES3; + return AssetBuilderSDK::Platform_ANDROID; } if (azstricmp(newPlatformName, "ios") == 0) { return AssetBuilderSDK::Platform_IOS; } - if (azstricmp(newPlatformName, "osx_gl") == 0) + if (azstricmp(newPlatformName, "mac") == 0) { - return AssetBuilderSDK::Platform_OSX; + return AssetBuilderSDK::Platform_MAC; } if (azstricmp(newPlatformName, "provo") == 0) { @@ -115,12 +115,12 @@ namespace AssetBuilderSDK { case AssetBuilderSDK::Platform_PC: return "pc"; - case AssetBuilderSDK::Platform_ES3: - return "es3"; + case AssetBuilderSDK::Platform_ANDROID: + return "android"; case AssetBuilderSDK::Platform_IOS: return "ios"; - case AssetBuilderSDK::Platform_OSX: - return "osx_gl"; + case AssetBuilderSDK::Platform_MAC: + return "mac"; case AssetBuilderSDK::Platform_PROVO: return "provo"; case AssetBuilderSDK::Platform_SALEM: diff --git a/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.h b/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.h index a11cc9a80d..126ecda2ba 100644 --- a/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.h +++ b/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.h @@ -148,15 +148,15 @@ namespace AssetBuilderSDK { Platform_NONE = 0x00, Platform_PC = 0x01, - Platform_ES3 = 0x02, + Platform_ANDROID = 0x02, Platform_IOS = 0x04, - Platform_OSX = 0x08, + Platform_MAC = 0x08, Platform_PROVO = 0x20, Platform_SALEM = 0x40, Platform_JASPER = 0x80, //! if you add a new platform entry to this enum, you must add it to allplatforms as well otherwise that platform would not be considered valid. - AllPlatforms = Platform_PC | Platform_ES3 | Platform_IOS | Platform_OSX | Platform_PROVO | Platform_SALEM | Platform_JASPER + AllPlatforms = Platform_PC | Platform_ANDROID | Platform_IOS | Platform_MAC | Platform_PROVO | Platform_SALEM | Platform_JASPER }; #endif // defined(ENABLE_LEGACY_PLATFORMFLAGS_SUPPORT) //! Map data structure to holder parameters that are passed into a job for ProcessJob requests. @@ -503,7 +503,7 @@ namespace AssetBuilderSDK AZ_CLASS_ALLOCATOR(PlatformInfo, AZ::SystemAllocator, 0); AZ_TYPE_INFO(PlatformInfo, "{F7DA39A5-C319-4552-954B-3479E2454D3F}"); - AZStd::string m_identifier; ///< like "pc" or "es3" or "ios"... + AZStd::string m_identifier; ///< like "pc" or "android" or "ios"... AZStd::unordered_set m_tags; ///< The tags like "console" or "tools" on that platform PlatformInfo() = default; diff --git a/Code/Tools/AssetProcessor/native/tests/AssetCatalog/AssetCatalogUnitTests.cpp b/Code/Tools/AssetProcessor/native/tests/AssetCatalog/AssetCatalogUnitTests.cpp index 52bedc7744..303f0ad0e8 100644 --- a/Code/Tools/AssetProcessor/native/tests/AssetCatalog/AssetCatalogUnitTests.cpp +++ b/Code/Tools/AssetProcessor/native/tests/AssetCatalog/AssetCatalogUnitTests.cpp @@ -240,7 +240,7 @@ namespace AssetProcessor void BuildConfig(const QDir& tempPath, AssetDatabaseConnection* dbConn, PlatformConfiguration& config) { config.EnablePlatform({ "pc" ,{ "desktop", "renderer" } }, true); - config.EnablePlatform({ "es3" ,{ "mobile", "renderer" } }, true); + config.EnablePlatform({ "android" ,{ "mobile", "renderer" } }, true); config.EnablePlatform({ "fandango" ,{ "console", "renderer" } }, false); AZStd::vector platforms; config.PopulatePlatformsForScanFolder(platforms); @@ -254,22 +254,22 @@ namespace AssetProcessor AssetRecognizer rec; AssetPlatformSpec specpc; - AssetPlatformSpec speces3; + AssetPlatformSpec specandroid; - speces3.m_extraRCParams = "somerandomparam"; + specandroid.m_extraRCParams = "somerandomparam"; rec.m_name = "random files"; rec.m_patternMatcher = AssetBuilderSDK::FilePatternMatcher("*.random", AssetBuilderSDK::AssetBuilderPattern::Wildcard); rec.m_platformSpecs.insert("pc", specpc); config.AddRecognizer(rec); specpc.m_extraRCParams = ""; // blank must work - speces3.m_extraRCParams = "testextraparams"; + specandroid.m_extraRCParams = "testextraparams"; const char* builderTxt1Name = "txt files"; rec.m_name = builderTxt1Name; rec.m_patternMatcher = AssetBuilderSDK::FilePatternMatcher("*.txt", AssetBuilderSDK::AssetBuilderPattern::Wildcard); rec.m_platformSpecs.insert("pc", specpc); - rec.m_platformSpecs.insert("es3", speces3); + rec.m_platformSpecs.insert("android", specandroid); config.AddRecognizer(rec); @@ -280,7 +280,7 @@ namespace AssetProcessor ignore_rec.m_name = "ignore files"; ignore_rec.m_patternMatcher = AssetBuilderSDK::FilePatternMatcher("*.ignore", AssetBuilderSDK::AssetBuilderPattern::Wildcard); ignore_rec.m_platformSpecs.insert("pc", specpc); - ignore_rec.m_platformSpecs.insert("es3", ignore_spec); + ignore_rec.m_platformSpecs.insert("android", ignore_spec); config.AddRecognizer(ignore_rec); ExcludeAssetRecognizer excludeRecogniser; @@ -1092,7 +1092,7 @@ namespace AssetProcessor { AssetCatalogTest::SetUp(); m_platforms.push_back("pc"); - m_platforms.push_back("es3"); + m_platforms.push_back("android"); // 4 products for one platform, 1 product for the other. m_platformToProductsForSourceWithDifferentProducts["pc"].push_back("subfolder3/basefilez.arc2"); @@ -1100,7 +1100,7 @@ namespace AssetProcessor m_platformToProductsForSourceWithDifferentProducts["pc"].push_back("subfolder3/basefile.arc2"); m_platformToProductsForSourceWithDifferentProducts["pc"].push_back("subfolder3/basefile.azm2"); - m_platformToProductsForSourceWithDifferentProducts["es3"].push_back("subfolder3/es3exclusivefile.azm2"); + m_platformToProductsForSourceWithDifferentProducts["android"].push_back("subfolder3/androidexclusivefile.azm2"); m_sourceFileWithDifferentProductsPerPlatform = AZ::Uuid::CreateString("{38032FC9-2838-4D6A-9DA0-79E5E4F20C1B}"); m_sourceFileWithDependency = AZ::Uuid::CreateString("{807C4174-1D19-42AD-B8BC-A59291D9388C}"); @@ -1113,7 +1113,7 @@ namespace AssetProcessor // resulting in image processing jobs having different products per platform. Because of this, the material jobs will then have different // dependencies per platform, because each material will depend on a referenced texture and all of that texture's mipmaps. - // Add a source file with 4 products on pc, but 1 on es3 + // Add a source file with 4 products on pc, but 1 on android bool result = AddSourceAndJobForMultiplePlatforms( "subfolder3", "MultiplatformFile.txt", @@ -1128,7 +1128,7 @@ namespace AssetProcessor result = AddSourceAndJobForMultiplePlatforms("subfolder3", "FileWithDependency.txt", &(m_data->m_dbConn), sourceFileWithSameProductsJobsPerPlatform, m_platforms, m_sourceFileWithDependency); EXPECT_TRUE(result); - const AZStd::string fileWithDependencyProductPath = "subfolder3/es3exclusivefile.azm2"; + const AZStd::string fileWithDependencyProductPath = "subfolder3/androidexclusivefile.azm2"; for (const AZStd::string& platform : m_platforms) { diff --git a/Code/Tools/AssetProcessor/native/tests/assetBuilderSDK/assetBuilderSDKTest.cpp b/Code/Tools/AssetProcessor/native/tests/assetBuilderSDK/assetBuilderSDKTest.cpp index c2931c6a09..671d8d96a9 100644 --- a/Code/Tools/AssetProcessor/native/tests/assetBuilderSDK/assetBuilderSDKTest.cpp +++ b/Code/Tools/AssetProcessor/native/tests/assetBuilderSDK/assetBuilderSDKTest.cpp @@ -28,7 +28,7 @@ namespace AssetProcessor createJobsRequest.m_enabledPlatforms = { { "pc", {} - }, { "es3", {} + }, { "android", {} } }; ASSERT_EQ(createJobsRequest.GetEnabledPlatformsCount(), 2); @@ -48,19 +48,19 @@ namespace AssetProcessor ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(1), AssetBuilderSDK::Platform_NONE); createJobsRequest.m_enabledPlatforms = { - { "es3", {} + { "android", {} } }; - ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(0), AssetBuilderSDK::Platform_ES3); + ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(0), AssetBuilderSDK::Platform_ANDROID); ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(1), AssetBuilderSDK::Platform_NONE); createJobsRequest.m_enabledPlatforms = { { "pc", {} - }, { "es3", {} + }, { "android", {} } }; ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(0), AssetBuilderSDK::Platform_PC); - ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(1), AssetBuilderSDK::Platform_ES3); + ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(1), AssetBuilderSDK::Platform_ANDROID); ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(2), AssetBuilderSDK::Platform_NONE); createJobsRequest.m_enabledPlatforms = { @@ -72,24 +72,24 @@ namespace AssetProcessor createJobsRequest.m_enabledPlatforms = { { "pc", {} - }, { "es3", {} + }, { "android", {} }, { "ios", {} - }, { "osx_gl", {} + }, { "mac", {} } }; ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(0), AssetBuilderSDK::Platform_PC); - ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(1), AssetBuilderSDK::Platform_ES3); + ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(1), AssetBuilderSDK::Platform_ANDROID); ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(2), AssetBuilderSDK::Platform_IOS); - ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(3), AssetBuilderSDK::Platform_OSX); + ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(3), AssetBuilderSDK::Platform_MAC); ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(4), AssetBuilderSDK::Platform_NONE); createJobsRequest.m_enabledPlatforms = { { "pc", {} - }, { "es3", {} + }, { "android", {} } }; ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(0), AssetBuilderSDK::Platform_PC); - ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(1), AssetBuilderSDK::Platform_ES3); + ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(1), AssetBuilderSDK::Platform_ANDROID); ASSERT_EQ(createJobsRequest.GetEnabledPlatformAt(2), AssetBuilderSDK::Platform_NONE); // using a deprecated API should have generated warnings. // but we can't test for it because these warnings are WarningOnce and some other unit test might have already triggered it @@ -106,23 +106,23 @@ namespace AssetProcessor } }; ASSERT_TRUE(createJobsRequest.IsPlatformEnabled(AssetBuilderSDK::Platform_PC)); - ASSERT_FALSE(createJobsRequest.IsPlatformEnabled(AssetBuilderSDK::Platform_ES3)); + ASSERT_FALSE(createJobsRequest.IsPlatformEnabled(AssetBuilderSDK::Platform_ANDROID)); createJobsRequest.m_enabledPlatforms = { { "pc", {} - }, { "es3", {} + }, { "android", {} } }; ASSERT_TRUE(createJobsRequest.IsPlatformEnabled(AssetBuilderSDK::Platform_PC)); - ASSERT_TRUE(createJobsRequest.IsPlatformEnabled(AssetBuilderSDK::Platform_ES3)); + ASSERT_TRUE(createJobsRequest.IsPlatformEnabled(AssetBuilderSDK::Platform_ANDROID)); createJobsRequest.m_enabledPlatforms = { { "pc", {} - }, { "es3", {} + }, { "android", {} } }; ASSERT_TRUE(createJobsRequest.IsPlatformEnabled(AssetBuilderSDK::Platform_PC)); - ASSERT_TRUE(createJobsRequest.IsPlatformEnabled(AssetBuilderSDK::Platform_ES3)); + ASSERT_TRUE(createJobsRequest.IsPlatformEnabled(AssetBuilderSDK::Platform_ANDROID)); // using a deprecated API should have generated warnings. // but we can't test for it because these warnings are WarningOnce and some other unit test might have already triggered it } @@ -133,9 +133,9 @@ namespace AssetProcessor UnitTestUtils::AssertAbsorber absorb; ASSERT_TRUE(createJobsRequest.IsPlatformValid(AssetBuilderSDK::Platform_PC)); - ASSERT_TRUE(createJobsRequest.IsPlatformValid(AssetBuilderSDK::Platform_ES3)); + ASSERT_TRUE(createJobsRequest.IsPlatformValid(AssetBuilderSDK::Platform_ANDROID)); ASSERT_TRUE(createJobsRequest.IsPlatformValid(AssetBuilderSDK::Platform_IOS)); - ASSERT_TRUE(createJobsRequest.IsPlatformValid(AssetBuilderSDK::Platform_OSX)); + ASSERT_TRUE(createJobsRequest.IsPlatformValid(AssetBuilderSDK::Platform_MAC)); ASSERT_TRUE(createJobsRequest.IsPlatformValid(AssetBuilderSDK::Platform_PROVO)); ASSERT_TRUE(createJobsRequest.IsPlatformValid(AssetBuilderSDK::Platform_SALEM)); ASSERT_TRUE(createJobsRequest.IsPlatformValid(AssetBuilderSDK::Platform_JASPER)); diff --git a/Code/Tools/AssetProcessor/native/tests/assetmanager/AssetProcessorManagerTest.cpp b/Code/Tools/AssetProcessor/native/tests/assetmanager/AssetProcessorManagerTest.cpp index d592ecb012..bd99cf7a94 100644 --- a/Code/Tools/AssetProcessor/native/tests/assetmanager/AssetProcessorManagerTest.cpp +++ b/Code/Tools/AssetProcessor/native/tests/assetmanager/AssetProcessorManagerTest.cpp @@ -4020,15 +4020,15 @@ TEST_F(ModtimeScanningTest, ModtimeSkipping_EnablePlatform_ShouldProcessFilesFor m_assetProcessorManager->m_allowModtimeSkippingFeature = true; AssetUtilities::SetUseFileHashOverride(true, true); - // Enable es3 platform after the initial SetUp has already processed the files for pc + // Enable android platform after the initial SetUp has already processed the files for pc QDir tempPath(m_tempDir.path()); - AssetBuilderSDK::PlatformInfo es3Platform("es3", { "host", "renderer" }); - m_config->EnablePlatform(es3Platform, true); + AssetBuilderSDK::PlatformInfo androidPlatform("android", { "host", "renderer" }); + m_config->EnablePlatform(androidPlatform, true); // There's no way to remove scanfolders and adding a new one after enabling the platform will cause the pc assets to build as well, which we don't want // Instead we'll just const cast the vector and modify the enabled platforms for the scanfolder auto& platforms = const_cast&>(m_config->GetScanFolderAt(0).GetPlatforms()); - platforms.push_back(es3Platform); + platforms.push_back(androidPlatform); // We need the builder fingerprints to be updated to reflect the newly enabled platform m_assetProcessorManager->ComputeBuilderDirty(); @@ -4036,10 +4036,10 @@ TEST_F(ModtimeScanningTest, ModtimeSkipping_EnablePlatform_ShouldProcessFilesFor QSet filePaths = BuildFileSet(); SimulateAssetScanner(filePaths); - ExpectWork(4, 2); // CreateJobs = 4, 2 files * 2 platforms. ProcessJobs = 2, just the es3 platform jobs (pc is already processed) + ExpectWork(4, 2); // CreateJobs = 4, 2 files * 2 platforms. ProcessJobs = 2, just the android platform jobs (pc is already processed) - ASSERT_TRUE(m_data->m_processResults[0].m_destinationPath.contains("es3")); - ASSERT_TRUE(m_data->m_processResults[1].m_destinationPath.contains("es3")); + ASSERT_TRUE(m_data->m_processResults[0].m_destinationPath.contains("android")); + ASSERT_TRUE(m_data->m_processResults[1].m_destinationPath.contains("android")); } TEST_F(ModtimeScanningTest, ModtimeSkipping_ModifyTimestamp) diff --git a/Code/Tools/AssetProcessor/native/tests/platformconfiguration/platformconfigurationtests.cpp b/Code/Tools/AssetProcessor/native/tests/platformconfiguration/platformconfigurationtests.cpp index 829d63472d..9c80b267eb 100644 --- a/Code/Tools/AssetProcessor/native/tests/platformconfiguration/platformconfigurationtests.cpp +++ b/Code/Tools/AssetProcessor/native/tests/platformconfiguration/platformconfigurationtests.cpp @@ -120,14 +120,14 @@ TEST_F(PlatformConfigurationUnitTests, TestFailReadConfigFile_Regular_Platforms) // verify the data. ASSERT_NE(config.GetPlatformByIdentifier(AzToolsFramework::AssetSystem::GetHostAssetPlatform()), nullptr); - ASSERT_NE(config.GetPlatformByIdentifier("es3"), nullptr); + ASSERT_NE(config.GetPlatformByIdentifier("android"), nullptr); ASSERT_NE(config.GetPlatformByIdentifier("server"), nullptr); - ASSERT_TRUE(config.GetPlatformByIdentifier("es3")->HasTag("mobile")); - ASSERT_TRUE(config.GetPlatformByIdentifier("es3")->HasTag("renderer")); - ASSERT_TRUE(config.GetPlatformByIdentifier("es3")->HasTag("android")); + ASSERT_TRUE(config.GetPlatformByIdentifier("android")->HasTag("mobile")); + ASSERT_TRUE(config.GetPlatformByIdentifier("android")->HasTag("renderer")); + ASSERT_TRUE(config.GetPlatformByIdentifier("android")->HasTag("android")); ASSERT_TRUE(config.GetPlatformByIdentifier("server")->HasTag("server")); - ASSERT_FALSE(config.GetPlatformByIdentifier("es3")->HasTag("server")); + ASSERT_FALSE(config.GetPlatformByIdentifier("android")->HasTag("server")); ASSERT_FALSE(config.GetPlatformByIdentifier("server")->HasTag("renderer")); } @@ -397,7 +397,7 @@ TEST_F(PlatformConfigurationUnitTests, TestFailReadConfigFile_RegularScanfolderP AZStd::vector platforms = config.GetScanFolderAt(0).GetPlatforms(); ASSERT_EQ(platforms.size(), 4); ASSERT_TRUE(AZStd::find(platforms.begin(), platforms.end(), AssetBuilderSDK::PlatformInfo(AzToolsFramework::AssetSystem::GetHostAssetPlatform(), AZStd::unordered_set{})) != platforms.end()); - ASSERT_TRUE(AZStd::find(platforms.begin(), platforms.end(), AssetBuilderSDK::PlatformInfo("es3", AZStd::unordered_set{})) != platforms.end()); + ASSERT_TRUE(AZStd::find(platforms.begin(), platforms.end(), AssetBuilderSDK::PlatformInfo("android", AZStd::unordered_set{})) != platforms.end()); ASSERT_TRUE(AZStd::find(platforms.begin(), platforms.end(), AssetBuilderSDK::PlatformInfo("ios", AZStd::unordered_set{})) != platforms.end()); ASSERT_TRUE(AZStd::find(platforms.begin(), platforms.end(), AssetBuilderSDK::PlatformInfo("server", AZStd::unordered_set{})) != platforms.end()); @@ -405,12 +405,12 @@ TEST_F(PlatformConfigurationUnitTests, TestFailReadConfigFile_RegularScanfolderP platforms = config.GetScanFolderAt(1).GetPlatforms(); ASSERT_EQ(platforms.size(), 2); ASSERT_TRUE(AZStd::find(platforms.begin(), platforms.end(), AssetBuilderSDK::PlatformInfo(AzToolsFramework::AssetSystem::GetHostAssetPlatform(), AZStd::unordered_set{})) != platforms.end()); - ASSERT_TRUE(AZStd::find(platforms.begin(), platforms.end(), AssetBuilderSDK::PlatformInfo("es3", AZStd::unordered_set{})) != platforms.end()); + ASSERT_TRUE(AZStd::find(platforms.begin(), platforms.end(), AssetBuilderSDK::PlatformInfo("android", AZStd::unordered_set{})) != platforms.end()); ASSERT_EQ(config.GetScanFolderAt(2).GetDisplayName(), QString("folder1output")); platforms = config.GetScanFolderAt(2).GetPlatforms(); ASSERT_EQ(platforms.size(), 1); - ASSERT_TRUE(AZStd::find(platforms.begin(), platforms.end(), AssetBuilderSDK::PlatformInfo("es3", AZStd::unordered_set{})) != platforms.end()); + ASSERT_TRUE(AZStd::find(platforms.begin(), platforms.end(), AssetBuilderSDK::PlatformInfo("android", AZStd::unordered_set{})) != platforms.end()); ASSERT_EQ(config.GetScanFolderAt(3).GetDisplayName(), QString("folder2output")); platforms = config.GetScanFolderAt(3).GetPlatforms(); @@ -454,7 +454,7 @@ TEST_F(PlatformConfigurationUnitTests, TestFailReadConfigFile_Recognizers) using namespace AzToolsFramework::AssetSystem; using namespace AssetProcessor; #if defined(AZ_PLATFORM_WINDOWS) - const char* platformWhichIsNotCurrentPlatform = "osx_gl"; + const char* platformWhichIsNotCurrentPlatform = "mac"; #else const char* platformWhichIsNotCurrentPlatform = "pc"; #endif @@ -475,27 +475,27 @@ TEST_F(PlatformConfigurationUnitTests, TestFailReadConfigFile_Recognizers) ASSERT_EQ(recogs["i_caf"].m_patternMatcher.GetBuilderPattern().m_pattern, "*.i_caf"); ASSERT_EQ(recogs["i_caf"].m_patternMatcher.GetBuilderPattern().m_type, AssetBuilderSDK::AssetBuilderPattern::Wildcard); ASSERT_EQ(recogs["i_caf"].m_platformSpecs.size(), 2); - ASSERT_TRUE(recogs["i_caf"].m_platformSpecs.contains("es3")); + ASSERT_TRUE(recogs["i_caf"].m_platformSpecs.contains("android")); ASSERT_TRUE(recogs["i_caf"].m_platformSpecs.contains(AzToolsFramework::AssetSystem::GetHostAssetPlatform())); ASSERT_FALSE(recogs["i_caf"].m_platformSpecs.contains("server")); // server has been set to skip. - ASSERT_EQ(recogs["i_caf"].m_platformSpecs["es3"].m_extraRCParams, "mobile"); + ASSERT_EQ(recogs["i_caf"].m_platformSpecs["android"].m_extraRCParams, "mobile"); ASSERT_EQ(recogs["i_caf"].m_platformSpecs[AzToolsFramework::AssetSystem::GetHostAssetPlatform()].m_extraRCParams, "defaultparams"); ASSERT_TRUE(recogs.contains("caf")); - ASSERT_TRUE(recogs["caf"].m_platformSpecs.contains("es3")); + ASSERT_TRUE(recogs["caf"].m_platformSpecs.contains("android")); ASSERT_TRUE(recogs["caf"].m_platformSpecs.contains("server")); ASSERT_TRUE(recogs["caf"].m_platformSpecs.contains(AzToolsFramework::AssetSystem::GetHostAssetPlatform())); ASSERT_EQ(recogs["caf"].m_platformSpecs.size(), 3); - ASSERT_EQ(recogs["caf"].m_platformSpecs["es3"].m_extraRCParams, "rendererparams"); + ASSERT_EQ(recogs["caf"].m_platformSpecs["android"].m_extraRCParams, "rendererparams"); ASSERT_EQ(recogs["caf"].m_platformSpecs[AzToolsFramework::AssetSystem::GetHostAssetPlatform()].m_extraRCParams, "rendererparams"); ASSERT_EQ(recogs["caf"].m_platformSpecs["server"].m_extraRCParams, "copy"); ASSERT_TRUE(recogs.contains("mov")); - ASSERT_TRUE(recogs["mov"].m_platformSpecs.contains("es3")); + ASSERT_TRUE(recogs["mov"].m_platformSpecs.contains("android")); ASSERT_TRUE(recogs["mov"].m_platformSpecs.contains("server")); ASSERT_TRUE(recogs["mov"].m_platformSpecs.contains(AzToolsFramework::AssetSystem::GetHostAssetPlatform())); ASSERT_EQ(recogs["mov"].m_platformSpecs.size(), 3); - ASSERT_EQ(recogs["mov"].m_platformSpecs["es3"].m_extraRCParams, "platformspecificoverride"); + ASSERT_EQ(recogs["mov"].m_platformSpecs["android"].m_extraRCParams, "platformspecificoverride"); ASSERT_EQ(recogs["mov"].m_platformSpecs[AzToolsFramework::AssetSystem::GetHostAssetPlatform()].m_extraRCParams, "rendererparams"); ASSERT_EQ(recogs["mov"].m_platformSpecs["server"].m_extraRCParams, "copy"); @@ -503,27 +503,27 @@ TEST_F(PlatformConfigurationUnitTests, TestFailReadConfigFile_Recognizers) // (but platforms can override it) ASSERT_TRUE(recogs.contains("rend")); ASSERT_TRUE(recogs["rend"].m_platformSpecs.contains(AzToolsFramework::AssetSystem::GetHostAssetPlatform())); - ASSERT_TRUE(recogs["rend"].m_platformSpecs.contains("es3")); + ASSERT_TRUE(recogs["rend"].m_platformSpecs.contains("android")); ASSERT_TRUE(recogs["rend"].m_platformSpecs.contains("server")); ASSERT_FALSE(recogs["rend"].m_platformSpecs.contains(platformWhichIsNotCurrentPlatform)); // this is not an enabled platform and should not be there. ASSERT_EQ(recogs["rend"].m_platformSpecs.size(), 3); ASSERT_EQ(recogs["rend"].m_platformSpecs[AzToolsFramework::AssetSystem::GetHostAssetPlatform()].m_extraRCParams, "rendererparams"); - ASSERT_EQ(recogs["rend"].m_platformSpecs["es3"].m_extraRCParams, "rendererparams"); + ASSERT_EQ(recogs["rend"].m_platformSpecs["android"].m_extraRCParams, "rendererparams"); ASSERT_EQ(recogs["rend"].m_platformSpecs["server"].m_extraRCParams, ""); // default if not specified is empty string ASSERT_TRUE(recogs.contains("alldefault")); ASSERT_TRUE(recogs["alldefault"].m_platformSpecs.contains(AzToolsFramework::AssetSystem::GetHostAssetPlatform())); - ASSERT_TRUE(recogs["alldefault"].m_platformSpecs.contains("es3")); + ASSERT_TRUE(recogs["alldefault"].m_platformSpecs.contains("android")); ASSERT_TRUE(recogs["alldefault"].m_platformSpecs.contains("server")); ASSERT_FALSE(recogs["alldefault"].m_platformSpecs.contains(platformWhichIsNotCurrentPlatform)); // this is not an enabled platform and should not be there. ASSERT_EQ(recogs["alldefault"].m_platformSpecs.size(), 3); ASSERT_EQ(recogs["alldefault"].m_platformSpecs[AzToolsFramework::AssetSystem::GetHostAssetPlatform()].m_extraRCParams, ""); - ASSERT_EQ(recogs["alldefault"].m_platformSpecs["es3"].m_extraRCParams, ""); + ASSERT_EQ(recogs["alldefault"].m_platformSpecs["android"].m_extraRCParams, ""); ASSERT_EQ(recogs["alldefault"].m_platformSpecs["server"].m_extraRCParams, ""); ASSERT_TRUE(recogs.contains("skipallbutone")); ASSERT_FALSE(recogs["skipallbutone"].m_platformSpecs.contains(AzToolsFramework::AssetSystem::GetHostAssetPlatform())); - ASSERT_FALSE(recogs["skipallbutone"].m_platformSpecs.contains("es3")); + ASSERT_FALSE(recogs["skipallbutone"].m_platformSpecs.contains("android")); ASSERT_TRUE(recogs["skipallbutone"].m_platformSpecs.contains("server")); // server is only one enabled (set to copy) ASSERT_EQ(recogs["skipallbutone"].m_platformSpecs.size(), 1); ASSERT_EQ(recogs["skipallbutone"].m_platformSpecs["server"].m_extraRCParams, "copy"); @@ -549,7 +549,7 @@ TEST_F(PlatformConfigurationUnitTests, TestFailReadConfigFile_Overrides) // verify the data. ASSERT_NE(config.GetPlatformByIdentifier(AzToolsFramework::AssetSystem::GetHostAssetPlatform()), nullptr); - ASSERT_NE(config.GetPlatformByIdentifier("es3"), nullptr); + ASSERT_NE(config.GetPlatformByIdentifier("android"), nullptr); ASSERT_NE(config.GetPlatformByIdentifier("provo"), nullptr); // this override swaps server with provo in that it turns ON provo, turns off server ASSERT_EQ(config.GetPlatformByIdentifier("server"), nullptr); // this should be off due to overrides @@ -566,11 +566,11 @@ TEST_F(PlatformConfigurationUnitTests, TestFailReadConfigFile_Overrides) ASSERT_EQ(recogs["i_caf"].m_patternMatcher.GetBuilderPattern().m_pattern, "*.i_caf"); ASSERT_EQ(recogs["i_caf"].m_patternMatcher.GetBuilderPattern().m_type, AssetBuilderSDK::AssetBuilderPattern::Wildcard); ASSERT_EQ(recogs["i_caf"].m_platformSpecs.size(), 3); - ASSERT_TRUE(recogs["i_caf"].m_platformSpecs.contains("es3")); + ASSERT_TRUE(recogs["i_caf"].m_platformSpecs.contains("android")); ASSERT_TRUE(recogs["i_caf"].m_platformSpecs.contains("provo")); ASSERT_TRUE(recogs["i_caf"].m_platformSpecs.contains(AzToolsFramework::AssetSystem::GetHostAssetPlatform())); ASSERT_FALSE(recogs["i_caf"].m_platformSpecs.contains("server")); // server has been set to skip. - ASSERT_EQ(recogs["i_caf"].m_platformSpecs["es3"].m_extraRCParams, "mobile"); + ASSERT_EQ(recogs["i_caf"].m_platformSpecs["android"].m_extraRCParams, "mobile"); ASSERT_EQ(recogs["i_caf"].m_platformSpecs[AzToolsFramework::AssetSystem::GetHostAssetPlatform()].m_extraRCParams, "defaultparams"); ASSERT_EQ(recogs["i_caf"].m_platformSpecs["provo"].m_extraRCParams, "copy"); diff --git a/Code/Tools/AssetProcessor/native/unittests/AssetProcessorManagerUnitTests.cpp b/Code/Tools/AssetProcessor/native/unittests/AssetProcessorManagerUnitTests.cpp index c632dc8a7a..079cdb7c66 100644 --- a/Code/Tools/AssetProcessor/native/unittests/AssetProcessorManagerUnitTests.cpp +++ b/Code/Tools/AssetProcessor/native/unittests/AssetProcessorManagerUnitTests.cpp @@ -90,34 +90,34 @@ namespace AssetProcessor //AZ_TracePrintf("test", "-------------------------\n"); } - void ComputeFingerprints(unsigned int& fingerprintForPC, unsigned int& fingerprintForES3, PlatformConfiguration& config, QString scanFolderPath, QString relPath) + void ComputeFingerprints(unsigned int& fingerprintForPC, unsigned int& fingerprintForANDROID, PlatformConfiguration& config, QString scanFolderPath, QString relPath) { QString extraInfoForPC; - QString extraInfoForES3; + QString extraInfoForANDROID; RecognizerPointerContainer output; QString filePath = scanFolderPath + "/" + relPath; config.GetMatchingRecognizers(filePath, output); for (const AssetRecognizer* assetRecogniser : output) { extraInfoForPC.append(assetRecogniser->m_platformSpecs["pc"].m_extraRCParams); - extraInfoForES3.append(assetRecogniser->m_platformSpecs["es3"].m_extraRCParams); + extraInfoForANDROID.append(assetRecogniser->m_platformSpecs["android"].m_extraRCParams); extraInfoForPC.append(assetRecogniser->m_version); - extraInfoForES3.append(assetRecogniser->m_version); + extraInfoForANDROID.append(assetRecogniser->m_version); } - //Calculating fingerprints for the file for pc and es3 platforms + //Calculating fingerprints for the file for pc and android platforms AZ::Uuid sourceId = AZ::Uuid("{2206A6E0-FDBC-45DE-B6FE-C2FC63020BD5}"); JobEntry jobEntryPC(scanFolderPath, relPath, relPath, 0, { "pc", {"desktop", "renderer"} }, "", 0, 1, sourceId); - JobEntry jobEntryES3(scanFolderPath, relPath, relPath, 0, { "es3", {"mobile", "renderer"} }, "", 0, 2, sourceId); + JobEntry jobEntryANDROID(scanFolderPath, relPath, relPath, 0, { "android", {"mobile", "renderer"} }, "", 0, 2, sourceId); JobDetails jobDetailsPC; jobDetailsPC.m_extraInformationForFingerprinting = extraInfoForPC.toUtf8().constData(); jobDetailsPC.m_jobEntry = jobEntryPC; - JobDetails jobDetailsES3; - jobDetailsES3.m_extraInformationForFingerprinting = extraInfoForES3.toUtf8().constData(); - jobDetailsES3.m_jobEntry = jobEntryES3; + JobDetails jobDetailsANDROID; + jobDetailsANDROID.m_extraInformationForFingerprinting = extraInfoForANDROID.toUtf8().constData(); + jobDetailsANDROID.m_jobEntry = jobEntryANDROID; fingerprintForPC = AssetUtilities::GenerateFingerprint(jobDetailsPC); - fingerprintForES3 = AssetUtilities::GenerateFingerprint(jobDetailsES3); + fingerprintForANDROID = AssetUtilities::GenerateFingerprint(jobDetailsANDROID); } } @@ -242,7 +242,7 @@ namespace AssetProcessor PlatformConfiguration config; config.EnablePlatform({ "pc",{ "desktop", "renderer" } }, true); - config.EnablePlatform({ "es3",{ "mobile", "renderer" } }, true); + config.EnablePlatform({ "android",{ "mobile", "renderer" } }, true); config.EnablePlatform({ "fandago",{ "console", "renderer" } }, false); AZStd::vector platforms; config.PopulatePlatformsForScanFolder(platforms); @@ -261,9 +261,9 @@ namespace AssetProcessor AssetRecognizer rec; AssetPlatformSpec specpc; - AssetPlatformSpec speces3; + AssetPlatformSpec specandroid; - speces3.m_extraRCParams = "somerandomparam"; + specandroid.m_extraRCParams = "somerandomparam"; rec.m_name = "random files"; rec.m_patternMatcher = AssetBuilderSDK::FilePatternMatcher("*.random", AssetBuilderSDK::AssetBuilderPattern::Wildcard); rec.m_platformSpecs.insert("pc", specpc); @@ -271,13 +271,13 @@ namespace AssetProcessor UNIT_TEST_EXPECT_TRUE(mockAppManager.RegisterAssetRecognizerAsBuilder(rec)); specpc.m_extraRCParams = ""; // blank must work - speces3.m_extraRCParams = "testextraparams"; + specandroid.m_extraRCParams = "testextraparams"; const char* builderTxt1Name = "txt files"; rec.m_name = builderTxt1Name; rec.m_patternMatcher = AssetBuilderSDK::FilePatternMatcher("*.txt", AssetBuilderSDK::AssetBuilderPattern::Wildcard); rec.m_platformSpecs.insert("pc", specpc); - rec.m_platformSpecs.insert("es3", speces3); + rec.m_platformSpecs.insert("android", specandroid); config.AddRecognizer(rec); @@ -307,21 +307,21 @@ namespace AssetProcessor rec.m_testLockSource = false; specpc.m_extraRCParams = "pcparams"; - speces3.m_extraRCParams = "es3params"; + specandroid.m_extraRCParams = "androidparams"; rec.m_name = "xxx files"; rec.m_patternMatcher = AssetBuilderSDK::FilePatternMatcher("*.xxx", AssetBuilderSDK::AssetBuilderPattern::Wildcard); rec.m_platformSpecs.insert("pc", specpc); - rec.m_platformSpecs.insert("es3", speces3); + rec.m_platformSpecs.insert("android", specandroid); config.AddRecognizer(rec); mockAppManager.RegisterAssetRecognizerAsBuilder(rec); // two recognizers for the same pattern. rec.m_name = "xxx files 2 (builder2)"; specpc.m_extraRCParams = "pcparams2"; - speces3.m_extraRCParams = "es3params2"; + specandroid.m_extraRCParams = "androidparams2"; rec.m_platformSpecs.insert("pc", specpc); - rec.m_platformSpecs.insert("es3", speces3); + rec.m_platformSpecs.insert("android", specandroid); config.AddRecognizer(rec); mockAppManager.RegisterAssetRecognizerAsBuilder(rec); @@ -332,7 +332,7 @@ namespace AssetProcessor ignore_rec.m_name = "ignore files"; ignore_rec.m_patternMatcher = AssetBuilderSDK::FilePatternMatcher("*.ignore", AssetBuilderSDK::AssetBuilderPattern::Wildcard); ignore_rec.m_platformSpecs.insert("pc", specpc); - ignore_rec.m_platformSpecs.insert("es3", ignore_spec); + ignore_rec.m_platformSpecs.insert("android", ignore_spec); config.AddRecognizer(ignore_rec); mockAppManager.RegisterAssetRecognizerAsBuilder(ignore_rec); @@ -434,7 +434,7 @@ namespace AssetProcessor sortAssetToProcessResultList(processResults); - UNIT_TEST_EXPECT_TRUE(processResults.size() == 1); // 1, since we have one recognizer for .ignore, but the 'es3' platform is marked as skip + UNIT_TEST_EXPECT_TRUE(processResults.size() == 1); // 1, since we have one recognizer for .ignore, but the 'android' platform is marked as skip UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "pc")); @@ -457,16 +457,16 @@ namespace AssetProcessor sortAssetToProcessResultList(processResults); - UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and es3,since we have two recognizer for .txt file + UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and android,since we have two recognizer for .txt file UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == processResults[1].m_jobEntry.m_platformInfo.m_identifier); UNIT_TEST_EXPECT_TRUE(processResults[2].m_jobEntry.m_platformInfo.m_identifier == processResults[3].m_jobEntry.m_platformInfo.m_identifier); - UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3")); - UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "es3")); + UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android")); + UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "android")); UNIT_TEST_EXPECT_TRUE((processResults[2].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE((processResults[3].m_jobEntry.m_platformInfo.m_identifier == "pc")); - QList es3JobsIndex; + QList androidJobsIndex; QList pcJobsIndex; for (int checkIdx = 0; checkIdx < 4; ++checkIdx) { @@ -664,19 +664,19 @@ namespace AssetProcessor // ---------- test successes ---------- - QStringList es3outs; - es3outs.push_back(cacheRoot.filePath(QString("es3/basefile.arc1"))); - es3outs.push_back(cacheRoot.filePath(QString("es3/basefile.arc2"))); + QStringList androidouts; + androidouts.push_back(cacheRoot.filePath(QString("android/basefile.arc1"))); + androidouts.push_back(cacheRoot.filePath(QString("android/basefile.arc2"))); // feed it the messages its waiting for (create the files) - UNIT_TEST_EXPECT_TRUE(CreateDummyFile(es3outs[0], "products.")); - UNIT_TEST_EXPECT_TRUE(CreateDummyFile(es3outs[1], "products.")) + UNIT_TEST_EXPECT_TRUE(CreateDummyFile(androidouts[0], "products.")); + UNIT_TEST_EXPECT_TRUE(CreateDummyFile(androidouts[1], "products.")) - //Invoke Asset Processed for es3 platform , txt files job description + //Invoke Asset Processed for android platform , txt files job description AssetBuilderSDK::ProcessJobResponse response; response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs[0].toUtf8().constData(), AZ::Uuid::CreateNull(), 1)); - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs[1].toUtf8().constData(), AZ::Uuid::CreateNull(), 2)); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts[0].toUtf8().constData(), AZ::Uuid::CreateNull(), 1)); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts[1].toUtf8().constData(), AZ::Uuid::CreateNull(), 2)); // make sure legacy SubIds get stored in the DB and in asset response messages. // also make sure they don't get filed for the wrong asset. @@ -695,8 +695,8 @@ namespace AssetProcessor UNIT_TEST_EXPECT_TRUE(changedInputResults.size() == 1); // always RELATIVE, always with the product name. - UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_platform == "es3"); - UNIT_TEST_EXPECT_TRUE(assetMessages[1].m_platform == "es3"); + UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_platform == "android"); + UNIT_TEST_EXPECT_TRUE(assetMessages[1].m_platform == "android"); UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_data == "basefile.arc1"); UNIT_TEST_EXPECT_TRUE(assetMessages[1].m_data == "basefile.arc2"); UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_type == AzFramework::AssetSystem::AssetNotificationMessage::AssetChanged); @@ -795,14 +795,14 @@ namespace AssetProcessor changedInputResults.clear(); assetMessages.clear(); - es3outs.clear(); - es3outs.push_back(cacheRoot.filePath(QString("es3/basefile.azm"))); - UNIT_TEST_EXPECT_TRUE(CreateDummyFile(es3outs[0], "products.")); + androidouts.clear(); + androidouts.push_back(cacheRoot.filePath(QString("android/basefile.azm"))); + UNIT_TEST_EXPECT_TRUE(CreateDummyFile(androidouts[0], "products.")); - //Invoke Asset Processed for es3 platform , txt files2 job description + //Invoke Asset Processed for android platform , txt files2 job description response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs[0].toUtf8().constData())); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts[0].toUtf8().constData())); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[1].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); @@ -814,7 +814,7 @@ namespace AssetProcessor UNIT_TEST_EXPECT_TRUE(changedInputResults.size() == 1); // always RELATIVE, always with the product name. - UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_platform == "es3"); + UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_platform == "android"); UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_data == "basefile.azm"); changedInputResults.clear(); @@ -1004,11 +1004,11 @@ namespace AssetProcessor sortAssetToProcessResultList(processResults); // --------- same result as above ---------- - UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and es3,since we have two recognizer for .txt file + UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and android,since we have two recognizer for .txt file UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == processResults[1].m_jobEntry.m_platformInfo.m_identifier); UNIT_TEST_EXPECT_TRUE(processResults[2].m_jobEntry.m_platformInfo.m_identifier == processResults[3].m_jobEntry.m_platformInfo.m_identifier); - UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3")); - UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "es3")); + UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android")); + UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "android")); UNIT_TEST_EXPECT_TRUE((processResults[2].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE((processResults[3].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_computedFingerprint != 0); @@ -1027,25 +1027,25 @@ namespace AssetProcessor // this time make different products: - QStringList oldes3outs; + QStringList oldandroidouts; QStringList oldpcouts; - oldes3outs = es3outs; + oldandroidouts = androidouts; oldpcouts.append(pcouts); - QStringList es3outs2; + QStringList androidouts2; QStringList pcouts2; - es3outs.clear(); + androidouts.clear(); pcouts.clear(); - es3outs.push_back(cacheRoot.filePath(QString("es3/basefilea.arc1"))); - es3outs2.push_back(cacheRoot.filePath(QString("es3/basefilea.azm"))); - // note that the ES3 outs have changed + androidouts.push_back(cacheRoot.filePath(QString("android/basefilea.arc1"))); + androidouts2.push_back(cacheRoot.filePath(QString("android/basefilea.azm"))); + // note that the android outs have changed // but the pc outs are still the same. pcouts.push_back(cacheRoot.filePath(QString("pc/basefile.arc1"))); pcouts2.push_back(cacheRoot.filePath(QString("pc/basefile.azm"))); // feed it the messages its waiting for (create the files) - UNIT_TEST_EXPECT_TRUE(CreateDummyFile(es3outs[0], "newfile.")); + UNIT_TEST_EXPECT_TRUE(CreateDummyFile(androidouts[0], "newfile.")); UNIT_TEST_EXPECT_TRUE(CreateDummyFile(pcouts[0], "newfile.")); - UNIT_TEST_EXPECT_TRUE(CreateDummyFile(es3outs2[0], "newfile.")); + UNIT_TEST_EXPECT_TRUE(CreateDummyFile(androidouts2[0], "newfile.")); UNIT_TEST_EXPECT_TRUE(CreateDummyFile(pcouts2[0], "newfile.")); QCoreApplication::processEvents(QEventLoop::AllEvents | QEventLoop::WaitForMoreEvents, 50); @@ -1057,12 +1057,12 @@ namespace AssetProcessor response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs[0].toUtf8().constData())); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts[0].toUtf8().constData())); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[0].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs2[0].toUtf8().constData())); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts2[0].toUtf8().constData())); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[1].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); response.m_outputProducts.clear(); @@ -1085,12 +1085,12 @@ namespace AssetProcessor // The files removed should be the ones we did not emit this time // note that order isn't guarantee but an example output it this - // [0] Removed: ES3, basefile.arc1 - // [1] Removed: ES3, basefile.arc2 - // [2] Changed: ES3, basefilea.arc1 (added) + // [0] Removed: ANDROID, basefile.arc1 + // [1] Removed: ANDROID, basefile.arc2 + // [2] Changed: ANDROID, basefilea.arc1 (added) - // [3] Removed: ES3, basefile.azm - // [4] Changed: ES3, basefilea.azm (added) + // [3] Removed: ANDROID, basefile.azm + // [4] Changed: ANDROID, basefilea.azm (added) // [5] changed: PC, basefile.arc1 (changed) // [6] changed: PC, basefile.azm (changed) @@ -1112,18 +1112,18 @@ namespace AssetProcessor if (element.m_data == "basefilea.arc1") { UNIT_TEST_EXPECT_TRUE(element.m_type == AzFramework::AssetSystem::AssetNotificationMessage::AssetChanged); - UNIT_TEST_EXPECT_TRUE(element.m_platform == "es3"); + UNIT_TEST_EXPECT_TRUE(element.m_platform == "android"); } if (element.m_data == "basefile.arc2") { UNIT_TEST_EXPECT_TRUE(element.m_type == AzFramework::AssetSystem::AssetNotificationMessage::AssetRemoved); - UNIT_TEST_EXPECT_TRUE(element.m_platform == "es3"); + UNIT_TEST_EXPECT_TRUE(element.m_platform == "android"); } } // original products must no longer exist since it should have found and deleted them! - for (QString outFile: oldes3outs) + for (QString outFile: oldandroidouts) { UNIT_TEST_EXPECT_FALSE(QFile::exists(outFile)); } @@ -1147,11 +1147,11 @@ namespace AssetProcessor sortAssetToProcessResultList(processResults); // --------- same result as above ---------- - UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // pc and es3 + UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // pc and android UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == processResults[1].m_jobEntry.m_platformInfo.m_identifier); UNIT_TEST_EXPECT_TRUE(processResults[2].m_jobEntry.m_platformInfo.m_identifier == processResults[3].m_jobEntry.m_platformInfo.m_identifier); - UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3")); - UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "es3")); + UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android")); + UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "android")); UNIT_TEST_EXPECT_TRUE((processResults[2].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE((processResults[3].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_computedFingerprint != 0); @@ -1171,12 +1171,12 @@ namespace AssetProcessor response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs[0].toUtf8().constData())); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts[0].toUtf8().constData())); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[0].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs2[0].toUtf8().constData())); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts2[0].toUtf8().constData())); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[1].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); response.m_outputProducts.clear(); @@ -1207,11 +1207,11 @@ namespace AssetProcessor sortAssetToProcessResultList(processResults); // --------- same result as above ---------- - UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and es3,since we have two recognizer for .txt file + UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and android,since we have two recognizer for .txt file UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == processResults[1].m_jobEntry.m_platformInfo.m_identifier); UNIT_TEST_EXPECT_TRUE(processResults[2].m_jobEntry.m_platformInfo.m_identifier == processResults[3].m_jobEntry.m_platformInfo.m_identifier); - UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3")); - UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "es3")); + UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android")); + UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "android")); UNIT_TEST_EXPECT_TRUE((processResults[2].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE((processResults[3].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_computedFingerprint != 0); @@ -1222,12 +1222,12 @@ namespace AssetProcessor response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs[0].toUtf8().constData())); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts[0].toUtf8().constData())); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[0].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs2[0].toUtf8().constData())); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts2[0].toUtf8().constData())); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[1].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); response.m_outputProducts.clear(); @@ -1245,9 +1245,9 @@ namespace AssetProcessor // deleting the fingerprint file should not have erased the products UNIT_TEST_EXPECT_TRUE(QFile::exists(pcouts[0])); - UNIT_TEST_EXPECT_TRUE(QFile::exists(es3outs[0])); + UNIT_TEST_EXPECT_TRUE(QFile::exists(androidouts[0])); UNIT_TEST_EXPECT_TRUE(QFile::exists(pcouts2[0])); - UNIT_TEST_EXPECT_TRUE(QFile::exists(es3outs2[0])); + UNIT_TEST_EXPECT_TRUE(QFile::exists(androidouts2[0])); changedInputResults.clear(); assetMessages.clear(); @@ -1306,9 +1306,9 @@ namespace AssetProcessor } UNIT_TEST_EXPECT_FALSE(QFile::exists(pcouts[0])); - UNIT_TEST_EXPECT_FALSE(QFile::exists(es3outs[0])); + UNIT_TEST_EXPECT_FALSE(QFile::exists(androidouts[0])); UNIT_TEST_EXPECT_FALSE(QFile::exists(pcouts2[0])); - UNIT_TEST_EXPECT_FALSE(QFile::exists(es3outs2[0])); + UNIT_TEST_EXPECT_FALSE(QFile::exists(androidouts2[0])); changedInputResults.clear(); assetMessages.clear(); @@ -1323,28 +1323,28 @@ namespace AssetProcessor sortAssetToProcessResultList(processResults); // --------- same result as above ---------- - UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and es3,since we have two recognizer for .txt file + UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and android,since we have two recognizer for .txt file UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == processResults[1].m_jobEntry.m_platformInfo.m_identifier); UNIT_TEST_EXPECT_TRUE(processResults[2].m_jobEntry.m_platformInfo.m_identifier == processResults[3].m_jobEntry.m_platformInfo.m_identifier); - UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3")); - UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "es3")); + UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android")); + UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "android")); UNIT_TEST_EXPECT_TRUE((processResults[2].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE((processResults[3].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_computedFingerprint != 0); - UNIT_TEST_EXPECT_TRUE(CreateDummyFile(es3outs[0], "newfile.")); - UNIT_TEST_EXPECT_TRUE(CreateDummyFile(es3outs2[0], "newfile.")); + UNIT_TEST_EXPECT_TRUE(CreateDummyFile(androidouts[0], "newfile.")); + UNIT_TEST_EXPECT_TRUE(CreateDummyFile(androidouts2[0], "newfile.")); UNIT_TEST_EXPECT_TRUE(CreateDummyFile(pcouts2[0], "newfile.")); // send both done messages simultaneously! response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs[0].toUtf8().constData())); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts[0].toUtf8().constData())); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[0].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs2[0].toUtf8().constData())); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts2[0].toUtf8().constData())); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[1].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); // send one failure only for PC : @@ -1422,12 +1422,12 @@ namespace AssetProcessor UNIT_TEST_EXPECT_TRUE(changedInputResults.size() == 3); UNIT_TEST_EXPECT_TRUE(assetMessages.size() == 3); - // which should be for the ES3: + // which should be for the ANDROID: UNIT_TEST_EXPECT_TRUE(AssetUtilities::NormalizeFilePath(changedInputResults[0].first) == absolutePath); // always RELATIVE, always with the product name. UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_data == "basefilea.arc1" || assetMessages[0].m_data == "basefilea.azm"); - UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_platform == "es3"); + UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_platform == "android"); for (auto& payload : payloadList) { @@ -1528,28 +1528,28 @@ namespace AssetProcessor sortAssetToProcessResultList(processResults); // --------- same result as above ---------- - UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and es3,since we have two recognizer for .txt file + UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and android,since we have two recognizer for .txt file UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == processResults[1].m_jobEntry.m_platformInfo.m_identifier); UNIT_TEST_EXPECT_TRUE(processResults[2].m_jobEntry.m_platformInfo.m_identifier == processResults[3].m_jobEntry.m_platformInfo.m_identifier); - UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3")); - UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "es3")); + UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android")); + UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "android")); UNIT_TEST_EXPECT_TRUE((processResults[2].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE((processResults[3].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_computedFingerprint != 0); - es3outs.clear(); - es3outs2.clear(); + androidouts.clear(); + androidouts2.clear(); pcouts.clear(); pcouts2.clear(); - es3outs.push_back(cacheRoot.filePath(QString("es3/basefilez.arc2"))); - es3outs2.push_back(cacheRoot.filePath(QString("es3/basefileaz.azm2"))); - // note that the ES3 outs have changed + androidouts.push_back(cacheRoot.filePath(QString("android/basefilez.arc2"))); + androidouts2.push_back(cacheRoot.filePath(QString("android/basefileaz.azm2"))); + // note that the android outs have changed // but the pc outs are still the same. pcouts.push_back(cacheRoot.filePath(QString("pc/basefile.arc2"))); pcouts2.push_back(cacheRoot.filePath(QString("pc/basefile.azm2"))); - UNIT_TEST_EXPECT_TRUE(CreateDummyFile(es3outs[0], "newfile.")); + UNIT_TEST_EXPECT_TRUE(CreateDummyFile(androidouts[0], "newfile.")); UNIT_TEST_EXPECT_TRUE(CreateDummyFile(pcouts[0], "newfile.")); - UNIT_TEST_EXPECT_TRUE(CreateDummyFile(es3outs2[0], "newfile.")); + UNIT_TEST_EXPECT_TRUE(CreateDummyFile(androidouts2[0], "newfile.")); UNIT_TEST_EXPECT_TRUE(CreateDummyFile(pcouts2[0], "newfile.")); changedInputResults.clear(); assetMessages.clear(); @@ -1557,12 +1557,12 @@ namespace AssetProcessor // send all the done messages simultaneously: response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs[0].toUtf8().constData(), AZ::Uuid::CreateNull(), 1)); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts[0].toUtf8().constData(), AZ::Uuid::CreateNull(), 1)); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[0].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); response.m_outputProducts.clear(); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(es3outs2[0].toUtf8().constData(), AZ::Uuid::CreateNull(), 2)); + response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(androidouts2[0].toUtf8().constData(), AZ::Uuid::CreateNull(), 2)); QMetaObject::invokeMethod(&apm, "AssetProcessed", Qt::QueuedConnection, Q_ARG(JobEntry, processResults[1].m_jobEntry), Q_ARG(AssetBuilderSDK::ProcessJobResponse, response)); response.m_outputProducts.clear(); @@ -1622,11 +1622,11 @@ namespace AssetProcessor sortAssetToProcessResultList(processResults); // --------- same result as above ---------- - UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and es3,since we have two recognizer for .txt file + UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // 2 each for pc and android,since we have two recognizer for .txt file UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == processResults[1].m_jobEntry.m_platformInfo.m_identifier); UNIT_TEST_EXPECT_TRUE(processResults[2].m_jobEntry.m_platformInfo.m_identifier == processResults[3].m_jobEntry.m_platformInfo.m_identifier); - UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3")); - UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "es3")); + UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android")); + UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "android")); UNIT_TEST_EXPECT_TRUE((processResults[2].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE((processResults[3].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_computedFingerprint != 0); @@ -1647,9 +1647,9 @@ namespace AssetProcessor absolutePath = watchFolderPath + "/" + relativePathFromWatchFolder; unsigned int fingerprintForPC = 0; - unsigned int fingerprintForES3 = 0; + unsigned int fingerprintForANDROID = 0; - ComputeFingerprints(fingerprintForPC, fingerprintForES3, config, watchFolderPath, relativePathFromWatchFolder); + ComputeFingerprints(fingerprintForPC, fingerprintForANDROID, config, watchFolderPath, relativePathFromWatchFolder); processResults.clear(); QMetaObject::invokeMethod(&apm, "AssessModifiedFile", Qt::QueuedConnection, Q_ARG(QString, absolutePath)); @@ -1657,11 +1657,11 @@ namespace AssetProcessor sortAssetToProcessResultList(processResults); - UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // // 2 each for pc and es3,since we have two recognizer for .xxx file + UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // // 2 each for pc and android,since we have two recognizer for .xxx file UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == processResults[1].m_jobEntry.m_platformInfo.m_identifier); UNIT_TEST_EXPECT_TRUE(processResults[2].m_jobEntry.m_platformInfo.m_identifier == processResults[3].m_jobEntry.m_platformInfo.m_identifier); - UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3")); - UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "es3")); + UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android")); + UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "android")); UNIT_TEST_EXPECT_TRUE((processResults[2].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE((processResults[3].m_jobEntry.m_platformInfo.m_identifier == "pc")); @@ -1683,11 +1683,11 @@ namespace AssetProcessor // we never actually submitted any fingerprints or indicated success, so the same number of jobs should occur as before sortAssetToProcessResultList(processResults); - UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // // 2 each for pc and es3,since we have two recognizer for .xxx file + UNIT_TEST_EXPECT_TRUE(processResults.size() == 4); // // 2 each for pc and android,since we have two recognizer for .xxx file UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == processResults[1].m_jobEntry.m_platformInfo.m_identifier); UNIT_TEST_EXPECT_TRUE(processResults[2].m_jobEntry.m_platformInfo.m_identifier == processResults[3].m_jobEntry.m_platformInfo.m_identifier); - UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3")); - UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "es3")); + UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android")); + UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "android")); UNIT_TEST_EXPECT_TRUE((processResults[2].m_jobEntry.m_platformInfo.m_identifier == "pc")); UNIT_TEST_EXPECT_TRUE((processResults[3].m_jobEntry.m_platformInfo.m_identifier == "pc")); @@ -1707,7 +1707,7 @@ namespace AssetProcessor // now re-perform the same test, this time only the pc ones should re-appear. // this should happen because we're changing the extra params, which should be part of the fingerprint // if this unit test fails, check to make sure that the extra params are being ingested into the fingerprint computation functions - // and also make sure that the jobs that are for the remaining es3 platform don't change. + // and also make sure that the jobs that are for the remaining android platform don't change. // store the UUID so that we can insert the new one with the same UUID AZStd::shared_ptr builderTxt2Builder; @@ -1745,12 +1745,12 @@ namespace AssetProcessor // --------------------- unsigned int newfingerprintForPC = 0; - unsigned int newfingerprintForES3 = 0; + unsigned int newfingerprintForANDROID = 0; - ComputeFingerprints(newfingerprintForPC, newfingerprintForES3, config, watchFolderPath, relativePathFromWatchFolder); + ComputeFingerprints(newfingerprintForPC, newfingerprintForANDROID, config, watchFolderPath, relativePathFromWatchFolder); UNIT_TEST_EXPECT_TRUE(newfingerprintForPC != fingerprintForPC);//Fingerprints should be different - UNIT_TEST_EXPECT_TRUE(newfingerprintForES3 == fingerprintForES3);//Fingerprints are same + UNIT_TEST_EXPECT_TRUE(newfingerprintForANDROID == fingerprintForANDROID);//Fingerprints are same config.RemoveRecognizer("xxx files 2 (builder2)"); mockAppManager.UnRegisterAssetRecognizerAsBuilder("xxx files 2 (builder2)"); @@ -1765,18 +1765,18 @@ namespace AssetProcessor absolutePath = AssetUtilities::NormalizeFilePath(absolutePath); QMetaObject::invokeMethod(&apm, "AssessModifiedFile", Qt::QueuedConnection, Q_ARG(QString, absolutePath)); UNIT_TEST_EXPECT_TRUE(BlockUntil(idling, 5000)); - UNIT_TEST_EXPECT_TRUE(processResults.size() == 2); // pc and es3 + UNIT_TEST_EXPECT_TRUE(processResults.size() == 2); // pc and android UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier != processResults[1].m_jobEntry.m_platformInfo.m_identifier); - UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "pc") || (processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3")); - UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "pc") || (processResults[1].m_jobEntry.m_platformInfo.m_identifier == "es3")); + UNIT_TEST_EXPECT_TRUE((processResults[0].m_jobEntry.m_platformInfo.m_identifier == "pc") || (processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android")); + UNIT_TEST_EXPECT_TRUE((processResults[1].m_jobEntry.m_platformInfo.m_identifier == "pc") || (processResults[1].m_jobEntry.m_platformInfo.m_identifier == "android")); unsigned int newfingerprintForPCAfterVersionChange = 0; - unsigned int newfingerprintForES3AfterVersionChange = 0; + unsigned int newfingerprintForANDROIDAfterVersionChange = 0; - ComputeFingerprints(newfingerprintForPCAfterVersionChange, newfingerprintForES3AfterVersionChange, config, watchFolderPath, relativePathFromWatchFolder); + ComputeFingerprints(newfingerprintForPCAfterVersionChange, newfingerprintForANDROIDAfterVersionChange, config, watchFolderPath, relativePathFromWatchFolder); UNIT_TEST_EXPECT_TRUE((newfingerprintForPCAfterVersionChange != fingerprintForPC) || (newfingerprintForPCAfterVersionChange != newfingerprintForPC));//Fingerprints should be different - UNIT_TEST_EXPECT_TRUE((newfingerprintForES3AfterVersionChange != fingerprintForES3) || (newfingerprintForES3AfterVersionChange != newfingerprintForES3));//Fingerprints should be different + UNIT_TEST_EXPECT_TRUE((newfingerprintForANDROIDAfterVersionChange != fingerprintForANDROID) || (newfingerprintForANDROIDAfterVersionChange != newfingerprintForANDROID));//Fingerprints should be different //------Test for Files which are excluded processResults.clear(); @@ -1921,7 +1921,7 @@ namespace AssetProcessor UNIT_TEST_EXPECT_TRUE(processResults.size() == 0); // nothing to process - // we are aware that 4 products went missing (es3 and pc versions of the 2 files since we renamed the SOURCE folder) + // we are aware that 4 products went missing (android and pc versions of the 2 files since we renamed the SOURCE folder) UNIT_TEST_EXPECT_TRUE(assetMessages.size() == 4); for (auto element : assetMessages) { @@ -2180,8 +2180,8 @@ namespace AssetProcessor UNIT_TEST_EXPECT_TRUE(assetMessages[2].m_assetId != AZ::Data::AssetId()); UNIT_TEST_EXPECT_TRUE(assetMessages[3].m_assetId != AZ::Data::AssetId()); - UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_platform == "es3"); - UNIT_TEST_EXPECT_TRUE(assetMessages[1].m_platform == "es3"); + UNIT_TEST_EXPECT_TRUE(assetMessages[0].m_platform == "android"); + UNIT_TEST_EXPECT_TRUE(assetMessages[1].m_platform == "android"); UNIT_TEST_EXPECT_TRUE(assetMessages[2].m_platform == "pc"); UNIT_TEST_EXPECT_TRUE(assetMessages[3].m_platform == "pc"); @@ -2214,12 +2214,12 @@ namespace AssetProcessor mockAppManager.UnRegisterAllBuilders(); AssetRecognizer abt_rec1; - AssetPlatformSpec abt_speces3; + AssetPlatformSpec abt_specandroid; abt_rec1.m_name = "UnitTestTextBuilder1"; abt_rec1.m_patternMatcher = AssetBuilderSDK::FilePatternMatcher("*.txt", AssetBuilderSDK::AssetBuilderPattern::Wildcard); //abt_rec1.m_regexp.setPatternSyntax(QRegExp::Wildcard); //abt_rec1.m_regexp.setPattern("*.txt"); - abt_rec1.m_platformSpecs.insert("es3", speces3); + abt_rec1.m_platformSpecs.insert("android", specandroid); mockAppManager.RegisterAssetRecognizerAsBuilder(abt_rec1); AssetRecognizer abt_rec2; @@ -2268,8 +2268,8 @@ namespace AssetProcessor sortAssetToProcessResultList(processResults); - UNIT_TEST_EXPECT_TRUE(processResults.size() == 2); // 1 for pc and es3 - UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == "es3"); + UNIT_TEST_EXPECT_TRUE(processResults.size() == 2); // 1 for pc and android + UNIT_TEST_EXPECT_TRUE(processResults[0].m_jobEntry.m_platformInfo.m_identifier == "android"); UNIT_TEST_EXPECT_TRUE(processResults[1].m_jobEntry.m_platformInfo.m_identifier == "pc"); UNIT_TEST_EXPECT_TRUE(QString::compare(processResults[0].m_jobEntry.GetAbsoluteSourcePath(), absolutePath, Qt::CaseInsensitive) == 0); UNIT_TEST_EXPECT_TRUE(QString::compare(processResults[1].m_jobEntry.GetAbsoluteSourcePath(), absolutePath, Qt::CaseInsensitive) == 0); diff --git a/Code/Tools/AssetProcessor/native/unittests/ConnectionUnitTests.cpp b/Code/Tools/AssetProcessor/native/unittests/ConnectionUnitTests.cpp index 29a0570d39..992cf09539 100644 --- a/Code/Tools/AssetProcessor/native/unittests/ConnectionUnitTests.cpp +++ b/Code/Tools/AssetProcessor/native/unittests/ConnectionUnitTests.cpp @@ -17,16 +17,16 @@ void ConnectionUnitTest::StartTest() m_testConnection.SetAssetPlatformsString("pc"); AzFramework::AssetSystem::AssetNotificationMessage testMessage; EXPECT_CALL(m_testConnection, Send(testing::_, testing::_)).Times(0); - m_testConnection.SendPerPlatform(0, testMessage, "osx_gl"); + m_testConnection.SendPerPlatform(0, testMessage, "mac"); EXPECT_CALL(m_testConnection, Send(testing::_, testing::_)).Times(1); m_testConnection.SendPerPlatform(0, testMessage, "pc"); - m_testConnection.SetAssetPlatformsString("pc,es3"); + m_testConnection.SetAssetPlatformsString("pc,android"); EXPECT_CALL(m_testConnection, Send(testing::_, testing::_)).Times(1); m_testConnection.SendPerPlatform(0, testMessage, "pc"); EXPECT_CALL(m_testConnection, Send(testing::_, testing::_)).Times(0); - m_testConnection.SendPerPlatform(0, testMessage, "osx_gl"); + m_testConnection.SendPerPlatform(0, testMessage, "mac"); EXPECT_CALL(m_testConnection, Send(testing::_, testing::_)).Times(1); - m_testConnection.SendPerPlatform(0, testMessage, "es3"); + m_testConnection.SendPerPlatform(0, testMessage, "android"); EXPECT_CALL(m_testConnection, Send(testing::_, testing::_)).Times(0); // Intended partial string match test - shouldn't send m_testConnection.SendPerPlatform(0, testMessage, "es"); diff --git a/Code/Tools/AssetProcessor/native/unittests/MockConnectionHandler.h b/Code/Tools/AssetProcessor/native/unittests/MockConnectionHandler.h index f0553d5e84..75ffdfe218 100644 --- a/Code/Tools/AssetProcessor/native/unittests/MockConnectionHandler.h +++ b/Code/Tools/AssetProcessor/native/unittests/MockConnectionHandler.h @@ -63,7 +63,7 @@ namespace AssetProcessor size_t SendPerPlatform(unsigned int serial, const AzFramework::AssetSystem::BaseAssetProcessorMessage& message, const QString& platform) override { - if (QString::compare(platform, "pc", Qt::CaseInsensitive) == 0 || QString::compare(platform, "es3", Qt::CaseInsensitive) == 0) + if (QString::compare(platform, "pc", Qt::CaseInsensitive) == 0 || QString::compare(platform, "android", Qt::CaseInsensitive) == 0) { return Send(serial, message); } @@ -72,7 +72,7 @@ namespace AssetProcessor size_t SendRawPerPlatform(unsigned int type, unsigned int serial, const QByteArray& data, const QString& platform) override { - if (QString::compare(platform, "pc", Qt::CaseInsensitive) == 0 || QString::compare(platform, "es3", Qt::CaseInsensitive) == 0) + if (QString::compare(platform, "pc", Qt::CaseInsensitive) == 0 || QString::compare(platform, "android", Qt::CaseInsensitive) == 0) { return SendRaw(type, serial, data); } diff --git a/Code/Tools/AssetProcessor/native/unittests/PlatformConfigurationUnitTests.cpp b/Code/Tools/AssetProcessor/native/unittests/PlatformConfigurationUnitTests.cpp index e09a6366a1..ff29cf2ca9 100644 --- a/Code/Tools/AssetProcessor/native/unittests/PlatformConfigurationUnitTests.cpp +++ b/Code/Tools/AssetProcessor/native/unittests/PlatformConfigurationUnitTests.cpp @@ -64,7 +64,7 @@ void PlatformConfigurationTests::StartTest() PlatformConfiguration config; config.EnablePlatform({ "pc",{ "desktop", "host" } }, true); - config.EnablePlatform({ "es3",{ "mobile", "android" } }, true); + config.EnablePlatform({ "android",{ "mobile", "android" } }, true); config.EnablePlatform({ "fandago",{ "console" } }, false); AZStd::vector platforms; config.PopulatePlatformsForScanFolder(platforms); @@ -88,15 +88,15 @@ void PlatformConfigurationTests::StartTest() AssetRecognizer rec; AssetPlatformSpec specpc; - AssetPlatformSpec speces3; + AssetPlatformSpec specandroid; AssetPlatformSpec specfandago; specpc.m_extraRCParams = ""; // blank must work - speces3.m_extraRCParams = "testextraparams"; + specandroid.m_extraRCParams = "testextraparams"; rec.m_name = "txt files"; rec.m_patternMatcher = AssetBuilderSDK::FilePatternMatcher("*.txt", AssetBuilderSDK::AssetBuilderPattern::Wildcard); rec.m_platformSpecs.insert("pc", specpc); - rec.m_platformSpecs.insert("es3", speces3); + rec.m_platformSpecs.insert("android", specandroid); rec.m_platformSpecs.insert("fandago", specfandago); config.AddRecognizer(rec); @@ -111,7 +111,7 @@ void PlatformConfigurationTests::StartTest() UNIT_TEST_EXPECT_TRUE(config.GetEnabledPlatforms().size() == 2); UNIT_TEST_EXPECT_TRUE(config.GetEnabledPlatforms()[0].m_identifier == "pc"); - UNIT_TEST_EXPECT_TRUE(config.GetEnabledPlatforms()[1].m_identifier == "es3"); + UNIT_TEST_EXPECT_TRUE(config.GetEnabledPlatforms()[1].m_identifier == "android"); UNIT_TEST_EXPECT_TRUE(config.GetScanFolderCount() == 11); UNIT_TEST_EXPECT_FALSE(config.GetScanFolderAt(0).IsRoot()); diff --git a/Code/Tools/AssetProcessor/native/unittests/RCcontrollerUnitTests.cpp b/Code/Tools/AssetProcessor/native/unittests/RCcontrollerUnitTests.cpp index 0e771f7fd1..02b98e5e33 100644 --- a/Code/Tools/AssetProcessor/native/unittests/RCcontrollerUnitTests.cpp +++ b/Code/Tools/AssetProcessor/native/unittests/RCcontrollerUnitTests.cpp @@ -239,14 +239,14 @@ void RCcontrollerUnitTests::RunRCControllerTests() createdJobs.push_back(job); } - // double them up for "es3" to make sure that platform is respected + // double them up for "android" to make sure that platform is respected for (QString name : tempJobNames) { AZ::Uuid uuidOfSource = AZ::Uuid::CreateName(name.toUtf8().constData()); RCJob* job0 = new RCJob(rcJobListModel); AssetProcessor::JobDetails jobDetails; jobDetails.m_jobEntry.m_databaseSourceName = jobDetails.m_jobEntry.m_pathRelativeToWatchFolder = name; - jobDetails.m_jobEntry.m_platformInfo = { "es3" ,{ "mobile", "renderer" } }; + jobDetails.m_jobEntry.m_platformInfo = { "android" ,{ "mobile", "renderer" } }; jobDetails.m_jobEntry.m_jobKey = "Compile Other Stuff"; jobDetails.m_jobEntry.m_sourceFileUUID = uuidOfSource; job0->Init(jobDetails); @@ -490,7 +490,7 @@ void RCcontrollerUnitTests::RunRCControllerTests() UNIT_TEST_EXPECT_FALSE(gotJobsInQueueCall); // submit same job but different platform: - details.m_jobEntry = JobEntry("d:/test", "test1.txt", "test1.txt", AZ::Uuid("{7954065D-CFD1-4666-9E4C-3F36F417C7AC}"), { "es3" ,{ "mobile", "renderer" } }, "Test Job", 1234, 3, sourceId); + details.m_jobEntry = JobEntry("d:/test", "test1.txt", "test1.txt", AZ::Uuid("{7954065D-CFD1-4666-9E4C-3F36F417C7AC}"), { "android" ,{ "mobile", "renderer" } }, "Test Job", 1234, 3, sourceId); m_rcController.JobSubmitted(details); QCoreApplication::processEvents(QEventLoop::AllEvents); diff --git a/Code/Tools/AssetProcessor/native/unittests/UnitTestRunner.cpp b/Code/Tools/AssetProcessor/native/unittests/UnitTestRunner.cpp index 1e10002b53..650f3120dd 100644 --- a/Code/Tools/AssetProcessor/native/unittests/UnitTestRunner.cpp +++ b/Code/Tools/AssetProcessor/native/unittests/UnitTestRunner.cpp @@ -54,7 +54,7 @@ namespace UnitTestUtils { void SleepForMinimumFileSystemTime() { - // note that on OSX, the file system has a resolution of 1 second, and since we're using modtime for a bunch of things, + // note that on Mac, the file system has a resolution of 1 second, and since we're using modtime for a bunch of things, // not the actual hash files, we have to wait different amount depending on the OS. #ifdef AZ_PLATFORM_WINDOWS int milliseconds = 1; diff --git a/Code/Tools/AssetProcessor/testdata/config_broken_badplatform/AssetProcessorPlatformConfig.setreg b/Code/Tools/AssetProcessor/testdata/config_broken_badplatform/AssetProcessorPlatformConfig.setreg index 468ab68f5d..05ed19cb74 100644 --- a/Code/Tools/AssetProcessor/testdata/config_broken_badplatform/AssetProcessorPlatformConfig.setreg +++ b/Code/Tools/AssetProcessor/testdata/config_broken_badplatform/AssetProcessorPlatformConfig.setreg @@ -5,11 +5,11 @@ "Platform pc": { "tags": "tools,renderer" }, - "Platform osx_gl": { + "Platform mac": { "tags": "tools,renderer" }, "Platforms": { - "es3": "enabled" + "android": "enabled" }, "ScanFolder Game": { "watch": "@PROJECTROOT@", diff --git a/Code/Tools/AssetProcessor/testdata/config_broken_noscans/AssetProcessorPlatformConfig.setreg b/Code/Tools/AssetProcessor/testdata/config_broken_noscans/AssetProcessorPlatformConfig.setreg index 507fe4afb1..23f5725548 100644 --- a/Code/Tools/AssetProcessor/testdata/config_broken_noscans/AssetProcessorPlatformConfig.setreg +++ b/Code/Tools/AssetProcessor/testdata/config_broken_noscans/AssetProcessorPlatformConfig.setreg @@ -5,7 +5,7 @@ "Platform pc": { "tags": "tools,renderer" }, - "Platform osx_gl": { + "Platform mac": { "tags": "tools,renderer" }, "RC i_caf": { diff --git a/Code/Tools/AssetProcessor/testdata/config_broken_recognizers/AssetProcessorPlatformConfig.setreg b/Code/Tools/AssetProcessor/testdata/config_broken_recognizers/AssetProcessorPlatformConfig.setreg index 0e687062b2..32c0af0593 100644 --- a/Code/Tools/AssetProcessor/testdata/config_broken_recognizers/AssetProcessorPlatformConfig.setreg +++ b/Code/Tools/AssetProcessor/testdata/config_broken_recognizers/AssetProcessorPlatformConfig.setreg @@ -5,7 +5,7 @@ "Platform pc": { "tags": "tools,renderer" }, - "Platform osx_gl": { + "Platform mac": { "tags": "tools,renderer" }, "ScanFolder Game": { diff --git a/Code/Tools/AssetProcessor/testdata/config_regular/AssetProcessorPlatformConfig.setreg b/Code/Tools/AssetProcessor/testdata/config_regular/AssetProcessorPlatformConfig.setreg index 1c5c487a46..c43996f3d5 100644 --- a/Code/Tools/AssetProcessor/testdata/config_regular/AssetProcessorPlatformConfig.setreg +++ b/Code/Tools/AssetProcessor/testdata/config_regular/AssetProcessorPlatformConfig.setreg @@ -5,17 +5,17 @@ "Platform pc": { "tags": "tools,renderer" }, - "Platform es3": { + "Platform android": { "tags": "android,mobile,renderer" }, - "Platform osx_gl": { + "Platform mac": { "tags": "tools,renderer" }, "Platform server": { "tags": "server" }, "Platforms": { - "es3": "enabled", + "android": "enabled", "server": "enabled" }, "Jobs": { @@ -56,7 +56,7 @@ "glob": "*.i_caf", "params": "defaultparams", "server": "skip", - "es3": "mobile", + "android": "mobile", "priority": 5, "checkServer": true }, @@ -68,7 +68,7 @@ "RC mov": { "glob": "*.mov", "params": "copy", - "es3": "platformspecificoverride", + "android": "platformspecificoverride", "renderer": "rendererparams" }, "RC rend": { diff --git a/Code/Tools/AssetProcessor/testdata/config_regular_platform_scanfolder/AssetProcessorPlatformConfig.setreg b/Code/Tools/AssetProcessor/testdata/config_regular_platform_scanfolder/AssetProcessorPlatformConfig.setreg index e1c2d6e8cc..5fe1071fd5 100644 --- a/Code/Tools/AssetProcessor/testdata/config_regular_platform_scanfolder/AssetProcessorPlatformConfig.setreg +++ b/Code/Tools/AssetProcessor/testdata/config_regular_platform_scanfolder/AssetProcessorPlatformConfig.setreg @@ -5,13 +5,13 @@ "Platform pc": { "tags": "tools,renderer" }, - "Platform es3": { + "Platform android": { "tags": "android,mobile,renderer" }, "Platform ios": { "tags": "mobile,renderer" }, - "Platform osx_gl": { + "Platform mac": { "tags": "tools,renderer" }, "Platform server": { @@ -21,7 +21,7 @@ "tags": "console,renderer" }, "Platforms": { - "es3": "enabled", + "android": "enabled", "ios": "enabled", "server": "enabled" }, @@ -54,14 +54,14 @@ "display": "folder1output", "recursive": 1, "order": 50000, - "include": "es3" + "include": "android" }, "ScanFolder Folder2": { "watch": "@ENGINEROOT@/Folder2", "display": "folder2output", "recursive": 1, "order": 60000, - "exclude": "es3" + "exclude": "android" }, "ScanFolder Folder3": { "watch": "@ENGINEROOT@/Folder3", @@ -80,7 +80,7 @@ "glob": "*.i_caf", "params": "defaultparams", "server": "skip", - "es3": "mobile", + "android": "mobile", "test": "copy", "priority": 5 }, @@ -92,7 +92,7 @@ "RC mov": { "glob": "*.mov", "params": "copy", - "es3": "platformspecificoverride", + "android": "platformspecificoverride", "renderer": "rendererparams" }, "RC rend": { diff --git a/Code/Tools/GridHub/GridHub/gridhub.cpp b/Code/Tools/GridHub/GridHub/gridhub.cpp index 7f85ade238..4b2d8e425b 100644 --- a/Code/Tools/GridHub/GridHub/gridhub.cpp +++ b/Code/Tools/GridHub/GridHub/gridhub.cpp @@ -552,7 +552,7 @@ GridHubComponent::OnMemberJoined([[maybe_unused]] GridMate::GridSession* session switch( member->GetPlatformId() ) { case AZ::PlatformID::PLATFORM_WINDOWS_64: - case AZ::PlatformID::PLATFORM_APPLE_OSX: + case AZ::PlatformID::PLATFORM_APPLE_MAC: { GridMate::string localMachineName = GridMate::Utils::GetMachineAddress(); if( member->GetMachineName() == localMachineName ) diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp index 04b015a66f..bf584c4d63 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp @@ -108,11 +108,11 @@ namespace ImageProcessingAtomEditor { readableString = "PC"; } - else if (platformStrLowerCase == "es3") + else if (platformStrLowerCase == "android") { readableString = "Android"; } - else if (platformStrLowerCase == "osx_gl") + else if (platformStrLowerCase == "mac") { readableString = "macOS"; } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Platform/Mac/ImageProcessing_Traits_Mac.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Platform/Mac/ImageProcessing_Traits_Mac.h index 28c1e78bb6..ef0e7f9619 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Platform/Mac/ImageProcessing_Traits_Mac.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Platform/Mac/ImageProcessing_Traits_Mac.h @@ -12,7 +12,7 @@ #pragma once #define AZ_TRAIT_IMAGEPROCESSING_BESSEL_FUNCTION_FIRST_ORDER j1 -#define AZ_TRAIT_IMAGEPROCESSING_DEFAULT_PLATFORM "osx_gl" +#define AZ_TRAIT_IMAGEPROCESSING_DEFAULT_PLATFORM "mac" #define AZ_TRAIT_IMAGEPROCESSING_DEFINE_DIRECT3D_CONSTANTS 1 #define AZ_TRAIT_IMAGEPROCESSING_PVRTEXLIB_USE_WINDLL_IMPORT 0 #define AZ_TRAIT_IMAGEPROCESSING_SQUISH_DO_NOT_USE_FASTCALL 1 diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Platform/iOS/ImageProcessing_Traits_iOS.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Platform/iOS/ImageProcessing_Traits_iOS.h index 28c1e78bb6..ef0e7f9619 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Platform/iOS/ImageProcessing_Traits_iOS.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Platform/iOS/ImageProcessing_Traits_iOS.h @@ -12,7 +12,7 @@ #pragma once #define AZ_TRAIT_IMAGEPROCESSING_BESSEL_FUNCTION_FIRST_ORDER j1 -#define AZ_TRAIT_IMAGEPROCESSING_DEFAULT_PLATFORM "osx_gl" +#define AZ_TRAIT_IMAGEPROCESSING_DEFAULT_PLATFORM "mac" #define AZ_TRAIT_IMAGEPROCESSING_DEFINE_DIRECT3D_CONSTANTS 1 #define AZ_TRAIT_IMAGEPROCESSING_PVRTEXLIB_USE_WINDLL_IMPORT 0 #define AZ_TRAIT_IMAGEPROCESSING_SQUISH_DO_NOT_USE_FASTCALL 1 diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/1024x1024_24bit.tif.exportsettings b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/1024x1024_24bit.tif.exportsettings index 0417122033..7bce3041b9 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/1024x1024_24bit.tif.exportsettings +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/1024x1024_24bit.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /bumptype=none /M=62,18,32,83,50,50 /preset=Diffuse_highQ /mipgentype=kaiser /reduce="es3:0,ios:3,osx_gl:0,pc:4,provo:1" /ser=0 +/autooptimizefile=0 /bumptype=none /M=62,18,32,83,50,50 /preset=Diffuse_highQ /mipgentype=kaiser /reduce="android:0,ios:3,mac:0,pc:4,provo:1" /ser=0 diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Albedo.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Albedo.preset index 0b68493198..3a5122f18e 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Albedo.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Albedo.preset @@ -25,7 +25,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{08A95286-ADB2-41E4-96EB-DB48F4726D6A}", "Name": "Albedo", "RGB_Weight": "CIEXYZ", @@ -67,7 +67,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{08A95286-ADB2-41E4-96EB-DB48F4726D6A}", "Name": "Albedo", "RGB_Weight": "CIEXYZ", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithCoverage.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithCoverage.preset index 3773857e0a..692ef99b1c 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithCoverage.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithCoverage.preset @@ -23,7 +23,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{57ED16B1-407B-4E29-BCFC-D3BAE60F2C85}", "Name": "AlbedoWithCoverage", "RGB_Weight": "CIEXYZ", @@ -61,7 +61,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{57ED16B1-407B-4E29-BCFC-D3BAE60F2C85}", "Name": "AlbedoWithCoverage", "RGB_Weight": "CIEXYZ", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithGenericAlpha.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithGenericAlpha.preset index 530e36038d..4ebe773f0e 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithGenericAlpha.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithGenericAlpha.preset @@ -23,7 +23,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{5D9ECB52-4CD9-4CB8-80E3-10CAE5EFB8A2}", "Name": "AlbedoWithGenericAlpha", "RGB_Weight": "CIEXYZ", @@ -61,7 +61,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{5D9ECB52-4CD9-4CB8-80E3-10CAE5EFB8A2}", "Name": "AlbedoWithGenericAlpha", "RGB_Weight": "CIEXYZ", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithOpacity.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithOpacity.preset index 6d6c156683..6049ef5bd4 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithOpacity.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithOpacity.preset @@ -23,7 +23,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{7BB7BC6C-D3DA-4184-AC42-BCD8C57DE565}", "Name": "AlbedoWithOpacity", "RGB_Weight": "CIEXYZ", @@ -61,7 +61,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{7BB7BC6C-D3DA-4184-AC42-BCD8C57DE565}", "Name": "AlbedoWithOpacity", "RGB_Weight": "CIEXYZ", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/AmbientOcclusion.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/AmbientOcclusion.preset index 4e69ae67f2..56dec20f3e 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/AmbientOcclusion.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/AmbientOcclusion.preset @@ -17,7 +17,7 @@ "PixelFormat": "BC4" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{02ED0ECE-B198-49D9-85BC-CEBA6C28546C}", "Name": "AmbientOcclusion", "SourceColor": "Linear", @@ -43,7 +43,7 @@ ], "PixelFormat": "EAC_R11" }, - "osx_gl": { + "mac": { "UUID": "{02ED0ECE-B198-49D9-85BC-CEBA6C28546C}", "Name": "AmbientOcclusion", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/CloudShadows.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/CloudShadows.preset index f37acd2f9d..2280a06302 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/CloudShadows.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/CloudShadows.preset @@ -11,7 +11,7 @@ "IsPowerOf2": true }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{884B5F7C-44AC-4E9E-8B8A-559D098BE2C7}", "Name": "CloudShadows", "DestColor": "Linear", @@ -25,7 +25,7 @@ "PixelFormat": "EAC_R11", "IsPowerOf2": true }, - "osx_gl": { + "mac": { "UUID": "{884B5F7C-44AC-4E9E-8B8A-559D098BE2C7}", "Name": "CloudShadows", "DestColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ColorChart.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/ColorChart.preset index 46327e87ed..5f0480cee7 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/ColorChart.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/ColorChart.preset @@ -15,7 +15,7 @@ "IsColorChart": true }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{0A17A85F-07EE-48A0-8BF8-D42F0A5E0B3C}", "Name": "ColorChart", "SourceColor": "Linear", @@ -37,7 +37,7 @@ "PixelFormat": "R8G8B8X8", "IsColorChart": true }, - "osx_gl": { + "mac": { "UUID": "{0A17A85F-07EE-48A0-8BF8-D42F0A5E0B3C}", "Name": "ColorChart", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ConvolvedCubemap.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/ConvolvedCubemap.preset index fe87f49426..abdf6501be 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/ConvolvedCubemap.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/ConvolvedCubemap.preset @@ -30,7 +30,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{2174E04B-73BB-4DF1-8961-4900DC3C9D72}", "Name": "ConvolvedCubemap", "SourceColor": "Linear", @@ -82,7 +82,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{2174E04B-73BB-4DF1-8961-4900DC3C9D72}", "Name": "ConvolvedCubemap", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Decal_AlbedoWithOpacity.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Decal_AlbedoWithOpacity.preset index 2c47f9eaed..f1e43e74b1 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Decal_AlbedoWithOpacity.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Decal_AlbedoWithOpacity.preset @@ -18,7 +18,7 @@ "NumberResidentMips": 255 }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{E06B5087-2640-49B6-B9BA-D40048162B90}", "Name": "Decal_AlbedoWithOpacity", "FileMasks": [ @@ -46,7 +46,7 @@ // Decal Texture Arrays need all mips available immediately for packing. "NumberResidentMips": 255 }, - "osx_gl": { + "mac": { "UUID": "{E06B5087-2640-49B6-B9BA-D40048162B90}", "Name": "Decal_AlbedoWithOpacity", "FileMasks": [ diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Detail_MergedAlbedoNormalsSmoothness.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Detail_MergedAlbedoNormalsSmoothness.preset index 23ec2347cd..991692c5cc 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Detail_MergedAlbedoNormalsSmoothness.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Detail_MergedAlbedoNormalsSmoothness.preset @@ -18,7 +18,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{5096FC7B-0B2D-4466-9943-AD59922968E8}", "Name": "Detail_MergedAlbedoNormalsSmoothness", "SourceColor": "Linear", @@ -46,7 +46,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{5096FC7B-0B2D-4466-9943-AD59922968E8}", "Name": "Detail_MergedAlbedoNormalsSmoothness", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Detail_MergedAlbedoNormalsSmoothness_Lossless.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Detail_MergedAlbedoNormalsSmoothness_Lossless.preset index 3145c5cf8a..fec11218e8 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Detail_MergedAlbedoNormalsSmoothness_Lossless.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Detail_MergedAlbedoNormalsSmoothness_Lossless.preset @@ -17,7 +17,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{B6FC1AEF-907C-4157-9A1A-D9960F0E5B9A}", "Name": "Detail_MergedAlbedoNormalsSmoothness_Lossless", "SourceColor": "Linear", @@ -43,7 +43,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{B6FC1AEF-907C-4157-9A1A-D9960F0E5B9A}", "Name": "Detail_MergedAlbedoNormalsSmoothness_Lossless", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Displacement.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Displacement.preset index 86ba9d74c0..520e4ae193 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Displacement.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Displacement.preset @@ -28,7 +28,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{D7B4BEA6-6427-4295-B61B-62776D0056DE}", "Name": "Displacement", "SourceColor": "Linear", @@ -77,7 +77,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{D7B4BEA6-6427-4295-B61B-62776D0056DE}", "Name": "Displacement", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Emissive.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Emissive.preset index 5a98d2cd30..ffb16482fd 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Emissive.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Emissive.preset @@ -18,7 +18,7 @@ "DiscardAlpha": true }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{07041D83-E0C3-4726-8735-CA0FE550C9A0}", "Name": "Emissive", "RGB_Weight": "CIEXYZ", @@ -46,7 +46,7 @@ "PixelFormat": "ASTC_6x6", "DiscardAlpha": true }, - "osx_gl": { + "mac": { "UUID": "{07041D83-E0C3-4726-8735-CA0FE550C9A0}", "Name": "Emissive", "RGB_Weight": "CIEXYZ", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Gradient.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Gradient.preset index 9cf32093d1..33d7babf00 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Gradient.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Gradient.preset @@ -11,7 +11,7 @@ "IsPowerOf2": true }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{0D26B387-2FBA-456D-AB8E-613020BCC7F8}", "Name": "Gradient", "SourceColor": "Linear", @@ -25,7 +25,7 @@ "DestColor": "Linear", "IsPowerOf2": true }, - "osx_gl": { + "mac": { "UUID": "{0D26B387-2FBA-456D-AB8E-613020BCC7F8}", "Name": "Gradient", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Greyscale.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Greyscale.preset index c77c77b988..f06682be42 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Greyscale.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Greyscale.preset @@ -18,7 +18,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{B6B04FD3-BD7B-44AC-AD93-6FECD2BD4D76}", "Name": "Greyscale", "SourceColor": "Linear", @@ -46,7 +46,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{B6B04FD3-BD7B-44AC-AD93-6FECD2BD4D76}", "Name": "Greyscale", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLDiffuse.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLDiffuse.preset index fb4155a974..8bd6b348d1 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLDiffuse.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLDiffuse.preset @@ -28,7 +28,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{E3706342-BF21-4D9C-AE28-9670EB3EF3C5}", "Name": "IBLDiffuse", "FileMasks": [ @@ -74,7 +74,7 @@ "SubId": 3000 } }, - "osx_gl": { + "mac": { "UUID": "{E3706342-BF21-4D9C-AE28-9670EB3EF3C5}", "Name": "IBLDiffuse", "FileMasks": [ diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSkybox.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSkybox.preset index 530eb3d048..402fc470eb 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSkybox.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSkybox.preset @@ -26,7 +26,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{E6441EAC-9843-484B-8EFC-C03B2935B48D}", "Name": "IBLSkybox", "FileMasks": [ @@ -68,7 +68,7 @@ "IBLDiffusePreset": "{E3706342-BF21-4D9C-AE28-9670EB3EF3C5}" } }, - "osx_gl": { + "mac": { "UUID": "{E6441EAC-9843-484B-8EFC-C03B2935B48D}", "Name": "IBLSkybox", "FileMasks": [ diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset index db5a9276bd..d940f425c2 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset @@ -30,7 +30,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", "FileMasks": [ @@ -80,7 +80,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", "FileMasks": [ diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ImageBuilder.settings b/Gems/Atom/Asset/ImageProcessingAtom/Config/ImageBuilder.settings index c8d921a8ff..82a57dd614 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/ImageBuilder.settings +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/ImageBuilder.settings @@ -5,7 +5,7 @@ "ClassData": { "AnalysisFingerprint": "2", "BuildSettings": { - "es3": { + "android": { "GlossScale": 16.0, "GlossBias": 0.0, "Streaming": false, @@ -17,7 +17,7 @@ "Streaming": false, "Enable": true }, - "osx_gl": { + "mac": { "GlossScale": 16.0, "GlossBias": 0.0, "Streaming": false, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG16.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG16.preset index 6bfb697a5e..183653d111 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG16.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG16.preset @@ -11,7 +11,7 @@ "PixelFormat": "R16G16" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{D55CBCD3-AF2D-4515-98AB-E278F6B3B5F6}", "Name": "LUT_RG16", "SourceColor": "Linear", @@ -25,7 +25,7 @@ "DestColor": "Linear", "PixelFormat": "R16G16" }, - "osx_gl": { + "mac": { "UUID": "{D55CBCD3-AF2D-4515-98AB-E278F6B3B5F6}", "Name": "LUT_RG16", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG32F.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG32F.preset index a010d26a9c..2cf0c6ca0a 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG32F.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG32F.preset @@ -12,7 +12,7 @@ "PixelFormat": "R32G32F" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{52470B8B-0798-4E03-B0D3-039D5141CFEC}", "Name": "LUT_RG32F", "SourceColor": "Linear", @@ -26,7 +26,7 @@ "DestColor": "Linear", "PixelFormat": "R32G32F" }, - "osx_gl": { + "mac": { "UUID": "{52470B8B-0798-4E03-B0D3-039D5141CFEC}", "Name": "LUT_RG32F", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG8.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG8.preset index ca636f486a..9838d532b2 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG8.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG8.preset @@ -14,7 +14,7 @@ "PixelFormat": "R8G8" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{3791319D-043B-4011-8B6F-3DE96D0C4309}", "Name": "LUT_RG8", "SourceColor": "Linear", @@ -34,7 +34,7 @@ ], "PixelFormat": "R8G8" }, - "osx_gl": { + "mac": { "UUID": "{3791319D-043B-4011-8B6F-3DE96D0C4309}", "Name": "LUT_RG8", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA32F.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA32F.preset index 717ece058d..3a456825bf 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA32F.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA32F.preset @@ -12,7 +12,7 @@ "PixelFormat": "R32G32B32A32F" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{AC4C49D4-2C70-425A-8DBF-E7FB2C61CF8D}", "Name": "LUT_RGBA32F", "SourceColor": "Linear", @@ -26,7 +26,7 @@ "DestColor": "Linear", "PixelFormat": "R32G32B32A32F" }, - "osx_gl": { + "mac": { "UUID": "{AC4C49D4-2C70-425A-8DBF-E7FB2C61CF8D}", "Name": "LUT_RGBA32F", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA8.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA8.preset index 6dbb29f830..49bf33dd84 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA8.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA8.preset @@ -10,7 +10,7 @@ "DestColor": "Linear" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{3A6BB297-B610-4EA5-8DA4-610FB12B9EC0}", "Name": "LUT_RGBA8", "SourceColor": "Linear", @@ -22,7 +22,7 @@ "SourceColor": "Linear", "DestColor": "Linear" }, - "osx_gl": { + "mac": { "UUID": "{3A6BB297-B610-4EA5-8DA4-610FB12B9EC0}", "Name": "LUT_RGBA8", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LayerMask.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LayerMask.preset index 9c57f80709..5ce06aaea2 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LayerMask.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LayerMask.preset @@ -15,7 +15,7 @@ "PixelFormat": "R8G8B8X8" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{B1AC2F76-CB1A-46A8-B92D-B8DFBB564FCF}", "Name": "LayerMask", "SourceColor": "Linear", @@ -37,7 +37,7 @@ ], "PixelFormat": "R8G8B8X8" }, - "osx_gl": { + "mac": { "UUID": "{B1AC2F76-CB1A-46A8-B92D-B8DFBB564FCF}", "Name": "LayerMask", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LensOptics.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LensOptics.preset index 84294dfbcc..9f4b5bf68d 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LensOptics.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LensOptics.preset @@ -9,7 +9,7 @@ "PixelFormat": "BC1" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{3000A993-0A04-4E08-A813-DFB1A47A0980}", "Name": "LensOptics", "PixelFormat": "ETC2" @@ -19,7 +19,7 @@ "Name": "LensOptics", "PixelFormat": "ASTC_4x4" }, - "osx_gl": { + "mac": { "UUID": "{3000A993-0A04-4E08-A813-DFB1A47A0980}", "Name": "LensOptics", "PixelFormat": "BC1" diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LightProjector.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LightProjector.preset index 8c98394d36..ede264a78e 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LightProjector.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LightProjector.preset @@ -14,7 +14,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{1DFEF41A-D97F-40FB-99D3-C142A3E5225E}", "Name": "LightProjector", "DestColor": "Linear", @@ -34,7 +34,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{1DFEF41A-D97F-40FB-99D3-C142A3E5225E}", "Name": "LightProjector", "DestColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LoadingScreen.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/LoadingScreen.preset index f64c48eb95..ad0e2ddf06 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LoadingScreen.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/LoadingScreen.preset @@ -9,7 +9,7 @@ "PixelFormat": "R8G8B8X8" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{9ED87726-12AB-4BE0-9397-AD62AE56D9E2}", "Name": "LoadingScreen", "PixelFormat": "R8G8B8X8" @@ -19,7 +19,7 @@ "Name": "LoadingScreen", "PixelFormat": "R8G8B8X8" }, - "osx_gl": { + "mac": { "UUID": "{9ED87726-12AB-4BE0-9397-AD62AE56D9E2}", "Name": "LoadingScreen", "PixelFormat": "R8G8B8X8" diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Minimap.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Minimap.preset index a402a2636c..9370de063d 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Minimap.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Minimap.preset @@ -15,7 +15,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{0D2F4C31-A665-4862-9C63-9E49A58E9A37}", "Name": "Minimap", "SuppressEngineReduce": true, @@ -37,7 +37,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{0D2F4C31-A665-4862-9C63-9E49A58E9A37}", "Name": "Minimap", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/MuzzleFlash.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/MuzzleFlash.preset index f5ecc58d1a..459cd5b1fb 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/MuzzleFlash.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/MuzzleFlash.preset @@ -14,7 +14,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{8BCC23A5-D08E-458E-B0B3-087C65FA1D31}", "Name": "MuzzleFlash", "SuppressEngineReduce": true, @@ -34,7 +34,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{8BCC23A5-D08E-458E-B0B3-087C65FA1D31}", "Name": "MuzzleFlash", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Normals.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Normals.preset index 104f3b4a39..04307eada4 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Normals.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Normals.preset @@ -27,7 +27,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{508B21D5-5250-4003-97EC-1CF28D571ACF}", "Name": "Normals", "SourceColor": "Linear", @@ -75,7 +75,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{508B21D5-5250-4003-97EC-1CF28D571ACF}", "Name": "Normals", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsFromDisplacement.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsFromDisplacement.preset index c513720b68..46e97c3443 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsFromDisplacement.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsFromDisplacement.preset @@ -19,7 +19,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{8AE5D8D7-ECF8-4B7D-91DE-8F787E3B4210}", "Name": "NormalsFromDisplacement", "SourceColor": "Linear", @@ -49,7 +49,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{8AE5D8D7-ECF8-4B7D-91DE-8F787E3B4210}", "Name": "NormalsFromDisplacement", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness.preset index e773f7d910..b8f6e38ac1 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness.preset @@ -25,7 +25,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{6EE749F4-846E-4F7A-878C-F211F85EA59F}", "Name": "NormalsWithSmoothness", "SourceColor": "Linear", @@ -67,7 +67,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{6EE749F4-846E-4F7A-878C-F211F85EA59F}", "Name": "NormalsWithSmoothness", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness_Legacy.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness_Legacy.preset index 4cf7af6f29..58bb02cd72 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness_Legacy.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness_Legacy.preset @@ -22,7 +22,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{A92541B8-2E70-4EF1-BA88-1DC1EA2A2341}", "Name": "NormalsWithSmoothness_Legacy", "SourceColor": "Linear", @@ -58,7 +58,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{A92541B8-2E70-4EF1-BA88-1DC1EA2A2341}", "Name": "NormalsWithSmoothness_Legacy", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Opacity.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Opacity.preset index 265379d053..bbd7fd5db9 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Opacity.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Opacity.preset @@ -27,7 +27,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{F3D5E572-A3CF-435A-A2AB-75D2B6907847}", "Name": "Opacity", "SourceColor": "Linear", @@ -73,7 +73,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{F3D5E572-A3CF-435A-A2AB-75D2B6907847}", "Name": "Opacity", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage.preset index 03744dee9e..e51848a116 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage.preset @@ -8,7 +8,7 @@ "Name": "ReferenceImage" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{C659D222-F56B-4B61-A2F8-C1FA547F3C39}", "Name": "ReferenceImage" }, @@ -16,7 +16,7 @@ "UUID": "{C659D222-F56B-4B61-A2F8-C1FA547F3C39}", "Name": "ReferenceImage" }, - "osx_gl": { + "mac": { "UUID": "{C659D222-F56B-4B61-A2F8-C1FA547F3C39}", "Name": "ReferenceImage" }, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinear.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinear.preset index 4d75e7ae1d..d9b9c17d07 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinear.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinear.preset @@ -13,7 +13,7 @@ "DiscardAlpha": true }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{46D9F30F-793C-4449-BCEF-12A396E61B2C}", "Name": "ReferenceImage_HDRLinear", "SourceColor": "Linear", @@ -31,7 +31,7 @@ "PixelFormat": "R9G9B9E5", "DiscardAlpha": true }, - "osx_gl": { + "mac": { "UUID": "{46D9F30F-793C-4449-BCEF-12A396E61B2C}", "Name": "ReferenceImage_HDRLinear", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinearUncompressed.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinearUncompressed.preset index 8344102425..8a5a83afa3 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinearUncompressed.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinearUncompressed.preset @@ -13,7 +13,7 @@ "DiscardAlpha": true }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{EEF24422-C8F0-4ECE-B32A-C70DB8129466}", "Name": "ReferenceImage_HDRLinearUncompressed", "SourceColor": "Linear", @@ -31,7 +31,7 @@ "PixelFormat": "R16G16B16A16F", "DiscardAlpha": true }, - "osx_gl": { + "mac": { "UUID": "{EEF24422-C8F0-4ECE-B32A-C70DB8129466}", "Name": "ReferenceImage_HDRLinearUncompressed", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_Linear.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_Linear.preset index 515e9b0512..bf72f21b06 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_Linear.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_Linear.preset @@ -11,7 +11,7 @@ "SuppressEngineReduce": true }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{02C3D9F5-3637-49BA-A48A-D68D629A4D14}", "Name": "ReferenceImage_Linear", "SourceColor": "Linear", @@ -25,7 +25,7 @@ "DestColor": "Linear", "SuppressEngineReduce": true }, - "osx_gl": { + "mac": { "UUID": "{02C3D9F5-3637-49BA-A48A-D68D629A4D14}", "Name": "ReferenceImage_Linear", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance.preset index 58e283add7..1844e0186e 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance.preset @@ -34,7 +34,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", "Name": "Reflectance", "SourceColor": "Linear", @@ -92,7 +92,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", "Name": "Reflectance", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReflectanceWithSmoothness_Legacy.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/ReflectanceWithSmoothness_Legacy.preset index e386d08a35..e51cc7122b 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReflectanceWithSmoothness_Legacy.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/ReflectanceWithSmoothness_Legacy.preset @@ -16,7 +16,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{851128B5-7454-42C4-83CE-FCFE071834C5}", "Name": "ReflectanceWithSmoothness_Legacy", "FileMasks": [ @@ -40,7 +40,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{851128B5-7454-42C4-83CE-FCFE071834C5}", "Name": "ReflectanceWithSmoothness_Legacy", "FileMasks": [ diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance_Linear.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance_Linear.preset index 767b0b67eb..07cc39c955 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance_Linear.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance_Linear.preset @@ -18,7 +18,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{9B2114F5-118A-4B3A-9CFE-97FA01EC8CFE}", "Name": "Reflectance_Linear", "DestColor": "Linear", @@ -46,7 +46,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{9B2114F5-118A-4B3A-9CFE-97FA01EC8CFE}", "Name": "Reflectance_Linear", "DestColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Font.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Font.preset index b2bbf905db..f76741148c 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Font.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Font.preset @@ -12,7 +12,7 @@ "IsPowerOf2": true }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{F34E3711-5F34-4DBC-8F5D-6340D3989F4B}", "Name": "SF_Font", "SourceColor": "Linear", @@ -28,7 +28,7 @@ "SuppressEngineReduce": true, "IsPowerOf2": true }, - "osx_gl": { + "mac": { "UUID": "{F34E3711-5F34-4DBC-8F5D-6340D3989F4B}", "Name": "SF_Font", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Gradient.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Gradient.preset index 41ba10f55c..aff25dc83d 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Gradient.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Gradient.preset @@ -12,7 +12,7 @@ "IsPowerOf2": true }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{E7F9DF56-DCB0-4683-96EE-F04DA547BE24}", "Name": "SF_Gradient", "SourceColor": "Linear", @@ -28,7 +28,7 @@ "SuppressEngineReduce": true, "IsPowerOf2": true }, - "osx_gl": { + "mac": { "UUID": "{E7F9DF56-DCB0-4683-96EE-F04DA547BE24}", "Name": "SF_Gradient", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Image.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Image.preset index e36e42860d..46a32ce5d4 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Image.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Image.preset @@ -13,7 +13,7 @@ "IsPowerOf2": true }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{189A42CB-AEE3-4B80-B276-0FDB0ECA140C}", "Name": "SF_Image", "SourceColor": "Linear", @@ -31,7 +31,7 @@ "PixelFormat": "PVRTC4", "IsPowerOf2": true }, - "osx_gl": { + "mac": { "UUID": "{189A42CB-AEE3-4B80-B276-0FDB0ECA140C}", "Name": "SF_Image", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Image_nonpower2.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Image_nonpower2.preset index fa2fe2ae72..0ba70d2ca3 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Image_nonpower2.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/SF_Image_nonpower2.preset @@ -12,7 +12,7 @@ "PixelFormat": "BC1" }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{C456B8AB-C360-4822-BCDD-225252D0E697}", "Name": "SF_Image_nonpower2", "SourceColor": "Linear", @@ -28,7 +28,7 @@ "SuppressEngineReduce": true, "PixelFormat": "PVRTC4" }, - "osx_gl": { + "mac": { "UUID": "{C456B8AB-C360-4822-BCDD-225252D0E697}", "Name": "SF_Image_nonpower2", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Skybox.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Skybox.preset index 9102bd53bb..4f71855ecf 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Skybox.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Skybox.preset @@ -21,7 +21,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{F359CD3B-37E6-4627-B4F6-2DFC2C0E3C1C}", "Name": "Skybox", "FileMasks": [ @@ -55,7 +55,7 @@ "RequiresConvolve": false } }, - "osx_gl": { + "mac": { "UUID": "{F359CD3B-37E6-4627-B4F6-2DFC2C0E3C1C}", "Name": "Skybox", "FileMasks": [ diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Terrain_Albedo.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Terrain_Albedo.preset index 19881f93d7..84a70935f1 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Terrain_Albedo.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Terrain_Albedo.preset @@ -16,7 +16,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{88D07159-2FC0-4CBE-82CC-A9DC258C9351}", "Name": "Terrain_Albedo", "SourceColor": "Linear", @@ -40,7 +40,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{88D07159-2FC0-4CBE-82CC-A9DC258C9351}", "Name": "Terrain_Albedo", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Terrain_Albedo_HighPassed.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Terrain_Albedo_HighPassed.preset index 2fcbb012d4..1d83737ef9 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Terrain_Albedo_HighPassed.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Terrain_Albedo_HighPassed.preset @@ -15,7 +15,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{7827AA52-0A7B-43E7-8CD4-55E0BC513AF1}", "Name": "Terrain_Albedo_HighPassed", "SourceColor": "Linear", @@ -37,7 +37,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{7827AA52-0A7B-43E7-8CD4-55E0BC513AF1}", "Name": "Terrain_Albedo_HighPassed", "SourceColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Uncompressed.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Uncompressed.preset index d0dbbcba6f..6e28cafe11 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Uncompressed.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/Uncompressed.preset @@ -13,7 +13,7 @@ } }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{E996A696-991C-4FFC-B270-F5AD408B0618}", "Name": "Uncompressed", "PixelFormat": "R8G8B8X8", @@ -31,7 +31,7 @@ "MipGenType": "Box" } }, - "osx_gl": { + "mac": { "UUID": "{E996A696-991C-4FFC-B270-F5AD408B0618}", "Name": "Uncompressed", "PixelFormat": "R8G8B8X8", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset index 01595a3425..6f70e8f14f 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset @@ -13,7 +13,7 @@ "FileMasks": [ "_ui" ] }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{2828FBFE-BDF9-45A7-9370-F93822719CCF}", "Name": "UserInterface_Compressed", "SuppressEngineReduce": true, @@ -25,7 +25,7 @@ "SuppressEngineReduce": true, "PixelFormat": "ASTC_6x6" }, - "osx_gl": { + "mac": { "UUID": "{2828FBFE-BDF9-45A7-9370-F93822719CCF}", "Name": "UserInterface_Compressed", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset index 78c63790ab..39066b242b 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset @@ -13,7 +13,7 @@ "FileMasks": [ "_ui" ] }, "PlatformsPresets": { - "es3": { + "android": { "UUID": "{83003128-F63E-422B-AEC2-68F0A947225F}", "Name": "UserInterface_Lossless", "SuppressEngineReduce": true, @@ -25,7 +25,7 @@ "SuppressEngineReduce": true, "PixelFormat": "R8G8B8A8" }, - "osx_gl": { + "mac": { "UUID": "{83003128-F63E-422B-AEC2-68F0A947225F}", "Name": "UserInterface_Lossless", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp index 89ca76bd01..0db53456e0 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp @@ -736,13 +736,13 @@ namespace AZ { platformId = AzFramework::PlatformId::PC; } - else if (platformIdentifier == "osx_gl") + else if (platformIdentifier == "mac") { - platformId = AzFramework::PlatformId::OSX; + platformId = AzFramework::PlatformId::MAC; } - else if (platformIdentifier == "es3") + else if (platformIdentifier == "android") { - platformId = AzFramework::PlatformId::ES3; + platformId = AzFramework::PlatformId::ANDROID_ID; } else if (platformIdentifier == "ios") { @@ -788,13 +788,13 @@ namespace AZ { platformId = AzFramework::PlatformId::PC; } - else if (platform == "osx_gl") + else if (platform == "mac") { - platformId = AzFramework::PlatformId::OSX; + platformId = AzFramework::PlatformId::MAC; } - else if (platform == "es3") + else if (platform == "android") { - platformId = AzFramework::PlatformId::ES3; + platformId = AzFramework::PlatformId::ANDROID_ID; } else if (platform == "ios") { diff --git a/Gems/Atom/Feature/Common/Assets/Textures/PostProcessing/AreaTex.dds.assetinfo b/Gems/Atom/Feature/Common/Assets/Textures/PostProcessing/AreaTex.dds.assetinfo index 53dbfb2623..72a7948174 100644 --- a/Gems/Atom/Feature/Common/Assets/Textures/PostProcessing/AreaTex.dds.assetinfo +++ b/Gems/Atom/Feature/Common/Assets/Textures/PostProcessing/AreaTex.dds.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/Atom/Feature/Common/Assets/Textures/PostProcessing/SearchTex.dds.assetinfo b/Gems/Atom/Feature/Common/Assets/Textures/PostProcessing/SearchTex.dds.assetinfo index 3ae9447621..86d698d24e 100644 --- a/Gems/Atom/Feature/Common/Assets/Textures/PostProcessing/SearchTex.dds.assetinfo +++ b/Gems/Atom/Feature/Common/Assets/Textures/PostProcessing/SearchTex.dds.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr.assetinfo b/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr.assetinfo index da00149fb0..16cb0dd668 100644 --- a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr.assetinfo +++ b/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/Atom/RHI/Null/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp b/Gems/Atom/RHI/Null/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp index 35ee5a7ec0..0be84dba15 100644 --- a/Gems/Atom/RHI/Null/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp +++ b/Gems/Atom/RHI/Null/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp @@ -104,7 +104,7 @@ namespace AZ { return WindowsAzslShaderHeader; } - else if (platform.m_identifier == "osx_gl") + else if (platform.m_identifier == "mac") { return MacAzslShaderHeader; } diff --git a/Gems/Atom/TestData/TestData/Textures/Foliage_Leaves_0_BaseColor.dds.assetinfo b/Gems/Atom/TestData/TestData/Textures/Foliage_Leaves_0_BaseColor.dds.assetinfo index 2ec31e38ce..1aa896a8d7 100644 --- a/Gems/Atom/TestData/TestData/Textures/Foliage_Leaves_0_BaseColor.dds.assetinfo +++ b/Gems/Atom/TestData/TestData/Textures/Foliage_Leaves_0_BaseColor.dds.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/AudioEngineWwise/Code/Source/Builder/AudioControlBuilderWorker.cpp b/Gems/AudioEngineWwise/Code/Source/Builder/AudioControlBuilderWorker.cpp index f7b54a44d9..b08aa6fa1d 100644 --- a/Gems/AudioEngineWwise/Code/Source/Builder/AudioControlBuilderWorker.cpp +++ b/Gems/AudioEngineWwise/Code/Source/Builder/AudioControlBuilderWorker.cpp @@ -57,11 +57,11 @@ namespace AudioControlBuilder { atlPlatform = "windows"; } - else if (platform == "es3") + else if (platform == "android") { atlPlatform = "android"; } - else if (platform == "osx_gl") + else if (platform == "mac") { atlPlatform = "mac"; } diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/Config_wwise.h b/Gems/AudioEngineWwise/Code/Source/Engine/Config_wwise.h index ad2ba28269..7fabfb75b3 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/Config_wwise.h +++ b/Gems/AudioEngineWwise/Code/Source/Engine/Config_wwise.h @@ -46,7 +46,7 @@ namespace Audio::Wwise ~PlatformMapping() = default; // Serialized Data... - AZStd::string m_assetPlatform; // LY Asset Platform name (i.e. "pc", "osx_gl", "es3", ...) + AZStd::string m_assetPlatform; // LY Asset Platform name (i.e. "pc", "mac", "android", ...) AZStd::string m_altAssetPlatform; // Some platforms can be run using a different asset platform. Useful for builder worker. AZStd::string m_enginePlatform; // LY Engine Platform name (i.e. "Windows", "Mac", "Android", ...) AZStd::string m_wwisePlatform; // Wwise Platform name (i.e. "Windows", "Mac", "Android", ...) diff --git a/Gems/AudioEngineWwise/Tools/WwiseConfig/Platform/Android/wwise_config_android.json b/Gems/AudioEngineWwise/Tools/WwiseConfig/Platform/Android/wwise_config_android.json index 22cc632cbd..38f6ff142e 100644 --- a/Gems/AudioEngineWwise/Tools/WwiseConfig/Platform/Android/wwise_config_android.json +++ b/Gems/AudioEngineWwise/Tools/WwiseConfig/Platform/Android/wwise_config_android.json @@ -1,5 +1,5 @@ { - "assetPlatform": "es3", + "assetPlatform": "android", "altAssetPlatform": "", "enginePlatform": "Android", "wwisePlatform": "Android", diff --git a/Gems/AudioEngineWwise/Tools/WwiseConfig/Platform/Mac/wwise_config_mac.json b/Gems/AudioEngineWwise/Tools/WwiseConfig/Platform/Mac/wwise_config_mac.json index 4069d8add7..a996b85150 100644 --- a/Gems/AudioEngineWwise/Tools/WwiseConfig/Platform/Mac/wwise_config_mac.json +++ b/Gems/AudioEngineWwise/Tools/WwiseConfig/Platform/Mac/wwise_config_mac.json @@ -1,5 +1,5 @@ { - "assetPlatform": "osx_gl", + "assetPlatform": "mac", "altAssetPlatform": "", "enginePlatform": "Mac", "wwisePlatform": "Mac", diff --git a/Gems/LyShine/Assets/Editor/Icons/Viewport/Canvas_Background.tif.assetinfo b/Gems/LyShine/Assets/Editor/Icons/Viewport/Canvas_Background.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShine/Assets/Editor/Icons/Viewport/Canvas_Background.tif.assetinfo +++ b/Gems/LyShine/Assets/Editor/Icons/Viewport/Canvas_Background.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleFrame.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleFrame.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleFrame.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleFrame.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleGradient.png.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleGradient.png.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleGradient.png.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleGradient.png.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/Circle_Shadow.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/Circle_Shadow.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/Circle_Shadow.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/Circle_Shadow.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTest.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTest.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTest.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTest.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTestPow2.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTestPow2.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTestPow2.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTestPow2.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ParticleGlow.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ParticleGlow.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ParticleGlow.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ParticleGlow.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/button.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/button.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/button.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/button.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonPressed.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonPressed.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonPressed.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonPressed.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonSlider.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonSlider.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonSlider.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonSlider.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkbox_spritesheet.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkbox_spritesheet.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkbox_spritesheet.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkbox_spritesheet.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkered3.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkered3.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkered3.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkered3.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/empty_icon.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/empty_icon.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/empty_icon.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/empty_icon.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/fixed_image.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/fixed_image.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/fixed_image.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/fixed_image.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/flipbook_walking.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/flipbook_walking.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/flipbook_walking.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/flipbook_walking.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/mask.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/mask.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/mask.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/mask.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outline.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outline.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outline.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outline.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outlineRounded.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outlineRounded.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outlineRounded.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outlineRounded.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/panelBkgd.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/panelBkgd.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/panelBkgd.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/panelBkgd.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02_big.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02_big.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02_big.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02_big.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical_big.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical_big.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical_big.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical_big.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03_big.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03_big.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03_big.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03_big.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_1.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_1.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_1.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_1.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_10.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_10.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_10.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_10.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_2.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_2.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_2.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_2.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_3.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_3.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_3.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_3.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_4.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_4.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_4.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_4.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_5.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_5.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_5.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_5.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_6.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_6.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_6.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_6.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_7.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_7.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_7.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_7.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_8.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_8.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_8.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_8.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_9.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_9.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_9.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_9.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_map.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_map.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_map.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_map.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/selected.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/selected.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/selected.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/selected.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInside2.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInside2.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInside2.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInside2.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInsideSquare.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInsideSquare.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInsideSquare.tif.assetinfo +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInsideSquare.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/NvCloth/Assets/Objects/cloth/Chicken/Actor/chicken_diff.png.imagesettings b/Gems/NvCloth/Assets/Objects/cloth/Chicken/Actor/chicken_diff.png.imagesettings index dd621c891f..adbf7d20f9 100644 --- a/Gems/NvCloth/Assets/Objects/cloth/Chicken/Actor/chicken_diff.png.imagesettings +++ b/Gems/NvCloth/Assets/Objects/cloth/Chicken/Actor/chicken_diff.png.imagesettings @@ -17,7 +17,7 @@ - + @@ -36,7 +36,7 @@ - + diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/anodized_metal_diff.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/anodized_metal_diff.tif.exportsettings index 8d01ab1ac2..e97c4e452c 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/anodized_metal_diff.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/anodized_metal_diff.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="es3:0,ios:0,osx_gl:0,pc:2,provo:0,wiiu:0" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="android:0,ios:0,mac:0,pc:2,provo:0,wiiu:0" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/brushed_steel_ddna.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/brushed_steel_ddna.tif.exportsettings index f1f2f06410..a098bdcad9 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/brushed_steel_ddna.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/brushed_steel_ddna.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="es3:1,ios:1,osx_gl:1,pc:0,provo:1,wiiu:1" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="android:1,ios:1,mac:1,pc:0,provo:1,wiiu:1" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/dark_leather_diff.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/dark_leather_diff.tif.exportsettings index 2a29854fae..19e899701a 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/dark_leather_diff.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/dark_leather_diff.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="es3:1,ios:1,osx_gl:1,pc:0,provo:1,wiiu:1" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="android:1,ios:1,mac:1,pc:0,provo:1,wiiu:1" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/galvanized_steel_spec.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/galvanized_steel_spec.tif.exportsettings index 93bcddc494..08861692ea 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/galvanized_steel_spec.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/galvanized_steel_spec.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Reflectance /reduce="es3:0,ios:0,osx_gl:0,pc:1,provo:0,wiiu:0" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Reflectance /reduce="android:0,ios:0,mac:0,pc:1,provo:0,wiiu:0" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/leather_ddna.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/leather_ddna.tif.exportsettings index f1f2f06410..a098bdcad9 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/leather_ddna.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/leather_ddna.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="es3:1,ios:1,osx_gl:1,pc:0,provo:1,wiiu:1" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="android:1,ios:1,mac:1,pc:0,provo:1,wiiu:1" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/light_leather_diff.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/light_leather_diff.tif.exportsettings index 2a29854fae..19e899701a 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/light_leather_diff.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/light_leather_diff.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="es3:1,ios:1,osx_gl:1,pc:0,provo:1,wiiu:1" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="android:1,ios:1,mac:1,pc:0,provo:1,wiiu:1" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/mixed_stones_ddna.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/mixed_stones_ddna.tif.exportsettings index f1f2f06410..a098bdcad9 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/mixed_stones_ddna.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/mixed_stones_ddna.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="es3:1,ios:1,osx_gl:1,pc:0,provo:1,wiiu:1" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="android:1,ios:1,mac:1,pc:0,provo:1,wiiu:1" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/mixed_stones_diff.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/mixed_stones_diff.tif.exportsettings index 2a29854fae..19e899701a 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/mixed_stones_diff.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/mixed_stones_diff.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="es3:1,ios:1,osx_gl:1,pc:0,provo:1,wiiu:1" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="android:1,ios:1,mac:1,pc:0,provo:1,wiiu:1" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/red_diff.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/red_diff.tif.exportsettings index 54586c2db1..48c18e1fe4 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/red_diff.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/red_diff.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="es3:0,ios:0,osx_gl:0,pc:3,provo:0,wiiu:0" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="android:0,ios:0,mac:0,pc:3,provo:0,wiiu:0" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rotary_brushed_steel_ddna.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rotary_brushed_steel_ddna.tif.exportsettings index f1f2f06410..a098bdcad9 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rotary_brushed_steel_ddna.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rotary_brushed_steel_ddna.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="es3:1,ios:1,osx_gl:1,pc:0,provo:1,wiiu:1" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="android:1,ios:1,mac:1,pc:0,provo:1,wiiu:1" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rust_ddna.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rust_ddna.tif.exportsettings index f1f2f06410..a098bdcad9 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rust_ddna.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rust_ddna.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="es3:1,ios:1,osx_gl:1,pc:0,provo:1,wiiu:1" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="android:1,ios:1,mac:1,pc:0,provo:1,wiiu:1" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rust_diff.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rust_diff.tif.exportsettings index 2a29854fae..19e899701a 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rust_diff.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/rust_diff.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="es3:1,ios:1,osx_gl:1,pc:0,provo:1,wiiu:1" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce="android:1,ios:1,mac:1,pc:0,provo:1,wiiu:1" diff --git a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/wood_planks_ddna.tif.exportsettings b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/wood_planks_ddna.tif.exportsettings index f1f2f06410..a098bdcad9 100644 --- a/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/wood_planks_ddna.tif.exportsettings +++ b/Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/wood_planks_ddna.tif.exportsettings @@ -1 +1 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="es3:1,ios:1,osx_gl:1,pc:0,provo:1,wiiu:1" +/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce="android:1,ios:1,mac:1,pc:0,provo:1,wiiu:1" diff --git a/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp b/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp index 7069f9a05d..3aeb3ad797 100644 --- a/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp +++ b/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp @@ -328,7 +328,7 @@ namespace PhysX physx::PxMeshMidPhase::Enum ret = physx::PxMeshMidPhase::eBVH34; // Fallback to 3.3 on Android and iOS platforms since they don't support SSE2, which is required for 3.4 - if (platformIdentifier == "es3" || platformIdentifier == "ios") + if (platformIdentifier == "android" || platformIdentifier == "ios") { ret = physx::PxMeshMidPhase::eBVH33; } diff --git a/Gems/PhysXSamples/Assets/Characters/Cowboy/Actor/Textures/Cowboy_01_ddna.tif.imagesettings b/Gems/PhysXSamples/Assets/Characters/Cowboy/Actor/Textures/Cowboy_01_ddna.tif.imagesettings index c2fe2400cb..9da169c456 100644 --- a/Gems/PhysXSamples/Assets/Characters/Cowboy/Actor/Textures/Cowboy_01_ddna.tif.imagesettings +++ b/Gems/PhysXSamples/Assets/Characters/Cowboy/Actor/Textures/Cowboy_01_ddna.tif.imagesettings @@ -17,7 +17,7 @@ - + @@ -81,7 +81,7 @@ - + diff --git a/Gems/PhysXSamples/Assets/Characters/Cowboy/Actor/Textures/Cowboy_01_spec.tif.imagesettings b/Gems/PhysXSamples/Assets/Characters/Cowboy/Actor/Textures/Cowboy_01_spec.tif.imagesettings index c3632028c2..43410a50df 100644 --- a/Gems/PhysXSamples/Assets/Characters/Cowboy/Actor/Textures/Cowboy_01_spec.tif.imagesettings +++ b/Gems/PhysXSamples/Assets/Characters/Cowboy/Actor/Textures/Cowboy_01_spec.tif.imagesettings @@ -17,7 +17,7 @@ - + @@ -81,7 +81,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check_Background.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check_Background.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check_Background.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check_Background.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Cross.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Cross.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Cross.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Cross.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Off.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Off.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Off.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Off.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_On.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_On.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_On.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_On.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Disabled.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Disabled.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Disabled.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Disabled.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Hover.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Hover.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Hover.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Hover.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Normal.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Normal.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Disabled.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Disabled.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Disabled.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Disabled.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Hover.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Hover.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Hover.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Hover.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Normal.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Normal.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Sliced.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Sliced.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Sliced.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Sliced.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Stretch.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Stretch.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Stretch.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Stretch.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Manipulator.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Manipulator.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Slider_Manipulator.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Manipulator.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Sliced.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Sliced.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Sliced.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Sliced.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Stretch.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Stretch.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Stretch.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Stretch.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.assetinfo +++ b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Arrow.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Arrow.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Arrow.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Arrow.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowL.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowL.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowL.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowL.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowR.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowR.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowR.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowR.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowU.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowU.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowU.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowU.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Button.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Button.tif.assetinfo index 95b548a2eb..f808dda121 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Button.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Button.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Menu.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Menu.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Menu.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Menu.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Disabled.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Disabled.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Disabled.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Hover.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Hover.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Hover.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Hover.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Normal.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Dot.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Dot.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Dot.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Dot.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/button_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/button_disabled.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/button_disabled.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/button_disabled.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/button_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/button_normal.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/button_normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/button_normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_disabled.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_disabled.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_disabled.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_hover.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_hover.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_hover.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_hover.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_normal.tif.assetinfo index 2eb5be8e93..54e075dd32 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -56,7 +56,7 @@ - + @@ -64,7 +64,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_check.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_check.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_check.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_check.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_handle.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_handle.tif.assetinfo index 95b548a2eb..f808dda121 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_handle.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_handle.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_horiz_track.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_horiz_track.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_horiz_track.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_horiz_track.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_vert_track.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_vert_track.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_vert_track.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_vert_track.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_disabled.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_disabled.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_disabled.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_normal.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_disabled.tif.assetinfo index 95b548a2eb..f808dda121 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_disabled.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_disabled.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_normal.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_disabled.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_disabled.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_disabled.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_normal.tif.assetinfo index 61b2832ff3..47b628d60a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_disabled.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_disabled.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_disabled.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_hover.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_hover.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_hover.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_hover.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_normal.tif.assetinfo index c6f6ca1e9c..c8704c4e0d 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_normal.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_normal.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/tooltip_sliced.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/tooltip_sliced.tif.assetinfo index dd1d22706e..e508d7465a 100644 --- a/Gems/UiBasics/Assets/UI/Textures/Prefab/tooltip_sliced.tif.assetinfo +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/tooltip_sliced.tif.assetinfo @@ -17,7 +17,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/Registry/AssetProcessorPlatformConfig.setreg b/Registry/AssetProcessorPlatformConfig.setreg index 5f397db06b..7407fb18db 100644 --- a/Registry/AssetProcessorPlatformConfig.setreg +++ b/Registry/AssetProcessorPlatformConfig.setreg @@ -24,13 +24,13 @@ "Platform pc": { "tags": "tools,renderer,dx12,vulkan,null" }, - "Platform es3": { + "Platform android": { "tags": "android,mobile,renderer,vulkan" }, "Platform ios": { "tags": "mobile,renderer,metal" }, - "Platform osx_gl": { + "Platform mac": { "tags": "tools,renderer,metal,null" }, // this is an example of a headless platform that has no renderer. @@ -42,10 +42,10 @@ // 'enabled' is AUTOMATICALLY TRUE for the current platform that you are running on, so it is not necessary to force it to true for that platform // To enable any additional platform, just uncomment the appropriate line below. "Platforms": { - //"pc": "enabled", - //"es3": "enabled", + "pc": "enabled", + //"android": "enabled", //"ios": "enabled", - //"osx_gl": "enabled", + "mac": "enabled", //"server": "enabled" }, // ---- The number of worker jobs, 0 means use the number of Logical Cores @@ -95,11 +95,11 @@ // "exclude": "(comma seperated platform tags or identifiers)" // } // For example if you want to include a scan folder only for platforms that have the platform tags tools and renderer - // but omit it for platform osx_gl, you will have a scanfolder rule like + // but omit it for platform mac, you will have a scanfolder rule like // "ScanFolder (unique identifier)": { // "watch": "@ROOT@/foo", // "include": "tools, renderer", - // "exclude": "osx_gl" + // "exclude": "mac" // } "ScanFolder Game": { diff --git a/Registry/bootstrap.setreg b/Registry/bootstrap.setreg index b0c954a127..ccbf744232 100644 --- a/Registry/bootstrap.setreg +++ b/Registry/bootstrap.setreg @@ -8,9 +8,9 @@ "ios_remote_filesystem": 0, "mac_remote_filesystem": 0, "assets": "pc", - "android_assets": "es3", + "android_assets": "android", "ios_assets": "ios", - "mac_assets": "osx_gl", + "mac_assets": "mac", "allowed_list": "", "remote_ip": "127.0.0.1", "remote_port": 45643, diff --git a/Tools/LyTestTools/ly_test_tools/_internal/managers/platforms/mac.py b/Tools/LyTestTools/ly_test_tools/_internal/managers/platforms/mac.py index 453e80ac41..4e19a3955a 100755 --- a/Tools/LyTestTools/ly_test_tools/_internal/managers/platforms/mac.py +++ b/Tools/LyTestTools/ly_test_tools/_internal/managers/platforms/mac.py @@ -21,8 +21,8 @@ from ly_test_tools._internal.managers.abstract_resource_locator import AbstractR logger = logging.getLogger(__name__) -CACHE_DIR = 'osx_gl' -CONFIG_FILE = 'system_osx_osx_gl.cfg' +CACHE_DIR = 'mac' +CONFIG_FILE = 'system_osx_mac.cfg' class _MacResourceLocator(AbstractResourceLocator): @@ -33,7 +33,7 @@ class _MacResourceLocator(AbstractResourceLocator): def platform_config_file(self): """ Return the path to the platform config file. - ex. engine_root/dev/system_osx_osx_gl.cfg + ex. engine_root/dev/system_osx_mac.cfg :return: path to the platform config file """ return os.path.join(self.engine_root(), CONFIG_FILE) diff --git a/Tools/LyTestTools/ly_test_tools/_internal/managers/platforms/windows.py b/Tools/LyTestTools/ly_test_tools/_internal/managers/platforms/windows.py index 80ac413dbb..db6e7d713d 100755 --- a/Tools/LyTestTools/ly_test_tools/_internal/managers/platforms/windows.py +++ b/Tools/LyTestTools/ly_test_tools/_internal/managers/platforms/windows.py @@ -39,7 +39,7 @@ class _WindowsResourceLocator(AbstractResourceLocator): def platform_config_file(self): """ Return the path to the platform config file. - ex. engine_root/dev/system_osx_osx_gl.cfg + ex. engine_root/dev/system_osx_mac.cfg :return: path to the platform config file """ return os.path.join(self.engine_root(), CONFIG_FILE) diff --git a/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py b/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py index d8b08cad24..8e2b93c20a 100644 --- a/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py +++ b/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py @@ -36,10 +36,10 @@ DEFAULT_TIMEOUT_HOURS = 8 DEFAULT_TIMEOUT_SECONDS = 300 ASSET_PROCESSOR_PLATFORM_MAP = { - 'android': 'es3', + 'android': 'android', 'ios': 'ios', 'linux': 'linux', # Not fully implemented, see SPEC-2501 - 'mac': 'osx_gl', + 'mac': 'mac', 'windows': 'pc', } diff --git a/cmake/Platform/Android/PAL_android.cmake b/cmake/Platform/Android/PAL_android.cmake index bb4ac5f32b..5f35767f98 100644 --- a/cmake/Platform/Android/PAL_android.cmake +++ b/cmake/Platform/Android/PAL_android.cmake @@ -35,7 +35,7 @@ else() endif() # Set the default asset type for deployment -set(LY_ASSET_DEPLOY_ASSET_TYPE "es3" CACHE STRING "Set the asset type for deployment.") +set(LY_ASSET_DEPLOY_ASSET_TYPE "android" CACHE STRING "Set the asset type for deployment.") # Set the python cmd tool if(PAL_HOST_PLATFORM_NAME_LOWERCASE STREQUAL "windows") diff --git a/cmake/Platform/Mac/PAL_mac.cmake b/cmake/Platform/Mac/PAL_mac.cmake index f6cf034312..988d36af14 100644 --- a/cmake/Platform/Mac/PAL_mac.cmake +++ b/cmake/Platform/Mac/PAL_mac.cmake @@ -35,7 +35,7 @@ else() endif() # Set the default asset type for deployment -set(LY_ASSET_DEPLOY_ASSET_TYPE "osx_gl" CACHE STRING "Set the asset type for deployment.") +set(LY_ASSET_DEPLOY_ASSET_TYPE "mac" CACHE STRING "Set the asset type for deployment.") # Set the python cmd tool ly_set(LY_PYTHON_CMD ${CMAKE_CURRENT_SOURCE_DIR}/python/python.sh) diff --git a/cmake/Tools/Platform/Android/android_deployment.py b/cmake/Tools/Platform/Android/android_deployment.py index 8a76270df1..eb8361ec18 100755 --- a/cmake/Tools/Platform/Android/android_deployment.py +++ b/cmake/Tools/Platform/Android/android_deployment.py @@ -62,7 +62,7 @@ class AndroidDeployment(object): :param deployment_type: The type of deployment (DEPLOY_APK_ONLY, DEPLOY_ASSETS_ONLY, or DEPLOY_BOTH) :param game_name: The name of the game whose assets are being deployed. None if is_test_project is True :param asset_mode: The asset mode of deployment (LOOSE, PAK, VFS). None if is_test_project is True - :param asset_type: The asset type (for android, 'es3'). None if is_test_project is True + :param asset_type: The asset type. None if is_test_project is True :param embedded_assets: Boolean to indicate if the assets are embedded in the APK or not :param is_unit_test: Boolean to indicate if this is a unit test deployment """ diff --git a/cmake/Tools/Platform/Android/generate_android_project.py b/cmake/Tools/Platform/Android/generate_android_project.py index f3f6a3acda..9a0e2760f5 100755 --- a/cmake/Tools/Platform/Android/generate_android_project.py +++ b/cmake/Tools/Platform/Android/generate_android_project.py @@ -118,7 +118,7 @@ ASSET_MODE_LOOSE = 'LOOSE' ASSET_MODE_VFS = 'VFS' ALL_ASSET_MODES = [ASSET_MODE_PAK, ASSET_MODE_LOOSE, ASSET_MODE_VFS] ASSET_TYPE_ARGUMENT_NAME = '--asset-type' -DEFAULT_ASSET_TYPE = 'es3' +DEFAULT_ASSET_TYPE = 'android' def wrap_parsed_args(parsed_args): diff --git a/cmake/Tools/Platform/Android/unit_test_android_deployment.py b/cmake/Tools/Platform/Android/unit_test_android_deployment.py index 011033649a..5ee168ca30 100755 --- a/cmake/Tools/Platform/Android/unit_test_android_deployment.py +++ b/cmake/Tools/Platform/Android/unit_test_android_deployment.py @@ -21,7 +21,7 @@ from cmake.Tools.Platform.Android import android_deployment TEST_GAME_NAME = "Foo" TEST_DEV_ROOT = pathlib.Path("Foo") TEST_ASSET_MODE = 'LOOSE' -TEST_ASSET_TYPE = 'es3' +TEST_ASSET_TYPE = 'android' TEST_ANDROID_SDK_PATH = pathlib.Path('c:\\AndroidSDK') TEST_BUILD_DIR = 'android_gradle_test' TEST_DEVICE_ID = '9A201FFAZ000ER' @@ -661,10 +661,10 @@ def test_execute_success(tmpdir, test_config, test_package_name, test_device_sto @pytest.mark.parametrize( "test_game_name, test_config, test_package_name, test_device_storage_path, test_asset_type", [ - pytest.param('game1','profile', 'com.amazon.lumberyard.foo', '/data/fool_storage', 'es3'), - pytest.param('game1','debug', 'com.amazon.lumberyard.foo', '/data/fool_storage', 'es3'), - pytest.param('game2','profile', 'com.amazon.lumberyard.bar', '/data/fool_storage', 'es3'), - pytest.param('game2','debug', 'com.amazon.lumberyard.bar', '/data/fool_storage', 'es3'), + pytest.param('game1','profile', 'com.amazon.lumberyard.foo', '/data/fool_storage', 'android'), + pytest.param('game1','debug', 'com.amazon.lumberyard.foo', '/data/fool_storage', 'android'), + pytest.param('game2','profile', 'com.amazon.lumberyard.bar', '/data/fool_storage', 'android'), + pytest.param('game2','debug', 'com.amazon.lumberyard.bar', '/data/fool_storage', 'android'), pytest.param('game3','profile', 'com.amazon.lumberyard.foo', '/data/fool_storage2', 'pc'), pytest.param('game3','debug', 'com.amazon.lumberyard.foo', '/data/fool_storage2', 'pc'), pytest.param('game4','profile', 'com.amazon.lumberyard.bar', '/data/fool_storage2', 'pc'), diff --git a/scripts/build/Platform/Android/build_config.json b/scripts/build/Platform/Android/build_config.json index d0fce80964..fe5e223612 100644 --- a/scripts/build/Platform/Android/build_config.json +++ b/scripts/build/Platform/Android/build_config.json @@ -99,7 +99,7 @@ "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", "ASSET_PROCESSOR_BINARY": "bin\\profile\\AssetProcessorBatch.exe", "ASSET_PROCESSOR_OPTIONS": "/zeroAnalysisMode --regset=\"/Amazon/AssetProcessor/Settings/Exclude Android/pattern=.*/DiffuseGlobalIllumination/.*precompiledshader\"", - "ASSET_PROCESSOR_PLATFORMS":"es3" + "ASSET_PROCESSOR_PLATFORMS":"android" } }, "release": { diff --git a/scripts/build/Platform/Mac/build_config.json b/scripts/build/Platform/Mac/build_config.json index f312279fe6..bcaffce880 100644 --- a/scripts/build/Platform/Mac/build_config.json +++ b/scripts/build/Platform/Mac/build_config.json @@ -86,7 +86,7 @@ "CMAKE_TARGET": "AssetProcessorBatch", "ASSET_PROCESSOR_BINARY": "bin/profile/AssetProcessorBatch", "ASSET_PROCESSOR_OPTIONS": "/zeroAnalysisMode", - "ASSET_PROCESSOR_PLATFORMS": "osx_gl" + "ASSET_PROCESSOR_PLATFORMS": "mac" } }, "periodic_test_profile": { diff --git a/scripts/bundler/gen_shaders.py b/scripts/bundler/gen_shaders.py index 46857179b1..bfb60287af 100644 --- a/scripts/bundler/gen_shaders.py +++ b/scripts/bundler/gen_shaders.py @@ -163,11 +163,11 @@ def add_shaders_types(): shaders.append(gl4) gles3 = _ShaderType('GLES3', 'GLSL_HLSLcc') - gles3.add_configuration('Android', 'es3') + gles3.add_configuration('Android', 'android') shaders.append(gles3) metal = _ShaderType('METAL', 'METAL_LLVM_DXC') - metal.add_configuration('Mac', 'osx_gl') + metal.add_configuration('Mac', 'mac') metal.add_configuration('iOS', 'ios') shaders.append(metal) diff --git a/system_android_es3.cfg b/system_android_android.cfg similarity index 93% rename from system_android_es3.cfg rename to system_android_android.cfg index 46ab50f558..d5bfddeb73 100644 --- a/system_android_es3.cfg +++ b/system_android_android.cfg @@ -1,4 +1,4 @@ --- config file used when the android platform is running off 'es3' assets. +-- config file used when the android platform is running off 'android' assets. sys_float_exceptions=0 log_IncludeTime=1 sys_PakLogInvalidFileAccess=1 diff --git a/system_mac_osx_gl.cfg b/system_mac_mac.cfg similarity index 100% rename from system_mac_osx_gl.cfg rename to system_mac_mac.cfg From 053e273b97bcacb191886afcad15c917addfa45c Mon Sep 17 00:00:00 2001 From: srikappa Date: Wed, 26 May 2021 18:24:49 -0700 Subject: [PATCH 194/811] Clear dirty entities at the end of InstantiatePrefab logic --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index d3553c78e1..1b98711352 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -384,7 +384,10 @@ namespace AzToolsFramework CreateLink(instanceToCreate->get(), instanceToParentUnder->get().GetTemplateId(), undoBatch.GetUndoBatch(), AZStd::move(patch)); // Update the cache - this prevents these changes from being stored in the regular undo/redo nodes - m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter)); + //m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter)); + + AzToolsFramework::ToolsApplicationRequestBus::Broadcast( + &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); } return AZ::Success(); From 84cf3bffde3ba8202923bcbb2c82f56aed777a13 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 26 May 2021 20:49:52 -0500 Subject: [PATCH 195/811] Updating the Install_common.cmake script to copy over the source engine.json templates array to the generated installed engine.json --- cmake/O3DEJson.cmake | 45 +++++++++++++--------- cmake/Platform/Common/Install_common.cmake | 15 +++++--- cmake/install/engine.json.in | 2 +- 3 files changed, 37 insertions(+), 25 deletions(-) diff --git a/cmake/O3DEJson.cmake b/cmake/O3DEJson.cmake index 5d748e9681..ab5f95bc8c 100644 --- a/cmake/O3DEJson.cmake +++ b/cmake/O3DEJson.cmake @@ -14,35 +14,42 @@ include_guard() set(LY_EXTERNAL_SUBDIRS "" CACHE STRING "List of subdirectories to recurse into when running cmake against the engine's CMakeLists.txt") #! read_json_external_subdirs -# Read the "external_subdirectories" array from a *.json file -# External subdirectories are any folders with CMakeLists.txt in them -# This could be regular subdirectories, Gems(contains an additional gem.json), -# Restricted folders(contains an additional restricted.json), etc... -# -# \arg:output_external_subdirs name of output variable to store external subdirectories into -# \arg:input_json_path path to the *.json file to load and read the external subdirectories from -# \return: external subdirectories as is from the json file. +# Read the "external_subdirectories" array from a *.json file +# External subdirectories are any folders with CMakeLists.txt in them +# This could be regular subdirectories, Gems(contains an additional gem.json), +# Restricted folders(contains an additional restricted.json), etc... +# +# \arg:output_external_subdirs name of output variable to store external subdirectories into +# \arg:input_json_path path to the *.json file to load and read the external subdirectories from +# \return: external subdirectories as is from the json file. function(read_json_external_subdirs output_external_subdirs input_json_path) + o3de_read_json_array(json_array ${input_json_path} "external_subdirectories") + set(${output_external_subdirs} ${json_array} PARENT_SCOPE) +endfunction() + +#! read_json_array +# Reads the a json array field into a cmake list variable +function(o3de_read_json_array read_output_array input_json_path array_key) file(READ ${input_json_path} manifest_json_data) - string(JSON external_subdirs_count ERROR_VARIABLE manifest_json_error - LENGTH ${manifest_json_data} "external_subdirectories") + string(JSON array_count ERROR_VARIABLE manifest_json_error + LENGTH ${manifest_json_data} ${array_key}) if(manifest_json_error) - # There is "external_subdirectories" key, so theire are no subdirectories to read + # There is no key, return return() endif() - if(external_subdirs_count GREATER 0) - math(EXPR external_subdir_range "${external_subdirs_count}-1") - foreach(external_subdir_index RANGE ${external_subdir_range}) - string(JSON external_subdir ERROR_VARIABLE manifest_json_error - GET ${manifest_json_data} "external_subdirectories" "${external_subdir_index}") + if(array_count GREATER 0) + math(EXPR array_range "${array_count}-1") + foreach(array_index RANGE ${array_range}) + string(JSON array_element ERROR_VARIABLE manifest_json_error + GET ${manifest_json_data} ${array_key} "${array_index}") if(manifest_json_error) - message(FATAL_ERROR "Error reading field at index ${external_subdir_index} in \"external_subdirectories\" JSON array: ${manifest_json_error}") + message(FATAL_ERROR "Error reading field at index ${array_index} in \"${array_key}\" JSON array: ${manifest_json_error}") endif() - list(APPEND external_subdirs ${external_subdir}) + list(APPEND array_elements ${array_element}) endforeach() endif() - set(${output_external_subdirs} ${external_subdirs} PARENT_SCOPE) + set(${read_output_array} ${array_elements} PARENT_SCOPE) endfunction() function(o3de_read_json_key output_value input_json_path key) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 7bf71d7e01..04f0a0ff23 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -225,14 +225,19 @@ function(ly_setup_cmake_install) ) # Transform the LY_EXTERNAL_SUBDIRS list into a json array - set(LY_INSTALL_EXTERNAL_SUBDIRS "[]") - set(external_subdir_index "0") + set(indent " ") foreach(external_subdir ${LY_EXTERNAL_SUBDIRS}) - math(EXPR external_subdir_index "${external_subdir_index} + 1") file(RELATIVE_PATH engine_rel_external_subdir ${LY_ROOT_FOLDER} ${external_subdir}) - string(JSON LY_INSTALL_EXTERNAL_SUBDIRS ERROR_VARIABLE external_subdir_error SET ${LY_INSTALL_EXTERNAL_SUBDIRS} - ${external_subdir_index} "\"${engine_rel_external_subdir}\"") + list(APPEND relative_external_subdirs "\"${engine_rel_external_subdir}\"") endforeach() + list(JOIN relative_external_subdirs ",\n${indent}" LY_INSTALL_EXTERNAL_SUBDIRS) + + # Read the "templates" key from the source engine.json + o3de_read_json_array(engine_templates ${LY_ROOT_FOLDER}/engine.json "templates") + foreach(template_path ${engine_templates}) + list(APPEND relative_templates "\"${template_path}\"") + endforeach() + list(JOIN relative_templates ",\n${indent}" LY_INSTALL_TEMPLATES) configure_file(${LY_ROOT_FOLDER}/cmake/install/engine.json.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/engine.json @ONLY) diff --git a/cmake/install/engine.json.in b/cmake/install/engine.json.in index 1cfb1826ce..ce2e1be25c 100644 --- a/cmake/install/engine.json.in +++ b/cmake/install/engine.json.in @@ -5,7 +5,7 @@ "O3DEVersion": "@LY_VERSION_STRING@", "O3DECopyrightYear": @LY_VERSION_COPYRIGHT_YEAR@, "O3DEBuildNumber": @LY_VERSION_BUILD_NUMBER@, - "external_subdirectories": @LY_INSTALL_EXTERNAL_SUBDIRS@, + "external_subdirectories": [@LY_INSTALL_EXTERNAL_SUBDIRS@], "projects": [@LY_INSTALL_PROJECTS@], "templates": [@LY_INSTALL_TEMPLATES@] } From 17e9c17f311bca70b61b3295c4aef49d23a2dd46 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Wed, 26 May 2021 19:18:18 -0700 Subject: [PATCH 196/811] Added Occlusion Culling Planes and RPI Culling support for Masked Occlusion Culling --- ...ionCullingPlaneFeatureProcessorInterface.h | 41 +++++ .../Code/Source/CommonSystemComponent.cpp | 4 + .../OcclusionCullingPlaneFeatureProcessor.cpp | 96 ++++++++++ .../OcclusionCullingPlaneFeatureProcessor.h | 75 ++++++++ .../Code/atom_feature_common_files.cmake | 2 + .../atom_feature_common_public_files.cmake | 1 + .../Code/Include/Atom/RPI.Public/Culling.h | 12 +- .../RPI/Code/Include/Atom/RPI.Public/View.h | 12 +- .../Source/Platform/Windows/PAL_windows.cmake | 13 ++ .../RPI/Code/Source/RPI.Public/Culling.cpp | 171 +++++++++++++----- .../Atom/RPI/Code/Source/RPI.Public/Scene.cpp | 3 +- Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp | 68 ++++++- .../Atom/RPI/Code/atom_rpi_public_files.cmake | 4 + .../CommonFeatures/Code/Source/Module.cpp | 4 + .../EditorOcclusionCullingPlaneComponent.cpp | 91 ++++++++++ .../EditorOcclusionCullingPlaneComponent.h | 43 +++++ .../OcclusionCullingPlaneComponent.cpp | 43 +++++ .../OcclusionCullingPlaneComponent.h | 37 ++++ .../OcclusionCullingPlaneComponentConstants.h | 22 +++ ...clusionCullingPlaneComponentController.cpp | 137 ++++++++++++++ ...OcclusionCullingPlaneComponentController.h | 78 ++++++++ ...egration_commonfeatures_editor_files.cmake | 2 + ...omlyintegration_commonfeatures_files.cmake | 4 + 23 files changed, 913 insertions(+), 50 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Code/Include/Atom/Feature/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessorInterface.h create mode 100644 Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp create mode 100644 Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.h create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponent.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponent.h create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentConstants.h create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.h diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessorInterface.h new file mode 100644 index 0000000000..07a6179e78 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessorInterface.h @@ -0,0 +1,41 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include +#include + +namespace AZ +{ + namespace Render + { + class OcclusionCullingPlane; + + using OcclusionCullingPlaneHandle = AZStd::shared_ptr; + + // OcclusionCullingPlaneFeatureProcessorInterface provides an interface to the feature processor for code outside of Atom + class OcclusionCullingPlaneFeatureProcessorInterface + : public RPI::FeatureProcessor + { + public: + AZ_RTTI(AZ::Render::OcclusionCullingPlaneFeatureProcessorInterface, "{50F6B45E-A622-44EC-B962-DE25FBD44095}"); + + virtual OcclusionCullingPlaneHandle AddOcclusionCullingPlane(const AZ::Transform& transform) = 0; + virtual void RemoveOcclusionCullingPlane(OcclusionCullingPlaneHandle& handle) = 0; + virtual bool IsValidOcclusionCullingPlaneHandle(const OcclusionCullingPlaneHandle& occlusionCullingPlane) const = 0; + virtual void SetTransform(const OcclusionCullingPlaneHandle& occlusionCullingPlane, const AZ::Transform& transform) = 0; + virtual void SetEnabled(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool enabled) = 0; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp index 089a6168b1..614e614c06 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp @@ -102,6 +102,7 @@ #include #include #include +#include namespace AZ { @@ -137,6 +138,7 @@ namespace AZ ModelPreset::Reflect(context); DiffuseProbeGridFeatureProcessor::Reflect(context); RayTracingFeatureProcessor::Reflect(context); + OcclusionCullingPlaneFeatureProcessor::Reflect(context); if (SerializeContext* serialize = azrtti_cast(context)) { @@ -193,6 +195,7 @@ namespace AZ AZ::RPI::FeatureProcessorFactory::Get()->RegisterFeatureProcessor(); AZ::RPI::FeatureProcessorFactory::Get()->RegisterFeatureProcessor(); AZ::RPI::FeatureProcessorFactory::Get()->RegisterFeatureProcessor(); + AZ::RPI::FeatureProcessorFactory::Get()->RegisterFeatureProcessor(); // Add SkyBox pass auto* passSystem = RPI::PassSystemInterface::Get(); @@ -295,6 +298,7 @@ namespace AZ AZ::RPI::FeatureProcessorFactory::Get()->UnregisterFeatureProcessor(); AZ::RPI::FeatureProcessorFactory::Get()->UnregisterFeatureProcessor(); AZ::RPI::FeatureProcessorFactory::Get()->UnregisterFeatureProcessor(); + AZ::RPI::FeatureProcessorFactory::Get()->UnregisterFeatureProcessor(); } void CommonSystemComponent::LoadPassTemplateMappings() diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp new file mode 100644 index 0000000000..d4a1a37521 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp @@ -0,0 +1,96 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + void OcclusionCullingPlaneFeatureProcessor::Reflect(ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext + ->Class() + ->Version(0); + } + } + + void OcclusionCullingPlaneFeatureProcessor::Activate() + { + m_occlusionCullingPlanes.reserve(InitialOcclusionCullingPlanesAllocationSize); + + EnableSceneNotification(); + } + + void OcclusionCullingPlaneFeatureProcessor::Deactivate() + { + AZ_Warning("OcclusionCullingPlaneFeatureProcessor", m_occlusionCullingPlanes.size() == 0, + "Deactivating the OcclusionCullingPlaneFeatureProcessor, but there are still outstanding occlusion planes. Components\n" + "using OcclusionCullingPlaneHandles should free them before the OcclusionCullingPlaneFeatureProcessor is deactivated.\n" + ); + + DisableSceneNotification(); + } + + void OcclusionCullingPlaneFeatureProcessor::Simulate([[maybe_unused]] const FeatureProcessor::SimulatePacket& packet) + { + AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + + AZStd::vector occlusionCullingPlanes; + for (auto& occlusionCullingPlane : m_occlusionCullingPlanes) + { + occlusionCullingPlanes.push_back(occlusionCullingPlane->GetTransform()); + } + GetParentScene()->GetCullingScene()->SetOcclusionCullingPlanes(occlusionCullingPlanes); + } + + OcclusionCullingPlaneHandle OcclusionCullingPlaneFeatureProcessor::AddOcclusionCullingPlane(const AZ::Transform& transform) + { + AZStd::shared_ptr occlusionCullingPlane = AZStd::make_shared(); + occlusionCullingPlane->SetTransform(transform); + m_occlusionCullingPlanes.push_back(occlusionCullingPlane); + return occlusionCullingPlane; + } + + void OcclusionCullingPlaneFeatureProcessor::RemoveOcclusionCullingPlane(OcclusionCullingPlaneHandle& occlusionCullingPlane) + { + AZ_Assert(occlusionCullingPlane.get(), "RemoveOcclusionCullingPlane called with an invalid handle"); + + auto itEntry = AZStd::find_if(m_occlusionCullingPlanes.begin(), m_occlusionCullingPlanes.end(), [&](AZStd::shared_ptr const& entry) + { + return (entry == occlusionCullingPlane); + }); + + AZ_Assert(itEntry != m_occlusionCullingPlanes.end(), "RemoveOcclusionCullingPlane called with an occlusion plane that is not in the occlusion plane list"); + m_occlusionCullingPlanes.erase(itEntry); + occlusionCullingPlane = nullptr; + } + + void OcclusionCullingPlaneFeatureProcessor::SetTransform(const OcclusionCullingPlaneHandle& occlusionCullingPlane, const AZ::Transform& transform) + { + AZ_Assert(occlusionCullingPlane.get(), "SetTransform called with an invalid handle"); + occlusionCullingPlane->SetTransform(transform); + } + + void OcclusionCullingPlaneFeatureProcessor::SetEnabled(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool enabled) + { + AZ_Assert(occlusionCullingPlane.get(), "Enable called with an invalid handle"); + occlusionCullingPlane->SetEnabled(enabled); + } + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h new file mode 100644 index 0000000000..c54c816bfd --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h @@ -0,0 +1,75 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include + +namespace AZ +{ + namespace Render + { + //! This class represents an OcclusionCullingPlane which is used to cull meshes that are inside the view frustum + class OcclusionCullingPlane final + { + public: + OcclusionCullingPlane() = default; + ~OcclusionCullingPlane() = default; + + void SetTransform(const AZ::Transform& transform) { m_transform = transform; } + const AZ::Transform& GetTransform() const { return m_transform; } + + void SetEnabled(bool enabled) { m_enabled = enabled; } + bool GetEnabled() const { return m_enabled; } + + private: + AZ::Transform m_transform; + bool m_enabled = true; + }; + + //! This class manages OcclusionCullingPlanes which are used to cull meshes that are inside the view frustum + class OcclusionCullingPlaneFeatureProcessor final + : public OcclusionCullingPlaneFeatureProcessorInterface + { + public: + AZ_RTTI(AZ::Render::OcclusionCullingPlaneFeatureProcessor, "{C3DE91D7-EF7A-4A82-A55F-E22BC52074EA}", OcclusionCullingPlaneFeatureProcessorInterface); + + static void Reflect(AZ::ReflectContext* context); + + OcclusionCullingPlaneFeatureProcessor() = default; + virtual ~OcclusionCullingPlaneFeatureProcessor() = default; + + // OcclusionCullingPlaneFeatureProcessorInterface overrides + OcclusionCullingPlaneHandle AddOcclusionCullingPlane(const AZ::Transform& transform) override; + void RemoveOcclusionCullingPlane(OcclusionCullingPlaneHandle& handle) override; + bool IsValidOcclusionCullingPlaneHandle(const OcclusionCullingPlaneHandle& occlusionCullingPlane) const override { return (occlusionCullingPlane.get() != nullptr); } + void SetTransform(const OcclusionCullingPlaneHandle& occlusionCullingPlane, const AZ::Transform& transform) override; + void SetEnabled(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool enable) override; + + // FeatureProcessor overrides + void Activate() override; + void Deactivate() override; + void Simulate(const FeatureProcessor::SimulatePacket& packet) override; + + // retrieve the full list of occlusion planes + using OcclusionCullingPlaneVector = AZStd::vector>; + OcclusionCullingPlaneVector& GetOcclusionCullingPlanes() { return m_occlusionCullingPlanes; } + + private: + AZ_DISABLE_COPY_MOVE(OcclusionCullingPlaneFeatureProcessor); + + // list of occlusion planes + const size_t InitialOcclusionCullingPlanesAllocationSize = 64; + OcclusionCullingPlaneVector m_occlusionCullingPlanes; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake index 8926b0c19f..f3ee1b4757 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -175,6 +175,8 @@ set(FILES Source/MorphTargets/MorphTargetComputePass.h Source/MorphTargets/MorphTargetDispatchItem.cpp Source/MorphTargets/MorphTargetDispatchItem.h + Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h + Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp Source/PostProcess/PostProcessBase.cpp Source/PostProcess/PostProcessBase.h Source/PostProcess/PostProcessFeatureProcessor.cpp diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake index 9034859707..3df15f9a70 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake @@ -44,6 +44,7 @@ set(FILES Include/Atom/Feature/ParamMacros/StartParamFunctionsVirtual.inl Include/Atom/Feature/ParamMacros/StartParamMembers.inl Include/Atom/Feature/ParamMacros/StartParamSerializeContext.inl + Include/Atom/Feature/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessorInterface.h Include/Atom/Feature/PostProcess/PostProcessFeatureProcessorInterface.h Include/Atom/Feature/PostProcess/PostProcessParams.inl Include/Atom/Feature/PostProcess/PostProcessSettings.inl diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h index c7e9cc4706..17e0a1f82d 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h @@ -31,7 +31,7 @@ #include #include - +#include #include #include @@ -213,8 +213,11 @@ namespace AZ void Activate(const class Scene* parentScene); void Deactivate(); + //! Sets a list of occlusion planes to be used during the culling process. + void SetOcclusionCullingPlanes(const AZStd::vector& occlusionCullingPlanes) { m_occlusionCullingPlanes = occlusionCullingPlanes; } + //! Notifies the CullingScene that culling will begin for this frame. - void BeginCulling(const AZStd::vector& views); + void BeginCulling(const AZStd::vector& views, const AZStd::vector& activePipelines); //! Notifies the CullingScene that the culling is done for this frame. void EndCulling(); @@ -251,12 +254,9 @@ namespace AZ const Scene* m_parentScene = nullptr; AzFramework::IVisibilityScene* m_visScene = nullptr; - CullingDebugContext m_debugCtx; - AZStd::concurrency_checker m_cullDataConcurrencyCheck; - - AZStd::mutex m_mutex; + AZStd::vector m_occlusionCullingPlanes; }; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h index aad099dc23..74c841d2a5 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -57,7 +58,7 @@ namespace AZ //! Only use this function to create a new view object. And force using smart pointer to manage view's life time static ViewPtr CreateView(const AZ::Name& name, UsageFlags usage); - ~View() = default; + ~View(); void SetDrawListMask(const RHI::DrawListMask& drawListMask); RHI::DrawListMask GetDrawListMask() const { return m_drawListMask; } @@ -126,6 +127,12 @@ namespace AZ //! Notifies consumers when the world to clip matrix has changed. void ConnectWorldToClipMatrixChangedHandler(MatrixChangedEvent::Handler& handler); + //! Prepare for view culling + void BeginCulling(const AZStd::vector& activePipelines); + + //! Returns the masked occlusion culling interface + MaskedOcclusionCulling* GetMaskedOcclusionCulling(); + private: View() = delete; View(const AZ::Name& name, UsageFlags usage); @@ -193,6 +200,9 @@ namespace AZ MatrixChangedEvent m_onWorldToClipMatrixChange; MatrixChangedEvent m_onWorldToViewMatrixChange; + + // Software occlusion culling + MaskedOcclusionCulling* m_maskedOcclusionCulling = nullptr; }; AZ_DEFINE_ENUM_BITWISE_OPERATORS(View::UsageFlags); diff --git a/Gems/Atom/RPI/Code/Source/Platform/Windows/PAL_windows.cmake b/Gems/Atom/RPI/Code/Source/Platform/Windows/PAL_windows.cmake index c060b8bbaa..51e42d5216 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Windows/PAL_windows.cmake +++ b/Gems/Atom/RPI/Code/Source/Platform/Windows/PAL_windows.cmake @@ -10,3 +10,16 @@ # set (PAL_TRAIT_BUILD_ATOM_RPI_ASSETS_SUPPORTED TRUE) + +ly_add_source_properties( + SOURCES Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX2.cpp + PROPERTY COMPILE_OPTIONS + VALUES /arch:AVX2 /W3 +) +ly_add_source_properties( + SOURCES + Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX512.cpp + Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCulling.cpp + PROPERTY COMPILE_OPTIONS + VALUES /W3 +) \ No newline at end of file diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index c64f08e4f8..ab25fb14fb 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -262,21 +262,24 @@ namespace AZ public: AZ_CLASS_ALLOCATOR(AddObjectsToViewJob, ThreadPoolAllocator, 0); + struct JobData + { + CullingDebugContext* m_debugCtx = nullptr; + MaskedOcclusionCulling* m_maskedOcclusionCulling = nullptr; + const Scene* m_scene = nullptr; + View* m_view = nullptr; + Frustum m_frustum; + }; + private: - CullingDebugContext* m_debugCtx; - const Scene* m_scene; - View* m_view; - Frustum m_frustum; + const AZStd::shared_ptr m_jobData; CullingScene::WorkListType m_worklist; public: - AddObjectsToViewJob(CullingDebugContext& debugCtx, const Scene& scene, View& view, Frustum& frustum, CullingScene::WorkListType& worklist) + AddObjectsToViewJob(const AZStd::shared_ptr& jobData, CullingScene::WorkListType& worklist) : Job(true, nullptr) //auto-deletes, no JobContext - , m_debugCtx(&debugCtx) - , m_scene(&scene) - , m_view(&view) - , m_frustum(frustum) //capture by value - , m_worklist(AZStd::move(worklist)) //capture by value + , m_jobData(jobData) + , m_worklist(worklist) { } @@ -285,37 +288,40 @@ namespace AZ { AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); - const View::UsageFlags viewFlags = m_view->GetUsageFlags(); - const RHI::DrawListMask drawListMask = m_view->GetDrawListMask(); + const View::UsageFlags viewFlags = m_jobData->m_view->GetUsageFlags(); + const RHI::DrawListMask drawListMask = m_jobData->m_view->GetDrawListMask(); uint32_t numDrawPackets = 0; uint32_t numVisibleCullables = 0; for (const AzFramework::IVisibilityScene::NodeData& nodeData : m_worklist) { //If a node is entirely contained within the frustum, then we can skip the fine grained culling. - bool nodeIsContainedInFrustum = ShapeIntersection::Contains(m_frustum, nodeData.m_bounds); + bool nodeIsContainedInFrustum = ShapeIntersection::Contains(m_jobData->m_frustum, nodeData.m_bounds); #ifdef AZ_CULL_PROFILE_VERBOSE AZ_PROFILE_SCOPE_DYNAMIC(Debug::ProfileCategory::AzRender, "process node (view: %s, skip fine cull: %d", m_view->GetName().GetCStr(), nodeIsContainedInFrustum ? 1 : 0); #endif - if (nodeIsContainedInFrustum || !m_debugCtx->m_enableFrustumCulling) + if (nodeIsContainedInFrustum || !m_jobData->m_debugCtx->m_enableFrustumCulling) { //Add all objects within this node to the view, without any extra culling for (AzFramework::VisibilityEntry* visibleEntry : nodeData.m_entries) { - if (visibleEntry->m_typeFlags & AzFramework::VisibilityEntry::TYPE_RPI_Cullable) + if (TestOcclusionCulling(visibleEntry) == MaskedOcclusionCulling::CullingResult::VISIBLE) { - Cullable* c = static_cast(visibleEntry->m_userData); - if ((c->m_cullData.m_drawListMask & drawListMask).none() || - c->m_cullData.m_hideFlags & viewFlags || - c->m_cullData.m_scene != m_scene) //[GFX_TODO][ATOM-13796] once the IVisibilitySystem supports multiple octree scenes, remove this + if (visibleEntry->m_typeFlags & AzFramework::VisibilityEntry::TYPE_RPI_Cullable) { - continue; + Cullable* c = static_cast(visibleEntry->m_userData); + if ((c->m_cullData.m_drawListMask & drawListMask).none() || + c->m_cullData.m_hideFlags & viewFlags || + c->m_cullData.m_scene != m_jobData->m_scene) //[GFX_TODO][ATOM-13796] once the IVisibilitySystem supports multiple octree scenes, remove this + { + continue; + } + numDrawPackets += AddLodDataToView(c->m_cullData.m_boundingSphere.GetCenter(), c->m_lodData, *m_jobData->m_view); + ++numVisibleCullables; } - numDrawPackets += AddLodDataToView(c->m_cullData.m_boundingSphere.GetCenter(), c->m_lodData, *m_view); - ++numVisibleCullables; } } } @@ -329,66 +335,69 @@ namespace AZ Cullable* c = static_cast(visibleEntry->m_userData); if ((c->m_cullData.m_drawListMask & drawListMask).none() || c->m_cullData.m_hideFlags & viewFlags || - c->m_cullData.m_scene != m_scene) //[GFX_TODO][ATOM-13796] once the IVisibilitySystem supports multiple octree scenes, remove this + c->m_cullData.m_scene != m_jobData->m_scene) //[GFX_TODO][ATOM-13796] once the IVisibilitySystem supports multiple octree scenes, remove this { continue; } - IntersectResult res = ShapeIntersection::Classify(m_frustum, c->m_cullData.m_boundingSphere); + IntersectResult res = ShapeIntersection::Classify(m_jobData->m_frustum, c->m_cullData.m_boundingSphere); if (res == IntersectResult::Exterior) { continue; } - else if (res == IntersectResult::Interior || ShapeIntersection::Overlaps(m_frustum, c->m_cullData.m_boundingObb)) + else if (res == IntersectResult::Interior || ShapeIntersection::Overlaps(m_jobData->m_frustum, c->m_cullData.m_boundingObb)) { - numDrawPackets += AddLodDataToView(c->m_cullData.m_boundingSphere.GetCenter(), c->m_lodData, *m_view); - ++numVisibleCullables; + if (TestOcclusionCulling(visibleEntry) == MaskedOcclusionCulling::CullingResult::VISIBLE) + { + numDrawPackets += AddLodDataToView(c->m_cullData.m_boundingSphere.GetCenter(), c->m_lodData, *m_jobData->m_view); + ++numVisibleCullables; + } } } } } - if (m_debugCtx->m_debugDraw && (m_view->GetName() == m_debugCtx->m_currentViewSelectionName)) + if (m_jobData->m_debugCtx->m_debugDraw && (m_jobData->m_view->GetName() == m_jobData->m_debugCtx->m_currentViewSelectionName)) { AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "debug draw culling"); - AuxGeomDrawPtr auxGeomPtr = AuxGeomFeatureProcessorInterface::GetDrawQueueForScene(m_scene); + AuxGeomDrawPtr auxGeomPtr = AuxGeomFeatureProcessorInterface::GetDrawQueueForScene(m_jobData->m_scene); if (auxGeomPtr) { //Draw the node bounds // "Fully visible" nodes are nodes that are fully inside the frustum. "Partially visible" nodes intersect the edges of the frustum. // Since the nodes of an octree have lots of overlapping boxes with coplanar edges, it's easier to view these separately, so // we have a few debug booleans to toggle which ones to draw. - if (nodeIsContainedInFrustum && m_debugCtx->m_drawFullyVisibleNodes) + if (nodeIsContainedInFrustum && m_jobData->m_debugCtx->m_drawFullyVisibleNodes) { auxGeomPtr->DrawAabb(nodeData.m_bounds, Colors::Lime, RPI::AuxGeomDraw::DrawStyle::Line, RPI::AuxGeomDraw::DepthTest::Off); } - else if (!nodeIsContainedInFrustum && m_debugCtx->m_drawPartiallyVisibleNodes) + else if (!nodeIsContainedInFrustum && m_jobData->m_debugCtx->m_drawPartiallyVisibleNodes) { auxGeomPtr->DrawAabb(nodeData.m_bounds, Colors::Yellow, RPI::AuxGeomDraw::DrawStyle::Line, RPI::AuxGeomDraw::DepthTest::Off); } //Draw bounds on individual objects - if (m_debugCtx->m_drawBoundingBoxes || m_debugCtx->m_drawBoundingSpheres || m_debugCtx->m_drawLodRadii) + if (m_jobData->m_debugCtx->m_drawBoundingBoxes || m_jobData->m_debugCtx->m_drawBoundingSpheres || m_jobData->m_debugCtx->m_drawLodRadii) { for (AzFramework::VisibilityEntry* visibleEntry : nodeData.m_entries) { if (visibleEntry->m_typeFlags & AzFramework::VisibilityEntry::TYPE_RPI_Cullable) { Cullable* c = static_cast(visibleEntry->m_userData); - if (m_debugCtx->m_drawBoundingBoxes) + if (m_jobData->m_debugCtx->m_drawBoundingBoxes) { auxGeomPtr->DrawObb(c->m_cullData.m_boundingObb, Matrix3x4::Identity(), nodeIsContainedInFrustum ? Colors::Lime : Colors::Yellow, AuxGeomDraw::DrawStyle::Line); } - if (m_debugCtx->m_drawBoundingSpheres) + if (m_jobData->m_debugCtx->m_drawBoundingSpheres) { auxGeomPtr->DrawSphere(c->m_cullData.m_boundingSphere.GetCenter(), c->m_cullData.m_boundingSphere.GetRadius(), Color(0.5f, 0.5f, 0.5f, 0.3f), AuxGeomDraw::DrawStyle::Shaded); } - if (m_debugCtx->m_drawLodRadii) + if (m_jobData->m_debugCtx->m_drawLodRadii) { auxGeomPtr->DrawSphere(c->m_cullData.m_boundingSphere.GetCenter(), c->m_lodData.m_lodSelectionRadius, @@ -401,9 +410,9 @@ namespace AZ } } - if (m_debugCtx->m_enableStats) + if (m_jobData->m_debugCtx->m_enableStats) { - CullingDebugContext::CullStats& cullStats = m_debugCtx->GetCullStatsForView(m_view); + CullingDebugContext::CullStats& cullStats = m_jobData->m_debugCtx->GetCullStatsForView(m_jobData->m_view); //no need for mutex here since these are all atomics cullStats.m_numVisibleDrawPackets += numDrawPackets; @@ -411,6 +420,29 @@ namespace AZ ++cullStats.m_numJobs; } } + + MaskedOcclusionCulling::CullingResult TestOcclusionCulling(AzFramework::VisibilityEntry* visibleEntry) + { + if (!m_jobData->m_maskedOcclusionCulling) + { + return MaskedOcclusionCulling::CullingResult::VISIBLE; + } + + // convert the bounding box of the visibility entry to NDC + AZ::Vector4 clipSpaceMin = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(visibleEntry->m_boundingVolume.GetMin()); + float depth = clipSpaceMin.GetW(); + AZ::Vector4 ndcMin = clipSpaceMin / clipSpaceMin.GetW(); + + AZ::Vector4 clipSpaceMax = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(visibleEntry->m_boundingVolume.GetMax()); + depth = AZStd::min(depth, clipSpaceMax.GetW()); + AZ::Vector4 ndcMax = clipSpaceMax / clipSpaceMax.GetW(); + + Vector2 rectMin(AZStd::min(ndcMin.GetX(), ndcMax.GetX()), AZStd::min(ndcMin.GetY(), ndcMax.GetY())); + Vector2 rectMax(AZStd::max(ndcMin.GetX(), ndcMax.GetX()), AZStd::max(ndcMin.GetY(), ndcMax.GetY())); + + // test against the occlusion buffer, which contains only the manually placed occlusion planes + return m_jobData->m_maskedOcclusionCulling->TestRect(rectMin.GetX(), rectMin.GetY(), rectMax.GetX(), rectMax.GetY(), depth); + } }; void CullingScene::ProcessCullables(const Scene& scene, View& view, AZ::Job& parentJob) @@ -444,8 +476,53 @@ namespace AZ cullStats.m_cameraViewToWorld = view.GetViewToWorldMatrix(); } + // setup occlusion culling, if necessary + MaskedOcclusionCulling* maskedOcclusionCulling = m_occlusionCullingPlanes.empty() ? nullptr : view.GetMaskedOcclusionCulling(); + if (maskedOcclusionCulling) + { + for (const AZ::Transform& transform : m_occlusionCullingPlanes) + { + // find the corners of the plane + static const Vector3 BL = Vector3(-0.5f, -0.5f, 0.0f); + static const Vector3 BR = Vector3(0.5f, -0.5f, 0.0f); + static const Vector3 TL = Vector3(-0.5f, 0.5f, 0.0f); + static const Vector3 TR = Vector3(0.5f, 0.5f, 0.0f); + + Vector3 planeBL = transform.TransformPoint(BL); + Vector3 planeBR = transform.TransformPoint(BR); + Vector3 planeTL = transform.TransformPoint(TL); + Vector3 planeTR = transform.TransformPoint(TR); + + // convert to clip-space + Vector4 projectedBL = view.GetWorldToClipMatrix() * Vector4(planeBL); + Vector4 projectedBR = view.GetWorldToClipMatrix() * Vector4(planeBR); + Vector4 projectedTL = view.GetWorldToClipMatrix() * Vector4(planeTL); + Vector4 projectedTR = view.GetWorldToClipMatrix() * Vector4(planeTR); + + // store to float array + float verts[16]; + projectedBL.StoreToFloat4(&verts[0]); + projectedBR.StoreToFloat4(&verts[4]); + projectedTL.StoreToFloat4(&verts[8]); + projectedTR.StoreToFloat4(&verts[12]); + + static uint32_t indices[6] = { 0, 2, 1, 2, 3, 1 }; + + // render into the occlusion buffer, specifying BACKFACE_NONE so it functions as a double-sided occluder + maskedOcclusionCulling->RenderTriangles((float*)verts, indices, 2, nullptr, MaskedOcclusionCulling::BACKFACE_NONE); + } + } + WorkListType worklist; - auto nodeVisitorLambda = [this, &scene, &view, &parentJob, &frustum, &worklist](const AzFramework::IVisibilityScene::NodeData& nodeData) -> void + + AZStd::shared_ptr jobData = AZStd::make_shared(); + jobData->m_debugCtx = &m_debugCtx; + jobData->m_maskedOcclusionCulling = maskedOcclusionCulling; + jobData->m_scene = &scene; + jobData->m_view = &view; + jobData->m_frustum = frustum; + + auto nodeVisitorLambda = [this, jobData, &parentJob, &frustum, &worklist](const AzFramework::IVisibilityScene::NodeData& nodeData) -> void { AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "nodeVisitorLambda()"); AZ_Assert(nodeData.m_entries.size() > 0, "should not get called with 0 entries"); @@ -458,7 +535,7 @@ namespace AZ if (worklist.size() == worklist.capacity()) { //Kick off a job to process the (full) worklist - AddObjectsToViewJob* job = aznew AddObjectsToViewJob(m_debugCtx, scene, view, frustum, worklist); //pool allocated (cheap), auto-deletes when job finishes + AddObjectsToViewJob* job = aznew AddObjectsToViewJob(jobData, worklist); //pool allocated (cheap), auto-deletes when job finishes worklist.clear(); parentJob.SetContinuation(job); job->Start(); @@ -476,8 +553,15 @@ namespace AZ if (worklist.size() > 0) { + AZStd::shared_ptr remainingJobData = AZStd::make_shared(); + remainingJobData->m_debugCtx = &m_debugCtx; + remainingJobData->m_maskedOcclusionCulling = maskedOcclusionCulling; + remainingJobData->m_scene = &scene; + remainingJobData->m_view = &view; + remainingJobData->m_frustum = frustum; + //Kick off a job to process any remaining workitems - AddObjectsToViewJob* job = aznew AddObjectsToViewJob(m_debugCtx, scene, view, frustum, worklist); //pool allocated (cheap), auto-deletes when job finishes + AddObjectsToViewJob* job = aznew AddObjectsToViewJob(remainingJobData, worklist); //pool allocated (cheap), auto-deletes when job finishes parentJob.SetContinuation(job); job->Start(); } @@ -559,13 +643,18 @@ namespace AZ } } - void CullingScene::BeginCulling(const AZStd::vector& views) + void CullingScene::BeginCulling(const AZStd::vector& views, const AZStd::vector& activePipelines) { m_cullDataConcurrencyCheck.soft_lock(); m_debugCtx.ResetCullStats(); m_debugCtx.m_numCullablesInScene = GetNumCullables(); + for (auto& view : views) + { + view->BeginCulling(activePipelines); + } + AuxGeomDrawPtr auxGeom; if (m_debugCtx.m_debugDraw) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp index 7e33750eb5..16c2189a00 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -499,7 +500,7 @@ namespace AZ } // Launch CullingSystem::ProcessCullables() jobs (will run concurrently with FeatureProcessor::Render() jobs) - m_cullingScene->BeginCulling(m_renderPacket.m_views); + m_cullingScene->BeginCulling(m_renderPacket.m_views, activePipelines); for (ViewPtr& viewPtr : m_renderPacket.m_views) { AZ::Job* processCullablesJob = AZ::CreateJobFunction([this, &viewPtr](AZ::Job& thisJob) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index 21a46693d5..3060fc34a3 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -15,7 +15,8 @@ #include #include #include - +#include +#include #include #include @@ -51,6 +52,18 @@ namespace AZ { m_shaderResourceGroup = ShaderResourceGroup::Create(viewSrgAsset); } + + m_maskedOcclusionCulling = MaskedOcclusionCulling::Create(); + m_maskedOcclusionCulling->SetNearClipPlane(0.1f); + } + + View::~View() + { + if (m_maskedOcclusionCulling) + { + MaskedOcclusionCulling::Destroy(m_maskedOcclusionCulling); + m_maskedOcclusionCulling = nullptr; + } } void View::SetDrawListMask(const RHI::DrawListMask& drawListMask) @@ -374,5 +387,58 @@ namespace AZ m_shaderResourceGroup->Compile(); m_needBuildSrg = false; } + + void View::BeginCulling(const AZStd::vector& activePipelines) + { + // retrieve current resolution + Vector2 resolution(0.0f, 0.0f); + for (auto& pipeline : activePipelines) + { + ViewPtr pipelineView = pipeline->GetDefaultView(); + if (pipelineView.get() == this) + { + RPI::SwapChainPass* pass = AZ::RPI::PassSystemInterface::Get()->FindSwapChainPass(pipeline->GetWindowHandle()); + if (pass) + { + const RHI::Viewport& viewport = pass->GetViewport(); + resolution.SetX(viewport.m_maxX); + resolution.SetY(viewport.m_maxY); + } + break; + } + } + + // calculate culling resolution based on required tile size for MaskedOcclusionCulling + static const uint32_t MaskedOcclusionCullingSubTileWidth = 8; + static const uint32_t MaskedOcclusionCullingSubTileHeight = 4; + + uint32_t cullingWidth = RHI::AlignUp(resolution.GetX(), MaskedOcclusionCullingSubTileWidth); + uint32_t cullingHeight = RHI::AlignUp(resolution.GetY(), MaskedOcclusionCullingSubTileHeight); + + m_maskedOcclusionCulling->SetResolution(cullingWidth, cullingHeight); + + if (cullingWidth > 0 && cullingHeight > 0) + { + m_maskedOcclusionCulling->ClearBuffer(); + } + } + + MaskedOcclusionCulling* View::GetMaskedOcclusionCulling() + { + if (m_maskedOcclusionCulling) + { + uint32_t width = 0; + uint32_t height = 0; + + m_maskedOcclusionCulling->GetResolution(width, height); + if (width > 0 && height > 0) + { + return m_maskedOcclusionCulling; + } + } + + return nullptr; + } + } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/atom_rpi_public_files.cmake b/Gems/Atom/RPI/Code/atom_rpi_public_files.cmake index 0d5c19758b..5ae72fe42f 100644 --- a/Gems/Atom/RPI/Code/atom_rpi_public_files.cmake +++ b/Gems/Atom/RPI/Code/atom_rpi_public_files.cmake @@ -101,6 +101,7 @@ set(FILES Include/Atom/RPI.Public/GpuQuery/Query.h Include/Atom/RPI.Public/GpuQuery/QueryPool.h Include/Atom/RPI.Public/GpuQuery/TimestampQueryPool.h + Include/Atom/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCulling.h Source/RPI.Public/Culling.cpp Source/RPI.Public/FeatureProcessor.cpp Source/RPI.Public/FeatureProcessorFactory.cpp @@ -178,4 +179,7 @@ set(FILES Source/RPI.Public/GpuQuery/Query.cpp Source/RPI.Public/GpuQuery/QueryPool.cpp Source/RPI.Public/GpuQuery/TimestampQueryPool.cpp + Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCulling.cpp + Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX2.cpp + Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX512.cpp ) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp index 2ef4e1e229..368d8e76e7 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -55,6 +56,7 @@ #include #include #include +#include #include #include #include @@ -114,6 +116,7 @@ namespace AZ DeferredFogComponent::CreateDescriptor(), SurfaceData::SurfaceDataMeshComponent::CreateDescriptor(), AttachmentComponent::CreateDescriptor(), + OcclusionCullingPlaneComponent::CreateDescriptor(), #ifdef ATOMLYINTEGRATION_FEATURE_COMMON_EDITOR EditorAreaLightComponent::CreateDescriptor(), @@ -145,6 +148,7 @@ namespace AZ EditorDeferredFogComponent::CreateDescriptor(), SurfaceData::EditorSurfaceDataMeshComponent::CreateDescriptor(), EditorAttachmentComponent::CreateDescriptor(), + EditorOcclusionCullingPlaneComponent::CreateDescriptor(), #endif }); } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.cpp new file mode 100644 index 0000000000..9a655727d6 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.cpp @@ -0,0 +1,91 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + void EditorOcclusionCullingPlaneComponent::Reflect(AZ::ReflectContext* context) + { + BaseClass::Reflect(context); + + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1, ConvertToEditorRenderComponentAdapter<1>) + ; + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class( + "Occlusion Culling Plane", "The OcclusionCullingPlane component is used to cull meshes that are inside the view frustum and behind the occlusion plane") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::Category, "Atom") + ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Component_Placeholder.svg") + ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Component_Placeholder.png") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ; + + editContext->Class( + "OcclusionCullingPlaneComponentController", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Default, &OcclusionCullingPlaneComponentController::m_configuration, "Configuration", "") + ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) + ; + + editContext->Class( + "OcclusionCullingPlaneComponentConfig", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ; + } + } + + if (auto behaviorContext = azrtti_cast(context)) + { + behaviorContext->ConstantProperty("EditorOcclusionCullingPlaneComponentTypeId", BehaviorConstant(Uuid(EditorOcclusionCullingPlaneComponentTypeId))) + ->Attribute(AZ::Script::Attributes::Module, "render") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation); + } + } + + EditorOcclusionCullingPlaneComponent::EditorOcclusionCullingPlaneComponent() + { + } + + EditorOcclusionCullingPlaneComponent::EditorOcclusionCullingPlaneComponent(const OcclusionCullingPlaneComponentConfig& config) + : BaseClass(config) + { + } + + void EditorOcclusionCullingPlaneComponent::Activate() + { + BaseClass::Activate(); + AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(GetEntityId()); + } + + void EditorOcclusionCullingPlaneComponent::Deactivate() + { + AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(); + BaseClass::Deactivate(); + } + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.h new file mode 100644 index 0000000000..8070c1d553 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.h @@ -0,0 +1,43 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + class EditorOcclusionCullingPlaneComponent final + : public EditorRenderComponentAdapter + , private AzFramework::EntityDebugDisplayEventBus::Handler + { + public: + using BaseClass = EditorRenderComponentAdapter; + AZ_EDITOR_COMPONENT(AZ::Render::EditorOcclusionCullingPlaneComponent, EditorOcclusionCullingPlaneComponentTypeId, BaseClass); + + static void Reflect(AZ::ReflectContext* context); + + EditorOcclusionCullingPlaneComponent(); + EditorOcclusionCullingPlaneComponent(const OcclusionCullingPlaneComponentConfig& config); + + // AZ::Component overrides + void Activate() override; + void Deactivate() override; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponent.cpp new file mode 100644 index 0000000000..567809266d --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponent.cpp @@ -0,0 +1,43 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include + +namespace AZ +{ + namespace Render + { + OcclusionCullingPlaneComponent::OcclusionCullingPlaneComponent(const OcclusionCullingPlaneComponentConfig& config) + : BaseClass(config) + { + } + + void OcclusionCullingPlaneComponent::Reflect(AZ::ReflectContext* context) + { + BaseClass::Reflect(context); + + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ; + } + + if (auto behaviorContext = azrtti_cast(context)) + { + behaviorContext->ConstantProperty("OcclusionCullingPlaneComponentTypeId", BehaviorConstant(Uuid(OcclusionCullingPlaneComponentTypeId))) + ->Attribute(AZ::Script::Attributes::Module, "render") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common); + } + } + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponent.h new file mode 100644 index 0000000000..7e7b48bd45 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponent.h @@ -0,0 +1,37 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include +#include + +namespace AZ +{ + namespace Render + { + class OcclusionCullingPlaneComponent final + : public AzFramework::Components::ComponentAdapter + { + public: + using BaseClass = AzFramework::Components::ComponentAdapter; + AZ_COMPONENT(AZ::Render::OcclusionCullingPlaneComponent, OcclusionCullingPlaneComponentTypeId, BaseClass); + + OcclusionCullingPlaneComponent() = default; + OcclusionCullingPlaneComponent(const OcclusionCullingPlaneComponentConfig& config); + + static void Reflect(AZ::ReflectContext* context); + }; + + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentConstants.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentConstants.h new file mode 100644 index 0000000000..59276de9ee --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentConstants.h @@ -0,0 +1,22 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +namespace AZ +{ + namespace Render + { + static constexpr const char* const OcclusionCullingPlaneComponentTypeId = "{F7537387-15A8-48F0-A1F3-D19C5886B886}"; + static constexpr const char* const EditorOcclusionCullingPlaneComponentTypeId = "{BE7CC17B-32EB-49B0-BAD9-D26E3A059012}"; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.cpp new file mode 100644 index 0000000000..bd03bec0f4 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.cpp @@ -0,0 +1,137 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include + +namespace AZ +{ + namespace Render + { + void OcclusionCullingPlaneComponentConfig::Reflect(ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ; + } + } + + void OcclusionCullingPlaneComponentController::Reflect(ReflectContext* context) + { + OcclusionCullingPlaneComponentConfig::Reflect(context); + + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Configuration", &OcclusionCullingPlaneComponentController::m_configuration); + } + } + + void OcclusionCullingPlaneComponentController::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + dependent.push_back(AZ_CRC("TransformService", 0x8ee22c50)); + } + + void OcclusionCullingPlaneComponentController::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC("OcclusionCullingPlaneService", 0x9123f33d)); + } + + void OcclusionCullingPlaneComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC("OcclusionCullingPlaneService", 0x9123f33d)); + } + + void OcclusionCullingPlaneComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + required.push_back(AZ_CRC("TransformService")); + } + + OcclusionCullingPlaneComponentController::OcclusionCullingPlaneComponentController(const OcclusionCullingPlaneComponentConfig& config) + : m_configuration(config) + { + } + + void OcclusionCullingPlaneComponentController::Activate(AZ::EntityId entityId) + { + m_entityId = entityId; + + TransformNotificationBus::Handler::BusConnect(m_entityId); + + m_featureProcessor = RPI::Scene::GetFeatureProcessorForEntity(entityId); + AZ_Assert(m_featureProcessor, "OcclusionCullingPlaneComponentController was unable to find a OcclusionCullingPlaneFeatureProcessor on the EntityContext provided."); + + m_transformInterface = TransformBus::FindFirstHandler(entityId); + AZ_Assert(m_transformInterface, "Unable to attach to a TransformBus handler"); + if (!m_transformInterface) + { + return; + } + + // add this occlusion plane to the feature processor + const AZ::Transform& transform = m_transformInterface->GetWorldTM(); + m_handle = m_featureProcessor->AddOcclusionCullingPlane(transform); + } + + void OcclusionCullingPlaneComponentController::Deactivate() + { + if (m_featureProcessor) + { + m_featureProcessor->RemoveOcclusionCullingPlane(m_handle); + } + + Data::AssetBus::MultiHandler::BusDisconnect(); + TransformNotificationBus::Handler::BusDisconnect(); + + m_transformInterface = nullptr; + m_featureProcessor = nullptr; + } + + void OcclusionCullingPlaneComponentController::SetConfiguration(const OcclusionCullingPlaneComponentConfig& config) + { + m_configuration = config; + } + + const OcclusionCullingPlaneComponentConfig& OcclusionCullingPlaneComponentController::GetConfiguration() const + { + return m_configuration; + } + + void OcclusionCullingPlaneComponentController::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) + { + if (!m_featureProcessor) + { + return; + } + + m_featureProcessor->SetTransform(m_handle, world); + } + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.h new file mode 100644 index 0000000000..5f0be5315f --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.h @@ -0,0 +1,78 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + class OcclusionCullingPlaneComponentConfig final + : public AZ::ComponentConfig + { + public: + AZ_RTTI(AZ::Render::OcclusionCullingPlaneComponentConfig, "{D0E107CA-5AFB-4675-BC97-94BCA5F248DB}", ComponentConfig); + AZ_CLASS_ALLOCATOR(OcclusionCullingPlaneComponentConfig, SystemAllocator, 0); + static void Reflect(AZ::ReflectContext* context); + + OcclusionCullingPlaneComponentConfig() = default; + }; + + class OcclusionCullingPlaneComponentController final + : public Data::AssetBus::MultiHandler + , private TransformNotificationBus::Handler + { + public: + friend class EditorOcclusionCullingPlaneComponent; + + AZ_CLASS_ALLOCATOR(OcclusionCullingPlaneComponentController, AZ::SystemAllocator, 0); + AZ_RTTI(AZ::Render::OcclusionCullingPlaneComponentController, "{8EDA3C7D-5171-4843-9969-4D84DB13F221}"); + + static void Reflect(AZ::ReflectContext* context); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + + OcclusionCullingPlaneComponentController() = default; + OcclusionCullingPlaneComponentController(const OcclusionCullingPlaneComponentConfig& config); + + void Activate(AZ::EntityId entityId); + void Deactivate(); + void SetConfiguration(const OcclusionCullingPlaneComponentConfig& config); + const OcclusionCullingPlaneComponentConfig& GetConfiguration() const; + + private: + + AZ_DISABLE_COPY(OcclusionCullingPlaneComponentController); + + // TransformNotificationBus overrides + void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; + + // handle for this occlusion plane in the feature processor + OcclusionCullingPlaneHandle m_handle; + + OcclusionCullingPlaneFeatureProcessorInterface* m_featureProcessor = nullptr; + TransformInterface* m_transformInterface = nullptr; + AZ::EntityId m_entityId; + OcclusionCullingPlaneComponentConfig m_configuration; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index e58f72a121..360511aaea 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -53,6 +53,8 @@ set(FILES Source/Mesh/EditorMeshSystemComponent.h Source/Mesh/MeshThumbnail.h Source/Mesh/MeshThumbnail.cpp + Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.h + Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.cpp Source/PostProcess/EditorPostFxLayerComponent.cpp Source/PostProcess/EditorPostFxLayerComponent.h Source/PostProcess/Bloom/EditorBloomComponent.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake index e13d1d37d6..deb8ab1b74 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake @@ -66,6 +66,10 @@ set(FILES Source/Mesh/MeshComponent.cpp Source/Mesh/MeshComponentController.h Source/Mesh/MeshComponentController.cpp + Source/OcclusionCullingPlane/OcclusionCullingPlaneComponent.h + Source/OcclusionCullingPlane/OcclusionCullingPlaneComponent.cpp + Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.h + Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.cpp Source/PostProcess/PostFxLayerComponent.cpp Source/PostProcess/PostFxLayerComponent.h Source/PostProcess/PostFxLayerComponentConfig.cpp From 13de9de3c1bd657a8e5edfeac9912347b81b9aa9 Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Wed, 26 May 2021 19:47:17 -0700 Subject: [PATCH 197/811] Project Manager Toolbar Update - use flow control for projects page for automatic updates when resizing - made the first time screen only display the first time --- AutomatedTesting/preview.png | 4 +- .../ProjectManager/Resources/AddOffset.svg | 5 + .../Resources/AddOffset_Hover.svg | 5 + .../ProjectManager/Resources/ArrowBack.svg | 3 + .../ProjectManager/Resources/FolderOffset.svg | 5 + .../Resources/FolderOffset_Hover.svg | 5 + .../Resources/ProjectManager.qrc | 9 + .../Resources/ProjectManager.qss | 275 +++++++++++++- Code/Tools/ProjectManager/Resources/build.svg | 11 + Code/Tools/ProjectManager/Resources/menu.svg | 5 + .../ProjectManager/Resources/menu_hover.svg | 5 + Code/Tools/ProjectManager/Resources/o3de.svg | 3 + .../Source/CreateProjectCtrl.cpp | 82 +++-- .../ProjectManager/Source/CreateProjectCtrl.h | 16 +- .../Source/EngineSettingsScreen.cpp | 10 + .../Source/EngineSettingsScreen.h | 3 + .../Source/FirstTimeUseScreen.cpp | 95 ----- .../Source/FirstTimeUseScreen.h | 49 --- .../Source/NewProjectSettingsScreen.cpp | 135 +++---- .../Source/NewProjectSettingsScreen.h | 8 +- .../Source/ProjectButtonWidget.cpp | 24 +- .../Source/ProjectButtonWidget.h | 1 - .../Source/ProjectManagerWindow.cpp | 51 +-- .../Source/ProjectManagerWindow.h | 14 - .../Source/ProjectManagerWindow.ui | 67 ---- .../Source/ProjectsHomeScreen.cpp | 206 ----------- .../ProjectManager/Source/ProjectsScreen.cpp | 347 ++++++++++++++++++ ...{ProjectsHomeScreen.h => ProjectsScreen.h} | 30 +- Code/Tools/ProjectManager/Source/ScreenDefs.h | 3 +- .../ProjectManager/Source/ScreenFactory.cpp | 10 +- .../Source/ScreenHeaderWidget.cpp | 62 ++++ .../Source/ScreenHeaderWidget.h | 42 +++ .../ProjectManager/Source/ScreenWidget.h | 15 + .../ProjectManager/Source/ScreensCtrl.cpp | 97 ++++- .../Tools/ProjectManager/Source/ScreensCtrl.h | 4 + .../Source/UpdateProjectCtrl.cpp | 2 +- Code/Tools/ProjectManager/Source/main.cpp | 7 +- .../project_manager_files.cmake | 9 +- Templates/DefaultProject/Template/preview.png | 4 +- 39 files changed, 1099 insertions(+), 629 deletions(-) create mode 100644 Code/Tools/ProjectManager/Resources/AddOffset.svg create mode 100644 Code/Tools/ProjectManager/Resources/AddOffset_Hover.svg create mode 100644 Code/Tools/ProjectManager/Resources/ArrowBack.svg create mode 100644 Code/Tools/ProjectManager/Resources/FolderOffset.svg create mode 100644 Code/Tools/ProjectManager/Resources/FolderOffset_Hover.svg create mode 100644 Code/Tools/ProjectManager/Resources/build.svg create mode 100644 Code/Tools/ProjectManager/Resources/menu.svg create mode 100644 Code/Tools/ProjectManager/Resources/menu_hover.svg create mode 100644 Code/Tools/ProjectManager/Resources/o3de.svg delete mode 100644 Code/Tools/ProjectManager/Source/FirstTimeUseScreen.cpp delete mode 100644 Code/Tools/ProjectManager/Source/FirstTimeUseScreen.h delete mode 100644 Code/Tools/ProjectManager/Source/ProjectManagerWindow.ui delete mode 100644 Code/Tools/ProjectManager/Source/ProjectsHomeScreen.cpp create mode 100644 Code/Tools/ProjectManager/Source/ProjectsScreen.cpp rename Code/Tools/ProjectManager/Source/{ProjectsHomeScreen.h => ProjectsScreen.h} (69%) create mode 100644 Code/Tools/ProjectManager/Source/ScreenHeaderWidget.cpp create mode 100644 Code/Tools/ProjectManager/Source/ScreenHeaderWidget.h diff --git a/AutomatedTesting/preview.png b/AutomatedTesting/preview.png index 2191a0ebc2..3d4fe78063 100644 --- a/AutomatedTesting/preview.png +++ b/AutomatedTesting/preview.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a18fae4040a22d2bb359a8ca642b97bb8f6468eeb52e2826b3b029bd8f1350b6 -size 5466 +oid sha256:40949893ed7009eeaa90b7ce6057cb6be9dfaf7b162e3c26ba9dadf985939d7d +size 2038 diff --git a/Code/Tools/ProjectManager/Resources/AddOffset.svg b/Code/Tools/ProjectManager/Resources/AddOffset.svg new file mode 100644 index 0000000000..4c62234070 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/AddOffset.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Code/Tools/ProjectManager/Resources/AddOffset_Hover.svg b/Code/Tools/ProjectManager/Resources/AddOffset_Hover.svg new file mode 100644 index 0000000000..a0e2a07eda --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/AddOffset_Hover.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Code/Tools/ProjectManager/Resources/ArrowBack.svg b/Code/Tools/ProjectManager/Resources/ArrowBack.svg new file mode 100644 index 0000000000..749bb5a02e --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/ArrowBack.svg @@ -0,0 +1,3 @@ + + + diff --git a/Code/Tools/ProjectManager/Resources/FolderOffset.svg b/Code/Tools/ProjectManager/Resources/FolderOffset.svg new file mode 100644 index 0000000000..a048fbcc39 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/FolderOffset.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Code/Tools/ProjectManager/Resources/FolderOffset_Hover.svg b/Code/Tools/ProjectManager/Resources/FolderOffset_Hover.svg new file mode 100644 index 0000000000..fb13cd8558 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/FolderOffset_Hover.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qrc b/Code/Tools/ProjectManager/Resources/ProjectManager.qrc index 2e60e84326..04d5e98a10 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qrc +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qrc @@ -4,6 +4,12 @@ Add.svg + AddOffset.svg + AddOffset_Hover.svg + ArrowBack.svg + build.svg + FolderOffset.svg + FolderOffset_Hover.svg Select_Folder.svg o3de_editor.ico Windows.svg @@ -14,6 +20,9 @@ DefaultProjectImage.png ArrowDownLine.svg ArrowUpLine.svg + o3de.svg + menu.svg + menu_hover.svg Backgrounds/FirstTimeBackgroundImage.jpg ArrowDownLine.svg ArrowUpLine.svg diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qss b/Code/Tools/ProjectManager/Resources/ProjectManager.qss index 849c9cbf5c..5eb92964dd 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qss +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qss @@ -1,29 +1,69 @@ /************** General (MainWindow) **************/ QMainWindow { - background-color: #333333; + background:#131313 url(:/o3de.svg) no-repeat top left; + /* position the logo using padding and background-origin, Qt does not support background-position pixels */ + background-origin:content; + padding:25px 16px; + margin:0; } - QPushButton:focus { outline: none; border:1px solid #1e70eb; } +QTabBar { + background-color: transparent; +} +QTabWidget::tab-bar +{ + left: 78px; /* make room for the logo */ +} +QTabBar::tab { + height:82px; + background-color: transparent; + font-size:24px; + min-width:100px; + margin-right:40px; + border-bottom: 3px solid transparent; +} +QTabBar::tab:text +{ + text-align:left; +} +QTabWidget::pane { + background-color: #333333; + border:0 none; +} +QTabBar::tab:selected +{ + border-bottom: 3px solid #1e70eb; + color: #1e70eb; +} +QTabBar::tab:hover +{ + color: #1e70eb; +} +QTabBar::tab:pressed +{ + color: #0e60eb; +} + /************** General (Forms) **************/ #formLineEditWidget, #formBrowseEditWidget { - max-width: 780px; + max-width: 890px; } #formFrame { - max-width: 720px; + max-width: 840px; background-color: #444444; border:1px solid #dddddd; border-radius: 4px; padding: 0px 10px 2px 6px; margin-top:10px; - margin-left:30px; + margin-left:50px; } #formFrame[Focus="true"] { @@ -59,16 +99,235 @@ QPushButton:focus { padding-top: -4px; } + #formErrorLabel { color: #ec3030; font-size: 14px; - margin-left: 40px; + margin-left: 50px; } #formTitleLabel { font-size:21px; color:#ffffff; - margin: 10px 0 10px 30px; + margin: 24px 0 10px 50px; +} + +/************** General (Modal windows) **************/ + +#header { + background-color:#111111; + min-height:80px; + max-height:80px; +} + +#header QPushButton { + /* settings min/max lets us use a fixed size */ + min-width: 24px; + max-width: 24px; + min-height: 24px; + max-height: 24px; + margin: 20px 10px 0px 10px; + background:transparent url(:/ArrowBack.svg) no-repeat center; + background-origin:content; + qproperty-flat: true; + qproperty-iconSize: 50px; +} + +#header QPushButton:focus { + border:none; +} +#header QPushButton:hover { + background:#333333 url(:/ArrowBack.svg) no-repeat center; +} +#header QPushButton:pressed { + background:#222222 url(:/ArrowBack.svg) no-repeat center; +} + +#headerTitle { + font-size:14px; + text-align:left; + margin:0; + padding-top:10px; + padding-bottom:-5px; + min-height:15px; + max-height:15px; +} +#headerSubTitle { + font-size:24px; + text-align:left; + margin:0; + min-height:42px; + max-height:42px; +} + +#body { + background-color:#333333; +} +#footer { + /* settings min/max lets us use a fixed size */ + min-width: 50px; + min-height:54px; + max-height:54px; +} + +#footer > QPushButton { + qproperty-flat: true; + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #0095f2, stop: 1.0 #1e70eb); + border-radius: 3px; + min-height: 28px; + max-height: 28px; + min-width: 150px; + margin-right:30px; +} +#footer > QPushButton:hover { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #10A5f2, stop: 1.0 #2e80eb); +} +#footer > QPushButton:pressed { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #0085e2, stop: 1.0 #0e60db); +} + +#footer > QPushButton[secondary="true"] { + margin-right: 10px; + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #888888, stop: 1.0 #555555); +} +#footer > QPushButton[secondary="true"]:hover { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #999999, stop: 1.0 #666666); +} +#footer > QPushButton[secondary="true"]:pressed { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #555555, stop: 1.0 #777777); +} + +/************** Project Settings **************/ +#projectSettings { + margin-top:42px; +} + +#projectTemplate { + margin: 55px 0 0 50px; + max-width: 780px; + min-height:200px; + max-height:200px; +} +#projectTemplateLabel { + font-size:16px; + font-weight:100; +} + +#projectTemplateDetailsLabel { + font-size:14px; + min-height:40px; + margin-bottom:20px; +} + +#projectTemplateDetails { + background-color:#444444; + max-width:240px; + min-width:240px; + margin-left:30px; +} + +/************** Projects **************/ +#firstTimeContent > #titleLabel { + font-size:60px; + margin:73px 0px 0px 0px; + qproperty-indent: 0; +} + +#firstTimeContent > #introLabel { + font-size:14px; + margin:10px 0 60px 0; + qproperty-indent: 0; +} + +#firstTimeContent > QPushButton { + min-width: 210px; + max-width: 210px; + min-height: 276px; + max-height: 276px; + qproperty-flat: true; + background-origin:content; + font-size:14px; + border: 1px solid #ffffff; +} + +#firstTimeContent > QPushButton:hover { + border: 1px solid #1e70eb; + color: #1e70eb; +} + +#firstTimeContent > QPushButton:pressed { + border: 1px solid #0e60eb; + color: #0e60eb; +} + +#createProjectButton { + background:rgba(0,0,0,180) url(:/AddOffset.svg) no-repeat center center; +} +#createProjectButton:hover, +#createProjectButton:pressed { + background:rgba(0,0,0,180) url(:/AddOffset_Hover.svg) no-repeat center center; +} + +#addProjectButton { + background:rgba(0,0,0,180) url(:/FolderOffset.svg) no-repeat center center; +} +#addProjectButton:hover, +#addProjectButton:pressed { + background:rgba(0,0,0,180) url(:/FolderOffset_Hover.svg) no-repeat center center; +} + +#projectsContent > QFrame { + margin-top:60px; +} + +#projectsContent > QFrame > #titleLabel { + font-size:24px; + qproperty-indent: 0; +} + +#projectsContent > QScrollArea { + margin-top:40px; + margin-bottom:5px; +} + +#projectButton > #labelButton { + border:1px solid white; +} +#projectButton > #labelButton:hover, +#projectButton > #labelButton:pressed { + border:1px solid #1e70eb; +} + +#projectButton > QFrame { + margin-top:6px; +} + +#projectButton > QFrame > QLabel { + font-weight:bold; + font-size:14px; + qproperty-indent: 0; +} + +#projectMenuButton { + qproperty-flat: true; + background:transparent url(:/menu.svg) no-repeat center center; + max-width:30px; + min-width:30px; + max-height:14px; + min-height:14px; +} + +#projectsContent > QFrame > #newProjectButton { + min-width:150px; + max-width:150px; + min-height:26px; + max-height:26px; } #labelButtonOverlay { @@ -77,4 +336,4 @@ QPushButton:focus { max-width:210px;; min-height:278px; max-height:278px; -} +} \ No newline at end of file diff --git a/Code/Tools/ProjectManager/Resources/build.svg b/Code/Tools/ProjectManager/Resources/build.svg new file mode 100644 index 0000000000..b6c3546443 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/build.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/Code/Tools/ProjectManager/Resources/menu.svg b/Code/Tools/ProjectManager/Resources/menu.svg new file mode 100644 index 0000000000..a639c74ab4 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/menu.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Code/Tools/ProjectManager/Resources/menu_hover.svg b/Code/Tools/ProjectManager/Resources/menu_hover.svg new file mode 100644 index 0000000000..4eea63faca --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/menu_hover.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Code/Tools/ProjectManager/Resources/o3de.svg b/Code/Tools/ProjectManager/Resources/o3de.svg new file mode 100644 index 0000000000..bb6e596a00 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/o3de.svg @@ -0,0 +1,3 @@ + + + diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp index 03e6a34b89..69f0a3983d 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp @@ -14,11 +14,17 @@ #include #include #include +#include +#include #include +#include #include #include #include +#include +#include +#include namespace O3DE::ProjectManager { @@ -26,29 +32,34 @@ namespace O3DE::ProjectManager : ScreenWidget(parent) { QVBoxLayout* vLayout = new QVBoxLayout(); - setLayout(vLayout); + vLayout->setContentsMargins(0,0,0,0); - m_screensCtrl = new ScreensCtrl(); - vLayout->addWidget(m_screensCtrl); + m_header = new ScreenHeader(this); + m_header->setTitle(tr("Create a New Project")); + m_header->setSubTitle(tr("Enter Project Details")); + connect(m_header->backButton(), &QPushButton::clicked, this, &CreateProjectCtrl::HandleBackButton); + vLayout->addWidget(m_header); + + m_stack = new QStackedWidget(this); + m_stack->setObjectName("body"); + m_stack->setSizePolicy(QSizePolicy(QSizePolicy::Preferred,QSizePolicy::Expanding)); + m_stack->addWidget(new NewProjectSettingsScreen()); + m_stack->addWidget(new GemCatalogScreen()); + vLayout->addWidget(m_stack); QDialogButtonBox* backNextButtons = new QDialogButtonBox(); + backNextButtons->setObjectName("footer"); vLayout->addWidget(backNextButtons); m_backButton = backNextButtons->addButton(tr("Back"), QDialogButtonBox::RejectRole); + m_backButton->setProperty("secondary", true); m_nextButton = backNextButtons->addButton(tr("Next"), QDialogButtonBox::ApplyRole); - connect(m_backButton, &QPushButton::pressed, this, &CreateProjectCtrl::HandleBackButton); - connect(m_nextButton, &QPushButton::pressed, this, &CreateProjectCtrl::HandleNextButton); + connect(m_backButton, &QPushButton::clicked, this, &CreateProjectCtrl::HandleBackButton); + connect(m_nextButton, &QPushButton::clicked, this, &CreateProjectCtrl::HandleNextButton); - m_screensOrder = - { - ProjectManagerScreen::NewProjectSettings, - ProjectManagerScreen::GemCatalog - }; - m_screensCtrl->BuildScreens(m_screensOrder); - m_screensCtrl->ForceChangeToScreen(ProjectManagerScreen::NewProjectSettings, false); - - UpdateNextButtonText(); + Update(); + setLayout(vLayout); } ProjectManagerScreen CreateProjectCtrl::GetScreenEnum() @@ -58,28 +69,20 @@ namespace O3DE::ProjectManager void CreateProjectCtrl::HandleBackButton() { - if (!m_screensCtrl->GotoPreviousScreen()) + if (m_stack->currentIndex() > 0) { - emit GotoPreviousScreenRequest(); + m_stack->setCurrentIndex(m_stack->currentIndex() - 1); + Update(); } else { - UpdateNextButtonText(); + emit GotoPreviousScreenRequest(); } } void CreateProjectCtrl::HandleNextButton() { - ScreenWidget* currentScreen = m_screensCtrl->GetCurrentScreen(); + ScreenWidget* currentScreen = reinterpret_cast(m_stack->currentWidget()); ProjectManagerScreen screenEnum = currentScreen->GetScreenEnum(); - auto screenOrderIter = m_screensOrder.begin(); - for (; screenOrderIter != m_screensOrder.end(); ++screenOrderIter) - { - if (*screenOrderIter == screenEnum) - { - ++screenOrderIter; - break; - } - } if (screenEnum == ProjectManagerScreen::NewProjectSettings) { @@ -97,10 +100,10 @@ namespace O3DE::ProjectManager } } - if (screenOrderIter != m_screensOrder.end()) + if (m_stack->currentIndex() != m_stack->count() - 1) { - m_screensCtrl->ChangeToScreen(*screenOrderIter); - UpdateNextButtonText(); + m_stack->setCurrentIndex(m_stack->currentIndex() + 1); + Update(); } else { @@ -108,7 +111,7 @@ namespace O3DE::ProjectManager if (result.IsSuccess()) { // adding gems is not implemented yet because we don't know what targets to add or how to add them - emit ChangeScreenRequest(ProjectManagerScreen::ProjectsHome); + emit ChangeScreenRequest(ProjectManagerScreen::Projects); } else { @@ -117,14 +120,21 @@ namespace O3DE::ProjectManager } } - void CreateProjectCtrl::UpdateNextButtonText() + void CreateProjectCtrl::Update() { - QString nextButtonText = tr("Next"); - if (m_screensCtrl->GetCurrentScreen()->GetScreenEnum() == ProjectManagerScreen::GemCatalog) + ScreenWidget* currentScreen = reinterpret_cast(m_stack->currentWidget()); + if (currentScreen && currentScreen->GetScreenEnum() == ProjectManagerScreen::GemCatalog) { - nextButtonText = tr("Create Project"); + m_header->setTitle(tr("Create Project")); + m_header->setSubTitle(tr("Configure project with Gems")); + m_nextButton->setText(tr("Create Project")); + } + else + { + m_header->setTitle(tr("Create Project")); + m_header->setSubTitle(tr("Enter Project Details")); + m_nextButton->setText(tr("Next")); } - m_nextButton->setText(nextButtonText); } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h index 213bff3bc2..01e3349b21 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h @@ -12,15 +12,18 @@ #pragma once #if !defined(Q_MOC_RUN) -#include "ProjectInfo.h" #include -#include -#include +#include #endif +QT_FORWARD_DECLARE_CLASS(QStackedWidget) +QT_FORWARD_DECLARE_CLASS(QPushButton) +QT_FORWARD_DECLARE_CLASS(QLabel) namespace O3DE::ProjectManager { + QT_FORWARD_DECLARE_CLASS(ScreenHeader) + class CreateProjectCtrl : public ScreenWidget { @@ -34,12 +37,13 @@ namespace O3DE::ProjectManager void HandleNextButton(); private: - void UpdateNextButtonText(); + void Update(); + + QStackedWidget* m_stack; + ScreenHeader* m_header; - ScreensCtrl* m_screensCtrl; QPushButton* m_backButton; QPushButton* m_nextButton; - QVector m_screensOrder; QString m_projectTemplatePath; ProjectInfo m_projectInfo; diff --git a/Code/Tools/ProjectManager/Source/EngineSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/EngineSettingsScreen.cpp index f51996bd65..6342041da4 100644 --- a/Code/Tools/ProjectManager/Source/EngineSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/EngineSettingsScreen.cpp @@ -82,6 +82,16 @@ namespace O3DE::ProjectManager return ProjectManagerScreen::EngineSettings; } + QString EngineSettingsScreen::GetTabText() + { + return tr("Engine"); + } + + bool EngineSettingsScreen::IsTab() + { + return true; + } + void EngineSettingsScreen::OnTextChanged() { // save engine settings diff --git a/Code/Tools/ProjectManager/Source/EngineSettingsScreen.h b/Code/Tools/ProjectManager/Source/EngineSettingsScreen.h index 0e91ec2d3b..36e329cdf6 100644 --- a/Code/Tools/ProjectManager/Source/EngineSettingsScreen.h +++ b/Code/Tools/ProjectManager/Source/EngineSettingsScreen.h @@ -26,7 +26,10 @@ namespace O3DE::ProjectManager public: explicit EngineSettingsScreen(QWidget* parent = nullptr); ~EngineSettingsScreen() = default; + ProjectManagerScreen GetScreenEnum() override; + QString GetTabText() override; + bool IsTab() override; protected slots: void OnTextChanged(); diff --git a/Code/Tools/ProjectManager/Source/FirstTimeUseScreen.cpp b/Code/Tools/ProjectManager/Source/FirstTimeUseScreen.cpp deleted file mode 100644 index 8654b221fb..0000000000 --- a/Code/Tools/ProjectManager/Source/FirstTimeUseScreen.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - -#include - -#include -#include -#include -#include -#include -#include - -namespace O3DE::ProjectManager -{ - FirstTimeUseScreen::FirstTimeUseScreen(QWidget* parent) - : ScreenWidget(parent) - { - QVBoxLayout* vLayout = new QVBoxLayout(); - setLayout(vLayout); - vLayout->setContentsMargins(s_contentMargins, s_contentMargins, s_contentMargins, s_contentMargins); - - QLabel* titleLabel = new QLabel(this); - titleLabel->setText(tr("Ready. Set. Create!")); - titleLabel->setStyleSheet("font-size: 60px"); - vLayout->addWidget(titleLabel); - - QLabel* introLabel = new QLabel(this); - introLabel->setTextFormat(Qt::AutoText); - introLabel->setText(tr("

Welcome to O3DE! Start something new by creating a project. Not sure what to create?

Explore what\342\200\231s available by downloading our sample project.

")); - introLabel->setStyleSheet("font-size: 14px"); - vLayout->addWidget(introLabel); - - QHBoxLayout* buttonLayout = new QHBoxLayout(); - buttonLayout->setSpacing(s_buttonSpacing); - - m_createProjectButton = CreateLargeBoxButton(QIcon(":/Add.svg"), tr("Create Project"), this); - m_createProjectButton->setIconSize(QSize(s_iconSize, s_iconSize)); - buttonLayout->addWidget(m_createProjectButton); - - m_addProjectButton = CreateLargeBoxButton(QIcon(":/Select_Folder.svg"), tr("Add a Project"), this); - m_addProjectButton->setIconSize(QSize(s_iconSize, s_iconSize)); - buttonLayout->addWidget(m_addProjectButton); - - QSpacerItem* buttonSpacer = new QSpacerItem(s_spacerSize, s_spacerSize, QSizePolicy::Expanding, QSizePolicy::Minimum); - buttonLayout->addItem(buttonSpacer); - - vLayout->addItem(buttonLayout); - - QSpacerItem* verticalSpacer = new QSpacerItem(s_spacerSize, s_spacerSize, QSizePolicy::Minimum, QSizePolicy::Expanding); - vLayout->addItem(verticalSpacer); - - // Using border-image allows for scaling options background-image does not support - setStyleSheet("O3DE--ProjectManager--ScreenWidget { border-image: url(:/Backgrounds/FirstTimeBackgroundImage.jpg) repeat repeat; }"); - - connect(m_createProjectButton, &QPushButton::pressed, this, &FirstTimeUseScreen::HandleNewProjectButton); - connect(m_addProjectButton, &QPushButton::pressed, this, &FirstTimeUseScreen::HandleAddProjectButton); - } - - ProjectManagerScreen FirstTimeUseScreen::GetScreenEnum() - { - return ProjectManagerScreen::FirstTimeUse; - } - - void FirstTimeUseScreen::HandleNewProjectButton() - { - emit ResetScreenRequest(ProjectManagerScreen::CreateProject); - emit ChangeScreenRequest(ProjectManagerScreen::CreateProject); - } - void FirstTimeUseScreen::HandleAddProjectButton() - { - emit ChangeScreenRequest(ProjectManagerScreen::ProjectsHome); - } - - QPushButton* FirstTimeUseScreen::CreateLargeBoxButton(const QIcon& icon, const QString& text, QWidget* parent) - { - QPushButton* largeBoxButton = new QPushButton(icon, text, parent); - - largeBoxButton->setFixedSize(s_boxButtonWidth, s_boxButtonHeight); - largeBoxButton->setFlat(true); - largeBoxButton->setFocusPolicy(Qt::FocusPolicy::NoFocus); - largeBoxButton->setStyleSheet("QPushButton { font-size: 14px; background-color: rgba(0, 0, 0, 191); }"); - - return largeBoxButton; - } - -} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/FirstTimeUseScreen.h b/Code/Tools/ProjectManager/Source/FirstTimeUseScreen.h deleted file mode 100644 index 80a2310d7a..0000000000 --- a/Code/Tools/ProjectManager/Source/FirstTimeUseScreen.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#endif - -QT_FORWARD_DECLARE_CLASS(QIcon) -QT_FORWARD_DECLARE_CLASS(QPushButton) - -namespace O3DE::ProjectManager -{ - class FirstTimeUseScreen - : public ScreenWidget - { - public: - explicit FirstTimeUseScreen(QWidget* parent = nullptr); - ~FirstTimeUseScreen() = default; - ProjectManagerScreen GetScreenEnum() override; - - protected slots: - void HandleNewProjectButton(); - void HandleAddProjectButton(); - - private: - QPushButton* CreateLargeBoxButton(const QIcon& icon, const QString& text, QWidget* parent = nullptr); - - QPushButton* m_createProjectButton; - QPushButton* m_addProjectButton; - - inline constexpr static int s_contentMargins = 80; - inline constexpr static int s_buttonSpacing = 30; - inline constexpr static int s_iconSize = 24; - inline constexpr static int s_spacerSize = 20; - inline constexpr static int s_boxButtonWidth = 210; - inline constexpr static int s_boxButtonHeight = 280; - }; - -} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp index ffbf1bf6fe..b57a2b35b2 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp @@ -12,6 +12,9 @@ #include #include +#include +#include +#include #include #include @@ -23,6 +26,7 @@ #include #include #include +#include namespace O3DE::ProjectManager { @@ -31,64 +35,81 @@ namespace O3DE::ProjectManager NewProjectSettingsScreen::NewProjectSettingsScreen(QWidget* parent) : ScreenWidget(parent) { - QHBoxLayout* hLayout = new QHBoxLayout(); - this->setLayout(hLayout); + QHBoxLayout* hLayout = new QHBoxLayout(this); + hLayout->setAlignment(Qt::AlignLeft); + hLayout->setContentsMargins(0,0,0,0); + // if we don't provide a parent for this box layout the stylesheet doesn't take + // if we don't set this in a frame (just use a sub-layout) all the content will align incorrectly horizontally + QFrame* projectSettingsFrame = new QFrame(this); + projectSettingsFrame->setObjectName("projectSettings"); QVBoxLayout* vLayout = new QVBoxLayout(this); - QLabel* projectNameLabel = new QLabel(tr("Project Name"), this); - vLayout->addWidget(projectNameLabel); - - m_projectNameLineEdit = new QLineEdit(tr("New Project"), this); - vLayout->addWidget(m_projectNameLineEdit); - - QLabel* projectPathLabel = new QLabel(tr("Project Location"), this); - vLayout->addWidget(projectPathLabel); - + // you cannot remove content margins in qss + vLayout->setContentsMargins(0,0,0,0); + vLayout->setAlignment(Qt::AlignTop); { - QHBoxLayout* projectPathLayout = new QHBoxLayout(this); + m_projectName = new FormLineEditWidget(tr("Project name"), tr("New Project"), this); + m_projectName->setErrorLabelText( + tr("A project with this name already exists at this location. Please choose a new name or location.")); + vLayout->addWidget(m_projectName); - m_projectPathLineEdit = new QLineEdit(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), this); - projectPathLayout->addWidget(m_projectPathLineEdit); + m_projectPath = + new FormBrowseEditWidget(tr("Project Location"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), this); + m_projectPath->lineEdit()->setReadOnly(true); + m_projectPath->setErrorLabelText(tr("Please provide a valid path to a folder that exists")); + m_projectPath->lineEdit()->setValidator(new PathValidator(PathValidator::PathMode::ExistingFolder, this)); + vLayout->addWidget(m_projectPath); - QPushButton* browseButton = new QPushButton(tr("Browse"), this); - connect(browseButton, &QPushButton::pressed, this, &NewProjectSettingsScreen::HandleBrowseButton); - projectPathLayout->addWidget(browseButton); - - vLayout->addLayout(projectPathLayout); - } - - QLabel* projectTemplateLabel = new QLabel(this); - projectTemplateLabel->setText("Project Template"); - vLayout->addWidget(projectTemplateLabel); - - QHBoxLayout* templateLayout = new QHBoxLayout(this); - vLayout->addItem(templateLayout); - - m_projectTemplateButtonGroup = new QButtonGroup(this); - auto templatesResult = PythonBindingsInterface::Get()->GetProjectTemplates(); - if (templatesResult.IsSuccess() && !templatesResult.GetValue().isEmpty()) - { - for (auto projectTemplate : templatesResult.GetValue()) + // if we don't use a QFrame we cannot "contain" the widgets inside and move them around + // as a group + QFrame* projectTemplateWidget = new QFrame(this); + projectTemplateWidget->setObjectName("projectTemplate"); + QVBoxLayout* containerLayout = new QVBoxLayout(); + containerLayout->setAlignment(Qt::AlignTop); { - QRadioButton* radioButton = new QRadioButton(projectTemplate.m_name, this); - radioButton->setProperty(k_pathProperty, projectTemplate.m_path); - m_projectTemplateButtonGroup->addButton(radioButton); + QLabel* projectTemplateLabel = new QLabel(tr("Select a Project Template")); + projectTemplateLabel->setObjectName("projectTemplateLabel"); + containerLayout->addWidget(projectTemplateLabel); - templateLayout->addWidget(radioButton); + QLabel* projectTemplateDetailsLabel = new QLabel(tr("Project templates are pre-configured with relevant Gems that provide " + "additional functionality and content to the project.")); + projectTemplateDetailsLabel->setWordWrap(true); + projectTemplateDetailsLabel->setObjectName("projectTemplateDetailsLabel"); + containerLayout->addWidget(projectTemplateDetailsLabel); + + QHBoxLayout* templateLayout = new QHBoxLayout(this); + containerLayout->addItem(templateLayout); + + m_projectTemplateButtonGroup = new QButtonGroup(this); + m_projectTemplateButtonGroup->setObjectName("templateButtonGroup"); + auto templatesResult = PythonBindingsInterface::Get()->GetProjectTemplates(); + if (templatesResult.IsSuccess() && !templatesResult.GetValue().isEmpty()) + { + for (auto projectTemplate : templatesResult.GetValue()) + { + QRadioButton* radioButton = new QRadioButton(projectTemplate.m_name, this); + radioButton->setProperty(k_pathProperty, projectTemplate.m_path); + m_projectTemplateButtonGroup->addButton(radioButton); + + containerLayout->addWidget(radioButton); + } + + m_projectTemplateButtonGroup->buttons().first()->setChecked(true); + } } - - m_projectTemplateButtonGroup->buttons().first()->setChecked(true); + projectTemplateWidget->setLayout(containerLayout); + vLayout->addWidget(projectTemplateWidget); } + projectSettingsFrame->setLayout(vLayout); - QSpacerItem* verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); - vLayout->addItem(verticalSpacer); + hLayout->addWidget(projectSettingsFrame); - hLayout->addItem(vLayout); + QWidget* projectTemplateDetails = new QWidget(this); + projectTemplateDetails->setObjectName("projectTemplateDetails"); + hLayout->addWidget(projectTemplateDetails); - QWidget* gemsListPlaceholder = new QWidget(this); - gemsListPlaceholder->setFixedWidth(250); - hLayout->addWidget(gemsListPlaceholder); + this->setLayout(hLayout); } ProjectManagerScreen NewProjectSettingsScreen::GetScreenEnum() @@ -96,26 +117,12 @@ namespace O3DE::ProjectManager return ProjectManagerScreen::NewProjectSettings; } - void NewProjectSettingsScreen::HandleBrowseButton() - { - QString defaultPath = m_projectPathLineEdit->text(); - if (defaultPath.isEmpty()) - { - defaultPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); - } - - QString directory = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(this, tr("New project path"), defaultPath)); - if (!directory.isEmpty()) - { - m_projectPathLineEdit->setText(directory); - } - } ProjectInfo NewProjectSettingsScreen::GetProjectInfo() { ProjectInfo projectInfo; - projectInfo.m_projectName = m_projectNameLineEdit->text(); - projectInfo.m_path = QDir::toNativeSeparators(m_projectPathLineEdit->text() + "/" + projectInfo.m_projectName); + projectInfo.m_projectName = m_projectName->lineEdit()->text(); + projectInfo.m_path = QDir::toNativeSeparators(m_projectPath->lineEdit()->text() + "/" + projectInfo.m_projectName); return projectInfo; } @@ -127,18 +134,18 @@ namespace O3DE::ProjectManager bool NewProjectSettingsScreen::Validate() { bool projectNameIsValid = true; - if (m_projectNameLineEdit->text().isEmpty()) + if (m_projectName->lineEdit()->text().isEmpty()) { projectNameIsValid = false; } bool projectPathIsValid = true; - if (m_projectPathLineEdit->text().isEmpty()) + if (m_projectPath->lineEdit()->text().isEmpty()) { projectPathIsValid = false; } - QDir path(QDir::toNativeSeparators(m_projectPathLineEdit->text() + "/" + m_projectNameLineEdit->text())); + QDir path(QDir::toNativeSeparators(m_projectPath->lineEdit()->text() + "/" + m_projectName->lineEdit()->text())); if (path.exists() && !path.isEmpty()) { projectPathIsValid = false; diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h index 1cfd3c9c35..f0e9609fdc 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h +++ b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h @@ -17,10 +17,12 @@ #endif QT_FORWARD_DECLARE_CLASS(QButtonGroup) -QT_FORWARD_DECLARE_CLASS(QLineEdit) namespace O3DE::ProjectManager { + QT_FORWARD_DECLARE_CLASS(FormLineEditWidget) + QT_FORWARD_DECLARE_CLASS(FormBrowseEditWidget) + class NewProjectSettingsScreen : public ScreenWidget { @@ -38,8 +40,8 @@ namespace O3DE::ProjectManager void HandleBrowseButton(); private: - QLineEdit* m_projectNameLineEdit; - QLineEdit* m_projectPathLineEdit; + FormLineEditWidget* m_projectName; + FormBrowseEditWidget* m_projectPath; QButtonGroup* m_projectTemplateButtonGroup; }; diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp index dada54b1a2..4be876e79f 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp @@ -31,6 +31,7 @@ namespace O3DE::ProjectManager LabelButton::LabelButton(QWidget* parent) : QLabel(parent) { + setObjectName("labelButton"); m_overlayLabel = new QLabel("", this); m_overlayLabel->setObjectName("labelButtonOverlay"); m_overlayLabel->setWordWrap(true); @@ -75,6 +76,8 @@ namespace O3DE::ProjectManager void ProjectButton::Setup() { + setObjectName("projectButton"); + QVBoxLayout* vLayout = new QVBoxLayout(); vLayout->setSpacing(0); vLayout->setContentsMargins(0, 0, 0, 0); @@ -98,14 +101,21 @@ namespace O3DE::ProjectManager m_deleteProjectAction = newProjectMenu->addAction(tr("Delete the Project")); #endif - m_projectSettingsMenuButton = new QPushButton(this); - m_projectSettingsMenuButton->setText(m_projectName); - m_projectSettingsMenuButton->setMenu(newProjectMenu); - m_projectSettingsMenuButton->setFocusPolicy(Qt::FocusPolicy::NoFocus); - m_projectSettingsMenuButton->setStyleSheet("font-size: 14px; text-align:left;"); - vLayout->addWidget(m_projectSettingsMenuButton); + QFrame* footer = new QFrame(this); + QHBoxLayout* hLayout = new QHBoxLayout(); + hLayout->setContentsMargins(0, 0, 0, 0); + footer->setLayout(hLayout); + { + QLabel* projectNameLabel = new QLabel(m_projectName, this); + hLayout->addWidget(projectNameLabel); - setFixedSize(s_projectImageWidth, s_projectImageHeight + m_projectSettingsMenuButton->height()); + QPushButton* projectMenuButton = new QPushButton(this); + projectMenuButton->setObjectName("projectMenuButton"); + projectMenuButton->setMenu(newProjectMenu); + hLayout->addWidget(projectMenuButton); + } + + vLayout->addWidget(footer); connect(m_projectImageLabel, &LabelButton::triggered, [this]() { emit OpenProject(m_projectName); }); connect(m_editProjectAction, &QAction::triggered, [this]() { emit EditProject(m_projectName); }); diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h index 43efaa1136..671debf6d0 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h @@ -73,7 +73,6 @@ namespace O3DE::ProjectManager QString m_projectName; QString m_projectImagePath; LabelButton* m_projectImageLabel; - QPushButton* m_projectSettingsMenuButton; QAction* m_editProjectAction; QAction* m_editProjectGemsAction; QAction* m_copyProjectAction; diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp index eb79f2da1e..76bcc2eb99 100644 --- a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp @@ -11,52 +11,46 @@ */ #include -#include +#include #include #include #include -#include - namespace O3DE::ProjectManager { ProjectManagerWindow::ProjectManagerWindow(QWidget* parent, const AZ::IO::PathView& engineRootPath) : QMainWindow(parent) - , m_ui(new Ui::ProjectManagerWindowClass()) { - m_ui->setupUi(this); - QLayout* layout = m_ui->centralWidget->layout(); - layout->setMargin(0); - layout->setSpacing(0); - layout->setContentsMargins(0, 0, 0, 0); - m_pythonBindings = AZStd::make_unique(engineRootPath); - m_screensCtrl = new ScreensCtrl(); - m_ui->verticalLayout->addWidget(m_screensCtrl); + setWindowTitle(tr("O3DE Project Manager")); - connect(m_ui->projectsMenu, &QMenu::aboutToShow, this, &ProjectManagerWindow::HandleProjectsMenu); - connect(m_ui->engineMenu, &QMenu::aboutToShow, this, &ProjectManagerWindow::HandleEngineMenu); + ScreensCtrl* screensCtrl = new ScreensCtrl(); + // currently the tab order on the home page is based on the order of this list + QVector screenEnums = + { + ProjectManagerScreen::Projects, + ProjectManagerScreen::EngineSettings, + ProjectManagerScreen::CreateProject, + ProjectManagerScreen::UpdateProject + }; + screensCtrl->BuildScreens(screenEnums); + + setCentralWidget(screensCtrl); + + // setup stylesheets and hot reloading QDir rootDir = QString::fromUtf8(engineRootPath.Native().data(), aznumeric_cast(engineRootPath.Native().size())); const auto pathOnDisk = rootDir.absoluteFilePath("Code/Tools/ProjectManager/Resources"); const auto qrcPath = QStringLiteral(":/ProjectManager/style"); AzQtComponents::StyleManager::addSearchPaths("style", pathOnDisk, qrcPath, engineRootPath); + // set stylesheet after creating the screens or their styles won't get updated AzQtComponents::StyleManager::setStyleSheet(this, QStringLiteral("style:ProjectManager.qss")); - QVector screenEnums = - { - ProjectManagerScreen::FirstTimeUse, - ProjectManagerScreen::CreateProject, - ProjectManagerScreen::ProjectsHome, - ProjectManagerScreen::UpdateProject, - ProjectManagerScreen::EngineSettings - }; - m_screensCtrl->BuildScreens(screenEnums); - m_screensCtrl->ForceChangeToScreen(ProjectManagerScreen::FirstTimeUse, false); + screensCtrl->ForceChangeToScreen(ProjectManagerScreen::Projects, false); } ProjectManagerWindow::~ProjectManagerWindow() @@ -64,13 +58,4 @@ namespace O3DE::ProjectManager m_pythonBindings.reset(); } - void ProjectManagerWindow::HandleProjectsMenu() - { - m_screensCtrl->ChangeToScreen(ProjectManagerScreen::ProjectsHome); - } - void ProjectManagerWindow::HandleEngineMenu() - { - m_screensCtrl->ChangeToScreen(ProjectManagerScreen::EngineSettings); - } - } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h index d5c586e59b..74db3467c5 100644 --- a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h +++ b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h @@ -13,17 +13,9 @@ #if !defined(Q_MOC_RUN) #include - -#include - #include #endif -namespace Ui -{ - class ProjectManagerWindowClass; -} - namespace O3DE::ProjectManager { class ProjectManagerWindow @@ -35,13 +27,7 @@ namespace O3DE::ProjectManager explicit ProjectManagerWindow(QWidget* parent, const AZ::IO::PathView& engineRootPath); ~ProjectManagerWindow(); - protected slots: - void HandleProjectsMenu(); - void HandleEngineMenu(); - private: - QScopedPointer m_ui; - ScreensCtrl* m_screensCtrl; AZStd::unique_ptr m_pythonBindings; }; diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.ui b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.ui deleted file mode 100644 index 633cd61182..0000000000 --- a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.ui +++ /dev/null @@ -1,67 +0,0 @@ - - - ProjectManagerWindowClass - - - - 0 - 0 - 1200 - 800 - - - - - 0 - 0 - - - - O3DE Project Manager - - - - - - - - 0 - 0 - 1200 - 36 - - - - - 16 - - - - - Icon - - - - :/o3de_editor.ico:/o3de_editor.ico - - - - - Projects - - - - - Engine - - - - - - - - - - - - diff --git a/Code/Tools/ProjectManager/Source/ProjectsHomeScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectsHomeScreen.cpp deleted file mode 100644 index 6c60685358..0000000000 --- a/Code/Tools/ProjectManager/Source/ProjectsHomeScreen.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace O3DE::ProjectManager -{ - ProjectsHomeScreen::ProjectsHomeScreen(QWidget* parent) - : ScreenWidget(parent) - { - QVBoxLayout* vLayout = new QVBoxLayout(); - setLayout(vLayout); - vLayout->setContentsMargins(s_contentMargins, s_contentMargins, s_contentMargins, s_contentMargins); - - QHBoxLayout* topLayout = new QHBoxLayout(); - - QLabel* titleLabel = new QLabel(this); - titleLabel->setText("My Projects"); - titleLabel->setStyleSheet("font-size: 24px"); - topLayout->addWidget(titleLabel); - - QSpacerItem* topSpacer = new QSpacerItem(s_spacerSize, s_spacerSize, QSizePolicy::Expanding, QSizePolicy::Minimum); - topLayout->addItem(topSpacer); - - QMenu* newProjectMenu = new QMenu(this); - m_createNewProjectAction = newProjectMenu->addAction("Create New Project"); - m_addExistingProjectAction = newProjectMenu->addAction("Add Existing Project"); - - QPushButton* newProjectMenuButton = new QPushButton(this); - newProjectMenuButton->setText("New Project..."); - newProjectMenuButton->setMenu(newProjectMenu); - newProjectMenuButton->setFixedWidth(s_newProjectButtonWidth); - newProjectMenuButton->setStyleSheet("font-size: 14px;"); - topLayout->addWidget(newProjectMenuButton); - - vLayout->addLayout(topLayout); - - // Get all projects and create a horizontal scrolling list of them - auto projectsResult = PythonBindingsInterface::Get()->GetProjects(); - if (projectsResult.IsSuccess() && !projectsResult.GetValue().isEmpty()) - { - QScrollArea* projectsScrollArea = new QScrollArea(this); - QWidget* scrollWidget = new QWidget(); - QGridLayout* projectGridLayout = new QGridLayout(); - scrollWidget->setLayout(projectGridLayout); - projectsScrollArea->setWidget(scrollWidget); - projectsScrollArea->setWidgetResizable(true); - - int gridIndex = 0; - for (auto project : projectsResult.GetValue()) - { - ProjectButton* projectButton; - QString projectPreviewPath = project.m_path + m_projectPreviewImagePath; - QFileInfo doesPreviewExist(projectPreviewPath); - if (doesPreviewExist.exists() && doesPreviewExist.isFile()) - { - projectButton = new ProjectButton(project.m_projectName, projectPreviewPath, this); - } - else - { - projectButton = new ProjectButton(project.m_projectName, this); - } - - // Create rows of projects buttons s_projectButtonRowCount buttons wide - projectGridLayout->addWidget(projectButton, gridIndex / s_projectButtonRowCount, gridIndex % s_projectButtonRowCount); - - connect(projectButton, &ProjectButton::OpenProject, this, &ProjectsHomeScreen::HandleOpenProject); - connect(projectButton, &ProjectButton::EditProject, this, &ProjectsHomeScreen::HandleEditProject); - -#ifdef SHOW_ALL_PROJECT_ACTIONS - connect(projectButton, &ProjectButton::EditProjectGems, this, &ProjectsHomeScreen::HandleEditProjectGems); - connect(projectButton, &ProjectButton::CopyProject, this, &ProjectsHomeScreen::HandleCopyProject); - connect(projectButton, &ProjectButton::RemoveProject, this, &ProjectsHomeScreen::HandleRemoveProject); - connect(projectButton, &ProjectButton::DeleteProject, this, &ProjectsHomeScreen::HandleDeleteProject); -#endif - ++gridIndex; - } - - vLayout->addWidget(projectsScrollArea); - } - - // Using border-image allows for scaling options background-image does not support - setStyleSheet("O3DE--ProjectManager--ScreenWidget { border-image: url(:/Backgrounds/FirstTimeBackgroundImage.jpg) repeat repeat; }"); - - connect(m_createNewProjectAction, &QAction::triggered, this, &ProjectsHomeScreen::HandleNewProjectButton); - connect(m_addExistingProjectAction, &QAction::triggered, this, &ProjectsHomeScreen::HandleAddProjectButton); - } - - ProjectManagerScreen ProjectsHomeScreen::GetScreenEnum() - { - return ProjectManagerScreen::ProjectsHome; - } - - void ProjectsHomeScreen::HandleNewProjectButton() - { - emit ResetScreenRequest(ProjectManagerScreen::CreateProject); - emit ChangeScreenRequest(ProjectManagerScreen::CreateProject); - } - void ProjectsHomeScreen::HandleAddProjectButton() - { - // Do nothing for now - } - void ProjectsHomeScreen::HandleOpenProject(const QString& projectPath) - { - if (!projectPath.isEmpty()) - { - AZ::IO::FixedMaxPath executableDirectory = AZ::Utils::GetExecutableDirectory(); - AZStd::string executableFilename = "Editor"; - AZ::IO::FixedMaxPath editorExecutablePath = executableDirectory / (executableFilename + AZ_TRAIT_OS_EXECUTABLE_EXTENSION); - auto cmdPath = AZ::IO::FixedMaxPathString::format("%s -regset=\"/Amazon/AzCore/Bootstrap/project_path=%s\"", editorExecutablePath.c_str(), projectPath.toStdString().c_str()); - - AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; - processLaunchInfo.m_commandlineParameters = cmdPath; - bool launchSucceeded = AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo); - if (!launchSucceeded) - { - AZ_Error("ProjectManager", false, "Failed to launch editor"); - QMessageBox::critical( this, tr("Error"), tr("Failed to launch the Editor, please verify the project settings are valid.")); - } - else - { - // prevent the user from accidentally pressing the button while the editor is launching - // and let them know what's happening - ProjectButton* button = qobject_cast(sender()); - if (button) - { - button->SetButtonEnabled(false); - button->SetButtonOverlayText(tr("Opening Editor...")); - } - - // enable the button after 3 seconds - constexpr int waitTimeInMs = 3000; - QTimer::singleShot(waitTimeInMs, this, [this, button] { - if (button) - { - button->SetButtonEnabled(true); - } - }); - } - } - else - { - AZ_Error("ProjectManager", false, "Cannot open editor because an empty project path was provided"); - QMessageBox::critical( this, tr("Error"), tr("Failed to launch the Editor because the project path is invalid.")); - } - - } - void ProjectsHomeScreen::HandleEditProject(const QString& projectPath) - { - emit NotifyCurrentProject(projectPath); - emit ResetScreenRequest(ProjectManagerScreen::UpdateProject); - emit ChangeScreenRequest(ProjectManagerScreen::UpdateProject); - } - void ProjectsHomeScreen::HandleEditProjectGems(const QString& projectPath) - { - emit NotifyCurrentProject(projectPath); - emit ChangeScreenRequest(ProjectManagerScreen::GemCatalog); - } - void ProjectsHomeScreen::HandleCopyProject([[maybe_unused]] const QString& projectPath) - { - // Open file dialog and choose location for copied project then register copy with O3DE - } - void ProjectsHomeScreen::HandleRemoveProject([[maybe_unused]] const QString& projectPath) - { - // Unregister Project from O3DE - } - void ProjectsHomeScreen::HandleDeleteProject([[maybe_unused]] const QString& projectPath) - { - // Remove project from 03DE and delete from disk - ProjectsHomeScreen::HandleRemoveProject(projectPath); - } - -} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp new file mode 100644 index 0000000000..5f1c0e2b36 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp @@ -0,0 +1,347 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +//#define DISPLAY_PROJECT_DEV_DATA true + +namespace O3DE::ProjectManager +{ + ProjectsScreen::ProjectsScreen(QWidget* parent) + : ScreenWidget(parent) + { + QVBoxLayout* vLayout = new QVBoxLayout(); + vLayout->setAlignment(Qt::AlignTop); + vLayout->setContentsMargins(s_contentMargins, 0, s_contentMargins, 0); + setLayout(vLayout); + + m_background.load(":/Backgrounds/FirstTimeBackgroundImage.jpg"); + + m_stack = new QStackedWidget(this); + + m_firstTimeContent = CreateFirstTimeContent(); + m_stack->addWidget(m_firstTimeContent); + + m_projectsContent = CreateProjectsContent(); + m_stack->addWidget(m_projectsContent); + + vLayout->addWidget(m_stack); + + connect(m_createNewProjectAction, &QAction::triggered, this, &ProjectsScreen::HandleNewProjectButton); + connect(m_addExistingProjectAction, &QAction::triggered, this, &ProjectsScreen::HandleAddProjectButton); + } + + QFrame* ProjectsScreen::CreateFirstTimeContent() + { + QFrame* frame = new QFrame(this); + frame->setObjectName("firstTimeContent"); + { + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->setAlignment(Qt::AlignTop); + frame->setLayout(layout); + + QLabel* titleLabel = new QLabel(tr("Ready. Set. Create."), this); + titleLabel->setObjectName("titleLabel"); + layout->addWidget(titleLabel); + + QLabel* introLabel = new QLabel(this); + introLabel->setObjectName("introLabel"); + introLabel->setText(tr("Welcome to O3DE! Start something new by creating a project. Not sure what to create? \nExplore what's " + "available by downloading our sample project.")); + layout->addWidget(introLabel); + + QHBoxLayout* buttonLayout = new QHBoxLayout(this); + buttonLayout->setAlignment(Qt::AlignLeft); + buttonLayout->setSpacing(s_spacerSize); + + // use a newline to force the text up + QPushButton* createProjectButton = new QPushButton(tr("Create a Project\n"), this); + createProjectButton->setObjectName("createProjectButton"); + buttonLayout->addWidget(createProjectButton); + + QPushButton* addProjectButton = new QPushButton(tr("Add a Project\n"), this); + addProjectButton->setObjectName("addProjectButton"); + buttonLayout->addWidget(addProjectButton); + + connect(createProjectButton, &QPushButton::clicked, this, &ProjectsScreen::HandleNewProjectButton); + connect(addProjectButton, &QPushButton::clicked, this, &ProjectsScreen::HandleAddProjectButton); + + layout->addLayout(buttonLayout); + } + + return frame; + } + + QFrame* ProjectsScreen::CreateProjectsContent() + { + QFrame* frame = new QFrame(this); + frame->setObjectName("projectsContent"); + { + QVBoxLayout* layout = new QVBoxLayout(); + layout->setAlignment(Qt::AlignTop); + layout->setContentsMargins(0, 0, 0, 0); + frame->setLayout(layout); + + QFrame* header = new QFrame(this); + QHBoxLayout* headerLayout = new QHBoxLayout(); + { + QLabel* titleLabel = new QLabel(tr("My Projects"), this); + titleLabel->setObjectName("titleLabel"); + headerLayout->addWidget(titleLabel); + + QMenu* newProjectMenu = new QMenu(this); + m_createNewProjectAction = newProjectMenu->addAction("Create New Project"); + m_addExistingProjectAction = newProjectMenu->addAction("Add Existing Project"); + + connect(m_createNewProjectAction, &QAction::triggered, this, &ProjectsScreen::HandleNewProjectButton); + connect(m_addExistingProjectAction, &QAction::triggered, this, &ProjectsScreen::HandleAddProjectButton); + + QPushButton* newProjectMenuButton = new QPushButton(tr("New Project..."), this); + newProjectMenuButton->setObjectName("newProjectButton"); + newProjectMenuButton->setMenu(newProjectMenu); + newProjectMenuButton->setDefault(true); + headerLayout->addWidget(newProjectMenuButton); + } + header->setLayout(headerLayout); + + layout->addWidget(header); + + // Get all projects and create a horizontal scrolling list of them + auto projectsResult = PythonBindingsInterface::Get()->GetProjects(); + if (projectsResult.IsSuccess() && !projectsResult.GetValue().isEmpty()) + { + QScrollArea* projectsScrollArea = new QScrollArea(this); + QWidget* scrollWidget = new QWidget(); + + FlowLayout* flowLayout = new FlowLayout(0, s_spacerSize, s_spacerSize); + scrollWidget->setLayout(flowLayout); + + projectsScrollArea->setWidget(scrollWidget); + projectsScrollArea->setWidgetResizable(true); + +#ifndef DISPLAY_PROJECT_DEV_DATA + for (auto project : projectsResult.GetValue()) +#else + ProjectInfo project = projectsResult.GetValue().at(0); + for (int i = 0; i < 15; i++) +#endif + { + ProjectButton* projectButton; + QString projectPreviewPath = project.m_path + m_projectPreviewImagePath; + QFileInfo doesPreviewExist(projectPreviewPath); + if (doesPreviewExist.exists() && doesPreviewExist.isFile()) + { + projectButton = new ProjectButton(project.m_projectName, projectPreviewPath, this); + } + else + { + projectButton = new ProjectButton(project.m_projectName, this); + } + + flowLayout->addWidget(projectButton); + + connect(projectButton, &ProjectButton::OpenProject, this, &ProjectsScreen::HandleOpenProject); + connect(projectButton, &ProjectButton::EditProject, this, &ProjectsScreen::HandleEditProject); + + #ifdef DISPLAY_PROJECT_DEV_DATA + connect(projectButton, &ProjectButton::EditProjectGems, this, &ProjectsScreen::HandleEditProjectGems); + connect(projectButton, &ProjectButton::CopyProject, this, &ProjectsScreen::HandleCopyProject); + connect(projectButton, &ProjectButton::RemoveProject, this, &ProjectsScreen::HandleRemoveProject); + connect(projectButton, &ProjectButton::DeleteProject, this, &ProjectsScreen::HandleDeleteProject); + #endif + } + + layout->addWidget(projectsScrollArea); + } + } + + return frame; + } + + ProjectManagerScreen ProjectsScreen::GetScreenEnum() + { + return ProjectManagerScreen::Projects; + } + + bool ProjectsScreen::IsTab() + { + return true; + } + + QString ProjectsScreen::GetTabText() + { + return tr("Projects"); + } + + void ProjectsScreen::paintEvent([[maybe_unused]] QPaintEvent* event) + { + // we paint the background here because qss does not support background cover scaling + QPainter painter(this); + + auto winSize = size(); + auto pixmapRatio = (float)m_background.width() / m_background.height(); + auto windowRatio = (float)winSize.width() / winSize.height(); + + if (pixmapRatio > windowRatio) + { + auto newWidth = (int)(winSize.height() * pixmapRatio); + auto offset = (newWidth - winSize.width()) / -2; + painter.drawPixmap(offset, 0, newWidth, winSize.height(), m_background); + } + else + { + auto newHeight = (int)(winSize.width() / pixmapRatio); + painter.drawPixmap(0, 0, winSize.width(), newHeight, m_background); + } + } + + void ProjectsScreen::HandleNewProjectButton() + { + emit ResetScreenRequest(ProjectManagerScreen::CreateProject); + emit ChangeScreenRequest(ProjectManagerScreen::CreateProject); + } + void ProjectsScreen::HandleAddProjectButton() + { + // Do nothing for now + } + void ProjectsScreen::HandleOpenProject(const QString& projectPath) + { + if (!projectPath.isEmpty()) + { + AZ::IO::FixedMaxPath executableDirectory = AZ::Utils::GetExecutableDirectory(); + AZStd::string executableFilename = "Editor"; + AZ::IO::FixedMaxPath editorExecutablePath = executableDirectory / (executableFilename + AZ_TRAIT_OS_EXECUTABLE_EXTENSION); + auto cmdPath = AZ::IO::FixedMaxPathString::format("%s -regset=\"/Amazon/AzCore/Bootstrap/project_path=%s\"", editorExecutablePath.c_str(), projectPath.toStdString().c_str()); + + AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; + processLaunchInfo.m_commandlineParameters = cmdPath; + bool launchSucceeded = AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo); + if (!launchSucceeded) + { + AZ_Error("ProjectManager", false, "Failed to launch editor"); + QMessageBox::critical( this, tr("Error"), tr("Failed to launch the Editor, please verify the project settings are valid.")); + } + else + { + // prevent the user from accidentally pressing the button while the editor is launching + // and let them know what's happening + ProjectButton* button = qobject_cast(sender()); + if (button) + { + button->SetButtonEnabled(false); + button->SetButtonOverlayText(tr("Opening Editor...")); + } + + // enable the button after 3 seconds + constexpr int waitTimeInMs = 3000; + QTimer::singleShot(waitTimeInMs, this, [this, button] { + if (button) + { + button->SetButtonEnabled(true); + } + }); + } + } + else + { + AZ_Error("ProjectManager", false, "Cannot open editor because an empty project path was provided"); + QMessageBox::critical( this, tr("Error"), tr("Failed to launch the Editor because the project path is invalid.")); + } + + } + void ProjectsScreen::HandleEditProject(const QString& projectPath) + { + emit NotifyCurrentProject(projectPath); + emit ResetScreenRequest(ProjectManagerScreen::UpdateProject); + emit ChangeScreenRequest(ProjectManagerScreen::UpdateProject); + } + void ProjectsScreen::HandleEditProjectGems(const QString& projectPath) + { + emit NotifyCurrentProject(projectPath); + emit ChangeScreenRequest(ProjectManagerScreen::GemCatalog); + } + void ProjectsScreen::HandleCopyProject([[maybe_unused]] const QString& projectPath) + { + // Open file dialog and choose location for copied project then register copy with O3DE + } + void ProjectsScreen::HandleRemoveProject([[maybe_unused]] const QString& projectPath) + { + // Unregister Project from O3DE + } + void ProjectsScreen::HandleDeleteProject([[maybe_unused]] const QString& projectPath) + { + // Remove project from 03DE and delete from disk + ProjectsScreen::HandleRemoveProject(projectPath); + } + + void ProjectsScreen::NotifyCurrentScreen() + { + if (ShouldDisplayFirstTimeContent()) + { + m_stack->setCurrentWidget(m_firstTimeContent); + } + else + { + m_stack->setCurrentWidget(m_projectsContent); + } + } + + bool ProjectsScreen::ShouldDisplayFirstTimeContent() + { + auto projectsResult = PythonBindingsInterface::Get()->GetProjects(); + if (!projectsResult.IsSuccess() || projectsResult.GetValue().isEmpty()) + { + return true; + } + + QSettings settings; + bool displayFirstTimeContent = settings.value("displayFirstTimeContent", true).toBool(); + if (displayFirstTimeContent) + { + settings.setValue("displayFirstTimeContent", false); + } + + return displayFirstTimeContent; + } + +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectsHomeScreen.h b/Code/Tools/ProjectManager/Source/ProjectsScreen.h similarity index 69% rename from Code/Tools/ProjectManager/Source/ProjectsHomeScreen.h rename to Code/Tools/ProjectManager/Source/ProjectsScreen.h index e8d1ac4fb5..d88ba8398d 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsHomeScreen.h +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.h @@ -15,16 +15,26 @@ #include #endif +QT_FORWARD_DECLARE_CLASS(QPaintEvent) +QT_FORWARD_DECLARE_CLASS(QFrame) +QT_FORWARD_DECLARE_CLASS(QStackedWidget) + namespace O3DE::ProjectManager { - class ProjectsHomeScreen + class ProjectsScreen : public ScreenWidget { public: - explicit ProjectsHomeScreen(QWidget* parent = nullptr); - ~ProjectsHomeScreen() = default; + explicit ProjectsScreen(QWidget* parent = nullptr); + ~ProjectsScreen() = default; + ProjectManagerScreen GetScreenEnum() override; + QString GetTabText() override; + bool IsTab() override; + + protected: + void NotifyCurrentScreen() override; protected slots: void HandleNewProjectButton(); @@ -36,16 +46,24 @@ namespace O3DE::ProjectManager void HandleRemoveProject(const QString& projectPath); void HandleDeleteProject(const QString& projectPath); + void paintEvent(QPaintEvent* event) override; + private: + QFrame* CreateFirstTimeContent(); + QFrame* CreateProjectsContent(); + bool ShouldDisplayFirstTimeContent(); + QAction* m_createNewProjectAction; QAction* m_addExistingProjectAction; + QPixmap m_background; + QFrame* m_firstTimeContent; + QFrame* m_projectsContent; + QStackedWidget* m_stack; const QString m_projectPreviewImagePath = "/preview.png"; + inline constexpr static int s_contentMargins = 80; inline constexpr static int s_spacerSize = 20; - inline constexpr static int s_projectButtonRowCount = 4; - inline constexpr static int s_newProjectButtonWidth = 156; - }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ScreenDefs.h b/Code/Tools/ProjectManager/Source/ScreenDefs.h index 13289e2481..46d243f677 100644 --- a/Code/Tools/ProjectManager/Source/ScreenDefs.h +++ b/Code/Tools/ProjectManager/Source/ScreenDefs.h @@ -17,11 +17,10 @@ namespace O3DE::ProjectManager { Invalid = -1, Empty, - FirstTimeUse, CreateProject, NewProjectSettings, GemCatalog, - ProjectsHome, + Projects, UpdateProject, ProjectSettings, EngineSettings diff --git a/Code/Tools/ProjectManager/Source/ScreenFactory.cpp b/Code/Tools/ProjectManager/Source/ScreenFactory.cpp index d37ccdb59f..b2b4376e14 100644 --- a/Code/Tools/ProjectManager/Source/ScreenFactory.cpp +++ b/Code/Tools/ProjectManager/Source/ScreenFactory.cpp @@ -11,12 +11,11 @@ */ #include -#include #include #include #include #include -#include +#include #include #include @@ -28,9 +27,6 @@ namespace O3DE::ProjectManager switch(screen) { - case (ProjectManagerScreen::FirstTimeUse): - newScreen = new FirstTimeUseScreen(parent); - break; case (ProjectManagerScreen::CreateProject): newScreen = new CreateProjectCtrl(parent); break; @@ -40,8 +36,8 @@ namespace O3DE::ProjectManager case (ProjectManagerScreen::GemCatalog): newScreen = new GemCatalogScreen(parent); break; - case (ProjectManagerScreen::ProjectsHome): - newScreen = new ProjectsHomeScreen(parent); + case (ProjectManagerScreen::Projects): + newScreen = new ProjectsScreen(parent); break; case (ProjectManagerScreen::UpdateProject): newScreen = new UpdateProjectCtrl(parent); diff --git a/Code/Tools/ProjectManager/Source/ScreenHeaderWidget.cpp b/Code/Tools/ProjectManager/Source/ScreenHeaderWidget.cpp new file mode 100644 index 0000000000..29b1eb6ff6 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ScreenHeaderWidget.cpp @@ -0,0 +1,62 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include +#include + +namespace O3DE::ProjectManager +{ + ScreenHeader::ScreenHeader(QWidget* parent) + : QFrame(parent) + { + setObjectName("header"); + + QHBoxLayout* layout = new QHBoxLayout(); + layout->setAlignment(Qt::AlignLeft); + layout->setContentsMargins(0,0,0,0); + + m_backButton = new QPushButton(); + m_backButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); + layout->addWidget(m_backButton); + + QVBoxLayout* titleLayout = new QVBoxLayout(); + m_title = new QLabel(); + m_title->setObjectName("headerTitle"); + titleLayout->addWidget(m_title); + + m_subTitle = new QLabel(); + m_subTitle->setObjectName("headerSubTitle"); + titleLayout->addWidget(m_subTitle); + + layout->addLayout(titleLayout); + + setLayout(layout); + } + + void ScreenHeader::setTitle(const QString& text) + { + m_title->setText(text); + } + + void ScreenHeader::setSubTitle(const QString& text) + { + m_subTitle->setText(text); + } + + QPushButton* ScreenHeader::backButton() + { + return m_backButton; + } + +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ScreenHeaderWidget.h b/Code/Tools/ProjectManager/Source/ScreenHeaderWidget.h new file mode 100644 index 0000000000..c5fdb56195 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ScreenHeaderWidget.h @@ -0,0 +1,42 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#endif + +QT_FORWARD_DECLARE_CLASS(QLabel) +QT_FORWARD_DECLARE_CLASS(QPushButton) + +namespace O3DE::ProjectManager +{ + class ScreenHeader + : public QFrame + { + Q_OBJECT // AUTOMOC + + public: + ScreenHeader(QWidget* parent = nullptr); + + void setTitle(const QString& text); + void setSubTitle(const QString& text); + + QPushButton* backButton(); + + private: + QLabel* m_title; + QLabel* m_subTitle; + QPushButton* m_backButton; + }; +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ScreenWidget.h b/Code/Tools/ProjectManager/Source/ScreenWidget.h index e80747d67b..2ad6d30201 100644 --- a/Code/Tools/ProjectManager/Source/ScreenWidget.h +++ b/Code/Tools/ProjectManager/Source/ScreenWidget.h @@ -41,12 +41,27 @@ namespace O3DE::ProjectManager { return true; } + virtual bool IsTab() + { + return false; + } + virtual QString GetTabText() + { + return tr("Missing"); + } + + //! Notify this screen it is the current screen + virtual void NotifyCurrentScreen() + { + + } signals: void ChangeScreenRequest(ProjectManagerScreen screen); void GotoPreviousScreenRequest(); void ResetScreenRequest(ProjectManagerScreen screen); void NotifyCurrentProject(const QString& projectPath); + }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp b/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp index a77c434026..7d31d02f6c 100644 --- a/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp @@ -14,6 +14,7 @@ #include #include +#include #include namespace O3DE::ProjectManager @@ -21,17 +22,19 @@ namespace O3DE::ProjectManager ScreensCtrl::ScreensCtrl(QWidget* parent) : QWidget(parent) { + setObjectName("ScreensCtrl"); + QVBoxLayout* vLayout = new QVBoxLayout(); - vLayout->setMargin(0); - vLayout->setSpacing(0); vLayout->setContentsMargins(0, 0, 0, 0); setLayout(vLayout); m_screenStack = new QStackedWidget(); vLayout->addWidget(m_screenStack); - //Track the bottom of the stack - m_screenVisitOrder.push(ProjectManagerScreen::Invalid); + // add a tab widget at the bottom of the stack + m_tabWidget = new QTabWidget(); + m_screenStack->addWidget(m_tabWidget); + connect(m_tabWidget, &QTabWidget::currentChanged, this, &ScreensCtrl::TabChanged); } void ScreensCtrl::BuildScreens(QVector screens) @@ -57,7 +60,14 @@ namespace O3DE::ProjectManager ScreenWidget* ScreensCtrl::GetCurrentScreen() { - return reinterpret_cast(m_screenStack->currentWidget()); + if (m_screenStack->currentWidget() == m_tabWidget) + { + return reinterpret_cast(m_tabWidget->currentWidget()); + } + else + { + return reinterpret_cast(m_screenStack->currentWidget()); + } } bool ScreensCtrl::ChangeToScreen(ProjectManagerScreen screen) @@ -79,13 +89,28 @@ namespace O3DE::ProjectManager if (iterator != m_screenMap.end()) { ScreenWidget* currentScreen = GetCurrentScreen(); - if (currentScreen != iterator.value()) + ScreenWidget* newScreen = iterator.value(); + + if (currentScreen != newScreen) { if (addVisit) { - m_screenVisitOrder.push(currentScreen->GetScreenEnum()); + ProjectManagerScreen oldScreen = currentScreen->GetScreenEnum(); + m_screenVisitOrder.push(oldScreen); } - m_screenStack->setCurrentWidget(iterator.value()); + + if (newScreen->IsTab()) + { + m_tabWidget->setCurrentWidget(newScreen); + m_screenStack->setCurrentWidget(m_tabWidget); + } + else + { + m_screenStack->setCurrentWidget(newScreen); + } + + newScreen->NotifyCurrentScreen(); + return true; } } @@ -95,23 +120,46 @@ namespace O3DE::ProjectManager bool ScreensCtrl::GotoPreviousScreen() { - // Don't go back if we are on the first set screen - if (m_screenVisitOrder.top() != ProjectManagerScreen::Invalid) + if (!m_screenVisitOrder.isEmpty()) { // We do not check with screen if we can go back, we should always be able to go back - return ForceChangeToScreen(m_screenVisitOrder.pop(), false); + ProjectManagerScreen previousScreen = m_screenVisitOrder.pop(); + return ForceChangeToScreen(previousScreen, false); } return false; } void ScreensCtrl::ResetScreen(ProjectManagerScreen screen) { + bool shouldRestoreCurrentScreen = false; + if (GetCurrentScreen() && GetCurrentScreen()->GetScreenEnum() == screen) + { + shouldRestoreCurrentScreen = true; + } + // Delete old screen if it exists to start fresh DeleteScreen(screen); // Add new screen ScreenWidget* newScreen = BuildScreen(this, screen); - m_screenStack->addWidget(newScreen); + if (newScreen->IsTab()) + { + m_tabWidget->addTab(newScreen, newScreen->GetTabText()); + if (shouldRestoreCurrentScreen) + { + m_tabWidget->setCurrentWidget(newScreen); + m_screenStack->setCurrentWidget(m_tabWidget); + } + } + else + { + m_screenStack->addWidget(newScreen); + if (shouldRestoreCurrentScreen) + { + m_screenStack->setCurrentWidget(newScreen); + } + } + m_screenMap.insert(screen, newScreen); connect(newScreen, &ScreenWidget::ChangeScreenRequest, this, &ScreensCtrl::ChangeToScreen); @@ -134,8 +182,21 @@ namespace O3DE::ProjectManager const auto iter = m_screenMap.find(screen); if (iter != m_screenMap.end()) { - m_screenStack->removeWidget(iter.value()); - iter.value()->deleteLater(); + ScreenWidget* screenToDelete = iter.value(); + if (screenToDelete->IsTab()) + { + int tabIndex = m_tabWidget->indexOf(screenToDelete); + if (tabIndex > -1) + { + m_tabWidget->removeTab(tabIndex); + } + } + else + { + // if the screen we delete is the current widget, a new one will + // be selected automatically (randomly?) + m_screenStack->removeWidget(screenToDelete); + } // Erase does not cause a rehash so interators remain valid m_screenMap.erase(iter); @@ -150,4 +211,12 @@ namespace O3DE::ProjectManager } } + void ScreensCtrl::TabChanged([[maybe_unused]] int index) + { + ScreenWidget* screen = reinterpret_cast(m_tabWidget->currentWidget()); + if (screen) + { + screen->NotifyCurrentScreen(); + } + } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ScreensCtrl.h b/Code/Tools/ProjectManager/Source/ScreensCtrl.h index a9d1023b4b..935fc78e25 100644 --- a/Code/Tools/ProjectManager/Source/ScreensCtrl.h +++ b/Code/Tools/ProjectManager/Source/ScreensCtrl.h @@ -18,6 +18,8 @@ #include #endif +QT_FORWARD_DECLARE_CLASS(QTabWidget) + namespace O3DE::ProjectManager { class ScreenWidget; @@ -46,11 +48,13 @@ namespace O3DE::ProjectManager void ResetAllScreens(); void DeleteScreen(ProjectManagerScreen screen); void DeleteAllScreens(); + void TabChanged(int index); private: QStackedWidget* m_screenStack; QHash m_screenMap; QStack m_screenVisitOrder; + QTabWidget* m_tabWidget; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp index 84e3d8359d..b3180966ce 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp @@ -108,7 +108,7 @@ namespace O3DE::ProjectManager auto result = PythonBindingsInterface::Get()->UpdateProject(m_projectInfo); if (result) { - emit ChangeScreenRequest(ProjectManagerScreen::ProjectsHome); + emit ChangeScreenRequest(ProjectManagerScreen::Projects); } else { diff --git a/Code/Tools/ProjectManager/Source/main.cpp b/Code/Tools/ProjectManager/Source/main.cpp index 3d8bb71a0c..cbeacbaf65 100644 --- a/Code/Tools/ProjectManager/Source/main.cpp +++ b/Code/Tools/ProjectManager/Source/main.cpp @@ -35,7 +35,6 @@ int main(int argc, char* argv[]) QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::SystemDpiAware); - AZ::AllocatorInstance::Create(); int runSuccess = 0; { @@ -55,6 +54,12 @@ int main(int argc, char* argv[]) O3DE::ProjectManager::ProjectManagerWindow window(nullptr, engineRootPath); window.show(); + // somethings is preventing us from moving the window to the center of the + // primary screen - likely an Az style or component helper + constexpr int width = 1200; + constexpr int height = 800; + window.resize(width, height); + runSuccess = app.exec(); } AZ::AllocatorInstance::Destroy(); diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index a41ddad21e..223465f3c8 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -21,8 +21,6 @@ set(FILES Source/ScreenWidget.h Source/EngineInfo.h Source/EngineInfo.cpp - Source/FirstTimeUseScreen.h - Source/FirstTimeUseScreen.cpp Source/FormLineEditWidget.h Source/FormLineEditWidget.cpp Source/FormBrowseEditWidget.h @@ -33,7 +31,6 @@ set(FILES Source/ProjectManagerWindow.cpp Source/ProjectTemplateInfo.h Source/ProjectTemplateInfo.cpp - Source/ProjectManagerWindow.ui Source/PythonBindings.h Source/PythonBindings.cpp Source/PythonBindingsInterface.h @@ -45,8 +42,8 @@ set(FILES Source/CreateProjectCtrl.cpp Source/UpdateProjectCtrl.h Source/UpdateProjectCtrl.cpp - Source/ProjectsHomeScreen.h - Source/ProjectsHomeScreen.cpp + Source/ProjectsScreen.h + Source/ProjectsScreen.cpp Source/ProjectSettingsScreen.h Source/ProjectSettingsScreen.cpp Source/ProjectSettingsScreen.ui @@ -54,6 +51,8 @@ set(FILES Source/EngineSettingsScreen.cpp Source/ProjectButtonWidget.h Source/ProjectButtonWidget.cpp + Source/ScreenHeaderWidget.h + Source/ScreenHeaderWidget.cpp Source/LinkWidget.h Source/LinkWidget.cpp Source/TagWidget.h diff --git a/Templates/DefaultProject/Template/preview.png b/Templates/DefaultProject/Template/preview.png index 2191a0ebc2..3d4fe78063 100644 --- a/Templates/DefaultProject/Template/preview.png +++ b/Templates/DefaultProject/Template/preview.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a18fae4040a22d2bb359a8ca642b97bb8f6468eeb52e2826b3b029bd8f1350b6 -size 5466 +oid sha256:40949893ed7009eeaa90b7ce6057cb6be9dfaf7b162e3c26ba9dadf985939d7d +size 2038 From 883ddf667e70fe61491dcc2a7162e59bc5d46166 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 26 May 2021 20:19:42 -0700 Subject: [PATCH 198/811] [cpack_installer] removed static cmake package in favor of using file(DOWNLOAD ...) --- .../CMake/cmake-3.19.1-win64-x64.zip | 3 -- cmake/Packaging.cmake | 37 +++++++++++++++++++ cmake/Platform/Common/Install_common.cmake | 2 +- .../Windows/Packaging/PostInstallSetup.wxs | 6 +-- .../Platform/Windows/Packaging_windows.cmake | 5 +++ 5 files changed, 45 insertions(+), 8 deletions(-) delete mode 100644 Tools/Redistributables/CMake/cmake-3.19.1-win64-x64.zip diff --git a/Tools/Redistributables/CMake/cmake-3.19.1-win64-x64.zip b/Tools/Redistributables/CMake/cmake-3.19.1-win64-x64.zip deleted file mode 100644 index fc3a243f06..0000000000 --- a/Tools/Redistributables/CMake/cmake-3.19.1-win64-x64.zip +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e95d70549f306adb46e0f131dcecdbcbc6412d3a1e073c2c0078812391bf21d3 -size 36098689 diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index fbeffa94eb..7766d7d0ee 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -17,6 +17,8 @@ endif() set(LY_INSTALLER_DOWNLOAD_URL "" CACHE STRING "URL embedded into the installer to download additional artifacts") set(LY_INSTALLER_LICENSE_URL "" CACHE STRING "Optionally embed a link to the license instead of raw text") +set(CPACK_DESIRED_CMAKE_VERSION 3.20.2) + # set all common cpack variable overrides first so they can be accessible via configure_file # when the platform specific settings are applied below. additionally, any variable with # the "CPACK_" prefix will automatically be cached for use in any phase of cpack namely @@ -38,6 +40,7 @@ set(CPACK_PACKAGE_INSTALL_DIRECTORY "${CPACK_PACKAGE_VENDOR}/${CPACK_PACKAGE_VER # neither of the SOURCE_DIR variables equate to anything during execution of pre/post build scripts set(CPACK_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/cmake) +set(CPACK_BINARY_DIR ${CMAKE_BINARY_DIR}/_CPack) # to match other CPack out dirs # attempt to apply platform specific settings ly_get_absolute_pal_filename(pal_dir ${CPACK_SOURCE_DIR}/Platform/${PAL_HOST_PLATFORM_NAME}) @@ -48,6 +51,40 @@ if(NOT CPACK_GENERATOR) return() endif() +# pull down the desired copy of CMake so it can be included in the package +if(NOT (CPACK_CMAKE_PACKAGE_FILE AND CPACK_CMAKE_PACKAGE_HASH)) + message(FATAL_ERROR + "Packaging is missing one or more following properties required to include CMake: " + " CPACK_CMAKE_PACKAGE_FILE, CPACK_CMAKE_PACKAGE_HASH") +endif() + +set(_cmake_package_dest ${CPACK_BINARY_DIR}/${CPACK_CMAKE_PACKAGE_FILE}) + +string(REPLACE "." ";" _version_componets "${CPACK_DESIRED_CMAKE_VERSION}") +list(GET _version_componets 0 _major_version) +list(GET _version_componets 1 _minor_version) + +set(_url_version_tag "v${_major_version}.${_minor_version}") + +message(STATUS "Ensuring CMake ${CPACK_DESIRED_CMAKE_VERSION} is avaiable for packaging...") +file(DOWNLOAD + https://cmake.org/files/${_url_version_tag}/${CPACK_CMAKE_PACKAGE_FILE} + ${_cmake_package_dest} +) + +file(SHA256 ${_cmake_package_dest} _package_hash) +if (NOT "${_package_hash}" STREQUAL "${CPACK_CMAKE_PACKAGE_HASH}") + file(REMOVE ${_cmake_package_dest}) + message(FATAL_ERROR "Donwload package of CMake does not match expected hash value. " + "Please double check the properies CPACK_CMAKE_PACKAGE_FILE and CPACK_CMAKE_PACKAGE_HASH " + "before trying again.") +endif() + +install(FILES ${_cmake_package_dest} + DESTINATION ./Tools/Redistributables/CMake + COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} +) + # IMPORTANT: required to be included AFTER setting all property overrides include(CPack REQUIRED) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 46d23f7b91..8fe2fe2c1c 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -286,7 +286,7 @@ endfunction() function(ly_setup_others) # List of directories we want to install relative to engine root - set(DIRECTORIES_TO_INSTALL Tools/LyTestTools Tools/RemoteConsole Tools/Redistributables/CMake) + set(DIRECTORIES_TO_INSTALL Tools/LyTestTools Tools/RemoteConsole) foreach(dir ${DIRECTORIES_TO_INSTALL}) get_filename_component(install_path ${dir} DIRECTORY) diff --git a/cmake/Platform/Windows/Packaging/PostInstallSetup.wxs b/cmake/Platform/Windows/Packaging/PostInstallSetup.wxs index ebcaa9502f..d4f6c181dd 100644 --- a/cmake/Platform/Windows/Packaging/PostInstallSetup.wxs +++ b/cmake/Platform/Windows/Packaging/PostInstallSetup.wxs @@ -43,16 +43,14 @@ - - diff --git a/cmake/Platform/Windows/Packaging_windows.cmake b/cmake/Platform/Windows/Packaging_windows.cmake index b7db250fda..db9c7fc906 100644 --- a/cmake/Platform/Windows/Packaging_windows.cmake +++ b/cmake/Platform/Windows/Packaging_windows.cmake @@ -28,6 +28,10 @@ endif() set(CPACK_GENERATOR "WIX") +set(_cmake_package_name "cmake-${CPACK_DESIRED_CMAKE_VERSION}-windows-x86_64") +set(CPACK_CMAKE_PACKAGE_FILE "${_cmake_package_name}.zip") +set(CPACK_CMAKE_PACKAGE_HASH "15a49e2ab81c1822d75b1b1a92f7863f58e31f6d6aac1c4103eef2b071be3112") + # CPack will generate the WiX product/upgrade GUIDs further down the chain if they weren't supplied # however, they are unique for each run. instead, let's do the auto generation here and add it to # the cache for run persistence and have the ability to detect if they are still being used. @@ -106,4 +110,5 @@ endif() set(CPACK_WIX_CANDLE_EXTRA_FLAGS -dCPACK_EMBED_ARTIFACTS=${_embed_artifacts} + -dCPACK_CMAKE_PACKAGE_NAME=${_cmake_package_name} ) From 7e023c36767b33fe3d78893eaf6120501b611760 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Wed, 26 May 2021 20:23:31 -0700 Subject: [PATCH 199/811] ATOM-15133 "Clean Up EnhancedPBR" Updated material type files for StandardPBR, EnhancedPBR, and Skin to align with each other as much as possible. There were minor cases like some property settings were different, properties in different order, comments, and formatting. There were major cases as well, like EnhancedPBR using clunky built in functors where lua functors would be better, property visibility state wasn't right, properties were missing, etc. I also added a new HasShaderWithTag function for lua functors. This is used in StandardPBR_ShaderEnable.lua to allow this script to be used for both StandardPBR and EnhancedPBR (EnhancedPBR doesn't have the low end pipeline shaders). --- .../Materials/Types/EnhancedPBR.materialtype | 753 ++++-------------- .../Assets/Materials/Types/Skin.materialtype | 41 +- .../Materials/Types/StandardPBR.materialtype | 28 +- .../Types/StandardPBR_ShaderEnable.lua | 30 +- .../RPI.Reflect/Material/LuaMaterialFunctor.h | 1 + .../Material/LuaMaterialFunctor.cpp | 6 + ...SubsurfaceScattering_Transmission.material | 1 - 7 files changed, 240 insertions(+), 620 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index a085afa327..4c988c590a 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -1,5 +1,5 @@ { - "description": "Material Type with properties used to define Enhanced PBR material shading model.", + "description": "Material Type with properties used to define Enhanced PBR, a metallic-roughness Physically-Based Rendering (PBR) material shading model, with advanced features like subsurface scattering, transmission, and anisotropy.", "propertyLayout": { "version": 3, "groups": [ @@ -32,7 +32,7 @@ "id": "clearCoat", "displayName": "Clear Coat", "description": "Properties for configuring gloss clear coat" - }, + }, { "id": "normal", "displayName": "Normal", @@ -205,6 +205,13 @@ "id": "m_baseColorMap" } }, + { + "id": "useTexture", + "displayName": "Use Texture", + "description": "Whether to use the texture map.", + "type": "Bool", + "defaultValue": true + }, { "id": "textureMapUv", "displayName": "UV", @@ -228,13 +235,6 @@ "type": "ShaderOption", "id": "o_baseColorTextureBlendMode" } - }, - { - "id": "useTexture", - "displayName": "Use Texture", - "description": "Whether to use the texture map.", - "type": "Bool", - "defaultValue": true } ], "metallic": [ @@ -261,6 +261,13 @@ "id": "m_metallicMap" } }, + { + "id": "useTexture", + "displayName": "Use Texture", + "description": "Whether to use the texture map, or just default to the Factor value.", + "type": "Bool", + "defaultValue": true + }, { "id": "textureMapUv", "displayName": "UV", @@ -272,29 +279,9 @@ "type": "ShaderInput", "id": "m_metallicMapUvIndex" } - }, - { - "id": "useTexture", - "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", - "type": "Bool", - "defaultValue": true } ], "roughness": [ - { - "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the values", - "type": "Float", - "defaultValue": 1.0, - "min": 0.0, - "max": 1.0, - "connection": { - "type": "ShaderInput", - "id": "m_roughnessFactor" - } - }, { "id": "textureMap", "displayName": "Texture Map", @@ -305,6 +292,13 @@ "id": "m_roughnessMap" } }, + { + "id": "useTexture", + "displayName": "Use Texture", + "description": "Whether to use the texture map, or just default to the Factor value.", + "type": "Bool", + "defaultValue": true + }, { "id": "textureMapUv", "displayName": "UV", @@ -346,11 +340,18 @@ } }, { - "id": "useTexture", - "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", - "type": "Bool", - "defaultValue": true + // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. + "id": "factor", + "displayName": "Factor", + "description": "Controls the roughness value", + "type": "Float", + "defaultValue": 1.0, + "min": 0.0, + "max": 1.0, + "connection": { + "type": "ShaderInput", + "id": "m_roughnessFactor" + } } ], "anisotropy": [ @@ -416,6 +417,13 @@ "id": "m_specularF0Map" } }, + { + "id": "useTexture", + "displayName": "Use Texture", + "description": "Whether to use the texture map, or just default to the Factor value.", + "type": "Bool", + "defaultValue": true + }, { "id": "textureMapUv", "displayName": "UV", @@ -428,13 +436,7 @@ "id": "m_specularF0MapUvIndex" } }, - { - "id": "useTexture", - "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", - "type": "Bool", - "defaultValue": true - }, + // Consider moving this to the "general" group to be consistent with StandardMultilayerPBR { "id": "enableMultiScatterCompensation", "displayName": "Multiscattering Compensation", @@ -452,11 +454,7 @@ "displayName": "Enable", "description": "Enable clear coat", "type": "Bool", - "defaultValue": false, - "connection": { - "type": "ShaderOption", - "id": "o_clearCoat_feature_enabled" - } + "defaultValue": false }, { "id": "factor", @@ -481,6 +479,13 @@ "id": "m_clearCoatInfluenceMap" } }, + { + "id": "useInfluenceMap", + "displayName": " Use Texture", + "description": "Whether to use the texture map, or just default to the Factor value.", + "type": "Bool", + "defaultValue": true + }, { "id": "influenceMapUv", "displayName": " UV", @@ -493,13 +498,6 @@ "id": "m_clearCoatInfluenceMapUvIndex" } }, - { - "id": "useInfluenceMap", - "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", - "type": "Bool", - "defaultValue": true - }, { "id": "roughness", "displayName": "Roughness", @@ -523,6 +521,13 @@ "id": "m_clearCoatRoughnessMap" } }, + { + "id": "useRoughnessMap", + "displayName": " Use Texture", + "description": "Whether to use the texture map, or just default to the roughness value.", + "type": "Bool", + "defaultValue": true + }, { "id": "roughnessMapUv", "displayName": " UV", @@ -535,13 +540,6 @@ "id": "m_clearCoatRoughnessMapUvIndex" } }, - { - "id": "useRoughnessMap", - "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the roughness value.", - "type": "Bool", - "defaultValue": true - }, { "id": "normalStrength", "displayName": "Normal Strength", @@ -565,9 +563,16 @@ "id": "m_clearCoatNormalMap" } }, + { + "id": "useNormalMap", + "displayName": " Use Texture", + "description": "Whether to use the normal map", + "type": "Bool", + "defaultValue": true + }, { "id": "normalMapUv", - "displayName": "UV", + "displayName": " UV", "description": "Normal texture map UV set", "type": "Enum", "enumIsUv": true, @@ -576,29 +581,9 @@ "type": "ShaderInput", "id": "m_clearCoatNormalMapUvIndex" } - }, - { - "id": "useNormalMap", - "displayName": "Use Texture", - "description": "Whether to use the normal map", - "type": "Bool", - "defaultValue": true } ], "normal": [ - { - "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the values", - "type": "Float", - "defaultValue": 1.0, - "min": 0.0, - "softMax": 2.0, - "connection": { - "type": "ShaderInput", - "id": "m_normalFactor" - } - }, { "id": "textureMap", "displayName": "Texture Map", @@ -609,6 +594,13 @@ "id": "m_normalMap" } }, + { + "id": "useTexture", + "displayName": "Use Texture", + "description": "Whether to use the texture map, or just rely on vertex normals.", + "type": "Bool", + "defaultValue": true + }, { "id": "textureMapUv", "displayName": "UV", @@ -621,13 +613,6 @@ "id": "m_normalMapUvIndex" } }, - { - "id": "useTexture", - "displayName": "Use Texture", - "description": "Whether to use the texture map, or just rely on vertex normals.", - "type": "Bool", - "defaultValue": true - }, { "id": "flipX", "displayName": "Flip X Channel", @@ -649,6 +634,19 @@ "type": "ShaderInput", "id": "m_flipNormalY" } + }, + { + "id": "factor", + "displayName": "Factor", + "description": "Strength factor for scaling the values", + "type": "Float", + "defaultValue": 1.0, + "min": 0.0, + "softMax": 2.0, + "connection": { + "type": "ShaderInput", + "id": "m_normalFactor" + } } ], "opacity": [ @@ -872,18 +870,14 @@ "displayName": "Enable", "description": "Enable the emissive group", "type": "Bool", - "defaultValue": false, - "connection": { - "type": "ShaderOption", - "id": "o_emissiveEnabled" - } + "defaultValue": false }, { "id": "unit", "displayName": "Units", "description": "The photometric units of the Intensity property.", "type": "Enum", - "enumValues": [ "Ev100" ], + "enumValues": ["Ev100"], "defaultValue": "Ev100" }, { @@ -918,24 +912,24 @@ "id": "m_emissiveMap" } }, - { - "id": "textureMapUv", - "displayName": "UV", - "description": "Emissive texture map UV set", - "type": "Enum", - "enumValues": [ "UV0", "UV1" ], - "defaultValue": "UV0", - "connection": { - "type": "ShaderInput", - "id": "m_emissiveMapUvIndex" - } - }, { "id": "useTexture", "displayName": "Use Texture", "description": "Whether to use the texture map.", "type": "Bool", "defaultValue": true + }, + { + "id": "textureMapUv", + "displayName": "UV", + "description": "Emissive texture map UV set", + "type": "Enum", + "enumIsUv": true, + "defaultValue": "Tiled", + "connection": { + "type": "ShaderInput", + "id": "m_emissiveMapUvIndex" + } } ], "parallax": [ @@ -961,8 +955,8 @@ "displayName": "UV", "description": "Depth texture map UV set", "type": "Enum", - "enumValues": [ "UV0", "UV1" ], - "defaultValue": "UV0", + "enumIsUv": true, + "defaultValue": "Tiled", "connection": { "type": "ShaderInput", "id": "m_parallaxUvIndex" @@ -1055,7 +1049,7 @@ "subsurfaceScattering": [ { "id": "enableSubsurfaceScattering", - "displayName": "Enable Subsurface Scattering", + "displayName": "Subsurface Scattering", "description": "Enable subsurface scattering feature, this will disable metallic and parallax mapping property due to incompatibility", "type": "Bool", "defaultValue": false, @@ -1069,7 +1063,7 @@ "displayName": " Factor", "description": "Strength factor for scaling percentage of subsurface scattering effect applied", "type": "float", - "defaultValue": 0.0, + "defaultValue": 1.0, "min": 0.0, "max": 1.0, "connection": { @@ -1087,18 +1081,6 @@ "id": "m_subsurfaceScatteringInfluenceMap" } }, - { - "id": "influenceMapUv", - "displayName": " UV", - "description": "Influence map UV set", - "type": "Enum", - "enumValues": [ "UV0", "UV1" ], - "defaultValue": "UV0", - "connection": { - "type": "ShaderInput", - "id": "m_subsurfaceScatteringInfluenceMapUvIndex" - } - }, { "id": "useInfluenceMap", "displayName": " Use Influence Map", @@ -1106,6 +1088,18 @@ "type": "Bool", "defaultValue": true }, + { + "id": "influenceMapUv", + "displayName": " UV", + "description": "Influence map UV set", + "type": "Enum", + "enumIsUv": true, + "defaultValue": "Tiled", + "connection": { + "type": "ShaderInput", + "id": "m_subsurfaceScatteringInfluenceMapUvIndex" + } + }, { "id": "scatterColor", "displayName": " Scatter color", @@ -1136,11 +1130,16 @@ } }, { - "id": "enableTransmission", - "displayName": "Enable Transmission", - "description": "Enable transmission feature", - "type": "Bool", - "defaultValue": false + "id": "transmissionMode", + "displayName": "Transmission", + "description": "Algorithm used for calculating transmission", + "type": "Enum", + "enumValues": [ "None", "ThickObject", "ThinObject" ], + "defaultValue": "None", + "connection": { + "type": "ShaderOption", + "id": "o_transmission_mode" + } }, { "id": "thickness", @@ -1161,18 +1160,6 @@ "id": "m_transmissionThicknessMap" } }, - { - "id": "thicknessMapUv", - "displayName": " UV", - "description": "Thickness map UV set", - "type": "Enum", - "enumValues": [ "UV0", "UV1" ], - "defaultValue": "UV0", - "connection": { - "type": "ShaderInput", - "id": "m_transmissionThicknessMapUvIndex" - } - }, { "id": "useThicknessMap", "displayName": " Use Thickness Map", @@ -1180,6 +1167,18 @@ "type": "Bool", "defaultValue": true }, + { + "id": "thicknessMapUv", + "displayName": " UV", + "description": "Thickness map UV set", + "type": "Enum", + "enumIsUv": true, + "defaultValue": "Tiled", + "connection": { + "type": "ShaderInput", + "id": "m_transmissionThicknessMapUvIndex" + } + }, { "id": "transmissionTint", "displayName": " Transmission Tint", @@ -1187,18 +1186,6 @@ "type": "Color", "defaultValue": [ 1.0, 0.8, 0.6 ] }, - { - "id": "transmissionMode", - "displayName": " Mode", - "description": "Algorithm used for calculating transmission", - "type": "Enum", - "enumValues": [ "None", "ThickObject", "ThinObject" ], - "defaultValue": "None", - "connection": { - "type": "ShaderOption", - "id": "o_transmission_mode" - } - }, { "id": "transmissionPower", "displayName": " Power", @@ -1287,7 +1274,7 @@ } }, { - "id": "detailMapsMapUv", + "id": "textureMapUv", "displayName": "Detail Map UVs", "description": "Which UV set to use for detail map texture sampling", "type": "Enum", @@ -1506,7 +1493,7 @@ { "file": "Shaders/Depth/DepthPassTransparentMax.shader", "tag": "DepthPassTransparentMax" - } + } ], "functors": [ { @@ -1549,26 +1536,9 @@ "lightUnitProperty": "emissive.unit", "shaderInput": "m_emissiveIntensity", "ev100Index": 0, - "nitIndex": 1, - "ev100MinMax": [ -10, 20 ], - "nitMinMax": [ 0.001, 100000.0 ] - } - }, - { - // Enable/Disable shader based on different option. - "type": "ShaderEnable", - "args": { - "opacityMode": "opacity.mode", - "parallaxEnable": "parallax.enable", - "parallaxPdoEnable": "parallax.pdo", - "pbrShaderNoEdsIndex": 0, - "pbrShaderWithEdsIndex": 1, - "shadowShaderNoPSIndex": 2, - "shadowShaderWithPSIndex": 3, - "depthShaderNoPSIndex": 4, - "depthShaderWithPSIndex": 5, - "depthShaderTransparentMin": 8, - "depthShaderTransparentMax": 9 + "nitIndex" : 1, + "ev100MinMax": [-10, 20], + "nitMinMax": [0.001, 100000.0] } }, { @@ -1590,120 +1560,40 @@ "tintThickenssShaderInput": "m_transmissionTintThickness" } }, - { - // Reads material properties to determine whether a specific texture map should be sampled at runtime, and sets a shader option accordingly. - // @param textureProperty - which material property contains the texture asset reference (or maybe null) - // @param useTextureProperty - a boolean flag that toggles whether the texture should be sampled (if it's not null) - // @param shaderTags - which shader in the 'shaders' list above is configured by this functor - // @param shaderOption - the name of a shader option in the AZSL file that controls sampling of this texture + { "type": "UseTexture", "args": { "textureProperty": "baseColor.textureMap", - "dependentProperties": ["baseColor.textureMapUv"], "useTextureProperty": "baseColor.useTexture", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], + "dependentProperties": ["baseColor.textureMapUv", "baseColor.textureBlendMode"], "shaderOption": "o_baseColor_useTexture" } }, { - // See the comment above for details. "type": "UseTexture", "args": { "textureProperty": "metallic.textureMap", - "dependentProperties": ["metallic.textureMapUv"], "useTextureProperty": "metallic.useTexture", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], + "dependentProperties": ["metallic.textureMapUv"], "shaderOption": "o_metallic_useTexture" } }, { - // See the comment above for details. - "type": "UseTexture", - "args": { - "textureProperty": "roughness.textureMap", - "dependentProperties": ["roughness.textureMapUv"], - "useTextureProperty": "roughness.useTexture", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], - "shaderOption": "o_roughness_useTexture" - } - }, - { - // See the comment above for details. "type": "UseTexture", "args": { "textureProperty": "specularF0.textureMap", - "dependentProperties": ["specularF0.textureMapUv"], "useTextureProperty": "specularF0.useTexture", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], + "dependentProperties": ["specularF0.textureMapUv"], "shaderOption": "o_specularF0_useTexture" } }, { - // See the comment above for details. - "type": "UseTexture", - "args": { - "textureProperty": "clearCoat.influenceMap", - "dependentProperties": ["clearCoat.influenceMapUv"], - "useTextureProperty": "clearCoat.useInfluenceMap", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], - "shaderOption": "o_clearCoat_factor_useTexture" - } - }, - { - // See the comment above for details. - "type": "UseTexture", - "args": { - "textureProperty": "clearCoat.roughnessMap", - "dependentProperties": ["clearCoat.roughnessMapUv"], - "useTextureProperty": "clearCoat.useRoughnessMap", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], - "shaderOption": "o_clearCoat_roughness_useTexture" - } - }, - { - // See the comment above for details. - "type": "UseTexture", - "args": { - "textureProperty": "clearCoat.normalMap", - "dependentProperties": ["clearCoat.normalMapUv"], - "useTextureProperty": "clearCoat.useNormalMap", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], - "shaderOption": "o_clearCoat_normal_useTexture" - } - }, - { - // See the comment above for details. "type": "UseTexture", "args": { "textureProperty": "normal.textureMap", - "dependentProperties": ["normal.textureMapUv"], "useTextureProperty": "normal.useTexture", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], - "shaderOption": "o_normal_useTexture" + "dependentProperties": ["normal.textureMapUv", "normal.factor", "normal.flipX", "normal.flipY"], + "shaderOption": "o_normal_useTexture" } }, { @@ -1725,335 +1615,21 @@ } }, { - // See the comment above for details. - "type": "UseTexture", + "type": "Lua", "args": { - "textureProperty": "emissive.textureMap", - "dependentProperties": ["emissive.textureMapUv"], - "useTextureProperty": "emissive.useTexture", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], - "shaderOption": "o_emissive_useTexture" + "file": "StandardPBR_ClearCoatState.lua" } }, { - // See the comment above for details. - "type": "UseTexture", + "type": "Lua", "args": { - "textureProperty": "subsurfaceScattering.influenceMap", - "dependentProperties": ["subsurfaceScattering.influenceMapUv"], - "useTextureProperty": "subsurfaceScattering.useInfluenceMap", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], - "shaderOption": "o_subsurfaceScattering_useTexture" + "file": "StandardPBR_ClearCoatEnableFeature.lua" } }, { - // See the comment above for details. - "type": "UseTexture", + "type": "Lua", "args": { - "textureProperty": "subsurfaceScattering.thicknessMap", - "dependentProperties": ["subsurfaceScattering.thicknessMapUv"], - "useTextureProperty": "subsurfaceScattering.useThicknessMap", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS" - ], - "shaderOption": "o_transmission_useTexture" - } - }, - { - // Controls visibility for properties in the editor. - // @param actions - a list of actions that are executed in order. visibility will be set when triggerProperty hits the triggerValue. - // @param affectedProperties - the properties that are affected by actions. - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "emissive.enable", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "emissive.enable", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "emissive.color", - "emissive.intensity", - "emissive.useTexture", - "emissive.unit" - ] - } - }, - { - // Controls visibility for properties in the editor. - // @param actions - a list of actions that are executed in order. visibility will be set when triggerProperty hits the triggerValue. - // @param affectedProperties - the properties that are affected by actions. - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "emissive.useTexture", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "emissive.useTexture", - "triggerValue": false, - "visibility": "Disabled" - }, - { - "triggerProperty": "emissive.enable", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "emissive.textureMap", - "emissive.textureMapUv" - ] - } - }, - { - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "clearCoat.useInfluenceMap", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "clearCoat.useInfluenceMap", - "triggerValue": false, - "visibility": "Disabled" - }, - { - "triggerProperty": "clearCoat.enable", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "clearCoat.influenceMap", - "clearCoat.influenceMapUv" - ] - } - }, - { - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "clearCoat.useRoughnessMap", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "clearCoat.useRoughnessMap", - "triggerValue": false, - "visibility": "Disabled" - }, - { - "triggerProperty": "clearCoat.enable", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "clearCoat.roughnessMap", - "clearCoat.roughnessMapUv" - ] - } - }, - { - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "clearCoat.useNormalMap", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "clearCoat.useNormalMap", - "triggerValue": false, - "visibility": "Disabled" - }, - { - "triggerProperty": "clearCoat.enable", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "clearCoat.normalMap", - "clearCoat.normalMapUv" - ] - } - - }, - { - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "subsurfaceScattering.useInfluenceMap", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "subsurfaceScattering.useInfluenceMap", - "triggerValue": false, - "visibility": "Disabled" - }, - { - "triggerProperty": "subsurfaceScattering.enableSubsurfaceScattering", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "subsurfaceScattering.influenceMap", - "subsurfaceScattering.influenceMapUv" - ] - } - }, - { - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "subsurfaceScattering.useThicknessMap", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "subsurfaceScattering.useThicknessMap", - "triggerValue": false, - "visibility": "Disabled" - }, - { - "triggerProperty": "subsurfaceScattering.enableTransmission", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "subsurfaceScattering.thicknessMap", - "subsurfaceScattering.thicknessMapUv" - ] - } - }, - { - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "clearCoat.enable", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "clearCoat.enable", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "clearCoat.factor", - "clearCoat.useInfluenceMap", - "clearCoat.roughness", - "clearCoat.useRoughnessMap", - "clearCoat.useNormalMap" - ] - } - }, - { - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "subsurfaceScattering.transmissionMode", - "triggerValue": "ThickObject", - "visibility": "Enabled" - }, - { - "triggerProperty": "subsurfaceScattering.transmissionMode", - "triggerValue": "None", - "visibility": "Hidden" - }, - { - "triggerProperty": "subsurfaceScattering.transmissionMode", - "triggerValue": "ThinObject", - "visibility": "Hidden" - }, - { - "triggerProperty": "subsurfaceScattering.enableTransmission", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "subsurfaceScattering.transmissionPower", - "subsurfaceScattering.transmissionDistortion", - "subsurfaceScattering.transmissionAttenuation" - ] - } - }, - { - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "subsurfaceScattering.enableSubsurfaceScattering", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "subsurfaceScattering.enableSubsurfaceScattering", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "subsurfaceScattering.subsurfaceScatterFactor", - "subsurfaceScattering.useInfluenceMap", - "subsurfaceScattering.scatterColor", - "subsurfaceScattering.scatterDistance", - "subsurfaceScattering.quality" - ] - } - }, - { - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "subsurfaceScattering.enableTransmission", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "subsurfaceScattering.enableTransmission", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "subsurfaceScattering.thickness", - "subsurfaceScattering.useThicknessMap", - "subsurfaceScattering.transmissionTint", - "subsurfaceScattering.transmissionMode", - "subsurfaceScattering.transmissionScale" - ] + "file": "StandardPBR_EmissiveState.lua" } }, { @@ -2062,6 +1638,18 @@ "file": "StandardPBR_ParallaxState.lua" } }, + { + "type": "Lua", + "args": { + "file": "StandardPBR_Roughness.lua" + } + }, + { + "type": "Lua", + "args": { + "file": "StandardPBR_SubsurfaceState.lua" + } + }, { "type": "Lua", "args": { @@ -2097,6 +1685,12 @@ "args": { "file": "MaterialInputs/DetailMapsCommonFunctor.lua" } + }, + { + "type": "Lua", + "args": { + "file": "StandardPBR_ShaderEnable.lua" + } } ], "uvNameMap": { @@ -2104,3 +1698,4 @@ "UV1": "Unwrapped" } } + diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype index 044b267645..f8c49d579c 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype @@ -287,6 +287,13 @@ "id": "m_specularF0Map" } }, + { + "id": "useTexture", + "displayName": "Use Texture", + "description": "Whether to use the texture map, or just default to the Factor value.", + "type": "Bool", + "defaultValue": true + }, { "id": "textureMapUv", "displayName": "UV", @@ -299,13 +306,7 @@ "id": "m_specularF0MapUvIndex" } }, - { - "id": "useTexture", - "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", - "type": "Bool", - "defaultValue": true - }, + // Consider moving this to the "general" group to be consistent with StandardMultilayerPBR { "id": "enableMultiScatterCompensation", "displayName": "Multiscattering Compensation", @@ -616,7 +617,7 @@ "type": "float", "defaultValue": 6.0, "min": 0.0, - "softMax": 20.0 + "softMax": 20.0 }, { "id": "transmissionDistortion", @@ -1011,18 +1012,18 @@ "type": "HandleSubsurfaceScatteringParameters", "args": { "mode": "subsurfaceScattering.transmissionMode", - "scale" : "subsurfaceScattering.transmissionScale", - "power" : "subsurfaceScattering.transmissionPower", - "distortion" : "subsurfaceScattering.transmissionDistortion", - "attenuation" : "subsurfaceScattering.transmissionAttenuation", - "tintColor" : "subsurfaceScattering.transmissionTint", - "thickness" : "subsurfaceScattering.thickness", + "scale": "subsurfaceScattering.transmissionScale", + "power": "subsurfaceScattering.transmissionPower", + "distortion": "subsurfaceScattering.transmissionDistortion", + "attenuation": "subsurfaceScattering.transmissionAttenuation", + "tintColor": "subsurfaceScattering.transmissionTint", + "thickness": "subsurfaceScattering.thickness", "enabled": "subsurfaceScattering.enableSubsurfaceScattering", - "scatterDistanceColor" : "subsurfaceScattering.scatterColor", - "scatterDistanceIntensity" : "subsurfaceScattering.scatterDistance", - "scatterDistanceShaderInput" : "m_scatterDistance", - "parametersShaderInput" : "m_transmissionParams", - "tintThickenssShaderInput" : "m_transmissionTintThickness" + "scatterDistanceColor": "subsurfaceScattering.scatterColor", + "scatterDistanceIntensity": "subsurfaceScattering.scatterDistance", + "scatterDistanceShaderInput": "m_scatterDistance", + "parametersShaderInput": "m_transmissionParams", + "tintThickenssShaderInput": "m_transmissionTintThickness" } }, { @@ -1038,8 +1039,8 @@ "type": "UseTexture", "args": { "textureProperty": "specularF0.textureMap", - "dependentProperties": ["specularF0.textureMapUv"], "useTextureProperty": "specularF0.useTexture", + "dependentProperties": ["specularF0.textureMapUv"], "shaderOption": "o_specularF0_useTexture" } }, diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index 04e6c0f501..038e65a89f 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -674,7 +674,7 @@ { "id": "tileU", "displayName": "Tile U", - "description": "Scales texture coordinates in V.", + "description": "Scales texture coordinates in U.", "type": "float", "defaultValue": 1.0, "step": 0.1 @@ -1139,7 +1139,7 @@ "type": "float", "defaultValue": 6.0, "min": 0.0, - "softMax": 20.0 + "softMax": 20.0 }, { "id": "transmissionDistortion", @@ -1170,7 +1170,7 @@ } ], "irradiance": [ - // Note: this property group is used in the DiffuseGlobalIllumination pass, it is not read by the StandardPBR shader + // Note: this property group is used in the DiffuseGlobalIllumination pass and not by the main forward shader { "id": "color", "displayName": "Color", @@ -1277,18 +1277,18 @@ "type": "HandleSubsurfaceScatteringParameters", "args": { "mode": "subsurfaceScattering.transmissionMode", - "scale" : "subsurfaceScattering.transmissionScale", - "power" : "subsurfaceScattering.transmissionPower", - "distortion" : "subsurfaceScattering.transmissionDistortion", - "attenuation" : "subsurfaceScattering.transmissionAttenuation", - "tintColor" : "subsurfaceScattering.transmissionTint", - "thickness" : "subsurfaceScattering.thickness", + "scale": "subsurfaceScattering.transmissionScale", + "power": "subsurfaceScattering.transmissionPower", + "distortion": "subsurfaceScattering.transmissionDistortion", + "attenuation": "subsurfaceScattering.transmissionAttenuation", + "tintColor": "subsurfaceScattering.transmissionTint", + "thickness": "subsurfaceScattering.thickness", "enabled": "subsurfaceScattering.enableSubsurfaceScattering", - "scatterDistanceColor" : "subsurfaceScattering.scatterColor", - "scatterDistanceIntensity" : "subsurfaceScattering.scatterDistance", - "scatterDistanceShaderInput" : "m_scatterDistance", - "parametersShaderInput" : "m_transmissionParams", - "tintThickenssShaderInput" : "m_transmissionTintThickness" + "scatterDistanceColor": "subsurfaceScattering.scatterColor", + "scatterDistanceIntensity": "subsurfaceScattering.scatterDistance", + "scatterDistanceShaderInput": "m_scatterDistance", + "parametersShaderInput": "m_transmissionParams", + "tintThickenssShaderInput": "m_transmissionTintThickness" } }, { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ShaderEnable.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ShaderEnable.lua index e502eb38f8..26c163d61b 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ShaderEnable.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ShaderEnable.lua @@ -21,6 +21,20 @@ OpacityMode_Cutout = 1 OpacityMode_Blended = 2 OpacityMode_TintedTransparent = 3 +function TryGetShaderByTag(context, shaderTag) + if context:HasShaderWithTag(shaderTag) then + return context:GetShaderByTag(shaderTag) + else + return nil + end +end + +function TrySetShaderEnabled(shader, enabled) + if shader then + shader:SetEnabled(enabled) + end +end + function Process(context) local opacityMode = context:GetMaterialPropertyValue_enum("opacity.mode") local parallaxEnabled = context:GetMaterialPropertyValue_bool("parallax.enable") @@ -29,33 +43,37 @@ function Process(context) local depthPass = context:GetShaderByTag("DepthPass") local shadowMap = context:GetShaderByTag("Shadowmap") local forwardPassEDS = context:GetShaderByTag("ForwardPass_EDS") - local lowEndForwardEDS = context:GetShaderByTag("LowEndForward_EDS") local depthPassWithPS = context:GetShaderByTag("DepthPass_WithPS") local shadowMapWithPS = context:GetShaderByTag("Shadowmap_WithPS") local forwardPass = context:GetShaderByTag("ForwardPass") - local lowEndForward = context:GetShaderByTag("LowEndForward") + + -- Use TryGetShaderByTag because these shaders only exist in StandardPBR but this script is also used for EnhancedPBR + local lowEndForwardEDS = TryGetShaderByTag(context, "LowEndForward_EDS") + local lowEndForward = TryGetShaderByTag(context, "LowEndForward") if parallaxEnabled and parallaxPdoEnabled then depthPass:SetEnabled(false) shadowMap:SetEnabled(false) forwardPassEDS:SetEnabled(false) - lowEndForwardEDS:SetEnabled(false) depthPassWithPS:SetEnabled(true) shadowMapWithPS:SetEnabled(true) forwardPass:SetEnabled(true) - lowEndForward:SetEnabled(true) + + TrySetShaderEnabled(lowEndForwardEDS, false) + TrySetShaderEnabled(lowEndForward, true) else depthPass:SetEnabled(opacityMode == OpacityMode_Opaque) shadowMap:SetEnabled(opacityMode == OpacityMode_Opaque) forwardPassEDS:SetEnabled((opacityMode == OpacityMode_Opaque) or (opacityMode == OpacityMode_Blended) or (opacityMode == OpacityMode_TintedTransparent)) - lowEndForwardEDS:SetEnabled((opacityMode == OpacityMode_Opaque) or (opacityMode == OpacityMode_Blended) or (opacityMode == OpacityMode_TintedTransparent)) depthPassWithPS:SetEnabled(opacityMode == OpacityMode_Cutout) shadowMapWithPS:SetEnabled(opacityMode == OpacityMode_Cutout) forwardPass:SetEnabled(opacityMode == OpacityMode_Cutout) - lowEndForward:SetEnabled(opacityMode == OpacityMode_Cutout) + + TrySetShaderEnabled(lowEndForwardEDS, (opacityMode == OpacityMode_Opaque) or (opacityMode == OpacityMode_Blended) or (opacityMode == OpacityMode_TintedTransparent)) + TrySetShaderEnabled(lowEndForward, opacityMode == OpacityMode_Cutout) end context:GetShaderByTag("DepthPassTransparentMin"):SetEnabled((opacityMode == OpacityMode_Blended) or (opacityMode == OpacityMode_TintedTransparent)) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/LuaMaterialFunctor.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/LuaMaterialFunctor.h index 396ba14810..f372f40981 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/LuaMaterialFunctor.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/LuaMaterialFunctor.h @@ -288,6 +288,7 @@ namespace AZ AZStd::size_t GetShaderCount() const; LuaMaterialFunctorShaderItem GetShader(AZStd::size_t index); LuaMaterialFunctorShaderItem GetShaderByTag(const char* shaderTag); + bool HasShaderWithTag(const char* shaderTag); private: diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/LuaMaterialFunctor.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/LuaMaterialFunctor.cpp index 7db5f12560..d6421e1337 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/LuaMaterialFunctor.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/LuaMaterialFunctor.cpp @@ -296,6 +296,7 @@ namespace AZ ->Method("GetShaderCount", &LuaMaterialFunctorRuntimeContext::GetShaderCount) ->Method("GetShader", &LuaMaterialFunctorRuntimeContext::GetShader) ->Method("GetShaderByTag", &LuaMaterialFunctorRuntimeContext::GetShaderByTag) + ->Method("HasShaderWithTag", &LuaMaterialFunctorRuntimeContext::HasShaderWithTag) ; } @@ -424,6 +425,11 @@ namespace AZ return LuaMaterialFunctorShaderItem{nullptr}; } } + + bool LuaMaterialFunctorRuntimeContext::HasShaderWithTag(const char* shaderTag) + { + return m_runtimeContextImpl->m_shaderCollection->HasShaderTag(AZ::Name{shaderTag}); + } void LuaMaterialFunctorEditorContext::LuaMaterialFunctorEditorContext::Reflect(BehaviorContext* behaviorContext) { diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/015_SubsurfaceScattering_Transmission.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/015_SubsurfaceScattering_Transmission.material index dbaf6cb587..38adbc70cd 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/015_SubsurfaceScattering_Transmission.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/015_SubsurfaceScattering_Transmission.material @@ -6,7 +6,6 @@ "properties": { "subsurfaceScattering": { "enableSubsurfaceScattering": true, - "enableTransmission": true, "scatterDistance": 64.6464614868164, "subsurfaceScatterFactor": 1.0, "thicknessMap": "TestData/Textures/checker8x8_512.png", From 74bdf2b0696a428ec85c9d6e4e1338360587c9ae Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Wed, 26 May 2021 20:25:48 -0700 Subject: [PATCH 200/811] Minor changes: Updated comments and removed an include file. --- .../DiffuseProbeGridFeatureProcessorInterface.h | 1 + .../Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h | 1 + .../DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp | 3 ++- .../DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp | 2 +- .../DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp | 1 - 5 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h index cf46383a64..73ce175d99 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h @@ -109,6 +109,7 @@ namespace AZ const AZStd::string& relocationTextureRelativePath, const AZStd::string& classificationTextureRelativePath) = 0; + // check for and retrieve a new baked texture asset (does not apply to hot-reloaded assets, only initial bakes) virtual bool CheckTextureAssetNotification( const AZStd::string& relativePath, Data::Asset& outTextureAsset, diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h index 325cbcb616..ff6ad719cf 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h @@ -27,6 +27,7 @@ namespace AZ struct DiffuseProbeGridRenderData { + // [GFX TODO][ATOM-15650] Change DiffuseProbeGrid Classification texture to R8_UINT static const RHI::Format RayTraceImageFormat = RHI::Format::R32G32B32A32_FLOAT; static const RHI::Format IrradianceImageFormat = RHI::Format::R16G16B16A16_UNORM; static const RHI::Format DistanceImageFormat = RHI::Format::R32G32_FLOAT; diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp index 11d7dc0385..060d51d1d0 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp @@ -352,7 +352,8 @@ namespace AZ azrtti_typeid(), false); - // we only track notifications for new texture assets, existing assets are automatically reloaded by the RPI + // We only track notifications for new texture assets, meaning assets that are created the first time a DiffuseProbeGrid is baked. + // On subsequent bakes the existing assets are automatically reloaded by the RPI since they are already known by the asset system. if (!assetId.IsValid()) { m_notifyTextureAssets.push_back({ assetPath, assetId }); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp index 1ec09995fd..5fb835de15 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp @@ -128,7 +128,7 @@ namespace AZ m_configuration.m_bakedRelocationTextureRelativePath, m_configuration.m_bakedClassificationTextureRelativePath)) { - // clear the baked texture paths and assets + // clear the baked texture paths and assets, since they belong to the original entity (not the clone) m_configuration.m_bakedIrradianceTextureRelativePath.clear(); m_configuration.m_bakedDistanceTextureRelativePath.clear(); m_configuration.m_bakedRelocationTextureRelativePath.clear(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp index 162740fe1e..1e5b959803 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp @@ -23,7 +23,6 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include #include -#include AZ_POP_DISABLE_WARNING namespace AZ From b1115c091ff94da14957ffd5e52ef7497100144e Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Wed, 26 May 2021 22:43:52 -0500 Subject: [PATCH 201/811] Removed unused watersample level (#975) --- .../Levels/WaterSample/WaterSample.ly | 3 - .../Levels/WaterSample/filelist.xml | 6 - .../Levels/WaterSample/halfsphere.cgf | 3 - .../Levels/WaterSample/halfsphere2.cgf | 3 - AutomatedTesting/Levels/WaterSample/level.pak | 3 - .../WaterSample/leveldata/Environment.xml | 14 - .../WaterSample/leveldata/TerrainTexture.xml | 7 - .../WaterSample/leveldata/TimeOfDay.xml | 356 ------------------ .../WaterSample/leveldata/VegetationMap.dat | 3 - AutomatedTesting/Levels/WaterSample/pool.cgf | 3 - AutomatedTesting/Levels/WaterSample/pool2.cgf | 3 - AutomatedTesting/Levels/WaterSample/tags.txt | 12 - .../Levels/WaterSample/terraintexture.pak | 3 - .../WaterSample/woodland_canyon_river.mtl | 7 - 14 files changed, 426 deletions(-) delete mode 100644 AutomatedTesting/Levels/WaterSample/WaterSample.ly delete mode 100644 AutomatedTesting/Levels/WaterSample/filelist.xml delete mode 100644 AutomatedTesting/Levels/WaterSample/halfsphere.cgf delete mode 100644 AutomatedTesting/Levels/WaterSample/halfsphere2.cgf delete mode 100644 AutomatedTesting/Levels/WaterSample/level.pak delete mode 100644 AutomatedTesting/Levels/WaterSample/leveldata/Environment.xml delete mode 100644 AutomatedTesting/Levels/WaterSample/leveldata/TerrainTexture.xml delete mode 100644 AutomatedTesting/Levels/WaterSample/leveldata/TimeOfDay.xml delete mode 100644 AutomatedTesting/Levels/WaterSample/leveldata/VegetationMap.dat delete mode 100644 AutomatedTesting/Levels/WaterSample/pool.cgf delete mode 100644 AutomatedTesting/Levels/WaterSample/pool2.cgf delete mode 100644 AutomatedTesting/Levels/WaterSample/tags.txt delete mode 100644 AutomatedTesting/Levels/WaterSample/terraintexture.pak delete mode 100644 AutomatedTesting/Levels/WaterSample/woodland_canyon_river.mtl diff --git a/AutomatedTesting/Levels/WaterSample/WaterSample.ly b/AutomatedTesting/Levels/WaterSample/WaterSample.ly deleted file mode 100644 index b1899f3710..0000000000 --- a/AutomatedTesting/Levels/WaterSample/WaterSample.ly +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d49aceca5ad4e0b9f46c8127afb5c53b68aa30272950b1abd66fba310977ff0c -size 15032 diff --git a/AutomatedTesting/Levels/WaterSample/filelist.xml b/AutomatedTesting/Levels/WaterSample/filelist.xml deleted file mode 100644 index d14b2fdaf2..0000000000 --- a/AutomatedTesting/Levels/WaterSample/filelist.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/AutomatedTesting/Levels/WaterSample/halfsphere.cgf b/AutomatedTesting/Levels/WaterSample/halfsphere.cgf deleted file mode 100644 index 4426d8a232..0000000000 --- a/AutomatedTesting/Levels/WaterSample/halfsphere.cgf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5f221acd847ec8a15e1333a5163d6d0fd886b8eda46fa7b133f76ddbf1d11216 -size 41472 diff --git a/AutomatedTesting/Levels/WaterSample/halfsphere2.cgf b/AutomatedTesting/Levels/WaterSample/halfsphere2.cgf deleted file mode 100644 index c776ff68b8..0000000000 --- a/AutomatedTesting/Levels/WaterSample/halfsphere2.cgf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c8e5dcfbe65fd2fd8ea29a38a96e703683c544fd42b9424857b1df3718c7775a -size 41472 diff --git a/AutomatedTesting/Levels/WaterSample/level.pak b/AutomatedTesting/Levels/WaterSample/level.pak deleted file mode 100644 index 1753ef4b93..0000000000 --- a/AutomatedTesting/Levels/WaterSample/level.pak +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0378911c27933302042550d5a031a5f9104296162edc2b21e44893f1b8cff969 -size 44124 diff --git a/AutomatedTesting/Levels/WaterSample/leveldata/Environment.xml b/AutomatedTesting/Levels/WaterSample/leveldata/Environment.xml deleted file mode 100644 index 6a95c631bb..0000000000 --- a/AutomatedTesting/Levels/WaterSample/leveldata/Environment.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/AutomatedTesting/Levels/WaterSample/leveldata/TerrainTexture.xml b/AutomatedTesting/Levels/WaterSample/leveldata/TerrainTexture.xml deleted file mode 100644 index 21741afe52..0000000000 --- a/AutomatedTesting/Levels/WaterSample/leveldata/TerrainTexture.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/AutomatedTesting/Levels/WaterSample/leveldata/TimeOfDay.xml b/AutomatedTesting/Levels/WaterSample/leveldata/TimeOfDay.xml deleted file mode 100644 index 60ad405904..0000000000 --- a/AutomatedTesting/Levels/WaterSample/leveldata/TimeOfDay.xml +++ /dev/null @@ -1,356 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AutomatedTesting/Levels/WaterSample/leveldata/VegetationMap.dat b/AutomatedTesting/Levels/WaterSample/leveldata/VegetationMap.dat deleted file mode 100644 index dce5631cd0..0000000000 --- a/AutomatedTesting/Levels/WaterSample/leveldata/VegetationMap.dat +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0e6a5435c928079b27796f6b202bbc2623e7e454244ddc099a3cadf33b7cb9e9 -size 63 diff --git a/AutomatedTesting/Levels/WaterSample/pool.cgf b/AutomatedTesting/Levels/WaterSample/pool.cgf deleted file mode 100644 index 04bec52a62..0000000000 --- a/AutomatedTesting/Levels/WaterSample/pool.cgf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:12ca8f1942331abde4d58724aea22609c8d7951cc415afa6e5f1c550a14e67b0 -size 363624 diff --git a/AutomatedTesting/Levels/WaterSample/pool2.cgf b/AutomatedTesting/Levels/WaterSample/pool2.cgf deleted file mode 100644 index 204306f8a8..0000000000 --- a/AutomatedTesting/Levels/WaterSample/pool2.cgf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f5b525a410730d84c0b3e97396d392e1e72f4b894742ddef3de4ede5542b0f8e -size 86148 diff --git a/AutomatedTesting/Levels/WaterSample/tags.txt b/AutomatedTesting/Levels/WaterSample/tags.txt deleted file mode 100644 index 0d6c1880e7..0000000000 --- a/AutomatedTesting/Levels/WaterSample/tags.txt +++ /dev/null @@ -1,12 +0,0 @@ -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 diff --git a/AutomatedTesting/Levels/WaterSample/terraintexture.pak b/AutomatedTesting/Levels/WaterSample/terraintexture.pak deleted file mode 100644 index fe3604a050..0000000000 --- a/AutomatedTesting/Levels/WaterSample/terraintexture.pak +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8739c76e681f900923b900c9df0ef75cf421d39cabb54650c4b9ad19b6a76d85 -size 22 diff --git a/AutomatedTesting/Levels/WaterSample/woodland_canyon_river.mtl b/AutomatedTesting/Levels/WaterSample/woodland_canyon_river.mtl deleted file mode 100644 index 4548bca421..0000000000 --- a/AutomatedTesting/Levels/WaterSample/woodland_canyon_river.mtl +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - From 8bd4c8d9742f9e117040cae76992d2890da38c48 Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Wed, 26 May 2021 20:51:05 -0700 Subject: [PATCH 202/811] Add back text drawing using Draw2d (#928) This is used by the UI Editor's viewport and also by LyShine to display debug text. --- Code/CryEngine/CryCommon/LyShine/IDraw2d.h | 3 +- .../AzFramework/Font/FontInterface.h | 9 +- .../AtomFont/Code/Source/FFont.cpp | 20 +- Gems/LyShine/Code/Editor/ViewportHelpers.cpp | 12 +- Gems/LyShine/Code/Editor/ViewportIcon.cpp | 2 +- Gems/LyShine/Code/Include/LyShine/Draw2d.h | 13 +- Gems/LyShine/Code/Source/Draw2d.cpp | 210 ++++++++++-------- Gems/LyShine/Code/Source/LyShine.cpp | 2 - Gems/LyShine/Code/Source/LyShineDebug.cpp | 15 +- Gems/LyShine/Code/Source/LyShineDebug.h | 6 +- Gems/LyShine/Code/Source/RenderGraph.cpp | 34 ++- Gems/LyShine/Code/Source/RenderGraph.h | 6 +- Gems/LyShine/Code/Source/UiCanvasManager.cpp | 6 +- Gems/LyShine/Code/Source/UiRenderer.cpp | 12 +- Gems/LyShine/Code/Source/UiRenderer.h | 6 +- 15 files changed, 203 insertions(+), 153 deletions(-) diff --git a/Code/CryEngine/CryCommon/LyShine/IDraw2d.h b/Code/CryEngine/CryCommon/LyShine/IDraw2d.h index 16fdfceca3..76a71c9e24 100644 --- a/Code/CryEngine/CryCommon/LyShine/IDraw2d.h +++ b/Code/CryEngine/CryCommon/LyShine/IDraw2d.h @@ -11,7 +11,6 @@ */ #pragma once -#include #include #include #include @@ -84,7 +83,7 @@ public: // types //! If this is not passed then the defaults below are used struct TextOptions { - IFFont* font; //!< default is "default" + AZStd::string fontName; //!< default is "default" unsigned int effectIndex; //!< default is 0 AZ::Vector3 color; //!< default is (1,1,1) HAlign horizontalAlignment; //!< default is HAlign::Left diff --git a/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h b/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h index b64b61e22c..04a0572bb9 100644 --- a/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -42,11 +43,15 @@ namespace AzFramework { ViewportId m_drawViewportId = InvalidViewportId; //!< Viewport to draw into AZ::Vector3 m_position; //!< world space position for 3d draws, screen space x,y,depth for 2d. - AZ::Color m_color = AZ::Colors::White; //!< Color to draw the text + AZ::Color m_color = AZ::Colors::White; //!< Color to draw the text + unsigned int m_effectIndex = 0; //!< effect index to apply AZ::Vector2 m_scale = AZ::Vector2(1.0f); //!< font scale - float m_lineSpacing; //!< Spacing between new lines, as a percentage of m_scale. + float m_textSizeFactor = 12.0f; //!< font size in pixels + float m_lineSpacing = 1.0f; //!< Spacing between new lines, as a percentage of m_scale. TextHorizontalAlignment m_hAlign = TextHorizontalAlignment::Left; //!< Horizontal text alignment TextVerticalAlignment m_vAlign = TextVerticalAlignment::Top; //!< Vertical text alignment + bool m_useTransform = false; //!< Use specified transform + AZ::Matrix3x4 m_transform = AZ::Matrix3x4::Identity(); //!< Transform to apply to text quads bool m_monospace = false; //!< disable character proportional spacing bool m_depthTest = false; //!< Test character against the depth buffer bool m_virtual800x600ScreenSize = true; //!< Text placement and size are scaled relative to a virtual 800x600 resolution diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index fc58eb9f07..31eb089803 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -54,7 +54,6 @@ #include -static const AZ::Vector2 UiDraw_TextSizeFactor = AZ::Vector2(12.0f, 12.0f); static const int TabCharCount = 4; // set buffer sizes to hold max characters that can be drawn in 1 DrawString call static const size_t MaxVerts = 8 * 1024; // 2048 quads @@ -1673,6 +1672,12 @@ static void SetCommonContextFlags(AZ::TextDrawContext& ctx, const AzFramework::T { ctx.m_drawTextFlags |= eDrawText_FixedSize; } + + if (params.m_useTransform) + { + ctx.m_drawTextFlags |= eDrawText_UseTransform; + ctx.SetTransform(AZMatrix3x4ToLYMatrix3x4(params.m_transform)); + } } AZ::FFont::DrawParameters AZ::FFont::ExtractDrawParameters(const AzFramework::TextDrawParameters& params, AZStd::string_view text, bool forceCalculateSize) @@ -1696,22 +1701,25 @@ AZ::FFont::DrawParameters AZ::FFont::ExtractDrawParameters(const AzFramework::Te } internalParams.m_ctx.SetBaseState(GS_NODEPTHTEST); internalParams.m_ctx.SetColor(AZColorToLYColorF(params.m_color)); + internalParams.m_ctx.SetEffect(params.m_effectIndex); internalParams.m_ctx.SetCharWidthScale((params.m_monospace || params.m_scaleWithWindow) ? 0.5f : 1.0f); internalParams.m_ctx.EnableFrame(false); internalParams.m_ctx.SetProportional(!params.m_monospace && params.m_scaleWithWindow); internalParams.m_ctx.SetSizeIn800x600(params.m_scaleWithWindow && params.m_virtual800x600ScreenSize); - internalParams.m_ctx.SetSize(AZVec2ToLYVec2(UiDraw_TextSizeFactor * params.m_scale)); + internalParams.m_ctx.SetSize(AZVec2ToLYVec2(AZ::Vector2(params.m_textSizeFactor, params.m_textSizeFactor) * params.m_scale)); internalParams.m_ctx.SetLineSpacing(params.m_lineSpacing); - if (params.m_monospace || !params.m_scaleWithWindow) - { - ScaleCoord(viewport, posX, posY); - } if (params.m_hAlign != AzFramework::TextHorizontalAlignment::Left || params.m_vAlign != AzFramework::TextVerticalAlignment::Top || forceCalculateSize) { + // We align based on the size of the default font effect because we do not want the + // text to move when the font effect is changed + unsigned int effectIndex = internalParams.m_ctx.m_fxIdx; + internalParams.m_ctx.SetEffect(0); Vec2 textSize = GetTextSizeUInternal(viewport, text.data(), params.m_multiline, internalParams.m_ctx); + internalParams.m_ctx.SetEffect(effectIndex); + // If we're using virtual 800x600 coordinates, convert the text size from // pixels to that before using it as an offset. if (internalParams.m_ctx.m_sizeIn800x600) diff --git a/Gems/LyShine/Code/Editor/ViewportHelpers.cpp b/Gems/LyShine/Code/Editor/ViewportHelpers.cpp index 428554a461..2195d2c9d4 100644 --- a/Gems/LyShine/Code/Editor/ViewportHelpers.cpp +++ b/Gems/LyShine/Code/Editor/ViewportHelpers.cpp @@ -30,6 +30,11 @@ namespace ViewportHelpers return isControlledByParent; } + float GetDpiScaledSize(float size) + { + return size * ViewportIcon::GetDpiScaleFactor(); + } + bool IsHorizontallyFit(const AZ::Entity* element) { bool isHorizontallyFit = false; @@ -332,11 +337,12 @@ namespace ViewportHelpers AZ::Vector2 pivotPos; EBUS_EVENT_ID_RESULT(pivotPos, element->GetId(), UiTransformBus, GetViewportSpacePivot); - AZ::Vector2 rotationStringPos(pivotPos.GetX(), pivotPos.GetY() - ((viewportPivot->GetSize().GetY() * 0.5f) + 4.0f)); + float offset = (viewportPivot->GetSize().GetY() * 0.5f) + (GetDpiScaledSize(4.0f)); + AZ::Vector2 rotationStringPos(pivotPos.GetX(), pivotPos.GetY() - offset); draw2d.SetTextAlignment(IDraw2d::HAlign::Center, IDraw2d::VAlign::Bottom); draw2d.SetTextRotation(0.0f); - draw2d.DrawText(rotationString.toUtf8().data(), rotationStringPos, 16.0f, 1.0f); + draw2d.DrawText(rotationString.toUtf8().data(), rotationStringPos, GetDpiScaledSize(16.0f), 1.0f); } } @@ -350,6 +356,6 @@ namespace ViewportHelpers draw2d.SetTextAlignment(IDraw2d::HAlign::Left, IDraw2d::VAlign::Bottom); draw2d.SetTextRotation(0.0f); - draw2d.DrawText(textLabel.c_str(), textPos, 16.0f, 1.0f); + draw2d.DrawText(textLabel.c_str(), textPos, GetDpiScaledSize(16.0f), 1.0f); } } // namespace ViewportHelpers diff --git a/Gems/LyShine/Code/Editor/ViewportIcon.cpp b/Gems/LyShine/Code/Editor/ViewportIcon.cpp index b1866efb00..4be06b2543 100644 --- a/Gems/LyShine/Code/Editor/ViewportIcon.cpp +++ b/Gems/LyShine/Code/Editor/ViewportIcon.cpp @@ -303,7 +303,7 @@ void ViewportIcon::DrawDistanceLine(Draw2dHelper& draw2d, AZ::Vector2 start, AZ: draw2d.SetTextAlignment(IDraw2d::HAlign::Center, IDraw2d::VAlign::Bottom); draw2d.SetTextRotation(rotation); - draw2d.DrawText(textBuf, textPos, 16.0f, 1.0f); + draw2d.DrawText(textBuf, textPos, 16.0f * ViewportIcon::GetDpiScaleFactor(), 1.0f); } void ViewportIcon::DrawAnchorLinesSplit(Draw2dHelper& draw2d, AZ::Vector2 anchorPos1, AZ::Vector2 anchorPos2, diff --git a/Gems/LyShine/Code/Include/LyShine/Draw2d.h b/Gems/LyShine/Code/Include/LyShine/Draw2d.h index 8270461e73..b83ec4794b 100644 --- a/Gems/LyShine/Code/Include/LyShine/Draw2d.h +++ b/Gems/LyShine/Code/Include/LyShine/Draw2d.h @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -256,9 +257,8 @@ protected: // types and constants const Draw2dShaderData& shaderData, AZ::RPI::ViewportContextPtr viewportContext) const override; - STextDrawContext m_fontContext; - IFFont* m_font; - AZ::Vector2 m_position; + AzFramework::TextDrawParameters m_drawParameters; + AzFramework::FontId m_fontId; std::string m_string; }; @@ -288,7 +288,7 @@ protected: // member functions void RotatePointsAboutPivot(AZ::Vector2* points, int numPoints, AZ::Vector2 pivot, float angle) const; //! Helper function to render a text string - void DrawTextInternal(const char* textString, IFFont* font, unsigned int effectIndex, + void DrawTextInternal(const char* textString, AzFramework::FontId fontId, unsigned int effectIndex, AZ::Vector2 position, float pointSize, AZ::Color color, float rotation, HAlign horizontalAlignment, VAlign verticalAlignment, int baseState); @@ -298,6 +298,9 @@ protected: // member functions //! Draw or defer a line void DrawOrDeferLine(const DeferredLine* line); + //! Draw or defer a text string + void DrawOrDeferTextString(const DeferredText* text); + //! Draw or defer a rect outline void DrawOrDeferRectOutline(const DeferredRectOutline* outlineRect); @@ -491,7 +494,7 @@ public: // member functions void SetImageBaseState(int state) { m_imageOptions.baseState = state; } //! Set the text font. - void SetTextFont(IFFont* font) { m_textOptions.font = font; } + void SetTextFont(AZStd::string_view fontName) { m_textOptions.fontName = fontName; } //! Set the text font effect index. void SetTextEffectIndex(unsigned int effectIndex) { m_textOptions.effectIndex = effectIndex; } diff --git a/Gems/LyShine/Code/Source/Draw2d.cpp b/Gems/LyShine/Code/Source/Draw2d.cpp index 1a639ea299..6feb47419d 100644 --- a/Gems/LyShine/Code/Source/Draw2d.cpp +++ b/Gems/LyShine/Code/Source/Draw2d.cpp @@ -11,11 +11,13 @@ */ #include "LyShine_precompiled.h" #include "IFont.h" +#include // for SVF_P3F_C4B_T2F which will be removed in a coming PR #include #include #include +#include #include #include @@ -55,7 +57,7 @@ CDraw2d::CDraw2d(AZ::RPI::ViewportContextPtr viewportContext) m_defaultImageOptions.pixelRounding = Rounding::Nearest; m_defaultImageOptions.baseState = g_defaultBaseState; - m_defaultTextOptions.font = (gEnv && gEnv->pCryFont != nullptr) ? gEnv->pCryFont->GetFont("default") : nullptr; + m_defaultTextOptions.fontName = "default"; m_defaultTextOptions.effectIndex = 0; m_defaultTextOptions.color.Set(1.0f, 1.0f, 1.0f); m_defaultTextOptions.horizontalAlignment = HAlign::Left; @@ -283,13 +285,20 @@ void CDraw2d::DrawText(const char* textString, AZ::Vector2 position, float point { TextOptions* actualTextOptions = (textOptions) ? textOptions : &m_defaultTextOptions; + AzFramework::FontId fontId = AzFramework::InvalidFontId; + AzFramework::FontQueryInterface* fontQueryInterface = AZ::Interface::Get(); + if (fontQueryInterface) + { + fontId = fontQueryInterface->GetFontId(actualTextOptions->fontName); + } + // render the drop shadow, if needed if ((actualTextOptions->dropShadowColor.GetA() > 0.0f) && (actualTextOptions->dropShadowOffset.GetX() || actualTextOptions->dropShadowOffset.GetY())) { // calculate the drop shadow pos and render it AZ::Vector2 dropShadowPosition(position + actualTextOptions->dropShadowOffset); - DrawTextInternal(textString, actualTextOptions->font, actualTextOptions->effectIndex, + DrawTextInternal(textString, fontId, actualTextOptions->effectIndex, dropShadowPosition, pointSize, actualTextOptions->dropShadowColor, actualTextOptions->rotation, actualTextOptions->horizontalAlignment, actualTextOptions->verticalAlignment, @@ -298,7 +307,7 @@ void CDraw2d::DrawText(const char* textString, AZ::Vector2 position, float point // draw the text string AZ::Color textColor = AZ::Color::CreateFromVector3AndFloat(actualTextOptions->color, opacity); - DrawTextInternal(textString, actualTextOptions->font, actualTextOptions->effectIndex, + DrawTextInternal(textString, fontId, actualTextOptions->effectIndex, position, pointSize, textColor, actualTextOptions->rotation, actualTextOptions->horizontalAlignment, actualTextOptions->verticalAlignment, @@ -398,20 +407,35 @@ void CDraw2d::DrawRectOutlineTextured(AZ::Data::Instance image, //////////////////////////////////////////////////////////////////////////////////////////////////// AZ::Vector2 CDraw2d::GetTextSize(const char* textString, float pointSize, TextOptions* textOptions) { - TextOptions* actualTextOptions = (textOptions) ? textOptions : &m_defaultTextOptions; - - if (!actualTextOptions->font) + AzFramework::FontDrawInterface* fontDrawInterface = nullptr; + AzFramework::FontQueryInterface* fontQueryInterface = AZ::Interface::Get(); + if (fontQueryInterface) + { + TextOptions* actualTextOptions = (textOptions) ? textOptions : &m_defaultTextOptions; + AzFramework::FontId fontId = fontQueryInterface->GetFontId(actualTextOptions->fontName); + fontDrawInterface = fontQueryInterface->GetFontDrawInterface(fontId); + } + if (!fontDrawInterface) { return AZ::Vector2(0.0f, 0.0f); } - STextDrawContext fontContext; - fontContext.SetEffect(actualTextOptions->effectIndex); - fontContext.SetSizeIn800x600(false); - fontContext.SetSize(vector2f(pointSize, pointSize)); + // Set up draw parameters + AzFramework::TextDrawParameters drawParams; + drawParams.m_drawViewportId = GetViewportContext()->GetId(); + drawParams.m_position = AZ::Vector3(0.0f, 0.0f, 1.0f); + drawParams.m_effectIndex = 0; + drawParams.m_textSizeFactor = pointSize; + drawParams.m_scale = AZ::Vector2(1.0f, 1.0f); + drawParams.m_lineSpacing = 1.0f; + drawParams.m_monospace = false; + drawParams.m_depthTest = false; + drawParams.m_virtual800x600ScreenSize = false; + drawParams.m_scaleWithWindow = false; + drawParams.m_multiline = true; - Vec2 textSize = actualTextOptions->font->GetTextSize(textString, true, fontContext); - return AZ::Vector2(textSize.x, textSize.y); + AZ::Vector2 textSize = fontDrawInterface->GetTextSize(drawParams, textString); + return textSize; } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -559,100 +583,89 @@ void CDraw2d::RotatePointsAboutPivot(AZ::Vector2* points, [[maybe_unused]] int n } //////////////////////////////////////////////////////////////////////////////////////////////////// -void CDraw2d::DrawTextInternal(const char* textString, IFFont* font, unsigned int effectIndex, +void CDraw2d::DrawTextInternal(const char* textString, AzFramework::FontId fontId, unsigned int effectIndex, AZ::Vector2 position, float pointSize, AZ::Color color, float rotation, - HAlign horizontalAlignment, VAlign verticalAlignment, int baseState) + HAlign horizontalAlignment, VAlign verticalAlignment, [[maybe_unused]] int baseState) { - if (!font) - { - return; - } - - STextDrawContext fontContext; - fontContext.SetEffect(effectIndex); - fontContext.SetSizeIn800x600(false); - fontContext.SetSize(vector2f(pointSize, pointSize)); - fontContext.SetColor(ColorF(color.GetR(), color.GetG(), color.GetB(), color.GetA())); - fontContext.m_baseState = baseState; - fontContext.SetOverrideViewProjMatrices(false); - // FFont.cpp uses the alpha value of the color to decide whether to use the color, if the alpha value is zero // (in a ColorB format) then the color set via SetColor is ignored and it usually ends up drawing with an alpha of 1. // This is not what we want so in this case do not draw at all. - if (!fontContext.IsColorOverridden()) + if (AZ::IsClose(color.GetA(), 0.0f)) { return; } - AZ::Vector2 alignedPosition; - if (horizontalAlignment == HAlign::Left && verticalAlignment == VAlign::Top) + // Convert Draw2d alignment to text alignment + AzFramework::TextHorizontalAlignment hAlignment = AzFramework::TextHorizontalAlignment::Left; + switch (horizontalAlignment) { - alignedPosition = position; - } - else - { - // we align based on the size of the default font effect, because we do not want the - // text to move when the font effect is changed - unsigned int fontEffectIndex = fontContext.m_fxIdx; - fontContext.SetEffect(0); - Vec2 textSize = font->GetTextSize(textString, true, fontContext); - fontContext.SetEffect(fontEffectIndex); - - alignedPosition = Align(position, AZ::Vector2(textSize.x, textSize.y), horizontalAlignment, verticalAlignment); + case HAlign::Left: + hAlignment = AzFramework::TextHorizontalAlignment::Left; + break; + case HAlign::Center: + hAlignment = AzFramework::TextHorizontalAlignment::Center; + break; + case HAlign::Right: + hAlignment = AzFramework::TextHorizontalAlignment::Right; + break; + default: + AZ_Assert(false, "Attempting to draw text with unsupported horizontal alignment."); + break; } - int flags = 0; + AzFramework::TextVerticalAlignment vAlignment = AzFramework::TextVerticalAlignment::Top; + switch (verticalAlignment) + { + case VAlign::Top: + vAlignment = AzFramework::TextVerticalAlignment::Top; + break; + case VAlign::Center: + vAlignment = AzFramework::TextVerticalAlignment::Center; + break; + case VAlign::Bottom: + vAlignment = AzFramework::TextVerticalAlignment::Bottom; + break; + default: + AZ_Assert(false, "Attempting to draw text with unsupported vertical alignment."); + break; + } + + // Set up draw parameters for font interface + AzFramework::TextDrawParameters drawParams; + drawParams.m_drawViewportId = GetViewportContext()->GetId(); + drawParams.m_position = AZ::Vector3(position.GetX(), position.GetY(), 1.0f); + drawParams.m_color = color; + drawParams.m_effectIndex = effectIndex; + drawParams.m_textSizeFactor = pointSize; + drawParams.m_scale = AZ::Vector2(1.0f, 1.0f); + drawParams.m_lineSpacing = 1.0f; //!< Spacing between new lines, as a percentage of m_scale. + drawParams.m_hAlign = hAlignment; + drawParams.m_vAlign = vAlignment; + drawParams.m_monospace = false; + drawParams.m_depthTest = false; + drawParams.m_virtual800x600ScreenSize = false; + drawParams.m_scaleWithWindow = false; + drawParams.m_multiline = true; + if (rotation != 0.0f) { // rotate around the position (if aligned to center will rotate about center etc) float rotRad = DEG2RAD(rotation); - Vec3 pivot(position.GetX(), position.GetY(), 0.0f); - Matrix34A moveToPivotSpaceMat = Matrix34A::CreateTranslationMat(-pivot); - Matrix34A rotMat = Matrix34A::CreateRotationZ(rotRad); - Matrix34A moveFromPivotSpaceMat = Matrix34A::CreateTranslationMat(pivot); + AZ::Vector3 pivot(position.GetX(), position.GetY(), 0.0f); + AZ::Matrix3x4 moveToPivotSpaceMat = AZ::Matrix3x4::CreateTranslation(-pivot); + AZ::Matrix3x4 rotMat = AZ::Matrix3x4::CreateRotationZ(rotRad); + AZ::Matrix3x4 moveFromPivotSpaceMat = AZ::Matrix3x4::CreateTranslation(pivot); - Matrix34A transform = moveFromPivotSpaceMat * rotMat * moveToPivotSpaceMat; - fontContext.SetTransform(transform); - flags |= eDrawText_UseTransform; + drawParams.m_transform = moveFromPivotSpaceMat * rotMat * moveToPivotSpaceMat; + drawParams.m_useTransform = true; } - // The font system uses these alignment flags to force text to be in the safe zone - // depending on overscan etc - if (horizontalAlignment == HAlign::Center) - { - flags |= eDrawText_Center; - } - else if (horizontalAlignment == HAlign::Right) - { - flags |= eDrawText_Right; - } + DeferredText newText; + newText.m_drawParameters = drawParams; + newText.m_fontId = fontId; + newText.m_string = textString; - if (verticalAlignment == VAlign::Center) - { - flags |= eDrawText_CenterV; - } - else if (verticalAlignment == VAlign::Bottom) - { - flags |= eDrawText_Bottom; - } - - fontContext.SetFlags(flags); - - if (m_deferCalls) - { - DeferredText* newText = new DeferredText; - - newText->m_fontContext = fontContext; - newText->m_font = font; - newText->m_position = alignedPosition; - newText->m_string = textString; - - m_deferredPrimitives.push_back(newText); - } - else - { - font->DrawString(alignedPosition.GetX(), alignedPosition.GetY(), textString, true, fontContext); - } + DrawOrDeferTextString(&newText); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -685,6 +698,20 @@ void CDraw2d::DrawOrDeferLine(const DeferredLine* line) } } +void CDraw2d::DrawOrDeferTextString(const DeferredText* text) +{ + if (m_deferCalls) + { + DeferredText* newText = new DeferredText; + *newText = *text; + m_deferredPrimitives.push_back(newText); + } + else + { + text->Draw(m_dynamicDraw, m_shaderData, GetViewportContext()); + } +} + void CDraw2d::DrawOrDeferRectOutline(const DeferredRectOutline* rectOutline) { if (m_deferCalls) @@ -919,6 +946,15 @@ void CDraw2d::DeferredText::Draw([[maybe_unused]] AZ::RHI::PtrDrawString(m_position.GetX(), m_position.GetY(), m_string.c_str(), true, m_fontContext); + AzFramework::FontDrawInterface* fontDrawInterface = nullptr; + AzFramework::FontQueryInterface* fontQueryInterface = AZ::Interface::Get(); + if (fontQueryInterface) + { + fontDrawInterface = fontQueryInterface->GetFontDrawInterface(m_fontId); + if (fontDrawInterface) + { + fontDrawInterface->DrawScreenAlignedText2d(m_drawParameters, m_string.c_str()); + } + } } diff --git a/Gems/LyShine/Code/Source/LyShine.cpp b/Gems/LyShine/Code/Source/LyShine.cpp index 679cae3421..fb6dcb2628 100644 --- a/Gems/LyShine/Code/Source/LyShine.cpp +++ b/Gems/LyShine/Code/Source/LyShine.cpp @@ -454,7 +454,6 @@ void CLyShine::Render() GetUiRenderer()->EndUiFrameRender(); -#ifdef LYSHINE_ATOM_TODO // convert debug info to Atom #ifndef _RELEASE if (CV_ui_DisplayElemBounds) { @@ -474,7 +473,6 @@ void CLyShine::Render() m_uiCanvasManager->DebugDisplayDrawCallData(); } #endif -#endif } //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/LyShine/Code/Source/LyShineDebug.cpp b/Gems/LyShine/Code/Source/LyShineDebug.cpp index 76b4030106..44e0e187ec 100644 --- a/Gems/LyShine/Code/Source/LyShineDebug.cpp +++ b/Gems/LyShine/Code/Source/LyShineDebug.cpp @@ -12,6 +12,7 @@ #include "LyShine_precompiled.h" #include "LyShineDebug.h" #include "IConsole.h" +#include "IRenderer.h" #include #include @@ -392,15 +393,15 @@ static void DebugDrawColoredBox(AZ::Vector2 pos, AZ::Vector2 size, AZ::Color col //////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(_RELEASE) -static void DebugDrawStringWithSizeBox(IFFont* font, unsigned int effectIndex, const char* sizeString, +static void DebugDrawStringWithSizeBox(AZStd::string_view font, unsigned int effectIndex, const char* sizeString, const char* testString, AZ::Vector2 pos, float spacing, float size) { CDraw2d* draw2d = Draw2dHelper::GetDefaultDraw2d(); IDraw2d::TextOptions textOptions = draw2d->GetDefaultTextOptions(); - if (font) + if (!font.empty()) { - textOptions.font = font; + textOptions.fontName = font; } textOptions.effectIndex = effectIndex; @@ -427,7 +428,7 @@ static void DebugDrawStringWithSizeBox(IFFont* font, unsigned int effectIndex, c //////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(_RELEASE) -static void DebugDraw2dFontSizes(IFFont* font, unsigned int effectIndex, const char* fontName) +static void DebugDraw2dFontSizes(AZStd::string_view font, unsigned int effectIndex) { CDraw2d* draw2d = Draw2dHelper::GetDefaultDraw2d(); @@ -436,7 +437,7 @@ static void DebugDraw2dFontSizes(IFFont* font, unsigned int effectIndex, const c float xSpacing = 20.0f; char buffer[32]; - sprintf_s(buffer, "Font = %s, effect = %d", fontName, effectIndex); + sprintf_s(buffer, "Font = %s, effect = %d", font.data(), effectIndex); draw2d->DrawText(buffer, AZ::Vector2(xOffset, yOffset), 32); yOffset += 40.0f; draw2d->DrawText("NOTE: if the effect includes a drop shadow baked into font then the pixel size", @@ -1441,10 +1442,10 @@ void LyShineDebug::RenderDebug() switch (CV_r_DebugUIDraw2dFont) { case 1: // test font sizes (default font, effect 0) - DebugDraw2dFontSizes(0, 0, "default"); + DebugDraw2dFontSizes("default", 0); break; case 2: // test font sizes (default font, effect 1) - DebugDraw2dFontSizes(0, 1, "default"); + DebugDraw2dFontSizes("default", 1); break; case 3: // test font alignment DebugDraw2dFontAlignment(); diff --git a/Gems/LyShine/Code/Source/LyShineDebug.h b/Gems/LyShine/Code/Source/LyShineDebug.h index ed03fd10b2..e50689710a 100644 --- a/Gems/LyShine/Code/Source/LyShineDebug.h +++ b/Gems/LyShine/Code/Source/LyShineDebug.h @@ -14,7 +14,9 @@ #ifndef _RELEASE #include -class ITexture; +#include +#include + #endif //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -66,7 +68,7 @@ public: // static member functions struct DebugInfoTextureUsage { - ITexture* m_texture; + AZ::Data::Instance m_texture; bool m_isClampTextureUsage; int m_numCanvasesUsed; int m_numDrawCallsUsed; diff --git a/Gems/LyShine/Code/Source/RenderGraph.cpp b/Gems/LyShine/Code/Source/RenderGraph.cpp index e5ac6c7b8f..d5a1df7b15 100644 --- a/Gems/LyShine/Code/Source/RenderGraph.cpp +++ b/Gems/LyShine/Code/Source/RenderGraph.cpp @@ -18,6 +18,7 @@ #include #ifndef _RELEASE +#include #include #endif @@ -1115,7 +1116,7 @@ namespace LyShine m_wasBuiltThisFrame = false; - AZStd::set uniqueTextures; + AZStd::set> uniqueTextures; // If we are rendering to the render targets this frame then record the stats for doing that if (m_renderToRenderTargetCount < 2) @@ -1144,13 +1145,11 @@ namespace LyShine } //////////////////////////////////////////////////////////////////////////////////////////////////// - void RenderGraph::GetDebugInfoRenderNodeList(const AZStd::vector& renderNodeList, LyShineDebug::DebugInfoRenderGraph& info, AZStd::set& uniqueTextures) const + void RenderGraph::GetDebugInfoRenderNodeList( + const AZStd::vector& renderNodeList, + LyShineDebug::DebugInfoRenderGraph& info, + AZStd::set>& uniqueTextures) const { - AZ_UNUSED(renderNodeList); - AZ_UNUSED(info); - AZ_UNUSED(uniqueTextures); - -#ifdef LYSHINE_ATOM_TODO // keeping this code for future phase (convert debug info to use Atom) const PrimitiveListRenderNode* prevPrimListNode = nullptr; bool isFirstNode = true; bool wasLastNodeAMask = false; @@ -1235,7 +1234,6 @@ namespace LyShine isFirstNode = false; } -#endif } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1290,13 +1288,6 @@ namespace LyShine void* context, const AZStd::string& indent) const { - AZ_UNUSED(renderNodeList); - AZ_UNUSED(fileHandle); - AZ_UNUSED(reportInfo); - AZ_UNUSED(context); - AZ_UNUSED(indent); - -#ifdef LYSHINE_ATOM_TODO // keeping this code for future phase (convert debug info to use Atom) AZStd::string logLine; bool previousNodeAlreadyCounted = false; @@ -1355,10 +1346,10 @@ namespace LyShine { for (int i = 0; i < prevPrimListNode->GetNumTextures(); ++i) { - ITexture* texture = prevPrimListNode->GetTexture(i); + AZ::Data::Instance texture = prevPrimListNode->GetTexture(i); if (!texture) { - texture = gEnv->pRenderer->GetWhiteTexture(); + texture = AZ::RPI::ImageSystemInterface::Get()->GetSystemImage(AZ::RPI::SystemImage::White); } bool isClampTextureUsage = prevPrimListNode->GetTextureIsClampMode(i); @@ -1405,17 +1396,19 @@ namespace LyShine for (int i = 0; i < primListRenderNode->GetNumTextures(); ++i) { - ITexture* texture = primListRenderNode->GetTexture(i); + AZ::Data::Instance texture = primListRenderNode->GetTexture(i); if (!texture) { - texture = gEnv->pRenderer->GetWhiteTexture(); + texture = AZ::RPI::ImageSystemInterface::Get()->GetSystemImage(AZ::RPI::SystemImage::White); } bool isClampTextureUsage = primListRenderNode->GetTextureIsClampMode(i); LyShineDebug::DebugInfoTextureUsage* matchingTextureUsage = nullptr; // Write line to logfile for this texture - logLine = AZStd::string::format("%s %s\r\n", indent.c_str(), texture->GetName()); + AZStd::string textureName; + AZ::Data::AssetCatalogRequestBus::BroadcastResult(textureName, &AZ::Data::AssetCatalogRequests::GetAssetPathById, texture->GetAssetId()); + logLine = AZStd::string::format("%s %s\r\n", indent.c_str(), textureName.c_str()); AZ::IO::LocalFileIO::GetInstance()->Write(fileHandle, logLine.c_str(), logLine.size()); // see if texture is in reportInfo @@ -1459,7 +1452,6 @@ namespace LyShine prevPrimListNode = primListRenderNode; } } -#endif } #endif diff --git a/Gems/LyShine/Code/Source/RenderGraph.h b/Gems/LyShine/Code/Source/RenderGraph.h index f9d16cf8b7..2f1586e857 100644 --- a/Gems/LyShine/Code/Source/RenderGraph.h +++ b/Gems/LyShine/Code/Source/RenderGraph.h @@ -13,7 +13,6 @@ #pragma once #include -#include #include #include #include @@ -294,7 +293,10 @@ namespace LyShine void ValidateGraph(); void GetDebugInfoRenderGraph(LyShineDebug::DebugInfoRenderGraph& info) const; - void GetDebugInfoRenderNodeList(const AZStd::vector& renderNodeList, LyShineDebug::DebugInfoRenderGraph& info, AZStd::set& uniqueTextures) const; + void GetDebugInfoRenderNodeList( + const AZStd::vector& renderNodeList, + LyShineDebug::DebugInfoRenderGraph& info, + AZStd::set>& uniqueTextures) const; void DebugReportDrawCalls(AZ::IO::HandleType fileHandle, LyShineDebug::DebugInfoDrawCallReport& reportInfo, void* context) const; void DebugReportDrawCallsRenderNodeList(const AZStd::vector& renderNodeList, AZ::IO::HandleType fileHandle, diff --git a/Gems/LyShine/Code/Source/UiCanvasManager.cpp b/Gems/LyShine/Code/Source/UiCanvasManager.cpp index 4115feaf22..b64a13280f 100644 --- a/Gems/LyShine/Code/Source/UiCanvasManager.cpp +++ b/Gems/LyShine/Code/Source/UiCanvasManager.cpp @@ -1425,7 +1425,8 @@ void UiCanvasManager::DebugReportDrawCalls(const AZStd::string& name) const if (reportTextureUsage.m_numCanvasesUsed > 1 && reportTextureUsage.m_numDrawCallsWhereExceedingMaxTextures) { - AZStd::string textureName = reportTextureUsage.m_texture->GetName(); + AZStd::string textureName; + AZ::Data::AssetCatalogRequestBus::BroadcastResult(textureName, &AZ::Data::AssetCatalogRequests::GetAssetPathById, reportTextureUsage.m_texture->GetAssetId()); if (textureName.compare(0, fontTexturePrefix.length(), fontTexturePrefix) != 0) { logLine = AZStd::string::format("%s\r\n", textureName.c_str()); @@ -1457,7 +1458,8 @@ void UiCanvasManager::DebugReportDrawCalls(const AZStd::string& name) const reportTextureUsage.m_lastContextUsed == canvas && reportTextureUsage.m_numDrawCallsWhereExceedingMaxTextures) { - AZStd::string textureName = reportTextureUsage.m_texture->GetName(); + AZStd::string textureName; + AZ::Data::AssetCatalogRequestBus::BroadcastResult(textureName, &AZ::Data::AssetCatalogRequests::GetAssetPathById, reportTextureUsage.m_texture->GetAssetId()); // exclude font textures if (textureName.compare(0, fontTexturePrefix.length(), fontTexturePrefix) != 0) diff --git a/Gems/LyShine/Code/Source/UiRenderer.cpp b/Gems/LyShine/Code/Source/UiRenderer.cpp index 2a2c950e82..57acbed5d5 100644 --- a/Gems/LyShine/Code/Source/UiRenderer.cpp +++ b/Gems/LyShine/Code/Source/UiRenderer.cpp @@ -12,6 +12,7 @@ #include "LyShine_precompiled.h" #include "UiRenderer.h" +#include #include #include #include @@ -24,7 +25,7 @@ #include #include -#include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC MEMBER FUNCTIONS @@ -353,7 +354,6 @@ void UiRenderer::DebugDisplayTextureData(int recordingOption) { if (recordingOption > 0) { -#ifdef LYSHINE_ATOM_TODO // compute the total area of all the textures, also create a vector that we can sort by area AZStd::vector textures; int totalArea = 0; @@ -374,15 +374,14 @@ void UiRenderer::DebugDisplayTextureData(int recordingOption) return lhs->GetDataSize() > rhs->GetDataSize(); }); - IDraw2d* draw2d = Draw2dHelper::GetDraw2d(); + CDraw2d* draw2d = Draw2dHelper::GetDefaultDraw2d(); // setup to render lines of text for the debug display - draw2d->BeginDraw2d(false); float xOffset = 20.0f; float yOffset = 20.0f; - int blackTexture = gEnv->pRenderer->GetBlackTextureId(); + auto blackTexture = AZ::RPI::ImageSystemInterface::Get()->GetSystemImage(AZ::RPI::SystemImage::Black); float textOpacity = 1.0f; float backgroundRectOpacity = 0.75f; const float lineSpacing = 20.0f; @@ -432,9 +431,6 @@ void UiRenderer::DebugDisplayTextureData(int recordingOption) texture->GetWidth(), texture->GetHeight(), texture->GetDataSize(), texture->GetFormatName(), texture->GetName()); WriteLine(buffer, white); } - - draw2d->EndDraw2d(); -#endif } } diff --git a/Gems/LyShine/Code/Source/UiRenderer.h b/Gems/LyShine/Code/Source/UiRenderer.h index 260bd8278c..888c88586a 100644 --- a/Gems/LyShine/Code/Source/UiRenderer.h +++ b/Gems/LyShine/Code/Source/UiRenderer.h @@ -20,6 +20,8 @@ #include #endif +class ITexture; + //////////////////////////////////////////////////////////////////////////////////////////////////// //! UI render interface // @@ -136,8 +138,6 @@ protected: // attributes #ifndef _RELEASE int m_debugTextureDataRecordLevel = 0; -#ifdef LYSHINE_ATOM_TODO // Convert debug code to Atom - AZStd::unordered_set m_texturesUsedInFrame; -#endif + AZStd::unordered_set m_texturesUsedInFrame; // LYSHINE_ATOM_TODO - convert to RPI::Image #endif }; From c84989832d82719e1687386676b0fb0944faf539 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Wed, 26 May 2021 21:07:49 -0700 Subject: [PATCH 203/811] ATOM-13216 Delete Deprecated Functors Removed unused PropertyVisibilityFunctor and ShaderEnableFunctor --- .../Code/Source/CommonSystemComponent.cpp | 4 - .../Source/EditorCommonSystemComponent.cpp | 6 - .../Material/PropertyVisibilityFunctor.cpp | 77 ------------ .../Material/PropertyVisibilityFunctor.h | 49 -------- .../PropertyVisibilityFunctorSourceData.cpp | 100 --------------- .../PropertyVisibilityFunctorSourceData.h | 48 -------- .../Source/Material/ShaderEnableFunctor.cpp | 74 ----------- .../Source/Material/ShaderEnableFunctor.h | 63 ---------- .../ShaderEnableFunctorSourceData.cpp | 116 ------------------ .../Material/ShaderEnableFunctorSourceData.h | 52 -------- .../atom_feature_common_editor_files.cmake | 4 - .../Code/atom_feature_common_files.cmake | 4 - 12 files changed, 597 deletions(-) delete mode 100644 Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctor.cpp delete mode 100644 Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctor.h delete mode 100644 Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctorSourceData.cpp delete mode 100644 Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctorSourceData.h delete mode 100644 Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctor.cpp delete mode 100644 Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctor.h delete mode 100644 Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctorSourceData.cpp delete mode 100644 Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctorSourceData.h diff --git a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp index 089a6168b1..16f20d7178 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp @@ -14,8 +14,6 @@ #include #include #include -#include -#include #include #include @@ -114,7 +112,6 @@ namespace AZ ProjectedShadowFeatureProcessor::Reflect(context); SkyBoxFeatureProcessor::Reflect(context); UseTextureFunctor::Reflect(context); - PropertyVisibilityFunctor::Reflect(context); DrawListFunctor::Reflect(context); SubsurfaceTransmissionParameterFunctor::Reflect(context); Transform2DFunctor::Reflect(context); @@ -126,7 +123,6 @@ namespace AZ DisplayMapperPassData::Reflect(context); ConvertEmissiveUnitFunctor::Reflect(context); LookupTableAsset::Reflect(context); - ShaderEnableFunctor::Reflect(context); ReflectionProbeFeatureProcessor::Reflect(context); DecalTextureArrayFeatureProcessor::Reflect(context); SMAAFeatureProcessor::Reflect(context); diff --git a/Gems/Atom/Feature/Common/Code/Source/EditorCommonSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/EditorCommonSystemComponent.cpp index 32a29cf4d3..2373d0cb00 100644 --- a/Gems/Atom/Feature/Common/Code/Source/EditorCommonSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/EditorCommonSystemComponent.cpp @@ -12,11 +12,9 @@ #include #include -#include #include #include #include -#include #include #include @@ -58,11 +56,9 @@ namespace AZ } AZ::Render::UseTextureFunctorSourceData::Reflect(context); - AZ::Render::PropertyVisibilityFunctorSourceData::Reflect(context); AZ::Render::DrawListFunctorSourceData::Reflect(context); AZ::Render::Transform2DFunctorSourceData::Reflect(context); AZ::Render::ConvertEmissiveUnitFunctorSourceData::Reflect(context); - AZ::Render::ShaderEnableFunctorSourceData::Reflect(context); AZ::Render::SubsurfaceTransmissionParameterFunctorSourceData::Reflect(context); AZ::Render::EditorLightingPreset::Reflect(context); @@ -104,11 +100,9 @@ namespace AZ } materialFunctorRegistration->RegisterMaterialFunctor("UseTexture", azrtti_typeid()); - materialFunctorRegistration->RegisterMaterialFunctor("UpdatePropertyVisibility", azrtti_typeid()); materialFunctorRegistration->RegisterMaterialFunctor("OverrideDrawList", azrtti_typeid()); materialFunctorRegistration->RegisterMaterialFunctor("Transform2D", azrtti_typeid()); materialFunctorRegistration->RegisterMaterialFunctor("ConvertEmissiveUnit", azrtti_typeid()); - materialFunctorRegistration->RegisterMaterialFunctor("ShaderEnable", azrtti_typeid()); materialFunctorRegistration->RegisterMaterialFunctor("HandleSubsurfaceScatteringParameters", azrtti_typeid()); materialFunctorRegistration->RegisterMaterialFunctor("Lua", azrtti_typeid()); diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctor.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctor.cpp deleted file mode 100644 index da8730f1ed..0000000000 --- a/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctor.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "PropertyVisibilityFunctor.h" - -namespace AZ -{ - namespace Render - { - void PropertyVisibilityFunctor::Reflect(ReflectContext* context) - { - if (auto* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("triggerProperty", &Action::m_triggerPropertyIndex) - ->Field("triggerValue", &Action::m_triggerValue) - ->Field("visibility", &Action::m_visibility) - ; - serializeContext->Class() - ->Version(1) - ->Field("actions", &PropertyVisibilityFunctor::m_actions) - ->Field("affectedProperties", &PropertyVisibilityFunctor::m_affectedProperties) - ; - } - } - - void PropertyVisibilityFunctor::Process(EditorContext& context) - { - bool visibilityApplied = false; - RPI::MaterialPropertyVisibility lastAppliedVisibility; - - for (const auto& action : m_actions) - { - bool willSetVisibility = false; - if (action.m_triggerValue.Is() || action.m_triggerValue.Is() || action.m_triggerValue.Is()) - { - willSetVisibility = action.m_triggerValue == context.GetMaterialPropertyValue(action.m_triggerPropertyIndex); - } - else if (action.m_triggerValue.Is()) - { - willSetVisibility = AZ::IsClose(action.m_triggerValue.GetValue(), - context.GetMaterialPropertyValue(action.m_triggerPropertyIndex), - std::numeric_limits::epsilon()); - } - else // for types Vector2, Vector3, Vector4, Color, Image - { - AZ_Error("PropertyVisibilityFunctor", false, "Unsupported property data type as an enable property."); - } - - if (willSetVisibility) - { - visibilityApplied = true; - lastAppliedVisibility = action.m_visibility; - } - } - - if (visibilityApplied) - { - for (const auto& propertyIndex : m_affectedProperties) - { - context.SetMaterialPropertyVisibility(propertyIndex, lastAppliedVisibility); - } - } - } - - } // namespace Render -} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctor.h b/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctor.h deleted file mode 100644 index d1a7772fc8..0000000000 --- a/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctor.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include - -namespace AZ -{ - namespace Render - { - //! Materials can use this functor to control when and how to set the visibility of a group of properties. - class PropertyVisibilityFunctor final - : public RPI::MaterialFunctor - { - friend class PropertyVisibilityFunctorSourceData; - public: - AZ_RTTI(AZ::Render::PropertyVisibilityFunctor, "{2582B36F-FA7C-450F-B46A-39AAE18356A0}", RPI::MaterialFunctor); - - static void Reflect(ReflectContext* context); - - void Process(EditorContext& context) override; - - private: - struct Action - { - AZ_TYPE_INFO(AZ::Render::PropertyVisibilityFunctor::Action, "{5DF4D981-9D0C-4040-A6C5-52E1D0BD876B}"); - - RPI::MaterialPropertyIndex m_triggerPropertyIndex; //! The control property for affected properties. - RPI::MaterialPropertyValue m_triggerValue; //! The trigger value of the control property. - RPI::MaterialPropertyVisibility m_visibility; //! The visibility of affected properties when the trigger value is hit. - }; - // Material property inputs... - AZStd::vector m_actions; //! The actions that describes when and what to do with visibilities. - AZStd::vector m_affectedProperties; //! The properties that are affected by actions. - }; - - } // namespace Render -} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctorSourceData.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctorSourceData.cpp deleted file mode 100644 index 3baf27de60..0000000000 --- a/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctorSourceData.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "PropertyVisibilityFunctorSourceData.h" -#include -#include - -#include - -namespace AZ -{ - namespace Render - { - void PropertyVisibilityFunctorSourceData::Reflect(ReflectContext* context) - { - if (auto* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("triggerProperty", &ActionSourceData::m_triggerPropertyName) - ->Field("triggerValue", &ActionSourceData::m_triggerValue) - ->Field("visibility", &ActionSourceData::m_visibility) - ; - serializeContext->Class() - ->Version(2) - ->Field("actions", &PropertyVisibilityFunctorSourceData::m_actions) - ->Field("affectedProperties", &PropertyVisibilityFunctorSourceData::m_affectedPropertyNames) - ; - } - } - - RPI::MaterialFunctorSourceData::FunctorResult PropertyVisibilityFunctorSourceData::CreateFunctor(const EditorContext& context) const - { - using namespace RPI; - - RPI::Ptr functor = aznew PropertyVisibilityFunctor; - - functor->m_actions.reserve(m_actions.size()); - - for (const auto& actionSource : m_actions) - { - functor->m_actions.emplace_back(); - PropertyVisibilityFunctor::Action& action = functor->m_actions.back(); - action.m_triggerPropertyIndex = context.FindMaterialPropertyIndex(AZ::Name{ actionSource.m_triggerPropertyName }); - if (action.m_triggerPropertyIndex.IsNull()) - { - return Failure(); - } - AddMaterialPropertyDependency(functor, action.m_triggerPropertyIndex); - - if (!actionSource.m_triggerValue.Resolve(*context.GetMaterialPropertiesLayout(), Name{ actionSource.m_triggerPropertyName })) - { - // Error is reported in Resolve(). - return Failure(); - } - - const MaterialPropertyDescriptor* propertyDescriptor = context.GetMaterialPropertiesLayout()->GetPropertyDescriptor(action.m_triggerPropertyIndex); - // Enum type should resolve further to a unit32_t from the string source. - if (propertyDescriptor->GetDataType() == RPI::MaterialPropertyDataType::Enum) - { - if (!RPI::MaterialUtils::ResolveMaterialPropertyEnumValue( - propertyDescriptor, - Name(actionSource.m_triggerValue.GetValue().GetValue()), - action.m_triggerValue)) - { - return Failure(); - } - } - else - { - action.m_triggerValue = actionSource.m_triggerValue.GetValue(); - } - - action.m_visibility = actionSource.m_visibility; - } - - functor->m_affectedProperties.reserve(m_affectedPropertyNames.size()); - for (const AZStd::string& name : m_affectedPropertyNames) - { - RPI::MaterialPropertyIndex index = context.FindMaterialPropertyIndex(AZ::Name{ name }); - if (index.IsNull()) - { - return Failure(); - } - functor->m_affectedProperties.push_back(index); - } - - return Success(RPI::Ptr(functor)); - } - } // namespace Render -} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctorSourceData.h b/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctorSourceData.h deleted file mode 100644 index 6b212f78a0..0000000000 --- a/Gems/Atom/Feature/Common/Code/Source/Material/PropertyVisibilityFunctorSourceData.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include "PropertyVisibilityFunctor.h" -#include -#include - -namespace AZ -{ - namespace Render - { - //! Builds a PropertyVisibilityFunctor. - //! Materials can use this functor to control whether a specific property group will be enabled. - class PropertyVisibilityFunctorSourceData final - : public RPI::MaterialFunctorSourceData - { - public: - AZ_RTTI(AZ::Render::PropertyVisibilityFunctorSourceData, "{B44E6929-8FFF-405F-9056-B9B811F97676}", RPI::MaterialFunctorSourceData); - - static void Reflect(ReflectContext* context); - - FunctorResult CreateFunctor(const EditorContext& context) const override; - private: - struct ActionSourceData - { - AZ_TYPE_INFO(AZ::Render::PropertyVisibilityFunctorSourceData::ActionSourceData, "{70E01DA6-0B42-4CCB-AAD0-51980DB43F62}"); - AZStd::string m_triggerPropertyName; //! The control property for affected properties. - RPI::MaterialPropertyValueSourceData m_triggerValue; //! The trigger value of the control property. - RPI::MaterialPropertyVisibility m_visibility; //! The visibility of affected properties when the trigger value is hit. - }; - // Material property inputs... - AZStd::vector m_actions; //! The actions that describes when and what to do with visibilities. - AZStd::vector m_affectedPropertyNames; //! The properties that are affected by actions. - }; - - } // namespace Render -} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctor.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctor.cpp deleted file mode 100644 index dd602cc4ba..0000000000 --- a/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctor.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "./ShaderEnableFunctor.h" -#include -#include -#include - -namespace AZ -{ - namespace Render - { - void ShaderEnableFunctor::Reflect(ReflectContext* context) - { - if (auto* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(4) - ->Field("opacityModeIndex", &ShaderEnableFunctor::m_opacityModeIndex) - ->Field("parallaxEnableIndex", &ShaderEnableFunctor::m_parallaxEnableIndex) - ->Field("parallaxPdoEnableIndex", &ShaderEnableFunctor::m_parallaxPdoEnableIndex) - ->Field("shadowShaderNoPSIndex", &ShaderEnableFunctor::m_shadowShaderNoPSIndex) - ->Field("shadowShaderWithPSIndex", &ShaderEnableFunctor::m_shadowShaderWithPSIndex) - ->Field("depthShaderNoPSIndex", &ShaderEnableFunctor::m_depthShaderNoPSIndex) - ->Field("depthShaderWithPSIndex", &ShaderEnableFunctor::m_depthShaderWithPSIndex) - ->Field("pbrShaderNoEdsIndex", &ShaderEnableFunctor::m_pbrShaderNoEdsIndex) - ->Field("pbrShaderWithEdsIndex", &ShaderEnableFunctor::m_pbrShaderWithEdsIndex) - ->Field("depthShaderTransparentMin", &ShaderEnableFunctor::m_depthShaderTransparentMin) - ->Field("depthShaderTransparentMax", &ShaderEnableFunctor::m_depthShaderTransparentMax) - ; - } - } - - void ShaderEnableFunctor::Process(RuntimeContext& context) - { - unsigned int opacityMode = context.GetMaterialPropertyValue(m_opacityModeIndex); - bool parallaxEnabled = context.GetMaterialPropertyValue(m_parallaxEnableIndex); - bool parallaxPdoEnabled = context.GetMaterialPropertyValue(m_parallaxPdoEnableIndex); - - if (parallaxEnabled && parallaxPdoEnabled) - { - context.SetShaderEnabled(m_depthShaderNoPSIndex, false); - context.SetShaderEnabled(m_shadowShaderNoPSIndex, false); - context.SetShaderEnabled(m_pbrShaderWithEdsIndex, false); - - context.SetShaderEnabled(m_depthShaderWithPSIndex, true); - context.SetShaderEnabled(m_shadowShaderWithPSIndex, true); - context.SetShaderEnabled(m_pbrShaderNoEdsIndex, true); - } - else - { - context.SetShaderEnabled(m_depthShaderNoPSIndex, opacityMode == OpacityMode::Opaque ); - context.SetShaderEnabled(m_shadowShaderNoPSIndex, opacityMode == OpacityMode::Opaque); - context.SetShaderEnabled(m_pbrShaderWithEdsIndex, opacityMode == OpacityMode::Opaque || opacityMode == OpacityMode::Blended || opacityMode == OpacityMode::TintedTransparent); - - context.SetShaderEnabled(m_depthShaderWithPSIndex, opacityMode == OpacityMode::Cutout); - context.SetShaderEnabled(m_shadowShaderWithPSIndex, opacityMode == OpacityMode::Cutout); - context.SetShaderEnabled(m_pbrShaderNoEdsIndex, opacityMode == OpacityMode::Cutout); - } - - context.SetShaderEnabled(m_depthShaderTransparentMin, opacityMode == OpacityMode::Blended || opacityMode == OpacityMode::TintedTransparent); - context.SetShaderEnabled(m_depthShaderTransparentMax, opacityMode == OpacityMode::Blended || opacityMode == OpacityMode::TintedTransparent); - } - } -} diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctor.h b/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctor.h deleted file mode 100644 index ac5f31ba30..0000000000 --- a/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctor.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include -#include - -namespace AZ -{ - namespace Render - { - enum OpacityMode - { - Opaque = 0, - Cutout, - Blended, - TintedTransparent, - }; - - //! Select shadow and depth shader based on opacity mode and parallax state - //! Opaque: Enable shader without PS - //! Cutout or Parallax enable: Enable shader with PS - //! Blended: Disable both - //! TintedTransparent: Disable both - class ShaderEnableFunctor final - : public RPI::MaterialFunctor - { - friend class ShaderEnableFunctorSourceData; - public: - AZ_RTTI(ShaderEnableFunctor, "{2079A693-FE4F-46A7-95C0-09D88AC156D0}", RPI::MaterialFunctor); - - static void Reflect(ReflectContext* context); - - void Process(RuntimeContext& context) override; - - private: - RPI::MaterialPropertyIndex m_opacityModeIndex; - RPI::MaterialPropertyIndex m_parallaxEnableIndex; - RPI::MaterialPropertyIndex m_parallaxPdoEnableIndex; - - uint32_t m_shadowShaderNoPSIndex = -1; - uint32_t m_shadowShaderWithPSIndex = -1; - uint32_t m_depthShaderNoPSIndex = -1; - uint32_t m_depthShaderWithPSIndex = -1; - uint32_t m_pbrShaderWithEdsIndex = -1; - uint32_t m_pbrShaderNoEdsIndex = -1; - // The following are used by the light culling system to produce min/max depth bounds - uint32_t m_depthShaderTransparentMin = -1; - uint32_t m_depthShaderTransparentMax = -1; - }; - } -} diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctorSourceData.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctorSourceData.cpp deleted file mode 100644 index 3c16666f82..0000000000 --- a/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctorSourceData.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "./ShaderEnableFunctorSourceData.h" -#include -#include - -namespace AZ -{ - namespace Render - { - void ShaderEnableFunctorSourceData::Reflect(ReflectContext* context) - { - if (auto* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(5) - ->Field("opacityMode", &ShaderEnableFunctorSourceData::m_opacityMode) - ->Field("parallaxEnable", &ShaderEnableFunctorSourceData::m_parallaxEnable) - ->Field("parallaxPdoEnable", &ShaderEnableFunctorSourceData::m_parallaxPdoEnable) - ->Field("shadowShaderNoPSIndex", &ShaderEnableFunctorSourceData::m_shadowShaderNoPSIndex) - ->Field("shadowShaderWithPSIndex", &ShaderEnableFunctorSourceData::m_shadowShaderWithPSIndex) - ->Field("depthShaderNoPSIndex", &ShaderEnableFunctorSourceData::m_depthShaderNoPSIndex) - ->Field("depthShaderWithPSIndex", &ShaderEnableFunctorSourceData::m_depthShaderWithPSIndex) - ->Field("pbrShaderNoEdsIndex", &ShaderEnableFunctorSourceData::m_pbrShaderNoEdsIndex) - ->Field("pbrShaderWithEdsIndex", &ShaderEnableFunctorSourceData::m_pbrShaderWithEdsIndex) - ->Field("depthShaderTransparentMin", &ShaderEnableFunctorSourceData::m_depthShaderTransparentMin) - ->Field("depthShaderTransparentMax", &ShaderEnableFunctorSourceData::m_depthShaderTransparentMax) - ; - } - } - - RPI::MaterialFunctorSourceData::FunctorResult ShaderEnableFunctorSourceData::CreateFunctor(const RuntimeContext& context) const - { - RPI::Ptr functor = aznew ShaderEnableFunctor; - - functor->m_opacityModeIndex = context.FindMaterialPropertyIndex(Name{ m_opacityMode }); - if (functor->m_opacityModeIndex.IsNull()) - { - return Failure(); - } - AddMaterialPropertyDependency(functor, functor->m_opacityModeIndex); - - functor->m_parallaxEnableIndex = context.FindMaterialPropertyIndex(Name{ m_parallaxEnable }); - if (functor->m_parallaxEnableIndex.IsNull()) - { - return Failure(); - } - AddMaterialPropertyDependency(functor, functor->m_parallaxEnableIndex); - - functor->m_parallaxPdoEnableIndex = context.FindMaterialPropertyIndex(Name{ m_parallaxPdoEnable }); - if (functor->m_parallaxPdoEnableIndex.IsNull()) - { - return Failure(); - } - AddMaterialPropertyDependency(functor, functor->m_parallaxPdoEnableIndex); - - if (!context.CheckShaderIndexValid(m_shadowShaderWithPSIndex)) - { - return Failure(); - } - functor->m_shadowShaderWithPSIndex = m_shadowShaderWithPSIndex; - - if (!context.CheckShaderIndexValid(m_shadowShaderNoPSIndex)) - { - return Failure(); - } - functor->m_shadowShaderNoPSIndex = m_shadowShaderNoPSIndex; - - if (!context.CheckShaderIndexValid(m_depthShaderWithPSIndex)) - { - return Failure(); - } - functor->m_depthShaderWithPSIndex = m_depthShaderWithPSIndex; - - if (!context.CheckShaderIndexValid(m_depthShaderNoPSIndex)) - { - return Failure(); - } - functor->m_depthShaderNoPSIndex = m_depthShaderNoPSIndex; - - if (!context.CheckShaderIndexValid(m_pbrShaderNoEdsIndex)) - { - return Failure(); - } - functor->m_pbrShaderNoEdsIndex = m_pbrShaderNoEdsIndex; - - if (!context.CheckShaderIndexValid(m_pbrShaderWithEdsIndex)) - { - return Failure(); - } - functor->m_pbrShaderWithEdsIndex = m_pbrShaderWithEdsIndex; - if (!context.CheckShaderIndexValid(m_depthShaderTransparentMin)) - { - return Failure(); - } - functor->m_depthShaderTransparentMin = m_depthShaderTransparentMin; - if (!context.CheckShaderIndexValid(m_depthShaderTransparentMax)) - { - return Failure(); - } - functor->m_depthShaderTransparentMax = m_depthShaderTransparentMax; - - return Success(RPI::Ptr(functor)); - } - } -} diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctorSourceData.h b/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctorSourceData.h deleted file mode 100644 index 2d00a4a015..0000000000 --- a/Gems/Atom/Feature/Common/Code/Source/Material/ShaderEnableFunctorSourceData.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include "./ShaderEnableFunctor.h" -#include - -namespace AZ -{ - namespace Render - { - class ShaderEnableFunctor; - - //! Builds a ShaderEnableFunctor - class ShaderEnableFunctorSourceData final - : public RPI::MaterialFunctorSourceData - { - public: - AZ_RTTI(ShaderEnableFunctorSourceData, "{63775ECB-5C3E-44D3-B175-4537BF76C3A7}", RPI::MaterialFunctorSourceData); - - static void Reflect(ReflectContext* context); - - FunctorResult CreateFunctor(const RuntimeContext& context) const override; - - private: - - AZStd::string m_opacityMode; - AZStd::string m_parallaxEnable; - AZStd::string m_parallaxPdoEnable; - - uint32_t m_shadowShaderNoPSIndex = -1; - uint32_t m_shadowShaderWithPSIndex = -1; - uint32_t m_depthShaderNoPSIndex = -1; - uint32_t m_depthShaderWithPSIndex = -1; - uint32_t m_pbrShaderWithEdsIndex = -1; - uint32_t m_pbrShaderNoEdsIndex = -1; - // The following are used by the light culling system to produce min/max depth bounds - uint32_t m_depthShaderTransparentMin = -1; - uint32_t m_depthShaderTransparentMax = -1; - }; - } -} diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_editor_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_editor_files.cmake index 3a749a4b67..4e7cc9dab3 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_editor_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_editor_files.cmake @@ -24,16 +24,12 @@ set(FILES Source/Material/ConvertEmissiveUnitFunctorSourceData.h Source/Material/MaterialConverterSystemComponent.cpp Source/Material/MaterialConverterSystemComponent.h - Source/Material/ShaderEnableFunctorSourceData.cpp - Source/Material/ShaderEnableFunctorSourceData.h Source/Material/SubsurfaceTransmissionParameterFunctorSourceData.cpp Source/Material/SubsurfaceTransmissionParameterFunctorSourceData.h Source/Material/Transform2DFunctorSourceData.cpp Source/Material/Transform2DFunctorSourceData.h Source/Material/UseTextureFunctorSourceData.cpp Source/Material/UseTextureFunctorSourceData.h - Source/Material/PropertyVisibilityFunctorSourceData.cpp - Source/Material/PropertyVisibilityFunctorSourceData.h Source/Material/DrawListFunctorSourceData.cpp Source/Material/DrawListFunctorSourceData.h ) diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake index 8926b0c19f..91d1587d27 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -153,16 +153,12 @@ set(FILES Source/LookupTable/LookupTableAsset.cpp Source/Material/ConvertEmissiveUnitFunctor.cpp Source/Material/ConvertEmissiveUnitFunctor.h - Source/Material/ShaderEnableFunctor.cpp - Source/Material/ShaderEnableFunctor.h Source/Material/SubsurfaceTransmissionParameterFunctor.cpp Source/Material/SubsurfaceTransmissionParameterFunctor.h Source/Material/Transform2DFunctor.cpp Source/Material/Transform2DFunctor.h Source/Material/UseTextureFunctor.cpp Source/Material/UseTextureFunctor.h - Source/Material/PropertyVisibilityFunctor.cpp - Source/Material/PropertyVisibilityFunctor.h Source/Material/DrawListFunctor.cpp Source/Material/DrawListFunctor.h Source/Math/GaussianMathFilter.h From 02e18be3fc5eda8a0ab9448f07765acadea2fd56 Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Wed, 26 May 2021 23:18:57 -0500 Subject: [PATCH 204/811] Turned off mac asset building on pc platforms (#977) --- Registry/AssetProcessorPlatformConfig.setreg | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Registry/AssetProcessorPlatformConfig.setreg b/Registry/AssetProcessorPlatformConfig.setreg index 7407fb18db..2147842da7 100644 --- a/Registry/AssetProcessorPlatformConfig.setreg +++ b/Registry/AssetProcessorPlatformConfig.setreg @@ -42,10 +42,10 @@ // 'enabled' is AUTOMATICALLY TRUE for the current platform that you are running on, so it is not necessary to force it to true for that platform // To enable any additional platform, just uncomment the appropriate line below. "Platforms": { - "pc": "enabled", + //"pc": "enabled", //"android": "enabled", //"ios": "enabled", - "mac": "enabled", + //"mac": "enabled", //"server": "enabled" }, // ---- The number of worker jobs, 0 means use the number of Logical Cores From 014f715fd88eb51677eea367638ea4ef3d611860 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Wed, 26 May 2021 21:27:31 -0700 Subject: [PATCH 205/811] ATOM-14037 StandardPBR TintedTransparent Opacity Copied tinted transparency opacity mode from EnhancedPBR to StandardPBR. Fixed a bug in EnhancedPBR where Blended opacity didn't work right because the second DrawListOverride functor was stomping on the results of the first DrawListOverride. I removed these functors and made StandardPBR_HandleOpacityMode.lua set the draw list override instead. --- .../Materials/Types/EnhancedPBR.materialtype | 18 --------------- .../Types/EnhancedPBR_ForwardPass.azsl | 10 ++++---- .../Materials/Types/StandardPBR.materialtype | 11 +-------- .../Types/StandardPBR_ForwardPass.azsl | 18 +++++++++++++++ .../Types/StandardPBR_HandleOpacityMode.lua | 3 +++ .../009_Opacity_TintedTransparent.material | 23 +++++++++++++++++++ 6 files changed, 50 insertions(+), 33 deletions(-) create mode 100644 Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/009_Opacity_TintedTransparent.material diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index 4c988c590a..36ebb3a0ca 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -1656,24 +1656,6 @@ "file": "StandardPBR_HandleOpacityDoubleSided.lua" } }, - { - "type": "OverrideDrawList", - "args": { - "triggerProperty": "opacity.mode", - "triggerValue": "Blended", - "shaderIndex": 1, - "drawList": "transparent" - } - }, - { - "type": "OverrideDrawList", - "args": { - "triggerProperty": "opacity.mode", - "triggerValue": "TintedTransparent", - "shaderIndex": 1, - "drawList": "transparent" - } - }, { "type": "Lua", "args": { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl index 440bb97c4e..a4fcccb5f5 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -267,16 +267,16 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // Directional light shadow coordinates lightingData.shadowCoords = IN.m_shadowCoords; - // ------- Occlusion ------- - - lightingData.diffuseAmbientOcclusion = GetOcclusionInput(MaterialSrg::m_diffuseOcclusionMap, MaterialSrg::m_sampler, IN.m_uv[MaterialSrg::m_diffuseOcclusionMapUvIndex], MaterialSrg::m_diffuseOcclusionFactor, o_diffuseOcclusion_useTexture); - lightingData.specularOcclusion = GetOcclusionInput(MaterialSrg::m_specularOcclusionMap, MaterialSrg::m_sampler, IN.m_uv[MaterialSrg::m_specularOcclusionMapUvIndex], MaterialSrg::m_specularOcclusionFactor, o_specularOcclusion_useTexture); - // ------- Emissive ------- float2 emissiveUv = IN.m_uv[MaterialSrg::m_emissiveMapUvIndex]; lightingData.emissiveLighting = GetEmissiveInput(MaterialSrg::m_emissiveMap, MaterialSrg::m_sampler, emissiveUv, MaterialSrg::m_emissiveIntensity, MaterialSrg::m_emissiveColor.rgb, o_emissiveEnabled, o_emissive_useTexture); + // ------- Occlusion ------- + + lightingData.diffuseAmbientOcclusion = GetOcclusionInput(MaterialSrg::m_diffuseOcclusionMap, MaterialSrg::m_sampler, IN.m_uv[MaterialSrg::m_diffuseOcclusionMapUvIndex], MaterialSrg::m_diffuseOcclusionFactor, o_diffuseOcclusion_useTexture); + lightingData.specularOcclusion = GetOcclusionInput(MaterialSrg::m_specularOcclusionMap, MaterialSrg::m_sampler, IN.m_uv[MaterialSrg::m_specularOcclusionMapUvIndex], MaterialSrg::m_specularOcclusionFactor, o_specularOcclusion_useTexture); + // ------- Clearcoat ------- // [GFX TODO][ATOM-14603]: Clean up the double uses of these clear coat flags diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index 038e65a89f..5cc7c933b9 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -601,7 +601,7 @@ "displayName": "Opacity Mode", "description": "Opacity mode for this texture.", "type": "Enum", - "enumValues": [ "Opaque", "Cutout", "Blended" ], + "enumValues": [ "Opaque", "Cutout", "Blended", "TintedTransparent" ], "defaultValue": "Opaque", "connection": { "type": "ShaderOption", @@ -1387,15 +1387,6 @@ "file": "StandardPBR_HandleOpacityDoubleSided.lua" } }, - { - "type": "OverrideDrawList", - "args": { - "triggerProperty": "opacity.mode", - "triggerValue": "Blended", - "shaderIndex": 1, - "drawList": "transparent" - } - }, { "type": "Lua", "args": { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl index 2667c8123b..10fa3814f3 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -294,6 +294,24 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float lightingOutput.m_diffuseColor.rgb *= lightingOutput.m_diffuseColor.w; // pre-multiply diffuse lightingOutput.m_diffuseColor.rgb += lightingOutput.m_specularColor.rgb; // add specular } + else if (o_opacity_mode == OpacityMode::TintedTransparent) + { + // See OpacityMode::Blended above for the basic method. TintedTransparent adds onto the above concept by supporting + // colored alpha. This is currently a very basic calculation that uses the baseColor as a multiplier with strength + // determined by the alpha. We'll modify this later to be more physically accurate and allow surface depth, + // absorption, and interior color to be specified. + // + // The technique uses dual source blending to allow two separate sources to be part of the blending equation + // even though ultimately only a single render target is being written to. m_diffuseColor is render target 0 and + // m_specularColor render target 1, and the blend mode is (dest * source1color) + (source * 1.0). + // + // This means that m_specularColor.rgb (source 1) is multiplied against the destination, then + // m_diffuseColor.rgb (source) is added to that, and the final result is stored in render target 0. + + lightingOutput.m_diffuseColor.rgb *= lightingOutput.m_diffuseColor.w; // pre-multiply diffuse + lightingOutput.m_diffuseColor.rgb += lightingOutput.m_specularColor.rgb; // add specular + lightingOutput.m_specularColor.rgb = baseColor * (1.0 - lightingOutput.m_diffuseColor.w); + } else { // Pack factor and quality, drawback: because of precision limit of float16 cannot represent exact 1, maximum representable value is 0.9961 diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_HandleOpacityMode.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_HandleOpacityMode.lua index 541b1ac1ce..20d3ee47ae 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_HandleOpacityMode.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_HandleOpacityMode.lua @@ -60,10 +60,13 @@ function Process(context) if(opacityMode == OpacityMode_Blended) then ConfigureAlphaBlending(context:GetShader(ForwardPassIndex)) + context:GetShader(ForwardPassIndex):SetDrawListTagOverride("transparent") elseif(opacityMode == OpacityMode_TintedTransparent) then ConfigureDualSourceBlending(context:GetShader(ForwardPassIndex)) + context:GetShader(ForwardPassIndex):SetDrawListTagOverride("transparent") else ResetAlphaBlending(context:GetShader(ForwardPassIndex)) + context:GetShader(ForwardPassIndex):SetDrawListTagOverride("") -- reset to default draw list end end diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/009_Opacity_TintedTransparent.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/009_Opacity_TintedTransparent.material new file mode 100644 index 0000000000..1716792af1 --- /dev/null +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/009_Opacity_TintedTransparent.material @@ -0,0 +1,23 @@ +{ + "description": "", + "materialType": "Materials/Types/StandardPBR.materialtype", + "parentMaterial": "", + "propertyLayoutVersion": 3, + "properties": { + "baseColor": { + "color": [ + 0.5906767249107361, + 1.0, + 0.11703670024871826, + 1.0 + ], + "textureMap": "Textures/Default/default_basecolor.tif" + }, + "opacity": { + "alphaSource": "Split", + "factor": 0.75, + "mode": "TintedTransparent", + "textureMap": "TestData/Textures/checker8x8_gray_512.png" + } + } +} \ No newline at end of file From 5b8e759c2d29e2d75e343d79d8134f6d8c3e8c4b Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Wed, 26 May 2021 23:59:49 -0500 Subject: [PATCH 206/811] Implemented changes in the ly_setup_target() command to forward the ly_create_alias() command calls to the configured CMakeLists.txt per installed target --- cmake/Gems.cmake | 15 +++++++++++++-- cmake/Platform/Common/Install_common.cmake | 19 +++++++++++++++++++ cmake/cmake_files.cmake | 1 + cmake/install/TargetCMakeLists.txt.in | 1 + 4 files changed, 34 insertions(+), 2 deletions(-) diff --git a/cmake/Gems.cmake b/cmake/Gems.cmake index caa5b74c93..a90cf09639 100644 --- a/cmake/Gems.cmake +++ b/cmake/Gems.cmake @@ -47,6 +47,10 @@ function(ly_create_alias) if (NOT TARGET ${ly_create_alias_NAME}) add_library(${ly_create_alias_NAME} ALIAS ${de_aliased_target_name}) endif() + # Store off the arguments needed used ly_create_alias into a DIRECTORY property + # This will be used to re-create the calls in the generated CMakeLists.txt in the INSTALL step + string(REPLACE ";" " " create_alias_args "${ly_create_alias_NAME},${ly_create_alias_NAMESPACE},${ly_create_alias_TARGETS}") + set_property(DIRECTORY APPEND PROPERTY LY_CREATE_ALIAS_ARGUMENTS "${ly_create_alias_NAME},${ly_create_alias_NAMESPACE},${ly_create_alias_TARGETS}") return() endif() @@ -75,6 +79,13 @@ function(ly_create_alias) # now add the final alias: add_library(${ly_create_alias_NAMESPACE}::${ly_create_alias_NAME} ALIAS ${ly_create_alias_NAME}) + + # Store off the arguments needed used ly_create_alias into a DIRECTORY property + # This will be used to re-create the calls in the generated CMakeLists.txt in the INSTALL step + + # Replace the CMake list separator with a space to replicate the space separated TARGETS arguments + string(REPLACE ";" " " create_alias_args "${ly_create_alias_NAME},${ly_create_alias_NAMESPACE},${ly_create_alias_TARGETS}") + set_property(DIRECTORY APPEND PROPERTY LY_CREATE_ALIAS_ARGUMENTS "${create_alias_args}") endfunction() # ly_enable_gems @@ -143,7 +154,7 @@ endfunction() function(ly_enable_gems_delayed) get_property(ly_delayed_enable_gems GLOBAL PROPERTY LY_DELAYED_ENABLE_GEMS) foreach(project_target_variant ${ly_delayed_enable_gems}) - # we expect a colon seperated list of + # we expect a colon separated list of # PROJECT_NAME,target_name,variant_name string(REPLACE "," ";" project_target_variant_list "${project_target_variant}") list(LENGTH project_target_variant_list project_target_variant_length) @@ -152,7 +163,7 @@ function(ly_enable_gems_delayed) endif() if(NOT project_target_variant_length EQUAL 3) - message(FATAL_ERROR "Invalid specificaiton of gems, expected 'project','target','variant' and got ${project_target_variant}") + message(FATAL_ERROR "Invalid specification of gems, expected 'project','target','variant' and got ${project_target_variant}") endif() list(POP_BACK project_target_variant_list variant) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 04f0a0ff23..27b8d83a9c 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -155,6 +155,25 @@ function(ly_setup_target ALIAS_TARGET_NAME) list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}") + # Replicate the ly_create_alias() calls based on the SOURCE_DIR for each target that generates an installed CMakeLists.txt + string(JOIN "\n" create_alias_template + "if(NOT TARGET @ALIAS_NAME@)" + " ly_create_alias(NAME @ALIAS_NAME@ NAMESPACE @ALIAS_NAMESPACE@ TARGETS @ALIAS_TARGETS@)" + "endif()" + "" + ) + get_property(create_alias_commands_arg_list DIRECTORY ${absolute_target_source_dir} PROPERTY LY_CREATE_ALIAS_ARGUMENTS) + foreach(create_alias_single_command_arg_list ${create_alias_commands_arg_list}) + # Split the ly_create_alias arguments back out based on commas + string(REPLACE "," ";" create_alias_single_command_arg_list "${create_alias_single_command_arg_list}") + list(POP_FRONT create_alias_single_command_arg_list ALIAS_NAME) + list(POP_FRONT create_alias_single_command_arg_list ALIAS_NAMESPACE) + # The rest of the list are the target dependencies + set(ALIAS_TARGETS ${create_alias_single_command_arg_list}) + string(CONFIGURE "${create_alias_template}" create_alias_command @ONLY) + string(APPEND CREATE_ALIASES_PLACEHOLDER ${create_alias_command}) + endforeach() + # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target configure_file(${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/CMakeLists.txt @ONLY) diff --git a/cmake/cmake_files.cmake b/cmake/cmake_files.cmake index b42d29c9c2..a1fd66a06d 100644 --- a/cmake/cmake_files.cmake +++ b/cmake/cmake_files.cmake @@ -20,6 +20,7 @@ set(FILES EngineJson.cmake FileUtil.cmake Findo3de.cmake + Gems.cmake GeneralSettings.cmake Install.cmake LyAutoGen.cmake diff --git a/cmake/install/TargetCMakeLists.txt.in b/cmake/install/TargetCMakeLists.txt.in index b2c8b9b6f6..06cd022898 100644 --- a/cmake/install/TargetCMakeLists.txt.in +++ b/cmake/install/TargetCMakeLists.txt.in @@ -27,6 +27,7 @@ ly_add_target( @RUNTIME_DEPENDENCIES_PLACEHOLDER@ ) +@CREATE_ALIASES_PLACEHOLDER@ set(configs @CMAKE_CONFIGURATION_TYPES@) foreach(config ${configs}) include("@NAME_PLACEHOLDER@_${config}.cmake" OPTIONAL) From 301bfe34861c0837defdccdc4d04b5b6f741ead2 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 26 May 2021 22:03:46 -0700 Subject: [PATCH 207/811] [cpack_installer] replaced raw file(DOWNLOAD ...) for download_file() utility --- cmake/Packaging.cmake | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index 7766d7d0ee..84bad13687 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -65,19 +65,32 @@ list(GET _version_componets 0 _major_version) list(GET _version_componets 1 _minor_version) set(_url_version_tag "v${_major_version}.${_minor_version}") +set(_package_url "https://cmake.org/files/${_url_version_tag}/${CPACK_CMAKE_PACKAGE_FILE}") -message(STATUS "Ensuring CMake ${CPACK_DESIRED_CMAKE_VERSION} is avaiable for packaging...") -file(DOWNLOAD - https://cmake.org/files/${_url_version_tag}/${CPACK_CMAKE_PACKAGE_FILE} - ${_cmake_package_dest} +message(STATUS "Ensuring CMake ${CPACK_DESIRED_CMAKE_VERSION} is available for packaging...") +download_file( + URL ${_package_url} + TARGET_FILE ${_cmake_package_dest} + EXPECTED_HASH ${CPACK_CMAKE_PACKAGE_HASH} + RESULTS _results ) +list(GET _results 0 _status_code) -file(SHA256 ${_cmake_package_dest} _package_hash) -if (NOT "${_package_hash}" STREQUAL "${CPACK_CMAKE_PACKAGE_HASH}") +if (${_status_code} EQUAL 0 AND EXISTS ${_cmake_package_dest}) + message(STATUS "-> Package found and verified!") +else() file(REMOVE ${_cmake_package_dest}) - message(FATAL_ERROR "Donwload package of CMake does not match expected hash value. " - "Please double check the properies CPACK_CMAKE_PACKAGE_FILE and CPACK_CMAKE_PACKAGE_HASH " - "before trying again.") + list(REMOVE_AT _results 0) + + set(_error_message "An error occurred, code ${_status_code}. URL ${_package_url} - ${_results}") + + if(${_status_code} EQUAL 1) + string(APPEND _error_message + " Please double check the CPACK_CMAKE_PACKAGE_FILE and " + "CPACK_CMAKE_PACKAGE_HASH properties before trying again.") + endif() + + message(FATAL_ERROR ${_error_message}) endif() install(FILES ${_cmake_package_dest} From cb2772a7484822f9126962df0900ea40cea46a04 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 01:51:09 -0500 Subject: [PATCH 208/811] Updating the Install_common.cmake ly_setup_o3de_install() function to be able forward all the ly_add_targets calls within a single source Engine CMakeLists.txt to a single installed Engine CMakeLists.txt --- cmake/LYWrappers.cmake | 9 + cmake/Platform/Common/Install_common.cmake | 367 +++++++++++---------- cmake/install/Copyright.in | 10 + cmake/install/TargetCMakeLists.txt.in | 11 - 4 files changed, 210 insertions(+), 187 deletions(-) create mode 100644 cmake/install/Copyright.in diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index af6aefdac0..a75a121ccd 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -308,6 +308,15 @@ function(ly_add_target) # Store the target so we can walk through all of them in LocationDependencies.cmake set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGETS ${interface_name}) + # Store the aliased target into a DIRECTORY property + set_property(DIRECTORY APPEND PROPERTY LY_DIRECTORY_TARGETS ${interface_name}) + # Store the directory path in a GLOBAL property so that it can be accessed + # in the layout install logic. Skip if the directory has already been added + get_property(ly_all_target_directories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) + if(NOT CMAKE_CURRENT_SOURCE_DIR IN_LIST ly_all_target_directories) + set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGET_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}) + endif() + set(runtime_dependencies_list SHARED MODULE EXECUTABLE APPLICATION) if(NOT ly_add_target_IMPORTED AND linking_options IN_LIST runtime_dependencies_list) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 27b8d83a9c..aa9e710a0e 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -17,143 +17,190 @@ file(RELATIVE_PATH runtime_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_RUNTIME_ file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) set(install_output_folder "${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$") -#! ly_setup_targets: setups all targets -function(ly_setup_targets) - get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) - foreach(target IN LISTS all_targets) - ly_setup_target(${target}) + +#! ly_setup_subdirectories: setups all targets on a per directory basis +function(ly_setup_subdirectories) + get_property(all_subdirectories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) + foreach(target IN LISTS all_subdirectories) + ly_setup_subdirectory(${target}) endforeach() endfunction() -#! ly_setup_target: setups the target to be installed by cmake install. -function(ly_setup_target ALIAS_TARGET_NAME) - unset(TARGET_NAME) - ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) - - get_target_property(absolute_target_source_dir ${TARGET_NAME} SOURCE_DIR) +#! ly_setup_subdirectory: setup all targets in the subdirectory +function(ly_setup_subdirectory absolute_target_source_dir) + + file(READ ${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in target_cmakelists_template) + # The builtin BUILDSYSTEM_TARGETS property isn't being used here as that returns the de-alised + # TARGET and we need the alias namespace for recreating the CMakeLists.txt in the install layout + get_property(ALIAS_TARGETS_NAME DIRECTORY ${absolute_target_source_dir} PROPERTY LY_DIRECTORY_TARGETS) file(RELATIVE_PATH target_source_dir ${LY_ROOT_FOLDER} ${absolute_target_source_dir}) + foreach(ALIAS_TARGET_NAME IN LISTS ALIAS_TARGETS_NAME) + unset(TARGET_NAME) + ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) - # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that - # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the - # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. - # Instead, we install them with install(DIRECTORY) - set(include_location "include") - get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) - if (include_directories) - unset(public_headers) - foreach(include_directory ${include_directories}) - string(GENEX_STRIP ${include_directory} include_genex_expr) - if(include_genex_expr STREQUAL include_directory) # only for cases where there are no generation expressions - unset(current_public_headers) - install(DIRECTORY ${include_directory} - DESTINATION ${include_location}/${target_source_dir} - COMPONENT ${ly_install_target_COMPONENT} - FILES_MATCHING - PATTERN *.h - PATTERN *.hpp - PATTERN *.inl - ) - endif() - endforeach() - endif() - - # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target - file(RELATIVE_PATH archive_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) - - get_target_property(target_runtime_output_directory ${TARGET_NAME} RUNTIME_OUTPUT_DIRECTORY) - if(target_runtime_output_directory) - file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) - endif() - - get_target_property(target_library_output_directory ${TARGET_NAME} LIBRARY_OUTPUT_DIRECTORY) - if(target_library_output_directory) - file(RELATIVE_PATH target_library_output_subdirectory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${target_library_output_directory}) - endif() - - install( - TARGETS ${TARGET_NAME} - ARCHIVE - DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ - COMPONENT ${ly_install_target_COMPONENT} - LIBRARY - DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} - COMPONENT ${ly_install_target_COMPONENT} - RUNTIME - DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} - COMPONENT ${ly_install_target_COMPONENT} - ) - - # CMakeLists.txt file - string(REGEX MATCH "(.*)::(.*)$" match ${ALIAS_TARGET_NAME}) - if(match) - set(NAMESPACE_PLACEHOLDER "NAMESPACE ${CMAKE_MATCH_1}") - set(NAME_PLACEHOLDER ${CMAKE_MATCH_2}) - else() - set(NAMESPACE_PLACEHOLDER "") - set(NAME_PLACEHOLDER ${TARGET_NAME}) - endif() - - set(TARGET_TYPE_PLACEHOLDER "") - get_target_property(target_type ${NAME_PLACEHOLDER} TYPE) - # Remove the _LIBRARY since we dont need to pass that to ly_add_targets - string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type}) - # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead - string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER}) - if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE") - get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE) - if(gem_module) - set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE") + # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that + # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the + # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. + # Instead, we install them with install(DIRECTORY) + set(include_location "include") + get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) + if (include_directories) + unset(public_headers) + foreach(include_directory ${include_directories}) + string(GENEX_STRIP ${include_directory} include_genex_expr) + if(include_genex_expr STREQUAL include_directory) # only for cases where there are no generation expressions + unset(current_public_headers) + install(DIRECTORY ${include_directory} + DESTINATION ${include_location}/${target_source_dir} + COMPONENT ${ly_install_target_COMPONENT} + FILES_MATCHING + PATTERN *.h + PATTERN *.hpp + PATTERN *.inl + ) + endif() + endforeach() endif() - endif() - get_target_property(COMPILE_DEFINITIONS_PLACEHOLDER ${TARGET_NAME} INTERFACE_COMPILE_DEFINITIONS) - if(COMPILE_DEFINITIONS_PLACEHOLDER) - string(REPLACE ";" "\n" COMPILE_DEFINITIONS_PLACEHOLDER "${COMPILE_DEFINITIONS_PLACEHOLDER}") - else() - unset(COMPILE_DEFINITIONS_PLACEHOLDER) - endif() + # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target + file(RELATIVE_PATH archive_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) - # Includes need additional processing to add the install root - if(include_directories) - foreach(include ${include_directories}) - string(GENEX_STRIP ${include} include_genex_expr) - if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions - file(RELATIVE_PATH relative_include ${absolute_target_source_dir} ${include}) - string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}/${relative_include}\n") + get_target_property(target_runtime_output_directory ${TARGET_NAME} RUNTIME_OUTPUT_DIRECTORY) + if(target_runtime_output_directory) + file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) + endif() + + get_target_property(target_library_output_directory ${TARGET_NAME} LIBRARY_OUTPUT_DIRECTORY) + if(target_library_output_directory) + file(RELATIVE_PATH target_library_output_subdirectory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${target_library_output_directory}) + endif() + + install( + TARGETS ${TARGET_NAME} + ARCHIVE + DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ + COMPONENT ${ly_install_target_COMPONENT} + LIBRARY + DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} + COMPONENT ${ly_install_target_COMPONENT} + RUNTIME + DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} + COMPONENT ${ly_install_target_COMPONENT} + ) + + # CMakeLists.txt file + string(REGEX MATCH "(.*)::(.*)$" match ${ALIAS_TARGET_NAME}) + if(match) + set(NAMESPACE_PLACEHOLDER "NAMESPACE ${CMAKE_MATCH_1}") + set(NAME_PLACEHOLDER ${CMAKE_MATCH_2}) + else() + set(NAMESPACE_PLACEHOLDER "") + set(NAME_PLACEHOLDER ${TARGET_NAME}) + endif() + + set(TARGET_TYPE_PLACEHOLDER "") + get_target_property(target_type ${NAME_PLACEHOLDER} TYPE) + # Remove the _LIBRARY since we dont need to pass that to ly_add_targets + string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type}) + # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead + string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER}) + if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE") + get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE) + if(gem_module) + set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE") endif() - endforeach() - endif() + endif() - get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) - if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found - string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") - else() - unset(RUNTIME_DEPENDENCIES_PLACEHOLDER) - endif() + get_target_property(COMPILE_DEFINITIONS_PLACEHOLDER ${TARGET_NAME} INTERFACE_COMPILE_DEFINITIONS) + if(COMPILE_DEFINITIONS_PLACEHOLDER) + string(REPLACE ";" "\n" COMPILE_DEFINITIONS_PLACEHOLDER "${COMPILE_DEFINITIONS_PLACEHOLDER}") + else() + unset(COMPILE_DEFINITIONS_PLACEHOLDER) + endif() - get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES) - unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) - if(inteface_build_dependencies_props) - foreach(build_dependency ${inteface_build_dependencies_props}) - # Skip wrapping produced when targets are not created in the same directory - if(NOT ${build_dependency} MATCHES "^::@") - list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + # Includes need additional processing to add the install root + if(include_directories) + foreach(include ${include_directories}) + string(GENEX_STRIP ${include} include_genex_expr) + if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions + file(RELATIVE_PATH relative_include ${absolute_target_source_dir} ${include}) + string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}/${relative_include}\n") + endif() + endforeach() + endif() + + get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) + if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found + string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") + else() + unset(RUNTIME_DEPENDENCIES_PLACEHOLDER) + endif() + + get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES) + unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) + if(inteface_build_dependencies_props) + foreach(build_dependency ${inteface_build_dependencies_props}) + # Skip wrapping produced when targets are not created in the same directory + if(NOT ${build_dependency} MATCHES "^::@") + list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + endif() + endforeach() + endif() + # We also need to pass the private link libraries since we will use that to generate the runtime dependencies + get_target_property(private_build_dependencies_props ${TARGET_NAME} LINK_LIBRARIES) + if(private_build_dependencies_props) + foreach(build_dependency ${private_build_dependencies_props}) + # Skip wrapping produced when targets are not created in the same directory + if(NOT ${build_dependency} MATCHES "^::@") + list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + endif() + endforeach() + endif() + list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) + string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}") + + # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target + string(CONFIGURE ${target_cmakelists_template} configured_target @ONLY) + string(APPEND all_configured_targets "${configured_target}") + + # Config file + set(target_file_contents "# Generated by O3DE install\n\n") + if(NOT target_type STREQUAL INTERFACE_LIBRARY) + + unset(target_location) + set(runtime_types EXECUTABLE APPLICATION) + if(target_type IN_LIST runtime_types) + set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$") + elseif(target_type STREQUAL MODULE_LIBRARY) + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") + elseif(target_type STREQUAL SHARED_LIBRARY) + string(APPEND target_file_contents "set_property(TARGET ${TARGET_NAME} PROPERTY IMPORTED_IMPLIB_$ \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\")\n") + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") + else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY + set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") endif() - endforeach() - endif() - # We also need to pass the private link libraries since we will use that to generate the runtime dependencies - get_target_property(private_build_dependencies_props ${TARGET_NAME} LINK_LIBRARIES) - if(private_build_dependencies_props) - foreach(build_dependency ${private_build_dependencies_props}) - # Skip wrapping produced when targets are not created in the same directory - if(NOT ${build_dependency} MATCHES "^::@") - list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + + if(target_location) + string(APPEND target_file_contents + "set_property(TARGET ${TARGET_NAME} + APPEND_STRING PROPERTY IMPORTED_LOCATION + $<$$:${target_location}$ + ) + set_property(TARGET ${TARGET_NAME} + PROPERTY IMPORTED_LOCATION_$> + ${target_location} + ) + ") endif() - endforeach() - endif() - list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) - string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}") + endif() + + file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" + DESTINATION ${target_source_dir} + COMPONENT ${ly_install_target_COMPONENT} + ) + endforeach() # Replicate the ly_create_alias() calls based on the SOURCE_DIR for each target that generates an installed CMakeLists.txt string(JOIN "\n" create_alias_template @@ -174,48 +221,16 @@ function(ly_setup_target ALIAS_TARGET_NAME) string(APPEND CREATE_ALIASES_PLACEHOLDER ${create_alias_command}) endforeach() - # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target - configure_file(${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/CMakeLists.txt @ONLY) - - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/CMakeLists.txt" - DESTINATION ${target_source_dir}/${NAME_PLACEHOLDER} - COMPONENT ${ly_install_target_COMPONENT} + file(READ ${LY_ROOT_FOLDER}/cmake/install/Copyright.in cmake_copyright_comment) + # Write out all the agreegated ly_add_target function calls and the final ly_create_alias() calls to the target CMakeList.txt + file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/CMakeLists.txt + "${cmake_copyright_comment}" + "${all_configured_targets}" + "\n" + "${CREATE_ALIASES_PLACEHOLDER}" ) - - # Config file - set(target_file_contents "# Generated by O3DE install\n\n") - if(NOT target_type STREQUAL INTERFACE_LIBRARY) - - unset(target_location) - set(runtime_types EXECUTABLE APPLICATION) - if(target_type IN_LIST runtime_types) - set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$") - elseif(target_type STREQUAL MODULE_LIBRARY) - set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") - elseif(target_type STREQUAL SHARED_LIBRARY) - string(APPEND target_file_contents "set_property(TARGET ${TARGET_NAME} PROPERTY IMPORTED_IMPLIB_$ \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\")\n") - set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") - else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY - set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") - endif() - - if(target_location) - string(APPEND target_file_contents -"set_property(TARGET ${TARGET_NAME} - APPEND_STRING PROPERTY IMPORTED_LOCATION - $<$$:${target_location}$ -) -set_property(TARGET ${TARGET_NAME} - PROPERTY IMPORTED_LOCATION_$> - ${target_location} -) -") - endif() - endif() - - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/${NAME_PLACEHOLDER}_$.cmake" - DESTINATION ${target_source_dir}/${NAME_PLACEHOLDER} + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/CMakeLists.txt" + DESTINATION ${target_source_dir} COMPONENT ${ly_install_target_COMPONENT} ) @@ -224,7 +239,7 @@ endfunction() #! ly_setup_o3de_install: orchestrates the installation of the different parts. This is the entry point from the root CMakeLists.txt function(ly_setup_o3de_install) - ly_setup_targets() + ly_setup_subdirectories() ly_setup_cmake_install() ly_setup_target_generator() ly_setup_runtime_dependencies() @@ -283,12 +298,12 @@ function(ly_setup_cmake_install) # Findo3de.cmake file: we generate a different Findo3de.camke file than the one we have in cmake. This one is going to expose all # targets that are pre-built - get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) unset(FIND_PACKAGES_PLACEHOLDER) - foreach(alias_target IN LISTS all_targets) - ly_de_alias_target(${alias_target} target) - get_target_property(target_source_dir ${target} SOURCE_DIR) - file(RELATIVE_PATH target_source_dir_relative ${LY_ROOT_FOLDER} ${target_source_dir}) + + # Add to the FIND_PACKAGES_PLACEHOLDER all directories in which ly_add_target were called in + get_property(all_subdirectories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) + foreach(target_subdirectory IN LISTS all_subdirectories) + file(RELATIVE_PATH target_source_dir_relative ${LY_ROOT_FOLDER} ${target_subdirectory}) string(APPEND FIND_PACKAGES_PLACEHOLDER " add_subdirectory(${target_source_dir_relative}/${target})\n") endforeach() @@ -339,7 +354,7 @@ function(ly_copy source_file target_directory) endfunction()" COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) - + unset(runtime_commands) get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) foreach(alias_target IN LISTS all_targets) @@ -350,12 +365,12 @@ endfunction()" if(NOT target_type IN_LIST LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS) continue() endif() - + get_target_property(target_runtime_output_directory ${target} RUNTIME_OUTPUT_DIRECTORY) if(target_runtime_output_directory) file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) endif() - + # Qt get_property(has_qt_dependency GLOBAL PROPERTY LY_DETECT_QT_DEPENDENCY_${target}) if(has_qt_dependency) @@ -374,7 +389,7 @@ endfunction()" foreach(runtime_dependency ${runtime_dependencies}) unset(runtime_command) ly_get_runtime_dependency_command(runtime_command ${runtime_dependency}) - string(CONFIGURE "${runtime_command}" runtime_command @ONLY) + string(CONFIGURE "${runtime_command}" runtime_command @ONLY) list(APPEND runtime_commands ${runtime_command}) endforeach() @@ -382,10 +397,10 @@ endfunction()" list(REMOVE_DUPLICATES runtime_commands) list(JOIN runtime_commands " " runtime_commands_str) # the spaces are just to see the right identation in the cmake_install.cmake file - install(CODE "${runtime_commands_str}" + install(CODE "${runtime_commands_str}" COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) - + endfunction() #! ly_setup_others: install directories required by the engine diff --git a/cmake/install/Copyright.in b/cmake/install/Copyright.in new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/cmake/install/Copyright.in @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/cmake/install/TargetCMakeLists.txt.in b/cmake/install/TargetCMakeLists.txt.in index 06cd022898..0503fd5f2b 100644 --- a/cmake/install/TargetCMakeLists.txt.in +++ b/cmake/install/TargetCMakeLists.txt.in @@ -1,13 +1,3 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# # Generated by O3DE @@ -27,7 +17,6 @@ ly_add_target( @RUNTIME_DEPENDENCIES_PLACEHOLDER@ ) -@CREATE_ALIASES_PLACEHOLDER@ set(configs @CMAKE_CONFIGURATION_TYPES@) foreach(config ${configs}) include("@NAME_PLACEHOLDER@_${config}.cmake" OPTIONAL) From 4205a69106b0be35341410c18e67b5b6f3e23bc9 Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Thu, 27 May 2021 09:34:52 +0100 Subject: [PATCH 209/811] Allow ComponentAdapter (and related types) to work with EntityComponentIdPairs as well as EntityIds (#920) * provide the ability for component adapters to support multiple components per entity * add missing explicit keywords * updates following review feedback - update how template logic works * small updats (fix typo, remove redundant includes) * add missing this-> * naming change, common -> controller * add [[maybe_unused]] --- .../AzFramework/Components/ComponentAdapter.h | 29 ++++---- .../Components/ComponentAdapter.inl | 27 ++++---- .../Components/ComponentAdapterHelpers.h | 34 +++++++-- .../ToolsComponents/EditorComponentAdapter.h | 39 +++++------ .../EditorComponentAdapter.inl | 69 +++++++++++-------- .../Utils/EditorRenderComponentAdapter.h | 30 ++++---- .../Utils/EditorRenderComponentAdapter.inl | 56 +++++++-------- 7 files changed, 159 insertions(+), 125 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapter.h b/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapter.h index 682e886061..ee8b79bf06 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapter.h +++ b/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapter.h @@ -1,22 +1,22 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once #include #include -#include #include #include +#include namespace AzFramework { @@ -64,15 +64,13 @@ namespace AzFramework the EditContext. TController can friend itself to the editor component to make this work if required. */ template - class ComponentAdapter - : public AZ::Component + class ComponentAdapter : public AZ::Component { public: - AZ_RTTI((ComponentAdapter, "{644A9187-4FDB-42C1-9D59-DD75304B551A}", TController, TConfiguration), AZ::Component); ComponentAdapter() = default; - ComponentAdapter(const TConfiguration& configuration); + explicit ComponentAdapter(const TConfiguration& configuration); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services); static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services); @@ -85,7 +83,6 @@ namespace AzFramework void Deactivate() override; protected: - static void Reflect(AZ::ReflectContext* context); // AZ::Component overrides ... diff --git a/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapter.inl b/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapter.inl index a1b0826193..5c36ff0bf7 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapter.inl +++ b/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapter.inl @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include @@ -32,10 +32,12 @@ namespace AzFramework if (auto serializeContext = azrtti_cast(context)) { + // clang-format off serializeContext->Class() ->Version(1) ->Field("Controller", &ComponentAdapter::m_controller) ; + // clang-format on } } @@ -66,9 +68,6 @@ namespace AzFramework GetDependentServicesHelper(services, typename AZ::HasComponentDependentServices::type()); } - ////////////////////////////////////////////////////////////////////////// - // AZ::Component interface implementation - template void ComponentAdapter::Init() { @@ -78,7 +77,7 @@ namespace AzFramework template void ComponentAdapter::Activate() { - m_controller.Activate(GetEntityId()); + ComponentActivateHelper::Activate(m_controller, AZ::EntityComponentIdPair(GetEntityId(), GetId())); } template diff --git a/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapterHelpers.h b/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapterHelpers.h index 158ee95f39..f0ef262a71 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapterHelpers.h +++ b/Code/Framework/AzFramework/AzFramework/Components/ComponentAdapterHelpers.h @@ -13,6 +13,7 @@ #pragma once #include +#include namespace AzFramework { @@ -27,18 +28,43 @@ namespace AzFramework template struct ComponentInitHelper { - static void Init(T& common) + static void Init([[maybe_unused]] T& controller) { - AZ_UNUSED(common); } }; template struct ComponentInitHelper().Init())>> { - static void Init(T& common) + static void Init(T& controller) { - common.Init(); + controller.Init(); + } + }; + + template + struct ComponentActivateHelper + { + static void Activate([[maybe_unused]] T& controller, [[maybe_unused]] const AZ::EntityComponentIdPair& entityComponentIdPair) + { + } + }; + + template + struct ComponentActivateHelper().Activate(AZ::EntityId()))>> + { + static void Activate(T& controller, const AZ::EntityComponentIdPair& entityComponentIdPair) + { + controller.Activate(entityComponentIdPair.GetEntityId()); + } + }; + + template + struct ComponentActivateHelper().Activate(AZ::EntityComponentIdPair()))>> + { + static void Activate(T& controller, const AZ::EntityComponentIdPair& entityComponentIdPair) + { + controller.Activate(entityComponentIdPair); } }; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorComponentAdapter.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorComponentAdapter.h index 6950717499..0ca5853adc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorComponentAdapter.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorComponentAdapter.h @@ -1,22 +1,22 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once -#include -#include -#include #include #include +#include +#include +#include namespace AzToolsFramework { @@ -31,7 +31,7 @@ namespace AzToolsFramework To use the EditorComponentAdapter, 3 classes are required: - a class that implements the functions required for TController (see below) - a configuration struct/class which extends AZ::ComponentConfig - - A runtime component that will be generated by the editor comoinent on export + - A runtime component that will be generated by the editor component on export The concrete component extends the adapter and implements behavior which is unique to the component. @@ -64,15 +64,15 @@ namespace AzToolsFramework the EditContext. TController can friend itself to the editor component to make this work if required. */ template - class EditorComponentAdapter - : public EditorComponentBase + class EditorComponentAdapter : public EditorComponentBase { public: - - AZ_RTTI((EditorComponentAdapter, "{2F5A3669-FFE9-4CD7-B9E2-7FC8100CF1A2}", TController, TRuntimeComponent, TConfiguration), EditorComponentBase); + AZ_RTTI( + (EditorComponentAdapter, "{2F5A3669-FFE9-4CD7-B9E2-7FC8100CF1A2}", TController, TRuntimeComponent, TConfiguration), + EditorComponentBase); EditorComponentAdapter() = default; - EditorComponentAdapter(const TConfiguration& configuration); + explicit EditorComponentAdapter(const TConfiguration& configuration); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services); static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services); @@ -86,7 +86,6 @@ namespace AzToolsFramework void BuildGameEntity(AZ::Entity* gameEntity) override; protected: - static void Reflect(AZ::ReflectContext* context); // AZ::Component overrides ... diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorComponentAdapter.inl b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorComponentAdapter.inl index 04619b079d..b8bd24589a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorComponentAdapter.inl +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorComponentAdapter.inl @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include @@ -28,23 +28,21 @@ namespace AzToolsFramework template void EditorComponentAdapter::Reflect(AZ::ReflectContext* context) { - if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + if (auto serializeContext = azrtti_cast(context)) { - serializeContext->Class() - ->Version(1) - ->Field("Controller", &EditorComponentAdapter::m_controller) - ; + serializeContext->Class()->Version(1)->Field( + "Controller", &EditorComponentAdapter::m_controller); if (AZ::EditContext* editContext = serializeContext->GetEditContext()) { - editContext->Class( - "EditorComponentAdapter", "") + // clang-format off + editContext->Class("EditorComponentAdapter", "") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorComponentAdapter::m_controller, "Controller", "") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorComponentAdapter::OnConfigurationChanged) - ; + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorComponentAdapter::OnConfigurationChanged); + // clang-format on } } } @@ -53,27 +51,35 @@ namespace AzToolsFramework // Get*Services functions template - void EditorComponentAdapter::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services) + void EditorComponentAdapter::GetProvidedServices( + AZ::ComponentDescriptor::DependencyArrayType& services) { - AzFramework::Components::GetProvidedServicesHelper(services, typename AZ::HasComponentProvidedServices::type()); + AzFramework::Components::GetProvidedServicesHelper( + services, typename AZ::HasComponentProvidedServices::type()); } template - void EditorComponentAdapter::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services) + void EditorComponentAdapter::GetRequiredServices( + AZ::ComponentDescriptor::DependencyArrayType& services) { - AzFramework::Components::GetRequiredServicesHelper(services, typename AZ::HasComponentRequiredServices::type()); + AzFramework::Components::GetRequiredServicesHelper( + services, typename AZ::HasComponentRequiredServices::type()); } template - void EditorComponentAdapter::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services) + void EditorComponentAdapter::GetIncompatibleServices( + AZ::ComponentDescriptor::DependencyArrayType& services) { - AzFramework::Components::GetIncompatibleServicesHelper(services, typename AZ::HasComponentIncompatibleServices::type()); + AzFramework::Components::GetIncompatibleServicesHelper( + services, typename AZ::HasComponentIncompatibleServices::type()); } template - void EditorComponentAdapter::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& services) + void EditorComponentAdapter::GetDependentServices( + AZ::ComponentDescriptor::DependencyArrayType& services) { - AzFramework::Components::GetDependentServicesHelper(services, typename AZ::HasComponentDependentServices::type()); + AzFramework::Components::GetDependentServicesHelper( + services, typename AZ::HasComponentDependentServices::type()); } ////////////////////////////////////////////////////////////////////////// @@ -99,7 +105,8 @@ namespace AzToolsFramework if (ShouldActivateController()) { - m_controller.Activate(GetEntityId()); + AzFramework::Components::ComponentActivateHelper::Activate( + m_controller, AZ::EntityComponentIdPair(GetEntityId(), GetId())); } } @@ -122,7 +129,8 @@ namespace AzToolsFramework } template - bool EditorComponentAdapter::WriteOutConfig(AZ::ComponentConfig* outBaseConfig) const + bool EditorComponentAdapter::WriteOutConfig( + AZ::ComponentConfig* outBaseConfig) const { if (auto config = azrtti_cast(outBaseConfig)) { @@ -139,7 +147,8 @@ namespace AzToolsFramework if (ShouldActivateController()) { - m_controller.Activate(GetEntityId()); + AzFramework::Components::ComponentActivateHelper::Activate( + m_controller, AZ::EntityComponentIdPair(GetEntityId(), GetId())); } return AZ::Edit::PropertyRefreshLevels::None; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/EditorRenderComponentAdapter.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/EditorRenderComponentAdapter.h index 101387205f..be761d8e7b 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/EditorRenderComponentAdapter.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/EditorRenderComponentAdapter.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -26,14 +26,15 @@ namespace AZ , public AzToolsFramework::EditorEntityVisibilityNotificationBus::Handler { public: - using BaseClass = AzToolsFramework::Components::EditorComponentAdapter; - AZ_RTTI((EditorRenderComponentAdapter, "{AAF38BE4-EA2F-408B-9C44-63C7FBAC6B33}", TController, TRuntimeComponent, TConfiguration), BaseClass); + AZ_RTTI( + (EditorRenderComponentAdapter, "{AAF38BE4-EA2F-408B-9C44-63C7FBAC6B33}", TController, TRuntimeComponent, TConfiguration), + BaseClass); static void Reflect(AZ::ReflectContext* context); EditorRenderComponentAdapter() = default; - EditorRenderComponentAdapter(const TConfiguration& config); + explicit EditorRenderComponentAdapter(const TConfiguration& config); // AzToolsFramework::Components::EditorComponentAdapter overrides void Activate() override; @@ -50,7 +51,8 @@ namespace AZ // Convert pre-existing EditorCompnentAdapter based serialized data to EditorRenderComponentAdapter template - static bool ConvertToEditorRenderComponentAdapter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement); + static bool ConvertToEditorRenderComponentAdapter( + AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement); }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/EditorRenderComponentAdapter.inl b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/EditorRenderComponentAdapter.inl index e3f7ccd44d..633ec0e0ca 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/EditorRenderComponentAdapter.inl +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/EditorRenderComponentAdapter.inl @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include #include @@ -19,11 +19,12 @@ namespace AZ { template template - bool EditorRenderComponentAdapter::ConvertToEditorRenderComponentAdapter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) + bool EditorRenderComponentAdapter::ConvertToEditorRenderComponentAdapter( + AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) { if (classElement.GetVersion() < TVersion) { - // Get the and remove the EditorComponentAdapter base class data that was previpously serialized + // Get the and remove the EditorComponentAdapter base class data that was previously serialized AzToolsFramework::Components::EditorComponentAdapter oldBaseClassData; if (!classElement.FindSubElementAndGetData(AZ_CRC("BaseClass1", 0xd4925735), oldBaseClassData)) @@ -41,8 +42,8 @@ namespace AZ // Replace the old base class data with EditorRenderComponentAdapter EditorRenderComponentAdapter newBaseClassData; - AZ::SerializeContext::DataElementNode& newBaseClassElement = classElement.GetSubElement( - classElement.AddElementWithData(context, "BaseClass1", newBaseClassData)); + AZ::SerializeContext::DataElementNode& newBaseClassElement = + classElement.GetSubElement(classElement.AddElementWithData(context, "BaseClass1", newBaseClassData)); // Overwrite EditorRenderComponentAdapter base class data with retrieved EditorComponentAdapter base class data if (!newBaseClassElement.RemoveElementByName(AZ_CRC("BaseClass1", 0xd4925735))) @@ -62,25 +63,24 @@ namespace AZ { BaseClass::Reflect(context); - if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + if (auto serializeContext = azrtti_cast(context)) { - serializeContext->Class() - ->Version(0) - ; + serializeContext->Class()->Version(0); if (AZ::EditContext* editContext = serializeContext->GetEditContext()) { - editContext->Class( - "EditorRenderComponentAdapter", "") + // clang-format off + editContext->Class("EditorRenderComponentAdapter", "") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ; + ->Attribute(AZ::Edit::Attributes::AutoExpand, true); + // clang-format on } } } template - EditorRenderComponentAdapter::EditorRenderComponentAdapter(const TConfiguration& config) + EditorRenderComponentAdapter::EditorRenderComponentAdapter( + const TConfiguration& config) : BaseClass(config) { } @@ -103,7 +103,8 @@ namespace AZ bool EditorRenderComponentAdapter::IsVisible() const { bool visible = true; - AzToolsFramework::EditorEntityInfoRequestBus::EventResult(visible, this->GetEntityId(), &AzToolsFramework::EditorEntityInfoRequestBus::Events::IsVisible); + AzToolsFramework::EditorEntityInfoRequestBus::EventResult( + visible, this->GetEntityId(), &AzToolsFramework::EditorEntityInfoRequestBus::Events::IsVisible); return visible; } @@ -114,15 +115,16 @@ namespace AZ } template - void EditorRenderComponentAdapter::OnEntityVisibilityChanged([[maybe_unused]] bool visibility) + void EditorRenderComponentAdapter::OnEntityVisibilityChanged( + [[maybe_unused]] bool visibility) { this->m_controller.Deactivate(); if (this->ShouldActivateController()) { - this->m_controller.Activate(this->GetEntityId()); + AzFramework::Components::ComponentActivateHelper::Activate( + this->m_controller, AZ::EntityComponentIdPair(this->GetEntityId(), this->GetId())); } } - } // namespace Render } // namespace AZ From 34c59a81b82671a2bb33ab212ec65779655f22fa Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 27 May 2021 10:51:36 +0100 Subject: [PATCH 210/811] update rigid body to use non-deprecated function and remove many deprecated transform bus functions --- .../AzCore/AzCore/Component/TransformBus.h | 70 +--------- .../Components/TransformComponent.cpp | 128 +----------------- .../Components/TransformComponent.h | 17 +-- .../SliceEditorEntityOwnershipService.cpp | 2 +- .../ToolsComponents/TransformComponent.cpp | 80 +---------- .../ToolsComponents/TransformComponent.h | 17 +-- Gems/Blast/Code/Tests/Mocks/BlastMocks.h | 14 +- Gems/PhysX/Code/Source/RigidBodyComponent.cpp | 4 +- 8 files changed, 10 insertions(+), 322 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Component/TransformBus.h b/Code/Framework/AzCore/AzCore/Component/TransformBus.h index be18593d54..b180e97332 100644 --- a/Code/Framework/AzCore/AzCore/Component/TransformBus.h +++ b/Code/Framework/AzCore/AzCore/Component/TransformBus.h @@ -172,78 +172,10 @@ namespace AZ //! Rotation modifiers //! @{ - //! @deprecated Use SetLocalRotation() - //! Sets the entity's rotation in the world. - //! The origin of the axes is the entity's position in world space. - //! @param eulerAnglesRadians A three-dimensional vector, containing Euler angles in radians, to rotate the entity by. - virtual void SetRotation([[maybe_unused]] const AZ::Vector3& eulerAnglesRadians) {} - - //! @deprecated Use SetLocalRotation() - //! Sets the entity's rotation around the world's X axis. - //! The origin of the axis is the entity's position in world space. - //! @param eulerAngleRadians The X coordinate Euler angle in radians to use for the entity's rotation. - virtual void SetRotationX([[maybe_unused]] float eulerAngleRadian) {} - - //! @deprecated Use SetLocalRotation() - //! Sets the entity's rotation around the world's Y axis. - //! The origin of the axis is the entity's position in world space. - //! @param eulerAngleRadians The Y coordinate Euler angle in radians to use for the entity's rotation. - virtual void SetRotationY([[maybe_unused]] float eulerAngleRadian) {} - - //! @deprecated Use SetLocalRotation() - //! Sets the entity's rotation around the world's Z axis. - //! The origin of the axis is the entity's position in world space. - //! @param eulerAngleRadians The Z coordinate Euler angle in radians to use for the entity's rotation. - virtual void SetRotationZ([[maybe_unused]] float eulerAngleRadian) {} - - //! @deprecated Use SetLocalRotationQuaternion() //! Sets the entity's rotation in the world in quaternion notation. //! The origin of the axes is the entity's position in world space. //! @param quaternion A quaternion that represents the rotation to use for the entity. - virtual void SetRotationQuaternion([[maybe_unused]] const AZ::Quaternion& quaternion) {} - - //! @deprecated Use RotateAroundLocalX() - //! Rotates the entity around the world's X axis. - //! The origin of the axis is the entity's position in world space. - //! @param eulerAngleRadians The Euler angle in radians by which to rotate the entity around the X axis. - virtual void RotateByX([[maybe_unused]] float eulerAngleRadian) {} - - //! @deprecated Use RotateAroundLocalY() - //! Rotates the entity around the world's Y axis. - //! The origin of the axis is the entity's position in world space. - //! @param eulerAngleRadians The Euler angle in radians by which to rotate the entity around the Y axis. - virtual void RotateByY([[maybe_unused]] float eulerAngleRadian) {} - - //! @deprecated Use RotateAroundLocalZ() - //! Rotates the entity around the world's Z axis. - //! The origin of the axis is the entity's position in world space. - //! @param eulerAngleRadians The Euler angle in radians by which to rotate the entity around the Z axis. - virtual void RotateByZ([[maybe_unused]] float eulerAngleRadian) {} - - //! @deprecated Use GetLocalRotation() - //! Gets the entity's rotation in the world in Euler angles rotation in radians. - //! @return A three-dimensional vector, containing Euler angles in radians, that represents the entity's rotation. - virtual AZ::Vector3 GetRotationEulerRadians() { return AZ::Vector3(FLT_MAX); } - - //! @deprecated Use GetLocalRotationQuaternion() - //! Gets the entity's rotation in the world in quaternion format. - //! @return A quaternion that represents the entity's rotation in world space. - virtual AZ::Quaternion GetRotationQuaternion() { return AZ::Quaternion::CreateZero(); } - - //! @deprecated Use GetLocalRotation() - //! Gets the entity's rotation around the world's X axis. - //! @return The Euler angle in radians by which the the entity is rotated around the X axis in world space. - virtual float GetRotationX() { return FLT_MAX; } - - //! @deprecated Use GetLocalRotation() - //! Gets the entity's rotation around the world's Y axis. - //! @return The Euler angle in radians by which the the entity is rotated around the Y axis in world space. - virtual float GetRotationY() { return FLT_MAX; } - - //! @deprecated Use GetLocalRotation() - //! Gets the entity's rotation around the world's Z axis. - //! @return The Euler angle in radians by which the the entity is rotated around the Z axis in world space. - virtual float GetRotationZ() { return FLT_MAX; } + virtual void SetWorldRotationQuaternion([[maybe_unused]] const AZ::Quaternion& quaternion) {} //! Get angles in radian for each principle axis around which the world transform is //! rotated in the order of z-axis and y-axis and then x-axis. diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp index 3dafc7c717..49adab2252 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp @@ -327,99 +327,13 @@ namespace AzFramework return localZ; } - void TransformComponent::SetRotation(const AZ::Vector3& eulerAnglesRadian) + void TransformComponent::SetWorldRotationQuaternion(const AZ::Quaternion& quaternion) { - AZ_Warning("TransformComponent", false, "SetRotation is deprecated, please use SetLocalRotation"); - - AZ::Transform newWorldTransform = m_worldTM; - newWorldTransform.SetRotation(AZ::ConvertEulerRadiansToQuaternion(eulerAnglesRadian)); - SetWorldTM(newWorldTransform); - } - - void TransformComponent::SetRotationQuaternion(const AZ::Quaternion& quaternion) - { - AZ_Warning("TransformComponent", false, "SetRotationQuaternion is deprecated, please use SetLocalRotationQuaternion"); - AZ::Transform newWorldTransform = m_worldTM; newWorldTransform.SetRotation(quaternion); SetWorldTM(newWorldTransform); } - void TransformComponent::SetRotationX(float eulerAngleRadian) - { - AZ_Warning("TransformComponent", false, "SetRotationX is deprecated, please use SetLocalRotation"); - - AZ::Transform newWorldTransform = m_worldTM; - newWorldTransform.SetRotation(AZ::Quaternion::CreateRotationX(eulerAngleRadian)); - SetWorldTM(newWorldTransform); - } - - void TransformComponent::SetRotationY(float eulerAngleRadian) - { - AZ_Warning("TransformComponent", false, "SetRotationY is deprecated, please use SetLocalRotation"); - - AZ::Transform newWorldTransform = m_worldTM; - newWorldTransform.SetRotation(AZ::Quaternion::CreateRotationY(eulerAngleRadian)); - SetWorldTM(newWorldTransform); - } - - void TransformComponent::SetRotationZ(float eulerAngleRadian) - { - AZ_Warning("TransformComponent", false, "SetRotationZ is deprecated, please use SetLocalRotation"); - - AZ::Transform newWorldTransform = m_worldTM; - newWorldTransform.SetRotation(AZ::Quaternion::CreateRotationZ(eulerAngleRadian)); - SetWorldTM(newWorldTransform); - } - - void TransformComponent::RotateByX(float eulerAngleRadian) - { - AZ_Warning("TransformComponent", false, "RotateByX is deprecated, please use RotateAroundLocalX"); - RotateAroundLocalX(eulerAngleRadian); - } - - void TransformComponent::RotateByY(float eulerAngleRadian) - { - AZ_Warning("TransformComponent", false, "RotateByY is deprecated, please use RotateAroundLocalY"); - RotateAroundLocalY(eulerAngleRadian); - } - - void TransformComponent::RotateByZ(float eulerAngleRadian) - { - AZ_Warning("TransformComponent", false, "RotateByZ is deprecated, please use RotateAroundLocalZ"); - RotateAroundLocalZ(eulerAngleRadian); - } - - AZ::Vector3 TransformComponent::GetRotationEulerRadians() - { - AZ_Warning("TransformComponent", false, "GetRotationEulerRadians is deprecated, please use GetWorldRotation"); - return m_worldTM.GetRotation().GetEulerRadians(); - } - - AZ::Quaternion TransformComponent::GetRotationQuaternion() - { - AZ_Warning("TransformComponent", false, "GetRotationQuaternion is deprecated, please use GetWorldRotationQuaternion"); - return m_worldTM.GetRotation(); - } - - float TransformComponent::GetRotationX() - { - AZ_Warning("TransformComponent", false, "GetRotationX is deprecated, please use GetWorldRotation"); - return GetRotationEulerRadians().GetX(); - } - - float TransformComponent::GetRotationY() - { - AZ_Warning("TransformComponent", false, "GetRotationY is deprecated, please use GetWorldRotation"); - return GetRotationEulerRadians().GetY(); - } - - float TransformComponent::GetRotationZ() - { - AZ_Warning("TransformComponent", false, "GetRotationZ is deprecated, please use GetWorldRotation"); - return GetRotationEulerRadians().GetZ(); - } - AZ::Vector3 TransformComponent::GetWorldRotation() { return m_worldTM.GetRotation().GetEulerRadians(); @@ -830,45 +744,7 @@ namespace AzFramework ->Event("GetLocalX", &AZ::TransformBus::Events::GetLocalX) ->Event("GetLocalY", &AZ::TransformBus::Events::GetLocalY) ->Event("GetLocalZ", &AZ::TransformBus::Events::GetLocalZ) - ->Event("RotateByX", &AZ::TransformBus::Events::RotateByX) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("RotateByY", &AZ::TransformBus::Events::RotateByY) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("RotateByZ", &AZ::TransformBus::Events::RotateByZ) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("SetEulerRotation", &AZ::TransformBus::Events::SetRotation) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("SetRotationQuaternion", &AZ::TransformBus::Events::SetRotationQuaternion) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("SetRotationX", &AZ::TransformBus::Events::SetRotationX) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("SetRotationY", &AZ::TransformBus::Events::SetRotationY) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("SetRotationZ", &AZ::TransformBus::Events::SetRotationZ) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("GetEulerRotation", &AZ::TransformBus::Events::GetRotationEulerRadians) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("GetRotationQuaternion", &AZ::TransformBus::Events::GetRotationQuaternion) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("GetRotationX", &AZ::TransformBus::Events::GetRotationX) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("GetRotationY", &AZ::TransformBus::Events::GetRotationY) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Event("GetRotationZ", &AZ::TransformBus::Events::GetRotationZ) - ->Attribute(AZ::Script::Attributes::Deprecated, true) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) + ->Event("SetWorldRotationQuaternion", &AZ::TransformBus::Events::SetWorldRotationQuaternion) ->Event("GetWorldRotation", &AZ::TransformBus::Events::GetWorldRotation) ->Event("GetWorldRotationQuaternion", &AZ::TransformBus::Events::GetWorldRotationQuaternion) ->Event("SetLocalRotation", &AZ::TransformBus::Events::SetLocalRotation) diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h index e3a647d39f..9009c6bff9 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h @@ -112,22 +112,7 @@ namespace AzFramework float GetLocalZ() override; // Rotation modifiers - void SetRotation(const AZ::Vector3& eulerAnglesRadian) override; - void SetRotationQuaternion(const AZ::Quaternion& quaternion) override; - void SetRotationX(float eulerAngleRadian) override; - void SetRotationY(float eulerAngleRadian) override; - void SetRotationZ(float eulerAngleRadian) override; - - void RotateByX(float eulerAngleRadian) override; - void RotateByY(float eulerAngleRadian) override; - void RotateByZ(float eulerAngleRadian) override; - - AZ::Vector3 GetRotationEulerRadians() override; - AZ::Quaternion GetRotationQuaternion() override; - - float GetRotationX() override; - float GetRotationY() override; - float GetRotationZ() override; + void SetWorldRotationQuaternion(const AZ::Quaternion& quaternion) override; AZ::Vector3 GetWorldRotation() override; AZ::Quaternion GetWorldRotationQuaternion() override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/SliceEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/SliceEditorEntityOwnershipService.cpp index 906ea98357..14dcf5e55d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/SliceEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/SliceEditorEntityOwnershipService.cpp @@ -614,7 +614,7 @@ namespace AzToolsFramework AZ::Quaternion oldEntityRotation; AZ::TransformBus::EventResult(oldEntityRotation, id, &AZ::TransformBus::Events::GetWorldRotationQuaternion); - transformComponent->SetRotationQuaternion(oldEntityRotation); + transformComponent->SetWorldRotationQuaternion(oldEntityRotation); // Ensure the existing hierarchy is maintained AZ::EntityId oldParentEntityId; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index b73978c792..285d962b46 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -520,91 +520,13 @@ namespace AzToolsFramework return m_editorTransform.m_translate.GetZ(); } - void TransformComponent::SetRotation(const AZ::Vector3& eulerAnglesRadians) + void TransformComponent::SetWorldRotationQuaternion(const AZ::Quaternion& quaternion) { - AZ_Warning("AzToolsFramework::TransformComponent", false, "SetRotation is deprecated, please use SetLocalRotation"); - AZ::Transform newWorldTransform = GetWorldTM(); - newWorldTransform.SetRotation(AZ::ConvertEulerRadiansToQuaternion(eulerAnglesRadians)); - SetWorldTM(newWorldTransform); - } - - void TransformComponent::SetRotationQuaternion(const AZ::Quaternion& quaternion) - { - AZ_Warning("AzToolsFramework::TransformComponent", false, "SetRotationQuaternion is deprecated, please use SetLocalRotation"); AZ::Transform newWorldTransform = GetWorldTM(); newWorldTransform.SetRotation(quaternion); SetWorldTM(newWorldTransform); } - void TransformComponent::SetRotationX(float eulerAngleRadians) - { - AZ_Warning("AzToolsFramework::TransformComponent", false, "SetRotationX is deprecated, please use SetLocalRotation"); - AZ::Transform newWorldTransform = GetWorldTM(); - newWorldTransform.SetRotation(AZ::Quaternion::CreateRotationX(eulerAngleRadians)); - SetWorldTM(newWorldTransform); - } - - void TransformComponent::SetRotationY(float eulerAngleRadians) - { - AZ_Warning("AzToolsFramework::TransformComponent", false, "SetRotationY is deprecated, please use SetLocalRotation"); - AZ::Transform newWorldTransform = GetWorldTM(); - newWorldTransform.SetRotation(AZ::Quaternion::CreateRotationY(eulerAngleRadians)); - SetWorldTM(newWorldTransform); - } - - void TransformComponent::SetRotationZ(float eulerAngleRadians) - { - AZ_Warning("AzToolsFramework::TransformComponent", false, "SetRotationZ is deprecated, please use SetLocalRotation"); - AZ::Transform newWorldTransform = GetWorldTM(); - newWorldTransform.SetRotation(AZ::Quaternion::CreateRotationZ(eulerAngleRadians)); - SetWorldTM(newWorldTransform); - } - - void TransformComponent::RotateByX(float eulerAngleRadians) - { - AZ_Warning("AzToolsFramework::TransformComponent", false, "RotateByX is deprecated, please use RotateAroundLocalX"); - SetWorldTM(GetWorldTM() * AZ::Transform::CreateRotationX(eulerAngleRadians)); - } - - void TransformComponent::RotateByY(float eulerAngleRadians) - { - AZ_Warning("AzToolsFramework::TransformComponent", false, "RotateByY is deprecated, please use RotateAroundLocalY"); - SetWorldTM(GetWorldTM() * AZ::Transform::CreateRotationY(eulerAngleRadians)); - } - - void TransformComponent::RotateByZ(float eulerAngleRadians) - { - AZ_Warning("AzToolsFramework::TransformComponent", false, "RotateByZ is deprecated, please use RotateAroundLocalZ"); - SetWorldTM(GetWorldTM() * AZ::Transform::CreateRotationZ(eulerAngleRadians)); - } - - AZ::Vector3 TransformComponent::GetRotationEulerRadians() - { - AZ_Warning("AzToolsFramework::TransformComponent", false, "GetRotationEulerRadians is deprecated, please use GetWorldRotation"); - return GetWorldTM().GetRotation().GetEulerRadians(); - } - - AZ::Quaternion TransformComponent::GetRotationQuaternion() - { - AZ_Warning("AzToolsFramework::TransformComponent", false, "GetRotationQuaternion is deprecated, please use GetWorldRotationQuaternion"); - return GetWorldTM().GetRotation(); - } - - float TransformComponent::GetRotationX() - { - return GetRotationEulerRadians().GetX(); - } - - float TransformComponent::GetRotationY() - { - return GetRotationEulerRadians().GetY(); - } - - float TransformComponent::GetRotationZ() - { - return GetRotationEulerRadians().GetZ(); - } - AZ::Vector3 TransformComponent::GetWorldRotation() { return GetWorldTM().GetRotation().GetEulerRadians(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h index 91d64b0533..f772b608c1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h @@ -99,22 +99,7 @@ namespace AzToolsFramework float GetLocalZ() override; // Rotation modifiers - void SetRotation(const AZ::Vector3& eulerAnglesRadians) override; - void SetRotationQuaternion(const AZ::Quaternion& quaternion) override; - void SetRotationX(float eulerAngleRadians) override; - void SetRotationY(float eulerAngleRadians) override; - void SetRotationZ(float eulerAngleRadians) override; - - void RotateByX(float eulerAngleRadians) override; - void RotateByY(float eulerAngleRadians) override; - void RotateByZ(float eulerAngleRadians) override; - - AZ::Vector3 GetRotationEulerRadians() override; - AZ::Quaternion GetRotationQuaternion() override; - - float GetRotationX() override; - float GetRotationY() override; - float GetRotationZ() override; + void SetWorldRotationQuaternion(const AZ::Quaternion& quaternion) override; AZ::Vector3 GetWorldRotation() override; AZ::Quaternion GetWorldRotationQuaternion() override; diff --git a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h index bd03a442d9..00aa12cb84 100644 --- a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h +++ b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h @@ -644,19 +644,7 @@ namespace Blast MOCK_METHOD0(GetLocalX, float()); MOCK_METHOD0(GetLocalY, float()); MOCK_METHOD0(GetLocalZ, float()); - MOCK_METHOD1(SetRotation, void(const AZ::Vector3&)); - MOCK_METHOD1(SetRotationX, void(float)); - MOCK_METHOD1(SetRotationY, void(float)); - MOCK_METHOD1(SetRotationZ, void(float)); - MOCK_METHOD1(SetRotationQuaternion, void(const AZ::Quaternion&)); - MOCK_METHOD1(RotateByX, void(float)); - MOCK_METHOD1(RotateByY, void(float)); - MOCK_METHOD1(RotateByZ, void(float)); - MOCK_METHOD0(GetRotationEulerRadians, AZ::Vector3()); - MOCK_METHOD0(GetRotationQuaternion, AZ::Quaternion()); - MOCK_METHOD0(GetRotationX, float()); - MOCK_METHOD0(GetRotationY, float()); - MOCK_METHOD0(GetRotationZ, float()); + MOCK_METHOD1(SetWorldRotationQuaternion, void(const AZ::Quaternion&)); MOCK_METHOD0(GetWorldRotation, AZ::Vector3()); MOCK_METHOD0(GetWorldRotationQuaternion, AZ::Quaternion()); MOCK_METHOD1(SetLocalRotation, void(const AZ::Vector3&)); diff --git a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp index feb35ea07d..40cac1e19e 100644 --- a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp @@ -201,7 +201,7 @@ namespace PhysX AZ::Quaternion newRotation = AZ::Quaternion::CreateIdentity(); m_interpolator->GetInterpolated(newPosition, newRotation, deltaTime); - AZ::TransformBus::Event(GetEntityId(), &AZ::TransformInterface::SetRotationQuaternion, newRotation); + AZ::TransformBus::Event(GetEntityId(), &AZ::TransformInterface::SetWorldRotationQuaternion, newRotation); AZ::TransformBus::Event(GetEntityId(), &AZ::TransformInterface::SetWorldTranslation, newPosition); } } @@ -256,7 +256,7 @@ namespace PhysX } else { - AZ::TransformBus::Event(GetEntityId(), &AZ::TransformInterface::SetRotationQuaternion, rigidBody->GetOrientation()); + AZ::TransformBus::Event(GetEntityId(), &AZ::TransformInterface::SetWorldRotationQuaternion, rigidBody->GetOrientation()); AZ::TransformBus::Event(GetEntityId(), &AZ::TransformInterface::SetWorldTranslation, rigidBody->GetPosition()); } m_isLastMovementFromKinematicSource = false; From c4dafc84959cb50443546ba90f50eca97bd5ce59 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 27 May 2021 12:54:13 +0100 Subject: [PATCH 211/811] update usages of transform vector scale --- .../Source/Decals/DecalFeatureProcessor.cpp | 2 +- .../DecalTextureArrayFeatureProcessor.cpp | 2 +- .../ReflectionProbe/ReflectionProbe.cpp | 12 +++---- .../Animation/EditorAttachmentComponent.cpp | 32 ++++++++++++++++--- .../Animation/EditorAttachmentComponent.h | 2 +- .../Source/CoreLights/QuadLightDelegate.cpp | 4 +-- 6 files changed, 39 insertions(+), 15 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp index 55fa633e5d..7c97af4f79 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp @@ -279,7 +279,7 @@ namespace AZ if (handle.IsValid()) { Quaternion orientation = world.GetRotation(); - Vector3 scale = world.GetScale() * nonUniformScale; + Vector3 scale = world.GetUniformScale() * nonUniformScale; SetDecalHalfSize(handle, scale); SetDecalPosition(handle, world.GetTranslation()); diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp index febb0b16c5..e783f3b531 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp @@ -285,7 +285,7 @@ namespace AZ { if (handle.IsValid()) { - SetDecalHalfSize(handle, nonUniformScale * world.GetScale()); + SetDecalHalfSize(handle, nonUniformScale * world.GetUniformScale()); SetDecalPosition(handle, world.GetTranslation()); SetDecalOrientation(handle, world.GetRotation()); diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp index 3497855c07..3e9e316a5a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp @@ -209,7 +209,7 @@ namespace AZ void ReflectionProbe::SetTransform(const AZ::Transform& transform) { // retrieve previous scale and revert the scale on the inner/outer extents - AZ::Vector3 previousScale = m_transform.GetScale(); + float previousScale = m_transform.GetUniformScale(); m_outerExtents /= previousScale; m_innerExtents /= previousScale; @@ -218,12 +218,12 @@ namespace AZ // avoid scaling the visualization sphere AZ::Transform visualizationTransform = m_transform; - visualizationTransform.ExtractScale(); + visualizationTransform.ExtractUniformScale(); m_meshFeatureProcessor->SetTransform(m_visualizationMeshHandle, visualizationTransform); // update the inner/outer extents with the new scale - m_outerExtents *= m_transform.GetScale(); - m_innerExtents *= m_transform.GetScale(); + m_outerExtents *= m_transform.GetUniformScale(); + m_innerExtents *= m_transform.GetUniformScale(); m_outerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_outerExtents / 2.0f); m_innerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_innerExtents / 2.0f); @@ -232,14 +232,14 @@ namespace AZ void ReflectionProbe::SetOuterExtents(const AZ::Vector3& outerExtents) { - m_outerExtents = outerExtents * m_transform.GetScale(); + m_outerExtents = outerExtents * m_transform.GetUniformScale(); m_outerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_outerExtents / 2.0f); m_updateSrg = true; } void ReflectionProbe::SetInnerExtents(const AZ::Vector3& innerExtents) { - m_innerExtents = innerExtents * m_transform.GetScale(); + m_innerExtents = innerExtents * m_transform.GetUniformScale(); m_innerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_innerExtents / 2.0f); m_updateSrg = true; } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.cpp index 3b50c0a48c..f14340b4c9 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.cpp @@ -21,18 +21,42 @@ namespace AZ { namespace Render { + bool EditorAttachmentComponentVersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) + { + if (classElement.GetVersion() < 2) + { + float uniformScaleOffset = 1.0f; + + int scaleElementIndex = classElement.FindElement(AZ_CRC_CE("Scale Offset")); + if (scaleElementIndex != -1) + { + AZ::Vector3 oldScaleValue = AZ::Vector3::CreateOne(); + AZ::SerializeContext::DataElementNode& dataElementNode = classElement.GetSubElement(scaleElementIndex); + if (dataElementNode.GetData(oldScaleValue)) + { + uniformScaleOffset = oldScaleValue.GetMaxElement(); + } + classElement.RemoveElement(scaleElementIndex); + } + + classElement.AddElementWithData(context, "Uniform Scale Offset", uniformScaleOffset); + } + + return true; + } + void EditorAttachmentComponent::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast(context); if (serializeContext) { serializeContext->Class() - ->Version(1) + ->Version(2, &EditorAttachmentComponentVersionConverter) ->Field("Target ID", &EditorAttachmentComponent::m_targetId) ->Field("Target Bone Name", &EditorAttachmentComponent::m_targetBoneName) ->Field("Position Offset", &EditorAttachmentComponent::m_positionOffset) ->Field("Rotation Offset", &EditorAttachmentComponent::m_rotationOffset) - ->Field("Scale Offset", &EditorAttachmentComponent::m_scaleOffset) + ->Field("Uniform Scale Offset", &EditorAttachmentComponent::m_uniformScaleOffset) ->Field("Attached Initially", &EditorAttachmentComponent::m_attachedInitially) ->Field("Scale Source", &EditorAttachmentComponent::m_scaleSource); @@ -70,7 +94,7 @@ namespace AZ ->Attribute(AZ::Edit::Attributes::Min, -AZ::RadToDeg(AZ::Constants::TwoPi)) ->Attribute(AZ::Edit::Attributes::Max, AZ::RadToDeg(AZ::Constants::TwoPi)) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetOffsetChanged) - ->DataElement(0, &EditorAttachmentComponent::m_scaleOffset, "Scale offset", "Local scale offset from target entity") + ->DataElement(0, &EditorAttachmentComponent::m_uniformScaleOffset, "Scale offset", "Local scale offset from target entity") ->Attribute(AZ::Edit::Attributes::Step, 0.1f) ->Attribute(AZ::Edit::Attributes::Min, 0.001f) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetOffsetChanged) @@ -128,7 +152,7 @@ namespace AZ { AZ::Transform offset = AZ::ConvertEulerDegreesToTransform(m_rotationOffset); offset.SetTranslation(m_positionOffset); - offset.MultiplyByScale(m_scaleOffset); + offset.MultiplyByUniformScale(m_uniformScaleOffset); return offset; } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.h index cac8a71a94..0f44043344 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.h @@ -88,7 +88,7 @@ namespace AZ AZ::Vector3 m_rotationOffset = AZ::Vector3::CreateZero(); //! Offset from target entity's scale. - AZ::Vector3 m_scaleOffset = AZ::Vector3::CreateOne(); + float m_uniformScaleOffset = 1.0f; //! Observe scale information from the specified source. AttachmentConfiguration::ScaleSource m_scaleSource = AttachmentConfiguration::ScaleSource::WorldScale; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/QuadLightDelegate.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/QuadLightDelegate.cpp index 2666be6f75..6caa8f31b3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/QuadLightDelegate.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/QuadLightDelegate.cpp @@ -76,12 +76,12 @@ namespace AZ float QuadLightDelegate::GetWidth() const { - return m_shapeBus->GetQuadWidth() * GetTransform().GetScale().GetX(); + return m_shapeBus->GetQuadWidth() * GetTransform().GetUniformScale(); } float QuadLightDelegate::GetHeight() const { - return m_shapeBus->GetQuadHeight() * GetTransform().GetScale().GetY(); + return m_shapeBus->GetQuadHeight() * GetTransform().GetUniformScale(); } } // namespace Render From 072f6e194e3adc7e4cd246e51e19b78e08e096ca Mon Sep 17 00:00:00 2001 From: John Jones-Steele Date: Thu, 27 May 2021 14:02:01 +0100 Subject: [PATCH 212/811] Changed editor icon --- Code/Sandbox/Editor/res/o3de_editor.ico | 4 ++-- Code/Tools/ProjectManager/Resources/o3de_editor.ico | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Sandbox/Editor/res/o3de_editor.ico b/Code/Sandbox/Editor/res/o3de_editor.ico index 0680ceea19..e7b77c35bf 100644 --- a/Code/Sandbox/Editor/res/o3de_editor.ico +++ b/Code/Sandbox/Editor/res/o3de_editor.ico @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c042fce57915fc749abc7b37de765fd697c3c4d7de045a3d44805aa0ce29901a -size 107016 +oid sha256:d717f77fe01f45df934a61bbc215e5322447d21e16f3cebcf2a02f148178f266 +size 106449 diff --git a/Code/Tools/ProjectManager/Resources/o3de_editor.ico b/Code/Tools/ProjectManager/Resources/o3de_editor.ico index 0680ceea19..e7b77c35bf 100644 --- a/Code/Tools/ProjectManager/Resources/o3de_editor.ico +++ b/Code/Tools/ProjectManager/Resources/o3de_editor.ico @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c042fce57915fc749abc7b37de765fd697c3c4d7de045a3d44805aa0ce29901a -size 107016 +oid sha256:d717f77fe01f45df934a61bbc215e5322447d21e16f3cebcf2a02f148178f266 +size 106449 From 6ca37bbf84e14118ccb1000ea51eed2d887a3473 Mon Sep 17 00:00:00 2001 From: igarri Date: Thu, 27 May 2021 14:04:02 +0100 Subject: [PATCH 213/811] Checking variable constness --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index fc2fc41656..2660b660e4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -26,6 +26,7 @@ AZ_POP_DISABLE_WARNING AZ_CVAR( bool, ed_useNewAssetBrowserTableView, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Use the new AssetBrowser TableView for searching assets."); +#pragma optimize("", off) namespace AzToolsFramework { namespace AssetBrowser @@ -138,17 +139,18 @@ namespace AzToolsFramework { const auto& subFilters = compFilter->GetSubFilters(); - auto compositeFilterIterator = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool + const auto compositeFilterIterator = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool { const auto assetTypeFilter = qobject_cast >(filter); return !assetTypeFilter.isNull(); }); + if (compositeFilterIterator != subFilters.end()) { m_assetTypeFilter = qobject_cast >(*compositeFilterIterator); } - auto compStringFilterIter = AZStd::find_if(subFilters.begin(), subFilters.end(), [](FilterConstType filter) -> bool + const auto compStringFilterIter = AZStd::find_if(subFilters.begin(), subFilters.end(), [](FilterConstType filter) -> bool { //The real StringFilter is really a CompositeFilter with just one StringFilter in its subfilter list //To know if it is actually a StringFilter we have to get that subfilter and check if it is a Stringfilter. @@ -162,7 +164,7 @@ namespace AzToolsFramework auto strFilter = qobject_cast>(filt); return !strFilter.isNull(); }; - auto stringSubfliterConstIter = AZStd::find_if(stringSubfilters.begin(), stringSubfilters.end(), canBeCasted); + const auto stringSubfliterConstIter = AZStd::find_if(stringSubfilters.begin(), stringSubfilters.end(), canBeCasted); //A Composite StringFilter will only have just one subfilter and nothing more. if (stringSubfliterConstIter != stringSubfilters.end() && stringSubfilters.size() == 1) @@ -176,6 +178,7 @@ namespace AzToolsFramework if (compStringFilterIter != subFilters.end()) { const auto compStringFilter = qobject_cast>(*compStringFilterIter); + if (!compStringFilter->GetSubFilters().isEmpty() && compStringFilter->GetSubFilters()[0]) { m_stringFilter = qobject_cast>(compStringFilter->GetSubFilters()[0]); @@ -185,7 +188,8 @@ namespace AzToolsFramework } invalidateFilter(); Q_EMIT filterChanged(); - emit stringFilterPopulated(!m_stringFilter.isNull()); + bool isNullAB = m_stringFilter.isNull(); + emit stringFilterPopulated(!isNullAB); } void AssetBrowserFilterModel::filterUpdatedSlot() @@ -205,5 +209,6 @@ namespace AzToolsFramework } // namespace AssetBrowser } // namespace AzToolsFramework// namespace AssetBrowser +#pragma optimize("", on) #include "AssetBrowser/moc_AssetBrowserFilterModel.cpp" From e0ed53577108c7f079b2f783fb44236e3c1d1813 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 27 May 2021 14:29:54 +0100 Subject: [PATCH 214/811] remove unused render cube function --- .../Code/EMotionFX/Rendering/Common/RenderUtil.cpp | 12 ------------ .../Code/EMotionFX/Rendering/Common/RenderUtil.h | 8 -------- .../EMotionFX/Rendering/Common/ScaleManipulator.cpp | 3 --- 3 files changed, 23 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp index 35f601a270..b2389a3086 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp @@ -1297,18 +1297,6 @@ namespace MCommon } - // render a cube - void RenderUtil::RenderCube(float size, const AZ::Vector3& position, const MCore::RGBAColor& color) - { - // setup the world space matrix of the cube - AZ::Transform cubeTransform = AZ::Transform::CreateUniformScale(size); - cubeTransform.SetTranslation(position); - - // render the cube - RenderCube(color, cubeTransform); - } - - // construct the arrow head mesh used for rendering RenderUtil::UtilMesh* RenderUtil::CreateArrowHead(float height, float radius) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h index e674943e53..b724c28720 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h @@ -297,14 +297,6 @@ namespace MCommon */ void RenderCylinder(float baseRadius, float topRadius, float length, const AZ::Vector3& position, const AZ::Vector3& direction, const MCore::RGBAColor& color); - /** - * Render a cube. - * @param size The size of the cube. - * @param position The position of the center of the cube. - * @param color The desired cube color. - */ - void RenderCube(float size, const AZ::Vector3& position, const MCore::RGBAColor& color); - /** * Render a triangle (CCW). * @param v1 The first corner of the triangle. diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp index 7fdec63f66..54ccd00535 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp @@ -169,7 +169,6 @@ namespace MCommon if (mXAxisVisible) { renderUtil->RenderLine(mPosition, mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + 0.5f * mBaseRadius, 0.0f, 0.0f), xAxisColor); - //renderUtil->RenderCube( mBaseRadius, mPosition + mSignX * Vector3(mScaledSize.x+mBaseRadius, 0, 0), ManipulatorColors::mRed ); AZ::Vector3 quadPos = MCore::Project(mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + mBaseRadius, 0, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight); renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::mRed, ManipulatorColors::mRed); @@ -186,7 +185,6 @@ namespace MCommon if (mYAxisVisible) { renderUtil->RenderLine(mPosition, mPosition + mSignY * AZ::Vector3(0.0f, mScaledSize.GetY(), 0.0f), yAxisColor); - //renderUtil->RenderCube( mBaseRadius, mPosition + mSignY * Vector3(0, mScaledSize.y+0.5*mBaseRadius, 0), ManipulatorColors::mGreen ); AZ::Vector3 quadPos = MCore::Project(mPosition + mSignY * AZ::Vector3(0, mScaledSize.GetY() + 0.5f * mBaseRadius, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight); renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::mGreen, ManipulatorColors::mGreen); @@ -203,7 +201,6 @@ namespace MCommon if (mZAxisVisible) { renderUtil->RenderLine(mPosition, mPosition + mSignZ * AZ::Vector3(0.0f, 0.0f, mScaledSize.GetZ()), zAxisColor); - //renderUtil->RenderCube( mBaseRadius, mPosition + mSignZ * Vector3(0, 0, mScaledSize.z+0.5*mBaseRadius), ManipulatorColors::mBlue ); AZ::Vector3 quadPos = MCore::Project(mPosition + mSignZ * AZ::Vector3(0, 0, mScaledSize.GetZ() + 0.5f * mBaseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::mBlue, ManipulatorColors::mBlue); From dd94795106b2691ff04360009fff23d8ab3811d2 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 27 May 2021 14:43:58 +0100 Subject: [PATCH 215/811] update force region to avoid vector scale Transform functions --- Gems/PhysX/Code/Source/ForceRegion.cpp | 4 ++-- Gems/PhysX/Code/Source/ForceRegionForces.cpp | 3 +-- Gems/PhysX/Code/Source/ForceRegionForces.h | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Gems/PhysX/Code/Source/ForceRegion.cpp b/Gems/PhysX/Code/Source/ForceRegion.cpp index c41ae47a0e..2cdd0dea3f 100644 --- a/Gems/PhysX/Code/Source/ForceRegion.cpp +++ b/Gems/PhysX/Code/Source/ForceRegion.cpp @@ -148,7 +148,7 @@ namespace PhysX { m_worldTransform = world; m_regionParams.m_position = world.GetTranslation(); - m_regionParams.m_scale = world.GetScale(); + m_regionParams.m_scale = world.GetUniformScale(); m_regionParams.m_rotation = world.GetRotation(); AZ::EBusReduceResult triggerAabb; triggerAabb.value = AZ::Aabb::CreateNull(); @@ -223,7 +223,7 @@ namespace PhysX , entityId , &AZ::TransformBus::Events::GetWorldTM); regionParams.m_position = worldTransform.GetTranslation(); - regionParams.m_scale = worldTransform.GetScale(); + regionParams.m_scale = worldTransform.GetUniformScale(); regionParams.m_rotation = worldTransform.GetRotation(); LmbrCentral::SplineComponentRequestBus::EventResult(regionParams.m_spline diff --git a/Gems/PhysX/Code/Source/ForceRegionForces.cpp b/Gems/PhysX/Code/Source/ForceRegionForces.cpp index 8ea74c0de7..61679e9cb4 100644 --- a/Gems/PhysX/Code/Source/ForceRegionForces.cpp +++ b/Gems/PhysX/Code/Source/ForceRegionForces.cpp @@ -294,8 +294,7 @@ namespace PhysX rotateInverse.InvertFull(); } - AZ::Vector3 scaleInverse = region.m_scale; - scaleInverse = scaleInverse.GetReciprocal(); + float scaleInverse = 1.0f / region.m_scale; AZ::Vector3 position = entity.m_position + entity.m_velocity * m_lookAhead; AZ::Vector3 localPos = position - region.m_position; diff --git a/Gems/PhysX/Code/Source/ForceRegionForces.h b/Gems/PhysX/Code/Source/ForceRegionForces.h index 206e35c195..6f7eb6b277 100644 --- a/Gems/PhysX/Code/Source/ForceRegionForces.h +++ b/Gems/PhysX/Code/Source/ForceRegionForces.h @@ -36,7 +36,7 @@ namespace PhysX AZ::EntityId m_id; AZ::Vector3 m_position; AZ::Quaternion m_rotation; - AZ::Vector3 m_scale; + float m_scale; AZ::SplinePtr m_spline; AZ::Aabb m_aabb; }; From 6b7caa93b163beffc4e7fcd74830389121e03df2 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 27 May 2021 14:47:06 +0100 Subject: [PATCH 216/811] update collider component to avoid vector scale Transform functions --- Gems/PhysX/Code/Source/EditorColliderComponent.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 26700a7103..87bb702184 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -868,7 +868,7 @@ namespace PhysX colliderConfigNoOffset.m_rotation = AZ::Quaternion::CreateIdentity(); colliderConfigNoOffset.m_position = AZ::Vector3::CreateZero(); m_colliderDebugDraw.DrawMesh(debugDisplay, colliderConfigNoOffset, m_scaledPrimitive.value(), - GetWorldTM().GetScale() * m_cachedNonUniformScale, shapeIndex); + GetWorldTM().GetUniformScale() * m_cachedNonUniformScale, shapeIndex); } } @@ -1007,7 +1007,7 @@ namespace PhysX AZ::Vector3 EditorColliderComponent::GetBoxScale() { - return GetWorldTM().GetScale(); + return AZ::Vector3(GetWorldTM().GetUniformScale()); } void EditorColliderComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) @@ -1049,7 +1049,7 @@ namespace PhysX void EditorColliderComponent::UpdateShapeConfigurationScale() { auto& shapeConfiguration = m_shapeConfiguration.GetCurrent(); - shapeConfiguration.m_scale = GetWorldTM().ExtractScale() * m_cachedNonUniformScale; + shapeConfiguration.m_scale = GetWorldTM().ExtractUniformScale() * m_cachedNonUniformScale; m_colliderDebugDraw.ClearCachedGeometry(); } From ece62c51d8176d360b6891a410c9697a8e3f88b1 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 27 May 2021 15:28:28 +0100 Subject: [PATCH 218/811] update physics debug draw to avoid vector scale Transform functions --- Gems/PhysX/Code/Editor/DebugDraw.cpp | 53 +++++++++++++++++----------- Gems/PhysX/Code/Editor/DebugDraw.h | 10 +++--- 2 files changed, 39 insertions(+), 24 deletions(-) diff --git a/Gems/PhysX/Code/Editor/DebugDraw.cpp b/Gems/PhysX/Code/Editor/DebugDraw.cpp index b73e3f22bd..23a9a3cb44 100644 --- a/Gems/PhysX/Code/Editor/DebugDraw.cpp +++ b/Gems/PhysX/Code/Editor/DebugDraw.cpp @@ -555,25 +555,37 @@ namespace PhysX if (meshConfig.GetCachedNativeMesh()) { - const AZ::Transform scaleMatrix = AZ::Transform::CreateScale(meshScale); - debugDisplay.PushMatrix(GetColliderLocalTransform(colliderConfig) * scaleMatrix); + debugDisplay.PushMatrix(GetColliderLocalTransform(colliderConfig)); if (meshConfig.GetMeshType() == Physics::CookedMeshShapeConfiguration::MeshType::TriangleMesh) { - DrawTriangleMesh(debugDisplay, colliderConfig, geomIndex); + DrawTriangleMesh(debugDisplay, colliderConfig, geomIndex, meshScale); } else { - DrawConvexMesh(debugDisplay, colliderConfig, geomIndex); + DrawConvexMesh(debugDisplay, colliderConfig, geomIndex, meshScale); } debugDisplay.PopMatrix(); } } - void Collider::DrawTriangleMesh(AzFramework::DebugDisplayRequests& debugDisplay, - const Physics::ColliderConfiguration& colliderConfig, - AZ::u32 geomIndex) const + AZStd::vector ScalePoints(const AZ::Vector3& scale, const AZStd::vector& points) + { + AZStd::vector scaledPoints; + scaledPoints.resize_no_construct(points.size()); + AZStd::transform( + points.begin(), points.end(), scaledPoints.begin(), + [scale](const AZ::Vector3& point) + { + return scale * point; + }); + return scaledPoints; + } + + void Collider::DrawTriangleMesh( + AzFramework::DebugDisplayRequests& debugDisplay, const Physics::ColliderConfiguration& colliderConfig, AZ::u32 geomIndex, + const AZ::Vector3& meshScale) const { AZ_Assert(geomIndex < m_geometry.size(), "DrawTriangleMesh: geomIndex is out of range"); @@ -581,10 +593,10 @@ namespace PhysX const AZStd::unordered_map>& triangleIndexesByMaterialSlot = geom.m_triangleIndexesByMaterialSlot; - const AZStd::vector& verts = geom.m_verts; - const AZStd::vector& points = geom.m_points; + AZStd::vector scaledVerts = ScalePoints(meshScale, geom.m_verts); + AZStd::vector scaledPoints = ScalePoints(meshScale, geom.m_points); - if (!verts.empty()) + if (!scaledVerts.empty()) { for (const auto& element : triangleIndexesByMaterialSlot) { @@ -596,30 +608,31 @@ namespace PhysX triangleMeshInfo.m_numTriangles = triangleCount; triangleMeshInfo.m_materialSlotIndex = materialSlot; - debugDisplay.DrawTrianglesIndexed(verts, triangleIndexes + debugDisplay.DrawTrianglesIndexed(scaledVerts, triangleIndexes , CalcDebugColor(colliderConfig, triangleMeshInfo)); } - debugDisplay.DrawLines(points, WireframeColor); + debugDisplay.DrawLines(scaledPoints, WireframeColor); } } - void Collider::DrawConvexMesh(AzFramework::DebugDisplayRequests& debugDisplay, - const Physics::ColliderConfiguration& colliderConfig, AZ::u32 geomIndex) const + void Collider::DrawConvexMesh( + AzFramework::DebugDisplayRequests& debugDisplay, const Physics::ColliderConfiguration& colliderConfig, AZ::u32 geomIndex, + const AZ::Vector3& meshScale) const { AZ_Assert(geomIndex < m_geometry.size(), "DrawConvexMesh: geomIndex is out of range"); const GeometryData& geom = m_geometry[geomIndex]; - const AZStd::vector& verts = geom.m_verts; - const AZStd::vector& points = geom.m_points; + AZStd::vector scaledVerts = ScalePoints(meshScale, geom.m_verts); + AZStd::vector scaledPoints = ScalePoints(meshScale, geom.m_points); - if (!verts.empty()) + if (!scaledVerts.empty()) { - const AZ::u32 triangleCount = static_cast(verts.size() / 3); + const AZ::u32 triangleCount = static_cast(scaledVerts.size() / 3); ElementDebugInfo convexMeshInfo; convexMeshInfo.m_numTriangles = triangleCount; - debugDisplay.DrawTriangles(verts, CalcDebugColor(colliderConfig, convexMeshInfo)); - debugDisplay.DrawLines(points, WireframeColor); + debugDisplay.DrawTriangles(scaledVerts, CalcDebugColor(colliderConfig, convexMeshInfo)); + debugDisplay.DrawLines(scaledPoints, WireframeColor); } } diff --git a/Gems/PhysX/Code/Editor/DebugDraw.h b/Gems/PhysX/Code/Editor/DebugDraw.h index fcff961412..c43634717a 100644 --- a/Gems/PhysX/Code/Editor/DebugDraw.h +++ b/Gems/PhysX/Code/Editor/DebugDraw.h @@ -115,11 +115,13 @@ namespace PhysX AzFramework::DebugDisplayRequests& debugDisplay) override; // Internal mesh drawing subroutines - void DrawTriangleMesh(AzFramework::DebugDisplayRequests& debugDisplay, - const Physics::ColliderConfiguration& colliderConfig, AZ::u32 geomIndex) const; + void DrawTriangleMesh( + AzFramework::DebugDisplayRequests& debugDisplay, const Physics::ColliderConfiguration& colliderConfig, AZ::u32 geomIndex, + const AZ::Vector3& meshScale = AZ::Vector3::CreateOne()) const; - void DrawConvexMesh(AzFramework::DebugDisplayRequests& debugDisplay, - const Physics::ColliderConfiguration& colliderConfig, AZ::u32 geomIndex) const; + void DrawConvexMesh( + AzFramework::DebugDisplayRequests& debugDisplay, const Physics::ColliderConfiguration& colliderConfig, AZ::u32 geomIndex, + const AZ::Vector3& meshScale = AZ::Vector3::CreateOne()) const; void BuildTriangleMesh(physx::PxBase* meshData, AZ::u32 geomIndex) const; From 379f0717fa67fc1b502311e2e1e4d43520840721 Mon Sep 17 00:00:00 2001 From: gallowj Date: Thu, 27 May 2021 09:39:05 -0500 Subject: [PATCH 219/811] transitioned from use of bootstrap.cfg to .o3de\Reigistry\bootstrap.setreg --- .../DccScriptingInterface/azpy/__init__.py | 2 +- .../azpy/config_utils.py | 38 +++++++++++++++++-- .../DccScriptingInterface/azpy/constants.py | 14 ++++++- .../DccScriptingInterface/config.py | 4 +- 4 files changed, 51 insertions(+), 7 deletions(-) diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/__init__.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/__init__.py index 69e4543a59..40ed8834b5 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/__init__.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/__init__.py @@ -84,7 +84,7 @@ _LY_DEV = os.getenv(constants.ENVAR_LY_DEV, # get/set the project name _LY_PROJECT_TAG = os.getenv(constants.ENVAR_LY_PROJECT, - config_utils.get_current_project(_LY_DEV)) + config_utils.get_current_project().name) # project cache log dir path _DCCSI_LOG_PATH = Path(os.getenv(constants.ENVAR_DCCSI_LOG_PATH, diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/config_utils.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/config_utils.py index 9c920a871d..0a0c6b8337 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/config_utils.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/config_utils.py @@ -137,8 +137,9 @@ def get_dccsi_config(dccsi_dirpath=return_stub_dir()): # ------------------------------------------------------------------------- -def get_current_project(dev_folder=get_stub_check_path()): - """Uses regex in lumberyard Dev\\bootstrap.cfg to retreive project tag str""" +def get_current_project_cfg(dev_folder=get_stub_check_path()): + """Uses regex in lumberyard Dev\\bootstrap.cfg to retreive project tag str + Note: boostrap.cfg will be deprecated. Don't use this method anymore.""" boostrap_filepath = Path(dev_folder, "bootstrap.cfg") if boostrap_filepath.exists(): bootstrap = open(str(boostrap_filepath), "r") @@ -153,6 +154,33 @@ def get_current_project(dev_folder=get_stub_check_path()): # ------------------------------------------------------------------------- +# ------------------------------------------------------------------------- +def get_current_project(): + """Gets o3de project via .o3de data in user directory""" + + from azpy.constants import PATH_USER_O3DE_BOOTSTRAP + from collections import OrderedDict + from box import Box + + bootstrap_box = None + + try: + bootstrap_box = Box.from_json(filename=PATH_USER_O3DE_BOOTSTRAP, + encoding="utf-8", + errors="strict", + object_pairs_hook=OrderedDict) + except FileExistsError as e: + _LOGGER.error('File does not exist: {}'.format(PATH_USER_O3DE_BOOTSTRAP)) + + if bootstrap_box: + # this seems fairly hard coded - what if the data changes? + project_path=Path(bootstrap_box.Amazon.AzCore.Bootstrap.project_path) + return project_path.resolve() + else: + return None +# ------------------------------------------------------------------------- + + # ------------------------------------------------------------------------- def bootstrap_dccsi_py_libs(dccsi_dirpath=return_stub_dir()): """Builds and adds local site dir libs based on py version""" @@ -194,7 +222,11 @@ if __name__ == '__main__': _LOGGER.info('LY_DEV: {}'.format(get_stub_check_path('engine.json'))) - _LOGGER.info('LY_PROJECT: {}'.format(get_current_project(get_stub_check_path('bootstrap.cfg')))) + # this will be deprecated and shouldn't work soon (returns None) + _LOGGER.info('LY_PROJECT: {}'.format(get_current_project_cfg(get_stub_check_path('bootstrap.cfg')))) + + # new o3de version + _LOGGER.info('LY_PROJECT: {}'.format(get_current_project())) _LOGGER.info('DCCSI_PYTHON_LIB_PATH: {}'.format(bootstrap_dccsi_py_libs(return_stub_dir('dccsi_stub')))) diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/constants.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/constants.py index 792f0faee6..e10221d324 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/constants.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/constants.py @@ -26,6 +26,7 @@ So we can make an update here once that is used elsewhere. import os import sys import site +from os.path import expanduser import logging as _logging # for this module to perform standalone @@ -91,6 +92,9 @@ TAG_DIR_DCCSI_SDK = str('SDK') TAG_DIR_LY_BUILD = str('build') TAG_QT_PLUGIN_PATH = str('QT_PLUGIN_PATH') +TAG_O3DE_FOLDER = str('.o3de') +TAG_O3DE_BOOTSTRAP = str('bootstrap.setreg') + # filesystem markers, stub file names. STUB_LY_DEV = str('engine.json') STUB_LY_ROOT_PROJECT = str('ly_project_stub') @@ -221,10 +225,17 @@ TAG_DEFAULT_PY = str('Launch_pyBASE.bat') # config file stuff FILENAME_DEFAULT_CONFIG = str('DCCSI_config.json') +# new o3de related paths +PATH_USER_O3DE = str('{home}\\{o3de}').format(home=expanduser("~"), + o3de=TAG_O3DE_FOLDER) +PATH_USER_O3DE_REGISTRY = str('{0}\\Registry').format(PATH_USER_O3DE) +PATH_USER_O3DE_BOOTSTRAP = str('{reg}\\{file}').format(reg=PATH_USER_O3DE_REGISTRY, + file=TAG_O3DE_BOOTSTRAP) + #python and site-dir TAG_DCCSI_PY_VERSION_MAJOR = str(3) TAG_DCCSI_PY_VERSION_MINOR = str(7) -TAG_DCCSI_PY_VERSION_RELEASE = str(5) +TAG_DCCSI_PY_VERSION_RELEASE = str(10) TAG_PYTHON_EXE = str('python.exe') TAG_TOOLS_DIR = str('Tools\\Python') TAG_PLATFORM = str('windows') @@ -314,6 +325,7 @@ if __name__ == '__main__': _stash_dict['QTFORPYTHON_PATH'] = Path(PATH_QTFORPYTHON_PATH) _stash_dict['QT_PLUGIN_PATH'] = Path(PATH_QT_PLUGIN_PATH) _stash_dict['SAT_INSTALL_PATH'] = Path(PATH_SAT_INSTALL_PATH) + _stash_dict['PATH_USER_O3DE_BOOTSTRAP'] = Path(PATH_USER_O3DE_BOOTSTRAP) # --------------------------------------------------------------------- # py 2 and 3 compatible iter diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/config.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/config.py index 45ff48c272..0fa0b6ee67 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/config.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/config.py @@ -223,8 +223,8 @@ os.environ["DYNACONF_DCCSI_DEV_MODE"] = str(_DCCSI_DEV_MODE) _LY_DEV = azpy.config_utils.get_stub_check_path(in_path=_DCCSIG_PATH, check_stub='engine.json') os.environ["DYNACONF_LY_DEV"] = str(_LY_DEV.resolve()) -_LY_PROJECT = azpy.config_utils.get_current_project(_LY_DEV) -os.environ["DYNACONF_LY_PROJECT"] = _LY_PROJECT +_LY_PROJECT = azpy.config_utils.get_current_project() +os.environ["DYNACONF_LY_PROJECT"] = str(_LY_PROJECT.resolve()) _LY_PROJECT_PATH = Path(_LY_DEV, _LY_PROJECT) os.environ["DYNACONF_LY_PROJECT_PATH"] = str(_LY_PROJECT_PATH) os.environ["DYNACONF_DCCSIG_PATH"] = str(_DCCSIG_PATH) From d53367858bd5a8e1f2f0652c66525496925c3a06 Mon Sep 17 00:00:00 2001 From: gallowj Date: Thu, 27 May 2021 09:50:49 -0500 Subject: [PATCH 220/811] Altered a variable to make usage more clear. --- .../TechnicalArt/DccScriptingInterface/azpy/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/__init__.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/__init__.py index 40ed8834b5..ab2d5db480 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/__init__.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/__init__.py @@ -83,13 +83,13 @@ _LY_DEV = os.getenv(constants.ENVAR_LY_DEV, check_stub='engine.json')) # get/set the project name -_LY_PROJECT_TAG = os.getenv(constants.ENVAR_LY_PROJECT, +_LY_PROJECT_NAME = os.getenv(constants.ENVAR_LY_PROJECT, config_utils.get_current_project().name) # project cache log dir path _DCCSI_LOG_PATH = Path(os.getenv(constants.ENVAR_DCCSI_LOG_PATH, Path(_LY_DEV, - _LY_PROJECT_TAG, + _LY_PROJECT_NAME, 'Cache', 'pc', 'user', 'log', 'logs'))) @@ -223,7 +223,7 @@ if _G_DEBUG: _LOGGER.debug('MODULE_PATH: {}'.format(_MODULE_PATH)) _LOGGER.debug('LY_DEV_PATH: {}'.format(_LY_DEV)) _LOGGER.debug('DCCSI_PATH: {}'.format(_DCCSIG_PATH)) -_LOGGER.debug('LY_PROJECT_TAG: {}'.format(_LY_PROJECT_TAG)) +_LOGGER.debug('LY_PROJECT_TAG: {}'.format(_LY_PROJECT_NAME)) _LOGGER.debug('DCCSI_LOG_PATH: {}'.format(_DCCSI_LOG_PATH)) From f286057046452f5bf21d63f3ac7780b9d50b062f Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 27 May 2021 16:05:18 +0100 Subject: [PATCH 221/811] update manipulators to avoid using vector scale Transform functions --- .../Manipulators/LineSegmentSelectionManipulator.cpp | 2 +- .../AzToolsFramework/Manipulators/LinearManipulator.cpp | 2 +- .../AzToolsFramework/Manipulators/ManipulatorSnapping.h | 2 +- .../AzToolsFramework/Manipulators/ManipulatorSpace.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.cpp index a8fe0e55bd..8874e0dcd9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.cpp @@ -31,7 +31,7 @@ namespace AzToolsFramework rayProportion, lineSegmentProportion, worldClosestPositionRay, worldClosestPositionLineSegment); AZ::Transform worldFromLocalNormalized = worldFromLocal; - const AZ::Vector3 scale = worldFromLocalNormalized.ExtractScale() * nonUniformScale; + const AZ::Vector3 scale = worldFromLocalNormalized.ExtractUniformScale() * nonUniformScale; const AZ::Transform localFromWorldNormalized = worldFromLocalNormalized.GetInverse(); return { (localFromWorldNormalized.TransformPoint(worldClosestPositionLineSegment)) / scale }; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp index 87d966fe84..aa84fc5752 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp @@ -59,7 +59,7 @@ namespace AzToolsFramework ? CalculateSnappedOffset(localTransform.GetTranslation(), axis, gridSize * scaleRecip) : AZ::Vector3::CreateZero(); - const AZ::Vector3 localScale = localTransform.GetScale(); + const AZ::Vector3 localScale = AZ::Vector3(localTransform.GetUniformScale()); const AZ::Quaternion localRotation = QuaternionFromTransformNoScaling(localTransform); // calculate scale amount to snap, to align to round scale value const AZ::Vector3 scaleSnapOffset = snapping && !gridSnapAction.m_localSnapping diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h index db0baa1479..e6c70079df 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h @@ -113,7 +113,7 @@ namespace AzToolsFramework /// noise in the value returned when dealing with values far from the origin. inline float ScaleReciprocal(const AZ::Transform& transform) { - return Round3(transform.GetScale().GetReciprocal().GetMinElement()); + return Round3(1.0f / transform.GetUniformScale()); } /// Find the reciprocal of the non-uniform scale. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.cpp index fba7e35078..cd08a95af7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.cpp @@ -39,7 +39,7 @@ namespace AzToolsFramework AZ::Transform result; result.SetRotation(m_space.GetRotation() * localTransform.GetRotation()); result.SetTranslation(m_space.TransformPoint(m_nonUniformScale * localTransform.GetTranslation())); - result.SetScale(m_space.GetScale() * localTransform.GetScale()); + result.SetScale(m_space.GetScale() * localTransform.GetUniformScale()); return result; } From 529e29071ca1b4d3048848d5cc21730a5184f405 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Thu, 27 May 2021 16:42:17 +0100 Subject: [PATCH 222/811] update Ragdoll component to only uses Handles (#981) --- .../AzFramework/AzFramework/Physics/Ragdoll.h | 2 +- .../Code/Tests/Mocks/PhysicsRagdoll.h | 2 +- .../Source/PhysXCharacters/API/Ragdoll.cpp | 2 +- .../Code/Source/PhysXCharacters/API/Ragdoll.h | 2 +- .../CharacterControllerComponent.cpp | 2 +- .../Components/RagdollComponent.cpp | 120 ++++++++++++------ .../Components/RagdollComponent.h | 5 +- 7 files changed, 93 insertions(+), 42 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Ragdoll.h b/Code/Framework/AzFramework/AzFramework/Physics/Ragdoll.h index 239d93cf32..97c841e8f8 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Ragdoll.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Ragdoll.h @@ -102,7 +102,7 @@ namespace Physics /// Is the ragdoll currently simulated? /// @result True in case the ragdoll is simulated, false if not. - virtual bool IsSimulated() = 0; + virtual bool IsSimulated() const = 0; /// Writes the state for all of the bodies in the ragdoll to the provided output. /// The caller owns the output state and can safely manipulate it without affecting the physics simulation. diff --git a/Gems/EMotionFX/Code/Tests/Mocks/PhysicsRagdoll.h b/Gems/EMotionFX/Code/Tests/Mocks/PhysicsRagdoll.h index b3acb73e19..446abbf6af 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/PhysicsRagdoll.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/PhysicsRagdoll.h @@ -26,7 +26,7 @@ namespace EMotionFX MOCK_METHOD0(DisableSimulation, void()); MOCK_METHOD0(DisableSimulationQueued, void()); - MOCK_METHOD0(IsSimulated, bool()); + MOCK_CONST_METHOD0(IsSimulated, bool()); MOCK_CONST_METHOD1(GetState, void(Physics::RagdollState&)); MOCK_METHOD1(SetState, void(const Physics::RagdollState&)); diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/Ragdoll.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/API/Ragdoll.cpp index 5249781e31..02ebe7281c 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/Ragdoll.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/Ragdoll.cpp @@ -274,7 +274,7 @@ namespace PhysX m_queuedDisableSimulation = true; } - bool Ragdoll::IsSimulated() + bool Ragdoll::IsSimulated() const { return m_simulating; } diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/Ragdoll.h b/Gems/PhysX/Code/Source/PhysXCharacters/API/Ragdoll.h index 7bf807bcc5..7182a3a44c 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/Ragdoll.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/Ragdoll.h @@ -46,7 +46,7 @@ namespace PhysX void EnableSimulationQueued(const Physics::RagdollState& initialState) override; void DisableSimulation() override; void DisableSimulationQueued() override; - bool IsSimulated() override; + bool IsSimulated() const override; void GetState(Physics::RagdollState& ragdollState) const override; void SetState(const Physics::RagdollState& ragdollState) override; void SetStateQueued(const Physics::RagdollState& ragdollState) override; diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.cpp index 431dbd9ac4..86c60565a0 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.cpp @@ -465,7 +465,7 @@ namespace PhysX PhysX::CharacterController* CharacterControllerComponent::GetController() { - return const_cast(GetControllerConst()); + return const_cast(static_cast(*this).GetControllerConst()); } void CharacterControllerComponent::CreateController() diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp index 4c58187fb8..8da512647f 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp @@ -170,63 +170,88 @@ namespace PhysX // RagdollPhysicsBus void RagdollComponent::EnableSimulation(const Physics::RagdollState& initialState) { - m_ragdoll->EnableSimulation(initialState); + if (auto* ragdoll = GetPhysXRagdoll()) + { + ragdoll->EnableSimulation(initialState); + } } void RagdollComponent::EnableSimulationQueued(const Physics::RagdollState& initialState) { - m_ragdoll->EnableSimulationQueued(initialState); + if (auto* ragdoll = GetPhysXRagdoll()) + { + ragdoll->EnableSimulationQueued(initialState); + } } void RagdollComponent::DisableSimulation() { - if (m_ragdoll) + if (auto* ragdoll = GetPhysXRagdoll()) { - m_ragdoll->DisableSimulation(); + ragdoll->DisableSimulation(); } } void RagdollComponent::DisableSimulationQueued() { - if (m_ragdoll) + if (auto* ragdoll = GetPhysXRagdoll()) { - m_ragdoll->DisableSimulationQueued(); + ragdoll->DisableSimulationQueued(); } } Physics::Ragdoll* RagdollComponent::GetRagdoll() { - return m_ragdoll; + return GetPhysXRagdoll(); } void RagdollComponent::GetState(Physics::RagdollState& ragdollState) const { - m_ragdoll->GetState(ragdollState); + if (const auto* ragdoll = GetPhysXRagdollConst()) + { + ragdoll->GetState(ragdollState); + } } void RagdollComponent::SetState(const Physics::RagdollState& ragdollState) { - m_ragdoll->SetState(ragdollState); + if (auto* ragdoll = GetPhysXRagdoll()) + { + ragdoll->SetState(ragdollState); + } } void RagdollComponent::SetStateQueued(const Physics::RagdollState& ragdollState) { - m_ragdoll->SetStateQueued(ragdollState); + if (auto* ragdoll = GetPhysXRagdoll()) + { + ragdoll->SetStateQueued(ragdollState); + } } void RagdollComponent::GetNodeState(size_t nodeIndex, Physics::RagdollNodeState& nodeState) const { - m_ragdoll->GetNodeState(nodeIndex, nodeState); + if (const auto* ragdoll = GetPhysXRagdollConst()) + { + ragdoll->GetNodeState(nodeIndex, nodeState); + } } void RagdollComponent::SetNodeState(size_t nodeIndex, const Physics::RagdollNodeState& nodeState) { - m_ragdoll->SetNodeState(nodeIndex, nodeState); + if (auto* ragdoll = GetPhysXRagdoll()) + { + ragdoll->SetNodeState(nodeIndex, nodeState); + } } Physics::RagdollNode* RagdollComponent::GetNode(size_t nodeIndex) const { - return m_ragdoll->GetNode(nodeIndex); + if (const auto* ragdoll = GetPhysXRagdollConst()) + { + return ragdoll->GetNode(nodeIndex); + } + return nullptr; } void RagdollComponent::EnablePhysics() @@ -245,14 +270,19 @@ namespace PhysX bool RagdollComponent::IsPhysicsEnabled() const { - return m_ragdoll && m_ragdoll->IsSimulated(); + if (const auto* ragdoll = GetPhysXRagdollConst()) + { + return ragdoll->IsSimulated(); + } + return false; + } AZ::Aabb RagdollComponent::GetAabb() const { - if (m_ragdoll) + if (const auto* ragdoll = GetPhysXRagdollConst()) { - return m_ragdoll->GetAabb(); + return ragdoll->GetAabb(); } return AZ::Aabb::CreateNull(); } @@ -264,18 +294,14 @@ namespace PhysX AzPhysics::SimulatedBodyHandle RagdollComponent::GetSimulatedBodyHandle() const { - if (m_ragdoll) - { - return m_ragdoll->m_bodyHandle; - } - return AzPhysics::InvalidSimulatedBodyHandle; + return m_ragdollHandle; } AzPhysics::SceneQueryHit RagdollComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_ragdoll) + if (auto* ragdoll = GetPhysXRagdoll()) { - return m_ragdoll->RayCast(request); + return ragdoll->RayCast(request); } return AzPhysics::SceneQueryHit(); } @@ -323,23 +349,24 @@ namespace PhysX AZ::TransformBus::EventResult(entityTransform, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); ragdollConfiguration.m_initialState = GetBindPoseWorld(bindPose, entityTransform); - AzPhysics::SceneHandle defaultSceneHandle = AzPhysics::InvalidSceneHandle; - Physics::DefaultWorldBus::BroadcastResult(defaultSceneHandle, &Physics::DefaultWorldRequests::GetDefaultSceneHandle); + m_attachedSceneHandle = AzPhysics::InvalidSceneHandle; + Physics::DefaultWorldBus::BroadcastResult(m_attachedSceneHandle, &Physics::DefaultWorldRequests::GetDefaultSceneHandle); if (auto* sceneInterface = AZ::Interface::Get()) { - AzPhysics::SimulatedBodyHandle bodyHandle = sceneInterface->AddSimulatedBody(defaultSceneHandle, &ragdollConfiguration); - m_ragdoll = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(defaultSceneHandle, bodyHandle)); + m_ragdollHandle = sceneInterface->AddSimulatedBody(m_attachedSceneHandle, &ragdollConfiguration); } - if (m_ragdoll == nullptr) + auto* ragdoll = GetPhysXRagdoll(); + if (ragdoll == nullptr || + m_ragdollHandle == AzPhysics::InvalidSimulatedBodyHandle) { AZ_Error("PhysX Ragdoll Component", false, "Failed to create ragdoll."); return; } - + for (size_t nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) { - if (physx::PxRigidDynamic* pxRigidBody = m_ragdoll->GetPxRigidDynamic(nodeIndex)) + if (physx::PxRigidDynamic* pxRigidBody = ragdoll->GetPxRigidDynamic(nodeIndex)) { pxRigidBody->setSolverIterationCounts(m_positionIterations, m_velocityIterations); } @@ -352,7 +379,7 @@ namespace PhysX for (size_t nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) { - if (const AZStd::shared_ptr& joint = m_ragdoll->GetNode(nodeIndex)->GetJoint()) + if (const AZStd::shared_ptr& joint = ragdoll->GetNode(nodeIndex)->GetJoint()) { if (auto* pxJoint = static_cast(joint->GetNativePointer())) { @@ -374,20 +401,41 @@ namespace PhysX void RagdollComponent::DestroyRagdoll() { - if (m_ragdoll) + if (m_ragdollHandle != AzPhysics::InvalidSimulatedBodyHandle && + m_attachedSceneHandle != AzPhysics::InvalidSceneHandle) { AzFramework::RagdollPhysicsRequestBus::Handler::BusDisconnect(); - AzFramework::RagdollPhysicsNotificationBus::Event(GetEntityId(), - &AzFramework::RagdollPhysicsNotifications::OnRagdollDeactivated); + AzFramework::RagdollPhysicsNotificationBus::Event( + GetEntityId(), &AzFramework::RagdollPhysicsNotifications::OnRagdollDeactivated); if (auto* sceneInterface = AZ::Interface::Get()) { - sceneInterface->RemoveSimulatedBody(m_ragdoll->m_sceneOwner, m_ragdoll->m_bodyHandle); + sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_ragdollHandle); + m_attachedSceneHandle = AzPhysics::InvalidSceneHandle; } - m_ragdoll = nullptr; } } + Ragdoll* RagdollComponent::GetPhysXRagdoll() + { + return const_cast(static_cast(*this).GetPhysXRagdollConst()); + } + + const Ragdoll* RagdollComponent::GetPhysXRagdollConst() const + { + if (m_ragdollHandle == AzPhysics::InvalidSimulatedBodyHandle || + m_attachedSceneHandle == AzPhysics::InvalidSceneHandle) + { + return nullptr; + } + + if (auto* sceneInterface = AZ::Interface::Get()) + { + return azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_ragdollHandle)); + } + return nullptr; + } + // deprecated Cry functions void RagdollComponent::EnterRagdoll() { diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h index a02e9c47fb..2c265b0f73 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h @@ -104,10 +104,13 @@ namespace PhysX private: void CreateRagdoll(const Physics::RagdollConfiguration& ragdollConfiguration); void DestroyRagdoll(); + Ragdoll* GetPhysXRagdoll(); + const Ragdoll* GetPhysXRagdollConst() const; bool IsJointProjectionVisible(); - Ragdoll* m_ragdoll; + AzPhysics::SimulatedBodyHandle m_ragdollHandle = AzPhysics::InvalidSimulatedBodyHandle; + AzPhysics::SceneHandle m_attachedSceneHandle = AzPhysics::InvalidSceneHandle; /// Minimum number of position iterations to perform in the PhysX solver. /// Lower iteration counts are less expensive but may behave less realistically. AZ::u32 m_positionIterations = 16; From 9d94977b2cde555c1e352ada77eb87a57a967846 Mon Sep 17 00:00:00 2001 From: AMZN-stankowi Date: Thu, 27 May 2021 08:45:32 -0700 Subject: [PATCH 223/811] FbxImportRequestHandler is now loaded only once per AssetBuilder and Editor + re-enabled STL support (#933) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Revert "FBX settings can be opened again: g_fbxImporter is set, and if the ex… (#878)" This reverts commit 58adcf168fcab0da94b25004482a6edabb2b0fad. * Revert "Merge pull request #753 from aws-lumberyard-dev/Helios_DataDrivenAssetImporter" This reverts commit 798d96f1a2056cc71156797a88d96e0a67f1f9d3, reversing changes made to eb31d90ad94da7cca7a13b8e1385f1edc4bc42b4. * Revert "Revert "Merge pull request #753 from aws-lumberyard-dev/Helios_DataDrivenAssetImporter"" This reverts commit c1124f26d957388e88cc4990021314b5af247e1d. * Revert "Revert "FBX settings can be opened again: g_fbxImporter is set, and if the ex… (#878)"" This reverts commit 978477097892a22e83519646527ff52ba6532f35. * Fixed how FbxImportRequestHandler is loaded * Bumped version to force FBX to rebuild + removed unused variable * Revert "Revert "FBX settings can be opened again: g_fbxImporter is set, and if the ex… (#878)"" This reverts commit 978477097892a22e83519646527ff52ba6532f35. * Revert "Revert "Merge pull request #753 from aws-lumberyard-dev/Helios_DataDrivenAssetImporter"" This reverts commit c1124f26d957388e88cc4990021314b5af247e1d. * Fixed a bad revert * Better error reporting at AP launch * AZ_CRC -> AZ_CRC_CE and removed delayed reload of settings registry file now that it's available at startup * fixed typo in comment --- .../AssetImporterPlugin.cpp | 5 +++ .../native/utilities/ApplicationManager.cpp | 3 +- .../utilities/ApplicationManagerBase.cpp | 8 ++++ .../SceneAPI/FbxSceneBuilder/DllMain.cpp | 22 +--------- .../FbxImportRequestHandler.cpp | 44 ++++++++++++++++--- .../FbxSceneBuilder/FbxImportRequestHandler.h | 20 +++++++-- .../Importers/AssImpMeshImporter.cpp | 2 +- .../SceneCore/Events/AssetImportRequest.h | 5 +++ .../SceneBuilder/SceneBuilderComponent.cpp | 6 ++- .../SceneBuilder/SceneBuilderComponent.h | 2 + Registry/sceneassetimporter.setreg | 16 +++++++ 11 files changed, 100 insertions(+), 33 deletions(-) create mode 100644 Registry/sceneassetimporter.setreg diff --git a/Code/Sandbox/Plugins/EditorAssetImporter/AssetImporterPlugin.cpp b/Code/Sandbox/Plugins/EditorAssetImporter/AssetImporterPlugin.cpp index c04f81f50c..ba705295ae 100644 --- a/Code/Sandbox/Plugins/EditorAssetImporter/AssetImporterPlugin.cpp +++ b/Code/Sandbox/Plugins/EditorAssetImporter/AssetImporterPlugin.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -37,6 +38,10 @@ AssetImporterPlugin::AssetImporterPlugin(IEditor* editor) opt.showInMenu = false; // this view pane is used to display scene settings, but the user never opens it directly through the Tools menu opt.saveKeyName = "Scene Settings (PREVIEW)"; // user settings for this pane were originally saved with PREVIEW, so ensure that's how they are loaded as well, even after the PREVIEW is removed from the name AzToolsFramework::RegisterViewPane(m_toolName.c_str(), LyViewPane::CategoryTools, opt); + + AzToolsFramework::ToolsApplicationRequestBus::Broadcast( + &AzToolsFramework::ToolsApplicationRequests::CreateAndAddEntityFromComponentTags, + AZStd::vector({ AZ::SceneAPI::Events::AssetImportRequest::GetAssetImportRequestComponentTag() }), "AssetImportersEntity"); } void AssetImporterPlugin::Release() diff --git a/Code/Tools/AssetProcessor/native/utilities/ApplicationManager.cpp b/Code/Tools/AssetProcessor/native/utilities/ApplicationManager.cpp index c85801a074..579c7f93d3 100644 --- a/Code/Tools/AssetProcessor/native/utilities/ApplicationManager.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/ApplicationManager.cpp @@ -622,13 +622,14 @@ bool ApplicationManager::Activate() { if (!AssetUtilities::ComputeAssetRoot(m_systemRoot)) { + AZ_Error(AssetProcessor::ConsoleChannel, false, "Unable to compute the asset root for the project, this application cannot launch until this is fixed."); return false; } auto projectName = AssetUtilities::ComputeProjectName(); if (projectName.isEmpty()) { - AZ_Error(AssetProcessor::ConsoleChannel, false, "Unable to detect name of current game project. Is bootstrap.cfg appropriately configured?"); + AZ_Error(AssetProcessor::ConsoleChannel, false, "Unable to detect name of current game project. Configure your game project name to launch this application."); return false; } diff --git a/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.cpp b/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.cpp index a17819bba2..7c4f429da4 100644 --- a/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.cpp @@ -1191,6 +1191,7 @@ bool ApplicationManagerBase::Activate() QDir projectCache; if (!AssetUtilities::ComputeProjectCacheRoot(projectCache)) { + AZ_Error("AssetProcessor", false, "Could not compute project cache root, please configure your project correctly to launch Asset Processor."); return false; } @@ -1200,22 +1201,27 @@ bool ApplicationManagerBase::Activate() // Shutdown if the disk has less than 128MB of free space if (!CheckSufficientDiskSpace(projectCache.absolutePath(), 128 * 1024 * 1024, true)) { + // CheckSufficientDiskSpace reports an error if disk space is low. return false; } bool appInited = InitApplicationServer(); if (!appInited) { + AZ_Error( + "AssetProcessor", false, "InitApplicationServer failed, something internal to Asset Processor has failed, please report this to support if you encounter this error."); return false; } if (!InitAssetDatabase()) { + // AssetDatabaseConnection::OpenDatabase reports any errors it encounters. return false; } if (!ApplicationManager::Activate()) { + // ApplicationManager::Activate() reports any errors it encounters. return false; } @@ -1230,6 +1236,7 @@ bool ApplicationManagerBase::Activate() m_isCurrentlyLoadingGems = true; if (!ActivateModules()) { + // ActivateModules reports any errors it encounters. m_isCurrentlyLoadingGems = false; return false; } @@ -1299,6 +1306,7 @@ bool ApplicationManagerBase::Activate() { if (!m_applicationServer->startListening()) { + // startListening reports any errors it encounters. return false; } } diff --git a/Code/Tools/SceneAPI/FbxSceneBuilder/DllMain.cpp b/Code/Tools/SceneAPI/FbxSceneBuilder/DllMain.cpp index 3dc14814de..4ab41423fa 100644 --- a/Code/Tools/SceneAPI/FbxSceneBuilder/DllMain.cpp +++ b/Code/Tools/SceneAPI/FbxSceneBuilder/DllMain.cpp @@ -38,21 +38,8 @@ namespace AZ { namespace FbxSceneBuilder { - static AZ::SceneAPI::FbxSceneImporter::FbxImportRequestHandler* g_fbxImporter = nullptr; static AZStd::vector g_componentDescriptors; - void Initialize() - { - // Currently it's still needed to explicitly create an instance of this instead of letting - // it be a normal component. This is because ResourceCompilerScene needs to return - // the list of available extensions before it can start the application. - if (!g_fbxImporter) - { - g_fbxImporter = aznew AZ::SceneAPI::FbxSceneImporter::FbxImportRequestHandler(); - g_fbxImporter->Activate(); - } - } - void Reflect(AZ::SerializeContext* /*context*/) { // Descriptor registration is done in Reflect instead of Initialize because the ResourceCompilerScene initializes the libraries before @@ -64,6 +51,7 @@ namespace AZ { // Global importer and behavior g_componentDescriptors.push_back(FbxSceneBuilder::FbxImporter::CreateDescriptor()); + g_componentDescriptors.push_back(FbxSceneImporter::FbxImportRequestHandler::CreateDescriptor()); // Node and attribute importers g_componentDescriptors.push_back(AssImpBitangentStreamImporter::CreateDescriptor()); @@ -110,13 +98,6 @@ namespace AZ g_componentDescriptors.clear(); g_componentDescriptors.shrink_to_fit(); } - - if (g_fbxImporter) - { - g_fbxImporter->Deactivate(); - delete g_fbxImporter; - g_fbxImporter = nullptr; - } } } // namespace FbxSceneBuilder } // namespace SceneAPI @@ -125,7 +106,6 @@ namespace AZ extern "C" AZ_DLL_EXPORT void InitializeDynamicModule(void* env) { AZ::Environment::Attach(static_cast(env)); - AZ::SceneAPI::FbxSceneBuilder::Initialize(); } extern "C" AZ_DLL_EXPORT void Reflect(AZ::SerializeContext* context) { diff --git a/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImportRequestHandler.cpp b/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImportRequestHandler.cpp index 155209f1b5..a8b059304d 100644 --- a/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImportRequestHandler.cpp +++ b/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImportRequestHandler.cpp @@ -10,12 +10,16 @@ * */ +#include +#include #include -#include +#include +#include +#include +#include #include #include #include -#include namespace AZ { @@ -23,10 +27,23 @@ namespace AZ { namespace FbxSceneImporter { - const char* FbxImportRequestHandler::s_extension = ".fbx"; + void SceneImporterSettings::Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context); serializeContext) + { + serializeContext->Class() + ->Version(2) + ->Field("SupportedFileTypeExtensions", &SceneImporterSettings::m_supportedFileTypeExtensions); + } + } void FbxImportRequestHandler::Activate() { + if (auto* settingsRegistry = AZ::SettingsRegistry::Get()) + { + settingsRegistry->GetObject(m_settings, "/O3DE/SceneAPI/AssetImporter"); + } + BusConnect(); } @@ -37,21 +54,31 @@ namespace AZ void FbxImportRequestHandler::Reflect(ReflectContext* context) { + SceneImporterSettings::Reflect(context); + SerializeContext* serializeContext = azrtti_cast(context); if (serializeContext) { - serializeContext->Class()->Version(1); + serializeContext->Class()->Version(1)->Attribute( + AZ::Edit::Attributes::SystemComponentTags, + AZStd::vector( + {AssetBuilderSDK::ComponentTags::AssetBuilder, + AssetImportRequest::GetAssetImportRequestComponentTag()})); + } } void FbxImportRequestHandler::GetSupportedFileExtensions(AZStd::unordered_set& extensions) { - extensions.insert(s_extension); + extensions.insert(m_settings.m_supportedFileTypeExtensions.begin(), m_settings.m_supportedFileTypeExtensions.end()); } Events::LoadingResult FbxImportRequestHandler::LoadAsset(Containers::Scene& scene, const AZStd::string& path, const Uuid& guid, [[maybe_unused]] RequestingApplication requester) { - if (!AzFramework::StringFunc::Path::IsExtension(path.c_str(), s_extension)) + AZStd::string extension; + StringFunc::Path::GetExtension(path.c_str(), extension); + + if (!m_settings.m_supportedFileTypeExtensions.contains(extension)) { return Events::LoadingResult::Ignored; } @@ -73,6 +100,11 @@ namespace AZ return Events::LoadingResult::AssetFailure; } } + + void FbxImportRequestHandler::GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided) + { + provided.emplace_back(AZ_CRC_CE("AssetImportRequestHandler")); + } } // namespace Import } // namespace SceneAPI } // namespace AZ diff --git a/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImportRequestHandler.h b/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImportRequestHandler.h index 8b33051f1e..12c7c6f877 100644 --- a/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImportRequestHandler.h +++ b/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImportRequestHandler.h @@ -21,12 +21,21 @@ namespace AZ { namespace FbxSceneImporter { + struct SceneImporterSettings + { + AZ_TYPE_INFO(SceneImporterSettings, "{8BB6C7AD-BF99-44DC-9DA1-E7AD3F03DC10}"); + + static void Reflect(AZ::ReflectContext* context); + + AZStd::unordered_set m_supportedFileTypeExtensions; + }; + class FbxImportRequestHandler - : public SceneCore::BehaviorComponent + : public AZ::Component , public Events::AssetImportRequestBus::Handler { public: - AZ_COMPONENT(FbxImportRequestHandler, "{9F4B189C-0A96-4F44-A5F0-E087FF1561F8}", SceneCore::BehaviorComponent); + AZ_COMPONENT(FbxImportRequestHandler, "{9F4B189C-0A96-4F44-A5F0-E087FF1561F8}"); ~FbxImportRequestHandler() override = default; @@ -38,8 +47,13 @@ namespace AZ Events::LoadingResult LoadAsset(Containers::Scene& scene, const AZStd::string& path, const Uuid& guid, RequestingApplication requester) override; + static void GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided); + private: - static const char* s_extension; + + SceneImporterSettings m_settings; + + static constexpr const char* SettingsFilename = "AssetImporterSettings.json"; }; } // namespace FbxSceneImporter } // namespace SceneAPI diff --git a/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpMeshImporter.cpp b/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpMeshImporter.cpp index 193a1f9fd5..c0d1fc3bd0 100644 --- a/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpMeshImporter.cpp +++ b/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpMeshImporter.cpp @@ -37,7 +37,7 @@ namespace AZ SerializeContext* serializeContext = azrtti_cast(context); if (serializeContext) { - serializeContext->Class()->Version(1); + serializeContext->Class()->Version(2); } } diff --git a/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.h b/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.h index a2f9450bce..2deed280db 100644 --- a/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.h +++ b/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.h @@ -71,6 +71,11 @@ namespace AZ static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; using MutexType = AZStd::recursive_mutex; + static AZ::Crc32 GetAssetImportRequestComponentTag() + { + return AZ_CRC_CE("AssetImportRequest"); + } + virtual ~AssetImportRequest() = 0; //! Fills the given list with all available file extensions, excluding the extension for the manifest. diff --git a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.cpp b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.cpp index e71a5207d0..25faca3667 100644 --- a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.cpp +++ b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.cpp @@ -72,6 +72,11 @@ namespace SceneBuilder m_sceneBuilder.BusDisconnect(); } + void BuilderPluginComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + required.emplace_back(AZ_CRC_CE("AssetImportRequestHandler")); + } + void BuilderPluginComponent::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast(context); @@ -81,5 +86,4 @@ namespace SceneBuilder ->Attribute(AZ::Edit::Attributes::SystemComponentTags, AZStd::vector({ AssetBuilderSDK::ComponentTags::AssetBuilder })); } } - } // namespace SceneBuilder diff --git a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.h b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.h index c1fc6ebb36..aed5e1b026 100644 --- a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.h +++ b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.h @@ -32,6 +32,8 @@ namespace SceneBuilder void Activate() override; void Deactivate() override; + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + private: SceneBuilderWorker m_sceneBuilder; }; diff --git a/Registry/sceneassetimporter.setreg b/Registry/sceneassetimporter.setreg new file mode 100644 index 0000000000..bd7c4d0705 --- /dev/null +++ b/Registry/sceneassetimporter.setreg @@ -0,0 +1,16 @@ +{ + "O3DE": + { + "SceneAPI": + { + "AssetImporter": + { + "SupportedFileTypeExtensions": + [ + ".fbx", + ".stl" + ] + } + } + } +} \ No newline at end of file From 56942d0f68932939030ef97d1c56d9c8f79182fd Mon Sep 17 00:00:00 2001 From: AMZN-stankowi Date: Thu, 27 May 2021 09:27:54 -0700 Subject: [PATCH 224/811] Fixed periodic failing test. Updated for new combined meshes, plus added some additional debug printing on failures. (#954) --- .../PythonAssetBuilder/AssetBuilder_test.py | 14 +++++++------- .../PythonAssetBuilder/AssetBuilder_test_case.py | 16 ++++++++-------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py index 818dc23079..ecf08cfcbd 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py @@ -31,13 +31,13 @@ class TestPythonAssetProcessing(object): unexpected_lines = [] expected_lines = [ 'Mock asset exists', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_positive_1.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_negative_1.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_positive_1.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_negative_1.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_positive_1.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_negative_1.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center_1.azmodel) found' + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_positive.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_negative.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_positive.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_negative.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_positive.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_negative.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel) found' ] timeout = 180 halt_on_unexpected = False diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py index cd9adfdbcf..a7907778b2 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py @@ -38,16 +38,16 @@ def test_azmodel_product(generatedModelAssetPath, expectedSubId): assetId = azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, 'GetAssetIdByPath', generatedModelAssetPath, azModelAssetType, False) assetIdString = assetId.to_string() if (assetIdString.endswith(':' + expectedSubId) is False): - raise_and_stop(f'Asset has unexpected asset ID ({assetIdString}) for ({generatedModelAssetPath})!') + raise_and_stop(f'Asset at path {generatedModelAssetPath} has unexpected asset ID ({assetIdString}) for ({generatedModelAssetPath}), expected {expectedSubId}!') else: print(f'Expected subId for asset ({generatedModelAssetPath}) found') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_positive_1.azmodel', '10315ae0') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_negative_1.azmodel', '10661093') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_positive_1.azmodel', '10af8810') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_negative_1.azmodel', '10f8c263') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_positive_1.azmodel', '100ac47f') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_negative_1.azmodel', '105d8e0c') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center_1.azmodel', '1002d464') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_positive.azmodel', '1024be55') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_negative.azmodel', '1052c94e') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_positive.azmodel', '10130556') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_negative.azmodel', '1065724d') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_positive.azmodel', '10d16e68') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_negative.azmodel', '10a71973') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel', '10412075') azlmbr.editor.EditorToolsApplicationRequestBus(azlmbr.bus.Broadcast, 'ExitNoPrompt') From fd8fe8b9398ed6c31344a28cc3e76b2d82fb9f27 Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Thu, 27 May 2021 11:40:16 -0500 Subject: [PATCH 225/811] Fixed newly created level having the right source field set (#986) * Fixed an issue with the source field a newly created level not being set correctly --- .../Entity/PrefabEditorEntityOwnershipInterface.h | 2 +- .../Entity/PrefabEditorEntityOwnershipService.cpp | 6 +++--- .../Entity/PrefabEditorEntityOwnershipService.h | 4 +--- Code/Sandbox/Editor/CryEdit.cpp | 2 +- Code/Sandbox/Editor/CryEdit.h | 2 ++ 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h index a26c3b0ecf..32ea9db3da 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h @@ -57,6 +57,6 @@ namespace AzToolsFramework virtual void StartPlayInEditor() = 0; virtual void StopPlayInEditor() = 0; - virtual void CreateNewLevelPrefab(AZStd::string_view filename) = 0; + virtual void CreateNewLevelPrefab(AZStd::string_view filename, const AZStd::string& templateFilename) = 0; }; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index b2b36cc318..439789f11b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -265,7 +265,7 @@ namespace AzToolsFramework return false; } - void PrefabEditorEntityOwnershipService::CreateNewLevelPrefab(AZStd::string_view filename) + void PrefabEditorEntityOwnershipService::CreateNewLevelPrefab(AZStd::string_view filename, const AZStd::string& templateFilename) { AZ::IO::Path relativePath = m_loaderInterface->GetRelativePathToProject(filename); AzToolsFramework::Prefab::TemplateId templateId = m_prefabSystemComponent->GetTemplateIdFromFilePath(relativePath); @@ -276,7 +276,7 @@ namespace AzToolsFramework AZ::Data::AssetInfo assetInfo; bool sourceInfoFound = false; AzToolsFramework::AssetSystemRequestBus::BroadcastResult( - sourceInfoFound, &AzToolsFramework::AssetSystemRequestBus::Events::GetSourceInfoBySourcePath, DefaultLevelTemplateName, + sourceInfoFound, &AzToolsFramework::AssetSystemRequestBus::Events::GetSourceInfoBySourcePath, templateFilename.c_str(), assetInfo, watchFolder); if (sourceInfoFound) @@ -292,7 +292,7 @@ namespace AzToolsFramework levelDefaultDom.CopyFrom(dom, levelDefaultDom.GetAllocator()); Prefab::PrefabDomPath sourcePath("/Source"); - sourcePath.Set(levelDefaultDom, assetInfo.m_relativePath.c_str()); + sourcePath.Set(levelDefaultDom, relativePath.c_str()); templateId = m_prefabSystemComponent->AddTemplate(relativePath, AZStd::move(levelDefaultDom)); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h index 915cafd316..d8eb81dd40 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h @@ -170,7 +170,7 @@ namespace AzToolsFramework void StartPlayInEditor() override; void StopPlayInEditor() override; - void CreateNewLevelPrefab(AZStd::string_view filename) override; + void CreateNewLevelPrefab(AZStd::string_view filename, const AZStd::string& templateFilename) override; protected: @@ -218,7 +218,5 @@ namespace AzToolsFramework Prefab::PrefabLoaderInterface* m_loaderInterface; AzFramework::EntityContextId m_entityContextId; AZ::SerializeContext m_serializeContext; - - static inline constexpr const char* DefaultLevelTemplateName = "Prefabs/Default_Level.prefab"; }; } diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index 5fd6eb2692..a0ff5d7eff 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -3111,7 +3111,7 @@ CCryEditApp::ECreateLevelResult CCryEditApp::CreateLevel(const QString& levelNam auto* service = AZ::Interface::Get(); if (service) { - service->CreateNewLevelPrefab((const char*)fullyQualifiedLevelName.toUtf8()); + service->CreateNewLevelPrefab(fullyQualifiedLevelName.toUtf8().constData(), DefaultLevelTemplateName); } } diff --git a/Code/Sandbox/Editor/CryEdit.h b/Code/Sandbox/Editor/CryEdit.h index 2e71ca6a58..d4c1304b6a 100644 --- a/Code/Sandbox/Editor/CryEdit.h +++ b/Code/Sandbox/Editor/CryEdit.h @@ -358,6 +358,8 @@ AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING private: + static inline constexpr const char* DefaultLevelTemplateName = "Prefabs/Default_Level.prefab"; + struct PythonOutputHandler; AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING AZStd::shared_ptr m_pythonOutputHandler; From 7cd325bad901d9b159e9af78574045e453aa21c8 Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Thu, 27 May 2021 09:40:48 -0700 Subject: [PATCH 226/811] Adding ProjectManager as an Editor runtime dependency The project manager is needed by the editor if it does not know what project to use --- Code/Sandbox/Editor/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Sandbox/Editor/CMakeLists.txt b/Code/Sandbox/Editor/CMakeLists.txt index c62e05f012..4706a61d08 100644 --- a/Code/Sandbox/Editor/CMakeLists.txt +++ b/Code/Sandbox/Editor/CMakeLists.txt @@ -173,6 +173,7 @@ ly_add_target( RUNTIME_DEPENDENCIES Legacy::CrySystem Legacy::EditorLib + ProjectManager ) ly_add_translations( TARGETS Editor From 600f97a46c53f246b48a810950d690d3ea8720ad Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Thu, 27 May 2021 09:41:45 -0700 Subject: [PATCH 227/811] Updating DirectXShaderCompiler 3P Packages to use built-from-source version (#976) --- .../Linux/BuiltInPackages_linux.cmake | 71 +++++++-------- .../Platform/Mac/BuiltInPackages_mac.cmake | 72 +++++++-------- .../Windows/BuiltInPackages_windows.cmake | 88 +++++++++---------- 3 files changed, 116 insertions(+), 115 deletions(-) diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index 3cd453b943..3220271b42 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -10,40 +10,41 @@ # # 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 alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) -ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev9-multiplatform TARGETS assimplib PACKAGE_HASH 448530277b51b145ca43b96becd0266e29ae210fc9e2b45f5afe85f301a040e7) -ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) -ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) -ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) -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) -ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) -ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) -ly_associate_package(PACKAGE_NAME lz4-r128-multiplatform TARGETS lz4 PACKAGE_HASH d7b1d5651191db2c339827ad24f669d9d37754143e9173abc986184532f57c9d) -ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) -ly_associate_package(PACKAGE_NAME zstd-1.35-multiplatform TARGETS zstd PACKAGE_HASH 45d466c435f1095898578eedde85acf1fd27190e7ea99aeaa9acfd2f09e12665) -ly_associate_package(PACKAGE_NAME SQLite-3.32.2-rev3-multiplatform TARGETS SQLite PACKAGE_HASH dd4d3de6cbb4ce3d15fc504ba0ae0587e515dc89a25228037035fc0aef4831f4) -ly_associate_package(PACKAGE_NAME glad-2.0.0-beta-rev2-multiplatform TARGETS glad PACKAGE_HASH ff97ee9664e97d0854b52a3734c2289329d9f2b4cd69478df6d0ca1f1c9392ee) -ly_associate_package(PACKAGE_NAME lux_core-2.2-rev5-multiplatform TARGETS lux_core PACKAGE_HASH c8c13cf7bc351643e1abd294d0841b24dee60e51647dff13db7aec396ad1e0b5) -ly_associate_package(PACKAGE_NAME xxhash-0.7.4-rev1-multiplatform TARGETS xxhash PACKAGE_HASH e81f3e6c4065975833996dd1fcffe46c3cf0f9e3a4207ec5f4a1b564ba75861e) -ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform TARGETS PVRTexTool PACKAGE_HASH d0d6da61c7557de0d2c71fc35ba56c3be49555b703f0e853d4c58225537acf1e) +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 alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) +ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev9-multiplatform TARGETS assimplib PACKAGE_HASH 448530277b51b145ca43b96becd0266e29ae210fc9e2b45f5afe85f301a040e7) +ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) +ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) +ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) +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) +ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) +ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) +ly_associate_package(PACKAGE_NAME lz4-r128-multiplatform TARGETS lz4 PACKAGE_HASH d7b1d5651191db2c339827ad24f669d9d37754143e9173abc986184532f57c9d) +ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) +ly_associate_package(PACKAGE_NAME zstd-1.35-multiplatform TARGETS zstd PACKAGE_HASH 45d466c435f1095898578eedde85acf1fd27190e7ea99aeaa9acfd2f09e12665) +ly_associate_package(PACKAGE_NAME SQLite-3.32.2-rev3-multiplatform TARGETS SQLite PACKAGE_HASH dd4d3de6cbb4ce3d15fc504ba0ae0587e515dc89a25228037035fc0aef4831f4) +ly_associate_package(PACKAGE_NAME glad-2.0.0-beta-rev2-multiplatform TARGETS glad PACKAGE_HASH ff97ee9664e97d0854b52a3734c2289329d9f2b4cd69478df6d0ca1f1c9392ee) +ly_associate_package(PACKAGE_NAME lux_core-2.2-rev5-multiplatform TARGETS lux_core PACKAGE_HASH c8c13cf7bc351643e1abd294d0841b24dee60e51647dff13db7aec396ad1e0b5) +ly_associate_package(PACKAGE_NAME xxhash-0.7.4-rev1-multiplatform TARGETS xxhash PACKAGE_HASH e81f3e6c4065975833996dd1fcffe46c3cf0f9e3a4207ec5f4a1b564ba75861e) +ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform TARGETS PVRTexTool PACKAGE_HASH d0d6da61c7557de0d2c71fc35ba56c3be49555b703f0e853d4c58225537acf1e) # platform-specific: -ly_associate_package(PACKAGE_NAME AWSGameLiftServerSDK-3.4.1-rev1-linux TARGETS AWSGameLiftServerSDK PACKAGE_HASH a8149a95bd100384af6ade97e2b21a56173740d921e6c3da8188cd51554d39af) -ly_associate_package(PACKAGE_NAME freetype-2.10.4.14-linux TARGETS freetype PACKAGE_HASH 9ad246873067717962c6b780d28a5ce3cef3321b73c9aea746a039c798f52e93) -ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-linux TARGETS tiff PACKAGE_HASH ae92b4d3b189c42ef644abc5cac865d1fb2eb7cb5622ec17e35642b00d1a0a76) -ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev4-linux TARGETS AWSNativeSDK PACKAGE_HASH b4db38de49d35a5f7500aed7f4aee5ec511dd3b584ee06fe9097885690191a5d) -ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev5-linux TARGETS Lua PACKAGE_HASH 1adc812abe3dd0dbb2ca9756f81d8f0e0ba45779ac85bf1d8455b25c531a38b0) -ly_associate_package(PACKAGE_NAME PhysX-4.1.0.25992954-rev1-linux TARGETS PhysX PACKAGE_HASH e3ca36106a8dbf1524709f8bb82d520920ebd3ff3a92672d382efff406c75ee3) -ly_associate_package(PACKAGE_NAME etc2comp-9cd0f9cae0-rev1-linux TARGETS etc2comp PACKAGE_HASH 9283aa5db5bb7fb90a0ddb7a9f3895317c8ebe8044943124bbb3673a41407430) -ly_associate_package(PACKAGE_NAME mcpp-2.7.2_az.1-rev1-linux TARGETS mcpp PACKAGE_HASH 0aa713f3f2c156cb2f17d9b800aed8acf9df5ab167c48b679853ecb040da9a67) -ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-linux TARGETS mikkelsen PACKAGE_HASH 5973b1e71a64633588eecdb5b5c06ca0081f7be97230f6ef64365cbda315b9c8) -ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-linux TARGETS googletest PACKAGE_HASH 7b7ad330f369450c316a4c4592d17fbb4c14c731c95bd8f37757203e8c2bbc1b) -ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-linux TARGETS GoogleBenchmark PACKAGE_HASH 4038878f337fc7e0274f0230f71851b385b2e0327c495fc3dd3d1c18a807928d) -ly_associate_package(PACKAGE_NAME unwind-1.2.1-linux TARGETS unwind PACKAGE_HASH 3453265fb056e25432f611a61546a25f60388e315515ad39007b5925dd054a77) -ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-linux TARGETS Qt PACKAGE_HASH b7d9932647f4b138b3f0b124d70debd250d2a8a6dca52b04dcbe82c6369d48ca) -ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-linux TARGETS libsamplerate PACKAGE_HASH 41643c31bc6b7d037f895f89d8d8d6369e906b92eff42b0fe05ee6a100f06261) -ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev2-linux TARGETS OpenSSL PACKAGE_HASH b779426d1e9c5ddf71160d5ae2e639c3b956e0fb5e9fcaf9ce97c4526024e3bc) +ly_associate_package(PACKAGE_NAME AWSGameLiftServerSDK-3.4.1-rev1-linux TARGETS AWSGameLiftServerSDK PACKAGE_HASH a8149a95bd100384af6ade97e2b21a56173740d921e6c3da8188cd51554d39af) +ly_associate_package(PACKAGE_NAME freetype-2.10.4.14-linux TARGETS freetype PACKAGE_HASH 9ad246873067717962c6b780d28a5ce3cef3321b73c9aea746a039c798f52e93) +ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-linux TARGETS tiff PACKAGE_HASH ae92b4d3b189c42ef644abc5cac865d1fb2eb7cb5622ec17e35642b00d1a0a76) +ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev4-linux TARGETS AWSNativeSDK PACKAGE_HASH b4db38de49d35a5f7500aed7f4aee5ec511dd3b584ee06fe9097885690191a5d) +ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev5-linux TARGETS Lua PACKAGE_HASH 1adc812abe3dd0dbb2ca9756f81d8f0e0ba45779ac85bf1d8455b25c531a38b0) +ly_associate_package(PACKAGE_NAME PhysX-4.1.0.25992954-rev1-linux TARGETS PhysX PACKAGE_HASH e3ca36106a8dbf1524709f8bb82d520920ebd3ff3a92672d382efff406c75ee3) +ly_associate_package(PACKAGE_NAME etc2comp-9cd0f9cae0-rev1-linux TARGETS etc2comp PACKAGE_HASH 9283aa5db5bb7fb90a0ddb7a9f3895317c8ebe8044943124bbb3673a41407430) +ly_associate_package(PACKAGE_NAME mcpp-2.7.2_az.1-rev1-linux TARGETS mcpp PACKAGE_HASH 0aa713f3f2c156cb2f17d9b800aed8acf9df5ab167c48b679853ecb040da9a67) +ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-linux TARGETS mikkelsen PACKAGE_HASH 5973b1e71a64633588eecdb5b5c06ca0081f7be97230f6ef64365cbda315b9c8) +ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-linux TARGETS googletest PACKAGE_HASH 7b7ad330f369450c316a4c4592d17fbb4c14c731c95bd8f37757203e8c2bbc1b) +ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-linux TARGETS GoogleBenchmark PACKAGE_HASH 4038878f337fc7e0274f0230f71851b385b2e0327c495fc3dd3d1c18a807928d) +ly_associate_package(PACKAGE_NAME unwind-1.2.1-linux TARGETS unwind PACKAGE_HASH 3453265fb056e25432f611a61546a25f60388e315515ad39007b5925dd054a77) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-linux TARGETS Qt PACKAGE_HASH b7d9932647f4b138b3f0b124d70debd250d2a8a6dca52b04dcbe82c6369d48ca) +ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-linux TARGETS libsamplerate PACKAGE_HASH 41643c31bc6b7d037f895f89d8d8d6369e906b92eff42b0fe05ee6a100f06261) +ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev2-linux TARGETS OpenSSL PACKAGE_HASH b779426d1e9c5ddf71160d5ae2e639c3b956e0fb5e9fcaf9ce97c4526024e3bc) +ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev2-linux TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 235606f98512c076a1ba84a8402ad24ac21945998abcea264e8e204678efc0ba) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index cf5ecaa15b..f85048d13e 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -10,41 +10,41 @@ # # 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 alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) -ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev9-multiplatform TARGETS assimplib PACKAGE_HASH 448530277b51b145ca43b96becd0266e29ae210fc9e2b45f5afe85f301a040e7) -ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) -ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) -ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) -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) -ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) -ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) -ly_associate_package(PACKAGE_NAME lz4-r128-multiplatform TARGETS lz4 PACKAGE_HASH d7b1d5651191db2c339827ad24f669d9d37754143e9173abc986184532f57c9d) -ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) -ly_associate_package(PACKAGE_NAME zstd-1.35-multiplatform TARGETS zstd PACKAGE_HASH 45d466c435f1095898578eedde85acf1fd27190e7ea99aeaa9acfd2f09e12665) -ly_associate_package(PACKAGE_NAME SQLite-3.32.2-rev3-multiplatform TARGETS SQLite PACKAGE_HASH dd4d3de6cbb4ce3d15fc504ba0ae0587e515dc89a25228037035fc0aef4831f4) -ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-mac TARGETS SPIRVCross PACKAGE_HASH 78c6376ed2fd195b9b1f5fb2b56e5267a32c3aa21fb399e905308de470eb4515) -ly_associate_package(PACKAGE_NAME DirectXShaderCompiler-1.6.2104-o3de-rev1-mac TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 4e97484f8fcf73fc39f22fc85ae86933a8f2e3ba0748fcec128bce05795035a6) -ly_associate_package(PACKAGE_NAME azslc-1.7.21-rev1-multiplatform TARGETS azslc PACKAGE_HASH 772b7a2d9cc68aa1da4f0ee7db57ee1b4e7a8f20b81961fc5849af779582f4df) -ly_associate_package(PACKAGE_NAME glad-2.0.0-beta-rev2-multiplatform TARGETS glad PACKAGE_HASH ff97ee9664e97d0854b52a3734c2289329d9f2b4cd69478df6d0ca1f1c9392ee) -ly_associate_package(PACKAGE_NAME lux_core-2.2-rev5-multiplatform TARGETS lux_core PACKAGE_HASH c8c13cf7bc351643e1abd294d0841b24dee60e51647dff13db7aec396ad1e0b5) -ly_associate_package(PACKAGE_NAME xxhash-0.7.4-rev1-multiplatform TARGETS xxhash PACKAGE_HASH e81f3e6c4065975833996dd1fcffe46c3cf0f9e3a4207ec5f4a1b564ba75861e) -ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform TARGETS PVRTexTool PACKAGE_HASH d0d6da61c7557de0d2c71fc35ba56c3be49555b703f0e853d4c58225537acf1e) +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 alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) +ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev9-multiplatform TARGETS assimplib PACKAGE_HASH 448530277b51b145ca43b96becd0266e29ae210fc9e2b45f5afe85f301a040e7) +ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) +ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) +ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) +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) +ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) +ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) +ly_associate_package(PACKAGE_NAME lz4-r128-multiplatform TARGETS lz4 PACKAGE_HASH d7b1d5651191db2c339827ad24f669d9d37754143e9173abc986184532f57c9d) +ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) +ly_associate_package(PACKAGE_NAME zstd-1.35-multiplatform TARGETS zstd PACKAGE_HASH 45d466c435f1095898578eedde85acf1fd27190e7ea99aeaa9acfd2f09e12665) +ly_associate_package(PACKAGE_NAME SQLite-3.32.2-rev3-multiplatform TARGETS SQLite PACKAGE_HASH dd4d3de6cbb4ce3d15fc504ba0ae0587e515dc89a25228037035fc0aef4831f4) +ly_associate_package(PACKAGE_NAME azslc-1.7.21-rev1-multiplatform TARGETS azslc PACKAGE_HASH 772b7a2d9cc68aa1da4f0ee7db57ee1b4e7a8f20b81961fc5849af779582f4df) +ly_associate_package(PACKAGE_NAME glad-2.0.0-beta-rev2-multiplatform TARGETS glad PACKAGE_HASH ff97ee9664e97d0854b52a3734c2289329d9f2b4cd69478df6d0ca1f1c9392ee) +ly_associate_package(PACKAGE_NAME lux_core-2.2-rev5-multiplatform TARGETS lux_core PACKAGE_HASH c8c13cf7bc351643e1abd294d0841b24dee60e51647dff13db7aec396ad1e0b5) +ly_associate_package(PACKAGE_NAME xxhash-0.7.4-rev1-multiplatform TARGETS xxhash PACKAGE_HASH e81f3e6c4065975833996dd1fcffe46c3cf0f9e3a4207ec5f4a1b564ba75861e) +ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform TARGETS PVRTexTool PACKAGE_HASH d0d6da61c7557de0d2c71fc35ba56c3be49555b703f0e853d4c58225537acf1e) # platform-specific: -ly_associate_package(PACKAGE_NAME freetype-2.10.4.14-mac-ios TARGETS freetype PACKAGE_HASH 67b4f57aed92082d3fd7c16aa244a7d908d90122c296b0a63f73e0a0b8761977) -ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-mac-ios TARGETS tiff PACKAGE_HASH a23ae1f8991a29f8e5df09d6d5b00d7768a740f90752cef465558c1768343709) -ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev3-mac TARGETS AWSNativeSDK PACKAGE_HASH 21920372e90355407578b45ac19580df1463a39a25a867bcd0ffd8b385c8254a) -ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev6-mac TARGETS Lua PACKAGE_HASH b9079fd35634774c9269028447562c6b712dbc83b9c64975c095fd423ff04c08) -ly_associate_package(PACKAGE_NAME PhysX-4.1.0.25992954-rev1-mac TARGETS PhysX PACKAGE_HASH 149f5e9b44bd27291b1c4772f5e89a1e0efa88eef73c7e0b188935ed4d0c4a70) -ly_associate_package(PACKAGE_NAME etc2comp-9cd0f9cae0-rev1-mac TARGETS etc2comp PACKAGE_HASH 1966ab101c89db7ecf30984917e0a48c0d02ee0e4d65b798743842b9469c0818) -ly_associate_package(PACKAGE_NAME mcpp-2.7.2_az.1-rev1-mac TARGETS mcpp PACKAGE_HASH 48a9c5197bf72843fb9ac44825501ee16bbe3e72e086a32b8c9c05bf47db12ab) -ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-mac TARGETS mikkelsen PACKAGE_HASH 83af99ca8bee123684ad254263add556f0cf49486c0b3e32e6d303535714e505) -ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-mac TARGETS googletest PACKAGE_HASH cbf020d5ef976c5db8b6e894c6c63151ade85ed98e7c502729dd20172acae5a8) -ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-mac TARGETS GoogleBenchmark PACKAGE_HASH ad25de0146769c91e179953d845de2bec8ed4a691f973f47e3eb37639381f665) -ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev1-mac TARGETS OpenSSL PACKAGE_HASH 28adc1c0616ac0482b2a9d7b4a3a3635a1020e87b163f8aba687c501cf35f96c) -ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-mac TARGETS Qt PACKAGE_HASH 4723ac43b19d4633c3fa4b9642f27c992d30cdc689f769f82869786f1c22a728) -ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-mac TARGETS libsamplerate PACKAGE_HASH b912af40c0ac197af9c43d85004395ba92a6a859a24b7eacd920fed5854a97fe) +ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev2-mac TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 2bede9a7ef3573027c005e38139237559eebf845c13ffb54c33c5b8675f962e2) +ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-mac TARGETS SPIRVCross PACKAGE_HASH 78c6376ed2fd195b9b1f5fb2b56e5267a32c3aa21fb399e905308de470eb4515) +ly_associate_package(PACKAGE_NAME freetype-2.10.4.14-mac-ios TARGETS freetype PACKAGE_HASH 67b4f57aed92082d3fd7c16aa244a7d908d90122c296b0a63f73e0a0b8761977) +ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-mac-ios TARGETS tiff PACKAGE_HASH a23ae1f8991a29f8e5df09d6d5b00d7768a740f90752cef465558c1768343709) +ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev3-mac TARGETS AWSNativeSDK PACKAGE_HASH 21920372e90355407578b45ac19580df1463a39a25a867bcd0ffd8b385c8254a) +ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev6-mac TARGETS Lua PACKAGE_HASH b9079fd35634774c9269028447562c6b712dbc83b9c64975c095fd423ff04c08) +ly_associate_package(PACKAGE_NAME PhysX-4.1.0.25992954-rev1-mac TARGETS PhysX PACKAGE_HASH 149f5e9b44bd27291b1c4772f5e89a1e0efa88eef73c7e0b188935ed4d0c4a70) +ly_associate_package(PACKAGE_NAME etc2comp-9cd0f9cae0-rev1-mac TARGETS etc2comp PACKAGE_HASH 1966ab101c89db7ecf30984917e0a48c0d02ee0e4d65b798743842b9469c0818) +ly_associate_package(PACKAGE_NAME mcpp-2.7.2_az.1-rev1-mac TARGETS mcpp PACKAGE_HASH 48a9c5197bf72843fb9ac44825501ee16bbe3e72e086a32b8c9c05bf47db12ab) +ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-mac TARGETS mikkelsen PACKAGE_HASH 83af99ca8bee123684ad254263add556f0cf49486c0b3e32e6d303535714e505) +ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-mac TARGETS googletest PACKAGE_HASH cbf020d5ef976c5db8b6e894c6c63151ade85ed98e7c502729dd20172acae5a8) +ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-mac TARGETS GoogleBenchmark PACKAGE_HASH ad25de0146769c91e179953d845de2bec8ed4a691f973f47e3eb37639381f665) +ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev1-mac TARGETS OpenSSL PACKAGE_HASH 28adc1c0616ac0482b2a9d7b4a3a3635a1020e87b163f8aba687c501cf35f96c) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-mac TARGETS Qt PACKAGE_HASH 4723ac43b19d4633c3fa4b9642f27c992d30cdc689f769f82869786f1c22a728) +ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-mac TARGETS libsamplerate PACKAGE_HASH b912af40c0ac197af9c43d85004395ba92a6a859a24b7eacd920fed5854a97fe) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index 8fc009c601..fa1326b63d 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -10,49 +10,49 @@ # # 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 alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) -ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev9-multiplatform TARGETS assimplib PACKAGE_HASH 448530277b51b145ca43b96becd0266e29ae210fc9e2b45f5afe85f301a040e7) -ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) -ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) -ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) -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) -ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) -ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) -ly_associate_package(PACKAGE_NAME lz4-r128-multiplatform TARGETS lz4 PACKAGE_HASH d7b1d5651191db2c339827ad24f669d9d37754143e9173abc986184532f57c9d) -ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) -ly_associate_package(PACKAGE_NAME zstd-1.35-multiplatform TARGETS zstd PACKAGE_HASH 45d466c435f1095898578eedde85acf1fd27190e7ea99aeaa9acfd2f09e12665) -ly_associate_package(PACKAGE_NAME SQLite-3.32.2-rev3-multiplatform TARGETS SQLite PACKAGE_HASH dd4d3de6cbb4ce3d15fc504ba0ae0587e515dc89a25228037035fc0aef4831f4) -ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-windows TARGETS SPIRVCross PACKAGE_HASH 7d601ea9d625b1d509d38bd132a1f433d7e895b16adab76bac6103567a7a6817) -ly_associate_package(PACKAGE_NAME DirectXShaderCompiler-1.6.2104-o3de-rev1-windows TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 2c60297758d73f7833911e5ae3006fe0b10ced6e0b1b54764b33ae2b86e0d41d) -ly_associate_package(PACKAGE_NAME azslc-1.7.21-rev1-multiplatform TARGETS azslc PACKAGE_HASH 772b7a2d9cc68aa1da4f0ee7db57ee1b4e7a8f20b81961fc5849af779582f4df) -ly_associate_package(PACKAGE_NAME glad-2.0.0-beta-rev2-multiplatform TARGETS glad PACKAGE_HASH ff97ee9664e97d0854b52a3734c2289329d9f2b4cd69478df6d0ca1f1c9392ee) -ly_associate_package(PACKAGE_NAME lux_core-2.2-rev5-multiplatform TARGETS lux_core PACKAGE_HASH c8c13cf7bc351643e1abd294d0841b24dee60e51647dff13db7aec396ad1e0b5) -ly_associate_package(PACKAGE_NAME xxhash-0.7.4-rev1-multiplatform TARGETS xxhash PACKAGE_HASH e81f3e6c4065975833996dd1fcffe46c3cf0f9e3a4207ec5f4a1b564ba75861e) -ly_associate_package(PACKAGE_NAME Blast-1.1.7-rev1-multiplatform TARGETS Blast PACKAGE_HASH 36b8f393bcd25d0f85cfc7a831ebbdac881e6054c4f0735649966aa6aa86e6f0) -ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform TARGETS PVRTexTool PACKAGE_HASH d0d6da61c7557de0d2c71fc35ba56c3be49555b703f0e853d4c58225537acf1e) +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 alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) +ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev9-multiplatform TARGETS assimplib PACKAGE_HASH 448530277b51b145ca43b96becd0266e29ae210fc9e2b45f5afe85f301a040e7) +ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) +ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) +ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) +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) +ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) +ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) +ly_associate_package(PACKAGE_NAME lz4-r128-multiplatform TARGETS lz4 PACKAGE_HASH d7b1d5651191db2c339827ad24f669d9d37754143e9173abc986184532f57c9d) +ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) +ly_associate_package(PACKAGE_NAME zstd-1.35-multiplatform TARGETS zstd PACKAGE_HASH 45d466c435f1095898578eedde85acf1fd27190e7ea99aeaa9acfd2f09e12665) +ly_associate_package(PACKAGE_NAME SQLite-3.32.2-rev3-multiplatform TARGETS SQLite PACKAGE_HASH dd4d3de6cbb4ce3d15fc504ba0ae0587e515dc89a25228037035fc0aef4831f4) +ly_associate_package(PACKAGE_NAME azslc-1.7.21-rev1-multiplatform TARGETS azslc PACKAGE_HASH 772b7a2d9cc68aa1da4f0ee7db57ee1b4e7a8f20b81961fc5849af779582f4df) +ly_associate_package(PACKAGE_NAME glad-2.0.0-beta-rev2-multiplatform TARGETS glad PACKAGE_HASH ff97ee9664e97d0854b52a3734c2289329d9f2b4cd69478df6d0ca1f1c9392ee) +ly_associate_package(PACKAGE_NAME lux_core-2.2-rev5-multiplatform TARGETS lux_core PACKAGE_HASH c8c13cf7bc351643e1abd294d0841b24dee60e51647dff13db7aec396ad1e0b5) +ly_associate_package(PACKAGE_NAME xxhash-0.7.4-rev1-multiplatform TARGETS xxhash PACKAGE_HASH e81f3e6c4065975833996dd1fcffe46c3cf0f9e3a4207ec5f4a1b564ba75861e) +ly_associate_package(PACKAGE_NAME Blast-1.1.7-rev1-multiplatform TARGETS Blast PACKAGE_HASH 36b8f393bcd25d0f85cfc7a831ebbdac881e6054c4f0735649966aa6aa86e6f0) +ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform TARGETS PVRTexTool PACKAGE_HASH d0d6da61c7557de0d2c71fc35ba56c3be49555b703f0e853d4c58225537acf1e) # platform-specific: -ly_associate_package(PACKAGE_NAME AWSGameLiftServerSDK-3.4.1-rev1-windows TARGETS AWSGameLiftServerSDK PACKAGE_HASH a0586b006e4def65cc25f388de17dc475e417dc1e6f9d96749777c88aa8271b0) -ly_associate_package(PACKAGE_NAME freetype-2.10.4.14-windows TARGETS freetype PACKAGE_HASH 88dedc86ccb8c92f14c2c033e51ee7d828fa08eafd6475c6aa963938a99f4bf3) -ly_associate_package(PACKAGE_NAME tiff-4.2.0.14-windows TARGETS tiff PACKAGE_HASH ab60d1398e4e1e375ec0f1a00cdb1d812a07c0096d827db575ce52dd6d714207) -ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev3-windows TARGETS AWSNativeSDK PACKAGE_HASH 929873d4252c464620a9d288e41bd5d47c0bd22750aeb3a1caa68a3da8247c48) -ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev5-windows TARGETS Lua PACKAGE_HASH 136faccf1f73891e3fa3b95f908523187792e56f5b92c63c6a6d7e72d1158d40) -ly_associate_package(PACKAGE_NAME PhysX-4.1.0.25992954-rev1-windows TARGETS PhysX PACKAGE_HASH 198bed89d1aae7caaf5dadba24cee56235fe41725d004b64040d4e50d0f3aa1a) -ly_associate_package(PACKAGE_NAME etc2comp-9cd0f9cae0-rev1-windows TARGETS etc2comp PACKAGE_HASH fc9ae937b2ec0d42d5e7d0e9e8c80e5e4d257673fb33bc9b7d6db76002117123) -ly_associate_package(PACKAGE_NAME mcpp-2.7.2_az.1-rev1-windows TARGETS mcpp PACKAGE_HASH 511672598fa319bfb8db87f965b59abff1620bb7c1dcf7669e039a8acd8d3ff8) -ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-windows TARGETS mikkelsen PACKAGE_HASH 872c4d245a1c86139aa929f2b465b63ea4ea55b04ced50309135dd4597457a4e) -ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-windows TARGETS googletest PACKAGE_HASH 7e8f03ae8a01563124e3daa06386f25a2b311c10bb95bff05cae6c41eff83837) -ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-windows TARGETS GoogleBenchmark PACKAGE_HASH 0c94ca69ae8e7e4aab8e90032b5c82c5964410429f3dd9dbb1f9bf4fe032b1d4) -ly_associate_package(PACKAGE_NAME d3dx12-headers-rev1-windows TARGETS d3dx12 PACKAGE_HASH 088c637159fba4a3e4c0cf08fb4921906fd4cca498939bd239db7c54b5b2f804) -ly_associate_package(PACKAGE_NAME pyside2-qt-5.15.1-rev2-windows TARGETS pyside2 PACKAGE_HASH c90f3efcc7c10e79b22a33467855ad861f9dbd2e909df27a5cba9db9fa3edd0f) -ly_associate_package(PACKAGE_NAME openimageio-2.1.16.0-rev2-windows TARGETS OpenImageIO PACKAGE_HASH 85a2a6cf35cbc4c967c56ca8074babf0955c5b490c90c6e6fd23c78db99fc282) -ly_associate_package(PACKAGE_NAME qt-5.15.2-rev2-windows TARGETS Qt PACKAGE_HASH 29966f22ec253dc9904e88ad48fe6b6a669302b2dc7049f2e2bbd4949e79e595) -ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-windows TARGETS libsamplerate PACKAGE_HASH dcf3c11a96f212a52e2c9241abde5c364ee90b0f32fe6eeb6dcdca01d491829f) -ly_associate_package(PACKAGE_NAME OpenMesh-8.1-rev1-windows TARGETS OpenMesh PACKAGE_HASH 1c1df639358526c368e790dfce40c45cbdfcfb1c9a041b9d7054a8949d88ee77) -ly_associate_package(PACKAGE_NAME civetweb-1.8-rev1-windows TARGETS civetweb PACKAGE_HASH 36d0e58a59bcdb4dd70493fb1b177aa0354c945b06c30416348fd326cf323dd4) -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 AWSGameLiftServerSDK-3.4.1-rev1-windows TARGETS AWSGameLiftServerSDK PACKAGE_HASH a0586b006e4def65cc25f388de17dc475e417dc1e6f9d96749777c88aa8271b0) +ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev2-windows TARGETS DirectXShaderCompilerDxc PACKAGE_HASH decc53e97c7ddda9c7f853a30af7808a7b652a912f59ad2cd4bca5d308aae2c4) +ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-windows TARGETS SPIRVCross PACKAGE_HASH 7d601ea9d625b1d509d38bd132a1f433d7e895b16adab76bac6103567a7a6817) +ly_associate_package(PACKAGE_NAME freetype-2.10.4.14-windows TARGETS freetype PACKAGE_HASH 88dedc86ccb8c92f14c2c033e51ee7d828fa08eafd6475c6aa963938a99f4bf3) +ly_associate_package(PACKAGE_NAME tiff-4.2.0.14-windows TARGETS tiff PACKAGE_HASH ab60d1398e4e1e375ec0f1a00cdb1d812a07c0096d827db575ce52dd6d714207) +ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev3-windows TARGETS AWSNativeSDK PACKAGE_HASH 929873d4252c464620a9d288e41bd5d47c0bd22750aeb3a1caa68a3da8247c48) +ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev5-windows TARGETS Lua PACKAGE_HASH 136faccf1f73891e3fa3b95f908523187792e56f5b92c63c6a6d7e72d1158d40) +ly_associate_package(PACKAGE_NAME PhysX-4.1.0.25992954-rev1-windows TARGETS PhysX PACKAGE_HASH 198bed89d1aae7caaf5dadba24cee56235fe41725d004b64040d4e50d0f3aa1a) +ly_associate_package(PACKAGE_NAME etc2comp-9cd0f9cae0-rev1-windows TARGETS etc2comp PACKAGE_HASH fc9ae937b2ec0d42d5e7d0e9e8c80e5e4d257673fb33bc9b7d6db76002117123) +ly_associate_package(PACKAGE_NAME mcpp-2.7.2_az.1-rev1-windows TARGETS mcpp PACKAGE_HASH 511672598fa319bfb8db87f965b59abff1620bb7c1dcf7669e039a8acd8d3ff8) +ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-windows TARGETS mikkelsen PACKAGE_HASH 872c4d245a1c86139aa929f2b465b63ea4ea55b04ced50309135dd4597457a4e) +ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-windows TARGETS googletest PACKAGE_HASH 7e8f03ae8a01563124e3daa06386f25a2b311c10bb95bff05cae6c41eff83837) +ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-windows TARGETS GoogleBenchmark PACKAGE_HASH 0c94ca69ae8e7e4aab8e90032b5c82c5964410429f3dd9dbb1f9bf4fe032b1d4) +ly_associate_package(PACKAGE_NAME d3dx12-headers-rev1-windows TARGETS d3dx12 PACKAGE_HASH 088c637159fba4a3e4c0cf08fb4921906fd4cca498939bd239db7c54b5b2f804) +ly_associate_package(PACKAGE_NAME pyside2-qt-5.15.1-rev2-windows TARGETS pyside2 PACKAGE_HASH c90f3efcc7c10e79b22a33467855ad861f9dbd2e909df27a5cba9db9fa3edd0f) +ly_associate_package(PACKAGE_NAME openimageio-2.1.16.0-rev2-windows TARGETS OpenImageIO PACKAGE_HASH 85a2a6cf35cbc4c967c56ca8074babf0955c5b490c90c6e6fd23c78db99fc282) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev2-windows TARGETS Qt PACKAGE_HASH 29966f22ec253dc9904e88ad48fe6b6a669302b2dc7049f2e2bbd4949e79e595) +ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-windows TARGETS libsamplerate PACKAGE_HASH dcf3c11a96f212a52e2c9241abde5c364ee90b0f32fe6eeb6dcdca01d491829f) +ly_associate_package(PACKAGE_NAME OpenMesh-8.1-rev1-windows TARGETS OpenMesh PACKAGE_HASH 1c1df639358526c368e790dfce40c45cbdfcfb1c9a041b9d7054a8949d88ee77) +ly_associate_package(PACKAGE_NAME civetweb-1.8-rev1-windows TARGETS civetweb PACKAGE_HASH 36d0e58a59bcdb4dd70493fb1b177aa0354c945b06c30416348fd326cf323dd4) +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) From b206e7ffe5bb88dc1194dd439c97fae3dbd6b24b Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Thu, 27 May 2021 09:58:58 -0700 Subject: [PATCH 228/811] ATOM-15295 Remove Unnecessary Enable Material Properties The only remaining unnecessary enable flag I found was for the parallax property group. It is removed, and now we just use the texture map and useTexture flag to gate whether the feature is enabled. --- .../Materials/Types/EnhancedPBR.materialtype | 14 ++++---- .../Materials/Types/StandardPBR.materialtype | 14 ++++---- .../Types/StandardPBR_ParallaxState.lua | 32 +++++++++++-------- .../Types/StandardPBR_ShaderEnable.lua | 6 ++-- .../TestData/Materials/ParallaxRock.material | 1 - .../012_Parallax_POM.material | 1 - .../012_Parallax_POM_Cutout.material | 1 - .../100_UvTiling_Parallax_A.material | 1 - .../100_UvTiling_Parallax_B.material | 1 - .../Materials/Bricks038_8K/bricks038.material | 1 - .../Concrete016_8K/Concrete016.material | 3 +- .../Materials/Fabric001_8K/Fabric001.material | 1 - .../Materials/Fabric030_4K/Fabric030.material | 1 - .../PaintedPlaster015.material | 1 - .../Assets/Materials/baseboards.material | 3 +- .../Assets/Materials/crown.material | 1 - .../ConcreteStucco/concrete_stucco.material | 3 +- .../Assets/objects/sponza_mat_arch.material | 3 +- .../objects/sponza_mat_background.material | 3 +- .../Assets/objects/sponza_mat_bricks.material | 3 +- .../objects/sponza_mat_ceiling.material | 3 +- .../objects/sponza_mat_columna.material | 3 +- .../objects/sponza_mat_columnb.material | 3 +- .../objects/sponza_mat_columnc.material | 3 +- .../objects/sponza_mat_details.material | 3 +- .../objects/sponza_mat_flagpole.material | 3 +- .../Assets/objects/sponza_mat_floor.material | 3 +- .../Assets/objects/sponza_mat_leaf.material | 3 +- .../Assets/objects/sponza_mat_lion.material | 1 - .../Assets/objects/sponza_mat_roof.material | 3 +- .../Assets/objects/sponza_mat_vase.material | 3 +- .../objects/sponza_mat_vasehanging.material | 3 +- .../objects/sponza_mat_vaseround.material | 3 +- 33 files changed, 72 insertions(+), 59 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index 36ebb3a0ca..4d13663aae 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -933,13 +933,6 @@ } ], "parallax": [ - { - "id": "enable", - "displayName": "Enable", - "description": "Whether to enable the parallax feature.", - "type": "Bool", - "defaultValue": false - }, { "id": "textureMap", "displayName": "Texture Map", @@ -950,6 +943,13 @@ "id": "m_depthMap" } }, + { + "id": "useTexture", + "displayName": "Use Texture", + "description": "Whether to use the texture map.", + "type": "Bool", + "defaultValue": true + }, { "id": "textureMapUv", "displayName": "UV", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index 5cc7c933b9..ca3e5e1ce4 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -879,13 +879,6 @@ } ], "parallax": [ - { - "id": "enable", - "displayName": "Enable", - "description": "Whether to enable the parallax feature.", - "type": "Bool", - "defaultValue": false - }, { "id": "textureMap", "displayName": "Texture Map", @@ -896,6 +889,13 @@ "id": "m_depthMap" } }, + { + "id": "useTexture", + "displayName": "Use Texture", + "description": "Whether to use the texture map.", + "type": "Bool", + "defaultValue": true + }, { "id": "textureMapUv", "displayName": "UV", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua index e6689da327..53d6334f28 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua @@ -13,7 +13,7 @@ ---------------------------------------------------------------------------------------------------- function GetMaterialPropertyDependencies() - return {"parallax.enable", "parallax.textureMap"} + return {"parallax.textureMap", "parallax.useTexture"} end function GetShaderOptionDependencies() @@ -21,27 +21,31 @@ function GetShaderOptionDependencies() end function Process(context) - local enable = context:GetMaterialPropertyValue_bool("parallax.enable") local textureMap = context:GetMaterialPropertyValue_Image("parallax.textureMap") + local useTexture = context:GetMaterialPropertyValue_bool("parallax.useTexture") + local enable = textureMap ~= nil and useTexture context:SetShaderOptionValue_bool("o_parallax_feature_enabled", enable) - context:SetShaderOptionValue_bool("o_useDepthMap", enable and textureMap ~= nil) + context:SetShaderOptionValue_bool("o_useDepthMap", enable) end function ProcessEditor(context) - local enable = context:GetMaterialPropertyValue_bool("parallax.enable") - - if enable then - context:SetMaterialPropertyVisibility("parallax.textureMap", MaterialPropertyVisibility_Enabled) - else - context:SetMaterialPropertyVisibility("parallax.textureMap", MaterialPropertyVisibility_Hidden) - end - local textureMap = context:GetMaterialPropertyValue_Image("parallax.textureMap") - local visibility = MaterialPropertyVisibility_Enabled - if(not enable or textureMap == nil) then - visibility = MaterialPropertyVisibility_Hidden + + if textureMap ~= nil then + context:SetMaterialPropertyVisibility("parallax.useTexture", MaterialPropertyVisibility_Enabled) + else + context:SetMaterialPropertyVisibility("parallax.useTexture", MaterialPropertyVisibility_Hidden) end + local useTexture = context:GetMaterialPropertyValue_bool("parallax.useTexture") + + local visibility = MaterialPropertyVisibility_Enabled + if(textureMap == nil) then + visibility = MaterialPropertyVisibility_Hidden + elseif not useTexture then + visibility = MaterialPropertyVisibility_Disabled + end + context:SetMaterialPropertyVisibility("parallax.factor", visibility) context:SetMaterialPropertyVisibility("parallax.offset", visibility) context:SetMaterialPropertyVisibility("parallax.showClipping", visibility) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ShaderEnable.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ShaderEnable.lua index 26c163d61b..b245fde3df 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ShaderEnable.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ShaderEnable.lua @@ -13,7 +13,7 @@ ---------------------------------------------------------------------------------------------------- function GetMaterialPropertyDependencies() - return {"opacity.mode", "parallax.enable", "parallax.pdo"} + return {"opacity.mode", "parallax.textureMap", "parallax.useTexture", "parallax.pdo"} end OpacityMode_Opaque = 0 @@ -37,7 +37,9 @@ end function Process(context) local opacityMode = context:GetMaterialPropertyValue_enum("opacity.mode") - local parallaxEnabled = context:GetMaterialPropertyValue_bool("parallax.enable") + local displacementMap = context:GetMaterialPropertyValue_Image("parallax.textureMap") + local useDisplacementMap = context:GetMaterialPropertyValue_bool("parallax.useTexture") + local parallaxEnabled = displacementMap ~= nil and useDisplacementMap local parallaxPdoEnabled = context:GetMaterialPropertyValue_bool("parallax.pdo") local depthPass = context:GetShaderByTag("DepthPass") diff --git a/Gems/Atom/TestData/TestData/Materials/ParallaxRock.material b/Gems/Atom/TestData/TestData/Materials/ParallaxRock.material index 4c3a925e52..c9276216eb 100644 --- a/Gems/Atom/TestData/TestData/Materials/ParallaxRock.material +++ b/Gems/Atom/TestData/TestData/Materials/ParallaxRock.material @@ -17,7 +17,6 @@ "textureMap": "TestData/Textures/cc0/Rock030_2K_Normal.jpg" }, "parallax": { - "enable": true, "algorithm": "POM", "factor": 0.03, "quality": "High", diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM.material index a94d90d04d..ed070d5de2 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM.material @@ -8,7 +8,6 @@ }, "parallax": { "algorithm": "POM", - "enable": true, "factor": 0.02500000037252903, "quality": "High", "textureMap": "TestData/Textures/TextureHaven/4k_castle_brick_02_red/4k_castle_brick_02_red_disp.png" diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material index 21f873fe1a..f5ec0e8287 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material @@ -13,7 +13,6 @@ "textureMap": "TestData/Textures/checker8x8_512.png" }, "parallax": { - "enable": true, "factor": 0.10000000149011612, "quality": "High", "textureMap": "TestData/Textures/TextureHaven/4k_castle_brick_02_red/4k_castle_brick_02_red_disp.png" diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/100_UvTiling_Parallax_A.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/100_UvTiling_Parallax_A.material index 7bf12e5358..b3e69212db 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/100_UvTiling_Parallax_A.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/100_UvTiling_Parallax_A.material @@ -13,7 +13,6 @@ }, "parallax": { "algorithm": "POM", - "enable": true, "factor": 0.10000000149011612, "quality": "High", "textureMap": "TestData/Objects/cube/cube_diff.tif" diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/100_UvTiling_Parallax_B.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/100_UvTiling_Parallax_B.material index 4b9f233a85..3d52f3b9e6 100644 --- a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/100_UvTiling_Parallax_B.material +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/100_UvTiling_Parallax_B.material @@ -13,7 +13,6 @@ }, "parallax": { "algorithm": "POM", - "enable": true, "factor": 0.05000000074505806, "quality": "High", "textureMap": "TestData/Objects/cube/cube_diff.tif" diff --git a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Bricks038_8K/bricks038.material b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Bricks038_8K/bricks038.material index 25e29b55e5..82b1cdb590 100644 --- a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Bricks038_8K/bricks038.material +++ b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Bricks038_8K/bricks038.material @@ -26,7 +26,6 @@ }, "parallax": { "algorithm": "POM", - "enable": true, "factor": 0.02500000037252903, "pdo": true, "quality": "Ultra", diff --git a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Concrete016_8K/Concrete016.material b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Concrete016_8K/Concrete016.material index 336d479b30..03fb0ea5be 100644 --- a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Concrete016_8K/Concrete016.material +++ b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Concrete016_8K/Concrete016.material @@ -31,7 +31,8 @@ "algorithm": "ContactRefinement", "factor": 0.019999999552965165, "quality": "Ultra", - "textureMap": "Materials/Concrete016_8K/Concrete016_8K_Displacement.png" + "textureMap": "Materials/Concrete016_8K/Concrete016_8K_Displacement.png", + "useTexture": false }, "roughness": { "textureMap": "Materials/Concrete016_8K/Concrete016_8K_Roughness.png" diff --git a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Fabric001_8K/Fabric001.material b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Fabric001_8K/Fabric001.material index 72610e8bb6..7d8c3d5142 100644 --- a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Fabric001_8K/Fabric001.material +++ b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Fabric001_8K/Fabric001.material @@ -20,7 +20,6 @@ }, "parallax": { "algorithm": "ContactRefinement", - "enable": true, "factor": 0.004999999888241291, "quality": "Ultra", "textureMap": "Materials/Fabric001_8K/Fabric001_8K_Displacement.png" diff --git a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Fabric030_4K/Fabric030.material b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Fabric030_4K/Fabric030.material index 458ab811b6..493bfab455 100644 --- a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Fabric030_4K/Fabric030.material +++ b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/Fabric030_4K/Fabric030.material @@ -20,7 +20,6 @@ }, "parallax": { "algorithm": "ContactRefinement", - "enable": true, "factor": 0.0020000000949949028, "pdo": true, "quality": "Medium", diff --git a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/PaintedPlaster015_8K/PaintedPlaster015.material b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/PaintedPlaster015_8K/PaintedPlaster015.material index 57163f520d..a2bb2c7704 100644 --- a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/PaintedPlaster015_8K/PaintedPlaster015.material +++ b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/PaintedPlaster015_8K/PaintedPlaster015.material @@ -19,7 +19,6 @@ }, "parallax": { "algorithm": "ContactRefinement", - "enable": true, "factor": 0.009999999776482582, "pdo": true, "quality": "Ultra", diff --git a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/baseboards.material b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/baseboards.material index 625d872475..f75490c2ad 100644 --- a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/baseboards.material +++ b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/baseboards.material @@ -30,7 +30,8 @@ "factor": 0.02500000037252903, "pdo": true, "quality": "Ultra", - "textureMap": "Materials/Bricks038_8K/Bricks038_8K_Displacement.png" + "textureMap": "Materials/Bricks038_8K/Bricks038_8K_Displacement.png", + "useTexture": false }, "roughness": { "factor": 0.4343433976173401, diff --git a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/crown.material b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/crown.material index e3c6d9eae6..d7e2050dbd 100644 --- a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/crown.material +++ b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/crown.material @@ -22,7 +22,6 @@ }, "parallax": { "algorithm": "POM", - "enable": true, "factor": 0.02500000037252903, "pdo": true, "quality": "Ultra", diff --git a/Gems/AtomContent/ReferenceMaterials/Assets/Materials/ConcreteStucco/concrete_stucco.material b/Gems/AtomContent/ReferenceMaterials/Assets/Materials/ConcreteStucco/concrete_stucco.material index ab9f366ff6..d4e2016022 100644 --- a/Gems/AtomContent/ReferenceMaterials/Assets/Materials/ConcreteStucco/concrete_stucco.material +++ b/Gems/AtomContent/ReferenceMaterials/Assets/Materials/ConcreteStucco/concrete_stucco.material @@ -19,7 +19,8 @@ }, "parallax": { "factor": 0.0010101000079885126, - "textureMap": "Materials/ConcreteStucco/concrete_stucco_height.jpg" + "textureMap": "Materials/ConcreteStucco/concrete_stucco_height.jpg", + "useTexture": false }, "specularF0": { "factor": 0.5050504803657532 diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_arch.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_arch.material index 1102fb150a..d95e84121c 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_arch.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_arch.material @@ -41,7 +41,8 @@ "factor": 0.050999999046325687, "pdo": true, "quality": "High", - "textureMap": "Textures/arch_1k_height.png" + "textureMap": "Textures/arch_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/arch_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_background.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_background.material index c1853250d7..710f790419 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_background.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_background.material @@ -47,7 +47,8 @@ "factor": 0.03099999949336052, "pdo": true, "quality": "High", - "textureMap": "Textures/background_1k_height.png" + "textureMap": "Textures/background_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/background_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_bricks.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_bricks.material index a269098b4d..26d64c7db9 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_bricks.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_bricks.material @@ -46,7 +46,8 @@ "algorithm": "ContactRefinement", "factor": 0.03500000014901161, "quality": "Medium", - "textureMap": "Textures/bricks_1k_height.png" + "textureMap": "Textures/bricks_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/bricks_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_ceiling.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_ceiling.material index 94225cd00e..95d08d398b 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_ceiling.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_ceiling.material @@ -48,7 +48,8 @@ "factor": 0.019999999552965165, "pdo": true, "quality": "Medium", - "textureMap": "Textures/ceiling_1k_height.png" + "textureMap": "Textures/ceiling_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/ceiling_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columna.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columna.material index 8f1cea8649..cc1f685c7c 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columna.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columna.material @@ -47,7 +47,8 @@ "factor": 0.017000000923871995, "pdo": true, "quality": "High", - "textureMap": "Textures/columnA_1k_height.png" + "textureMap": "Textures/columnA_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/columnA_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columnb.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columnb.material index ac474d7e76..a1e8747f65 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columnb.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columnb.material @@ -46,7 +46,8 @@ "factor": 0.020999999716877939, "pdo": true, "quality": "High", - "textureMap": "Textures/columnB_1k_height.png" + "textureMap": "Textures/columnB_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/columnB_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columnc.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columnc.material index 81fd03fc4a..6edbfde47c 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columnc.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_columnc.material @@ -47,7 +47,8 @@ "factor": 0.014000000432133675, "pdo": true, "quality": "High", - "textureMap": "Textures/columnC_1k_height.png" + "textureMap": "Textures/columnC_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/columnC_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_details.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_details.material index fde599fd4c..1b66a51ec0 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_details.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_details.material @@ -38,7 +38,8 @@ "algorithm": "POM", "factor": 0.02500000037252903, "pdo": true, - "textureMap": "Textures/details_1k_height.png" + "textureMap": "Textures/details_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/details_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_flagpole.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_flagpole.material index e50e8a0ed2..19010d66e5 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_flagpole.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_flagpole.material @@ -41,7 +41,8 @@ "factor": 0.014000000432133675, "pdo": true, "quality": "High", - "textureMap": "Textures/flagpole_1k_height.png" + "textureMap": "Textures/flagpole_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/flagpole_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_floor.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_floor.material index 064a2b24a6..bee92e0edb 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_floor.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_floor.material @@ -43,7 +43,8 @@ "algorithm": "POM", "factor": 0.012000000104308129, "pdo": true, - "textureMap": "Textures/floor_1k_height.png" + "textureMap": "Textures/floor_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/floor_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_leaf.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_leaf.material index 269e1e5684..ac326ae935 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_leaf.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_leaf.material @@ -42,7 +42,8 @@ "mode": "Cutout" }, "parallax": { - "textureMap": "Textures/thorn_height.png" + "textureMap": "Textures/thorn_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/thorn_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_lion.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_lion.material index 8dc4852b03..b1f78aa33f 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_lion.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_lion.material @@ -38,7 +38,6 @@ }, "parallax": { "algorithm": "ContactRefinement", - "enable": true, "factor": 0.009999999776482582, "pdo": true, "quality": "Ultra", diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_roof.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_roof.material index 0a7246703c..a3e066a438 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_roof.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_roof.material @@ -35,7 +35,8 @@ "algorithm": "ContactRefinement", "factor": 0.019999999552965165, "quality": "Medium", - "textureMap": "Textures/roof_1k_height.png" + "textureMap": "Textures/roof_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/roof_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vase.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vase.material index 77adc798a0..dea9aa2a8a 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vase.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vase.material @@ -41,7 +41,8 @@ "factor": 0.027000000700354577, "pdo": true, "quality": "High", - "textureMap": "Textures/vase_1k_height.png" + "textureMap": "Textures/vase_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/vase_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vasehanging.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vasehanging.material index 22e78f03ae..b2a342dd76 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vasehanging.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vasehanging.material @@ -41,7 +41,8 @@ "factor": 0.04600000008940697, "pdo": true, "quality": "High", - "textureMap": "Textures/vaseHanging_1k_height.png" + "textureMap": "Textures/vaseHanging_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/vaseHanging_1k_roughness.png" diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vaseround.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vaseround.material index c773146b51..fba07379c0 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vaseround.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vaseround.material @@ -45,7 +45,8 @@ "factor": 0.019999999552965165, "pdo": true, "quality": "High", - "textureMap": "Textures/vaseRound_1k_height.png" + "textureMap": "Textures/vaseRound_1k_height.png", + "useTexture": false }, "roughness": { "textureMap": "Textures/vaseRound_1k_roughness.png" From b4ab2032e8eea711474800a98a9d0d868c55946e Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Thu, 27 May 2021 18:03:01 +0100 Subject: [PATCH 229/811] Fix for viewport ui crash and small refactor (#992) --- .../EditorTransformComponentSelection.cpp | 39 ++++++++----------- .../EditorTransformComponentSelection.h | 26 ++++++++----- 2 files changed, 33 insertions(+), 32 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index 0edbc4f8b5..3507f532b5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -809,14 +809,12 @@ namespace AzToolsFramework EntityIdManipulators& entityIdManipulators, OptionalFrame& pivotOverrideFrame, ViewportInteraction::KeyboardModifiers& prevModifiers, - bool& transformChangedInternally, SpaceCluster spaceCluster) + bool& transformChangedInternally, const AZStd::optional spaceLock) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); entityIdManipulators.m_manipulators->SetLocalPosition(action.LocalPosition()); - const ReferenceFrame referenceFrame = spaceCluster.m_spaceLock ? spaceCluster.m_currentSpace : ReferenceFrameFromModifiers(action.m_modifiers); - if (action.m_modifiers.Ctrl()) { // moving with ctrl - setting override @@ -826,6 +824,8 @@ namespace AzToolsFramework } else { + const ReferenceFrame referenceFrame = spaceLock.value_or(ReferenceFrameFromModifiers(action.m_modifiers)); + // note: used for parent and world depending on the current reference frame const auto pivotOrientation = ETCS::CalculateSelectionPivotOrientation( @@ -1298,7 +1298,7 @@ namespace AzToolsFramework { UpdateTranslationManipulator( action, manipulatorEntityIds->m_entityIds, m_entityIdManipulators, m_pivotOverrideFrame, prevModifiers, - m_transformChangedInternally, m_spaceCluster); + m_transformChangedInternally, m_spaceCluster.m_spaceLock); }); translationManipulators->InstallLinearManipulatorMouseUpCallback( @@ -1329,7 +1329,7 @@ namespace AzToolsFramework { UpdateTranslationManipulator( action, manipulatorEntityIds->m_entityIds, m_entityIdManipulators, m_pivotOverrideFrame, prevModifiers, - m_transformChangedInternally, m_spaceCluster); + m_transformChangedInternally, m_spaceCluster.m_spaceLock); }); translationManipulators->InstallPlanarManipulatorMouseUpCallback( @@ -1359,7 +1359,7 @@ namespace AzToolsFramework { UpdateTranslationManipulator( action, manipulatorEntityIds->m_entityIds, m_entityIdManipulators, m_pivotOverrideFrame, prevModifiers, - m_transformChangedInternally, m_spaceCluster); + m_transformChangedInternally, m_spaceCluster.m_spaceLock); }); translationManipulators->InstallSurfaceManipulatorMouseUpCallback( @@ -1437,8 +1437,7 @@ namespace AzToolsFramework [this, prevModifiers, sharedRotationState] (const AngularManipulator::Action& action) mutable -> void { - const ReferenceFrame referenceFrame = m_spaceCluster.m_spaceLock ? m_spaceCluster.m_currentSpace : ReferenceFrameFromModifiers(action.m_modifiers); - + const ReferenceFrame referenceFrame = m_spaceCluster.m_spaceLock.value_or(ReferenceFrameFromModifiers(action.m_modifiers)); const AZ::Quaternion manipulatorOrientation = action.m_start.m_rotation * action.m_current.m_delta; // store the pivot override frame when positioning the manipulator manually (ctrl) // so we don't lose the orientation when adding/removing entities from the selection @@ -2605,40 +2604,37 @@ namespace AzToolsFramework if (buttonId == m_spaceCluster.m_localButtonId) { // Unlock - if (m_spaceCluster.m_spaceLock && m_spaceCluster.m_currentSpace == ReferenceFrame::Local) + if (m_spaceCluster.m_spaceLock.has_value() && m_spaceCluster.m_spaceLock.value() == ReferenceFrame::Local) { - m_spaceCluster.m_spaceLock = false; + m_spaceCluster.m_spaceLock = AZStd::nullopt; } else { - m_spaceCluster.m_spaceLock = true; - m_spaceCluster.m_currentSpace = ReferenceFrame::Local; + m_spaceCluster.m_spaceLock = ReferenceFrame::Local; } } else if (buttonId == m_spaceCluster.m_parentButtonId) { // Unlock - if (m_spaceCluster.m_spaceLock && m_spaceCluster.m_currentSpace == ReferenceFrame::Parent) + if (m_spaceCluster.m_spaceLock.has_value() && m_spaceCluster.m_spaceLock.value() == ReferenceFrame::Parent) { - m_spaceCluster.m_spaceLock = false; + m_spaceCluster.m_spaceLock = AZStd::nullopt; } else { - m_spaceCluster.m_spaceLock = true; - m_spaceCluster.m_currentSpace = ReferenceFrame::Parent; + m_spaceCluster.m_spaceLock = ReferenceFrame::Parent; } } else if (buttonId == m_spaceCluster.m_worldButtonId) { // Unlock - if (m_spaceCluster.m_spaceLock && m_spaceCluster.m_currentSpace == ReferenceFrame::World) + if (m_spaceCluster.m_spaceLock.has_value() && m_spaceCluster.m_spaceLock.value() == ReferenceFrame::World) { - m_spaceCluster.m_spaceLock = false; + m_spaceCluster.m_spaceLock = AZStd::nullopt; } else { - m_spaceCluster.m_spaceLock = true; - m_spaceCluster.m_currentSpace = ReferenceFrame::World; + m_spaceCluster.m_spaceLock = ReferenceFrame::World; } } }; @@ -3361,8 +3357,7 @@ namespace AzToolsFramework ViewportInteraction::BuildMouseButtons( QGuiApplication::mouseButtons()), m_boxSelect.Active()); - const ReferenceFrame referenceFrame = - m_spaceCluster.m_spaceLock ? m_spaceCluster.m_currentSpace : ReferenceFrameFromModifiers(modifiers); + const ReferenceFrame referenceFrame = m_spaceCluster.m_spaceLock.value_or(ReferenceFrameFromModifiers(modifiers)); UpdateSpaceCluster(referenceFrame); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h index 4be84df26e..2bc4d7cbf6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h @@ -106,15 +106,20 @@ namespace AzToolsFramework World, //!< World space (space aligned to world axes - identity). }; + //! Grouping of viewport ui related state for controlling the current reference space of the Editor. struct SpaceCluster { - ViewportUi::ClusterId m_spaceClusterId; - ViewportUi::ButtonId m_localButtonId; - ViewportUi::ButtonId m_parentButtonId; - ViewportUi::ButtonId m_worldButtonId; - AZ::Event::Handler m_spaceSelectionHandler; - ReferenceFrame m_currentSpace = ReferenceFrame::Parent; - bool m_spaceLock = false; + SpaceCluster() = default; + // disable copying and moving (implicit) + SpaceCluster(const SpaceCluster&) = delete; + SpaceCluster& operator=(const SpaceCluster&) = delete; + + ViewportUi::ClusterId m_spaceClusterId; //!< The id identifying the reference space cluster. + ViewportUi::ButtonId m_localButtonId; //!< Local reference space button id. + ViewportUi::ButtonId m_parentButtonId; //!< Parent reference space button id. + ViewportUi::ButtonId m_worldButtonId; //!< World reference space button id. + AZ::Event::Handler m_spaceSelectionHandler; //!< Callback for when a space cluster button is pressed. + AZStd::optional m_spaceLock; //!< Locked reference frame to use if set. }; //! Entity selection/interaction handling. @@ -265,6 +270,9 @@ namespace AzToolsFramework void SetEntityLocalScale(AZ::EntityId entityId, float localScale); void SetEntityLocalRotation(AZ::EntityId entityId, const AZ::Vector3& localRotation); + // Responsible for keeping the space cluster in sync with the current reference frame. + void UpdateSpaceCluster(ReferenceFrame referenceFrame); + AZ::EntityId m_hoveredEntityId; //!< What EntityId is the mouse currently hovering over (if any). AZ::EntityId m_cachedEntityIdUnderCursor; //!< Store the EntityId on each mouse move for use in Display. AZ::EntityId m_editorCameraComponentEntityId; //!< The EditorCameraComponent EntityId if it is set. @@ -297,9 +305,7 @@ namespace AzToolsFramework AZ::Event::Handler m_transformModeSelectionHandler; //!< Event handler for the Viewport UI cluster. AzFramework::ClickDetector m_clickDetector; //!< Detect different types of mouse click. AzFramework::CursorState m_cursorState; //!< Track the mouse position and delta movement each frame. - - SpaceCluster m_spaceCluster; - void UpdateSpaceCluster(ReferenceFrame referenceFrame); + SpaceCluster m_spaceCluster; //!< Related viewport ui state for controlling the current reference space. }; //! The ETCS (EntityTransformComponentSelection) namespace contains functions and data used exclusively by From 0dd8fce2b0073c0ccc5ce3d3cd170def9b6e9fda Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 10:30:11 -0700 Subject: [PATCH 230/811] Pass on fixing LmbrCentral.Static dependencies --- Gems/AudioEngineWwise/Code/CMakeLists.txt | 2 +- Gems/AutomatedLauncherTesting/Code/CMakeLists.txt | 2 +- Gems/EMotionFX/Code/CMakeLists.txt | 2 +- Gems/FastNoise/Code/CMakeLists.txt | 10 +++++++--- Gems/GradientSignal/Code/CMakeLists.txt | 10 ++++++++-- Gems/ImGui/Code/CMakeLists.txt | 3 ++- Gems/LyShine/Code/CMakeLists.txt | 8 +++++--- Gems/LyShineExamples/Code/CMakeLists.txt | 2 +- Gems/PhysX/Code/CMakeLists.txt | 7 +++++-- Gems/StartingPointCamera/Code/CMakeLists.txt | 2 +- Gems/SurfaceData/Code/CMakeLists.txt | 5 ++++- Gems/Vegetation/Code/CMakeLists.txt | 5 +++-- 12 files changed, 39 insertions(+), 19 deletions(-) diff --git a/Gems/AudioEngineWwise/Code/CMakeLists.txt b/Gems/AudioEngineWwise/Code/CMakeLists.txt index 75006a1673..f90064908a 100644 --- a/Gems/AudioEngineWwise/Code/CMakeLists.txt +++ b/Gems/AudioEngineWwise/Code/CMakeLists.txt @@ -207,8 +207,8 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::EditorCore PUBLIC AZ::AssetBuilderSDK - Gem::AudioSystem.Editor.Static Gem::AudioEngineWwise.Static + Gem::AudioSystem.Editor RUNTIME_DEPENDENCIES Gem::AudioSystem.Editor ) diff --git a/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt b/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt index 264491500f..6215ae7697 100644 --- a/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt +++ b/Gems/AutomatedLauncherTesting/Code/CMakeLists.txt @@ -23,7 +23,7 @@ ly_add_target( PUBLIC AZ::AzCore Legacy::CryCommon - Gem::LmbrCentral.Static + Gem::LmbrCentral ) ly_add_target( diff --git a/Gems/EMotionFX/Code/CMakeLists.txt b/Gems/EMotionFX/Code/CMakeLists.txt index a78e8487f0..bc0268cd60 100644 --- a/Gems/EMotionFX/Code/CMakeLists.txt +++ b/Gems/EMotionFX/Code/CMakeLists.txt @@ -36,10 +36,10 @@ ly_add_target( AZ::AzCore AZ::AzFramework Legacy::CryCommon - Gem::LmbrCentral.Static PUBLIC AZ::AtomCore Gem::Atom_RPI.Public + Gem::LmbrCentral COMPILE_DEFINITIONS PUBLIC EMFX_DEVELOPMENT_BUILD diff --git a/Gems/FastNoise/Code/CMakeLists.txt b/Gems/FastNoise/Code/CMakeLists.txt index 0fb98c0237..8c12dcf5be 100644 --- a/Gems/FastNoise/Code/CMakeLists.txt +++ b/Gems/FastNoise/Code/CMakeLists.txt @@ -23,7 +23,8 @@ ly_add_target( PUBLIC Legacy::CryCommon Gem::GradientSignal - Gem::LmbrCentral.Static + PRIVATE + Gem::LmbrCentral ) ly_add_target( @@ -61,6 +62,8 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) PUBLIC Include BUILD_DEPENDENCIES + PRIVATE + Gem::LmbrCentral.Editor PUBLIC Gem::FastNoise.Static AZ::AzToolsFramework @@ -69,7 +72,6 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME FastNoise.Editor GEM_MODULE - NAMESPACE Gem FILES_CMAKE fastnoise_editor_shared_files.cmake @@ -80,7 +82,8 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Include BUILD_DEPENDENCIES PRIVATE - FastNoise.Editor.Static + Gem::FastNoise.Editor.Static + Gem::LmbrCentral.Editor RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor Gem::SurfaceData.Editor @@ -113,6 +116,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE AZ::AzTest FastNoise.Editor.Static + Gem::LmbrCentral.Editor ) ly_add_googletest( NAME Gem::FastNoise.Editor.Tests diff --git a/Gems/GradientSignal/Code/CMakeLists.txt b/Gems/GradientSignal/Code/CMakeLists.txt index 7fe3897568..244f7360ea 100644 --- a/Gems/GradientSignal/Code/CMakeLists.txt +++ b/Gems/GradientSignal/Code/CMakeLists.txt @@ -22,9 +22,10 @@ ly_add_target( BUILD_DEPENDENCIES PUBLIC Legacy::CryCommon - Gem::LmbrCentral.Static Gem::SurfaceData Gem::ImageProcessingAtom.Headers + PRIVATE + Gem::LmbrCentral ) ly_add_target( @@ -40,6 +41,7 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE Gem::GradientSignal.Static + Gem::LmbrCentral PUBLIC Gem::ImageProcessingAtom.Headers # Atom/ImageProcessing/PixelFormats.h is part of a header in Includes RUNTIME_DEPENDENCIES @@ -66,6 +68,8 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) PUBLIC GRADIENTSIGNAL_EDITOR BUILD_DEPENDENCIES + PRIVATE + Gem::LmbrCentral.Editor PUBLIC 3rdParty::Qt::Widgets Legacy::CryCommon @@ -79,7 +83,6 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME GradientSignal.Editor GEM_MODULE - NAMESPACE Gem FILES_CMAKE gradientsignal_editor_shared_files.cmake @@ -91,6 +94,7 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) BUILD_DEPENDENCIES PRIVATE Gem::GradientSignal.Editor.Static + Gem::LmbrCentral.Editor RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor ) @@ -120,6 +124,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE AZ::AzTest Gem::GradientSignal.Static + Gem::LmbrCentral ) ly_add_googletest( NAME Gem::GradientSignal.Tests @@ -140,6 +145,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest Gem::GradientSignal.Static Gem::GradientSignal.Editor.Static + Gem::LmbrCentral.Editor ) ly_add_googletest( NAME Gem::GradientSignal.Editor.Tests diff --git a/Gems/ImGui/Code/CMakeLists.txt b/Gems/ImGui/Code/CMakeLists.txt index e1286419ce..fccdb6fc08 100644 --- a/Gems/ImGui/Code/CMakeLists.txt +++ b/Gems/ImGui/Code/CMakeLists.txt @@ -72,7 +72,8 @@ ly_add_target( BUILD_DEPENDENCIES PUBLIC Gem::ImGui.ImGuiLYUtils - Gem::LmbrCentral.Static + PRIVATE + Gem::LmbrCentral ) ly_add_target( diff --git a/Gems/LyShine/Code/CMakeLists.txt b/Gems/LyShine/Code/CMakeLists.txt index 9f38120088..4dede1c6ac 100644 --- a/Gems/LyShine/Code/CMakeLists.txt +++ b/Gems/LyShine/Code/CMakeLists.txt @@ -26,13 +26,13 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE Legacy::CryCommon + Gem::LmbrCentral PUBLIC Gem::Atom_RPI.Public Gem::Atom_Utils.Static Gem::Atom_Bootstrap.Headers Gem::AtomFont - Gem::LmbrCentral.Static - Gem::TextureAtlas + Gem::TextureAtlas ) ly_add_target( @@ -49,6 +49,7 @@ ly_add_target( PRIVATE Gem::LyShine.Static Legacy::CryCommon + Gem::LmbrCentral RUNTIME_DEPENDENCIES Gem::LmbrCentral Gem::TextureAtlas @@ -86,7 +87,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::EditorCore Gem::LyShine.Static Legacy::CryCommon - Gem::LmbrCentral.Editor.Static + Gem::LmbrCentral.Editor Gem::TextureAtlas.Editor Gem::AtomToolsFramework.Static Gem::AtomToolsFramework.Editor @@ -152,6 +153,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest Gem::LyShine.Static Legacy::CryCommon + Gem::LmbrCentral RUNTIME_DEPENDENCIES Gem::LmbrCentral Gem::TextureAtlas diff --git a/Gems/LyShineExamples/Code/CMakeLists.txt b/Gems/LyShineExamples/Code/CMakeLists.txt index a80b05d6c2..ce420cbd30 100644 --- a/Gems/LyShineExamples/Code/CMakeLists.txt +++ b/Gems/LyShineExamples/Code/CMakeLists.txt @@ -22,7 +22,7 @@ ly_add_target( BUILD_DEPENDENCIES PUBLIC Legacy::CryCommon - Gem::LmbrCentral.Static + Gem::LmbrCentral Gem::LyShine.Static ) diff --git a/Gems/PhysX/Code/CMakeLists.txt b/Gems/PhysX/Code/CMakeLists.txt index 64b8efb98a..b0318af9f2 100644 --- a/Gems/PhysX/Code/CMakeLists.txt +++ b/Gems/PhysX/Code/CMakeLists.txt @@ -46,7 +46,8 @@ ly_add_target( AZ::AzCore AZ::AzFramework Legacy::CryCommon - Gem::LmbrCentral.Static + PRIVATE + Gem::LmbrCentral ) ly_add_target( @@ -66,6 +67,7 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE Gem::PhysX.Static + Gem::LmbrCentral RUNTIME_DEPENDENCIES Gem::LmbrCentral ) @@ -111,7 +113,7 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) AZ::SceneCore AZ::SceneData Legacy::CryCommon - Gem::LmbrCentral.Editor.Static + Gem::LmbrCentral.Editor Gem::PhysX.NumericalMethods Gem::PhysX.Static Gem::AtomLyIntegration_CommonFeatures.Static @@ -165,6 +167,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTestShared AZ::AzTest Gem::PhysX.Static + Gem::LmbrCentral RUNTIME_DEPENDENCIES Gem::LmbrCentral ) diff --git a/Gems/StartingPointCamera/Code/CMakeLists.txt b/Gems/StartingPointCamera/Code/CMakeLists.txt index cf8efc0cd6..7bc57476a5 100644 --- a/Gems/StartingPointCamera/Code/CMakeLists.txt +++ b/Gems/StartingPointCamera/Code/CMakeLists.txt @@ -23,7 +23,7 @@ ly_add_target( PRIVATE AZ::AzCore Gem::CameraFramework.Static - Gem::LmbrCentral.Static + Gem::LmbrCentral Legacy::CryCommon ) diff --git a/Gems/SurfaceData/Code/CMakeLists.txt b/Gems/SurfaceData/Code/CMakeLists.txt index 7a9cb47039..642849675c 100644 --- a/Gems/SurfaceData/Code/CMakeLists.txt +++ b/Gems/SurfaceData/Code/CMakeLists.txt @@ -22,10 +22,10 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE Legacy::CryCommon + Gem::LmbrCentral PUBLIC Gem::Atom_RPI.Public Gem::Atom_Feature_Common.Static - Gem::LmbrCentral.Static ) ly_add_target( @@ -42,6 +42,7 @@ ly_add_target( PRIVATE Legacy::CryCommon Gem::SurfaceData.Static + Gem::LmbrCentral RUNTIME_DEPENDENCIES Gem::LmbrCentral ) @@ -71,6 +72,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::CryCommon AZ::AzToolsFramework Gem::SurfaceData.Static + Gem::LmbrCentral.Editor RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor ) @@ -100,6 +102,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest Legacy::CryCommon Gem::SurfaceData.Static + Gem::LmbrCentral ) ly_add_googletest( NAME Gem::SurfaceData.Tests diff --git a/Gems/Vegetation/Code/CMakeLists.txt b/Gems/Vegetation/Code/CMakeLists.txt index 12439878af..7283f53c97 100644 --- a/Gems/Vegetation/Code/CMakeLists.txt +++ b/Gems/Vegetation/Code/CMakeLists.txt @@ -24,10 +24,11 @@ ly_add_target( PUBLIC Include BUILD_DEPENDENCIES + PRIVATE + Gem::LmbrCentral + Gem::SurfaceData PUBLIC Legacy::CryCommon - Gem::LmbrCentral.Static - Gem::SurfaceData.Static Gem::AtomLyIntegration_CommonFeatures.Static RUNTIME_DEPENDENCIES Gem::GradientSignal From 4e80ce1b1d9131354fbee4571b7ca847a9033d0b Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 12:36:33 -0500 Subject: [PATCH 231/811] Re-added back an ly_setup_target function which configures the CMakeLists.txt template for a single target --- cmake/Platform/Common/Install_common.cmake | 336 +++++++++++---------- 1 file changed, 171 insertions(+), 165 deletions(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index aa9e710a0e..939f523d75 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -18,6 +18,175 @@ file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_ set(install_output_folder "${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$") +#! ly_setup_target: Setup the data needed to re-create the cmake target commands for a single target +function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME) + # De-alias target name + ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) + + # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that + # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the + # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. + # Instead, we install them with install(DIRECTORY) + set(include_location "include") + get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) + if (include_directories) + unset(public_headers) + foreach(include_directory ${include_directories}) + string(GENEX_STRIP ${include_directory} include_genex_expr) + if(include_genex_expr STREQUAL include_directory) # only for cases where there are no generation expressions + unset(current_public_headers) + install(DIRECTORY ${include_directory} + DESTINATION ${include_location}/${target_source_dir} + COMPONENT ${ly_install_target_COMPONENT} + FILES_MATCHING + PATTERN *.h + PATTERN *.hpp + PATTERN *.inl + ) + endif() + endforeach() + endif() + + # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target + file(RELATIVE_PATH archive_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) + + get_target_property(target_runtime_output_directory ${TARGET_NAME} RUNTIME_OUTPUT_DIRECTORY) + if(target_runtime_output_directory) + file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) + endif() + + get_target_property(target_library_output_directory ${TARGET_NAME} LIBRARY_OUTPUT_DIRECTORY) + if(target_library_output_directory) + file(RELATIVE_PATH target_library_output_subdirectory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${target_library_output_directory}) + endif() + + install( + TARGETS ${TARGET_NAME} + ARCHIVE + DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ + COMPONENT ${ly_install_target_COMPONENT} + LIBRARY + DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} + COMPONENT ${ly_install_target_COMPONENT} + RUNTIME + DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} + COMPONENT ${ly_install_target_COMPONENT} + ) + + # CMakeLists.txt file + string(REGEX MATCH "(.*)::(.*)$" match ${ALIAS_TARGET_NAME}) + if(match) + set(NAMESPACE_PLACEHOLDER "NAMESPACE ${CMAKE_MATCH_1}") + set(NAME_PLACEHOLDER ${CMAKE_MATCH_2}) + else() + set(NAMESPACE_PLACEHOLDER "") + set(NAME_PLACEHOLDER ${TARGET_NAME}) + endif() + + set(TARGET_TYPE_PLACEHOLDER "") + get_target_property(target_type ${NAME_PLACEHOLDER} TYPE) + # Remove the _LIBRARY since we dont need to pass that to ly_add_targets + string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type}) + # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead + string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER}) + if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE") + get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE) + if(gem_module) + set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE") + endif() + endif() + + get_target_property(COMPILE_DEFINITIONS_PLACEHOLDER ${TARGET_NAME} INTERFACE_COMPILE_DEFINITIONS) + if(COMPILE_DEFINITIONS_PLACEHOLDER) + string(REPLACE ";" "\n" COMPILE_DEFINITIONS_PLACEHOLDER "${COMPILE_DEFINITIONS_PLACEHOLDER}") + else() + unset(COMPILE_DEFINITIONS_PLACEHOLDER) + endif() + + # Includes need additional processing to add the install root + if(include_directories) + foreach(include ${include_directories}) + string(GENEX_STRIP ${include} include_genex_expr) + if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions + file(RELATIVE_PATH relative_include ${absolute_target_source_dir} ${include}) + string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}/${relative_include}\n") + endif() + endforeach() + endif() + + get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) + if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found + string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") + else() + unset(RUNTIME_DEPENDENCIES_PLACEHOLDER) + endif() + + get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES) + unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) + if(inteface_build_dependencies_props) + foreach(build_dependency ${inteface_build_dependencies_props}) + # Skip wrapping produced when targets are not created in the same directory + if(NOT ${build_dependency} MATCHES "^::@") + list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + endif() + endforeach() + endif() + # We also need to pass the private link libraries since we will use that to generate the runtime dependencies + get_target_property(private_build_dependencies_props ${TARGET_NAME} LINK_LIBRARIES) + if(private_build_dependencies_props) + foreach(build_dependency ${private_build_dependencies_props}) + # Skip wrapping produced when targets are not created in the same directory + if(NOT ${build_dependency} MATCHES "^::@") + list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + endif() + endforeach() + endif() + list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) + string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}") + + # Config file + set(target_file_contents "# Generated by O3DE install\n\n") + if(NOT target_type STREQUAL INTERFACE_LIBRARY) + + unset(target_location) + set(runtime_types EXECUTABLE APPLICATION) + if(target_type IN_LIST runtime_types) + set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$") + elseif(target_type STREQUAL MODULE_LIBRARY) + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") + elseif(target_type STREQUAL SHARED_LIBRARY) + string(APPEND target_file_contents "set_property(TARGET ${TARGET_NAME} PROPERTY IMPORTED_IMPLIB_$ \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\")\n") + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") + else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY + set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") + endif() + + if(target_location) + string(APPEND target_file_contents +"set_property(TARGET ${TARGET_NAME} + APPEND_STRING PROPERTY IMPORTED_LOCATION + $<$$:${target_location}$ +) +set_property(TARGET ${TARGET_NAME} + PROPERTY IMPORTED_LOCATION_$> + ${target_location} +) +") + endif() + endif() + + file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" + DESTINATION ${target_source_dir} + COMPONENT ${ly_install_target_COMPONENT} + ) + + # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target + file(READ ${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in target_cmakelists_template) + string(CONFIGURE ${target_cmakelists_template} output_cmakelists_data @ONLY) + set(${OUTPUT_CONFIGURED_TARGET} ${output_cmakelists_data} PARENT_SCOPE) +endfunction() + #! ly_setup_subdirectories: setups all targets on a per directory basis function(ly_setup_subdirectories) get_property(all_subdirectories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) @@ -30,176 +199,13 @@ endfunction() #! ly_setup_subdirectory: setup all targets in the subdirectory function(ly_setup_subdirectory absolute_target_source_dir) - file(READ ${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in target_cmakelists_template) # The builtin BUILDSYSTEM_TARGETS property isn't being used here as that returns the de-alised # TARGET and we need the alias namespace for recreating the CMakeLists.txt in the install layout get_property(ALIAS_TARGETS_NAME DIRECTORY ${absolute_target_source_dir} PROPERTY LY_DIRECTORY_TARGETS) file(RELATIVE_PATH target_source_dir ${LY_ROOT_FOLDER} ${absolute_target_source_dir}) foreach(ALIAS_TARGET_NAME IN LISTS ALIAS_TARGETS_NAME) - unset(TARGET_NAME) - ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) - - # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that - # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the - # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. - # Instead, we install them with install(DIRECTORY) - set(include_location "include") - get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) - if (include_directories) - unset(public_headers) - foreach(include_directory ${include_directories}) - string(GENEX_STRIP ${include_directory} include_genex_expr) - if(include_genex_expr STREQUAL include_directory) # only for cases where there are no generation expressions - unset(current_public_headers) - install(DIRECTORY ${include_directory} - DESTINATION ${include_location}/${target_source_dir} - COMPONENT ${ly_install_target_COMPONENT} - FILES_MATCHING - PATTERN *.h - PATTERN *.hpp - PATTERN *.inl - ) - endif() - endforeach() - endif() - - # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target - file(RELATIVE_PATH archive_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) - - get_target_property(target_runtime_output_directory ${TARGET_NAME} RUNTIME_OUTPUT_DIRECTORY) - if(target_runtime_output_directory) - file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) - endif() - - get_target_property(target_library_output_directory ${TARGET_NAME} LIBRARY_OUTPUT_DIRECTORY) - if(target_library_output_directory) - file(RELATIVE_PATH target_library_output_subdirectory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${target_library_output_directory}) - endif() - - install( - TARGETS ${TARGET_NAME} - ARCHIVE - DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ - COMPONENT ${ly_install_target_COMPONENT} - LIBRARY - DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} - COMPONENT ${ly_install_target_COMPONENT} - RUNTIME - DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} - COMPONENT ${ly_install_target_COMPONENT} - ) - - # CMakeLists.txt file - string(REGEX MATCH "(.*)::(.*)$" match ${ALIAS_TARGET_NAME}) - if(match) - set(NAMESPACE_PLACEHOLDER "NAMESPACE ${CMAKE_MATCH_1}") - set(NAME_PLACEHOLDER ${CMAKE_MATCH_2}) - else() - set(NAMESPACE_PLACEHOLDER "") - set(NAME_PLACEHOLDER ${TARGET_NAME}) - endif() - - set(TARGET_TYPE_PLACEHOLDER "") - get_target_property(target_type ${NAME_PLACEHOLDER} TYPE) - # Remove the _LIBRARY since we dont need to pass that to ly_add_targets - string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type}) - # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead - string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER}) - if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE") - get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE) - if(gem_module) - set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE") - endif() - endif() - - get_target_property(COMPILE_DEFINITIONS_PLACEHOLDER ${TARGET_NAME} INTERFACE_COMPILE_DEFINITIONS) - if(COMPILE_DEFINITIONS_PLACEHOLDER) - string(REPLACE ";" "\n" COMPILE_DEFINITIONS_PLACEHOLDER "${COMPILE_DEFINITIONS_PLACEHOLDER}") - else() - unset(COMPILE_DEFINITIONS_PLACEHOLDER) - endif() - - # Includes need additional processing to add the install root - if(include_directories) - foreach(include ${include_directories}) - string(GENEX_STRIP ${include} include_genex_expr) - if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions - file(RELATIVE_PATH relative_include ${absolute_target_source_dir} ${include}) - string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}/${relative_include}\n") - endif() - endforeach() - endif() - - get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) - if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found - string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") - else() - unset(RUNTIME_DEPENDENCIES_PLACEHOLDER) - endif() - - get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES) - unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) - if(inteface_build_dependencies_props) - foreach(build_dependency ${inteface_build_dependencies_props}) - # Skip wrapping produced when targets are not created in the same directory - if(NOT ${build_dependency} MATCHES "^::@") - list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") - endif() - endforeach() - endif() - # We also need to pass the private link libraries since we will use that to generate the runtime dependencies - get_target_property(private_build_dependencies_props ${TARGET_NAME} LINK_LIBRARIES) - if(private_build_dependencies_props) - foreach(build_dependency ${private_build_dependencies_props}) - # Skip wrapping produced when targets are not created in the same directory - if(NOT ${build_dependency} MATCHES "^::@") - list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") - endif() - endforeach() - endif() - list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) - string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}") - - # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target - string(CONFIGURE ${target_cmakelists_template} configured_target @ONLY) + ly_setup_target(configured_target ${ALIAS_TARGET_NAME}) string(APPEND all_configured_targets "${configured_target}") - - # Config file - set(target_file_contents "# Generated by O3DE install\n\n") - if(NOT target_type STREQUAL INTERFACE_LIBRARY) - - unset(target_location) - set(runtime_types EXECUTABLE APPLICATION) - if(target_type IN_LIST runtime_types) - set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$") - elseif(target_type STREQUAL MODULE_LIBRARY) - set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") - elseif(target_type STREQUAL SHARED_LIBRARY) - string(APPEND target_file_contents "set_property(TARGET ${TARGET_NAME} PROPERTY IMPORTED_IMPLIB_$ \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\")\n") - set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") - else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY - set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") - endif() - - if(target_location) - string(APPEND target_file_contents - "set_property(TARGET ${TARGET_NAME} - APPEND_STRING PROPERTY IMPORTED_LOCATION - $<$$:${target_location}$ - ) - set_property(TARGET ${TARGET_NAME} - PROPERTY IMPORTED_LOCATION_$> - ${target_location} - ) - ") - endif() - endif() - - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" - DESTINATION ${target_source_dir} - COMPONENT ${ly_install_target_COMPONENT} - ) endforeach() # Replicate the ly_create_alias() calls based on the SOURCE_DIR for each target that generates an installed CMakeLists.txt @@ -304,7 +310,7 @@ function(ly_setup_cmake_install) get_property(all_subdirectories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) foreach(target_subdirectory IN LISTS all_subdirectories) file(RELATIVE_PATH target_source_dir_relative ${LY_ROOT_FOLDER} ${target_subdirectory}) - string(APPEND FIND_PACKAGES_PLACEHOLDER " add_subdirectory(${target_source_dir_relative}/${target})\n") + string(APPEND FIND_PACKAGES_PLACEHOLDER " add_subdirectory(${target_source_dir_relative})\n") endforeach() configure_file(${LY_ROOT_FOLDER}/cmake/install/Findo3de.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/Findo3de.cmake @ONLY) From 824be567fcab3c053cb701745dca1e8e94178d28 Mon Sep 17 00:00:00 2001 From: sconel Date: Thu, 27 May 2021 10:45:47 -0700 Subject: [PATCH 232/811] Prepping for PR --- .../ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp | 11 ++++------- .../ScriptCanvas/Libraries/Spawning/SpawnNodeable.h | 4 ++-- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index 93a248de5d..28d9af9bcd 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -22,10 +22,6 @@ namespace ScriptCanvas { namespace Spawning { - SpawnNodeable::SpawnNodeable() - { - } - SpawnNodeable::SpawnNodeable(const SpawnNodeable& rhs) { m_spawnableAsset = rhs.m_spawnableAsset; @@ -38,7 +34,6 @@ namespace ScriptCanvas AZ::TickBus::Handler::BusConnect(); } - m_spawnTicket.IsValid(); m_spawnTicket = AzFramework::EntitySpawnTicket(m_spawnableAsset); } @@ -57,7 +52,7 @@ namespace ScriptCanvas AZStd::vector swappedSpawnedEntityList; AZStd::vector swappedSpawnBatchSizes; { - AZStd::lock_guard lock(m_recursiveMutex); + AZStd::lock_guard lock(m_idBatchMutex); swappedSpawnedEntityList.swap(m_spawnedEntityList); swappedSpawnBatchSizes.swap(m_spawnBatchSizes); @@ -99,6 +94,8 @@ namespace ScriptCanvas m_spawnableAsset = AZ::Data::AssetManager::Instance(). FindOrCreateAsset(rootAssetId, AZ::Data::AssetLoadBehavior::Default); } + + m_spawnableAsset.SetAutoLoadBehavior(AZ::Data::AssetLoadBehavior::PreLoad); } } @@ -129,7 +126,7 @@ namespace ScriptCanvas auto spawnCompleteCB = [this]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, AzFramework::SpawnableConstEntityContainerView view) { - AZStd::lock_guard lock(m_recursiveMutex); + AZStd::lock_guard lock(m_idBatchMutex); m_spawnedEntityList.reserve(m_spawnedEntityList.size() + view.size()); for (const AZ::Entity* entity : view) { diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h index 25cb92742e..2b2a22601d 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h @@ -34,7 +34,7 @@ namespace ScriptCanvas { SCRIPTCANVAS_NODE(SpawnNodeable); public: - SpawnNodeable(); + SpawnNodeable() = default; SpawnNodeable(const SpawnNodeable& rhs); void OnInitializeExecutionState() override; @@ -50,7 +50,7 @@ namespace ScriptCanvas AZStd::vector m_spawnedEntityList; AZStd::vector m_spawnBatchSizes; - AZStd::recursive_mutex m_recursiveMutex; + AZStd::recursive_mutex m_idBatchMutex; }; } } From b600dd9b7126296e5a03849ba62f478c66763075 Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Thu, 27 May 2021 12:49:16 -0500 Subject: [PATCH 233/811] Fixed issues with mac build caused by a double define of "MAC" (#996) * fixed missed reference to name change * Fixed MAC double define issue, changed to MAC_ID --- Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp | 4 ++-- Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h | 4 ++-- .../AzCore/Platform/Mac/AzCore/PlatformId/PlatformId_Mac.h | 2 +- .../Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp index c3f6357706..e31c3b0a1e 100644 --- a/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp +++ b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp @@ -35,7 +35,7 @@ namespace AZ return "Android"; case AZ::IOS: return "iOS"; - case AZ::MAC: + case AZ::MAC_ID: return "Mac"; case AZ::PROVO: return "Provo"; @@ -213,7 +213,7 @@ namespace AZ case PlatformId::IOS: platformCodes.emplace_back(PlatformCodeNameiOS); break; - case PlatformId::MAC: + case PlatformId::MAC_ID: platformCodes.emplace_back(PlatformCodeNameMac); break; case PlatformId::PROVO: diff --git a/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h index 93477ebeb9..ba8c55f5f5 100644 --- a/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h +++ b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h @@ -56,7 +56,7 @@ namespace AZ PC, ANDROID_ID, IOS, - MAC, + MAC_ID, PROVO, SALEM, JASPER, @@ -75,7 +75,7 @@ namespace AZ Platform_PC = 1 << PlatformId::PC, Platform_ANDROID = 1 << PlatformId::ANDROID_ID, Platform_IOS = 1 << PlatformId::IOS, - Platform_MAC = 1 << PlatformId::MAC, + Platform_MAC = 1 << PlatformId::MAC_ID, Platform_PROVO = 1 << PlatformId::PROVO, Platform_SALEM = 1 << PlatformId::SALEM, Platform_JASPER = 1 << PlatformId::JASPER, diff --git a/Code/Framework/AzCore/Platform/Mac/AzCore/PlatformId/PlatformId_Mac.h b/Code/Framework/AzCore/Platform/Mac/AzCore/PlatformId/PlatformId_Mac.h index d361e79f05..42dcd3e2f7 100644 --- a/Code/Framework/AzCore/Platform/Mac/AzCore/PlatformId/PlatformId_Mac.h +++ b/Code/Framework/AzCore/Platform/Mac/AzCore/PlatformId/PlatformId_Mac.h @@ -13,5 +13,5 @@ namespace AZ { - static const PlatformID g_currentPlatform = PlatformID::PLATFORM_APPLE_OSX; + static const PlatformID g_currentPlatform = PlatformID::PLATFORM_APPLE_MAC; } diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp index 0db53456e0..c256caac4a 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp @@ -738,7 +738,7 @@ namespace AZ } else if (platformIdentifier == "mac") { - platformId = AzFramework::PlatformId::MAC; + platformId = AzFramework::PlatformId::MAC_ID; } else if (platformIdentifier == "android") { @@ -790,7 +790,7 @@ namespace AZ } else if (platform == "mac") { - platformId = AzFramework::PlatformId::MAC; + platformId = AzFramework::PlatformId::MAC_ID; } else if (platform == "android") { From 933f012def618e56ff92dde683e95652b8c85c43 Mon Sep 17 00:00:00 2001 From: sconel Date: Thu, 27 May 2021 10:50:56 -0700 Subject: [PATCH 234/811] Code cleanup, removed pragma optimize macro --- .../UI/PropertyEditor/PropertyAssetCtrl.cpp | 11 +---------- .../ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp | 1 - 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp index 4bf261122d..dd39cf9b97 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp @@ -802,16 +802,7 @@ namespace AzToolsFramework AZ_Assert(product || folder, "Incorrect entry type selected. Expected product or folder."); if (product) { - AZ::Data::AssetId selectedAssetId = product->GetAssetId(); - - // If we hid the product files a source asset was picked - // Clear the sub id as a source could have N products with different sub ids - if (m_hideProductFilesInAssetPicker) - { - selectedAssetId.m_subId = 0; - } - - SetSelectedAssetID(selectedAssetId); + SetSelectedAssetID(product->GetAssetId()); } else if (folder) { diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index 28d9af9bcd..37bb64745a 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -10,7 +10,6 @@ * */ -#pragma optimize("", off) #include #include From 5b5d02baa46478618d6491f2e50cb888fa11119e Mon Sep 17 00:00:00 2001 From: jackalbe <23512001+jackalbe@users.noreply.github.com> Date: Thu, 27 May 2021 12:59:42 -0500 Subject: [PATCH 235/811] {LYN-4060} Helios - Fix to load PAK Archive files (#964) * {LYN-4060} Helios - Fix to load PAK Archive files {LYN-4060} Helios - Fix to load PAK Archive files * Helios - Archive does not load from PAK files due to IsFileExists() error * the decompression tag does not need to be ZCRY, so removed it * the PAK files are on disk, so a "on disk file exists" method is used * the mapped files m_mapFiles need to track the file path, not just the filename Tests: Release Launcher with a new level * re-adding the read only flag check so that ZIP files can be created --- .../AzFramework/AzFramework/Archive/Archive.cpp | 15 +++++---------- .../AzFramework/Archive/ArchiveFindData.cpp | 15 +++++++-------- 2 files changed, 12 insertions(+), 18 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp index b0285616df..4a80db2b24 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp @@ -2008,13 +2008,12 @@ namespace AZ::IO // if no bind root is specified, compute one: strBindRoot = !bindRoot.empty() ? bindRoot : szFullPath->ParentPath().Native(); - // Check if archive file disk exist on disk or inside of pak. - bool bFileExists = IsFileExist(szFullPath->Native()); - - if (!bFileExists && (nFactoryFlags & ZipDir::CacheFactory::FLAGS_READ_ONLY)) + // Check if archive file disk exist on disk. + const bool pakOnDisk = FileIOBase::GetDirectInstance()->Exists(szFullPath->c_str()); + if (!pakOnDisk && (nFactoryFlags & ZipDir::CacheFactory::FLAGS_READ_ONLY)) { // Archive file not found. - AZ_TracePrintf("Archive", "Cannot open Archive file %s\n", szFullPath->c_str()); + AZ_TracePrintf("Archive", "Archive file %s does not exist\n", szFullPath->c_str()); return nullptr; } @@ -2492,8 +2491,6 @@ namespace AZ::IO void Archive::FindCompressionInfo(bool& found, AZ::IO::CompressionInfo& info, const AZStd::string_view filename) { - constexpr uint32_t s_compressionTag = static_cast('Z') << 24 | static_cast('C') << 16 | static_cast('R') << 8 | static_cast('Y'); - if (!found) { auto correctedFilename = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(filename); @@ -2519,7 +2516,6 @@ namespace AZ::IO found = true; info.m_archiveFilename.InitFromRelativePath(archive->GetFilePath()); - info.m_compressionTag.m_code = s_compressionTag; info.m_offset = pFileData->GetFileDataOffset(); info.m_compressedSize = entry->desc.lSizeCompressed; info.m_uncompressedSize = entry->desc.lSizeUncompressed; @@ -2539,9 +2535,8 @@ namespace AZ::IO break; } - info.m_decompressor = [&s_compressionTag]([[maybe_unused]] const AZ::IO::CompressionInfo& info, const void* compressed, size_t compressedSize, void* uncompressed, size_t uncompressedBufferSize)->bool + info.m_decompressor = []([[maybe_unused]] const AZ::IO::CompressionInfo& info, const void* compressed, size_t compressedSize, void* uncompressed, size_t uncompressedBufferSize)->bool { - AZ_Assert(info.m_compressionTag.m_code == s_compressionTag, "Provided compression info isn't supported by this decompressor."); size_t nSizeUncompressed = uncompressedBufferSize; return ZipDir::ZipRawUncompress(uncompressed, &nSizeUncompressed, compressed, compressedSize) == 0; }; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp index 678f4e40bf..1794ae90e7 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp @@ -50,6 +50,7 @@ namespace AZ::IO , tWrite{ writeTime } { } + ArchiveFileIterator::ArchiveFileIterator(FindData* findData, AZStd::string_view filename, const FileDesc& fileDesc) : m_findData{ findData } , m_filename{ filename } @@ -108,13 +109,10 @@ namespace AZ::IO AZ::StringFunc::Path::GetFullPath(directory.c_str(), searchDirectory); AZ::StringFunc::Path::GetFullFileName(directory.c_str(), pattern); } - AZ::IO::FileIOBase::GetDirectInstance()->FindFiles(searchDirectory.c_str(), pattern.c_str(), [&](const char* filePath) -> bool { AZ::IO::FileDesc fileDesc; - - AZStd::string fullFilePath; - AZ::StringFunc::Path::GetFullFileName(filePath, fullFilePath); + AZStd::string filePathEntry{filePath}; if (AZ::IO::FileIOBase::GetDirectInstance()->IsDirectory(filePath)) { @@ -135,9 +133,8 @@ namespace AZ::IO fileDesc.tAccess = fileDesc.tWrite; fileDesc.tCreate = fileDesc.tWrite; } - [[maybe_unused]] auto result = m_mapFiles.emplace(AZStd::move(fullFilePath), fileDesc); - AZ_Assert(result.second, "Failed to insert FindData entry for %s", fullFilePath.c_str()); - + [[maybe_unused]] auto result = m_mapFiles.emplace(AZStd::move(filePathEntry), fileDesc); + AZ_Assert(result.second, "Failed to insert FindData entry for filePath %s", filePath); return true; }); } @@ -273,7 +270,9 @@ namespace AZ::IO } auto pakFileIter = m_mapFiles.begin(); - fileIterator.m_filename = pakFileIter->first; + AZStd::string fullFilePath; + AZ::StringFunc::Path::GetFullFileName(pakFileIter->first.c_str(), fullFilePath); + fileIterator.m_filename = AZStd::move(fullFilePath); fileIterator.m_fileDesc = pakFileIter->second; fileIterator.m_lastFetchValid = true; From 05654ea152640022e8e6a01ea0ec0e48db53f33c Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Thu, 27 May 2021 11:09:10 -0700 Subject: [PATCH 236/811] ATOM-15653 Remove Unnecessary Parallax Map Invert Flag Removed the parallax invert flags and instead all the materials assume displacement is always specified as heightmaps. Updated property naming, tooltips, and shader variable names to reflect this. Updated ParallaxMapping.azsli to treat depthOffset as an offset in depth value rather than an offset in height value, so it matches the fact that ParallaxMapping.azsli always operates in depth values rather than height values. --- .../ReflectionProbeVisualization.materialtype | 15 +--- .../Materials/Types/EnhancedPBR.materialtype | 25 ++---- .../Materials/Types/EnhancedPBR_Common.azsli | 4 +- .../Types/EnhancedPBR_DepthPass_WithPS.azsl | 2 +- .../Types/EnhancedPBR_ForwardPass.azsl | 2 +- .../Types/EnhancedPBR_Shadowmap_WithPS.azsl | 2 +- .../Types/MaterialInputs/ParallaxInput.azsli | 25 +++--- .../Types/StandardMultilayerPBR.materialtype | 87 ++++++------------- .../Types/StandardMultilayerPBR_Common.azsli | 28 +++--- .../Materials/Types/StandardPBR.materialtype | 25 ++---- .../Materials/Types/StandardPBR_Common.azsli | 4 +- .../Types/StandardPBR_DepthPass_WithPS.azsl | 2 +- .../Types/StandardPBR_ForwardPass.azsl | 2 +- .../Types/StandardPBR_ParallaxState.lua | 4 +- .../Types/StandardPBR_Shadowmap_WithPS.azsl | 2 +- .../Atom/Features/ParallaxMapping.azsli | 29 +++---- 16 files changed, 95 insertions(+), 163 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/ReflectionProbe/ReflectionProbeVisualization.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/ReflectionProbe/ReflectionProbeVisualization.materialtype index 214fc02660..9a2edc9fca 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/ReflectionProbe/ReflectionProbeVisualization.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/ReflectionProbe/ReflectionProbeVisualization.materialtype @@ -469,7 +469,7 @@ "max": 1.0, "connection": { "type": "ShaderInput", - "id": "m_depthFactor" + "id": "m_heightmapScale" } }, { @@ -479,18 +479,7 @@ "type": "Image", "connection": { "type": "ShaderInput", - "id": "m_depthMap" - } - }, - { - "id": "invert", - "displayName": "Invert", - "description": "Invert to depthmap if the texture is heightmap", - "type": "Bool", - "defaultValue": true, - "connection": { - "type": "ShaderInput", - "id": "m_depthInverted" + "id": "m_heightmap" } }, { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index 4d13663aae..3696188514 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -935,25 +935,25 @@ "parallax": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Depthmap to create parallax effect.", + "displayName": "Heightmap", + "description": "Displacement heightmap to create parallax effect.", "type": "Image", "connection": { "type": "ShaderInput", - "id": "m_depthMap" + "id": "m_heightmap" } }, { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the heightmap.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Depth texture map UV set", + "description": "Heightmap UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -972,7 +972,7 @@ "softMax": 0.1, "connection": { "type": "ShaderInput", - "id": "m_depthFactor" + "id": "m_heightmapScale" } }, { @@ -985,18 +985,7 @@ "softMax": 0.1, "connection": { "type": "ShaderInput", - "id": "m_depthOffset" - } - }, - { - "id": "invert", - "displayName": "Invert", - "description": "Invert to depthmap if the texture is heightmap", - "type": "Bool", - "defaultValue": true, - "connection": { - "type": "ShaderInput", - "id": "m_depthInverted" + "id": "m_heightmapOffset" } }, { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli index 34af9229c2..b6d6439268 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli @@ -108,7 +108,7 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial // Callback function for ParallaxMapping.azsli DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { - return SampleDepthOrHeightMap(MaterialSrg::m_depthInverted, MaterialSrg::m_depthMap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); + return SampleDepthFromHeightmap(MaterialSrg::m_heightmap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); } COMMON_OPTIONS_PARALLAX() @@ -116,7 +116,7 @@ COMMON_OPTIONS_PARALLAX() bool ShouldHandleParallax() { // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scattering is enabled. - return !o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap; + return !o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useHeightmap; } bool ShouldHandleParallaxInDepthShaders() diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl index 644473fef9..d70e3b899a 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl @@ -84,7 +84,7 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_heightmapScale, MaterialSrg::m_heightmapOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl index a4fcccb5f5..a8b4075d51 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -141,7 +141,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_heightmapScale, MaterialSrg::m_heightmapOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, IN.m_position.w, displacementIsClipped); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl index 7f6be252e2..6d3d4f2ea5 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl @@ -88,7 +88,7 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_heightmapScale, MaterialSrg::m_heightmapOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli index ffd7c18045..84d4bfcc02 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli @@ -22,15 +22,14 @@ // You can optionally provide a prefix for the set of inputs which corresponds to a prefix string supplied by the .materialtype file. This is common for multi-layered material types. #define COMMON_SRG_INPUTS_PARALLAX(prefix) \ -Texture2D prefix##m_depthMap; \ -float prefix##m_depthFactor; \ -float prefix##m_depthOffset; \ -bool prefix##m_depthInverted; +Texture2D prefix##m_heightmap; \ +float prefix##m_heightmapScale; \ +float prefix##m_heightmapOffset; #define COMMON_OPTIONS_PARALLAX(prefix) \ -option bool prefix##o_useDepthMap; +option bool prefix##o_useHeightmap; -void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, float depthOffset, +void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float heightmapScale, float heightmapOffset, float4x4 objectWorldMatrix, float3x3 uvMatrix, float3x3 uvMatrixInverse, inout float2 uv, inout float3 worldPosition, inout float depthNDC, inout float depthCS, out bool isClipped) { @@ -48,8 +47,8 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep dirToCamera = ViewSrg::m_worldPosition.xyz - worldPosition; } - ParallaxOffset tangentOffset = GetParallaxOffset( depthFactor, - depthOffset, + ParallaxOffset tangentOffset = GetParallaxOffset( heightmapScale, + -heightmapOffset, uv, dirToCamera, tangent, @@ -62,7 +61,7 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep if(o_parallax_enablePixelDepthOffset) { - PixelDepthOffset pdo = CalcPixelDepthOffset(depthFactor, + PixelDepthOffset pdo = CalcPixelDepthOffset(heightmapScale, tangentOffset.m_offsetTS, worldPosition, tangent, @@ -81,19 +80,19 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep } } -void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, float depthOffset, +void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float heightmapScale, float heightmapOffset, float4x4 objectWorldMatrix, float3x3 uvMatrix, float3x3 uvMatrixInverse, inout float2 uv, inout float3 worldPosition, inout float depthNDC, inout float depthCS) { bool isClipped; - GetParallaxInput(normal, tangent, bitangent, depthFactor, depthOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depthNDC, depthCS, isClipped); + GetParallaxInput(normal, tangent, bitangent, heightmapScale, heightmapOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depthNDC, depthCS, isClipped); } -void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, float depthOffset, +void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float heightmapScale, float heightmapOffset, float4x4 objectWorldMatrix, float3x3 uvMatrix, float3x3 uvMatrixInverse, inout float2 uv, inout float3 worldPosition, inout float depthNDC) { float depthCS; - GetParallaxInput(normal, tangent, bitangent, depthFactor, depthOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depthNDC, depthCS); + GetParallaxInput(normal, tangent, bitangent, heightmapScale, heightmapOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depthNDC, depthCS); } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype index ec1298ae77..ca6cb77b0a 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype @@ -1109,43 +1109,32 @@ "layer1_parallax": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Displacement texture map, which can be used for layer blending and/or a parallax effect.", + "displayName": "Heightmap", + "description": "Displacement heightmap, which can be used for layer blending and/or a parallax effect.", "type": "Image", "connection": { "type": "ShaderInput", - "id": "m_layer1_m_depthMap" + "id": "m_layer1_m_heightmap" } }, { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the heightmap.", "type": "Bool", "defaultValue": true }, - { - "id": "invert", - "displayName": "Invert", - "description": "Invert the displacement map", - "type": "Bool", - "defaultValue": true, - "connection": { - "type": "ShaderInput", - "id": "m_layer1_m_depthInverted" - } - }, { "id": "factor", "displayName": "Scale", - "description": "The total height of the displacement texture map in local model units.", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.05, "min": 0.0, "softMax": 0.1, "connection": { "type": "ShaderInput", - "id": "m_layer1_m_depthFactor" + "id": "m_layer1_m_heightmapScale" } }, { @@ -1158,7 +1147,7 @@ "softMax": 0.1, "connection": { "type": "ShaderInput", - "id": "m_layer1_m_depthOffset" + "id": "m_layer1_m_heightmapOffset" } } ], @@ -1815,43 +1804,32 @@ "layer2_parallax": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Displacement texture map, which can be used for layer blending and/or a parallax effect.", + "displayName": "Heightmap", + "description": "Displacement heightmap, which can be used for layer blending and/or a parallax effect.", "type": "Image", "connection": { "type": "ShaderInput", - "id": "m_layer2_m_depthMap" + "id": "m_layer2_m_heightmap" } }, { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the heightmap.", "type": "Bool", "defaultValue": true }, - { - "id": "invert", - "displayName": "Invert", - "description": "Invert the displacement map", - "type": "Bool", - "defaultValue": true, - "connection": { - "type": "ShaderInput", - "id": "m_layer2_m_depthInverted" - } - }, { "id": "factor", "displayName": "Scale", - "description": "The total height of the displacement texture map in local model units.", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.05, "min": 0.0, "softMax": 0.1, "connection": { "type": "ShaderInput", - "id": "m_layer2_m_depthFactor" + "id": "m_layer2_m_heightmapScale" } }, { @@ -1864,7 +1842,7 @@ "softMax": 0.1, "connection": { "type": "ShaderInput", - "id": "m_layer2_m_depthOffset" + "id": "m_layer2_m_heightmapOffset" } } ], @@ -2521,43 +2499,32 @@ "layer3_parallax": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Displacement texture map, which can be used for layer blending and/or a parallax effect.", + "displayName": "Heightmap", + "description": "Displacement heightmap, which can be used for layer blending and/or a parallax effect.", "type": "Image", "connection": { "type": "ShaderInput", - "id": "m_layer3_m_depthMap" + "id": "m_layer3_m_heightmap" } }, { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the heightmap.", "type": "Bool", "defaultValue": true }, - { - "id": "invert", - "displayName": "Invert", - "description": "Invert the displacement map", - "type": "Bool", - "defaultValue": true, - "connection": { - "type": "ShaderInput", - "id": "m_layer3_m_depthInverted" - } - }, { "id": "factor", "displayName": "Scale", - "description": "The total height of the displacement texture map in local model units.", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.05, "min": 0.0, "softMax": 0.1, "connection": { "type": "ShaderInput", - "id": "m_layer3_m_depthFactor" + "id": "m_layer3_m_heightmapScale" } }, { @@ -2570,7 +2537,7 @@ "softMax": 0.1, "connection": { "type": "ShaderInput", - "id": "m_layer3_m_depthOffset" + "id": "m_layer3_m_heightmapOffset" } } ], @@ -2837,8 +2804,8 @@ "args": { "textureProperty": "layer1_parallax.textureMap", "useTextureProperty": "layer1_parallax.useTexture", - "dependentProperties": ["layer1_parallax.factor", "layer1_parallax.invert"], - "shaderOption": "o_layer1_o_useDepthMap" + "dependentProperties": ["layer1_parallax.factor"], + "shaderOption": "o_layer1_o_useHeightmap" } }, { @@ -2974,8 +2941,8 @@ "args": { "textureProperty": "layer2_parallax.textureMap", "useTextureProperty": "layer2_parallax.useTexture", - "dependentProperties": ["layer2_parallax.factor", "layer2_parallax.invert"], - "shaderOption": "o_layer2_o_useDepthMap" + "dependentProperties": ["layer2_parallax.factor"], + "shaderOption": "o_layer2_o_useHeightmap" } }, { @@ -3111,8 +3078,8 @@ "args": { "textureProperty": "layer3_parallax.textureMap", "useTextureProperty": "layer3_parallax.useTexture", - "dependentProperties": ["layer3_parallax.factor", "layer3_parallax.invert"], - "shaderOption": "o_layer3_o_useDepthMap" + "dependentProperties": ["layer3_parallax.factor"], + "shaderOption": "o_layer3_o_useHeightmap" } }, { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli index c20a90c00b..1750da5020 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli @@ -379,7 +379,7 @@ float3 GetLayerDepthValues(float2 uv, float2 uv_ddx, float2 uv_ddy) // layer1 { - if(o_layer1_o_useDepthMap) + if(o_layer1_o_useHeightmap) { float2 layerUv = uv; if(MaterialSrg::m_parallaxUvIndex == 0) @@ -387,16 +387,16 @@ float3 GetLayerDepthValues(float2 uv, float2 uv_ddx, float2 uv_ddy) layerUv = mul(MaterialSrg::m_layer1_m_uvMatrix, float3(uv, 1.0)).xy; } - layerDepthValues.r = SampleDepthOrHeightMap(MaterialSrg::m_layer1_m_depthInverted, MaterialSrg::m_layer1_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; - layerDepthValues.r *= MaterialSrg::m_layer1_m_depthFactor; + layerDepthValues.r = SampleDepthFromHeightmap(MaterialSrg::m_layer1_m_heightmap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; + layerDepthValues.r *= MaterialSrg::m_layer1_m_heightmapScale; } - layerDepthValues.r -= MaterialSrg::m_layer1_m_depthOffset; + layerDepthValues.r -= MaterialSrg::m_layer1_m_heightmapOffset; } if(o_layer2_enabled) { - if(o_layer2_o_useDepthMap) + if(o_layer2_o_useHeightmap) { float2 layerUv = uv; if(MaterialSrg::m_parallaxUvIndex == 0) @@ -404,17 +404,17 @@ float3 GetLayerDepthValues(float2 uv, float2 uv_ddx, float2 uv_ddy) layerUv = mul(MaterialSrg::m_layer2_m_uvMatrix, float3(uv, 1.0)).xy; } - layerDepthValues.g = SampleDepthOrHeightMap(MaterialSrg::m_layer2_m_depthInverted, MaterialSrg::m_layer2_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; - layerDepthValues.g *= MaterialSrg::m_layer2_m_depthFactor; + layerDepthValues.g = SampleDepthFromHeightmap(MaterialSrg::m_layer2_m_heightmap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; + layerDepthValues.g *= MaterialSrg::m_layer2_m_heightmapScale; } - layerDepthValues.g -= MaterialSrg::m_layer2_m_depthOffset; + layerDepthValues.g -= MaterialSrg::m_layer2_m_heightmapOffset; } if(o_layer3_enabled) { - if(o_layer3_o_useDepthMap) + if(o_layer3_o_useHeightmap) { float2 layerUv = uv; if(MaterialSrg::m_parallaxUvIndex == 0) @@ -422,11 +422,11 @@ float3 GetLayerDepthValues(float2 uv, float2 uv_ddx, float2 uv_ddy) layerUv = mul(MaterialSrg::m_layer3_m_uvMatrix, float3(uv, 1.0)).xy; } - layerDepthValues.b = SampleDepthOrHeightMap(MaterialSrg::m_layer3_m_depthInverted, MaterialSrg::m_layer3_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; - layerDepthValues.b *= MaterialSrg::m_layer3_m_depthFactor; + layerDepthValues.b = SampleDepthFromHeightmap(MaterialSrg::m_layer3_m_heightmap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; + layerDepthValues.b *= MaterialSrg::m_layer3_m_heightmapScale; } - layerDepthValues.b -= MaterialSrg::m_layer3_m_depthOffset; + layerDepthValues.b -= MaterialSrg::m_layer3_m_heightmapOffset; } @@ -448,13 +448,13 @@ float3 ApplyBlendMaskToDepthValues(float3 blendMaskValues, float3 layerDepthValu if(o_layer2_enabled) { - float dropoffRange = MaterialSrg::m_layer2_m_depthOffset - zeroMaskDisplacement; + float dropoffRange = MaterialSrg::m_layer2_m_heightmapOffset - zeroMaskDisplacement; layerDepthValues.g += dropoffRange * (1-blendMaskValues.r); } if(o_layer3_enabled) { - float dropoffRange = MaterialSrg::m_layer3_m_depthOffset - zeroMaskDisplacement; + float dropoffRange = MaterialSrg::m_layer3_m_heightmapOffset - zeroMaskDisplacement; layerDepthValues.b += dropoffRange * (1-blendMaskValues.g); } } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index ca3e5e1ce4..183cddd4cb 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -881,25 +881,25 @@ "parallax": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Depthmap to create parallax effect.", + "displayName": "Heightmap", + "description": "Displacement heightmap to create parallax effect.", "type": "Image", "connection": { "type": "ShaderInput", - "id": "m_depthMap" + "id": "m_heightmap" } }, { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the heightmap.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Depth texture map UV set", + "description": "Heightmap UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -918,7 +918,7 @@ "softMax": 0.1, "connection": { "type": "ShaderInput", - "id": "m_depthFactor" + "id": "m_heightmapScale" } }, { @@ -931,18 +931,7 @@ "softMax": 0.1, "connection": { "type": "ShaderInput", - "id": "m_depthOffset" - } - }, - { - "id": "invert", - "displayName": "Invert", - "description": "Invert to depthmap if the texture is heightmap", - "type": "Bool", - "defaultValue": true, - "connection": { - "type": "ShaderInput", - "id": "m_depthInverted" + "id": "m_heightmapOffset" } }, { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli index 5723a6cd1e..87562c3d20 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli @@ -97,7 +97,7 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial // Callback function for ParallaxMapping.azsli DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { - return SampleDepthOrHeightMap(MaterialSrg::m_depthInverted, MaterialSrg::m_depthMap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); + return SampleDepthFromHeightmap(MaterialSrg::m_heightmap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); } @@ -106,7 +106,7 @@ COMMON_OPTIONS_PARALLAX() bool ShouldHandleParallax() { // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scattering is enabled. - return !o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap; + return !o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useHeightmap; } bool ShouldHandleParallaxInDepthShaders() diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl index afc93f060e..cc2b4ce659 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl @@ -86,7 +86,7 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_heightmapScale, MaterialSrg::m_heightmapOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl index 10fa3814f3..286b9b23df 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -130,7 +130,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_heightmapScale, MaterialSrg::m_heightmapOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depthNDC, IN.m_position.w, displacementIsClipped); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua index 53d6334f28..771726aea7 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua @@ -17,7 +17,7 @@ function GetMaterialPropertyDependencies() end function GetShaderOptionDependencies() - return {"o_parallax_feature_enabled", "o_useDepthMap"} + return {"o_parallax_feature_enabled", "o_useHeightmap"} end function Process(context) @@ -25,7 +25,7 @@ function Process(context) local useTexture = context:GetMaterialPropertyValue_bool("parallax.useTexture") local enable = textureMap ~= nil and useTexture context:SetShaderOptionValue_bool("o_parallax_feature_enabled", enable) - context:SetShaderOptionValue_bool("o_useDepthMap", enable) + context:SetShaderOptionValue_bool("o_useHeightmap", enable) end function ProcessEditor(context) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl index 533df3bb92..8b6fee849e 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl @@ -88,7 +88,7 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_heightmapScale, MaterialSrg::m_heightmapOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli index 8b1efc8eea..ff2a37d29b 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli @@ -58,7 +58,7 @@ DepthResult DepthResultAbsolute(float depth) //! The client shader must define this function. //! This allows the client shader to implement special depth map sampling, for example procedurally generating or blending depth maps. -//! In simple cases though, the implementation of GetDepth() can simply call SampleDepthOrHeightMap(). +//! In simple cases though, the implementation of GetDepth() can simply call SampleDepthFromHeightmap(). //! @param uv the UV coordinates to use for sampling //! @param uv_ddx will be set to ddx_fine(uv) //! @param uv_ddy will be set to ddy_fine(uv) @@ -66,13 +66,12 @@ DepthResult DepthResultAbsolute(float depth) DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy); //! Convenience function that can be used to implement GetDepth(). -//! @param isHeightmap indicates whether to sample the map is a height map rather than a depth map. //! @return see struct DepthResult. In this case it will always contain a Code::Normalized result. -DepthResult SampleDepthOrHeightMap(bool isHeightmap, Texture2D map, sampler mapSampler, float2 uv, float2 uv_ddx, float2 uv_ddy) +DepthResult SampleDepthFromHeightmap(Texture2D map, sampler mapSampler, float2 uv, float2 uv_ddx, float2 uv_ddy) { DepthResult result; result.m_resultCode = DepthResultCode_Normalized; - result.m_depth = abs((isHeightmap * 1.0) - map.SampleGrad(mapSampler, uv, uv_ddx, uv_ddy).r); + result.m_depth = 1.0 - map.SampleGrad(mapSampler, uv, uv_ddx, uv_ddy).r; return result; } @@ -169,20 +168,20 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo float2 ddx_uv = ddx_fine(uv); float2 ddy_uv = ddy_fine(uv); - float depthSearchStart = -depthOffset; + float depthSearchStart = depthOffset; float depthSearchEnd = depthSearchStart + depthFactor; float inverseDepthFactor = 1.0 / depthFactor; // This is the relative position at which we begin searching for intersection. // It is adjusted according to the depthOffset, raising or lowering the whole surface by depthOffset units. - float3 parallaxOffset = dirToCameraTS.xyz * dirToCameraZInverse * depthOffset; + float3 parallaxOffset = -dirToCameraTS.xyz * dirToCameraZInverse * depthOffset; // Get an initial heightmap sample to start the intersection search, starting at our initial parallaxOffset position. float currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, uv + parallaxOffset.xy, ddx_uv, ddy_uv); float prevSample; - // Note that when depthOffset < 0, we could actually narrow the search so that instead of going through the entire [depthSearchStart,depthSearchEnd] range + // Note that when depthOffset > 0, we could actually narrow the search so that instead of going through the entire [depthSearchStart,depthSearchEnd] range // of the heightmap, we could go through the range [0,depthSearchEnd]. This would give more accurate results and fewer artifacts // in case where the magnitude of depthOffset is significant. But for the sake of simplicity we currently search the whole range in all cases. @@ -271,7 +270,7 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo } // Even though we do a bunch of clamping above when calling GetClampedDepth(), there are still cases where the parallax offset - // can be noticeably above the surface and still needs to be clamped here. The main case is when depthFactor==0 and depthOffset>1. + // can be noticeably above the surface and still needs to be clamped here. The main case is when depthFactor==0 and depthOffset<1. if(parallaxOffset.z > 0.0) { parallaxOffset = float3(0,0,0); @@ -371,13 +370,13 @@ ParallaxOffset CalculateParallaxOffset(float depthFactor, float depthOffset, flo // @param dirToCameraTS - normalized direction to the camera, in tangent space. // @param dirToLightTS - normalized direction to a light source, in tangent space, for self-shadowing (if enabled via o_parallax_shadow). ParallaxOffset GetParallaxOffset( float depthFactor, - float depthOffset, - float2 uv, - float3 dirToCameraWS, - float3 tangentWS, - float3 bitangentWS, - float3 normalWS, - float3x3 uvMatrix) + float depthOffset, + float2 uv, + float3 dirToCameraWS, + float3 tangentWS, + float3 bitangentWS, + float3 normalWS, + float3x3 uvMatrix) { // Tangent space eye vector float3 dirToCameraTS = normalize(WorldSpaceToTangent(dirToCameraWS, normalWS, tangentWS, bitangentWS)); From c946d579282340877d8e11cba758a82b38e37cb8 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Thu, 27 May 2021 11:14:21 -0700 Subject: [PATCH 237/811] Addressed PR feedback. --- .../Spawnable/SpawnableEntitiesContainer.cpp | 12 +++---- .../Spawnable/SpawnableEntitiesInterface.cpp | 2 +- .../Spawnable/SpawnableEntitiesInterface.h | 16 ++++----- .../Spawnable/SpawnableEntitiesManager.h | 4 +++ .../Spawnable/SpawnableSystemComponent.cpp | 4 +-- .../SpawnableEntitiesManagerTests.cpp | 34 +++++++++---------- 6 files changed, 38 insertions(+), 34 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp index 9b06eb1f20..808de74e71 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp @@ -38,20 +38,20 @@ namespace AzFramework void SpawnableEntitiesContainer::SpawnAllEntities() { AZ_Assert(m_threadData, "Calling SpawnAllEntities on a Spawnable container that's not set."); - SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_threadData->m_spawnedEntitiesTicket, SpawnablePriorty_Default); + SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_threadData->m_spawnedEntitiesTicket, SpawnablePriority_Default); } void SpawnableEntitiesContainer::SpawnEntities(AZStd::vector entityIndices) { AZ_Assert(m_threadData, "Calling SpawnEntities on a Spawnable container that's not set."); SpawnableEntitiesInterface::Get()->SpawnEntities( - m_threadData->m_spawnedEntitiesTicket, SpawnablePriorty_Default, AZStd::move(entityIndices)); + m_threadData->m_spawnedEntitiesTicket, SpawnablePriority_Default, AZStd::move(entityIndices)); } void SpawnableEntitiesContainer::DespawnAllEntities() { AZ_Assert(m_threadData, "Calling DespawnEntities on a Spawnable container that's not set."); - SpawnableEntitiesInterface::Get()->DespawnAllEntities(m_threadData->m_spawnedEntitiesTicket, SpawnablePriorty_Default); + SpawnableEntitiesInterface::Get()->DespawnAllEntities(m_threadData->m_spawnedEntitiesTicket, SpawnablePriority_Default); } void SpawnableEntitiesContainer::Reset(AZ::Data::Asset spawnable) @@ -69,7 +69,7 @@ namespace AzFramework SpawnableEntitiesInterface::Get()->Barrier( m_threadData->m_spawnedEntitiesTicket, - SpawnablePriorty_Default, + SpawnablePriority_Default, [threadData = m_threadData](EntitySpawnTicket::Id) mutable { threadData.reset(); @@ -88,7 +88,7 @@ namespace AzFramework AZ_Assert(m_threadData, "Calling DespawnEntities on a Spawnable container that's not set."); SpawnableEntitiesInterface::Get()->Barrier( m_threadData->m_spawnedEntitiesTicket, - SpawnablePriorty_Default, + SpawnablePriority_Default, [generation = m_threadData->m_generation, callback = AZStd::move(callback)](EntitySpawnTicket::Id) { callback(generation); @@ -116,6 +116,6 @@ namespace AzFramework AZ_TracePrintf("Spawnables", "Reloading spawnable '%s'.\n", replacementAsset.GetHint().c_str()); SpawnableEntitiesInterface::Get()->ReloadSpawnable( - m_threadData->m_spawnedEntitiesTicket, SpawnablePriorty_Default, AZStd::move(replacementAsset)); + m_threadData->m_spawnedEntitiesTicket, SpawnablePriority_Default, AZStd::move(replacementAsset)); } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp index 26a10933b5..ad1bf032c8 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp @@ -275,7 +275,7 @@ namespace AzFramework return *this; } - uint64_t EntitySpawnTicket::GetId() const + auto EntitySpawnTicket::GetId() const -> Id { return m_id; } diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index b40136def7..27f45064b6 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -27,11 +27,11 @@ namespace AzFramework { AZ_TYPE_SAFE_INTEGRAL(SpawnablePriority, uint8_t); - inline static constexpr SpawnablePriority SpawnablePriorty_Highest { 0 }; - inline static constexpr SpawnablePriority SpawnablePriorty_High { 32 }; - inline static constexpr SpawnablePriority SpawnablePriorty_Default { 128 }; - inline static constexpr SpawnablePriority SpawnablePriorty_Low { 192 }; - inline static constexpr SpawnablePriority SpawnablePriorty_Lowest { 255 }; + inline static constexpr SpawnablePriority SpawnablePriority_Highest { 0 }; + inline static constexpr SpawnablePriority SpawnablePriority_High { 32 }; + inline static constexpr SpawnablePriority SpawnablePriority_Default { 128 }; + inline static constexpr SpawnablePriority SpawnablePriority_Low { 192 }; + inline static constexpr SpawnablePriority SpawnablePriority_Lowest { 255 }; class SpawnableEntityContainerView { @@ -154,7 +154,7 @@ namespace AzFramework EntitySpawnTicket& operator=(const EntitySpawnTicket&) = delete; EntitySpawnTicket& operator=(EntitySpawnTicket&& rhs); - uint64_t GetId() const; + Id GetId() const; bool IsValid() const; private: @@ -179,11 +179,11 @@ namespace AzFramework //! Calls on the same ticket are guaranteed to be executed in the order they are issued. Note that when issuing requests from //! multiple threads on the same ticket the order in which the requests are assigned to the ticket is not guaranteed. //! - //! Most calls have a priority where values closer to 0 mean higher priority than values closer to 255. The implementation of this + //! Most calls have a priority with values that range from 0 (highest priority) to 255 (lowest priority). The implementation of this //! interface may choose to use priority lanes which doesn't guarantee that higher priority requests happen before lower priority //! requests if they don't pass the priority lane threshold. Priority lanes and their thresholds are implementation specific and may //! differ between platforms. Note that if a call happened on a ticket with lower priority followed by a one with a higher priority - //! the first lower priority call will still needs to complete before the second higher priority call can be executed and the priority + //! the first lower priority call will still need to complete before the second higher priority call can be executed and the priority //! of the first call will not be updated. class SpawnableEntitiesDefinition { diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h index 373a4db9cb..afffdab8b5 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h @@ -207,6 +207,10 @@ namespace AzFramework AZ::Event> m_onSpawnedEvent; AZ::Event> m_onDespawnedEvent; + //! The threshold used to determine if a request goes in the regular (if bigger than the value) or high priority queue (if smaller + //! or equal to this value). The starting value of 64 is chosen as it's between default values SpawnablePriority_High and + //! SpawnablePriority_Default which gives users a bit of room to fine tune the priorities as this value can be configured + //! through the Settings Registry under the key "/O3DE/AzFramework/Spawnables/HighPriorityThreshold". SpawnablePriority m_highPriorityThreshold { 64 }; }; diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp index 32cc61914e..300ff1441e 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp @@ -60,8 +60,8 @@ namespace AzFramework void SpawnableSystemComponent::OnSystemTick() { - // Handle only high priority spawning events such as those created from network. These need to happen even if the server - // doesn't have focus to avoid + // Handle only high priority spawning events such as those created from network. These need to happen even if the client + // doesn't have focus to avoid time-out issues for instance. m_entitiesManager.ProcessQueue(SpawnableEntitiesManager::CommandQueuePriority::High); } diff --git a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp index 320e2ec435..484b7f46d7 100644 --- a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp +++ b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp @@ -104,7 +104,7 @@ namespace UnitTest { spawnedEntitiesCount += entities.size(); }; - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, {}, AZStd::move(callback)); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, {}, AZStd::move(callback)); m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); EXPECT_EQ(NumEntities, spawnedEntitiesCount); @@ -114,7 +114,7 @@ namespace UnitTest { { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->SpawnAllEntities(ticket, AzFramework::SpawnablePriorty_Default); + m_manager->SpawnAllEntities(ticket, AzFramework::SpawnablePriority_Default); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -128,7 +128,7 @@ namespace UnitTest { { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->SpawnEntities(ticket, AzFramework::SpawnablePriorty_Default, {}); + m_manager->SpawnEntities(ticket, AzFramework::SpawnablePriority_Default, {}); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -142,7 +142,7 @@ namespace UnitTest { { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->DespawnAllEntities(ticket, AzFramework::SpawnablePriorty_Default); + m_manager->DespawnAllEntities(ticket, AzFramework::SpawnablePriority_Default); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -156,7 +156,7 @@ namespace UnitTest { { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->ReloadSpawnable(ticket, AzFramework::SpawnablePriorty_Default, *m_spawnableAsset); + m_manager->ReloadSpawnable(ticket, AzFramework::SpawnablePriority_Default, *m_spawnableAsset); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -183,8 +183,8 @@ namespace UnitTest spawnedEntitiesCount += entities.size(); }; - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default); - m_manager->ListEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default); + m_manager->ListEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); EXPECT_TRUE(allValidEntityIds); @@ -197,7 +197,7 @@ namespace UnitTest { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->ListEntities(ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + m_manager->ListEntities(ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -228,8 +228,8 @@ namespace UnitTest } }; - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default); - m_manager->ListIndicesAndEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default); + m_manager->ListIndicesAndEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); EXPECT_TRUE(allValidEntityIds); @@ -242,7 +242,7 @@ namespace UnitTest { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->ListIndicesAndEntities(ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + m_manager->ListIndicesAndEntities(ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -258,7 +258,7 @@ namespace UnitTest { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->ClaimEntities(ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + m_manager->ClaimEntities(ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -274,7 +274,7 @@ namespace UnitTest { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->Barrier(ticket, AzFramework::SpawnablePriorty_Default, AZStd::move(callback)); + m_manager->Barrier(ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -305,8 +305,8 @@ namespace UnitTest defaultPriorityCallId = callCounter++; }; - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, {}, AZStd::move(defaultCallback)); - m_manager->SpawnAllEntities(highPriorityTicket, AzFramework::SpawnablePriorty_High, {}, AZStd::move(highCallback)); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, {}, AZStd::move(defaultCallback)); + m_manager->SpawnAllEntities(highPriorityTicket, AzFramework::SpawnablePriority_High, {}, AZStd::move(highCallback)); m_manager->ProcessQueue( AzFramework::SpawnableEntitiesManager::CommandQueuePriority::High | AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); @@ -333,8 +333,8 @@ namespace UnitTest defaultPriorityCallId = callCounter++; }; - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_Default, {}, AZStd::move(defaultCallback)); - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriorty_High, {}, AZStd::move(highCallback)); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, {}, AZStd::move(defaultCallback)); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_High, {}, AZStd::move(highCallback)); m_manager->ProcessQueue( AzFramework::SpawnableEntitiesManager::CommandQueuePriority::High | AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); From c2822a4063d3512166fe467c6fdaa43488885de3 Mon Sep 17 00:00:00 2001 From: guthadam Date: Thu, 27 May 2021 13:17:51 -0500 Subject: [PATCH 238/811] ATOM-15649 sorting material types in create material dialog --- .../Source/Window/CreateMaterialDialog/CreateMaterialDialog.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/CreateMaterialDialog/CreateMaterialDialog.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/CreateMaterialDialog/CreateMaterialDialog.cpp index 6a4bb8c0f4..887019787b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/CreateMaterialDialog/CreateMaterialDialog.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/CreateMaterialDialog/CreateMaterialDialog.cpp @@ -71,6 +71,8 @@ namespace MaterialEditor QObject::connect(m_ui->m_materialTypeComboBox, static_cast(&QComboBox::currentIndexChanged), this, [this]() { UpdateMaterialTypeSelection(); }); QObject::connect(m_ui->m_materialTypeComboBox, &QComboBox::currentTextChanged, this, [this]() { UpdateMaterialTypeSelection(); }); + m_ui->m_materialTypeComboBox->model()->sort(0, Qt::AscendingOrder); + // Select the default material type from settings auto settings = AZ::UserSettings::CreateFind(AZ::Crc32("MaterialDocumentSettings"), AZ::UserSettings::CT_GLOBAL); From cb62322f0d85094e14543569397291f6790087b5 Mon Sep 17 00:00:00 2001 From: sconel Date: Thu, 27 May 2021 11:58:56 -0700 Subject: [PATCH 239/811] Addressed PR feedback --- .../SpawnNodeable.ScriptCanvasNodeable.xml | 8 +- .../Libraries/Spawning/SpawnNodeable.cpp | 220 +++++++++--------- .../Libraries/Spawning/SpawnNodeable.h | 45 ++-- 3 files changed, 133 insertions(+), 140 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml index d0c4cfd806..e9b1ce9f4e 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.ScriptCanvasNodeable.xml @@ -10,16 +10,16 @@ Version="0" GeneratePropertyFriend="True" Namespace="ScriptCanvas" - Description="Spawn"> + Description="Spawns a selected prefab, positioned using the provided transform inputs"> - - + + - + /> diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index 37bb64745a..1bfd3e2386 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -15,127 +15,125 @@ #include #include -namespace ScriptCanvas +namespace ScriptCanvas::Nodeables::Spawning { - namespace Nodeables + SpawnNodeable::SpawnNodeable(const SpawnNodeable& rhs) + : m_spawnableAsset(rhs.m_spawnableAsset) + {} + + SpawnNodeable& SpawnNodeable::operator=(SpawnNodeable& rhs) { - namespace Spawning + m_spawnableAsset = rhs.m_spawnableAsset; + return *this; + } + + void SpawnNodeable::OnInitializeExecutionState() + { + if (!AZ::TickBus::Handler::BusIsConnected()) { - SpawnNodeable::SpawnNodeable(const SpawnNodeable& rhs) + AZ::TickBus::Handler::BusConnect(); + } + + m_spawnTicket = AzFramework::EntitySpawnTicket(m_spawnableAsset); + } + + void SpawnNodeable::OnDeactivate() + { + AZ::TickBus::Handler::BusDisconnect(); + + m_spawnTicket = AzFramework::EntitySpawnTicket(); + } + + void SpawnNodeable::OnTick([[maybe_unused]] float delta, [[maybe_unused]] AZ::ScriptTimePoint timePoint) + { + AZStd::vector swappedSpawnedEntityList; + AZStd::vector swappedSpawnBatchSizes; + { + AZStd::lock_guard lock(m_idBatchMutex); + + swappedSpawnedEntityList.swap(m_spawnedEntityList); + swappedSpawnBatchSizes.swap(m_spawnBatchSizes); + } + + AZ::EntityId* batchBegin = swappedSpawnedEntityList.data(); + for (size_t batchSize : swappedSpawnBatchSizes) + { + if (batchSize == 0) { - m_spawnableAsset = rhs.m_spawnableAsset; + continue; } - void SpawnNodeable::OnInitializeExecutionState() - { - if (!AZ::TickBus::Handler::BusIsConnected()) - { - AZ::TickBus::Handler::BusConnect(); - } + AZStd::vector spawnedEntitiesBatch( + batchBegin, batchBegin + batchSize); - m_spawnTicket = AzFramework::EntitySpawnTicket(m_spawnableAsset); + CallOnSpawn(AZStd::move(spawnedEntitiesBatch)); + + batchBegin += batchSize; + } + } + + void SpawnNodeable::OnSpawnAssetChanged() + { + if (m_spawnableAsset.GetId().IsValid()) + { + AZStd::string rootSpawnableFile; + AzFramework::StringFunc::Path::GetFileName(m_spawnableAsset.GetHint().c_str(), rootSpawnableFile); + + rootSpawnableFile += AzFramework::Spawnable::DotFileExtension; + + AZ::u32 rootSubId = AzFramework::SpawnableAssetHandler::BuildSubId(AZStd::move(rootSpawnableFile)); + + if (m_spawnableAsset.GetId().m_subId != rootSubId) + { + AZ::Data::AssetId rootAssetId = m_spawnableAsset.GetId(); + rootAssetId.m_subId = rootSubId; + + m_spawnableAsset = AZ::Data::AssetManager::Instance(). + FindOrCreateAsset(rootAssetId, AZ::Data::AssetLoadBehavior::PreLoad); } - - void SpawnNodeable::OnDeactivate() + else { - if (AZ::TickBus::Handler::BusIsConnected()) - { - AZ::TickBus::Handler::BusDisconnect(); - } - - m_spawnTicket = AzFramework::EntitySpawnTicket(); - } - - void SpawnNodeable::OnTick([[maybe_unused]] float delta, [[maybe_unused]] AZ::ScriptTimePoint timePoint) - { - AZStd::vector swappedSpawnedEntityList; - AZStd::vector swappedSpawnBatchSizes; - { - AZStd::lock_guard lock(m_idBatchMutex); - - swappedSpawnedEntityList.swap(m_spawnedEntityList); - swappedSpawnBatchSizes.swap(m_spawnBatchSizes); - } - - AZ::EntityId* batchBegin = swappedSpawnedEntityList.data(); - for (size_t batchSize : swappedSpawnBatchSizes) - { - if (batchSize == 0) - { - continue; - } - - AZStd::vector spawnedEntitiesBatch( - batchBegin, batchBegin + batchSize); - - CallOnSpawn(AZStd::move(spawnedEntitiesBatch)); - - batchBegin += batchSize; - } - } - - void SpawnNodeable::OnSpawnAssetChanged() - { - if (m_spawnableAsset.GetId().IsValid()) - { - AZStd::string rootSpawnableFile; - AzFramework::StringFunc::Path::GetFileName(m_spawnableAsset.GetHint().c_str(), rootSpawnableFile); - - rootSpawnableFile += AzFramework::Spawnable::DotFileExtension; - - AZ::u32 rootSubId = AzFramework::SpawnableAssetHandler::BuildSubId(AZStd::move(rootSpawnableFile)); - - if (m_spawnableAsset.GetId().m_subId != rootSubId) - { - AZ::Data::AssetId rootAssetId = m_spawnableAsset.GetId(); - rootAssetId.m_subId = rootSubId; - - m_spawnableAsset = AZ::Data::AssetManager::Instance(). - FindOrCreateAsset(rootAssetId, AZ::Data::AssetLoadBehavior::Default); - } - - m_spawnableAsset.SetAutoLoadBehavior(AZ::Data::AssetLoadBehavior::PreLoad); - } - } - - void SpawnNodeable::RequestSpawn(Data::Vector3Type translation, Data::Vector3Type rotation, Data::NumberType scale) - { - if (!m_spawnableAsset.IsReady()) - { - return; - } - - auto preSpawnCB = [this, translation, rotation, scale]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, - AzFramework::SpawnableEntityContainerView view) - { - AZ::Entity* rootEntity = *view.begin(); - - AzFramework::TransformComponent* entityTransform = - rootEntity->FindComponent(); - - if (entityTransform) - { - AZ::Vector3 rotationCopy = rotation; - AZ::Quaternion rotationQuat = AZ::Quaternion::CreateFromEulerAnglesDegrees(rotationCopy); - - entityTransform->SetWorldTM(AZ::Transform(translation, rotationQuat, AZ::Vector3(scale, scale, scale))); - } - }; - - auto spawnCompleteCB = [this]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, - AzFramework::SpawnableConstEntityContainerView view) - { - AZStd::lock_guard lock(m_idBatchMutex); - m_spawnedEntityList.reserve(m_spawnedEntityList.size() + view.size()); - for (const AZ::Entity* entity : view) - { - m_spawnedEntityList.emplace_back(entity->GetId()); - } - m_spawnBatchSizes.push_back(view.size()); - }; - - AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_spawnTicket, preSpawnCB, spawnCompleteCB); + m_spawnableAsset.SetAutoLoadBehavior(AZ::Data::AssetLoadBehavior::PreLoad); } } } + + void SpawnNodeable::RequestSpawn(Data::Vector3Type translation, Data::Vector3Type rotation, Data::NumberType scale) + { + if (!m_spawnableAsset.IsReady()) + { + return; + } + + auto preSpawnCB = [this, translation, rotation, scale]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, + AzFramework::SpawnableEntityContainerView view) + { + AZ::Entity* rootEntity = *view.begin(); + + AzFramework::TransformComponent* entityTransform = + rootEntity->FindComponent(); + + if (entityTransform) + { + AZ::Vector3 rotationCopy = rotation; + AZ::Quaternion rotationQuat = AZ::Quaternion::CreateFromEulerAnglesDegrees(rotationCopy); + + entityTransform->SetWorldTM(AZ::Transform(translation, rotationQuat, AZ::Vector3(scale, scale, scale))); + } + }; + + auto spawnCompleteCB = [this]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, + AzFramework::SpawnableConstEntityContainerView view) + { + AZStd::lock_guard lock(m_idBatchMutex); + m_spawnedEntityList.reserve(m_spawnedEntityList.size() + view.size()); + for (const AZ::Entity* entity : view) + { + m_spawnedEntityList.emplace_back(entity->GetId()); + } + m_spawnBatchSizes.push_back(view.size()); + }; + + AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_spawnTicket, preSpawnCB, spawnCompleteCB); + } } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h index 2b2a22601d..0f3a27d2ea 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.h @@ -22,36 +22,31 @@ #include #include -namespace ScriptCanvas +namespace ScriptCanvas::Nodeables::Spawning { - namespace Nodeables + class SpawnNodeable + : public ScriptCanvas::Nodeable, + public AZ::TickBus::Handler { - namespace Spawning - { - class SpawnNodeable - : public ScriptCanvas::Nodeable, - public AZ::TickBus::Handler - { - SCRIPTCANVAS_NODE(SpawnNodeable); - public: - SpawnNodeable() = default; - SpawnNodeable(const SpawnNodeable& rhs); + SCRIPTCANVAS_NODE(SpawnNodeable); + public: + SpawnNodeable() = default; + SpawnNodeable(const SpawnNodeable& rhs); + SpawnNodeable& operator=(SpawnNodeable& rhs); - void OnInitializeExecutionState() override; - void OnDeactivate() override; + void OnInitializeExecutionState() override; + void OnDeactivate() override; - //TickBus - void OnTick(float delta, AZ::ScriptTimePoint timePoint) override; + //TickBus + void OnTick(float delta, AZ::ScriptTimePoint timePoint) override; - void OnSpawnAssetChanged(); + void OnSpawnAssetChanged(); - private: - AzFramework::EntitySpawnTicket m_spawnTicket; + private: + AzFramework::EntitySpawnTicket m_spawnTicket; - AZStd::vector m_spawnedEntityList; - AZStd::vector m_spawnBatchSizes; - AZStd::recursive_mutex m_idBatchMutex; - }; - } - } + AZStd::vector m_spawnedEntityList; + AZStd::vector m_spawnBatchSizes; + AZStd::recursive_mutex m_idBatchMutex; + }; } From 18e479589d672a146ac6e8c1362ca481825c3723 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 01:51:09 -0500 Subject: [PATCH 240/811] Updating the Install_common.cmake ly_setup_o3de_install() function to be able forward all the ly_add_targets calls within a single source Engine CMakeLists.txt to a single installed Engine CMakeLists.txt --- cmake/LYWrappers.cmake | 9 + cmake/Platform/Common/Install_common.cmake | 367 +++++++++++---------- cmake/install/Copyright.in | 10 + cmake/install/TargetCMakeLists.txt.in | 11 - 4 files changed, 210 insertions(+), 187 deletions(-) create mode 100644 cmake/install/Copyright.in diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index ee0d66553a..bef3b25328 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -313,6 +313,15 @@ function(ly_add_target) # Store the target so we can walk through all of them in LocationDependencies.cmake set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGETS ${interface_name}) + # Store the aliased target into a DIRECTORY property + set_property(DIRECTORY APPEND PROPERTY LY_DIRECTORY_TARGETS ${interface_name}) + # Store the directory path in a GLOBAL property so that it can be accessed + # in the layout install logic. Skip if the directory has already been added + get_property(ly_all_target_directories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) + if(NOT CMAKE_CURRENT_SOURCE_DIR IN_LIST ly_all_target_directories) + set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGET_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}) + endif() + set(runtime_dependencies_list SHARED MODULE EXECUTABLE APPLICATION) if(NOT ly_add_target_IMPORTED AND linking_options IN_LIST runtime_dependencies_list) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 27b8d83a9c..aa9e710a0e 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -17,143 +17,190 @@ file(RELATIVE_PATH runtime_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_RUNTIME_ file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) set(install_output_folder "${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$") -#! ly_setup_targets: setups all targets -function(ly_setup_targets) - get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) - foreach(target IN LISTS all_targets) - ly_setup_target(${target}) + +#! ly_setup_subdirectories: setups all targets on a per directory basis +function(ly_setup_subdirectories) + get_property(all_subdirectories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) + foreach(target IN LISTS all_subdirectories) + ly_setup_subdirectory(${target}) endforeach() endfunction() -#! ly_setup_target: setups the target to be installed by cmake install. -function(ly_setup_target ALIAS_TARGET_NAME) - unset(TARGET_NAME) - ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) - - get_target_property(absolute_target_source_dir ${TARGET_NAME} SOURCE_DIR) +#! ly_setup_subdirectory: setup all targets in the subdirectory +function(ly_setup_subdirectory absolute_target_source_dir) + + file(READ ${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in target_cmakelists_template) + # The builtin BUILDSYSTEM_TARGETS property isn't being used here as that returns the de-alised + # TARGET and we need the alias namespace for recreating the CMakeLists.txt in the install layout + get_property(ALIAS_TARGETS_NAME DIRECTORY ${absolute_target_source_dir} PROPERTY LY_DIRECTORY_TARGETS) file(RELATIVE_PATH target_source_dir ${LY_ROOT_FOLDER} ${absolute_target_source_dir}) + foreach(ALIAS_TARGET_NAME IN LISTS ALIAS_TARGETS_NAME) + unset(TARGET_NAME) + ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) - # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that - # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the - # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. - # Instead, we install them with install(DIRECTORY) - set(include_location "include") - get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) - if (include_directories) - unset(public_headers) - foreach(include_directory ${include_directories}) - string(GENEX_STRIP ${include_directory} include_genex_expr) - if(include_genex_expr STREQUAL include_directory) # only for cases where there are no generation expressions - unset(current_public_headers) - install(DIRECTORY ${include_directory} - DESTINATION ${include_location}/${target_source_dir} - COMPONENT ${ly_install_target_COMPONENT} - FILES_MATCHING - PATTERN *.h - PATTERN *.hpp - PATTERN *.inl - ) - endif() - endforeach() - endif() - - # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target - file(RELATIVE_PATH archive_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) - - get_target_property(target_runtime_output_directory ${TARGET_NAME} RUNTIME_OUTPUT_DIRECTORY) - if(target_runtime_output_directory) - file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) - endif() - - get_target_property(target_library_output_directory ${TARGET_NAME} LIBRARY_OUTPUT_DIRECTORY) - if(target_library_output_directory) - file(RELATIVE_PATH target_library_output_subdirectory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${target_library_output_directory}) - endif() - - install( - TARGETS ${TARGET_NAME} - ARCHIVE - DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ - COMPONENT ${ly_install_target_COMPONENT} - LIBRARY - DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} - COMPONENT ${ly_install_target_COMPONENT} - RUNTIME - DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} - COMPONENT ${ly_install_target_COMPONENT} - ) - - # CMakeLists.txt file - string(REGEX MATCH "(.*)::(.*)$" match ${ALIAS_TARGET_NAME}) - if(match) - set(NAMESPACE_PLACEHOLDER "NAMESPACE ${CMAKE_MATCH_1}") - set(NAME_PLACEHOLDER ${CMAKE_MATCH_2}) - else() - set(NAMESPACE_PLACEHOLDER "") - set(NAME_PLACEHOLDER ${TARGET_NAME}) - endif() - - set(TARGET_TYPE_PLACEHOLDER "") - get_target_property(target_type ${NAME_PLACEHOLDER} TYPE) - # Remove the _LIBRARY since we dont need to pass that to ly_add_targets - string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type}) - # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead - string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER}) - if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE") - get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE) - if(gem_module) - set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE") + # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that + # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the + # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. + # Instead, we install them with install(DIRECTORY) + set(include_location "include") + get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) + if (include_directories) + unset(public_headers) + foreach(include_directory ${include_directories}) + string(GENEX_STRIP ${include_directory} include_genex_expr) + if(include_genex_expr STREQUAL include_directory) # only for cases where there are no generation expressions + unset(current_public_headers) + install(DIRECTORY ${include_directory} + DESTINATION ${include_location}/${target_source_dir} + COMPONENT ${ly_install_target_COMPONENT} + FILES_MATCHING + PATTERN *.h + PATTERN *.hpp + PATTERN *.inl + ) + endif() + endforeach() endif() - endif() - get_target_property(COMPILE_DEFINITIONS_PLACEHOLDER ${TARGET_NAME} INTERFACE_COMPILE_DEFINITIONS) - if(COMPILE_DEFINITIONS_PLACEHOLDER) - string(REPLACE ";" "\n" COMPILE_DEFINITIONS_PLACEHOLDER "${COMPILE_DEFINITIONS_PLACEHOLDER}") - else() - unset(COMPILE_DEFINITIONS_PLACEHOLDER) - endif() + # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target + file(RELATIVE_PATH archive_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) - # Includes need additional processing to add the install root - if(include_directories) - foreach(include ${include_directories}) - string(GENEX_STRIP ${include} include_genex_expr) - if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions - file(RELATIVE_PATH relative_include ${absolute_target_source_dir} ${include}) - string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}/${relative_include}\n") + get_target_property(target_runtime_output_directory ${TARGET_NAME} RUNTIME_OUTPUT_DIRECTORY) + if(target_runtime_output_directory) + file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) + endif() + + get_target_property(target_library_output_directory ${TARGET_NAME} LIBRARY_OUTPUT_DIRECTORY) + if(target_library_output_directory) + file(RELATIVE_PATH target_library_output_subdirectory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${target_library_output_directory}) + endif() + + install( + TARGETS ${TARGET_NAME} + ARCHIVE + DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ + COMPONENT ${ly_install_target_COMPONENT} + LIBRARY + DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} + COMPONENT ${ly_install_target_COMPONENT} + RUNTIME + DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} + COMPONENT ${ly_install_target_COMPONENT} + ) + + # CMakeLists.txt file + string(REGEX MATCH "(.*)::(.*)$" match ${ALIAS_TARGET_NAME}) + if(match) + set(NAMESPACE_PLACEHOLDER "NAMESPACE ${CMAKE_MATCH_1}") + set(NAME_PLACEHOLDER ${CMAKE_MATCH_2}) + else() + set(NAMESPACE_PLACEHOLDER "") + set(NAME_PLACEHOLDER ${TARGET_NAME}) + endif() + + set(TARGET_TYPE_PLACEHOLDER "") + get_target_property(target_type ${NAME_PLACEHOLDER} TYPE) + # Remove the _LIBRARY since we dont need to pass that to ly_add_targets + string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type}) + # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead + string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER}) + if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE") + get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE) + if(gem_module) + set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE") endif() - endforeach() - endif() + endif() - get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) - if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found - string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") - else() - unset(RUNTIME_DEPENDENCIES_PLACEHOLDER) - endif() + get_target_property(COMPILE_DEFINITIONS_PLACEHOLDER ${TARGET_NAME} INTERFACE_COMPILE_DEFINITIONS) + if(COMPILE_DEFINITIONS_PLACEHOLDER) + string(REPLACE ";" "\n" COMPILE_DEFINITIONS_PLACEHOLDER "${COMPILE_DEFINITIONS_PLACEHOLDER}") + else() + unset(COMPILE_DEFINITIONS_PLACEHOLDER) + endif() - get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES) - unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) - if(inteface_build_dependencies_props) - foreach(build_dependency ${inteface_build_dependencies_props}) - # Skip wrapping produced when targets are not created in the same directory - if(NOT ${build_dependency} MATCHES "^::@") - list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + # Includes need additional processing to add the install root + if(include_directories) + foreach(include ${include_directories}) + string(GENEX_STRIP ${include} include_genex_expr) + if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions + file(RELATIVE_PATH relative_include ${absolute_target_source_dir} ${include}) + string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}/${relative_include}\n") + endif() + endforeach() + endif() + + get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) + if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found + string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") + else() + unset(RUNTIME_DEPENDENCIES_PLACEHOLDER) + endif() + + get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES) + unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) + if(inteface_build_dependencies_props) + foreach(build_dependency ${inteface_build_dependencies_props}) + # Skip wrapping produced when targets are not created in the same directory + if(NOT ${build_dependency} MATCHES "^::@") + list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + endif() + endforeach() + endif() + # We also need to pass the private link libraries since we will use that to generate the runtime dependencies + get_target_property(private_build_dependencies_props ${TARGET_NAME} LINK_LIBRARIES) + if(private_build_dependencies_props) + foreach(build_dependency ${private_build_dependencies_props}) + # Skip wrapping produced when targets are not created in the same directory + if(NOT ${build_dependency} MATCHES "^::@") + list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + endif() + endforeach() + endif() + list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) + string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}") + + # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target + string(CONFIGURE ${target_cmakelists_template} configured_target @ONLY) + string(APPEND all_configured_targets "${configured_target}") + + # Config file + set(target_file_contents "# Generated by O3DE install\n\n") + if(NOT target_type STREQUAL INTERFACE_LIBRARY) + + unset(target_location) + set(runtime_types EXECUTABLE APPLICATION) + if(target_type IN_LIST runtime_types) + set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$") + elseif(target_type STREQUAL MODULE_LIBRARY) + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") + elseif(target_type STREQUAL SHARED_LIBRARY) + string(APPEND target_file_contents "set_property(TARGET ${TARGET_NAME} PROPERTY IMPORTED_IMPLIB_$ \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\")\n") + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") + else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY + set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") endif() - endforeach() - endif() - # We also need to pass the private link libraries since we will use that to generate the runtime dependencies - get_target_property(private_build_dependencies_props ${TARGET_NAME} LINK_LIBRARIES) - if(private_build_dependencies_props) - foreach(build_dependency ${private_build_dependencies_props}) - # Skip wrapping produced when targets are not created in the same directory - if(NOT ${build_dependency} MATCHES "^::@") - list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + + if(target_location) + string(APPEND target_file_contents + "set_property(TARGET ${TARGET_NAME} + APPEND_STRING PROPERTY IMPORTED_LOCATION + $<$$:${target_location}$ + ) + set_property(TARGET ${TARGET_NAME} + PROPERTY IMPORTED_LOCATION_$> + ${target_location} + ) + ") endif() - endforeach() - endif() - list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) - string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}") + endif() + + file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" + DESTINATION ${target_source_dir} + COMPONENT ${ly_install_target_COMPONENT} + ) + endforeach() # Replicate the ly_create_alias() calls based on the SOURCE_DIR for each target that generates an installed CMakeLists.txt string(JOIN "\n" create_alias_template @@ -174,48 +221,16 @@ function(ly_setup_target ALIAS_TARGET_NAME) string(APPEND CREATE_ALIASES_PLACEHOLDER ${create_alias_command}) endforeach() - # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target - configure_file(${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/CMakeLists.txt @ONLY) - - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/CMakeLists.txt" - DESTINATION ${target_source_dir}/${NAME_PLACEHOLDER} - COMPONENT ${ly_install_target_COMPONENT} + file(READ ${LY_ROOT_FOLDER}/cmake/install/Copyright.in cmake_copyright_comment) + # Write out all the agreegated ly_add_target function calls and the final ly_create_alias() calls to the target CMakeList.txt + file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/CMakeLists.txt + "${cmake_copyright_comment}" + "${all_configured_targets}" + "\n" + "${CREATE_ALIASES_PLACEHOLDER}" ) - - # Config file - set(target_file_contents "# Generated by O3DE install\n\n") - if(NOT target_type STREQUAL INTERFACE_LIBRARY) - - unset(target_location) - set(runtime_types EXECUTABLE APPLICATION) - if(target_type IN_LIST runtime_types) - set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$") - elseif(target_type STREQUAL MODULE_LIBRARY) - set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") - elseif(target_type STREQUAL SHARED_LIBRARY) - string(APPEND target_file_contents "set_property(TARGET ${TARGET_NAME} PROPERTY IMPORTED_IMPLIB_$ \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\")\n") - set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") - else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY - set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") - endif() - - if(target_location) - string(APPEND target_file_contents -"set_property(TARGET ${TARGET_NAME} - APPEND_STRING PROPERTY IMPORTED_LOCATION - $<$$:${target_location}$ -) -set_property(TARGET ${TARGET_NAME} - PROPERTY IMPORTED_LOCATION_$> - ${target_location} -) -") - endif() - endif() - - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${NAME_PLACEHOLDER}/${NAME_PLACEHOLDER}_$.cmake" - DESTINATION ${target_source_dir}/${NAME_PLACEHOLDER} + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/CMakeLists.txt" + DESTINATION ${target_source_dir} COMPONENT ${ly_install_target_COMPONENT} ) @@ -224,7 +239,7 @@ endfunction() #! ly_setup_o3de_install: orchestrates the installation of the different parts. This is the entry point from the root CMakeLists.txt function(ly_setup_o3de_install) - ly_setup_targets() + ly_setup_subdirectories() ly_setup_cmake_install() ly_setup_target_generator() ly_setup_runtime_dependencies() @@ -283,12 +298,12 @@ function(ly_setup_cmake_install) # Findo3de.cmake file: we generate a different Findo3de.camke file than the one we have in cmake. This one is going to expose all # targets that are pre-built - get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) unset(FIND_PACKAGES_PLACEHOLDER) - foreach(alias_target IN LISTS all_targets) - ly_de_alias_target(${alias_target} target) - get_target_property(target_source_dir ${target} SOURCE_DIR) - file(RELATIVE_PATH target_source_dir_relative ${LY_ROOT_FOLDER} ${target_source_dir}) + + # Add to the FIND_PACKAGES_PLACEHOLDER all directories in which ly_add_target were called in + get_property(all_subdirectories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) + foreach(target_subdirectory IN LISTS all_subdirectories) + file(RELATIVE_PATH target_source_dir_relative ${LY_ROOT_FOLDER} ${target_subdirectory}) string(APPEND FIND_PACKAGES_PLACEHOLDER " add_subdirectory(${target_source_dir_relative}/${target})\n") endforeach() @@ -339,7 +354,7 @@ function(ly_copy source_file target_directory) endfunction()" COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) - + unset(runtime_commands) get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) foreach(alias_target IN LISTS all_targets) @@ -350,12 +365,12 @@ endfunction()" if(NOT target_type IN_LIST LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS) continue() endif() - + get_target_property(target_runtime_output_directory ${target} RUNTIME_OUTPUT_DIRECTORY) if(target_runtime_output_directory) file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) endif() - + # Qt get_property(has_qt_dependency GLOBAL PROPERTY LY_DETECT_QT_DEPENDENCY_${target}) if(has_qt_dependency) @@ -374,7 +389,7 @@ endfunction()" foreach(runtime_dependency ${runtime_dependencies}) unset(runtime_command) ly_get_runtime_dependency_command(runtime_command ${runtime_dependency}) - string(CONFIGURE "${runtime_command}" runtime_command @ONLY) + string(CONFIGURE "${runtime_command}" runtime_command @ONLY) list(APPEND runtime_commands ${runtime_command}) endforeach() @@ -382,10 +397,10 @@ endfunction()" list(REMOVE_DUPLICATES runtime_commands) list(JOIN runtime_commands " " runtime_commands_str) # the spaces are just to see the right identation in the cmake_install.cmake file - install(CODE "${runtime_commands_str}" + install(CODE "${runtime_commands_str}" COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) - + endfunction() #! ly_setup_others: install directories required by the engine diff --git a/cmake/install/Copyright.in b/cmake/install/Copyright.in new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/cmake/install/Copyright.in @@ -0,0 +1,10 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# diff --git a/cmake/install/TargetCMakeLists.txt.in b/cmake/install/TargetCMakeLists.txt.in index 06cd022898..0503fd5f2b 100644 --- a/cmake/install/TargetCMakeLists.txt.in +++ b/cmake/install/TargetCMakeLists.txt.in @@ -1,13 +1,3 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# # Generated by O3DE @@ -27,7 +17,6 @@ ly_add_target( @RUNTIME_DEPENDENCIES_PLACEHOLDER@ ) -@CREATE_ALIASES_PLACEHOLDER@ set(configs @CMAKE_CONFIGURATION_TYPES@) foreach(config ${configs}) include("@NAME_PLACEHOLDER@_${config}.cmake" OPTIONAL) From 78afc45709a26a03c30a1d8159671a91482840c8 Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 27 May 2021 12:39:14 -0700 Subject: [PATCH 241/811] [ftue_auto_register] add logic to auto register engine if it is not already --- .../ProjectManager/Source/PythonBindings.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 8c79a153c8..0672e02ff4 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -286,6 +286,30 @@ namespace O3DE::ProjectManager m_registration = pybind11::module::import("cmake.Tools.registration"); m_engineTemplate = pybind11::module::import("cmake.Tools.engine_template"); + // register the current engine if it isn't already + bool registerThis = true; + auto allEngines = m_registration.attr("get_engines")(); + if (pybind11::isinstance(allEngines)) + { + for (const auto& engine : allEngines) + { + AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"])); + if (enginePath.Compare(m_enginePath) == 0) + { + registerThis = false; + break; + } + } + } + + if (registerThis) + { + auto registrationResult = m_registration.attr("register")(m_enginePath.c_str()); + + AZ_Error("ProjectManagerWindow", registrationResult.cast() == 0, + "Registration of this engine failed!"); + } + return result == 0 && !PyErr_Occurred(); } catch ([[maybe_unused]] const std::exception& e) { From f6568f5c639849a890d9cef803d7b6fd4ba5b66b Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 12:36:33 -0500 Subject: [PATCH 242/811] Re-added back an ly_setup_target function which configures the CMakeLists.txt template for a single target --- cmake/Platform/Common/Install_common.cmake | 336 +++++++++++---------- 1 file changed, 171 insertions(+), 165 deletions(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index aa9e710a0e..939f523d75 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -18,6 +18,175 @@ file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_ set(install_output_folder "${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$") +#! ly_setup_target: Setup the data needed to re-create the cmake target commands for a single target +function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME) + # De-alias target name + ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) + + # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that + # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the + # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. + # Instead, we install them with install(DIRECTORY) + set(include_location "include") + get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) + if (include_directories) + unset(public_headers) + foreach(include_directory ${include_directories}) + string(GENEX_STRIP ${include_directory} include_genex_expr) + if(include_genex_expr STREQUAL include_directory) # only for cases where there are no generation expressions + unset(current_public_headers) + install(DIRECTORY ${include_directory} + DESTINATION ${include_location}/${target_source_dir} + COMPONENT ${ly_install_target_COMPONENT} + FILES_MATCHING + PATTERN *.h + PATTERN *.hpp + PATTERN *.inl + ) + endif() + endforeach() + endif() + + # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target + file(RELATIVE_PATH archive_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) + + get_target_property(target_runtime_output_directory ${TARGET_NAME} RUNTIME_OUTPUT_DIRECTORY) + if(target_runtime_output_directory) + file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) + endif() + + get_target_property(target_library_output_directory ${TARGET_NAME} LIBRARY_OUTPUT_DIRECTORY) + if(target_library_output_directory) + file(RELATIVE_PATH target_library_output_subdirectory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${target_library_output_directory}) + endif() + + install( + TARGETS ${TARGET_NAME} + ARCHIVE + DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ + COMPONENT ${ly_install_target_COMPONENT} + LIBRARY + DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} + COMPONENT ${ly_install_target_COMPONENT} + RUNTIME + DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} + COMPONENT ${ly_install_target_COMPONENT} + ) + + # CMakeLists.txt file + string(REGEX MATCH "(.*)::(.*)$" match ${ALIAS_TARGET_NAME}) + if(match) + set(NAMESPACE_PLACEHOLDER "NAMESPACE ${CMAKE_MATCH_1}") + set(NAME_PLACEHOLDER ${CMAKE_MATCH_2}) + else() + set(NAMESPACE_PLACEHOLDER "") + set(NAME_PLACEHOLDER ${TARGET_NAME}) + endif() + + set(TARGET_TYPE_PLACEHOLDER "") + get_target_property(target_type ${NAME_PLACEHOLDER} TYPE) + # Remove the _LIBRARY since we dont need to pass that to ly_add_targets + string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type}) + # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead + string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER}) + if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE") + get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE) + if(gem_module) + set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE") + endif() + endif() + + get_target_property(COMPILE_DEFINITIONS_PLACEHOLDER ${TARGET_NAME} INTERFACE_COMPILE_DEFINITIONS) + if(COMPILE_DEFINITIONS_PLACEHOLDER) + string(REPLACE ";" "\n" COMPILE_DEFINITIONS_PLACEHOLDER "${COMPILE_DEFINITIONS_PLACEHOLDER}") + else() + unset(COMPILE_DEFINITIONS_PLACEHOLDER) + endif() + + # Includes need additional processing to add the install root + if(include_directories) + foreach(include ${include_directories}) + string(GENEX_STRIP ${include} include_genex_expr) + if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions + file(RELATIVE_PATH relative_include ${absolute_target_source_dir} ${include}) + string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}/${relative_include}\n") + endif() + endforeach() + endif() + + get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) + if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found + string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") + else() + unset(RUNTIME_DEPENDENCIES_PLACEHOLDER) + endif() + + get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES) + unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) + if(inteface_build_dependencies_props) + foreach(build_dependency ${inteface_build_dependencies_props}) + # Skip wrapping produced when targets are not created in the same directory + if(NOT ${build_dependency} MATCHES "^::@") + list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + endif() + endforeach() + endif() + # We also need to pass the private link libraries since we will use that to generate the runtime dependencies + get_target_property(private_build_dependencies_props ${TARGET_NAME} LINK_LIBRARIES) + if(private_build_dependencies_props) + foreach(build_dependency ${private_build_dependencies_props}) + # Skip wrapping produced when targets are not created in the same directory + if(NOT ${build_dependency} MATCHES "^::@") + list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") + endif() + endforeach() + endif() + list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) + string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}") + + # Config file + set(target_file_contents "# Generated by O3DE install\n\n") + if(NOT target_type STREQUAL INTERFACE_LIBRARY) + + unset(target_location) + set(runtime_types EXECUTABLE APPLICATION) + if(target_type IN_LIST runtime_types) + set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$") + elseif(target_type STREQUAL MODULE_LIBRARY) + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") + elseif(target_type STREQUAL SHARED_LIBRARY) + string(APPEND target_file_contents "set_property(TARGET ${TARGET_NAME} PROPERTY IMPORTED_IMPLIB_$ \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\")\n") + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") + else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY + set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") + endif() + + if(target_location) + string(APPEND target_file_contents +"set_property(TARGET ${TARGET_NAME} + APPEND_STRING PROPERTY IMPORTED_LOCATION + $<$$:${target_location}$ +) +set_property(TARGET ${TARGET_NAME} + PROPERTY IMPORTED_LOCATION_$> + ${target_location} +) +") + endif() + endif() + + file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" + DESTINATION ${target_source_dir} + COMPONENT ${ly_install_target_COMPONENT} + ) + + # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target + file(READ ${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in target_cmakelists_template) + string(CONFIGURE ${target_cmakelists_template} output_cmakelists_data @ONLY) + set(${OUTPUT_CONFIGURED_TARGET} ${output_cmakelists_data} PARENT_SCOPE) +endfunction() + #! ly_setup_subdirectories: setups all targets on a per directory basis function(ly_setup_subdirectories) get_property(all_subdirectories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) @@ -30,176 +199,13 @@ endfunction() #! ly_setup_subdirectory: setup all targets in the subdirectory function(ly_setup_subdirectory absolute_target_source_dir) - file(READ ${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in target_cmakelists_template) # The builtin BUILDSYSTEM_TARGETS property isn't being used here as that returns the de-alised # TARGET and we need the alias namespace for recreating the CMakeLists.txt in the install layout get_property(ALIAS_TARGETS_NAME DIRECTORY ${absolute_target_source_dir} PROPERTY LY_DIRECTORY_TARGETS) file(RELATIVE_PATH target_source_dir ${LY_ROOT_FOLDER} ${absolute_target_source_dir}) foreach(ALIAS_TARGET_NAME IN LISTS ALIAS_TARGETS_NAME) - unset(TARGET_NAME) - ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) - - # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that - # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the - # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. - # Instead, we install them with install(DIRECTORY) - set(include_location "include") - get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) - if (include_directories) - unset(public_headers) - foreach(include_directory ${include_directories}) - string(GENEX_STRIP ${include_directory} include_genex_expr) - if(include_genex_expr STREQUAL include_directory) # only for cases where there are no generation expressions - unset(current_public_headers) - install(DIRECTORY ${include_directory} - DESTINATION ${include_location}/${target_source_dir} - COMPONENT ${ly_install_target_COMPONENT} - FILES_MATCHING - PATTERN *.h - PATTERN *.hpp - PATTERN *.inl - ) - endif() - endforeach() - endif() - - # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target - file(RELATIVE_PATH archive_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) - - get_target_property(target_runtime_output_directory ${TARGET_NAME} RUNTIME_OUTPUT_DIRECTORY) - if(target_runtime_output_directory) - file(RELATIVE_PATH target_runtime_output_subdirectory ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ${target_runtime_output_directory}) - endif() - - get_target_property(target_library_output_directory ${TARGET_NAME} LIBRARY_OUTPUT_DIRECTORY) - if(target_library_output_directory) - file(RELATIVE_PATH target_library_output_subdirectory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${target_library_output_directory}) - endif() - - install( - TARGETS ${TARGET_NAME} - ARCHIVE - DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ - COMPONENT ${ly_install_target_COMPONENT} - LIBRARY - DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} - COMPONENT ${ly_install_target_COMPONENT} - RUNTIME - DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} - COMPONENT ${ly_install_target_COMPONENT} - ) - - # CMakeLists.txt file - string(REGEX MATCH "(.*)::(.*)$" match ${ALIAS_TARGET_NAME}) - if(match) - set(NAMESPACE_PLACEHOLDER "NAMESPACE ${CMAKE_MATCH_1}") - set(NAME_PLACEHOLDER ${CMAKE_MATCH_2}) - else() - set(NAMESPACE_PLACEHOLDER "") - set(NAME_PLACEHOLDER ${TARGET_NAME}) - endif() - - set(TARGET_TYPE_PLACEHOLDER "") - get_target_property(target_type ${NAME_PLACEHOLDER} TYPE) - # Remove the _LIBRARY since we dont need to pass that to ly_add_targets - string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type}) - # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead - string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER}) - if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE") - get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE) - if(gem_module) - set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE") - endif() - endif() - - get_target_property(COMPILE_DEFINITIONS_PLACEHOLDER ${TARGET_NAME} INTERFACE_COMPILE_DEFINITIONS) - if(COMPILE_DEFINITIONS_PLACEHOLDER) - string(REPLACE ";" "\n" COMPILE_DEFINITIONS_PLACEHOLDER "${COMPILE_DEFINITIONS_PLACEHOLDER}") - else() - unset(COMPILE_DEFINITIONS_PLACEHOLDER) - endif() - - # Includes need additional processing to add the install root - if(include_directories) - foreach(include ${include_directories}) - string(GENEX_STRIP ${include} include_genex_expr) - if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions - file(RELATIVE_PATH relative_include ${absolute_target_source_dir} ${include}) - string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/include/${target_source_dir}/${relative_include}\n") - endif() - endforeach() - endif() - - get_target_property(RUNTIME_DEPENDENCIES_PLACEHOLDER ${TARGET_NAME} MANUALLY_ADDED_DEPENDENCIES) - if(RUNTIME_DEPENDENCIES_PLACEHOLDER) # not found properties return the name of the variable with a "-NOTFOUND" at the end, here we set it to empty if not found - string(REPLACE ";" "\n" RUNTIME_DEPENDENCIES_PLACEHOLDER "${RUNTIME_DEPENDENCIES_PLACEHOLDER}") - else() - unset(RUNTIME_DEPENDENCIES_PLACEHOLDER) - endif() - - get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES) - unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) - if(inteface_build_dependencies_props) - foreach(build_dependency ${inteface_build_dependencies_props}) - # Skip wrapping produced when targets are not created in the same directory - if(NOT ${build_dependency} MATCHES "^::@") - list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") - endif() - endforeach() - endif() - # We also need to pass the private link libraries since we will use that to generate the runtime dependencies - get_target_property(private_build_dependencies_props ${TARGET_NAME} LINK_LIBRARIES) - if(private_build_dependencies_props) - foreach(build_dependency ${private_build_dependencies_props}) - # Skip wrapping produced when targets are not created in the same directory - if(NOT ${build_dependency} MATCHES "^::@") - list(APPEND INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${build_dependency}") - endif() - endforeach() - endif() - list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER) - string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}") - - # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target - string(CONFIGURE ${target_cmakelists_template} configured_target @ONLY) + ly_setup_target(configured_target ${ALIAS_TARGET_NAME}) string(APPEND all_configured_targets "${configured_target}") - - # Config file - set(target_file_contents "# Generated by O3DE install\n\n") - if(NOT target_type STREQUAL INTERFACE_LIBRARY) - - unset(target_location) - set(runtime_types EXECUTABLE APPLICATION) - if(target_type IN_LIST runtime_types) - set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$") - elseif(target_type STREQUAL MODULE_LIBRARY) - set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") - elseif(target_type STREQUAL SHARED_LIBRARY) - string(APPEND target_file_contents "set_property(TARGET ${TARGET_NAME} PROPERTY IMPORTED_IMPLIB_$ \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\")\n") - set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") - else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY - set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") - endif() - - if(target_location) - string(APPEND target_file_contents - "set_property(TARGET ${TARGET_NAME} - APPEND_STRING PROPERTY IMPORTED_LOCATION - $<$$:${target_location}$ - ) - set_property(TARGET ${TARGET_NAME} - PROPERTY IMPORTED_LOCATION_$> - ${target_location} - ) - ") - endif() - endif() - - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" - DESTINATION ${target_source_dir} - COMPONENT ${ly_install_target_COMPONENT} - ) endforeach() # Replicate the ly_create_alias() calls based on the SOURCE_DIR for each target that generates an installed CMakeLists.txt @@ -304,7 +310,7 @@ function(ly_setup_cmake_install) get_property(all_subdirectories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) foreach(target_subdirectory IN LISTS all_subdirectories) file(RELATIVE_PATH target_source_dir_relative ${LY_ROOT_FOLDER} ${target_subdirectory}) - string(APPEND FIND_PACKAGES_PLACEHOLDER " add_subdirectory(${target_source_dir_relative}/${target})\n") + string(APPEND FIND_PACKAGES_PLACEHOLDER " add_subdirectory(${target_source_dir_relative})\n") endforeach() configure_file(${LY_ROOT_FOLDER}/cmake/install/Findo3de.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/Findo3de.cmake @ONLY) From 85222130d4137d79c994b273f88dc7c39fc12929 Mon Sep 17 00:00:00 2001 From: Qing Tao <55564570+VickyAtAZ@users.noreply.github.com> Date: Thu, 27 May 2021 13:56:19 -0700 Subject: [PATCH 243/811] LYN-4007 Editor crashes when entering the Game Mode with two Box Shape entities with Game View enabled (#974) The crash was caused by using gpu query across command lists. --- .../Code/Source/RPI.Public/GpuQuery/Query.cpp | 12 --------- .../Source/RPI.Public/Pass/RenderPass.cpp | 26 ++++++++++++++++--- .../RPI/Code/Tests/System/GpuQueryTests.cpp | 12 ++++++--- ...AtomViewportDisplayInfoSystemComponent.cpp | 8 +++--- 4 files changed, 36 insertions(+), 22 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/GpuQuery/Query.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/GpuQuery/Query.cpp index 227e096594..1d6e8cdc65 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/GpuQuery/Query.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/GpuQuery/Query.cpp @@ -96,12 +96,6 @@ namespace AZ return QueryResultCode::Fail; } - // Limit calling BeginQuery() to the first CommandList in the array. - if (context.GetCommandListIndex() != 0) - { - return QueryResultCode::Success; - } - const auto rhiQueryIndices = GetRhiQueryIndicesFromCurrentFrame(); if (!rhiQueryIndices) { @@ -124,12 +118,6 @@ namespace AZ return QueryResultCode::Fail; } - // Limit calling EndQuery() to the last CommandList in the array. - if (context.GetCommandListIndex() != context.GetCommandListCount() - 1) - { - return QueryResultCode::Success; - } - // Validate that the queries are recorded for the same scope. if (m_cachedScopeId != context.GetScopeId()) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp index 9c6a95e582..3a2a556429 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp @@ -522,8 +522,11 @@ namespace AZ } }; - ExecuteOnTimestampQuery(beginQuery); - ExecuteOnPipelineStatisticsQuery(beginQuery); + if (context.GetCommandListIndex() == 0) + { + ExecuteOnTimestampQuery(beginQuery); + ExecuteOnPipelineStatisticsQuery(beginQuery); + } } void RenderPass::EndScopeQuery(const RHI::FrameGraphExecuteContext& context) @@ -533,8 +536,23 @@ namespace AZ query->EndQuery(context); }; - ExecuteOnTimestampQuery(endQuery); - ExecuteOnPipelineStatisticsQuery(endQuery); + // This scopy query implmentation should be replaced by + // [ATOM-5407] [RHI][Core] - Add GPU timestamp and pipeline statistic support for scopes + + // For timestamp query, it's okay to execute across different command lists + if (context.GetCommandListIndex() == context.GetCommandListCount() - 1) + { + ExecuteOnTimestampQuery(endQuery); + } + // For all the other types of queries except timestamp, the query start and end has to be in the same command list + // Here only tracks the PipelineStatistics for the first command list due to that we don't know how many queries are + // needed when AddScopeQueryToFrameGraph is called. + // This implementation leads to an issue that we may not get accurate pipeline statistic data + // for passes which were executed with more than one command list + if (context.GetCommandListIndex() == 0) + { + ExecuteOnPipelineStatisticsQuery(endQuery); + } } void RenderPass::ReadbackScopeQueryResults() diff --git a/Gems/Atom/RPI/Code/Tests/System/GpuQueryTests.cpp b/Gems/Atom/RPI/Code/Tests/System/GpuQueryTests.cpp index e55ec8012b..98ff6befdd 100644 --- a/Gems/Atom/RPI/Code/Tests/System/GpuQueryTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/System/GpuQueryTests.cpp @@ -159,7 +159,9 @@ namespace UnitTest const uint32_t ResultSize = sizeof(uint64_t); uint64_t mockData; - const RHI::FrameGraphExecuteContext::Descriptor desc = {}; + RHI::FrameGraphExecuteContext::Descriptor desc = {}; + uint64_t dummyCommandList; + desc.m_commandList = reinterpret_cast(&dummyCommandList); RHI::FrameGraphExecuteContext context(desc); RHI::Scope scope; @@ -209,7 +211,9 @@ namespace UnitTest const uint32_t ResultSize = sizeof(uint64_t) * 4u; uint64_t mockData; - const RHI::FrameGraphExecuteContext::Descriptor desc = {}; + RHI::FrameGraphExecuteContext::Descriptor desc = {}; + uint64_t dummyCommandList; + desc.m_commandList = reinterpret_cast(&dummyCommandList); RHI::FrameGraphExecuteContext context(desc); RHI::Scope scope; @@ -273,7 +277,9 @@ namespace UnitTest const uint32_t ResultSize = sizeof(uint64_t) * 2u; uint64_t mockData; - const RHI::FrameGraphExecuteContext::Descriptor desc = {}; + RHI::FrameGraphExecuteContext::Descriptor desc = {}; + uint64_t dummyCommandList; + desc.m_commandList = reinterpret_cast(&dummyCommandList); RHI::FrameGraphExecuteContext context(desc); RHI::Scope scope; diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp index 672c26a9ab..7d830b4ca9 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp @@ -18,10 +18,11 @@ #include #include +#include +#include #include #include #include -#include #include #include @@ -146,7 +147,7 @@ namespace AZ::Render if (m_updateRootPassQuery) { - if (auto rootPass = AZ::RPI::PassSystemInterface::Get()->GetRootPass()) + if (auto rootPass = viewportContext->GetCurrentPipeline()->GetRootPass()) { rootPass->SetPipelineStatisticsQueryEnabled(displayLevel != AtomBridge::ViewportInfoDisplayState::CompactInfo); m_updateRootPassQuery = false; @@ -226,7 +227,8 @@ namespace AZ::Render void AtomViewportDisplayInfoSystemComponent::DrawPassInfo() { - auto rootPass = AZ::RPI::PassSystemInterface::Get()->GetRootPass(); + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + auto rootPass = viewportContext->GetCurrentPipeline()->GetRootPass(); const RPI::PipelineStatisticsResult stats = rootPass->GetLatestPipelineStatisticsResult(); AZStd::function)> containingPassCount = [&containingPassCount](const AZ::RPI::Ptr pass) { From 0d7c23641aca8db473c310a25c8e707df252f9c3 Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Thu, 27 May 2021 14:12:29 -0700 Subject: [PATCH 244/811] Fix missing space betweek arguments causing dxc commands with additional args to fail (#1003) --- Gems/Atom/RHI/Code/Source/RHI.Edit/ShaderCompilerArguments.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/RHI/Code/Source/RHI.Edit/ShaderCompilerArguments.cpp b/Gems/Atom/RHI/Code/Source/RHI.Edit/ShaderCompilerArguments.cpp index 3a04bf6b88..09cd1c125e 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Edit/ShaderCompilerArguments.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Edit/ShaderCompilerArguments.cpp @@ -164,7 +164,7 @@ namespace AZ arguments += " -Zi"; // Generate debug information arguments += " -Zss"; // Compute Shader Hash considering source information } - arguments += m_dxcAdditionalFreeArguments; + arguments += " " + m_dxcAdditionalFreeArguments; return arguments; } } From ecc18338fa0ef9f71c9ee4956ae7275a5cbf91af Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 27 May 2021 14:19:31 -0700 Subject: [PATCH 245/811] [ftue_auto_register] move engine registration check into private helper function --- .../ProjectManager/Source/PythonBindings.cpp | 56 +++++++++++-------- .../ProjectManager/Source/PythonBindings.h | 2 + 2 files changed, 35 insertions(+), 23 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 0672e02ff4..90e18f5f27 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -286,29 +286,8 @@ namespace O3DE::ProjectManager m_registration = pybind11::module::import("cmake.Tools.registration"); m_engineTemplate = pybind11::module::import("cmake.Tools.engine_template"); - // register the current engine if it isn't already - bool registerThis = true; - auto allEngines = m_registration.attr("get_engines")(); - if (pybind11::isinstance(allEngines)) - { - for (const auto& engine : allEngines) - { - AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"])); - if (enginePath.Compare(m_enginePath) == 0) - { - registerThis = false; - break; - } - } - } - - if (registerThis) - { - auto registrationResult = m_registration.attr("register")(m_enginePath.c_str()); - - AZ_Error("ProjectManagerWindow", registrationResult.cast() == 0, - "Registration of this engine failed!"); - } + // make sure the engine is registered + RegisterThisEngine(); return result == 0 && !PyErr_Occurred(); } catch ([[maybe_unused]] const std::exception& e) @@ -332,6 +311,37 @@ namespace O3DE::ProjectManager return !PyErr_Occurred(); } + bool PythonBindings::RegisterThisEngine() + { + bool registerThis = true; + + // check current engine path against all other registered engines + // to see if we are already registered + auto allEngines = m_registration.attr("get_engines")(); + if (pybind11::isinstance(allEngines)) + { + for (const auto& engine : allEngines) + { + AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"])); + if (enginePath.Compare(m_enginePath) == 0) + { + registerThis = false; + break; + } + } + } + + bool result = true; + if (registerThis) + { + auto registrationResult = m_registration.attr("register")(m_enginePath.c_str()); + result = (registrationResult.cast() == 0); + } + + AZ_Error("ProjectManagerWindow", result, "Registration of this engine failed!"); + return result; + } + bool PythonBindings::ExecuteWithLock(AZStd::function executionCallback) { AZStd::lock_guard lock(m_lock); diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h index 892e13a65b..71616de4e0 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.h +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -60,9 +60,11 @@ namespace O3DE::ProjectManager GemInfo GemInfoFromPath(pybind11::handle path); ProjectInfo ProjectInfoFromPath(pybind11::handle path); ProjectTemplateInfo ProjectTemplateInfoFromPath(pybind11::handle path); + bool RegisterThisEngine(); bool StartPython(); bool StopPython(); + AZ::IO::FixedMaxPath m_enginePath; pybind11::handle m_engineTemplate; AZStd::recursive_mutex m_lock; From 8919530ac532b4e9fc86b1437fae2366ce70ae7b Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 27 May 2021 22:34:54 +0100 Subject: [PATCH 246/811] add version converter to remove vector scale from transforms in trackview sequences --- .../Code/Source/Cinematics/AnimNode.cpp | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimNode.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimNode.cpp index ec6bf4258a..7fea8097ed 100644 --- a/Gems/Maestro/Code/Source/Cinematics/AnimNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/AnimNode.cpp @@ -280,6 +280,45 @@ static bool AnimNodeVersionConverter( rootElement.AddElement(serializeContext, "BaseClass1", azrtti_typeid()); } + if (rootElement.GetVersion() < 4) + { + // remove vector scale tracks from transform anim nodes + AZStd::string name; + if (rootElement.FindSubElementAndGetData(AZ_CRC_CE("Name"), name) && name == "Transform") + { + auto tracksElement = rootElement.FindSubElement(AZ_CRC_CE("Tracks")); + if (tracksElement) + { + for (int trackIndex = tracksElement->GetNumSubElements() - 1; trackIndex >= 0; trackIndex--) + { + auto trackElement = tracksElement->GetSubElement(trackIndex); + bool isScale = false; + + // trackElement should be an intrusive_ptr with one child + if (trackElement.GetNumSubElements() == 1) + { + auto ptrElement = trackElement.GetSubElement(0); + auto paramTypeElement = ptrElement.FindSubElement(AZ_CRC_CE("ParamType")); + if (paramTypeElement) + { + AZStd::string paramName; + if (paramTypeElement->FindSubElementAndGetData(AZ_CRC_CE("Name"), paramName) && paramName == "Scale") + { + isScale = true; + } + } + } + + if (isScale) + { + tracksElement->RemoveElement(trackIndex); + } + } + } + } + + } + return true; } @@ -288,7 +327,7 @@ void CAnimNode::Reflect(AZ::ReflectContext* context) if (auto serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(3, &AnimNodeVersionConverter) + ->Version(4, &AnimNodeVersionConverter) ->Field("ID", &CAnimNode::m_id) ->Field("Name", &CAnimNode::m_name) ->Field("Flags", &CAnimNode::m_flags) From 1fa7adb185a7ed066116e17711b3b1bd45ed53c8 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 14:42:50 -0700 Subject: [PATCH 247/811] Adding missing gem.json files --- .../AtomViewportDisplayIcons/gem.json | 10 ++++++++++ .../AtomLyIntegration/AtomViewportDisplayInfo/gem.json | 10 ++++++++++ 2 files changed, 20 insertions(+) create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayIcons/gem.json create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/gem.json b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/gem.json new file mode 100644 index 0000000000..41f69e33a0 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "AtomViewportDisplayIcons", + "display_name": "Atom Viewport Display Icons", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json new file mode 100644 index 0000000000..04e2464a26 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "AtomViewportDisplayInfo", + "display_name": "Atom Viewport Display Info", + "summary": "", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + ] +} From 394ac7ab6a1255bd34099dbcba214544801fa952 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 16:44:50 -0500 Subject: [PATCH 248/811] Updated the enable gem and disable gem API (#54) * Updated the enable gem and disable gem API Renamed remove_gem_project.py -> disable_gem.py Renamed add_gem_project.py -> enable_gem.py Renamed the "add-gem-to-project" command -> "enable-gem" Renamed the "remove-gem-from-project" command -> "disable-gem" Fixed the parsing of the enabled gems from the enabled_gems.cmake file * Adding newline to the end of the CMakeLists.txt --- .../ProjectManager/Source/PythonBindings.cpp | 8 +- .../ProjectManager/Source/PythonBindings.h | 4 +- scripts/o3de.py | 6 +- scripts/o3de/o3de/cmake.py | 28 +- .../{remove_gem_project.py => disable_gem.py} | 74 ++--- .../{add_gem_project.py => enable_gem.py} | 66 ++--- scripts/o3de/o3de/manifest.py | 68 +++-- scripts/o3de/tests/CMakeLists.txt | 7 + .../o3de/tests/unit_test_add_remove_gem.py | 259 ------------------ scripts/o3de/tests/unit_test_cmake.py | 69 +++++ scripts/project_manager/projects.py | 10 +- 11 files changed, 208 insertions(+), 391 deletions(-) rename scripts/o3de/o3de/{remove_gem_project.py => disable_gem.py} (69%) rename scripts/o3de/o3de/{add_gem_project.py => enable_gem.py} (76%) delete mode 100755 scripts/o3de/tests/unit_test_add_remove_gem.py create mode 100644 scripts/o3de/tests/unit_test_cmake.py diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index c1e62f9c04..71d3c6de63 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -286,8 +286,8 @@ namespace O3DE::ProjectManager m_register = pybind11::module::import("o3de.register"); m_manifest = pybind11::module::import("o3de.manifest"); m_engineTemplate = pybind11::module::import("o3de.engine_template"); - m_addGemProject = pybind11::module::import("o3de.add_gem_project"); - m_removeGemProject = pybind11::module::import("o3de.remove_gem_project"); + m_enableGemProject = pybind11::module::import("o3de.enable_gem"); + m_disableGemProject = pybind11::module::import("o3de.disable_gem"); return result == 0 && !PyErr_Occurred(); } catch ([[maybe_unused]] const std::exception& e) @@ -588,7 +588,7 @@ namespace O3DE::ProjectManager pybind11::str pyGemPath = gemPath.toStdString(); pybind11::str pyProjectPath = projectPath.toStdString(); - m_addGemProject.attr("add_gem_to_project")( + m_enableGemProject.attr("enable_gem_in_project")( pybind11::none(), // gem_name pyGemPath, pybind11::none(), // project_name @@ -605,7 +605,7 @@ namespace O3DE::ProjectManager pybind11::str pyGemPath = gemPath.toStdString(); pybind11::str pyProjectPath = projectPath.toStdString(); - m_removeGemProject.attr("remove_gem_from_project")( + m_disableGemProject.attr("disable_gem_in_project")( pybind11::none(), // gem_name pyGemPath, pybind11::none(), // project_name diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h index 2dc15bd574..88bd0c1911 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.h +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -68,7 +68,7 @@ namespace O3DE::ProjectManager AZStd::recursive_mutex m_lock; pybind11::handle m_register; pybind11::handle m_manifest; - pybind11::handle m_addGemProject; - pybind11::handle m_removeGemProject; + pybind11::handle m_enableGemProject; + pybind11::handle m_disableGemProject; }; } diff --git a/scripts/o3de.py b/scripts/o3de.py index f91d5a25a0..24ba862529 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -32,7 +32,7 @@ def add_args(parser, subparsers) -> None: # add the scripts/o3de directory to the front of the sys.path sys.path.insert(0, str(o3de_package_dir)) from o3de import engine_template, global_project, register, print_registration, get_registration, download, \ - add_gem_project, remove_gem_project, sha256 + enable_gem, disable_gem, sha256 # Remove the temporarily added path sys.path = sys.path[1:] @@ -54,10 +54,10 @@ def add_args(parser, subparsers) -> None: download.add_args(subparsers) # add a gem to a project - add_gem_project.add_args(subparsers) + enable_gem.add_args(subparsers) # remove a gem from a project - remove_gem_project.add_args(subparsers) + disable_gem.add_args(subparsers) # sha256 sha256.add_args(subparsers) diff --git a/scripts/o3de/o3de/cmake.py b/scripts/o3de/o3de/cmake.py index eb8e3957ad..dfcce708eb 100644 --- a/scripts/o3de/o3de/cmake.py +++ b/scripts/o3de/o3de/cmake.py @@ -26,9 +26,9 @@ def get_project_gems(project_path: pathlib.Path, return get_gems_from_cmake_file(get_enabled_gem_cmake_file(project_path=project_path, platform=platform)) -def get_gem_from_cmake_file(cmake_file: pathlib.Path) -> set: +def get_enabled_gems(cmake_file: pathlib.Path) -> set: """ - Gets a list of declared gem targets dependencies of a cmake file + Gets a list of enabled gems from the cmake file :param cmake_file: path to the cmake file :return: set of gem targets found """ @@ -38,11 +38,29 @@ def get_gem_from_cmake_file(cmake_file: pathlib.Path) -> set: logger.error(f'Failed to locate cmake file {cmake_file}') return set() + enable_gem_start_marker = 'set(ENABLED_GEMS' + enable_gem_end_marker = ')' gem_target_set = set() with cmake_file.open('r') as s: + in_gem_list = False for line in s: - gem_name = line.strip() - gem_target_set.add(gem_name) + line = line.strip() + if line.startswith(enable_gem_start_marker): + # Set the flag to indicate that we are in the ENABLED_GEMS variable + in_gem_list = True + # Skip pass the 'set(ENABLED_GEMS' marker just in case their are gems declared on the same line + line = line[len(enable_gem_start_marker):] + if in_gem_list: + # Since we are inside the ENABLED_GEMS variable determine if the line has the end_marker of ')' + if line.endswith(enable_gem_end_marker): + # Strip away the line end marker + line = line[:-len(enable_gem_end_marker)] + # Set the flag to indicate that we are no longer in the ENABLED_GEMS variable after this line + in_gem_list = False + # Split the rest of the line on whitespace just in case there are multiple gems in a line + gem_name_list = line.split() + gem_target_set.update(gem_name_list) + return gem_target_set @@ -72,7 +90,7 @@ def get_enabled_gem_cmake_file(project_name: str = None, project_path = manifest.get_registered(project_name=project_name) project_path = pathlib.Path(project_path).resolve() - enable_gem_filename = "enabled_gem.cmake" + enable_gem_filename = "enabled_gems.cmake" if platform == 'Common': project_code_dir = project_path / 'Gem/Code' diff --git a/scripts/o3de/o3de/remove_gem_project.py b/scripts/o3de/o3de/disable_gem.py similarity index 69% rename from scripts/o3de/o3de/remove_gem_project.py rename to scripts/o3de/o3de/disable_gem.py index 72c51f0e2c..6c466c3631 100644 --- a/scripts/o3de/o3de/remove_gem_project.py +++ b/scripts/o3de/o3de/disable_gem.py @@ -58,20 +58,18 @@ def remove_gem_dependency(cmake_file: pathlib.Path, return 0 -def remove_gem_from_project(gem_name: str = None, - gem_path: pathlib.Path = None, - project_name: str = None, - project_path: pathlib.Path = None, - enabled_gem_file: pathlib.Path = None, - platforms: str = 'Common') -> int: +def disable_gem_in_project(gem_name: str = None, + gem_path: pathlib.Path = None, + project_name: str = None, + project_path: pathlib.Path = None, + enabled_gem_file: pathlib.Path = None) -> int: """ - remove a gem from a project + disable a gem in a projects enabled_gems.cmake file :param gem_name: name of the gem to add :param gem_path: path to the gem to add :param project_name: name of the project to add the gem to :param project_path: path to the project to add the gem to :param enabled_gem_file: File to remove enabled gem from - :param platforms: str to specify common or which specific platforms :return: 0 for success or non 0 failure code """ @@ -122,53 +120,37 @@ def remove_gem_from_project(gem_name: str = None, # when removing we will try to do as much as possible even with failures so ret_val will be the last error code ret_val = 0 - # if the user has specified the dependencies file then ignore the runtime_dependency and tool_dependency flags - if enabled_gem_file: - # make sure this is a project has an enabled_gem file - if not enabled_gem_file.is_file(): - logger.error(f'Enabled gem file {enabled_gem_file} is not present.') - return 1 - # remove the dependency - error_code = remove_gem_dependency(dependencies_file, gem_json_data['gem_name']) - if error_code: - ret_val = error_code - else: - if ',' in platforms: - platforms = platforms.split(',') - else: - platforms = [platforms] - for platform in platforms: - # make sure this is a project has a enabled_gem.cmake file - project_enabled_gem_file = cmake.get_enabled_gem_cmake_file(project_path=project_path, platform=platform) - if not project_enabled_gem_file.is_file(): - logger.error(f'Enabled gem file {project_enabled_gem_file} is not present.') - else: - # remove the dependency - error_code = remove_gem_dependency(project_enabled_gem_file, gem_json_data['gem_name']) - if error_code: - ret_val = error_code + if not enabled_gem_file: + enabled_gem_file = cmake.get_enabled_gem_cmake_file(project_path=project_path) + # make sure this is a project has an enabled gems file + if not enabled_gem_file.is_file(): + logger.error(f'Enabled gem file {enabled_gem_file} is not present.') + return 1 + # remove the gem + error_code = remove_gem_dependency(enabled_gem_file, gem_json_data['gem_name']) + if error_code: + ret_val = error_code return ret_val -def _run_remove_gem_from_project(args: argparse) -> int: +def _run_disable_gem_in_project(args: argparse) -> int: if args.override_home_folder: manifest.override_home_folder = args.override_home_folder - return remove_gem_from_project(args.gem_name, + return disable_gem_in_project(args.gem_name, args.gem_path, args.project_name, args.project_path, - args.enabled_gem_file, - args.platforms) + args.enabled_gem_file) def add_parser_args(parser): """ add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python remove_gem_project.py --project-path D:/Test --gem-name Atom + Ex. Directly run from this file alone with: python disable_gem.py --project-path D:/Test --gem-name Atom :param parser: the caller passes an argparse parser like instance to this method """ group = parser.add_mutually_exclusive_group(required=True) @@ -182,17 +164,13 @@ def add_parser_args(parser): group.add_argument('-gn', '--gem-name', type=str, required=False, help='The name of the gem.') parser.add_argument('-egf', '--enabled-gem-file', type=pathlib.Path, required=False, - help='The cmake enabled gem file in which gem dependencies are to be removed from.' + help='The cmake enabled gem file in which gem names are to be removed from.' 'If not specified it will assume ') - parser.add_argument('-pl', '--platforms', type=str, required=False, - default='Common', - help='Optional list of platforms this gem should be removed from' - ' Ex. --platforms Mac,Windows,Linux') parser.add_argument('-ohf', '--override-home-folder', type=pathlib.Path, required=False, help='By default the home folder is the user folder, override it to this folder.') - parser.set_defaults(func=_run_remove_gem_from_project) + parser.set_defaults(func=_run_disable_gem_in_project) def add_args(subparsers) -> None: @@ -200,16 +178,16 @@ def add_args(subparsers) -> None: add_args is called to add subparsers arguments to each command such that it can be a central python file such as o3de.py. It can be run from the o3de.py script as follows - call add_args and execute: python o3de.py remove-gem-from-project --project-path D:/Test --gem-name Atom + call add_args and execute: python o3de.py disable-gem-from-cmake --project-path D:/Test --gem-name Atom :param subparsers: the caller instantiates subparsers and passes it in here """ - remove_gem_project_subparser = subparsers.add_parser('remove-gem-from-project') - add_parser_args(remove_gem_project_subparser) + disable_gem_project_subparser = subparsers.add_parser('disable-gem') + add_parser_args(disable_gem_project_subparser) def main(): """ - Runs remove_gem_project.py script as standalone script + Runs disable_gem_project.py script as standalone script """ # parse the command line args the_parser = argparse.ArgumentParser() diff --git a/scripts/o3de/o3de/add_gem_project.py b/scripts/o3de/o3de/enable_gem.py similarity index 76% rename from scripts/o3de/o3de/add_gem_project.py rename to scripts/o3de/o3de/enable_gem.py index 42db0a97bd..73fc2ea3cf 100644 --- a/scripts/o3de/o3de/add_gem_project.py +++ b/scripts/o3de/o3de/enable_gem.py @@ -75,20 +75,18 @@ def add_gem_dependency(cmake_file: pathlib.Path, return 0 -def add_gem_to_project(gem_name: str = None, - gem_path: pathlib.Path = None, - project_name: str = None, - project_path: pathlib.Path = None, - enabled_gem_file: pathlib.Path = None, - platforms: str = 'Common') -> int: +def enable_gem_in_project(gem_name: str = None, + gem_path: pathlib.Path = None, + project_name: str = None, + project_path: pathlib.Path = None, + enabled_gem_file: pathlib.Path = None) -> int: """ - add a gem to a project + enable a gem in a projects enabled_gems.cmake file :param gem_name: name of the gem to add :param gem_path: path to the gem to add :param project_name: name of to the project to add the gem to :param project_path: path to the project to add the gem to :param enabled_gem_file_file: if this dependency goes/is in a specific file - :param platforms: str to specify common or which specific platforms :return: 0 for success or non 0 failure code """ # we need either a project name or path @@ -138,47 +136,41 @@ def add_gem_to_project(gem_name: str = None, ret_val = 0 if enabled_gem_file: - # make sure this is a project has a dependencies_file + # make sure this is a project has an enabled gems file if not enabled_gem_file.is_file(): logger.error(f'Enabled gem file {enabled_gem_file} is not present.') return 1 - # add the dependency + # add the gem ret_val = add_gem_dependency(enabled_gem_file, gem_json_data['gem_name']) else: - if ',' in platforms: - platforms = platforms.split(',') - else: - platforms = [platforms] - for platform in platforms: - # Find the path to enabled gem file. - # It will be created by add_gem_dependency if it doesn't exist - project_enabled_gem_file = cmake.get_enabled_gem_cmake_file(project_path=project_path, platform=platform) - if not project_enabled_gem_file.is_file(): - project_enabled_gem_file.touch() - # add the dependency - ret_val = add_gem_dependency(project_enabled_gem_file, gem_json_data['gem_name']) + # Find the path to enabled gem file. + # It will be created if it doesn't exist + project_enabled_gem_file = cmake.get_enabled_gem_cmake_file(project_path=project_path) + if not project_enabled_gem_file.is_file(): + project_enabled_gem_file.touch() + # add the gem + ret_val = add_gem_dependency(project_enabled_gem_file, gem_json_data['gem_name']) return ret_val -def _run_add_gem_to_project(args: argparse) -> int: +def _run_enable_gem_in_project(args: argparse) -> int: if args.override_home_folder: manifest.override_home_folder = args.override_home_folder - return add_gem_to_project(args.gem_name, - args.gem_path, - args.project_name, - args.project_path, - args.enabled_gem_file, - args.platforms) + return enable_gem_in_project(args.gem_name, + args.gem_path, + args.project_name, + args.project_path, + args.enabled_gem_file) def add_parser_args(parser): """ add_parser_args is called to add arguments to each command such that it can be invoked locally or added by a central python file. - Ex. Directly run from this file alone with: python add_gem_project.py --project-path "D:/TestProject" --gem-path "D:/TestGem" + Ex. Directly run from this file alone with: python enable_gem.py --project-path "D:/TestProject" --gem-path "D:/TestGem" :param parser: the caller passes an argparse parser like instance to this method """ group = parser.add_mutually_exclusive_group(required=True) @@ -192,17 +184,13 @@ def add_parser_args(parser): group.add_argument('-gn', '--gem-name', type=str, required=False, help='The name of the gem.') parser.add_argument('-egf', '--enabled-gem-file', type=pathlib.Path, required=False, - help='The cmake enabled_gem file in which the gem dependencies are specified.' + help='The cmake enabled_gem file in which the gem names are specified.' 'If not specified it will assume enabled_gems.cmake') - parser.add_argument('-pl', '--platforms', type=str, required=False, - default='Common', - help='Optional list of platforms this gem should be added to.' - ' Ex. --platforms Mac,Windows,Linux') parser.add_argument('-ohf', '--override-home-folder', type=pathlib.Path, required=False, help='By default the home folder is the user folder, override it to this folder.') - parser.set_defaults(func=_run_add_gem_to_project) + parser.set_defaults(func=_run_enable_gem_in_project) def add_args(subparsers) -> None: @@ -213,13 +201,13 @@ def add_args(subparsers) -> None: call add_args and execute: python o3de.py add-gem-to-project --project-path "D:/TestProject" --gem-path "D:/TestGem" :param subparsers: the caller instantiates subparsers and passes it in here """ - add_gem_project_subparser = subparsers.add_parser('add-gem-to-project') - add_parser_args(add_gem_project_subparser) + enable_gem_project_subparser = subparsers.add_parser('enable-gem') + add_parser_args(enable_gem_project_subparser) def main(): """ - Runs add_gem_project.py script as standalone script + Runs enable_gem.py script as standalone script """ # parse the command line args the_parser = argparse.ArgumentParser() diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index c3b327641c..092430500f 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -231,6 +231,11 @@ def get_gems() -> list: return list(filter(is_gem_subdirectory, external_subdirs)) if external_subdirs else [] +def get_external_subdirectories() -> list: + json_data = load_o3de_manifest() + return json_data['external_subdirectories'] + + def get_templates() -> list: json_data = load_o3de_manifest() return json_data['templates'] @@ -241,11 +246,6 @@ def get_restricted() -> list: return json_data['restricted'] -def get_external_subdirectories() -> list: - json_data = load_o3de_manifest() - return json_data['external_subdirectories'] - - def get_repos() -> list: json_data = load_o3de_manifest() return json_data['repos'] @@ -266,6 +266,13 @@ def get_engine_gems() -> list: return list(filter(is_gem_subdirectory, external_subdirs)) if external_subdirs else [] +def get_engine_external_subdirectories() -> list: + engine_path = get_this_engine_path() + engine_object = get_engine_json_data(engine_path=engine_path) + return list(map(lambda rel_path: (pathlib.Path(engine_path) / rel_path).as_posix(), + engine_object['external_subdirectories'])) if 'external_subdirectories' in engine_object else [] + + def get_engine_templates() -> list: engine_path = get_this_engine_path() engine_object = get_engine_json_data(engine_path=engine_path) @@ -280,19 +287,12 @@ def get_engine_restricted() -> list: engine_object['restricted'])) if 'restricted' in engine_object else [] -def get_engine_external_subdirectories() -> list: - engine_path = get_this_engine_path() - engine_object = get_engine_json_data(engine_path=engine_path) - return list(map(lambda rel_path: (pathlib.Path(engine_path) / rel_path).as_posix(), - engine_object['external_subdirectories'])) if 'external_subdirectories' in engine_object else [] - - # project.json queries def get_project_gems(project_path: pathlib.Path) -> list: def is_gem_subdirectory(subdir): return (pathlib.Path(subdir) / 'gem.json').exists() - external_subdirs = get_project_external_subdirectories() + external_subdirs = get_project_external_subdirectories(project_path) return list(filter(is_gem_subdirectory, external_subdirs)) if external_subdirs else [] @@ -302,26 +302,42 @@ def get_project_external_subdirectories(project_path: pathlib.Path) -> list: project_object['external_subdirectories'])) if 'external_subdirectories' in project_object else [] +# Combined manifest queries def get_all_projects() -> list: - engine_projects = get_engine_projects() - projects_data = get_projects() - projects_data.extend(engine_projects) - return projects_data + projects_data = set(get_projects()) + projects_data.update(get_engine_projects()) + return list(projects_data) -def get_all_gems() -> list: - engine_gems = get_engine_gems() - gems_data = get_gems() - gems_data.extend(engine_gems) - return gems_data +def get_all_gems(project_path: pathlib.Path = None) -> list: + gems_data = set(get_gems()) + gems_data.update(get_engine_gems()) + if project_path: + gems_data.update(get_project_gems(project_path)) + return list(gems_data) + + +def get_all_external_subdirectories(project_path: pathlib.Path = None) -> list: + external_subdirectories_data = set(get_external_subdirectories()) + external_subdirectories_data.update(get_engine_external_subdirectories()) + if project_path: + external_subdirectories_data.update(get_project_external_subdirectories(project_path)) + return list(templates_data) def get_all_templates() -> list: - engine_templates = get_engine_templates() - templates_data = get_templates() - templates_data.extend(engine_templates) - return templates_data + templates_data = set(get_templates()) + templates_data.update(get_engine_templates()) + return list(templates_data) + +def get_all_restricted() -> list: + restricted_data = set(get_restricted()) + restricted_data.update(get_engine_restricted()) + return list(gems_data) + + +# Template functions def get_project_templates(): # temporary until we have a better way to do this... maybe template_type element project_templates = [] for template in get_all_templates(): diff --git a/scripts/o3de/tests/CMakeLists.txt b/scripts/o3de/tests/CMakeLists.txt index 7abc22a030..5c83f4112b 100644 --- a/scripts/o3de/tests/CMakeLists.txt +++ b/scripts/o3de/tests/CMakeLists.txt @@ -20,3 +20,10 @@ ly_add_pytest( TEST_SUITE smoke EXCLUDE_TEST_RUN_TARGET_FROM_IDE ) + +ly_add_pytest( + NAME o3de_cmake + PATH ${CMAKE_CURRENT_LIST_DIR}/unit_test_cmake.py + TEST_SUITE smoke + EXCLUDE_TEST_RUN_TARGET_FROM_IDE +) diff --git a/scripts/o3de/tests/unit_test_add_remove_gem.py b/scripts/o3de/tests/unit_test_add_remove_gem.py deleted file mode 100755 index cc793bf32b..0000000000 --- a/scripts/o3de/tests/unit_test_add_remove_gem.py +++ /dev/null @@ -1,259 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -import os -import pytest - -from o3de import add_gem_project - -TEST_WITHOUT_NO_GEM_CONTENT = """ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES -) -""" - -TEST_WITHOUT_ONLY_GEM_CONTENT = """ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::TestGem -) -""" - -TEST_WITHOUT_ADDED_GEM_CONTENT = """ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::ExistingGem -) -""" - -TEST_WITH_ADDED_GEM_CONTENT = """ -# {BEGIN_LICENSE} -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# {END_LICENSE} - -set(GEM_DEPENDENCIES - Gem::TestGem - Gem::ExistingGem -) -""" - - -@pytest.mark.parametrize( - "contents, gem, expected_result, runtime_present, expect_failure", [ - pytest.param(TEST_WITHOUT_ADDED_GEM_CONTENT, "TestGem", TEST_WITH_ADDED_GEM_CONTENT, True, False), - pytest.param(TEST_WITHOUT_ADDED_GEM_CONTENT, "TestGem", TEST_WITH_ADDED_GEM_CONTENT, False, True), - pytest.param(TEST_WITHOUT_ADDED_GEM_CONTENT, "/TestGem", TEST_WITH_ADDED_GEM_CONTENT, True, True), - pytest.param(TEST_WITHOUT_NO_GEM_CONTENT, "TestGem", TEST_WITHOUT_ONLY_GEM_CONTENT, True, False), - ] -) -def test_add_gem_dependency(tmpdir, contents, gem, expected_result, runtime_present, expect_failure): - dev_root = str(tmpdir.join('dev').realpath()).replace('\\', '/') - os.makedirs(dev_root, exist_ok=True) - - dev_project_gem_code = f'{dev_root}/TestProject/Gem/Code' - os.makedirs(dev_project_gem_code, exist_ok=True) - - runtime_dependencies_cmake_file = f'{dev_project_gem_code}/runtime_dependencies.cmake' - if runtime_present: - if os.path.isfile(runtime_dependencies_cmake_file): - os.unlink(runtime_dependencies_cmake_file) - with open(runtime_dependencies_cmake_file, 'a') as s: - s.write(contents) - - result = add_gem_project.add_gem_dependency(runtime_dependencies_cmake_file, gem) - - if expect_failure: - assert result != 0 - else: - assert result == 0 - with open(runtime_dependencies_cmake_file, 'r') as s: - s_data = s.read() - assert s_data == expected_result - - -@pytest.mark.parametrize( - "contents, gem, expected_result, runtime_present, expect_failure", [ - pytest.param(TEST_WITH_ADDED_GEM_CONTENT, "TestGem", TEST_WITHOUT_ADDED_GEM_CONTENT, True, False), - pytest.param(TEST_WITH_ADDED_GEM_CONTENT, "TestGem", TEST_WITHOUT_ADDED_GEM_CONTENT, False, True), - pytest.param(TEST_WITHOUT_ADDED_GEM_CONTENT, "TestGem", TEST_WITHOUT_ADDED_GEM_CONTENT, True, True) - ] -) -def test_remove_gem_dependency(tmpdir, contents, gem, expected_result, runtime_present, expect_failure): - dev_root = str(tmpdir.join('dev').realpath()).replace('\\', '/') - os.makedirs(dev_root, exist_ok=True) - - dev_project_gem_code = f'{dev_root}/TestProject/Gem/Code' - os.makedirs(dev_project_gem_code, exist_ok=True) - - runtime_dependencies_cmake_file = f'{dev_project_gem_code}/runtime_dependencies.cmake' - if runtime_present: - if os.path.isfile(runtime_dependencies_cmake_file): - os.unlink(runtime_dependencies_cmake_file) - with open(runtime_dependencies_cmake_file, 'a') as s: - s.write(contents) - - result = add_remove_gem.remove_gem_dependency(runtime_dependencies_cmake_file, gem) - - if expect_failure: - assert result != 0 - else: - assert result == 0 - with open(runtime_dependencies_cmake_file, 'r') as s: - s_data = s.read() - assert s_data == expected_result - - -@pytest.mark.parametrize("add," - " contents, gem, project, expected_result," - " runtime_present, tool_present," - " ask_for_runtime, ask_for_tool," - " expect_failure", [ - pytest.param(True, - TEST_WITHOUT_ADDED_GEM_CONTENT, "TestGem", "TestProject", - TEST_WITH_ADDED_GEM_CONTENT, - True, True, - True, True, - False), - pytest.param(True, - TEST_WITHOUT_ADDED_GEM_CONTENT, "TestGem", "TestProject", - TEST_WITH_ADDED_GEM_CONTENT, - True, False, - True, True, - True), - pytest.param(True, - TEST_WITHOUT_ADDED_GEM_CONTENT, "TestGem", "TestProject", - TEST_WITH_ADDED_GEM_CONTENT, - False, True, - True, True, - True), - pytest.param(True, - TEST_WITHOUT_ADDED_GEM_CONTENT, "TestGem", "TestProject", - TEST_WITH_ADDED_GEM_CONTENT, - False, False, - True, True, - True), - - pytest.param(False, - TEST_WITH_ADDED_GEM_CONTENT, "TestGem", "TestProject", - TEST_WITHOUT_ADDED_GEM_CONTENT, - True, True, - True, True, - False), - pytest.param(False, - TEST_WITH_ADDED_GEM_CONTENT, "TestGem", "TestProject", - TEST_WITHOUT_ADDED_GEM_CONTENT, - True, False, - True, True, - True), - pytest.param(False, - TEST_WITH_ADDED_GEM_CONTENT, "TestGem", "TestProject", - TEST_WITHOUT_ADDED_GEM_CONTENT, - False, True, - True, True, - True), - pytest.param(False, - TEST_WITH_ADDED_GEM_CONTENT, "TestGem", "TestProject", - TEST_WITHOUT_ADDED_GEM_CONTENT, - False, False, - True, True, - True) - ] - ) -def test_add_remove_gem(tmpdir, - add, - contents, gem, project, - expected_result, - runtime_present, tool_present, - ask_for_runtime, ask_for_tool, - expect_failure): - dev_root = str(tmpdir.join('dev').realpath()).replace('\\', '/') - os.makedirs(dev_root, exist_ok=True) - - dev_project_gem_code = f'{dev_root}/TestProject/Gem/Code' - os.makedirs(dev_project_gem_code, exist_ok=True) - - runtime_dependencies_cmake_file = f'{dev_project_gem_code}/runtime_dependencies.cmake' - if runtime_present: - if os.path.isfile(runtime_dependencies_cmake_file): - os.unlink(runtime_dependencies_cmake_file) - with open(runtime_dependencies_cmake_file, 'a') as s: - s.write(contents) - - tool_dependencies_cmake_file = f'{dev_project_gem_code}/tool_dependencies.cmake' - os.makedirs(dev_project_gem_code, exist_ok=True) - - if tool_present: - if os.path.isfile(tool_dependencies_cmake_file): - os.unlink(tool_dependencies_cmake_file) - with open(tool_dependencies_cmake_file, 'w') as s: - s.write(contents) - - project_folder = f'{dev_root}/TestProject' - os.makedirs(project_folder, exist_ok=True) - - gems_folder = f'{dev_root}/Gems' - os.makedirs(gems_folder, exist_ok=True) - - gem_folder = f'{gems_folder}/{gem}' - os.makedirs(gem_folder, exist_ok=True) - - result = add_remove_gem.add_remove_gem(add, dev_root, gem, project, ask_for_runtime, ask_for_tool) - - if expect_failure: - assert result != 0 - else: - assert result == 0 - if runtime_present: - with open(runtime_dependencies_cmake_file, 'r') as s: - s_data = s.read() - assert s_data == expected_result - if tool_present: - with open(tool_dependencies_cmake_file, 'r') as s: - s_data = s.read() - assert s_data == expected_result - diff --git a/scripts/o3de/tests/unit_test_cmake.py b/scripts/o3de/tests/unit_test_cmake.py new file mode 100644 index 0000000000..e5ce17dc03 --- /dev/null +++ b/scripts/o3de/tests/unit_test_cmake.py @@ -0,0 +1,69 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +import io +import json +import logging +import pytest +import pathlib +from unittest.mock import patch + +from o3de import cmake + + +class TestGetEnabledGems: + @pytest.mark.parametrize( + "enable_gems_cmake_data, expected_set", [ + pytest.param(""" + # Comment + set(ENABLED_GEMS foo bar baz) + """, set(['foo', 'bar', 'baz'])), + pytest.param(""" + # Comment + set(ENABLED_GEMS + foo + bar + baz + ) + """, set(['foo', 'bar', 'baz'])), + pytest.param(""" + # Comment + set(ENABLED_GEMS + foo + bar + baz) + """, set(['foo', 'bar', 'baz'])), + pytest.param(""" + # Comment + set(ENABLED_GEMS + foo bar + baz) + """, set(['foo', 'bar', 'baz'])), + pytest.param(""" + # Comment + set(RANDOM_VARIABLE TestGame, TestProject Test Engine) + set(ENABLED_GEMS HelloWorld IceCream + foo + baz bar + baz baz baz baz baz morebaz lessbaz + ) + Random Text + """, set(['HelloWorld', 'IceCream', 'foo', 'bar', 'baz', 'morebaz', 'lessbaz'])), + ] + ) + def test_get_enabled_gems(self, enable_gems_cmake_data, expected_set): + enabled_gems_set = set() + with patch('pathlib.Path.resolve', return_value=pathlib.Path('enabled_gems.cmake')) as pathlib_is_resolve_mock,\ + patch('pathlib.Path.is_file', return_value=True) as pathlib_is_file_mock,\ + patch('pathlib.Path.open', return_value=io.StringIO(enable_gems_cmake_data)) as pathlib_open_mock: + enabled_gems_set = cmake.get_enabled_gems(pathlib.Path('enabled_gems.cmake')) + + assert enabled_gems_set == expected_set diff --git a/scripts/project_manager/projects.py b/scripts/project_manager/projects.py index d062343662..f9f40aa4bf 100755 --- a/scripts/project_manager/projects.py +++ b/scripts/project_manager/projects.py @@ -29,7 +29,7 @@ executable_path = '' logger = logging.getLogger() logger.setLevel(logging.INFO) -from o3de import add_gem_project, cmake, engine_template, manifest, register, remove_gem_project +from o3de import disable_gem, enable_gem, cmake, engine_template, manifest, register o3de_folder = manifest.get_o3de_folder() o3de_logs_folder = manifest.get_o3de_logs_folder() @@ -671,8 +671,8 @@ class ProjectManagerDialog(QObject): gem_paths = manifest.get_all_gems() for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): for gem_path in gem_paths: - add_gem_project.add_gem_to_project(gem_path=gem_path, - project_path=self.get_selected_project_path()) + enable_gem.enable_gem_in_project(gem_path=gem_path, + project_path=self.get_selected_project_path()) self.refresh_project_gem_targets_available_list() self.refresh_project_gem_targets_enabled_list() return @@ -683,8 +683,8 @@ class ProjectManagerDialog(QObject): gem_paths = manifest.get_all_gems() for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): for gem_path in gem_paths: - remove_gem_project.remove_gem_from_project(gem_path=gem_path, - project_path=self.get_selected_project_path()) + disable_gem.disable_gem_in_project(gem_path=gem_path, + project_path=self.get_selected_project_path()) self.refresh_project_gem_targets_available_list() self.refresh_project_gem_targets_enabled_list() return From 3137b961bf860f03aac17bd5192477380c7056e3 Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 27 May 2021 14:54:51 -0700 Subject: [PATCH 249/811] [ftue_auto_register] elevated error to assert if registration fails --- Code/Tools/ProjectManager/Source/PythonBindings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 90e18f5f27..7158bfefb7 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -338,7 +338,7 @@ namespace O3DE::ProjectManager result = (registrationResult.cast() == 0); } - AZ_Error("ProjectManagerWindow", result, "Registration of this engine failed!"); + AZ_Assert(result, "Registration of this engine failed!"); return result; } From d6cfa6833375b76a24f8f53b3b6805aec41ba739 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 15:04:17 -0700 Subject: [PATCH 250/811] Reverting error check and comment --- cmake/LYWrappers.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index bef3b25328..48423f3575 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -692,7 +692,9 @@ endfunction() # given a target name, returns the "real" name of the target if its an alias. # this function recursively de-aliases function(ly_de_alias_target target_name output_variable_name) + # its not okay to call get_target_property on a non-existent target if (NOT TARGET ${target_name}) + message(FATAL_ERROR "ly_de_alias_target called on non-existent target: ${target_name}") endif() while(target_name) From be54df8c1e4dbb85e48e3b02cef89d385b5ab4f7 Mon Sep 17 00:00:00 2001 From: gallowj Date: Thu, 27 May 2021 17:04:23 -0500 Subject: [PATCH 251/811] Added a required CC license for Sponza content --- Gems/AtomContent/Sponza/Assets/license.txt | 8 ++++++++ Gems/AtomContent/Sponza/Assets/stub | 0 2 files changed, 8 insertions(+) create mode 100644 Gems/AtomContent/Sponza/Assets/license.txt delete mode 100644 Gems/AtomContent/Sponza/Assets/stub diff --git a/Gems/AtomContent/Sponza/Assets/license.txt b/Gems/AtomContent/Sponza/Assets/license.txt new file mode 100644 index 0000000000..e303d8c767 --- /dev/null +++ b/Gems/AtomContent/Sponza/Assets/license.txt @@ -0,0 +1,8 @@ +The content in this gem "O3DE\Gems\AtomContent\Sponza" is ported +from the original source, and modified for the O3DE Engine and Atom Renderer. + +The original "Crytek Sponza" scene data can be downloaded from the +"McGuire Computer Graphics Archive": https://casual-effects.com/data/ + +The original content is under the "CC BY 3.0" License: +https://creativecommons.org/licenses/by/3.0/ \ No newline at end of file diff --git a/Gems/AtomContent/Sponza/Assets/stub b/Gems/AtomContent/Sponza/Assets/stub deleted file mode 100644 index e69de29bb2..0000000000 From 1c52147c3ad05fb3845868e335beb5da2ddfeda1 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 17:12:28 -0500 Subject: [PATCH 252/811] Fixed path case issue in the declaration of the path to the UiBasics gem --- engine.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/engine.json b/engine.json index 7662d4f034..09bb3f5ff6 100644 --- a/engine.json +++ b/engine.json @@ -81,7 +81,7 @@ "Gems/TextureAtlas", "Gems/TickBusOrderViewer", "Gems/Twitch", - "Gems/UIBasics", + "Gems/UiBasics", "Gems/Vegetation", "Gems/Vegetation_Gem_Assets", "Gems/VideoPlaybackFramework", From e1dfac34fc7fba0d5478c1a412e368a1805aad86 Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 27 May 2021 15:24:39 -0700 Subject: [PATCH 253/811] [ftue_auto_register] wrapped registration pybind calls with ExecuteWithLock --- .../ProjectManager/Source/PythonBindings.cpp | 49 ++++++++++--------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 7158bfefb7..1a3e30f99f 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -313,33 +313,38 @@ namespace O3DE::ProjectManager bool PythonBindings::RegisterThisEngine() { - bool registerThis = true; - - // check current engine path against all other registered engines - // to see if we are already registered - auto allEngines = m_registration.attr("get_engines")(); - if (pybind11::isinstance(allEngines)) - { - for (const auto& engine : allEngines) + bool registrationResult = true; // already registered is considered successful + bool pythonResult = ExecuteWithLock( + [&] { - AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"])); - if (enginePath.Compare(m_enginePath) == 0) + bool registerThis = true; + + // check current engine path against all other registered engines + // to see if we are already registered + auto allEngines = m_registration.attr("get_engines")(); + if (pybind11::isinstance(allEngines)) { - registerThis = false; - break; + for (const auto& engine : allEngines) + { + AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"])); + if (enginePath.Compare(m_enginePath) == 0) + { + registerThis = false; + break; + } + } } - } - } - bool result = true; - if (registerThis) - { - auto registrationResult = m_registration.attr("register")(m_enginePath.c_str()); - result = (registrationResult.cast() == 0); - } + if (registerThis) + { + auto result = m_registration.attr("register")(m_enginePath.c_str()); + registrationResult = (result.cast() == 0); + } + }); - AZ_Assert(result, "Registration of this engine failed!"); - return result; + bool finalResult = (registrationResult && pythonResult); + AZ_Assert(finalResult, "Registration of this engine failed!"); + return finalResult; } bool PythonBindings::ExecuteWithLock(AZStd::function executionCallback) From c67cd2dc4e25fa3f3890d4937d57327f537b68a0 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 17:35:08 -0500 Subject: [PATCH 254/811] Renaming the TargetCMakeLists.txt.in to InstalledTarget.in to get avoid it being picked up by the CopyrightValidator --- cmake/Platform/Common/Install_common.cmake | 2 +- cmake/install/{TargetCMakeLists.txt.in => InstalledTarget.in} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename cmake/install/{TargetCMakeLists.txt.in => InstalledTarget.in} (100%) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 939f523d75..b18aed6fb4 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -182,7 +182,7 @@ set_property(TARGET ${TARGET_NAME} ) # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target - file(READ ${LY_ROOT_FOLDER}/cmake/install/TargetCMakeLists.txt.in target_cmakelists_template) + file(READ ${LY_ROOT_FOLDER}/cmake/install/InstalledTarget.in target_cmakelists_template) string(CONFIGURE ${target_cmakelists_template} output_cmakelists_data @ONLY) set(${OUTPUT_CONFIGURED_TARGET} ${output_cmakelists_data} PARENT_SCOPE) endfunction() diff --git a/cmake/install/TargetCMakeLists.txt.in b/cmake/install/InstalledTarget.in similarity index 100% rename from cmake/install/TargetCMakeLists.txt.in rename to cmake/install/InstalledTarget.in From f007efbc36615a2048758aaf315c6a5700549066 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Thu, 27 May 2021 16:01:57 -0700 Subject: [PATCH 255/811] Fix various container issues in jinja --- .../Source/AutoGen/AutoComponent_Source.jinja | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 6b2c5b199a..3641412609 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -118,21 +118,24 @@ void {{ ClassName }}::Set{{ UpperFirst(Property.attrib['Name']) }}(int32_t index bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PushBack(const {{ Property.attrib['Type'] }} &value) { - if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.push_back(value)) + int32_t indexToSet = GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size(); + if (indexToSet < {{ Property.attrib['Count'] }}) { - int32_t indexToSet = GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size(); + GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.push_back(value); int32_t bitIndex = indexToSet + static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(bitIndex, true); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); GetParent().MarkDirty(); return true; } + return false; } bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PopBack(const Multiplayer::NetworkInput&) { - if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back()) + if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size() > 0) { + GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back(); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); GetParent().MarkDirty(); return true; @@ -216,12 +219,13 @@ void {{ ClassName }}::Set{{ UpperFirst(Property.attrib['Name']) }}(int32_t index bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PushBack(const {{ Property.attrib['Type'] }} &value) { - if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.push_back(value)) + int32_t indexToSet = GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size(); + if (indexToSet < {{ Property.attrib['Count'] }}) { - uint32_t indexToSet = aznumeric_cast(GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size()); - uint32_t bitIndex = indexToSet + aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); + GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.push_back(value); + int32_t bitIndex = indexToSet + static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(bitIndex, true); - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); GetParent().MarkDirty(); return true; } @@ -230,8 +234,9 @@ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PushBack(const {{ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PopBack() { - if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back()) + if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size() > 0) { + GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back(); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); GetParent().MarkDirty(); return true; @@ -586,8 +591,14 @@ bool {{ ClassName }}::Serialize{{ AutoComponentMacros.GetNetPropertiesSetName(Re const uint32_t lastBit = static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'End') }}); {% endif %} +{% if Property.attrib['IsRewindable']|booleanTrue %} AzNetworking::FixedSizeBitsetView deltaRecord(replicationRecord.m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}, firstBit, lastBit - firstBit + 1); m_{{ LowerFirst(Property.attrib['Name']) }}.Serialize(serializer, deltaRecord); +{% elif Property.attrib['Container'] == 'Vector' %} + serializer.Serialize>(m_{{ LowerFirst(Property.attrib['Name']) }}, "{{ LowerFirst(Property.attrib['Name']) }}"); +{% elif Property.attrib['Container'] == 'Array' %} + serializer.Serialize>(m_{{ LowerFirst(Property.attrib['Name']) }}, "{{ LowerFirst(Property.attrib['Name']) }}"); +{% endif %} } {% else %} Multiplayer::SerializeNetworkPropertyHelper @@ -618,11 +629,11 @@ void {{ ClassName }}::NotifyChanges{{ AutoComponentMacros.GetNetPropertiesSetNam {% if (Property.attrib['GenerateEventBindings']|booleanTrue) %} {% if Property.attrib['Container'] != 'None' and Property.attrib['Container'] != 'Object' %} // NotifyChangesAuthorityToClientProperties for Arrays and Vectors - for (uint32_t bitIndex = static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}), elementIndex = 0; bitIndex <= static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component, ReplicateFrom, ReplicateTo, Property, 'End') }}); ++bitIndex, ++elementIndex) + for (uint32_t bitIndex = static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}), elementIndex = 0; bitIndex <= static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'End') }}); ++bitIndex, ++elementIndex) { - if (replicationRecord.m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.GetBit(bitIndex){% if Property.attrib['Container'] == 'Vector' %} && elementIndex < m_{{ Property.attrib['Name'] }}.GetSize(){% endif %}) + if (replicationRecord.m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.GetBit(bitIndex){% if Property.attrib['Container'] == 'Vector' %} && elementIndex < m_{{ LowerFirst(Property.attrib['Name']) }}.size(){% endif %}) { - m_LowerFirst( Property.attrib['Name']) }}Event.Signal(elementIndex, m_{{ LowerFirst(Property.attrib['Name']) }}[elementIndex]); + m_{{ LowerFirst(Property.attrib['Name']) }}Event.Signal(elementIndex, m_{{ LowerFirst(Property.attrib['Name']) }}[elementIndex]); } } {% if Property.attrib['Container'] == 'Vector' %} From 166db0b0c60dd80e833c4d7e80b75f0e4f8a7532 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 16:09:12 -0700 Subject: [PATCH 256/811] Android fix for FastNoise --- Gems/FastNoise/Code/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/FastNoise/Code/CMakeLists.txt b/Gems/FastNoise/Code/CMakeLists.txt index 8c12dcf5be..ae42af771a 100644 --- a/Gems/FastNoise/Code/CMakeLists.txt +++ b/Gems/FastNoise/Code/CMakeLists.txt @@ -134,6 +134,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE AZ::AzTest Gem::FastNoise.Static + Gem::LmbrCentral ) ly_add_googletest( NAME Gem::FastNoise.Tests From 2550c3e1ff1f9cfb2241a1c3e488ef6091d77168 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Thu, 27 May 2021 16:13:32 -0700 Subject: [PATCH 257/811] Spawnable Entity Manager threshold default to "m_highPriorityThreshold" --- .../AzFramework/Spawnable/SpawnableEntitiesManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp index 2c80aa8cbd..7b767d2a72 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp @@ -40,7 +40,7 @@ namespace AzFramework { if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { - AZ::u64 value = 64; + AZ::u64 value = aznumeric_caster(m_highPriorityThreshold); settingsRegistry->Get(value, "/O3DE/AzFramework/Spawnables/HighPriorityThreshold"); m_highPriorityThreshold = aznumeric_cast(AZStd::clamp(value, 0llu, 255llu)); } From 291e27a381ce0c702b8cd163735e53e634d94d65 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Thu, 27 May 2021 16:26:26 -0700 Subject: [PATCH 258/811] Correct numeric cast --- .../Code/Source/AutoGen/AutoComponent_Source.jinja | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 3641412609..d1487c199a 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -124,7 +124,7 @@ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PushBack(const {{ GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.push_back(value); int32_t bitIndex = indexToSet + static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(bitIndex, true); - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); GetParent().MarkDirty(); return true; } @@ -136,7 +136,7 @@ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PopBack(const Mul if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size() > 0) { GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back(); - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); GetParent().MarkDirty(); return true; } @@ -237,7 +237,7 @@ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PopBack() if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size() > 0) { GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back(); - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); GetParent().MarkDirty(); return true; } @@ -246,7 +246,7 @@ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PopBack() void {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}Clear() { - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.clear(); GetParent().MarkDirty(); } From 0c6af2365273959cc8558e61c0693df7d278eeee Mon Sep 17 00:00:00 2001 From: puvvadar Date: Thu, 27 May 2021 16:27:26 -0700 Subject: [PATCH 259/811] Correct numeric cast --- Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index d1487c199a..bd11454b20 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -225,7 +225,7 @@ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PushBack(const {{ GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.push_back(value); int32_t bitIndex = indexToSet + static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Start') }}); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(bitIndex, true); - GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(static_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); + GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); GetParent().MarkDirty(); return true; } From 5e87250f6794759c469006f325f68482d8c8e9d5 Mon Sep 17 00:00:00 2001 From: Nicholas Van Sickle Date: Thu, 27 May 2021 16:31:30 -0700 Subject: [PATCH 260/811] Fix viewport icon rendering on high DPI devices (#1006) * Clarify ViewportWorldToScreen being in widget space and add DeviceScalingFactor * -Fix viewport icons being draw wrong on high DPI displays -Fix loading viewport icons from absolute paths, which * Address review feedback, fix build --- .../ViewportInteraction.h | 1 + .../Source/ViewportInteraction.cpp | 7 ++- .../Viewport/ViewportMessages.h | 7 ++- Code/Sandbox/Editor/RenderViewport.h | 1 + .../Viewport/RenderViewportWidget.h | 1 + .../Source/Viewport/RenderViewportWidget.cpp | 8 +++- ...tomViewportDisplayIconsSystemComponent.cpp | 46 +++++++++++++------ .../AtomViewportDisplayIconsSystemComponent.h | 2 +- 8 files changed, 53 insertions(+), 20 deletions(-) diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h index 884562d7e8..28971dc779 100644 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h +++ b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h @@ -41,6 +41,7 @@ namespace AzManipulatorTestFramework AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) override; AZStd::optional ViewportScreenToWorldRay( const AzFramework::ScreenPoint& screenPosition) override; + float DeviceScalingFactor() override; private: // ViewportInteractionRequestBus ... bool GridSnappingEnabled(); diff --git a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp index ebef9dea30..7d32187a74 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp @@ -127,4 +127,9 @@ namespace AzManipulatorTestFramework { return {}; } -} // namespace AzManipulatorTestFramework + + float ViewportInteraction::DeviceScalingFactor() + { + return 1.0f; + } +}// namespace AzManipulatorTestFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h index 8e91dc945d..91eee18cb7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h @@ -165,15 +165,18 @@ namespace AzToolsFramework virtual bool AngleSnappingEnabled() = 0; /// Return the angle snapping/step size. virtual float AngleStep() = 0; - /// Transform a point in world space to screen space coordinates. + /// Transform a point in world space to screen space coordinates in Qt Widget space. + /// Multiply by DeviceScalingFactor to get the position in viewport pixel space. virtual AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) = 0; - /// Transform a point in screen space coordinates to a vector in world space based on clip space depth. + /// Transform a point from Qt widget screen space to world space based on the given clip space depth. /// Depth specifies a relative camera depth to project in the range of [0.f, 1.f]. /// Returns the world space position if successful. virtual AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) = 0; /// Casts a point in screen space to a ray in world space originating from the viewport camera frustum's near plane. /// Returns a ray containing the ray's origin and a direction normal, if successful. virtual AZStd::optional ViewportScreenToWorldRay(const AzFramework::ScreenPoint& screenPosition) = 0; + /// Gets the DPI scaling factor that translates Qt widget space into viewport pixel space. + virtual float DeviceScalingFactor() = 0; protected: ~ViewportInteractionRequests() = default; diff --git a/Code/Sandbox/Editor/RenderViewport.h b/Code/Sandbox/Editor/RenderViewport.h index d70dd59b98..b45c92b1c8 100644 --- a/Code/Sandbox/Editor/RenderViewport.h +++ b/Code/Sandbox/Editor/RenderViewport.h @@ -200,6 +200,7 @@ public: { return {}; } + float DeviceScalingFactor() override { return 1.0f; } // AzToolsFramework::ViewportFreezeRequestBus bool IsViewportInputFrozen() override; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h index a41c8221f0..f2c120dbcd 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h @@ -98,6 +98,7 @@ namespace AtomToolsFramework AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) override; AZStd::optional ViewportScreenToWorldRay( const AzFramework::ScreenPoint& screenPosition) override; + float DeviceScalingFactor() override; //! Set interface for providing viewport specific settings (e.g. snapping properties). void SetViewportSettings(const AzToolsFramework::ViewportInteraction::ViewportSettings* viewportSettings); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp index cee178c724..35edb3af5b 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp @@ -313,8 +313,7 @@ namespace AtomToolsFramework // Scale the size by the DPI of the platform to // get the proper size in pixels. const QSize uiWindowSize = size(); - const qreal deficePixelRatio = devicePixelRatioF(); - const QSize windowSize = uiWindowSize * deficePixelRatio; + const QSize windowSize = uiWindowSize * devicePixelRatioF(); const AzFramework::NativeWindowHandle windowId = reinterpret_cast(winId()); AzFramework::WindowNotificationBus::Event(windowId, &AzFramework::WindowNotifications::OnWindowResized, windowSize.width(), windowSize.height()); @@ -465,6 +464,11 @@ namespace AtomToolsFramework return AzToolsFramework::ViewportInteraction::ProjectedViewportRay{rayOrigin, rayDirection}; } + float RenderViewportWidget::DeviceScalingFactor() + { + return aznumeric_cast(devicePixelRatioF()); + } + AzFramework::ScreenPoint RenderViewportWidget::ViewportCursorScreenPosition() { return AzToolsFramework::ViewportInteraction::ScreenPointFromQPoint(m_mousePosition.toPoint()); diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.cpp index dce83c3072..5fe8c50350 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include @@ -145,12 +146,24 @@ namespace AZ::Render } // Initialize our shader - auto viewportSize = viewportContext->GetViewportSize(); + AZ::Vector2 viewportSize; + { + AzFramework::WindowSize viewportWindowSize = viewportContext->GetViewportSize(); + viewportSize = AZ::Vector2{aznumeric_cast(viewportWindowSize.m_width), aznumeric_cast(viewportWindowSize.m_height)}; + } AZ::Data::Instance drawSrg = dynamicDraw->NewDrawSrg(); - drawSrg->SetConstant(m_viewportSizeIndex, AZ::Vector2(aznumeric_cast(viewportSize.m_width), aznumeric_cast(viewportSize.m_height))); + drawSrg->SetConstant(m_viewportSizeIndex,viewportSize); drawSrg->SetImageView(m_textureParameterIndex, image->GetImageView()); drawSrg->Compile(); + // Scale icons by screen DPI + float scalingFactor = 1.0f; + { + using ViewportRequestBus = AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus; + ViewportRequestBus::EventResult( + scalingFactor, drawParameters.m_viewport, &ViewportRequestBus::Events::DeviceScalingFactor); + } + AZ::Vector3 screenPosition; if (drawParameters.m_positionSpace == CoordinateSpace::ScreenSpace) { @@ -158,9 +171,11 @@ namespace AZ::Render } else if (drawParameters.m_positionSpace == CoordinateSpace::WorldSpace) { - using ViewportRequestBus = AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus; - AzFramework::ScreenPoint position; - ViewportRequestBus::EventResult(position, drawParameters.m_viewport, &ViewportRequestBus::Events::ViewportWorldToScreen, drawParameters.m_position); + // Calculate our screen space position using the viewport size + // We want this instead of RenderViewportWidget::WorldToScreen which works in QWidget virtual coordinate space + AzFramework::ScreenPoint position = AzFramework::WorldToScreen( + drawParameters.m_position, viewportContext->GetCameraViewMatrix(), viewportContext->GetCameraProjectionMatrix(), + viewportSize); screenPosition.SetX(aznumeric_cast(position.m_x)); screenPosition.SetY(aznumeric_cast(position.m_y)); } @@ -179,8 +194,8 @@ namespace AZ::Render { Vertex vertex; screenPosition.StoreToFloat3(vertex.m_position); - vertex.m_position[0] += offsetX * drawParameters.m_size.GetX(); - vertex.m_position[1] += offsetY * drawParameters.m_size.GetY(); + vertex.m_position[0] += offsetX * drawParameters.m_size.GetX() * scalingFactor; + vertex.m_position[1] += offsetY * drawParameters.m_size.GetY() * scalingFactor; vertex.m_color = drawParameters.m_color.ToU32(); vertex.m_uv[0] = u; vertex.m_uv[1] = v; @@ -197,8 +212,15 @@ namespace AZ::Render dynamicDraw->DrawIndexed(&vertices, vertices.size(), &indices, indices.size(), RHI::IndexFormat::Uint16, drawSrg); } - QString AtomViewportDisplayIconsSystemComponent::FindAssetPath(const QString& sourceRelativePath) const + QString AtomViewportDisplayIconsSystemComponent::FindAssetPath(const QString& path) const { + // If we get an absolute path, just use it. + QFileInfo pathInfo(path); + if (pathInfo.isAbsolute()) + { + return path; + } + bool found = false; AZStd::vector scanFolders; AzToolsFramework::AssetSystemRequestBus::BroadcastResult( @@ -212,9 +234,9 @@ namespace AZ::Render for (const auto& folder : scanFolders) { QDir dir(folder.data()); - if (dir.exists(sourceRelativePath)) + if (dir.exists(path)) { - return dir.absoluteFilePath(sourceRelativePath); + return dir.absoluteFilePath(path); } } @@ -256,10 +278,6 @@ namespace AZ::Render AzToolsFramework::EditorViewportIconDisplayInterface::IconId AtomViewportDisplayIconsSystemComponent::GetOrLoadIconForPath( AZStd::string_view path) { - AZ_Error( - "AtomViewportDisplayIconsSystemComponent", AzFramework::StringFunc::Path::IsRelative(path.data()), - "GetOrLoadIconForPath assumes that it will always be given a relative path, but got '%s'", path.data()); - // Check our cache to see if the image is already loaded auto existingEntryIt = AZStd::find_if(m_iconData.begin(), m_iconData.end(), [&path](const auto& iconData) { diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.h b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.h index 0c7366f23b..b44957b51d 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.h +++ b/Gems/AtomLyIntegration/AtomViewportDisplayIcons/Code/Source/AtomViewportDisplayIconsSystemComponent.h @@ -61,7 +61,7 @@ namespace AZ static constexpr QSize MinimumRenderedSvgSize = QSize(128, 128); static constexpr QImage::Format QtImageFormat = QImage::Format_RGBA8888; - QString FindAssetPath(const QString& sourceRelativePath) const; + QString FindAssetPath(const QString& path) const; QImage RenderSvgToImage(const QString& svgPath) const; AZ::Data::Instance ConvertToAtomImage(AZ::Uuid assetId, QImage image) const; From da147f273dcbef1b84e8d94c28e7656e385cd631 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 18:41:28 -0500 Subject: [PATCH 261/811] Adding VERBOSE messages to the SettingsRegistry.cmake 'ly_get_gem_load_dependencies()' function which logs the gem target to it's load dependencies --- cmake/SettingsRegistry.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index c6ddbf810b..6f929d06e1 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -74,6 +74,7 @@ function(ly_get_gem_load_dependencies ly_GEM_LOAD_DEPENDENCIES ly_TARGET) ly_get_gem_load_dependencies(dependencies ${dealias_load_dependency}) list(APPEND all_gem_load_dependencies ${dependencies}) list(APPEND all_gem_load_dependencies ${dealias_load_dependency}) + message(VERBOSE "Load Dependency \"${dealias_load_dependency}\" has load dependencies of: ${dependencies}") endif() endforeach() endif() @@ -81,6 +82,7 @@ function(ly_get_gem_load_dependencies ly_GEM_LOAD_DEPENDENCIES ly_TARGET) list(REMOVE_DUPLICATES all_gem_load_dependencies) set_property(GLOBAL PROPERTY LY_GEM_LOAD_DEPENDENCIES_${ly_TARGET} "${all_gem_load_dependencies}") set(${ly_GEM_LOAD_DEPENDENCIES} ${all_gem_load_dependencies} PARENT_SCOPE) + message(VERBOSE "Gem Target \"${ly_TARGET}\" has load dependencies of: ${all_gem_load_dependencies}") endfunction() #!ly_get_gem_module_root: Uses the supplied gem_target to lookup the nearest gem.json file above the SOURCE_DIR From d4ce2849c7995b24311a973d731dc85fb33f82ad Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Thu, 27 May 2021 16:46:33 -0700 Subject: [PATCH 262/811] Post-merge fixup. --- .../Code/Source/Pipeline/NetBindMarkerComponent.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetBindMarkerComponent.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetBindMarkerComponent.cpp index 1696e851a5..c93c09cfbc 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetBindMarkerComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetBindMarkerComponent.cpp @@ -59,7 +59,7 @@ namespace Multiplayer AZ::Transform worldTm = GetEntity()->FindComponent()->GetWorldTM(); auto preInsertionCallback = [worldTm = AZStd::move(worldTm), netEntityIndex = m_netEntityIndex, spawnableAssetId = m_networkSpawnableAsset.GetId()] - (AzFramework::EntitySpawnTicket&, AzFramework::SpawnableEntityContainerView entities) + (AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableEntityContainerView entities) { if (entities.size() == 1) { @@ -81,7 +81,8 @@ namespace Multiplayer }; m_netSpawnTicket = AzFramework::EntitySpawnTicket(m_networkSpawnableAsset); - AzFramework::SpawnableEntitiesInterface::Get()->SpawnEntities(m_netSpawnTicket, {m_netEntityIndex}, preInsertionCallback); + AzFramework::SpawnableEntitiesInterface::Get()->SpawnEntities( + m_netSpawnTicket, AzFramework::SpawnablePriority_Default, { m_netEntityIndex }, preInsertionCallback); } } @@ -89,7 +90,7 @@ namespace Multiplayer { if(m_netSpawnTicket.IsValid()) { - AzFramework::SpawnableEntitiesInterface::Get()->DespawnAllEntities(m_netSpawnTicket); + AzFramework::SpawnableEntitiesInterface::Get()->DespawnAllEntities(m_netSpawnTicket, AzFramework::SpawnablePriority_Default); } } From 4d2e453b73d6736bc9fa4a01280ce3752ae3cfe3 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Thu, 27 May 2021 16:53:53 -0700 Subject: [PATCH 263/811] Cleanup flow of logic in serialization --- .../Code/Source/AutoGen/AutoComponent_Source.jinja | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index bd11454b20..97e2085a69 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -594,10 +594,12 @@ bool {{ ClassName }}::Serialize{{ AutoComponentMacros.GetNetPropertiesSetName(Re {% if Property.attrib['IsRewindable']|booleanTrue %} AzNetworking::FixedSizeBitsetView deltaRecord(replicationRecord.m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}, firstBit, lastBit - firstBit + 1); m_{{ LowerFirst(Property.attrib['Name']) }}.Serialize(serializer, deltaRecord); -{% elif Property.attrib['Container'] == 'Vector' %} +{% else %} +{% if Property.attrib['Container'] == 'Vector' %} serializer.Serialize>(m_{{ LowerFirst(Property.attrib['Name']) }}, "{{ LowerFirst(Property.attrib['Name']) }}"); -{% elif Property.attrib['Container'] == 'Array' %} +{% elif Property.attrib['Container'] == 'Array' %} serializer.Serialize>(m_{{ LowerFirst(Property.attrib['Name']) }}, "{{ LowerFirst(Property.attrib['Name']) }}"); +{% endif %} {% endif %} } {% else %} From c45697fd510efd95fb41f861799763b9998aae17 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Thu, 27 May 2021 16:57:15 -0700 Subject: [PATCH 264/811] Fixed unit test compile error with spawnables --- .../Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp | 3 ++- .../AzToolsFramework/Tests/Prefab/SpawnableCreateTests.cpp | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp index 821daaba82..8e4c2eaad7 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp @@ -34,7 +34,8 @@ namespace Benchmark { state.PauseTiming(); - auto spawnable = ::AzToolsFramework::Prefab::SpawnableUtils::CreateSpawnable(prefabDom); + AzFramework::Spawnable spawnable; + AzToolsFramework::Prefab::SpawnableUtils::CreateSpawnable(spawnable, prefabDom); state.ResumeTiming(); } diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/SpawnableCreateTests.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/SpawnableCreateTests.cpp index 2e1cd14b2a..af178ec7a4 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/SpawnableCreateTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/SpawnableCreateTests.cpp @@ -40,7 +40,8 @@ namespace UnitTest //Create Spawnable auto& prefabDom = m_prefabSystemComponent->FindTemplateDom(instance->GetTemplateId()); - auto spawnable = ::AzToolsFramework::Prefab::SpawnableUtils::CreateSpawnable(prefabDom); + AzFramework::Spawnable spawnable; + AzToolsFramework::Prefab::SpawnableUtils::CreateSpawnable(spawnable, prefabDom); EXPECT_EQ(spawnable.GetEntities().size() - 1, normalEntityCount); // 1 for container entity const auto& spawnableEntities = spawnable.GetEntities(); @@ -84,7 +85,8 @@ namespace UnitTest //Create Spawnable auto& prefabDom = m_prefabSystemComponent->FindTemplateDom(thirdInstance->GetTemplateId()); - auto spawnable = ::AzToolsFramework::Prefab::SpawnableUtils::CreateSpawnable(prefabDom); + AzFramework::Spawnable spawnable; + AzToolsFramework::Prefab::SpawnableUtils::CreateSpawnable(spawnable, prefabDom); EXPECT_EQ(spawnable.GetEntities().size() - 1, normalEntityCount); // 1 for container entity const auto& spawnableEntities = spawnable.GetEntities(); From 62b6cfac421fe9c1f1dac60c5a1a8ae97b0f3741 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 16:58:06 -0700 Subject: [PATCH 265/811] letting users pass CMAKE_MODULE_PATH to find the engine --- Templates/DefaultProject/Template/EngineFinder.cmake | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Templates/DefaultProject/Template/EngineFinder.cmake b/Templates/DefaultProject/Template/EngineFinder.cmake index a7dbf671fd..fbbe3d8cfe 100644 --- a/Templates/DefaultProject/Template/EngineFinder.cmake +++ b/Templates/DefaultProject/Template/EngineFinder.cmake @@ -61,5 +61,8 @@ if(EXISTS ${manifest_path}) endif() endforeach() else() - message(FATAL_ERROR "Engine registration is required before configuring a project. Please register an engine by running 'scripts/o3de register --this-engine'") + # If the user is passing CMAKE_MODULE_PATH we assume thats where we will find the engine + if(NOT CMAKE_MODULE_PATH) + message(FATAL_ERROR "Engine registration is required before configuring a project. Please register an engine by running 'scripts/o3de register --this-engine'") + endif() endif() From c21a59af50933d1d0541de154b2ef154de3c6c44 Mon Sep 17 00:00:00 2001 From: chiyteng Date: Thu, 27 May 2021 17:19:32 -0700 Subject: [PATCH 266/811] Remove print dom for debug previously --- .../Prefab/Instance/InstanceToTemplatePropagator.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index cd8fad1725..6d3ddedd51 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -176,15 +176,10 @@ namespace AzToolsFramework { PrefabDom& templateDomReference = m_prefabSystemComponentInterface->FindTemplateDom(templateId); - PrefabDomUtils::PrintPrefabDomValue("providedPatch", providedPatch); - PrefabDomUtils::PrintPrefabDomValue("templateDomReference", templateDomReference); - //apply patch to template AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::ApplyPatch(templateDomReference, templateDomReference.GetAllocator(), providedPatch, AZ::JsonMergeApproach::JsonPatch); - PrefabDomUtils::PrintPrefabDomValue("templateDomReference(Patch applied)", templateDomReference); - //trigger propagation if (result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success) { From d1a2eed40c37df587ee80bde6ddcd2b5ee7c3ed0 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 17:26:25 -0700 Subject: [PATCH 267/811] Fix identiation issues --- cmake/LYWrappers.cmake | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index 48423f3575..d7f88f12ec 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -88,8 +88,8 @@ function(ly_add_target) endif() if(NOT ly_add_target_IMPORTED AND NOT ly_add_target_HEADERONLY) if(NOT ly_add_target_FILES_CMAKE) - message(FATAL_ERROR "You must provide a list of _files.cmake files for the target") - endif() + message(FATAL_ERROR "You must provide a list of _files.cmake files for the target") + endif() endif() # If the GEM_MODULE tag is passed set the normal MODULE argument @@ -127,7 +127,7 @@ function(ly_add_target) set(linking_options INTERFACE) set(target_type_options INTERFACE) set(linking_count "${linking_count}1") - endif() + endif() if(ly_add_target_EXECUTABLE) set(linking_options EXECUTABLE) set(linking_count "${linking_count}1") From 9435305f01bce2bb88fcabb143654bf02edeeb61 Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Thu, 27 May 2021 19:31:32 -0500 Subject: [PATCH 268/811] Make entity creation via asset drag and drop properly create an entity so it works with prefabs correctly (#1010) --- .../AzAssetBrowserRequestHandler.cpp | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp index c8bd157b65..e0ba106875 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp @@ -137,8 +137,20 @@ namespace AzAssetBrowserRequestHandlerPrivate entityName = AZStd::string::format("Entity%d", GetIEditor()->GetObjectManager()->GetObjectCount()); } - AZ::Entity* newEntity = aznew AZ::Entity(entityName.c_str()); - EditorEntityContextRequestBus::Broadcast(&EditorEntityContextRequests::AddRequiredComponents, *newEntity); + AZ::EntityId targetEntityId; + EditorRequests::Bus::BroadcastResult(targetEntityId, &EditorRequests::CreateNewEntityAtPosition, worldTransform.GetTranslation(), AZ::EntityId()); + + AZ::Entity* newEntity = nullptr; + AZ::ComponentApplicationBus::BroadcastResult(newEntity, &AZ::ComponentApplicationRequests::FindEntity, targetEntityId); + + if (newEntity == nullptr) + { + return; + } + + newEntity->SetName(entityName); + + newEntity->Deactivate(); // Create component. AZ::Component* newComponent = newEntity->CreateComponent(componentTypeId); @@ -151,15 +163,7 @@ namespace AzAssetBrowserRequestHandlerPrivate newEntity->AddComponent(newComponent); } - // Set entity position. - auto* transformComponent = newEntity->FindComponent(); - if (transformComponent) - { - transformComponent->SetWorldTM(worldTransform); - } - - // Add the entity to the editor context, which activates it and creates the sandbox object. - EditorEntityContextRequestBus::Broadcast(&EditorEntityContextRequests::AddEditorEntity, newEntity); + newEntity->Activate(); // set asset after components have been activated in AddEditorEntity method if (newComponent) From 4a15f55f789a8c3e9cae506e43b4482c20b303c7 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 17:37:59 -0700 Subject: [PATCH 269/811] Updating AutomatedTesting/EngineFinder.cmake --- AutomatedTesting/EngineFinder.cmake | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/AutomatedTesting/EngineFinder.cmake b/AutomatedTesting/EngineFinder.cmake index a7dbf671fd..fbbe3d8cfe 100644 --- a/AutomatedTesting/EngineFinder.cmake +++ b/AutomatedTesting/EngineFinder.cmake @@ -61,5 +61,8 @@ if(EXISTS ${manifest_path}) endif() endforeach() else() - message(FATAL_ERROR "Engine registration is required before configuring a project. Please register an engine by running 'scripts/o3de register --this-engine'") + # If the user is passing CMAKE_MODULE_PATH we assume thats where we will find the engine + if(NOT CMAKE_MODULE_PATH) + message(FATAL_ERROR "Engine registration is required before configuring a project. Please register an engine by running 'scripts/o3de register --this-engine'") + endif() endif() From 57913d837854fafe4b47725266d62aaabc694f6e Mon Sep 17 00:00:00 2001 From: srikappa Date: Thu, 27 May 2021 18:19:28 -0700 Subject: [PATCH 270/811] A couple of bug fixes --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 6 +++--- .../AzToolsFramework/Prefab/PrefabSystemComponent.cpp | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 1b98711352..f6ded4ae45 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -1141,12 +1141,12 @@ namespace AzToolsFramework CreateLink(*nestedInstancePtr, parentTemplateId, currentUndoBatch, AZStd::move(linkPatchesCopy), true); }); - - AzToolsFramework::ToolsApplicationRequestBus::Broadcast( - &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); } } + AzToolsFramework::ToolsApplicationRequestBus::Broadcast( + &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); + if (createdUndo) { ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::EndUndoBatch); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index c4e6415b02..1d478ad581 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -652,7 +652,8 @@ namespace AzToolsFramework if (instancesValue->get().FindMember(rapidjson::StringRef(instanceAlias.c_str())) == instancesValue->get().MemberEnd()) { instancesValue->get().AddMember( - rapidjson::StringRef(instanceAlias.c_str()), PrefabDomValue(), targetTemplateDom.GetAllocator()); + rapidjson::Value(instanceAlias.c_str(), targetTemplateDom.GetAllocator()), PrefabDomValue(), + targetTemplateDom.GetAllocator()); } Template& sourceTemplate = sourceTemplateRef->get(); From 32b620501dfb3cb2c1d875cb3fac6281ae511843 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 18:33:28 -0700 Subject: [PATCH 271/811] Fix some cross dependencies between client and non-client gems --- Gems/LyShineExamples/Code/CMakeLists.txt | 16 ++++++++-------- Gems/ScriptCanvasPhysics/Code/CMakeLists.txt | 16 +++++++--------- Gems/ScriptCanvasTesting/Code/CMakeLists.txt | 4 ++-- cmake/SettingsRegistry.cmake | 2 +- 4 files changed, 18 insertions(+), 20 deletions(-) diff --git a/Gems/LyShineExamples/Code/CMakeLists.txt b/Gems/LyShineExamples/Code/CMakeLists.txt index ce420cbd30..04812ec722 100644 --- a/Gems/LyShineExamples/Code/CMakeLists.txt +++ b/Gems/LyShineExamples/Code/CMakeLists.txt @@ -20,9 +20,10 @@ ly_add_target( PUBLIC Include BUILD_DEPENDENCIES + PRIVATE + Gem::LmbrCentral PUBLIC Legacy::CryCommon - Gem::LmbrCentral Gem::LyShine.Static ) @@ -39,13 +40,12 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE Gem::LyShineExamples.Static - RUNTIME_DEPENDENCIES - Gem::LmbrCentral ) -# if enabled, LyShineExamples is used by all kinds of applications -ly_create_alias(NAME LyShineExamples.Builders NAMESPACE Gem TARGETS Gem::LyShineExamples) -ly_create_alias(NAME LyShineExamples.Tools NAMESPACE Gem TARGETS Gem::LyShineExamples) -ly_create_alias(NAME LyShineExamples.Clients NAMESPACE Gem TARGETS Gem::LyShineExamples) -ly_create_alias(NAME LyShineExamples.Servers NAMESPACE Gem TARGETS Gem::LyShineExamples) +# if enabled, LyShineExamples is used by all kinds of applications, however, the dependency to LmbrCentral is different +# per application type +ly_create_alias(NAME LyShineExamples.Builders NAMESPACE Gem TARGETS Gem::LyShineExamples Gem::LmbrCentral.Editor) +ly_create_alias(NAME LyShineExamples.Tools NAMESPACE Gem TARGETS Gem::LyShineExamples Gem::LmbrCentral.Editor) +ly_create_alias(NAME LyShineExamples.Clients NAMESPACE Gem TARGETS Gem::LyShineExamples Gem::LmbrCentral) +ly_create_alias(NAME LyShineExamples.Servers NAMESPACE Gem TARGETS Gem::LyShineExamples Gem::LmbrCentral) diff --git a/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt b/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt index 73ec851b70..c97dba180a 100644 --- a/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt @@ -18,10 +18,9 @@ ly_add_target( PRIVATE Source BUILD_DEPENDENCIES - PUBLIC - Gem::ScriptCanvas PRIVATE Legacy::CryCommon + Gem::ScriptCanvas ) ly_add_target( @@ -36,15 +35,14 @@ ly_add_target( PRIVATE Legacy::CryCommon Gem::ScriptCanvasPhysics.Static - RUNTIME_DEPENDENCIES - Gem::ScriptCanvas ) -# By default, the above module is used by all application types -ly_create_alias(NAME ScriptCanvasPhysics.Clients NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics) -ly_create_alias(NAME ScriptCanvasPhysics.Servers NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics) -ly_create_alias(NAME ScriptCanvasPhysics.Tools NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics) -ly_create_alias(NAME ScriptCanvasPhysics.Builders NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics) +# By default, the above module is used by all application types, however, the module depends at runtime to ScriptCanvas +# and the dependency needs to be different per application type +ly_create_alias(NAME ScriptCanvasPhysics.Clients NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics Gem::ScriptCanvas) +ly_create_alias(NAME ScriptCanvasPhysics.Servers NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics Gem::ScriptCanvas) +ly_create_alias(NAME ScriptCanvasPhysics.Tools NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics Gem::ScriptCanvas.Editor) +ly_create_alias(NAME ScriptCanvasPhysics.Builders NAMESPACE Gem TARGETS Gem::ScriptCanvasPhysics Gem::ScriptCanvas.Editor) ################################################################################ # Tests diff --git a/Gems/ScriptCanvasTesting/Code/CMakeLists.txt b/Gems/ScriptCanvasTesting/Code/CMakeLists.txt index 5641813a43..c6264e2fef 100644 --- a/Gems/ScriptCanvasTesting/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasTesting/Code/CMakeLists.txt @@ -34,7 +34,7 @@ ly_add_target( Gem::ScriptCanvas Gem::ScriptCanvasEditor Gem::GraphCanvasWidgets - Gem::ScriptEvents + Gem::ScriptEvents.Editor PRIVATE AZ::AzCore AZ::AzFramework @@ -46,7 +46,7 @@ ly_add_target( *.ScriptCanvasNodeable.xml,ScriptCanvasNodeable_Header.jinja,$path/$fileprefix.generated.h *.ScriptCanvasNodeable.xml,ScriptCanvasNodeable_Source.jinja,$path/$fileprefix.generated.cpp RUNTIME_DEPENDENCIES - Gem::ScriptCanvas + Gem::ScriptCanvas.Editor Gem::ScriptCanvasEditor Gem::GraphCanvasWidgets Gem::ScriptEvents diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index 6f929d06e1..4d932601b4 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -74,7 +74,6 @@ function(ly_get_gem_load_dependencies ly_GEM_LOAD_DEPENDENCIES ly_TARGET) ly_get_gem_load_dependencies(dependencies ${dealias_load_dependency}) list(APPEND all_gem_load_dependencies ${dependencies}) list(APPEND all_gem_load_dependencies ${dealias_load_dependency}) - message(VERBOSE "Load Dependency \"${dealias_load_dependency}\" has load dependencies of: ${dependencies}") endif() endforeach() endif() @@ -83,6 +82,7 @@ function(ly_get_gem_load_dependencies ly_GEM_LOAD_DEPENDENCIES ly_TARGET) set_property(GLOBAL PROPERTY LY_GEM_LOAD_DEPENDENCIES_${ly_TARGET} "${all_gem_load_dependencies}") set(${ly_GEM_LOAD_DEPENDENCIES} ${all_gem_load_dependencies} PARENT_SCOPE) message(VERBOSE "Gem Target \"${ly_TARGET}\" has load dependencies of: ${all_gem_load_dependencies}") + endfunction() #!ly_get_gem_module_root: Uses the supplied gem_target to lookup the nearest gem.json file above the SOURCE_DIR From 639240576f9d696cba04547831473c7bb1f181d5 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 18:37:34 -0700 Subject: [PATCH 272/811] Adding alias for the project gem so it gets loaded --- AutomatedTesting/Gem/Code/CMakeLists.txt | 6 ++++++ .../DefaultProject/Template/Code/CMakeLists.txt | 12 +++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/AutomatedTesting/Gem/Code/CMakeLists.txt b/AutomatedTesting/Gem/Code/CMakeLists.txt index 9315bf8397..548aa51ad1 100644 --- a/AutomatedTesting/Gem/Code/CMakeLists.txt +++ b/AutomatedTesting/Gem/Code/CMakeLists.txt @@ -28,6 +28,12 @@ ly_add_target( Gem::Atom_AtomBridge.Static ) +# if enabled, AutomatedTesting is used by all kinds of applications +ly_create_alias(NAME AutomatedTesting.Builders NAMESPACE Gem TARGETS Gem::AutomatedTesting) +ly_create_alias(NAME AutomatedTesting.Tools NAMESPACE Gem TARGETS Gem::AutomatedTesting) +ly_create_alias(NAME AutomatedTesting.Clients NAMESPACE Gem TARGETS Gem::AutomatedTesting) +ly_create_alias(NAME AutomatedTesting.Servers NAMESPACE Gem TARGETS Gem::AutomatedTesting) + ################################################################################ # Gem dependencies ################################################################################ diff --git a/Templates/DefaultProject/Template/Code/CMakeLists.txt b/Templates/DefaultProject/Template/Code/CMakeLists.txt index b116fb2044..43459b1606 100644 --- a/Templates/DefaultProject/Template/Code/CMakeLists.txt +++ b/Templates/DefaultProject/Template/Code/CMakeLists.txt @@ -33,7 +33,7 @@ endif() # in ${pal_dir}/${NameLower}_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake ly_add_target( NAME ${Name}.Static STATIC - NAMESPACE Project + NAMESPACE Gem FILES_CMAKE ${NameLower}_files.cmake ${pal_dir}/${NameLower}_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake @@ -48,7 +48,7 @@ ly_add_target( ly_add_target( NAME ${Name} ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} - NAMESPACE Project + NAMESPACE Gem FILES_CMAKE ${NameLower}_shared_files.cmake ${pal_dir}/${NameLower}_shared_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake @@ -57,10 +57,16 @@ ly_add_target( Include BUILD_DEPENDENCIES PRIVATE - Project::${Name}.Static + Gem::${Name}.Static AZ::AzCore ) +# if enabled, ${Name} is used by all kinds of applications +ly_create_alias(NAME ${Name}.Builders NAMESPACE Gem TARGETS Gem::${Name}) +ly_create_alias(NAME ${Name}.Tools NAMESPACE Gem TARGETS Gem::${Name}) +ly_create_alias(NAME ${Name}.Clients NAMESPACE Gem TARGETS Gem::${Name}) +ly_create_alias(NAME ${Name}.Servers NAMESPACE Gem TARGETS Gem::${Name}) + ################################################################################ # Gem dependencies ################################################################################ From 68e2fb83dd8101923b3c85c352808ece9c3db32b Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 18:54:22 -0700 Subject: [PATCH 273/811] More dependency fixes for linux builds --- Gems/LyShineExamples/Code/CMakeLists.txt | 1 + Gems/ScriptCanvasPhysics/Code/CMakeLists.txt | 2 ++ 2 files changed, 3 insertions(+) diff --git a/Gems/LyShineExamples/Code/CMakeLists.txt b/Gems/LyShineExamples/Code/CMakeLists.txt index 04812ec722..96c41bbb64 100644 --- a/Gems/LyShineExamples/Code/CMakeLists.txt +++ b/Gems/LyShineExamples/Code/CMakeLists.txt @@ -40,6 +40,7 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE Gem::LyShineExamples.Static + Gem::LmbrCentral ) # if enabled, LyShineExamples is used by all kinds of applications, however, the dependency to LmbrCentral is different diff --git a/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt b/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt index c97dba180a..107db38f5e 100644 --- a/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasPhysics/Code/CMakeLists.txt @@ -35,6 +35,7 @@ ly_add_target( PRIVATE Legacy::CryCommon Gem::ScriptCanvasPhysics.Static + Gem::ScriptCanvas ) # By default, the above module is used by all application types, however, the module depends at runtime to ScriptCanvas @@ -63,6 +64,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest Legacy::CryCommon Gem::ScriptCanvasPhysics.Static + Gem::ScriptCanvas ) ly_add_googletest( NAME Gem::ScriptCanvasPhysics.Tests From 87721cae55fd167724ddace87b62b9fc6a853bed Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 20:56:03 -0500 Subject: [PATCH 274/811] Removed the ability to run download command from the o3de python package without user intervention --- scripts/o3de.py | 5 +---- scripts/o3de/o3de/download.py | 3 +-- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/scripts/o3de.py b/scripts/o3de.py index 24ba862529..8d7532878c 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -31,7 +31,7 @@ def add_args(parser, subparsers) -> None: o3de_package_dir = (script_dir / 'o3de').resolve() # add the scripts/o3de directory to the front of the sys.path sys.path.insert(0, str(o3de_package_dir)) - from o3de import engine_template, global_project, register, print_registration, get_registration, download, \ + from o3de import engine_template, global_project, register, print_registration, get_registration, \ enable_gem, disable_gem, sha256 # Remove the temporarily added path sys.path = sys.path[1:] @@ -50,9 +50,6 @@ def add_args(parser, subparsers) -> None: # get-registered get_registration.add_args(subparsers) - # download - download.add_args(subparsers) - # add a gem to a project enable_gem.add_args(subparsers) diff --git a/scripts/o3de/o3de/download.py b/scripts/o3de/o3de/download.py index 1dbb584c92..6f1b82e754 100644 --- a/scripts/o3de/o3de/download.py +++ b/scripts/o3de/o3de/download.py @@ -237,5 +237,4 @@ def main(): sys.exit(ret) -if __name__ == "__main__": - main() +# Do not allow running the download.py script as a standalone script until it is reviewed by app-sec From 425cb3e2fa4065c24661c4bfccf598c177e61f73 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 19:18:42 -0700 Subject: [PATCH 275/811] Aaaaannnddd another dependency fix --- Gems/ScriptCanvasTesting/Code/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/ScriptCanvasTesting/Code/CMakeLists.txt b/Gems/ScriptCanvasTesting/Code/CMakeLists.txt index c6264e2fef..76a549d6b9 100644 --- a/Gems/ScriptCanvasTesting/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasTesting/Code/CMakeLists.txt @@ -109,6 +109,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzFramework AZ::AzToolsFramework Gem::ScriptCanvasTesting.Editor.Static + Gem::ScriptCanvas.Editor RUNTIME_DEPENDENCIES Gem::GraphCanvas.Editor Gem::ScriptCanvas.Editor From 74464afbf3a31ea0e82c766444fb34e5bd4c451a Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 21:20:19 -0500 Subject: [PATCH 276/811] Updated the global_project.py script to be able to specify and output path when setting the global project path Also updated that script to support an input path when reading the global project path. Added a unit test for the global_projecy.py "set-global-project" command --- scripts/o3de/o3de/disable_gem.py | 2 +- scripts/o3de/o3de/enable_gem.py | 2 +- scripts/o3de/o3de/global_project.py | 221 +++++++++++------- scripts/o3de/o3de/manifest.py | 12 +- scripts/o3de/o3de/register.py | 8 +- scripts/o3de/o3de/sha256.py | 2 +- scripts/o3de/tests/CMakeLists.txt | 7 + scripts/o3de/tests/unit_global_project.py | 40 ++++ .../o3de/tests/unit_test_current_project.py | 102 -------- 9 files changed, 192 insertions(+), 204 deletions(-) create mode 100644 scripts/o3de/tests/unit_global_project.py delete mode 100755 scripts/o3de/tests/unit_test_current_project.py diff --git a/scripts/o3de/o3de/disable_gem.py b/scripts/o3de/o3de/disable_gem.py index 6c466c3631..61d71445f0 100644 --- a/scripts/o3de/o3de/disable_gem.py +++ b/scripts/o3de/o3de/disable_gem.py @@ -83,7 +83,7 @@ def disable_gem_in_project(gem_name: str = None, project_path = manifest.get_registered(project_name=project_name) if not project_path: logger.error(f'Unable to locate project path from the registered manifest.json files:' - f' {str(pathlib.Path.home() / ".o3de/manifest.json")}, engine.json') + f' {str(pathlib.Path("~/.o3de/o3de_manifest.json").expanduser())}, engine.json') return 1 project_path = pathlib.Path(project_path).resolve() diff --git a/scripts/o3de/o3de/enable_gem.py b/scripts/o3de/o3de/enable_gem.py index 73fc2ea3cf..0dee01e05e 100644 --- a/scripts/o3de/o3de/enable_gem.py +++ b/scripts/o3de/o3de/enable_gem.py @@ -117,7 +117,7 @@ def enable_gem_in_project(gem_name: str = None, gem_path = manifest.get_registered(gem_name=gem_name) if not gem_path: logger.error(f'Unable to locate gem path from the registered manifest.json files:' - f' {str(pathlib.Path.home() / ".o3de/manifest.json")},' + f' {str(pathlib.Path( "~/.o3de/o3de_manifest.json").expanduser())},' f' {project_path / "project.json"}, engine.json') return 1 diff --git a/scripts/o3de/o3de/global_project.py b/scripts/o3de/o3de/global_project.py index 787e676a7e..d165510250 100644 --- a/scripts/o3de/o3de/global_project.py +++ b/scripts/o3de/o3de/global_project.py @@ -16,94 +16,122 @@ import sys import re import pathlib import json -from o3de import manifest + +from o3de import manifest, validation logger = logging.getLogger() logging.basicConfig() +DEFAULT_BOOTSTRAP_SETREG = pathlib.Path('~/.o3de/Registry/bootstrap.setreg').expanduser() +PROJECT_PATH_KEY = ('Amazon', 'AzCore', 'Bootstrap', 'project_path') -def set_global_project(project_name: str or None, - project_path: str or pathlib.Path or None) -> int: +def get_json_data(input_path: pathlib.Path): + setreg_json_data = {} + # If the output_path exist validate that it is a valid json file + if input_path.is_file(): + with input_path.open('r') as f: + try: + setreg_json_data = json.load(f) + except json.JSONDecodeError as e: + logger.error(f'The file: {input_path} is not a valid json file: {str(e)}') + + return setreg_json_data + +def set_global_project(output_path: pathlib.Path, + project_name: str = None, + project_path: pathlib.Path = None, + force: bool = False) -> int: """ - set what the current project is - :param project_name: the name of the project you want to set, resolves project_path - :param project_path: the path of the project you want to set + Adds a project path the a settings registry file in the users ~/.o3de/Registry directory + :param output_path: path to .setreg file to store project_path value into + :param project_name: name of the project to lookup path for + :param project_path: path to the project to add to .setreg file + :param force: if set, the project path will be set within the .setreg file regardless of if the path doesn't exist :return: 0 for success or non 0 failure code """ - if project_path and project_name: - logger.error(f'Project Name and Project Path provided, these are mutually exclusive.') - return 1 - + # we need either a project name or path if not project_name and not project_path: - logger.error('Must specify either a Project name or Project Path.') + logger.error(f'Must either specify a Project path or Project Name.') return 1 + # if project name resolve it into a path if project_name and not project_path: project_path = manifest.get_registered(project_name=project_name) if not project_path: - logger.error(f'Project Path {project_path} has not been registered.') + logger.error( + f'The project name has been supplied. Unable to locate project path from the registered manifest.json files:' + f' {str(pathlib.Path("~/.o3de/o3de_manifest.json").expanduser())}, engine.json\n' + 'A The --project-path parameter can be used directly to skip checking the manifest') return 1 - project_path = pathlib.Path(project_path).resolve() + # Only perform project path validations when force=False + if not force: + if not project_path.is_dir(): + logger.error(f'Project path {project_path} is not a folder.') + return 1 - bootstrap_setreg_file = manifest.get_o3de_registry_folder() / 'bootstrap.setreg' - if bootstrap_setreg_file.is_file(): - with bootstrap_setreg_file.open('r') as f: + # Validate that the supplied path points contains a valid project.json + if not validation.valid_o3de_project_json(project_path / 'project.json'): + logger.error(f'The supplied project path does not contain a valid project.json.\n' + f'The Path will not be set') + return 1 + + # If the output_path exist validate that it is a valid json file and read it's json data + setreg_json_data = get_json_data(output_path) + if output_path.is_file(): + with output_path.open('r') as f: try: - json_data = json.load(f) - except json.JSONDecodeError as e: - logger.error(f'Bootstrap.setreg failed to load: {str(e)}') - else: - try: - json_data["Amazon"]["AzCore"]["Bootstrap"]["project_path"] = project_path - except KeyError as e: - logger.error(f'Bootstrap.setreg failed to load: {str(e)}') - else: - try: - os.unlink(bootstrap_setreg_file) - except OSError as e: - logger.error(f'Failed to unlink bootstrap file {bootstrap_setreg_file}: {str(e)}') - return 1 - else: - json_data = {} - json_data.update({"Amazon":{"AzCore":{"Bootstrap":{"project_path":project_path.as_posix()}}}}) + setreg_json_data = json.load(f) + except (json.JSONDecodeError) as e: + logger.error(f'The output file: {output_path} is not a valid json file: {str(e)}') + return 1 - with bootstrap_setreg_file.open('w') as s: - s.write(json.dumps(json_data, indent=4)) + # Add a json dictionary that will be merged with any existing json data from the .setreg file + merge_json_data = {} + json_object_iter = merge_json_data + for json_key in PROJECT_PATH_KEY[:-1]: + # Add the parent json object for the key to update + json_object_iter = json_object_iter.setdefault(json_key, {}) + + # Set the project path value here + json_object_iter[PROJECT_PATH_KEY[-1]] = project_path.as_posix() + setreg_json_data.update(merge_json_data) + + # Create the parent directories + if output_path.parent: + output_path.parent.mkdir(parents=True, exist_ok=True) + try: + with output_path.open('w') as s: + s.write(json.dumps(setreg_json_data, indent=4) + '\n') + except OSError as e: + logger.error(f'Failed to write project path {project_path} to file {output_path}: {str(e)}') + return 1 return 0 -def get_global_project() -> pathlib.Path or None: +def get_global_project(input_path: pathlib.Path) -> pathlib.Path or None: """ - get what the current project set is + Retrieves the /Amazon/AzCore/Bootstrap/project_path key from the supplied file path :return: project_path or None on failure """ - bootstrap_setreg_file = manifest.get_o3de_registry_folder() / 'bootstrap.setreg' - if not bootstrap_setreg_file.is_file(): - logger.error(f'Bootstrap.setreg file {bootstrap_setreg_file} does not exist.') - return None + setreg_json_data = get_json_data(input_path) - with bootstrap_setreg_file.open('r') as f: - try: - json_data = json.load(f) - except json.JSONDecodeError as e: - logger.error(f'Bootstrap.setreg failed to load: {str(e)}') - else: - try: - project_path = json_data["Amazon"]["AzCore"]["Bootstrap"]["project_path"] - except KeyError as e: - logger.error(f'Bootstrap.setreg cannot find Amazon:AzCore:Bootstrap:project_path: {str(e)}') - else: - return pathlib.Path(project_path).resolve() + try: + # Iterate over each element of the tuple and read the json key from each successive json object + json_object_iter = setreg_json_data + for json_key in PROJECT_PATH_KEY: + json_object_iter = json_object_iter[json_key] + except KeyError as e: + logger.error(f'Cannot read key /{"/".join(PROJECT_PATH_KEY)} from file {input_path.as_posix()}: {str(e)}') + else: + project_path = json_object_iter + return pathlib.Path(project_path).resolve() return None def _run_get_global_project(args: argparse) -> int: - if args.override_home_folder: - manifest.override_home_folder = args.override_home_folder - - project_path = get_global_project() + project_path = get_global_project(args.input_path) if project_path: print(project_path.as_posix()) return 0 @@ -111,51 +139,66 @@ def _run_get_global_project(args: argparse) -> int: def _run_set_global_project(args: argparse) -> int: - if args.override_home_folder: - manifest.override_home_folder = args.override_home_folder + return set_global_project(args.output_path, + args.project_name, + args.project_path, + args.force) - return set_global_project(args.project_name, - args.project_path) +def add_parser_args(get_project_parser, set_project_parser): + """ + add_parser_args is called to add arguments to each command such that it can be + invoked locally or added by a central python file. + Ex. Directly run from this file alone with: python global_project.py --project-path "D:/TestProject" + :param parser: the caller passes an argparse parser like instance to this method + """ + + # get-current-project + get_project_parser.add_argument('-i', '--input-path', type=pathlib.Path, required=False, default=DEFAULT_BOOTSTRAP_SETREG, + help=f'Optional path to file to read /{"/".join(PROJECT_PATH_KEY)} key from.' + f' If not supplied, then {DEFAULT_BOOTSTRAP_SETREG} is used instead') + get_project_parser.set_defaults(func=_run_get_global_project) + + # set-current-project + group = set_project_parser.add_mutually_exclusive_group(required=True) + group.add_argument('-pp', '--project-path', type=pathlib.Path, required=False, + help='The path to the project.') + group.add_argument('-pn', '--project-name', type=str, required=False, + help='The name of the project.') + set_project_parser.add_argument('-o', '--output-path', type=pathlib.Path, required=False, + default=DEFAULT_BOOTSTRAP_SETREG, + help=f'Optional path to output file to write project_path key to. ' + f'If not supplied, then {DEFAULT_BOOTSTRAP_SETREG} is used instead') + set_project_parser.add_argument('-f', '--force', action='store_true', default=False, + help=f'Force the setting of the project path in the supplied setreg file') + set_project_parser.set_defaults(func=_run_set_global_project) def add_args(subparsers) -> None: """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be - invoked locally or aggregated by a central python file. - Ex. Directly run from this file alone with: python global_project.py set_global_project --project-name TestProject - OR - o3de.py can aggregate commands by importing global_project, call add_args and - execute: python o3de.py set_global_project --project-path C:/TestProject + add_args is called to add subparsers arguments to each command such that it can be + a central python file such as o3de.py. + It can be run from the o3de.py script as follows + call add_args and execute: python o3de.py set-global-project --project-path "D:/TestProject" :param subparsers: the caller instantiates subparsers and passes it in here """ - get_global_project_subparser = subparsers.add_parser('get-global-project') - get_global_project_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - get_global_project_subparser.set_defaults(func=_run_get_global_project) - - set_global_project_subparser = subparsers.add_parser('set-global-project') - group = set_global_project_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('-pn', '--project-name', required=False, - help='The name of the project. If supplied this will resolve the --project-path.') - group.add_argument('-pp', '--project-path', required=False, - help='The path to the project') - - set_global_project_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') - - set_global_project_subparser.set_defaults(func=_run_set_global_project) + get_project_subparser = subparsers.add_parser('get-global-project') + set_project_subparser = subparsers.add_parser('set-global-project') + add_parser_args(get_project_subparser, set_project_subparser) -if __name__ == "__main__": +def main(): + """ + Runs this script as standalone script + """ # parse the command line args the_parser = argparse.ArgumentParser() # add subparsers - the_subparsers = the_parser.add_subparsers(help='sub-command help', dest='command', required=True) + project_subparsers = the_parser.add_subparsers(help="Commands for modifying the project path in the user's home" + " setreg files") # add args to the parser - add_args(the_subparsers) + add_args(project_subparsers) # parse args the_args = the_parser.parse_args() @@ -165,3 +208,7 @@ if __name__ == "__main__": # return sys.exit(ret) + + +if __name__ == "__main__": + main() diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index 092430500f..9436e1dd29 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -142,7 +142,7 @@ def get_o3de_manifest() -> pathlib.Path: with default_restricted_folder_json.open('w') as s: restricted_json_data = {} restricted_json_data.update({'restricted_name': 'o3de'}) - s.write(json.dumps(restricted_json_data, indent=4)) + s.write(json.dumps(restricted_json_data, indent=4) + '\n') json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) default_projects_restricted_folder_json = default_projects_restricted_folder / 'restricted.json' @@ -150,24 +150,24 @@ def get_o3de_manifest() -> pathlib.Path: with default_projects_restricted_folder_json.open('w') as s: restricted_json_data = {} restricted_json_data.update({'restricted_name': 'projects'}) - s.write(json.dumps(restricted_json_data, indent=4)) + s.write(json.dumps(restricted_json_data, indent=4) + '\n') default_gems_restricted_folder_json = default_gems_restricted_folder / 'restricted.json' if not default_gems_restricted_folder_json.is_file(): with default_gems_restricted_folder_json.open('w') as s: restricted_json_data = {} restricted_json_data.update({'restricted_name': 'gems'}) - s.write(json.dumps(restricted_json_data, indent=4)) + s.write(json.dumps(restricted_json_data, indent=4) + '\n') default_templates_restricted_folder_json = default_templates_restricted_folder / 'restricted.json' if not default_templates_restricted_folder_json.is_file(): with default_templates_restricted_folder_json.open('w') as s: restricted_json_data = {} restricted_json_data.update({'restricted_name': 'templates'}) - s.write(json.dumps(restricted_json_data, indent=4)) + s.write(json.dumps(restricted_json_data, indent=4) + '\n') with manifest_path.open('w') as s: - s.write(json.dumps(json_data, indent=4)) + s.write(json.dumps(json_data, indent=4) + '\n') return manifest_path @@ -201,7 +201,7 @@ def save_o3de_manifest(json_data: dict, manifest_path: pathlib.Path = None) -> N manifest_path = get_o3de_manifest() with manifest_path.open('w') as s: try: - s.write(json.dumps(json_data, indent=4)) + s.write(json.dumps(json_data, indent=4) + '\n') except OSError as e: logger.error(f'Manifest json failed to save: {str(e)}') diff --git a/scripts/o3de/o3de/register.py b/scripts/o3de/o3de/register.py index 1b30448db9..68575488dc 100644 --- a/scripts/o3de/o3de/register.py +++ b/scripts/o3de/o3de/register.py @@ -410,12 +410,8 @@ def register_project_path(json_data: dict, if update_project_json: project_json_data['engine'] = this_engine_json['engine_name'] utils.backup_file(project_json) - with project_json.open('w') as s: - try: - s.write(json.dumps(project_json_data, indent=4)) - except OSError as e: - logger.error(f'Project json failed to save: {str(e)}') - return 1 + if not manifest.save_o3de_manifest(project_json_data, project_path): + return 1 return 0 diff --git a/scripts/o3de/o3de/sha256.py b/scripts/o3de/o3de/sha256.py index bbec7696d6..db0a1fe834 100644 --- a/scripts/o3de/o3de/sha256.py +++ b/scripts/o3de/o3de/sha256.py @@ -51,7 +51,7 @@ def sha256(file_path: str or pathlib.Path, utils.backup_file(json_path) with json_path.open('w') as s: try: - s.write(json.dumps(json_data, indent=4)) + s.write(json.dumps(json_data, indent=4) + '\n') except OSError as e: logger.error(f'Failed to write Json path {json_path}: {str(e)}') return 1 diff --git a/scripts/o3de/tests/CMakeLists.txt b/scripts/o3de/tests/CMakeLists.txt index 5c83f4112b..0526c7740d 100644 --- a/scripts/o3de/tests/CMakeLists.txt +++ b/scripts/o3de/tests/CMakeLists.txt @@ -27,3 +27,10 @@ ly_add_pytest( TEST_SUITE smoke EXCLUDE_TEST_RUN_TARGET_FROM_IDE ) + +ly_add_pytest( + NAME o3de_global_project + PATH ${CMAKE_CURRENT_LIST_DIR}/unit_test_global_project.py + TEST_SUITE smoke + EXCLUDE_TEST_RUN_TARGET_FROM_IDE +) diff --git a/scripts/o3de/tests/unit_global_project.py b/scripts/o3de/tests/unit_global_project.py new file mode 100644 index 0000000000..1d3a4dd4f4 --- /dev/null +++ b/scripts/o3de/tests/unit_global_project.py @@ -0,0 +1,40 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +import io +import json +import logging +import pytest +import pathlib +from unittest.mock import patch + +from o3de import global_project + + +logger = logging.getLogger() +logging.basicConfig() + +DEFAULT_BOOTSTRAP_SETREG = pathlib.Path('~/.o3de/Registry/bootstrap.setreg').expanduser() +PROJECT_PATH_KEY = ('Amazon', 'AzCore', 'Bootstrap', 'project_path') + +class TestSetGlobalProject: + @pytest.mark.parametrize( + "output_path, project_path, force, expected_result", [ + pytest.param(pathlib.Path('~/.o3de/Registry/bootstrap.setreg'), pathlib.Path('A:/'), False, False), + pytest.param(pathlib.Path('~/.o3de/Registry/bootstrap.setreg'), pathlib.Path('A:/'), True, True) + ] + ) + def test_set_global_project_non_existent_project_path(self, output_path, project_path, force, expected_result): + with patch('pathlib.Path.open', return_value=io.StringIO()) as pathlib_open_mock: + result = global_project.set_global_project(output_path, project_path=project_path, force=force) == 0 + + + assert result == expected_result diff --git a/scripts/o3de/tests/unit_test_current_project.py b/scripts/o3de/tests/unit_test_current_project.py deleted file mode 100755 index 7db48b62aa..0000000000 --- a/scripts/o3de/tests/unit_test_current_project.py +++ /dev/null @@ -1,102 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -import os -import pytest - -from . import current_project - -TEST_BOOTSTRAP_CONTENT_1 = """ -project_path = Game1 -foo = bar -key1 = value1 -key2 = value2 -assets = pc -""" -TEST_BOOTSTRAP_CONTENT_2 = """ -project_path=Game1 -foo = bar -key1 = value1 -key2 = value2 -assets = pc -""" -TEST_BOOTSTRAP_CONTENT_3 = """ -project_path= Game1 -foo = bar -key1 = value1 -key2 = value2 -assets = pc -""" -TEST_BOOTSTRAP_CONTENT_4 = """ -project_path =Game1 -foo = bar -key1 = value1 -key2 = value2 -assets = pc -""" -TEST_BOOTSTRAP_CONTENT_5 = """ -project_path = Game1 -foo = bar -key1 = value1 -key2 = value2 -assets = pc -""" - -@pytest.mark.parametrize( - "contents, expected_result", [ - pytest.param(TEST_BOOTSTRAP_CONTENT_1, 'Game1'), - pytest.param(TEST_BOOTSTRAP_CONTENT_2, 'Game1'), - pytest.param(TEST_BOOTSTRAP_CONTENT_3, 'Game1'), - pytest.param(TEST_BOOTSTRAP_CONTENT_4, 'Game1'), - pytest.param(TEST_BOOTSTRAP_CONTENT_5, 'Game1'), - ] -) -def test_get_current_project(tmpdir, contents, expected_result): - dev_root = str(tmpdir.join('dev').realpath()).replace('\\', '/') - os.makedirs(dev_root, exist_ok=True) - - bootstrap_file = f'{dev_root}/bootstrap.cfg' - if os.path.isfile(bootstrap_file): - os.unlink(bootstrap_file) - with open(bootstrap_file, 'a') as s: - s.write(contents) - - result = current_project.get_current_project(dev_root) - assert expected_result == result - - -@pytest.mark.parametrize( - "contents, project_to_set, expected_result", [ - pytest.param(TEST_BOOTSTRAP_CONTENT_1, 'Test1', 0), - pytest.param(TEST_BOOTSTRAP_CONTENT_1, ' Test2', 0), - pytest.param(TEST_BOOTSTRAP_CONTENT_1, 'Test3 ', 0), - pytest.param(TEST_BOOTSTRAP_CONTENT_1, '/Test4', 1), - pytest.param(TEST_BOOTSTRAP_CONTENT_1, '=Test5', 1), - ] -) -def test_set_current_project(tmpdir, contents, project_to_set, expected_result): - dev_root = str(tmpdir.join('dev').realpath()).replace('\\', '/') - os.makedirs(dev_root, exist_ok=True) - - bootstrap_file = f'{dev_root}/bootstrap.cfg' - if os.path.isfile(bootstrap_file): - os.unlink(bootstrap_file) - with open(bootstrap_file, 'a') as s: - s.write(contents) - - result = current_project.set_current_project(dev_root, project_to_set) - assert expected_result == result - - if result == 0: - project_that_is_set = current_project.get_current_project(dev_root) - print(project_that_is_set) - print(project_to_set) - assert project_to_set.strip() == project_that_is_set \ No newline at end of file From bee811ae4ffa6767853233bfe32416ba2a709450 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Thu, 27 May 2021 19:22:46 -0700 Subject: [PATCH 277/811] Moved Simulate to OnBeginPrepareRender. --- .../OcclusionCullingPlaneFeatureProcessor.cpp | 6 ++---- .../OcclusionCullingPlaneFeatureProcessor.h | 4 +++- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp index d4a1a37521..bed008a3da 100644 --- a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp @@ -47,10 +47,8 @@ namespace AZ DisableSceneNotification(); } - void OcclusionCullingPlaneFeatureProcessor::Simulate([[maybe_unused]] const FeatureProcessor::SimulatePacket& packet) - { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); - + void OcclusionCullingPlaneFeatureProcessor::OnBeginPrepareRender() + { AZStd::vector occlusionCullingPlanes; for (auto& occlusionCullingPlane : m_occlusionCullingPlanes) { diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h index c54c816bfd..5319666745 100644 --- a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h @@ -58,7 +58,9 @@ namespace AZ // FeatureProcessor overrides void Activate() override; void Deactivate() override; - void Simulate(const FeatureProcessor::SimulatePacket& packet) override; + + // RPI::SceneNotificationBus overrides ... + void OnBeginPrepareRender() override; // retrieve the full list of occlusion planes using OcclusionCullingPlaneVector = AZStd::vector>; From 25dc42e298eefde477909f4ccd11e4cfd15667ec Mon Sep 17 00:00:00 2001 From: galibzon <66021303+galibzon@users.noreply.github.com> Date: Thu, 27 May 2021 21:45:19 -0500 Subject: [PATCH 278/811] [ATOM-15600] Fix cpu over usage when loading shader variant assets. (#1014) This is a temporary fix, in the future ShaderVariantAsyncLoader will use OnCatalogAssetRemoved()/ OnCatalogAssetAdded(). Signed-off-by: garrieta --- .../Source/RPI.Public/Shader/ShaderVariantAsyncLoader.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderVariantAsyncLoader.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderVariantAsyncLoader.cpp index 6579e6a98d..3fc2bbd197 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderVariantAsyncLoader.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderVariantAsyncLoader.cpp @@ -150,10 +150,7 @@ namespace AZ } } - if (!shaderVariantTreePendingRequests.empty() || !shaderVariantPendingRequests.empty()) - { - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(1000)); - } + AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(1000)); } } From 802943bbb3bf0553bfaf311608587ed295ff3866 Mon Sep 17 00:00:00 2001 From: karlberg Date: Thu, 27 May 2021 19:54:56 -0700 Subject: [PATCH 279/811] Bug fixes, naming changes to make variables more clear, and adds a cvar to adjust client window size --- Code/LauncherUnified/Launcher.cpp | 16 +++ .../Multiplayer/Components/NetBindComponent.h | 4 + .../Components/NetworkTransformComponent.h | 10 ++ .../EntityReplication/ReplicationRecord.h | 8 +- .../LocalPredictionPlayerInputComponent.cpp | 32 +++--- .../Source/Components/NetBindComponent.cpp | 10 ++ .../Components/NetworkTransformComponent.cpp | 48 ++++++--- .../Source/MultiplayerSystemComponent.cpp | 98 +++++++++++++++++-- .../Code/Source/MultiplayerSystemComponent.h | 4 + .../EntityReplicationManager.cpp | 2 +- .../EntityReplication/PropertyPublisher.cpp | 10 +- .../EntityReplication/ReplicationRecord.cpp | 26 ++--- 12 files changed, 210 insertions(+), 58 deletions(-) diff --git a/Code/LauncherUnified/Launcher.cpp b/Code/LauncherUnified/Launcher.cpp index 1f29478399..acb5cb9dba 100644 --- a/Code/LauncherUnified/Launcher.cpp +++ b/Code/LauncherUnified/Launcher.cpp @@ -9,6 +9,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ + #include #include @@ -22,6 +23,8 @@ #include #include #include +#include +#include #include @@ -45,6 +48,19 @@ extern "C" void CreateStaticModules(AZStd::vector& modulesOut); namespace { + void OnViewportResize(const AZ::Vector2& value); + + AZ_CVAR(AZ::Vector2, r_viewportSize, AZ::Vector2::CreateZero(), OnViewportResize, AZ::ConsoleFunctorFlags::DontReplicate, + "The default size for the launcher viewport, 0 0 means full screen"); + + void OnViewportResize(const AZ::Vector2& value) + { + AzFramework::NativeWindowHandle windowHandle = nullptr; + AzFramework::WindowSystemRequestBus::BroadcastResult(windowHandle, &AzFramework::WindowSystemRequestBus::Events::GetDefaultWindowHandle); + AzFramework::WindowSize newSize = AzFramework::WindowSize(aznumeric_cast(value.GetX()), aznumeric_cast(value.GetY())); + AzFramework::WindowRequestBus::Broadcast(&AzFramework::WindowRequestBus::Events::ResizeClientArea, newSize); + } + void ExecuteConsoleCommandFile(AzFramework::Application& application) { const AZStd::string_view customConCmdKey = "console-command-file"; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetBindComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetBindComponent.h index 4fe60f14a3..7d9b7d4086 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetBindComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetBindComponent.h @@ -39,6 +39,7 @@ namespace Multiplayer using EntityMigrationStartEvent = AZ::Event; using EntityMigrationEndEvent = AZ::Event<>; using EntityServerMigrationEvent = AZ::Event; + using EntityPreRenderEvent = AZ::Event; //! @class NetBindComponent //! @brief Component that provides net-binding to a networked entity. @@ -97,6 +98,7 @@ namespace Multiplayer void NotifyMigrationStart(ClientInputId migratedInputId); void NotifyMigrationEnd(); void NotifyServerMigration(HostId hostId, AzNetworking::ConnectionId connectionId); + void NotifyPreRender(float deltaTime, float blendFactor); void AddEntityStopEventHandler(EntityStopEvent::Handler& eventHandler); void AddEntityDirtiedEventHandler(EntityDirtiedEvent::Handler& eventHandler); @@ -104,6 +106,7 @@ namespace Multiplayer void AddEntityMigrationStartEventHandler(EntityMigrationStartEvent::Handler& eventHandler); void AddEntityMigrationEndEventHandler(EntityMigrationEndEvent::Handler& eventHandler); void AddEntityServerMigrationEventHandler(EntityServerMigrationEvent::Handler& eventHandler); + void AddEntityPreRenderEventHandler(EntityPreRenderEvent::Handler& eventHandler); bool SerializeEntityCorrection(AzNetworking::ISerializer& serializer); @@ -152,6 +155,7 @@ namespace Multiplayer EntityMigrationStartEvent m_entityMigrationStartEvent; EntityMigrationEndEvent m_entityMigrationEndEvent; EntityServerMigrationEvent m_entityServerMigrationEvent; + EntityPreRenderEvent m_entityPreRenderEvent; AZ::Event<> m_onRemove; RpcSendEvent::Handler m_handleLocalServerRpcMessageEventHandle; AZ::Event<>::Handler m_handleMarkedDirty; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h index 2a3b5fb3cc..0bf913a89a 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h @@ -13,6 +13,7 @@ #pragma once #include +#include #include namespace Multiplayer @@ -32,13 +33,22 @@ namespace Multiplayer void OnDeactivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; private: + void OnPreRender(float deltaTime, float blendFactor); + void OnRotationChangedEvent(const AZ::Quaternion& rotation); void OnTranslationChangedEvent(const AZ::Vector3& translation); void OnScaleChangedEvent(const AZ::Vector3& scale); + void OnResetCountChangedEvent(); + + AZ::Transform m_previousTransform = AZ::Transform::CreateIdentity(); + AZ::Transform m_targetTransform = AZ::Transform::CreateIdentity(); AZ::Event::Handler m_rotationEventHandler; AZ::Event::Handler m_translationEventHandler; AZ::Event::Handler m_scaleEventHandler; + AZ::Event::Handler m_resetCountEventHandler; + + EntityPreRenderEvent::Handler m_entityPreRenderEventHandler; }; class NetworkTransformComponentController diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/EntityReplication/ReplicationRecord.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/EntityReplication/ReplicationRecord.h index 3dfc4b8016..33e1e0bde6 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/EntityReplication/ReplicationRecord.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/EntityReplication/ReplicationRecord.h @@ -45,10 +45,10 @@ namespace Multiplayer static constexpr uint32_t MaxRecordBits = 2048; ReplicationRecord() = default; - ReplicationRecord(NetEntityRole netEntityRole); + ReplicationRecord(NetEntityRole remoteNetEntityRole); - void SetNetworkRole(NetEntityRole netEntityRole); - NetEntityRole GetNetworkRole() const; + void SetRemoteNetworkRole(NetEntityRole remoteNetEntityRole); + NetEntityRole GetRemoteNetworkRole() const; bool AreAllBitsConsumed() const; void ResetConsumedBits(); @@ -92,6 +92,6 @@ namespace Multiplayer // Sequence number this ReplicationRecord was sent on AzNetworking::PacketId m_sentPacketId = AzNetworking::InvalidPacketId; - NetEntityRole m_netEntityRole = NetEntityRole::InvalidRole;; + NetEntityRole m_remoteNetEntityRole = NetEntityRole::InvalidRole;; }; } diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp index 612601883c..99e19a89fd 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp @@ -25,6 +25,7 @@ namespace Multiplayer AZ_CVAR(AZ::TimeMs, cl_MaxRewindHistoryMs, AZ::TimeMs{ 2000 }, nullptr, AZ::ConsoleFunctorFlags::Null, "Maximum number of milliseconds to keep for server correction rewind and replay"); #ifndef AZ_RELEASE_BUILD AZ_CVAR(float, cl_DebugHackTimeMultiplier, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "Scalar value used to simulate clock hacking cheats for validating bank time system and anticheat"); + AZ_CVAR(bool, cl_EnableDesyncDebugging, true, nullptr, AZ::ConsoleFunctorFlags::Null, "If enabled, debug logs will contain verbose information on detected state desyncs"); #endif AZ_CVAR(bool, sv_EnableCorrections, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Enables server corrections on autonomous proxy desyncs"); @@ -214,11 +215,12 @@ namespace Multiplayer // Send correction SendClientInputCorrection(GetLastInputId(), correction); -#ifdef _DEBUG - // In debug, show which states caused the correction +#ifndef AZ_RELEASE_BUILD AZStd::string clientStateString; AZStd::string serverStateString; + if (cl_EnableDesyncDebugging) { + // In debug, show which states caused the correction // Write in client state AzNetworking::NetworkOutputSerializer clientStateSerializer(clientState.GetBuffer(), clientState.GetSize()); GetNetBindComponent()->SerializeEntityCorrection(clientStateSerializer); @@ -236,11 +238,13 @@ namespace Multiplayer GetNetBindComponent()->SerializeEntityCorrection(serverValues); AZStd::map> mapComparison; + // put the server value in the first part of the pair for (const auto& pair : serverValues.GetValueMap()) { mapComparison[pair.first].first = pair.second; } + // put the client value in the second part of the pair for (const auto& pair : clientValues.GetValueMap()) { @@ -266,12 +270,13 @@ namespace Multiplayer } } } -#else - const AZStd::string clientStateString = "available in debug only"; - const AZStd::string serverStateString = "available in debug only"; -#endif - + else + { + clientStateString = "available in debug only"; + serverStateString = "available in debug only"; + } AZLOG_ERROR("** Autonomous proxy desync detected! ** clientState=[%s], serverState=[%s]", clientStateString.c_str(), serverStateString.c_str()); +#endif } } } @@ -416,7 +421,7 @@ namespace Multiplayer ClientInputId LocalPredictionPlayerInputComponentController::GetLastInputId() const { - return m_clientInputId; + return m_lastClientInputId; } HostFrameId LocalPredictionPlayerInputComponentController::GetInputFrameId(const NetworkInput& input) const @@ -520,10 +525,13 @@ namespace Multiplayer // In debug, send the entire client output state to the server to make it easier to debug desync issues AzNetworking::PacketEncodingBuffer processInputResult; -#ifdef _DEBUG - AzNetworking::NetworkInputSerializer processInputResultSerializer(processInputResult.GetBuffer(), processInputResult.GetCapacity()); - GetNetBindComponent()->SerializeEntityCorrection(processInputResultSerializer); - processInputResult.Resize(processInputResultSerializer.GetSize()); +#ifndef AZ_RELEASE_BUILD + if (cl_EnableDesyncDebugging) + { + AzNetworking::NetworkInputSerializer processInputResultSerializer(processInputResult.GetBuffer(), processInputResult.GetCapacity()); + GetNetBindComponent()->SerializeEntityCorrection(processInputResultSerializer); + processInputResult.Resize(processInputResultSerializer.GetSize()); + } #endif // Save this input and discard move history outside our client rewind window diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp index d91bba2e0c..0847d42dd6 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp @@ -390,6 +390,11 @@ namespace Multiplayer m_entityServerMigrationEvent.Signal(m_netEntityHandle, hostId, connectionId); } + void NetBindComponent::NotifyPreRender(float deltaTime, float blendFactor) + { + m_entityPreRenderEvent.Signal(deltaTime, blendFactor); + } + void NetBindComponent::AddEntityStopEventHandler(EntityStopEvent::Handler& eventHandler) { eventHandler.Connect(m_entityStopEvent); @@ -420,6 +425,11 @@ namespace Multiplayer eventHandler.Connect(m_entityServerMigrationEvent); } + void NetBindComponent::AddEntityPreRenderEventHandler(EntityPreRenderEvent::Handler& eventHandler) + { + eventHandler.Connect(m_entityPreRenderEvent); + } + bool NetBindComponent::SerializeEntityCorrection(AzNetworking::ISerializer& serializer) { m_predictableRecord.ResetConsumedBits(); diff --git a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp index 0cc4cb131e..81b756de50 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp @@ -33,6 +33,8 @@ namespace Multiplayer : m_rotationEventHandler([this](const AZ::Quaternion& rotation) { OnRotationChangedEvent(rotation); }) , m_translationEventHandler([this](const AZ::Vector3& translation) { OnTranslationChangedEvent(translation); }) , m_scaleEventHandler([this](const AZ::Vector3& scale) { OnScaleChangedEvent(scale); }) + , m_resetCountEventHandler([this](const uint8_t&) { OnResetCountChangedEvent(); }) + , m_entityPreRenderEventHandler([this](float deltaTime, float blendFactor) { OnPreRender(deltaTime, blendFactor); }) { ; } @@ -47,6 +49,11 @@ namespace Multiplayer RotationAddEvent(m_rotationEventHandler); TranslationAddEvent(m_translationEventHandler); ScaleAddEvent(m_scaleEventHandler); + ResetCountAddEvent(m_resetCountEventHandler); + GetNetBindComponent()->AddEntityPreRenderEventHandler(m_entityPreRenderEventHandler); + + // When coming into relevance, reset all blending factors so we don't interpolate to our start position + OnResetCountChangedEvent(); } void NetworkTransformComponent::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) @@ -56,23 +63,37 @@ namespace Multiplayer void NetworkTransformComponent::OnRotationChangedEvent(const AZ::Quaternion& rotation) { - AZ::Transform worldTm = GetTransformComponent()->GetWorldTM(); - worldTm.SetRotation(rotation); - GetTransformComponent()->SetWorldTM(worldTm); + m_previousTransform.SetRotation(m_targetTransform.GetRotation()); + m_targetTransform.SetRotation(rotation); } void NetworkTransformComponent::OnTranslationChangedEvent(const AZ::Vector3& translation) { - AZ::Transform worldTm = GetTransformComponent()->GetWorldTM(); - worldTm.SetTranslation(translation); - GetTransformComponent()->SetWorldTM(worldTm); + m_previousTransform.SetTranslation(m_targetTransform.GetTranslation()); + m_targetTransform.SetTranslation(translation); } void NetworkTransformComponent::OnScaleChangedEvent(const AZ::Vector3& scale) { - AZ::Transform worldTm = GetTransformComponent()->GetWorldTM(); - worldTm.SetScale(scale); - GetTransformComponent()->SetWorldTM(worldTm); + m_previousTransform.SetScale(m_targetTransform.GetScale()); + m_targetTransform.SetScale(scale); + } + + void NetworkTransformComponent::OnResetCountChangedEvent() + { + m_previousTransform = m_targetTransform; + } + + void NetworkTransformComponent::OnPreRender([[maybe_unused]] float deltaTime, float blendFactor) + { + if (!HasController()) + { + AZ::Transform blendTransform; + blendTransform.SetRotation(m_previousTransform.GetRotation().Slerp(m_targetTransform.GetRotation(), blendFactor)); + blendTransform.SetTranslation(m_previousTransform.GetTranslation().Lerp(m_targetTransform.GetTranslation(), blendFactor)); + blendTransform.SetScale(m_previousTransform.GetScale().Lerp(m_targetTransform.GetScale(), blendFactor)); + GetTransformComponent()->SetWorldTM(blendTransform); + } } @@ -96,11 +117,8 @@ namespace Multiplayer void NetworkTransformComponentController::OnTransformChangedEvent(const AZ::Transform& worldTm) { - if (IsAuthority()) - { - SetRotation(worldTm.GetRotation()); - SetTranslation(worldTm.GetTranslation()); - SetScale(worldTm.GetScale()); - } + SetRotation(worldTm.GetRotation()); + SetTranslation(worldTm.GetTranslation()); + SetScale(worldTm.GetScale()); } } diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index ef8627fe54..485a3719ad 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -12,7 +12,6 @@ #include #include - #include #include #include @@ -24,12 +23,19 @@ #include #include #include +#include #include #include +#include #include #include #include + +#include +#include +#include #include + #include namespace AZ::ConsoleTypeHelpers @@ -74,6 +80,7 @@ namespace Multiplayer AZ_CVAR(ProtocolType, sv_protocol, ProtocolType::Udp, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "This flag controls whether we use TCP or UDP for game networking"); AZ_CVAR(bool, sv_isDedicated, true, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Whether the host command creates an independent or client hosted server"); AZ_CVAR(AZ::TimeMs, cl_defaultNetworkEntityActivationTimeSliceMs, AZ::TimeMs{ 0 }, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Max Ms to use to activate entities coming from the network, 0 means instantiate everything"); + AZ_CVAR(AZ::TimeMs, sv_serverSendRateMs, AZ::TimeMs{ 50 }, nullptr, AZ::ConsoleFunctorFlags::Null, "Minimum number of milliseconds between each network update"); AZ_CVAR(AZ::CVarFixedString, sv_defaultPlayerSpawnAsset, "prefabs/player.network.spawnable", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The default spawnable to use when a new player connects"); void MultiplayerSystemComponent::Reflect(AZ::ReflectContext* context) @@ -156,10 +163,26 @@ namespace Multiplayer AZ::TickBus::Handler::BusDisconnect(); } - void MultiplayerSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) + void MultiplayerSystemComponent::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - AZ::TimeMs deltaTimeMs = aznumeric_cast(static_cast(deltaTime * 1000.0f)); - AZ::TimeMs hostTimeMs = AZ::GetElapsedTimeMs(); + const AZ::TimeMs deltaTimeMs = aznumeric_cast(static_cast(deltaTime * 1000.0f)); + const AZ::TimeMs hostTimeMs = AZ::GetElapsedTimeMs(); + const AZ::TimeMs serverRateMs = static_cast(sv_serverSendRateMs); + const float serverRateSeconds = static_cast(serverRateMs) / 1000.0f; + + TickVisibleNetworkEntities(deltaTime, serverRateSeconds); + + if (GetAgentType() == MultiplayerAgentType::ClientServer + || GetAgentType() == MultiplayerAgentType::DedicatedServer) + { + m_serverSendAccumulator += deltaTime; + if (m_serverSendAccumulator < serverRateSeconds) + { + return; + } + m_serverSendAccumulator -= serverRateSeconds; + m_networkTime.IncrementHostFrameId(); + } // Handle deferred local rpc messages that were generated during the updates m_networkEntityManager.DispatchLocalDeferredRpcMessages(); @@ -365,13 +388,21 @@ namespace Multiplayer } EntityReplicationManager& replicationManager = reinterpret_cast(connection->GetUserData())->GetReplicationManager(); - - // Ignore a_Request.GetServerGameTimePoint(), clients can't affect the server gametime + + if ((GetAgentType() == MultiplayerAgentType::Client) && (packet.GetHostFrameId() > m_lastReplicatedHostFrameId)) + { + // Update client to latest server time + m_renderBlendFactor = 0.0f; + m_lastReplicatedHostTimeMs = packet.GetHostTimeMs(); + m_lastReplicatedHostFrameId = packet.GetHostFrameId(); + m_networkTime.AlterTime(m_lastReplicatedHostFrameId, m_lastReplicatedHostTimeMs, AzNetworking::InvalidConnectionId); + } + for (AZStd::size_t i = 0; i < packet.GetEntityMessages().size(); ++i) { const NetworkEntityUpdateMessage& updateMessage = packet.GetEntityMessages()[i]; handledAll &= replicationManager.HandleEntityUpdateMessage(connection, packetHeader, updateMessage); - AZ_Assert(handledAll, "GameServerToClientNetworkRequestHandler EntityUpdates Did not handle all updates"); + AZ_Assert(handledAll, "EntityUpdates did not handle all update messages"); } return handledAll; @@ -439,7 +470,7 @@ namespace Multiplayer } if (GetAgentType() == MultiplayerAgentType::ClientServer - || GetAgentType() == MultiplayerAgentType::DedicatedServer) + || GetAgentType() == MultiplayerAgentType::DedicatedServer) { PrefabEntityId playerPrefabEntityId(AZ::Name(static_cast(sv_defaultPlayerSpawnAsset).c_str()), 1); INetworkEntityManager::EntityList entityList = m_networkEntityManager.CreateEntitiesImmediate(playerPrefabEntityId, NetEntityRole::Authority, AZ::Transform::CreateIdentity()); @@ -594,6 +625,57 @@ namespace Multiplayer AZLOG_INFO("Total RPCs received bytes: %llu", aznumeric_cast(rpcsRecv.m_totalBytes)); } + void MultiplayerSystemComponent::TickVisibleNetworkEntities(float deltaTime, float serverRateSeconds) + { + const float targetAdjustBlend = AZStd::clamp(deltaTime / serverRateSeconds, 0.0f, 1.0f); + m_renderBlendFactor += targetAdjustBlend; + + // Linear close to the origin, but asymptote at y = 1 + const float adjustedBlendFactor = 1.0f - (std::powf(0.2f, m_renderBlendFactor)); + AZLOG(NET_Blending, "Computed blend factor of %f", adjustedBlendFactor); + + AZ::Transform activeCameraTransform; + Camera::Configuration activeCameraConfiguration; + Camera::ActiveCameraRequestBus::BroadcastResult(activeCameraTransform, &Camera::ActiveCameraRequestBus::Events::GetActiveCameraTransform); + Camera::ActiveCameraRequestBus::BroadcastResult(activeCameraConfiguration, &Camera::ActiveCameraRequestBus::Events::GetActiveCameraConfiguration); + + const AZ::ViewFrustumAttributes frustumAttributes + ( + activeCameraTransform, + activeCameraConfiguration.m_frustumHeight / activeCameraConfiguration.m_frustumWidth, + activeCameraConfiguration.m_fovRadians, + activeCameraConfiguration.m_nearClipDistance, + activeCameraConfiguration.m_farClipDistance + ); + const AZ::Frustum viewFrustum = AZ::Frustum(frustumAttributes); + + // Unfortunately necessary, as NotifyPreRender can update transforms and thus cause a deadlock inside the vis system + AZStd::vector gatheredEntities; + AzFramework::IEntityBoundsUnion* entityBoundsUnion = AZ::Interface::Get(); + AZ::Interface::Get()->GetDefaultVisibilityScene()->Enumerate(viewFrustum, + [&gatheredEntities, entityBoundsUnion](const AzFramework::IVisibilityScene::NodeData& nodeData) + { + gatheredEntities.reserve(gatheredEntities.size() + nodeData.m_entries.size()); + for (AzFramework::VisibilityEntry* visEntry : nodeData.m_entries) + { + if (visEntry->m_typeFlags & AzFramework::VisibilityEntry::TypeFlags::TYPE_Entity) + { + AZ::Entity* entity = static_cast(visEntry->m_userData); + NetBindComponent* netBindComponent = entity->template FindComponent(); + if (netBindComponent != nullptr) + { + gatheredEntities.push_back(netBindComponent); + } + } + } + }); + + for (NetBindComponent* netBindComponent : gatheredEntities) + { + netBindComponent->NotifyPreRender(deltaTime, adjustedBlendFactor); + } + } + void MultiplayerSystemComponent::OnConsoleCommandInvoked ( AZStd::string_view command, diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index db83c50fb5..a38bb935a2 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -102,6 +102,7 @@ namespace Multiplayer private: + void TickVisibleNetworkEntities(float deltaTime, float serverRateSeconds); void OnConsoleCommandInvoked(AZStd::string_view command, const AZ::ConsoleCommandContainer& args, AZ::ConsoleFunctorFlags flags, AZ::ConsoleInvokedFrom invokedFrom); void ExecuteConsoleCommandList(AzNetworking::IConnection* connection, const AZStd::fixed_vector& commands); @@ -123,6 +124,9 @@ namespace Multiplayer AZ::TimeMs m_lastReplicatedHostTimeMs = AZ::TimeMs{ 0 }; HostFrameId m_lastReplicatedHostFrameId = InvalidHostFrameId; + double m_serverSendAccumulator = 0.0; + float m_renderBlendFactor = 0.0f; + #if !defined(AZ_RELEASE_BUILD) MultiplayerEditorConnection m_editorConnectionListener; #endif diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index bd30c5e37f..5d0284dfb2 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -132,7 +132,7 @@ namespace Multiplayer EntityReplicatorList replicatorUpdatedList; MultiplayerPackets::EntityUpdates entityUpdatePacket; entityUpdatePacket.SetHostTimeMs(hostTimeMs); - entityUpdatePacket.SetHostFrameId(InvalidHostFrameId); + entityUpdatePacket.SetHostFrameId(GetNetworkTime()->GetHostFrameId()); // Serialize everything while (!toSendList.empty()) { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.cpp index dfa324f76b..8af636870b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.cpp @@ -27,7 +27,7 @@ namespace Multiplayer , m_sentRecords(net_EntityReplicatorRecordsMax) { AZ_Assert(m_netBindComponent, "NetBindComponent is nullptr"); - m_pendingRecord.SetNetworkRole(remoteNetworkRole); + m_pendingRecord.SetRemoteNetworkRole(remoteNetworkRole); } bool PropertyPublisher::IsDeleting() const @@ -67,7 +67,7 @@ namespace Multiplayer void PropertyPublisher::SetRebasing() { - AZ_Assert(m_pendingRecord.GetNetworkRole() == NetEntityRole::Autonomous, "Expected to be rebasing on a Autonomous entity"); + AZ_Assert(m_pendingRecord.GetRemoteNetworkRole() == NetEntityRole::Autonomous, "Expected to be rebasing on a Autonomous entity"); m_replicatorState = EntityReplicatorState::Rebasing; } @@ -118,7 +118,7 @@ namespace Multiplayer m_sentRecords.clear(); m_netBindComponent->FillTotalReplicationRecord(m_pendingRecord); // Don't send predictable properties back to the Autonomous unless we correct them - if (m_pendingRecord.GetNetworkRole() == NetEntityRole::Autonomous) + if (m_pendingRecord.GetRemoteNetworkRole() == NetEntityRole::Autonomous) { m_pendingRecord.Subtract(m_netBindComponent->GetPredictableRecord()); } @@ -137,7 +137,7 @@ namespace Multiplayer // We need to clear out old records, and build up a list of everything that has changed since the last acked packet m_sentRecords.push_front(m_pendingRecord); auto iter = m_sentRecords.begin(); - ++iter; // consider everything after the record we are going to send + ++iter; // Consider everything after the record we are going to send for (; iter != m_sentRecords.end(); ++iter) { // Sequence wasn't acked, so we need to send these bits again @@ -145,7 +145,7 @@ namespace Multiplayer } // Don't send predictable properties back to the Autonomous unless we correct them - if (m_pendingRecord.GetNetworkRole() == NetEntityRole::Autonomous) + if (m_pendingRecord.GetRemoteNetworkRole() == NetEntityRole::Autonomous) { m_pendingRecord.Subtract(m_netBindComponent->GetPredictableRecord()); } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp index 7fe0efd323..47360bfba6 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp @@ -49,19 +49,19 @@ namespace Multiplayer } ReplicationRecord::ReplicationRecord(NetEntityRole netEntityRole) - : m_netEntityRole(netEntityRole) + : m_remoteNetEntityRole(netEntityRole) { ; } - void ReplicationRecord::SetNetworkRole(NetEntityRole netEntityRole) + void ReplicationRecord::SetRemoteNetworkRole(NetEntityRole remoteNetEntityRole) { - m_netEntityRole = netEntityRole; + m_remoteNetEntityRole = remoteNetEntityRole; } - NetEntityRole ReplicationRecord::GetNetworkRole() const + NetEntityRole ReplicationRecord::GetRemoteNetworkRole() const { - return m_netEntityRole; + return m_remoteNetEntityRole; } bool ReplicationRecord::AreAllBitsConsumed() const @@ -196,26 +196,26 @@ namespace Multiplayer bool ReplicationRecord::ContainsAuthorityToClientBits() const { - return (m_netEntityRole != NetEntityRole::Authority) - || (m_netEntityRole == NetEntityRole::InvalidRole); + return (m_remoteNetEntityRole != NetEntityRole::Authority) + || (m_remoteNetEntityRole == NetEntityRole::InvalidRole); } bool ReplicationRecord::ContainsAuthorityToServerBits() const { - return (m_netEntityRole == NetEntityRole::Server) - || (m_netEntityRole == NetEntityRole::InvalidRole); + return (m_remoteNetEntityRole == NetEntityRole::Server) + || (m_remoteNetEntityRole == NetEntityRole::InvalidRole); } bool ReplicationRecord::ContainsAuthorityToAutonomousBits() const { - return (m_netEntityRole == NetEntityRole::Autonomous || m_netEntityRole == NetEntityRole::Server) - || (m_netEntityRole == NetEntityRole::InvalidRole); + return (m_remoteNetEntityRole == NetEntityRole::Autonomous || m_remoteNetEntityRole == NetEntityRole::Server) + || (m_remoteNetEntityRole == NetEntityRole::InvalidRole); } bool ReplicationRecord::ContainsAutonomousToAuthorityBits() const { - return (m_netEntityRole == NetEntityRole::Authority) - || (m_netEntityRole == NetEntityRole::InvalidRole); + return (m_remoteNetEntityRole == NetEntityRole::Authority) + || (m_remoteNetEntityRole == NetEntityRole::InvalidRole); } uint32_t ReplicationRecord::GetRemainingAuthorityToClientBits() const From 69e79867be5f87132c43c89f8ca081d543498242 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 27 May 2021 20:12:48 -0700 Subject: [PATCH 280/811] Making imported targets global, fixing identiation of the enabled_gems.cmake file --- AutomatedTesting/Gem/Code/enabled_gems.cmake | 2 +- cmake/Gems.cmake | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/AutomatedTesting/Gem/Code/enabled_gems.cmake b/AutomatedTesting/Gem/Code/enabled_gems.cmake index 32fdd11415..2ea800bae6 100644 --- a/AutomatedTesting/Gem/Code/enabled_gems.cmake +++ b/AutomatedTesting/Gem/Code/enabled_gems.cmake @@ -54,4 +54,4 @@ set(ENABLED_GEMS AWSCore AWSClientAuth AWSMetrics - ) +) diff --git a/cmake/Gems.cmake b/cmake/Gems.cmake index a90cf09639..d418d5dcd1 100644 --- a/cmake/Gems.cmake +++ b/cmake/Gems.cmake @@ -63,13 +63,17 @@ function(ly_create_alias) "This could be a copy-paste error, where some part of the ly_create_alias call was changed but the other") endif() - add_library(${ly_create_alias_NAME} INTERFACE IMPORTED) + add_library(${ly_create_alias_NAME} INTERFACE IMPORTED GLOBAL) set_target_properties(${ly_create_alias_NAME} PROPERTIES GEM_MODULE TRUE) foreach(target_name ${ly_create_alias_TARGETS}) - ly_de_alias_target(${target_name} de_aliased_target_name) - if(NOT de_aliased_target_name) - message(FATAL_ERROR "Target not found in ly_create_alias call: ${target_name} - check your spelling of the target name") + if(TARGET ${target_name}) + ly_de_alias_target(${target_name} de_aliased_target_name) + if(NOT de_aliased_target_name) + message(FATAL_ERROR "Target not found in ly_create_alias call: ${target_name} - check your spelling of the target name") + endif() + else() + set(de_aliased_target_name ${target_name}) endif() list(APPEND final_targets ${de_aliased_target_name}) endforeach() From 051384e9a74dcdb795eb1412561528f82f58757d Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Thu, 27 May 2021 20:13:45 -0700 Subject: [PATCH 281/811] Remove AZ_TRAIT_DISABLE_ASSET_JOB_PARALLEL_TESTS from Linux traits (#1018) --- .../Framework/AzTest/AzTest/Platform/Linux/AzTest_Traits_Linux.h | 1 - 1 file changed, 1 deletion(-) diff --git a/Code/Framework/AzTest/AzTest/Platform/Linux/AzTest_Traits_Linux.h b/Code/Framework/AzTest/AzTest/Platform/Linux/AzTest_Traits_Linux.h index 0090ce066b..855b4fe416 100644 --- a/Code/Framework/AzTest/AzTest/Platform/Linux/AzTest_Traits_Linux.h +++ b/Code/Framework/AzTest/AzTest/Platform/Linux/AzTest_Traits_Linux.h @@ -39,4 +39,3 @@ #define AZ_TRAIT_DISABLE_FAILED_EMOTION_FX_EDITOR_TESTS true #define AZ_TRAIT_DISABLE_FAILED_METRICS_TESTS true -#define AZ_TRAIT_DISABLE_ASSET_JOB_PARALLEL_TESTS true From 23a5afeefb72854df46f7b861c12f07fcfba5d1d Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 27 May 2021 23:47:51 -0500 Subject: [PATCH 282/811] Renaming the unit_global_project.py to unit_test_global_project.py. This fixes the unit test not being found --- .../tests/{unit_global_project.py => unit_test_global_project.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename scripts/o3de/tests/{unit_global_project.py => unit_test_global_project.py} (100%) diff --git a/scripts/o3de/tests/unit_global_project.py b/scripts/o3de/tests/unit_test_global_project.py similarity index 100% rename from scripts/o3de/tests/unit_global_project.py rename to scripts/o3de/tests/unit_test_global_project.py From 0f258954fbd8a0bd2279b4a29369dc0667c3f2bf Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Thu, 27 May 2021 22:29:40 -0700 Subject: [PATCH 283/811] Fix for unit test. Checking that AssetManager is ready before spawning entities; MultiplayerSystemComponent will attempt to spawn a default player on init(), but during unit tests the AssetManager isn't stood up --- .../Code/Source/NetworkEntity/NetworkEntityManager.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index dda3f18ad4..eaf89f3489 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -402,8 +402,12 @@ namespace Multiplayer const AZ::Transform& transform ) { - INetworkEntityManager::EntityList returnList; - + EntityList returnList; + if (!AZ::Data::AssetManager::IsReady()) + { + return returnList; + } + auto spawnableAssetId = m_networkPrefabLibrary.GetAssetIdByName(prefabEntryId.m_prefabName); // Required for sync-instantiation. Todo: keep the reference in NetworkSpawnableLibrary auto netSpawnableAsset = AZ::Data::AssetManager::Instance().GetAsset(spawnableAssetId, AZ::Data::AssetLoadBehavior::PreLoad); From 5bb55ac1c7723512d24ce610ebb0ead2554ee99c Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Fri, 28 May 2021 07:38:05 +0200 Subject: [PATCH 284/811] [LYN-2514] Optimizing for new window dimensions (#990) --- .../Resources/ProjectManager.qss | 29 ++++++++++++++++++- .../GemCatalog/GemCatalogHeaderWidget.cpp | 8 +++-- .../Source/GemCatalog/GemFilterWidget.cpp | 13 +++++---- .../Source/GemCatalog/GemInspector.cpp | 17 ++++++----- .../Source/GemCatalog/GemItemDelegate.cpp | 14 ++++----- .../Source/GemCatalog/GemItemDelegate.h | 26 ++++++++--------- .../Source/GemCatalog/GemListHeaderWidget.cpp | 11 +++---- .../ProjectManager/Source/LinkWidget.cpp | 4 +-- .../Tools/ProjectManager/Source/TagWidget.cpp | 6 ++-- 9 files changed, 80 insertions(+), 48 deletions(-) diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qss b/Code/Tools/ProjectManager/Resources/ProjectManager.qss index 5eb92964dd..a85b911c15 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qss +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qss @@ -336,4 +336,31 @@ QTabBar::tab:pressed max-width:210px;; min-height:278px; max-height:278px; -} \ No newline at end of file +} + +/************** Gem Catalog **************/ + +#GemCatalogTitle { + font-size: 18px; +} + +/************** Gem Catalog (Inspector) **************/ + +#GemCatalogInspector { + background-color: #444444; +} + +/************** Gem Catalog (Filter/left pane) **************/ + +#GemCatalogFilterWidget { + background-color: #444444; +} + +#GemCatalogHeaderWidget { + background-color: #1E252F; +} + +#GemCatalogFilterCategoryTitle { + font-size: 12px; + font-weight: 600; +} diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp index 6e9ad42017..6402121e4a 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp @@ -25,10 +25,12 @@ namespace O3DE::ProjectManager hLayout->setMargin(0); setLayout(hLayout); - setStyleSheet("background-color: #1E252F;"); + setObjectName("GemCatalogHeaderWidget"); + + hLayout->addSpacing(7); QLabel* titleLabel = new QLabel(tr("Gem Catalog")); - titleLabel->setStyleSheet("font-size: 21px;"); + titleLabel->setObjectName("GemCatalogTitle"); hLayout->addWidget(titleLabel); hLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding)); @@ -42,7 +44,7 @@ namespace O3DE::ProjectManager hLayout->addWidget(filterLineEdit); hLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding)); - hLayout->addSpacerItem(new QSpacerItem(220, 0, QSizePolicy::Fixed)); + hLayout->addSpacerItem(new QSpacerItem(140, 0, QSizePolicy::Fixed)); setFixedHeight(60); } diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemFilterWidget.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemFilterWidget.cpp index 3ece7760cf..a6a4e95ff9 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemFilterWidget.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemFilterWidget.cpp @@ -43,7 +43,6 @@ namespace O3DE::ProjectManager m_collapseButton->setFlat(true); m_collapseButton->setFocusPolicy(Qt::NoFocus); m_collapseButton->setFixedWidth(s_collapseButtonSize); - m_collapseButton->setStyleSheet("border: 0px; border-radius: 0px;"); connect(m_collapseButton, &QPushButton::clicked, this, [=]() { UpdateCollapseState(); @@ -52,7 +51,7 @@ namespace O3DE::ProjectManager // Category title QLabel* headerLabel = new QLabel(header); - headerLabel->setStyleSheet("font-size: 11pt;"); + headerLabel->setObjectName("GemCatalogFilterCategoryTitle"); collapseLayout->addWidget(headerLabel); vLayout->addLayout(collapseLayout); @@ -79,14 +78,14 @@ namespace O3DE::ProjectManager elementWidget->setLayout(elementLayout); QCheckBox* checkbox = new QCheckBox(elementNames[i]); - checkbox->setStyleSheet("font-size: 11pt;"); + checkbox->setStyleSheet("font-size: 12px;"); m_buttonGroup->addButton(checkbox); elementLayout->addWidget(checkbox); elementLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding)); QLabel* countLabel = new QLabel(QString::number(elementCounts[i])); - countLabel->setStyleSheet("font-size: 11pt; background-color: #333333; border-radius: 3px; color: #94D2FF;"); + countLabel->setStyleSheet("font-size: 12px; background-color: #333333; border-radius: 3px; color: #94D2FF;"); elementLayout->addWidget(countLabel); m_elementWidgets.push_back(elementWidget); @@ -110,6 +109,8 @@ namespace O3DE::ProjectManager } } + vLayout->addSpacing(5); + // Separating line QFrame* hLine = new QFrame(); hLine->setFrameShape(QFrame::HLine); @@ -181,6 +182,8 @@ namespace O3DE::ProjectManager : QScrollArea(parent) , m_filterProxyModel(filterProxyModel) { + setObjectName("GemCatalogFilterWidget"); + m_gemModel = m_filterProxyModel->GetSourceModel(); setWidgetResizable(true); @@ -195,7 +198,7 @@ namespace O3DE::ProjectManager mainWidget->setLayout(m_mainLayout); QLabel* filterByLabel = new QLabel("Filter by"); - filterByLabel->setStyleSheet("font-size: 15pt;"); + filterByLabel->setStyleSheet("font-size: 16px;"); m_mainLayout->addWidget(filterByLabel); AddGemOriginFilter(); diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp index 6276ddc996..3ecc18231e 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp @@ -23,6 +23,7 @@ namespace O3DE::ProjectManager : QScrollArea(parent) , m_model(model) { + setObjectName("GemCatalogInspector"); setWidgetResizable(true); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); @@ -85,7 +86,7 @@ namespace O3DE::ProjectManager QLabel* GemInspector::CreateStyledLabel(QLayout* layout, int fontSize, const QString& colorCodeString) { QLabel* result = new QLabel(); - result->setStyleSheet(QString("font-size: %1pt; color: %2;").arg(QString::number(fontSize), colorCodeString)); + result->setStyleSheet(QString("font-size: %1px; color: %2;").arg(QString::number(fontSize), colorCodeString)); layout->addWidget(result); return result; } @@ -93,13 +94,13 @@ namespace O3DE::ProjectManager void GemInspector::InitMainWidget() { // Gem name, creator and summary - m_nameLabel = CreateStyledLabel(m_mainLayout, 17, s_headerColor); + m_nameLabel = CreateStyledLabel(m_mainLayout, 18, s_headerColor); m_creatorLabel = CreateStyledLabel(m_mainLayout, 12, s_creatorColor); m_mainLayout->addSpacing(5); // TODO: QLabel seems to have issues determining the right sizeHint() for our font with the given font size. // This results into squeezed elements in the layout in case the text is a little longer than a sentence. - m_summaryLabel = new QLabel();//CreateLabel(m_mainLayout, 12, s_textColor); + m_summaryLabel = CreateStyledLabel(m_mainLayout, 12, s_textColor); m_mainLayout->addWidget(m_summaryLabel); m_summaryLabel->setWordWrap(true); m_mainLayout->addSpacing(5); @@ -146,9 +147,9 @@ namespace O3DE::ProjectManager QLabel* additionalInfoLabel = CreateStyledLabel(m_mainLayout, 14, s_headerColor); additionalInfoLabel->setText("Additional Information"); - m_versionLabel = CreateStyledLabel(m_mainLayout, 11, s_textColor); - m_lastUpdatedLabel = CreateStyledLabel(m_mainLayout, 11, s_textColor); - m_binarySizeLabel = CreateStyledLabel(m_mainLayout, 11, s_textColor); + m_versionLabel = CreateStyledLabel(m_mainLayout, 12, s_textColor); + m_lastUpdatedLabel = CreateStyledLabel(m_mainLayout, 12, s_textColor); + m_binarySizeLabel = CreateStyledLabel(m_mainLayout, 12, s_textColor); } GemInspector::GemsSubWidget::GemsSubWidget(QWidget* parent) @@ -159,8 +160,8 @@ namespace O3DE::ProjectManager m_layout->setMargin(0); setLayout(m_layout); - m_titleLabel = GemInspector::CreateStyledLabel(m_layout, 15, s_headerColor); - m_textLabel = GemInspector::CreateStyledLabel(m_layout, 9, s_textColor); + m_titleLabel = GemInspector::CreateStyledLabel(m_layout, 16, s_headerColor); + m_textLabel = GemInspector::CreateStyledLabel(m_layout, 10, s_textColor); m_textLabel->setWordWrap(true); m_tagWidget = new TagContainerWidget(); diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp index a40e5eb447..57200e3b36 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp @@ -49,7 +49,7 @@ namespace O3DE::ProjectManager painter->setRenderHint(QPainter::Antialiasing); QRect fullRect, itemRect, contentRect; - CalcRects(options, modelIndex, fullRect, itemRect, contentRect); + CalcRects(options, fullRect, itemRect, contentRect); QFont standardFont(options.font); standardFont.setPixelSize(s_fontSize); @@ -99,7 +99,7 @@ namespace O3DE::ProjectManager painter->drawText(gemCreatorRect, Qt::TextSingleLine, gemCreator); // Gem summary - const QSize summarySize = QSize(contentRect.width() - s_summaryStartX - s_buttonWidth - s_itemMargins.right() * 4, contentRect.height()); + const QSize summarySize = QSize(contentRect.width() - s_summaryStartX - s_buttonWidth - s_itemMargins.right() * 3, contentRect.height()); const QRect summaryRect = QRect(/*topLeft=*/QPoint(contentRect.left() + s_summaryStartX, contentRect.top()), summarySize); painter->setFont(standardFont); @@ -134,12 +134,10 @@ namespace O3DE::ProjectManager return QStyledItemDelegate::editorEvent(event, model, option, modelIndex); } - void GemItemDelegate::CalcRects(const QStyleOptionViewItem& option, const QModelIndex& modelIndex, QRect& outFullRect, QRect& outItemRect, QRect& outContentRect) const + void GemItemDelegate::CalcRects(const QStyleOptionViewItem& option, QRect& outFullRect, QRect& outItemRect, QRect& outContentRect) const { - const bool isFirst = modelIndex.row() == 0; - outFullRect = QRect(option.rect); - outItemRect = QRect(outFullRect.adjusted(s_itemMargins.left(), isFirst ? s_itemMargins.top() * 2 : s_itemMargins.top(), -s_itemMargins.right(), -s_itemMargins.bottom())); + outItemRect = QRect(outFullRect.adjusted(s_itemMargins.left(), s_itemMargins.top(), -s_itemMargins.right(), -s_itemMargins.bottom())); outContentRect = QRect(outItemRect.adjusted(s_contentMargins.left(), s_contentMargins.top(), -s_contentMargins.right(), -s_contentMargins.bottom())); } @@ -194,12 +192,12 @@ namespace O3DE::ProjectManager painter->setBrush(m_buttonEnabledColor); painter->setPen(m_buttonEnabledColor); - circleCenter = buttonRect.center() + QPoint(buttonRect.width() / 2 - s_buttonBorderRadius, 1); + circleCenter = buttonRect.center() + QPoint(buttonRect.width() / 2 - s_buttonBorderRadius + 1, 1); buttonText = "Added"; } else { - circleCenter = buttonRect.center() + QPoint(-buttonRect.width() / 2 + s_buttonBorderRadius + 1, 1); + circleCenter = buttonRect.center() + QPoint(-buttonRect.width() / 2 + s_buttonBorderRadius, 1); buttonText = "Get"; } diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.h index d43b5d15f6..48f173ec3f 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.h @@ -45,25 +45,25 @@ namespace O3DE::ProjectManager const QColor m_buttonEnabledColor = QColor("#00B931"); // Item - inline constexpr static int s_height = 135; // Gem item total height - inline constexpr static qreal s_gemNameFontSize = 16.0; - inline constexpr static qreal s_fontSize = 15.0; - inline constexpr static int s_summaryStartX = 200; + inline constexpr static int s_height = 105; // Gem item total height + inline constexpr static qreal s_gemNameFontSize = 13.0; + inline constexpr static qreal s_fontSize = 12.0; + inline constexpr static int s_summaryStartX = 150; // Margin and borders - inline constexpr static QMargins s_itemMargins = QMargins(/*left=*/20, /*top=*/10, /*right=*/20, /*bottom=*/10); // Item border distances - inline constexpr static QMargins s_contentMargins = QMargins(/*left=*/15, /*top=*/12, /*right=*/12, /*bottom=*/12); // Distances of the elements within an item to the item borders + inline constexpr static QMargins s_itemMargins = QMargins(/*left=*/16, /*top=*/8, /*right=*/16, /*bottom=*/8); // Item border distances + inline constexpr static QMargins s_contentMargins = QMargins(/*left=*/20, /*top=*/12, /*right=*/15, /*bottom=*/12); // Distances of the elements within an item to the item borders inline constexpr static int s_borderWidth = 4; // Button - inline constexpr static int s_buttonWidth = 70; - inline constexpr static int s_buttonHeight = 24; - inline constexpr static int s_buttonBorderRadius = 12; - inline constexpr static int s_buttonCircleRadius = s_buttonBorderRadius - 3; - inline constexpr static qreal s_buttonFontSize = 12.0; + inline constexpr static int s_buttonWidth = 55; + inline constexpr static int s_buttonHeight = 18; + inline constexpr static int s_buttonBorderRadius = 9; + inline constexpr static int s_buttonCircleRadius = s_buttonBorderRadius - 2; + inline constexpr static qreal s_buttonFontSize = 10.0; private: - void CalcRects(const QStyleOptionViewItem& option, const QModelIndex& modelIndex, QRect& outFullRect, QRect& outItemRect, QRect& outContentRect) const; + void CalcRects(const QStyleOptionViewItem& option, QRect& outFullRect, QRect& outItemRect, QRect& outContentRect) const; QRect GetTextRect(QFont& font, const QString& text, qreal fontSize) const; QRect CalcButtonRect(const QRect& contentRect) const; void DrawPlatformIcons(QPainter* painter, const QRect& contentRect, const QModelIndex& modelIndex) const; @@ -73,7 +73,7 @@ namespace O3DE::ProjectManager // Platform icons void AddPlatformIcon(GemInfo::Platform platform, const QString& iconPath); - inline constexpr static int s_platformIconSize = 16; + inline constexpr static int s_platformIconSize = 12; QHash m_platformIcons; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemListHeaderWidget.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemListHeaderWidget.cpp index 128fb93345..bc287e3c61 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemListHeaderWidget.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemListHeaderWidget.cpp @@ -35,7 +35,7 @@ namespace O3DE::ProjectManager topLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding)); QLabel* showCountLabel = new QLabel(); - showCountLabel->setStyleSheet("font-size: 11pt; font: italic;"); + showCountLabel->setStyleSheet("font-size: 12px; font: italic;"); topLayout->addWidget(showCountLabel); connect(proxyModel, &GemSortFilterProxyModel::OnInvalidated, this, [=] { @@ -61,16 +61,17 @@ namespace O3DE::ProjectManager QHBoxLayout* columnHeaderLayout = new QHBoxLayout(); columnHeaderLayout->setAlignment(Qt::AlignLeft); - columnHeaderLayout->addSpacing(31); + const int gemNameStartX = GemItemDelegate::s_itemMargins.left() + GemItemDelegate::s_contentMargins.left() - 3; + columnHeaderLayout->addSpacing(gemNameStartX); QLabel* gemNameLabel = new QLabel(tr("Gem Name")); - gemNameLabel->setStyleSheet("font-size: 11pt;"); + gemNameLabel->setStyleSheet("font-size: 12px;"); columnHeaderLayout->addWidget(gemNameLabel); - columnHeaderLayout->addSpacing(111); + columnHeaderLayout->addSpacing(77); QLabel* gemSummaryLabel = new QLabel(tr("Gem Summary")); - gemSummaryLabel->setStyleSheet("font-size: 11pt;"); + gemSummaryLabel->setStyleSheet("font-size: 12px;"); columnHeaderLayout->addWidget(gemSummaryLabel); vLayout->addLayout(columnHeaderLayout); diff --git a/Code/Tools/ProjectManager/Source/LinkWidget.cpp b/Code/Tools/ProjectManager/Source/LinkWidget.cpp index a6308f6c62..160d9cf7c7 100644 --- a/Code/Tools/ProjectManager/Source/LinkWidget.cpp +++ b/Code/Tools/ProjectManager/Source/LinkWidget.cpp @@ -37,7 +37,7 @@ namespace O3DE::ProjectManager void LinkLabel::enterEvent([[maybe_unused]] QEvent* event) { - setStyleSheet("font-size: 9pt; color: #94D2FF; text-decoration: underline;"); + setStyleSheet("font-size: 10px; color: #94D2FF; text-decoration: underline;"); } void LinkLabel::leaveEvent([[maybe_unused]] QEvent* event) @@ -52,6 +52,6 @@ namespace O3DE::ProjectManager void LinkLabel::SetDefaultStyle() { - setStyleSheet("font-size: 9pt; color: #94D2FF;"); + setStyleSheet("font-size: 10px; color: #94D2FF;"); } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/TagWidget.cpp b/Code/Tools/ProjectManager/Source/TagWidget.cpp index 3e80944204..628b682b95 100644 --- a/Code/Tools/ProjectManager/Source/TagWidget.cpp +++ b/Code/Tools/ProjectManager/Source/TagWidget.cpp @@ -18,9 +18,9 @@ namespace O3DE::ProjectManager TagWidget::TagWidget(const QString& text, QWidget* parent) : QLabel(text, parent) { - setFixedHeight(35); + setFixedHeight(24); setMargin(5); - setStyleSheet("font-size: 12pt; background-color: #333333; border-radius: 4px;"); + setStyleSheet("font-size: 12px; background-color: #333333; border-radius: 3px;"); } TagContainerWidget::TagContainerWidget(QWidget* parent) @@ -35,7 +35,7 @@ namespace O3DE::ProjectManager void TagContainerWidget::Update(const QStringList& tags) { QWidget* parentWidget = qobject_cast(parent()); - int width = 250; + int width = 200; if (parentWidget) { width = parentWidget->width(); From 3b349e72a05e10d13e0a35b7d5912b8cc6d0c500 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 28 May 2021 01:17:57 -0500 Subject: [PATCH 285/811] Adding QtForPython gem to the AutomatedTesting project --- .../Platform/Android/runtime_dependencies.cmake | 10 ---------- .../Code/Platform/Android/tool_dependencies.cmake | 10 ---------- .../Code/Platform/Linux/runtime_dependencies.cmake | 10 ---------- .../Code/Platform/Linux/tool_dependencies.cmake | 10 ---------- .../Platform/Windows/runtime_dependencies.cmake | 13 ------------- .../Code/Platform/Windows/tool_dependencies.cmake | 14 -------------- .../Code/Platform/iOS/runtime_dependencies.cmake | 10 ---------- .../Gem/Code/Platform/iOS/tool_dependencies.cmake | 10 ---------- AutomatedTesting/Gem/Code/enabled_gems.cmake | 1 + 9 files changed, 1 insertion(+), 87 deletions(-) delete mode 100644 AutomatedTesting/Gem/Code/Platform/Android/runtime_dependencies.cmake delete mode 100644 AutomatedTesting/Gem/Code/Platform/Android/tool_dependencies.cmake delete mode 100644 AutomatedTesting/Gem/Code/Platform/Linux/runtime_dependencies.cmake delete mode 100644 AutomatedTesting/Gem/Code/Platform/Linux/tool_dependencies.cmake delete mode 100644 AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake delete mode 100644 AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake delete mode 100644 AutomatedTesting/Gem/Code/Platform/iOS/runtime_dependencies.cmake delete mode 100644 AutomatedTesting/Gem/Code/Platform/iOS/tool_dependencies.cmake diff --git a/AutomatedTesting/Gem/Code/Platform/Android/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Android/runtime_dependencies.cmake deleted file mode 100644 index 4d5680a30d..0000000000 --- a/AutomatedTesting/Gem/Code/Platform/Android/runtime_dependencies.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# diff --git a/AutomatedTesting/Gem/Code/Platform/Android/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Android/tool_dependencies.cmake deleted file mode 100644 index 4d5680a30d..0000000000 --- a/AutomatedTesting/Gem/Code/Platform/Android/tool_dependencies.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# diff --git a/AutomatedTesting/Gem/Code/Platform/Linux/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Linux/runtime_dependencies.cmake deleted file mode 100644 index 4d5680a30d..0000000000 --- a/AutomatedTesting/Gem/Code/Platform/Linux/runtime_dependencies.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# diff --git a/AutomatedTesting/Gem/Code/Platform/Linux/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Linux/tool_dependencies.cmake deleted file mode 100644 index 4d5680a30d..0000000000 --- a/AutomatedTesting/Gem/Code/Platform/Linux/tool_dependencies.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# diff --git a/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake deleted file mode 100644 index ffcaf7293a..0000000000 --- a/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(GEM_DEPENDENCIES -) \ No newline at end of file diff --git a/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake deleted file mode 100644 index 933dd7927b..0000000000 --- a/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(GEM_DEPENDENCIES - Gem::QtForPython.Editor -) \ No newline at end of file diff --git a/AutomatedTesting/Gem/Code/Platform/iOS/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/iOS/runtime_dependencies.cmake deleted file mode 100644 index 4d5680a30d..0000000000 --- a/AutomatedTesting/Gem/Code/Platform/iOS/runtime_dependencies.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# diff --git a/AutomatedTesting/Gem/Code/Platform/iOS/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/iOS/tool_dependencies.cmake deleted file mode 100644 index 4d5680a30d..0000000000 --- a/AutomatedTesting/Gem/Code/Platform/iOS/tool_dependencies.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# diff --git a/AutomatedTesting/Gem/Code/enabled_gems.cmake b/AutomatedTesting/Gem/Code/enabled_gems.cmake index 2ea800bae6..d99d17b55e 100644 --- a/AutomatedTesting/Gem/Code/enabled_gems.cmake +++ b/AutomatedTesting/Gem/Code/enabled_gems.cmake @@ -21,6 +21,7 @@ set(ENABLED_GEMS InAppPurchases AutomatedTesting EditorPythonBindings + QtForPython PythonAssetBuilder Metastream AudioSystem From b73bc09ce709cfb2efe58f69592a77fee2192822 Mon Sep 17 00:00:00 2001 From: phistere Date: Fri, 28 May 2021 01:20:24 -0500 Subject: [PATCH 286/811] Fixes a name comparison issue during module load A name like Camera.dll was matching against Atom_Component_DebugCamera.dll so it thought the module was already seen and wouldn't add it to the list of dynamic modules to load. --- Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index d1cab75564..1010ae3473 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -1330,7 +1330,7 @@ namespace AZ { auto CompareDynamicModuleDescriptor = [&dynamicLibraryPath](const DynamicModuleDescriptor& entry) { - return entry.m_dynamicLibraryPath.contains(dynamicLibraryPath); + return AZ::IO::PathView(entry.m_dynamicLibraryPath).Stem() == AZ::IO::PathView(dynamicLibraryPath).Stem(); }; if (auto moduleIter = AZStd::find_if(gemModules.begin(), gemModules.end(), CompareDynamicModuleDescriptor); moduleIter == gemModules.end()) From fdc57cdaff7138f0e576978ce867ff6b099300fb Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Fri, 28 May 2021 00:08:13 -0700 Subject: [PATCH 287/811] Added TLAS dependency --- .../ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli | 2 +- .../Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli index 2352f5d09b..b8c97ef421 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli @@ -143,7 +143,7 @@ ShaderResourceGroup RayTracingSceneSrg : SRG_RayTracingScene float4 m_irradianceColor; float3x3 m_worldInvTranspose; - float m_padding1[1]; + float m_padding1; uint m_bufferFlags; uint m_bufferStartIndex; diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h index d89b61b2f9..90a9383ae6 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h @@ -236,7 +236,7 @@ namespace AZ AZStd::array m_irradianceColor; // float4 AZStd::array m_worldInvTranspose; // float3x3 - float m_padding1[1]; + float m_padding1; RayTracingSubMeshBufferFlags m_bufferFlags = RayTracingSubMeshBufferFlags::None; uint32_t m_bufferStartIndex = 0; From 9ec4278f86d517c6ac830c2e60f106abe1bf891a Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Fri, 28 May 2021 00:09:00 -0700 Subject: [PATCH 288/811] Added TLAS dependency --- .../Code/Source/RayTracing/RayTracingPass.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp index 1ec2d9ae04..988870cc0e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingPass.cpp @@ -196,8 +196,36 @@ namespace AZ void RayTracingPass::SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) { + RPI::Scene* scene = m_pipeline->GetScene(); + RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor(); + AZ_Assert(rayTracingFeatureProcessor, "RayTracingPass requires the RayTracingFeatureProcessor"); + RPI::RenderPass::SetupFrameGraphDependencies(frameGraph); frameGraph.SetEstimatedItemCount(1); + + // TLAS + { + const RHI::Ptr& rayTracingTlasBuffer = rayTracingFeatureProcessor->GetTlas()->GetTlasBuffer(); + if (rayTracingTlasBuffer) + { + AZ::RHI::AttachmentId tlasAttachmentId = rayTracingFeatureProcessor->GetTlasAttachmentId(); + if (frameGraph.GetAttachmentDatabase().IsAttachmentValid(tlasAttachmentId) == false) + { + [[maybe_unused]] RHI::ResultCode result = frameGraph.GetAttachmentDatabase().ImportBuffer(tlasAttachmentId, rayTracingTlasBuffer); + AZ_Assert(result == RHI::ResultCode::Success, "Failed to import ray tracing TLAS buffer with error %d", result); + } + + uint32_t tlasBufferByteCount = aznumeric_cast(rayTracingFeatureProcessor->GetTlas()->GetTlasBuffer()->GetDescriptor().m_byteCount); + RHI::BufferViewDescriptor tlasBufferViewDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, tlasBufferByteCount); + + RHI::BufferScopeAttachmentDescriptor desc; + desc.m_attachmentId = tlasAttachmentId; + desc.m_bufferViewDescriptor = tlasBufferViewDescriptor; + desc.m_loadStoreAction.m_loadAction = AZ::RHI::AttachmentLoadAction::Load; + + frameGraph.UseShaderAttachment(desc, RHI::ScopeAttachmentAccess::ReadWrite); + } + } } void RayTracingPass::CompileResources(const RHI::FrameGraphCompileContext& context) From 58bad80ffa590a760ace9f2ca311bf2b57a6f545 Mon Sep 17 00:00:00 2001 From: pappeste Date: Fri, 28 May 2021 00:17:20 -0700 Subject: [PATCH 289/811] changing paths for the install location in Jenkins --- scripts/build/Platform/Windows/build_config.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index d3adf69f43..38cd7d6ad8 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -300,7 +300,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_DISABLE_TEST_MODULES=TRUE -DCMAKE_INSTALL_PREFIX=install", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_DISABLE_TEST_MODULES=TRUE", "CMAKE_LY_PROJECTS": "", "CMAKE_TARGET": "INSTALL", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" @@ -332,7 +332,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DCMAKE_MODULE_PATH=!WORKSPACE!/o3de/build/windows_vs2019/install/cmake", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DCMAKE_MODULE_PATH=!WORKSPACE!/o3de/install/cmake", "CMAKE_LY_PROJECTS": "", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" From dc4a15628f4702d54035a7680dc3c68a478fcdf9 Mon Sep 17 00:00:00 2001 From: srikappa Date: Fri, 28 May 2021 00:43:31 -0700 Subject: [PATCH 290/811] Remove unused GetNestedInstance method in Prefab Instance class --- .../AzToolsFramework/Prefab/Instance/Instance.cpp | 11 ----------- .../AzToolsFramework/Prefab/Instance/Instance.h | 1 - 2 files changed, 12 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp index 8c7604f680..8f483ec818 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp @@ -401,17 +401,6 @@ namespace AzToolsFramework } } - InstancePtrOptionalReference Instance::GetNestedInstance(const InstanceAlias& instanceAlias) - { - auto nestedInstanceIterator = m_nestedInstances.find(instanceAlias); - if (nestedInstanceIterator != m_nestedInstances.end()) - { - return nestedInstanceIterator->second; - } - - return AZStd::nullopt; - } - void Instance::GetNestedInstances(const AZStd::function&)>& callback) { for (auto& [instanceAlias, instance] : m_nestedInstances) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h index 377be68753..31dfb7b8b4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h @@ -95,7 +95,6 @@ namespace AzToolsFramework Instance& AddInstance(AZStd::unique_ptr instance); AZStd::unique_ptr DetachNestedInstance(const InstanceAlias& instanceAlias); - InstancePtrOptionalReference GetNestedInstance(const InstanceAlias& instanceAlias); /** * Gets the aliases for the entities in the Instance DOM. From 3c0c066f8807b5a8bcf8ca1385e689a0a0153800 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 28 May 2021 02:54:54 -0500 Subject: [PATCH 291/811] Updating the ProjectManager Gem validation check to make sure the name isn't empty either --- Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.cpp index 16e52c7073..bc44928868 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.cpp @@ -25,7 +25,7 @@ namespace O3DE::ProjectManager bool GemInfo::IsValid() const { - return !m_path.isEmpty(); + return !m_name.isEmpty() && !m_path.isEmpty(); } QString GemInfo::GetPlatformString(Platform platform) From be6cee806ddcc1b629cfcf3fad51c5429091a504 Mon Sep 17 00:00:00 2001 From: srikappa Date: Fri, 28 May 2021 02:14:28 -0700 Subject: [PATCH 292/811] Show detach prefab only when a single instance is selected --- .../Prefab/PrefabPublicHandler.cpp | 26 +++++++++---------- .../UI/Prefab/PrefabIntegrationManager.cpp | 21 +++++++-------- 2 files changed, 22 insertions(+), 25 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index f6ded4ae45..653b7d4878 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -1155,19 +1155,6 @@ namespace AzToolsFramework return AZ::Success(); } - void PrefabPublicHandler::ReplaceOldAliases(QString& stringToReplace, AZStd::string_view oldAlias, AZStd::string_view newAlias) - { - QString oldAliasQuotes = QString("\"%1\"").arg(oldAlias.data()); - QString newAliasQuotes = QString("\"%1\"").arg(newAlias.data()); - - stringToReplace.replace(oldAliasQuotes, newAliasQuotes); - - QString oldAliasPathRef = QString("/%1").arg(oldAlias.data()); - QString newAliasPathRef = QString("/%1").arg(newAlias.data()); - - stringToReplace.replace(oldAliasPathRef, newAliasPathRef); - } - void PrefabPublicHandler::GenerateContainerEntityTransform(const EntityList& topLevelEntities, AZ::Vector3& translation, AZ::Quaternion& rotation) { @@ -1418,5 +1405,18 @@ namespace AzToolsFramework return true; } + + void PrefabPublicHandler::ReplaceOldAliases(QString& stringToReplace, AZStd::string_view oldAlias, AZStd::string_view newAlias) + { + QString oldAliasQuotes = QString("\"%1\"").arg(oldAlias.data()); + QString newAliasQuotes = QString("\"%1\"").arg(newAlias.data()); + + stringToReplace.replace(oldAliasQuotes, newAliasQuotes); + + QString oldAliasPathRef = QString("/%1").arg(oldAlias.data()); + QString newAliasPathRef = QString("/%1").arg(newAlias.data()); + + stringToReplace.replace(oldAliasPathRef, newAliasPathRef); + } } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index 090c7bdc54..45499a4071 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -238,24 +238,21 @@ namespace AzToolsFramework deleteAction->setDisabled(true); } - QAction* detachPrefabAction = menu->addAction(QObject::tr("Detach Prefab...")); - if (selectedEntities.size() != 1) - { - detachPrefabAction->setDisabled(true); - } - else + // Detach Prefab + if (selectedEntities.size() == 1) { AZ::EntityId selectedEntity = selectedEntities[0]; if (s_prefabPublicInterface->IsInstanceContainerEntity(selectedEntity) && !s_prefabPublicInterface->IsLevelInstanceContainerEntity(selectedEntity)) { - QObject::connect(detachPrefabAction, &QAction::triggered, detachPrefabAction, - [this, selectedEntity] { ContextMenu_DetachPrefab(selectedEntity); }); - } - else - { - detachPrefabAction->setDisabled(true); + QAction* detachPrefabAction = menu->addAction(QObject::tr("Detach Prefab...")); + QObject::connect( + detachPrefabAction, &QAction::triggered, detachPrefabAction, + [this, selectedEntity] + { + ContextMenu_DetachPrefab(selectedEntity); + }); } } } From 55e1da64bb2e95a6668fd919619334a74ebb8d90 Mon Sep 17 00:00:00 2001 From: srikappa Date: Fri, 28 May 2021 02:29:09 -0700 Subject: [PATCH 293/811] Renamed a function and improved comments --- .../AzToolsFramework/Prefab/Instance/Instance.h | 1 - .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 2 +- .../AzToolsFramework/Prefab/PrefabPublicHandler.h | 2 +- .../AzToolsFramework/Prefab/PrefabPublicInterface.h | 9 ++++++--- .../UI/Prefab/PrefabIntegrationManager.cpp | 2 +- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h index 31dfb7b8b4..68bc395012 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h @@ -48,7 +48,6 @@ namespace AzToolsFramework using EntityAliasOptionalReference = AZStd::optional>; using InstanceOptionalReference = AZStd::optional>; using InstanceOptionalConstReference = AZStd::optional>; - using InstancePtrOptionalReference = AZStd::optional>>; using InstanceSet = AZStd::unordered_set; using InstanceSetConstReference = AZStd::optional>; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 653b7d4878..7ec0ddf8ad 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -990,7 +990,7 @@ namespace AzToolsFramework return AZ::Success(); } - PrefabOperationResult PrefabPublicHandler::DetachPrefabFromParent(const AZ::EntityId& entityId) + PrefabOperationResult PrefabPublicHandler::DetachPrefab(const AZ::EntityId& entityId) { if (!entityId.IsValid()) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index f1c32ee35c..f3b3b242dd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -64,7 +64,7 @@ namespace AzToolsFramework PrefabOperationResult DeleteEntitiesAndAllDescendantsInInstance(const EntityIdList& entityIds) override; PrefabOperationResult DuplicateEntitiesInInstance(const EntityIdList& entityIds) override; - PrefabOperationResult DetachPrefabFromParent(const AZ::EntityId& entityId) override; + PrefabOperationResult DetachPrefab(const AZ::EntityId& entityId) override; private: PrefabOperationResult DeleteFromInstance(const EntityIdList& entityIds, bool deleteDescendants); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h index f12bc359f2..ec13a852ee 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h @@ -152,12 +152,15 @@ namespace AzToolsFramework virtual PrefabOperationResult DuplicateEntitiesInInstance(const EntityIdList& entityIds) = 0; /** - * Detaches target container entity's owning instance from its parent instance. + * If the entity id is a container entity id, detaches the prefab instance corresponding to it. This includes converting + * the container entity into a regular entity and putting it under the parent prefab, removing the link between this + * instance and the parent, removing links between this instance and it's nested instances, adding entities directly + * owned by this instance under the parent instance. * Bails if the entity is not a container entity or belongs to the level prefab instance. - * @param entityId The container entity whose instance to detach. + * @param entityId The container entity id of the instance to detach. * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. */ - virtual PrefabOperationResult DetachPrefabFromParent(const AZ::EntityId& entityId) = 0; + virtual PrefabOperationResult DetachPrefab(const AZ::EntityId& entityId) = 0; }; } // namespace Prefab diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index 45499a4071..b7feb1a8c1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -413,7 +413,7 @@ namespace AzToolsFramework void PrefabIntegrationManager::ContextMenu_DetachPrefab(AZ::EntityId containerEntity) { PrefabOperationResult detachPrefabResult = - s_prefabPublicInterface->DetachPrefabFromParent(containerEntity); + s_prefabPublicInterface->DetachPrefab(containerEntity); if (!detachPrefabResult.IsSuccess()) { From e4f73d44fec7a7436438cd3bcbb1011357c91ead Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 10:33:12 +0100 Subject: [PATCH 294/811] remove vector scale and add uniform scale as animatable properties --- .../AzFramework/AzFramework/Components/TransformComponent.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp index 49adab2252..3fd5c4d81c 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp @@ -759,7 +759,9 @@ namespace AzFramework ->Event("SetLocalScale", &AZ::TransformBus::Events::SetLocalScale) ->Event("GetLocalScale", &AZ::TransformBus::Events::GetLocalScale) ->Attribute("Scale", AZ::Edit::Attributes::PropertyScale) - ->VirtualProperty("Scale", "GetLocalScale", "SetLocalScale") + ->Event("SetLocalUniformScale", &AZ::TransformBus::Events::SetLocalUniformScale) + ->Event("GetLocalUniformScale", &AZ::TransformBus::Events::GetLocalUniformScale) + ->VirtualProperty("Uniform Scale", "GetLocalUniformScale", "SetLocalUniformScale") ->Event("GetWorldScale", &AZ::TransformBus::Events::GetWorldScale) ->Event("GetChildren", &AZ::TransformBus::Events::GetChildren) ->Event("GetAllDescendants", &AZ::TransformBus::Events::GetAllDescendants) From 23d481773ac4a976f69197b7835be5e4ed89a6cb Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 10:37:44 +0100 Subject: [PATCH 295/811] refactor vector scale transform function usages in trackview --- Code/Sandbox/Editor/TrackView/TrackViewSequence.cpp | 4 ++-- .../Code/Source/Cinematics/AnimComponentNode.cpp | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Code/Sandbox/Editor/TrackView/TrackViewSequence.cpp b/Code/Sandbox/Editor/TrackView/TrackViewSequence.cpp index f915c804f8..d26c8fd973 100644 --- a/Code/Sandbox/Editor/TrackView/TrackViewSequence.cpp +++ b/Code/Sandbox/Editor/TrackView/TrackViewSequence.cpp @@ -828,7 +828,7 @@ void CTrackViewSequence::SyncSelectedTracksToBase() const Vec3 scale = pAnimNode->GetScale(); AZ::Transform transform = AZ::Transform::CreateIdentity(); - transform.SetScale(LYVec3ToAZVec3(scale)); + transform.SetUniformScale(LYVec3ToAZVec3(scale).GetMaxElement()); transform.SetRotation(LYQuaternionToAZQuaternion(rotation)); transform.SetTranslation(LYVec3ToAZVec3(position)); @@ -870,7 +870,7 @@ void CTrackViewSequence::SyncSelectedTracksFromBase() pAnimNode->SetPos(AZVec3ToLYVec3(transform.GetTranslation())); pAnimNode->SetRotation(AZQuaternionToLYQuaternion(transform.GetRotation())); - pAnimNode->SetScale(AZVec3ToLYVec3(transform.GetScale())); + pAnimNode->SetScale(AZVec3ToLYVec3(AZ::Vector3(transform.GetUniformScale()))); bNothingWasSynced = false; } diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.cpp index ea7322014c..324b712f40 100644 --- a/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.cpp @@ -324,11 +324,11 @@ void CAnimComponentNode::ConvertBetweenWorldAndLocalRotation(Quat& rotation, ETr { AZ::Quaternion rot(rotation.v.x, rotation.v.y, rotation.v.z, rotation.w); AZ::Transform rotTransform = AZ::Transform::CreateFromQuaternion(rot); - rotTransform.ExtractScale(); + rotTransform.ExtractUniformScale(); AZ::Transform parentTransform = AZ::Transform::Identity(); GetParentWorldTransform(parentTransform); - parentTransform.ExtractScale(); + parentTransform.ExtractUniformScale(); if (conversionDirection == eTransformConverstionDirection_toLocalSpace) { parentTransform.Invert(); @@ -344,7 +344,7 @@ void CAnimComponentNode::ConvertBetweenWorldAndLocalRotation(Quat& rotation, ETr void CAnimComponentNode::ConvertBetweenWorldAndLocalScale(Vec3& scale, ETransformSpaceConversionDirection conversionDirection) const { AZ::Transform parentTransform = AZ::Transform::Identity(); - AZ::Transform scaleTransform = AZ::Transform::CreateScale(AZ::Vector3(scale.x, scale.y, scale.z)); + AZ::Transform scaleTransform = AZ::Transform::CreateUniformScale(AZ::Vector3(scale.x, scale.y, scale.z).GetMaxElement()); GetParentWorldTransform(parentTransform); if (conversionDirection == eTransformConverstionDirection_toLocalSpace) @@ -353,8 +353,8 @@ void CAnimComponentNode::ConvertBetweenWorldAndLocalScale(Vec3& scale, ETransfor } scaleTransform = parentTransform * scaleTransform; - AZ::Vector3 vScale = scaleTransform.GetScale(); - scale.Set(vScale.GetX(), vScale.GetY(), vScale.GetZ()); + const float uniformScale = scaleTransform.GetUniformScale(); + scale.Set(uniformScale, uniformScale, uniformScale); } ////////////////////////////////////////////////////////////////////////// From fcfb5a7941a77ecb11a41f946cd40ccd87f65597 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 10:50:35 +0100 Subject: [PATCH 296/811] refactor vector scale transform function usages in GradientSignal --- .../Code/Include/GradientSignal/GradientSampler.h | 10 +++++----- .../Source/Components/GradientTransformComponent.cpp | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Gems/GradientSignal/Code/Include/GradientSignal/GradientSampler.h b/Gems/GradientSignal/Code/Include/GradientSignal/GradientSampler.h index 8a8eacc952..9e7823c8d3 100644 --- a/Gems/GradientSignal/Code/Include/GradientSignal/GradientSampler.h +++ b/Gems/GradientSignal/Code/Include/GradientSignal/GradientSampler.h @@ -103,12 +103,12 @@ namespace GradientSignal //apply transform if set if (m_enableTransform && GradientSamplerUtil::AreTransformParamsSet(*this)) { - const AZ::Transform transform = - AZ::Transform::CreateTranslation(m_translate) * - AZ::ConvertEulerDegreesToTransform(m_rotate) * - AZ::Transform::CreateScale(m_scale); + AZ::Matrix3x4 matrix3x4; + matrix3x4.SetFromEulerDegrees(m_rotate); + matrix3x4.MultiplyByScale(m_scale); + matrix3x4.SetTranslation(m_translate); - sampleParamsTransformed.m_position = transform.TransformPoint(sampleParamsTransformed.m_position); + sampleParamsTransformed.m_position = matrix3x4 * sampleParamsTransformed.m_position; } float output = 0.0f; diff --git a/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp b/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp index 336f428582..a2d979313e 100644 --- a/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp @@ -493,7 +493,7 @@ namespace GradientSignal if (!m_configuration.m_advancedMode || !m_configuration.m_overrideScale) { - m_configuration.m_scale = shapeTransform.GetScale(); + m_configuration.m_scale = AZ::Vector3(shapeTransform.GetUniformScale()); } //rebuild bounds from parameters From c35c1d67e77dc96bb8bdf7cad35cf5fb9a0ee2bb Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 11:34:42 +0100 Subject: [PATCH 297/811] update transform widget to work with uniform scale --- .../RowWidgets/TransformRowHandler.cpp | 10 ++++--- .../SceneUI/RowWidgets/TransformRowWidget.cpp | 28 ++++++++----------- .../SceneUI/RowWidgets/TransformRowWidget.h | 16 +++++++---- .../RowWidgets/TransformRowWidgetTests.cpp | 20 ++++++------- 4 files changed, 37 insertions(+), 37 deletions(-) diff --git a/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowHandler.cpp b/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowHandler.cpp index 322aa9ac51..640c092070 100644 --- a/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowHandler.cpp +++ b/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowHandler.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include namespace AZ @@ -58,10 +59,11 @@ namespace AZ } else { - AzToolsFramework::Vector3PropertyHandler handler; - handler.ConsumeAttribute(widget->GetTranslationWidget(), attrib, attrValue, debugName); - handler.ConsumeAttribute(widget->GetRotationWidget(), attrib, attrValue, debugName); - handler.ConsumeAttribute(widget->GetScaleWidget(), attrib, attrValue, debugName); + AzToolsFramework::Vector3PropertyHandler vector3Handler; + vector3Handler.ConsumeAttribute(widget->GetTranslationWidget(), attrib, attrValue, debugName); + vector3Handler.ConsumeAttribute(widget->GetRotationWidget(), attrib, attrValue, debugName); + AzToolsFramework::doublePropertySpinboxHandler spinboxHandler; + spinboxHandler.ConsumeAttribute(widget->GetScaleWidget(), attrib, attrValue, debugName); } } diff --git a/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowWidget.cpp b/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowWidget.cpp index 10e0fd2a68..e8ecaa0c27 100644 --- a/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowWidget.cpp +++ b/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowWidget.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -47,7 +48,7 @@ namespace AZ ExpandedTransform::ExpandedTransform() : m_translation(0, 0, 0) , m_rotation(0, 0, 0) - , m_scale(1, 1, 1) + , m_scale(1) { } @@ -60,14 +61,14 @@ namespace AZ { m_translation = transform.GetTranslation(); m_rotation = transform.GetEulerDegrees(); - m_scale = transform.GetScale(); + m_scale = transform.GetUniformScale(); } void ExpandedTransform::GetTransform(AZ::Transform& transform) const { transform = Transform::CreateTranslation(m_translation); transform *= AZ::ConvertEulerDegreesToTransform(m_rotation); - transform.MultiplyByScale(m_scale); + transform.MultiplyByUniformScale(m_scale); } const AZ::Vector3& ExpandedTransform::GetTranslation() const @@ -90,12 +91,12 @@ namespace AZ m_rotation = rotation; } - const AZ::Vector3& ExpandedTransform::GetScale() const + const float ExpandedTransform::GetScale() const { return m_scale; } - void ExpandedTransform::SetScale(const AZ::Vector3& scale) + void ExpandedTransform::SetScale(const float scale) { m_scale = scale; } @@ -131,7 +132,7 @@ namespace AZ m_rotationWidget->setMaximum(360); m_rotationWidget->setSuffix(" degrees"); - m_scaleWidget = new AzQtComponents::VectorInput(this, 3); + m_scaleWidget = new AzToolsFramework::PropertyDoubleSpinCtrl(this); m_scaleWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); m_scaleWidget->setMinimum(0); m_scaleWidget->setMaximum(10000); @@ -191,13 +192,10 @@ namespace AZ AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestWrite, this); }); - QObject::connect(m_scaleWidget, &AzQtComponents::VectorInput::valueChanged, this, [this] + QObject::connect(m_scaleWidget, &AzToolsFramework::PropertyDoubleSpinCtrl::valueChanged, this, [this] { - AzQtComponents::VectorInput* widget = this->GetScaleWidget(); - AZ::Vector3 scale; - - PopulateVector3(widget, scale); - + AzToolsFramework::PropertyDoubleSpinCtrl* widget = this->GetScaleWidget(); + float scale = aznumeric_cast(widget->value()); m_transform.SetScale(scale); AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestWrite, this); }); @@ -224,9 +222,7 @@ namespace AZ m_rotationWidget->setValuebyIndex(m_transform.GetRotation().GetY(), 1); m_rotationWidget->setValuebyIndex(m_transform.GetRotation().GetZ(), 2); - m_scaleWidget->setValuebyIndex(m_transform.GetScale().GetX(), 0); - m_scaleWidget->setValuebyIndex(m_transform.GetScale().GetY(), 1); - m_scaleWidget->setValuebyIndex(m_transform.GetScale().GetZ(), 2); + m_scaleWidget->setValue(m_transform.GetScale()); blockSignals(false); } @@ -251,7 +247,7 @@ namespace AZ return m_rotationWidget; } - AzQtComponents::VectorInput* TransformRowWidget::GetScaleWidget() + AzToolsFramework::PropertyDoubleSpinCtrl* TransformRowWidget::GetScaleWidget() { return m_scaleWidget; } diff --git a/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowWidget.h b/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowWidget.h index dc3286f80e..3977d26c7c 100644 --- a/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowWidget.h +++ b/Code/Tools/SceneAPI/SceneUI/RowWidgets/TransformRowWidget.h @@ -21,6 +21,7 @@ #include #include #include + #endif namespace AzQtComponents @@ -28,6 +29,11 @@ namespace AzQtComponents class VectorInput; } +namespace AzToolsFramework +{ + class PropertyDoubleSpinCtrl; +} + namespace AZ { namespace SceneAPI @@ -51,14 +57,14 @@ namespace AZ const AZ::Vector3& GetRotation() const; void SetRotation(const AZ::Vector3& translation); - const AZ::Vector3& GetScale() const; - void SetScale(const AZ::Vector3& scale); + const float GetScale() const; + void SetScale(const float scale); private: AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING AZ::Vector3 m_translation; AZ::Vector3 m_rotation; - AZ::Vector3 m_scale; + float m_scale; AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING }; @@ -78,7 +84,7 @@ namespace AZ AzQtComponents::VectorInput* GetTranslationWidget(); AzQtComponents::VectorInput* GetRotationWidget(); - AzQtComponents::VectorInput* GetScaleWidget(); + AzToolsFramework::PropertyDoubleSpinCtrl* GetScaleWidget(); protected: ExpandedTransform m_transform; @@ -87,7 +93,7 @@ namespace AZ AzQtComponents::VectorInput* m_translationWidget; AzQtComponents::VectorInput* m_rotationWidget; - AzQtComponents::VectorInput* m_scaleWidget; + AzToolsFramework::PropertyDoubleSpinCtrl* m_scaleWidget; }; } // namespace SceneUI } // namespace SceneAPI diff --git a/Code/Tools/SceneAPI/SceneUI/Tests/RowWidgets/TransformRowWidgetTests.cpp b/Code/Tools/SceneAPI/SceneUI/Tests/RowWidgets/TransformRowWidgetTests.cpp index 05082f29fb..cda6582e63 100644 --- a/Code/Tools/SceneAPI/SceneUI/Tests/RowWidgets/TransformRowWidgetTests.cpp +++ b/Code/Tools/SceneAPI/SceneUI/Tests/RowWidgets/TransformRowWidgetTests.cpp @@ -30,7 +30,7 @@ namespace AZ Vector3 m_translation = Vector3(10.0f, 20.0f, 30.0f); Vector3 m_rotation = Vector3(30.0f, 45.0f, 60.0f); - Vector3 m_scale = Vector3(2.0f, 3.0f, 4.0f); + float m_scale = 3.0f; }; TEST_F(TransformRowWidgetTest, GetTranslation_TranslationInMatrix_TranslationCanBeRetrievedDirectly) @@ -83,26 +83,22 @@ namespace AZ TEST_F(TransformRowWidgetTest, GetScale_ScaleInMatrix_ScaleCanBeRetrievedDirectly) { - m_transform = Transform::CreateScale(m_scale); + m_transform = Transform::CreateUniformScale(m_scale); m_expanded.SetTransform(m_transform); - const Vector3& returned = m_expanded.GetScale(); - EXPECT_NEAR(m_scale.GetX(), returned.GetX(), 0.1f); - EXPECT_NEAR(m_scale.GetY(), returned.GetY(), 0.1f); - EXPECT_NEAR(m_scale.GetZ(), returned.GetZ(), 0.1f); + const float returned = m_expanded.GetScale(); + EXPECT_NEAR(m_scale, returned, 0.1f); } TEST_F(TransformRowWidgetTest, GetScale_ScaleInMatrix_ScaleCanBeRetrievedFromTransform) { - m_transform = Transform::CreateScale(m_scale); + m_transform = Transform::CreateUniformScale(m_scale); m_expanded.SetTransform(m_transform); Transform rebuild; m_expanded.GetTransform(rebuild); - Vector3 returned = rebuild.GetScale(); - EXPECT_NEAR(m_scale.GetX(), returned.GetX(), 0.1f); - EXPECT_NEAR(m_scale.GetY(), returned.GetY(), 0.1f); - EXPECT_NEAR(m_scale.GetZ(), returned.GetZ(), 0.1f); + float returned = rebuild.GetUniformScale(); + EXPECT_NEAR(m_scale, returned, 0.1f); } TEST_F(TransformRowWidgetTest, GetTransform_RotateAndTranslateInMatrix_ReconstructedTransformMatchesOriginal) @@ -121,7 +117,7 @@ namespace AZ { Quaternion quaternion = AZ::ConvertEulerDegreesToQuaternion(m_rotation); m_transform = Transform::CreateFromQuaternionAndTranslation(quaternion, m_translation); - m_transform.MultiplyByScale(m_scale); + m_transform.MultiplyByUniformScale(m_scale); m_expanded.SetTransform(m_transform); Transform rebuild; From c84882869bc57887d7e534e803a0c006d516d9fd Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Fri, 28 May 2021 03:41:44 -0700 Subject: [PATCH 298/811] Changed to a fixed-size occlusion buffer --- .../Code/Include/Atom/RPI.Public/Culling.h | 2 +- .../RPI/Code/Include/Atom/RPI.Public/View.h | 2 +- .../RPI/Code/Source/RPI.Public/Culling.cpp | 4 +- .../Atom/RPI/Code/Source/RPI.Public/Scene.cpp | 2 +- Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp | 50 ++----------------- 5 files changed, 9 insertions(+), 51 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h index 17e0a1f82d..8892266683 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h @@ -217,7 +217,7 @@ namespace AZ void SetOcclusionCullingPlanes(const AZStd::vector& occlusionCullingPlanes) { m_occlusionCullingPlanes = occlusionCullingPlanes; } //! Notifies the CullingScene that culling will begin for this frame. - void BeginCulling(const AZStd::vector& views, const AZStd::vector& activePipelines); + void BeginCulling(const AZStd::vector& views); //! Notifies the CullingScene that the culling is done for this frame. void EndCulling(); diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h index 74c841d2a5..0b6b41c8b0 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h @@ -128,7 +128,7 @@ namespace AZ void ConnectWorldToClipMatrixChangedHandler(MatrixChangedEvent::Handler& handler); //! Prepare for view culling - void BeginCulling(const AZStd::vector& activePipelines); + void BeginCulling(); //! Returns the masked occlusion culling interface MaskedOcclusionCulling* GetMaskedOcclusionCulling(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index ab25fb14fb..7bed2d3232 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -643,7 +643,7 @@ namespace AZ } } - void CullingScene::BeginCulling(const AZStd::vector& views, const AZStd::vector& activePipelines) + void CullingScene::BeginCulling(const AZStd::vector& views) { m_cullDataConcurrencyCheck.soft_lock(); @@ -652,7 +652,7 @@ namespace AZ for (auto& view : views) { - view->BeginCulling(activePipelines); + view->BeginCulling(); } AuxGeomDrawPtr auxGeom; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp index 16c2189a00..c02ac0713c 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp @@ -500,7 +500,7 @@ namespace AZ } // Launch CullingSystem::ProcessCullables() jobs (will run concurrently with FeatureProcessor::Render() jobs) - m_cullingScene->BeginCulling(m_renderPacket.m_views, activePipelines); + m_cullingScene->BeginCulling(m_renderPacket.m_views); for (ViewPtr& viewPtr : m_renderPacket.m_views) { AZ::Job* processCullablesJob = AZ::CreateJobFunction([this, &viewPtr](AZ::Job& thisJob) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index 3060fc34a3..edae0f88b7 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -54,7 +54,7 @@ namespace AZ } m_maskedOcclusionCulling = MaskedOcclusionCulling::Create(); - m_maskedOcclusionCulling->SetNearClipPlane(0.1f); + m_maskedOcclusionCulling->SetResolution(1920, 1080); } View::~View() @@ -388,56 +388,14 @@ namespace AZ m_needBuildSrg = false; } - void View::BeginCulling(const AZStd::vector& activePipelines) + void View::BeginCulling() { - // retrieve current resolution - Vector2 resolution(0.0f, 0.0f); - for (auto& pipeline : activePipelines) - { - ViewPtr pipelineView = pipeline->GetDefaultView(); - if (pipelineView.get() == this) - { - RPI::SwapChainPass* pass = AZ::RPI::PassSystemInterface::Get()->FindSwapChainPass(pipeline->GetWindowHandle()); - if (pass) - { - const RHI::Viewport& viewport = pass->GetViewport(); - resolution.SetX(viewport.m_maxX); - resolution.SetY(viewport.m_maxY); - } - break; - } - } - - // calculate culling resolution based on required tile size for MaskedOcclusionCulling - static const uint32_t MaskedOcclusionCullingSubTileWidth = 8; - static const uint32_t MaskedOcclusionCullingSubTileHeight = 4; - - uint32_t cullingWidth = RHI::AlignUp(resolution.GetX(), MaskedOcclusionCullingSubTileWidth); - uint32_t cullingHeight = RHI::AlignUp(resolution.GetY(), MaskedOcclusionCullingSubTileHeight); - - m_maskedOcclusionCulling->SetResolution(cullingWidth, cullingHeight); - - if (cullingWidth > 0 && cullingHeight > 0) - { - m_maskedOcclusionCulling->ClearBuffer(); - } + m_maskedOcclusionCulling->ClearBuffer(); } MaskedOcclusionCulling* View::GetMaskedOcclusionCulling() { - if (m_maskedOcclusionCulling) - { - uint32_t width = 0; - uint32_t height = 0; - - m_maskedOcclusionCulling->GetResolution(width, height); - if (width > 0 && height > 0) - { - return m_maskedOcclusionCulling; - } - } - - return nullptr; + return m_maskedOcclusionCulling; } } // namespace RPI From e556cdbba5f7dce65e3f7c47f538f7b30bc499a5 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 11:54:12 +0100 Subject: [PATCH 299/811] update scriptcanvas to handle uniform scale on transform --- .../Code/Include/ScriptCanvas/Core/Datum.cpp | 6 ++--- .../Libraries/Math/TransformNodes.h | 22 +++++++++---------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp index a0db02c3a8..30e55cee49 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp @@ -2527,15 +2527,15 @@ namespace ScriptCanvas { Data::TransformType copy(source); AZ::Vector3 pos = copy.GetTranslation(); - AZ::Vector3 scale = copy.ExtractScale(); + float scale = copy.ExtractUniformScale(); AZ::Vector3 rotation = AZ::ConvertTransformToEulerDegrees(copy); return AZStd::string::format ( "(Position: X: %f, Y: %f, Z: %f," " Rotation: X: %f, Y: %f, Z: %f," - " Scale: X: %f, Y: %f, Z: %f)" + " Scale: %f)" , static_cast(pos.GetX()), static_cast(pos.GetY()), static_cast(pos.GetZ()) , static_cast(rotation.GetX()), static_cast(rotation.GetY()), static_cast(rotation.GetZ()) - , static_cast(scale.GetX()), static_cast(scale.GetY()), static_cast(scale.GetZ())); + , scale); } AZStd::string Datum::ToStringVector2(const AZ::Vector2& source) const diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h index 6a0f082272..292827310b 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h @@ -26,12 +26,12 @@ namespace ScriptCanvas using namespace MathNodeUtilities; static const char* k_categoryName = "Math/Transform"; - AZ_INLINE std::tuple ExtractScale(TransformType source) + AZ_INLINE std::tuple ExtractUniformScale(TransformType source) { - auto scale(source.ExtractScale()); + auto scale(source.ExtractUniformScale()); return std::make_tuple( scale, source ); } - SCRIPT_CANVAS_GENERIC_FUNCTION_MULTI_RESULTS_NODE(ExtractScale, k_categoryName, "{8DFE5247-0950-4CD1-87E6-0CAAD42F1637}", "returns a vector which is the length of the scale components, and a transform with the scale extracted ", "Source", "Scale", "Extracted"); + SCRIPT_CANVAS_GENERIC_FUNCTION_MULTI_RESULTS_NODE(ExtractUniformScale, k_categoryName, "{8DFE5247-0950-4CD1-87E6-0CAAD42F1637}", "returns the uniform scale as a float, and a transform with the scale extracted ", "Source", "Uniform Scale", "Extracted"); AZ_INLINE TransformType FromMatrix3x3(Matrix3x3Type source) { @@ -145,12 +145,12 @@ namespace ScriptCanvas } SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(Multiply3x3ByVector3, k_categoryName, "{4F2ABFC6-2E93-4A9D-8639-C7967DB318DB}", "returns Source's 3x3 upper matrix post multiplied by Multiplier", "Source", "Multiplier"); - AZ_INLINE TransformType MultiplyByScale(TransformType source, Vector3Type scale) + AZ_INLINE TransformType MultiplyByUniformScale(TransformType source, NumberType scale) { - source.MultiplyByScale(scale); + source.MultiplyByUniformScale(scale); return source; } - SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(MultiplyByScale, k_categoryName, "{90472D62-65A8-40C1-AB08-FA66D793F689}", "returns Source multiplied by the scale matrix produced by Scale", "Source", "Scale"); + SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(MultiplyByUniformScale, k_categoryName, "{90472D62-65A8-40C1-AB08-FA66D793F689}", "returns Source multiplied uniformly by Scale", "Source", "Scale"); AZ_INLINE TransformType MultiplyByTransform(const TransformType& a, const TransformType& b) { @@ -194,16 +194,16 @@ namespace ScriptCanvas } SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(RotationZDegrees, k_categoryName, "{F848306A-C07C-4586-B52F-BEEE489045D2}", "returns a transform representing a rotation Degrees around the Z-Axis", "Degrees"); - AZ_INLINE Vector3Type ToScale(const TransformType& source) + AZ_INLINE NumberType ToScale(const TransformType& source) { - return source.GetScale(); + return source.GetUniformScale(); } - SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(ToScale, k_categoryName, "{063C58AD-F567-464D-A432-F298FE3953A6}", "returns the scale part of the Source, the length of the scale components", "Source"); + SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(ToScale, k_categoryName, "{063C58AD-F567-464D-A432-F298FE3953A6}", "returns the uniform scale of the Source", "Source"); using Registrar = RegistrarGeneric < #if ENABLE_EXTENDED_MATH_SUPPORT - ExtractScaleNode , + ExtractUniformScaleNode , #endif FromMatrix3x3AndTranslationNode , FromMatrix3x3Node @@ -230,7 +230,7 @@ namespace ScriptCanvas , Multiply3x3ByVector3Node #endif - , MultiplyByScaleNode + , MultiplyByUniformScaleNode , MultiplyByTransformNode , MultiplyByVector3Node , MultiplyByVector4Node From b2513cbb51732ba0d42909808215833e35b16530 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 12:05:03 +0100 Subject: [PATCH 300/811] update one more vector scale usage in scriptcanvas --- .../Include/ScriptCanvas/Libraries/Math/TransformNodes.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h index 292827310b..9e66c6c6fc 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h @@ -57,11 +57,11 @@ namespace ScriptCanvas } SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(FromRotationAndTranslation, k_categoryName, "{99A4D55D-6EFB-4E24-8113-F5B46DE3A194}", "returns a transform from the rotation and the translation", "Rotation", "Translation"); - AZ_INLINE TransformType FromScale(Vector3Type scale) + AZ_INLINE TransformType FromScale(NumberType scale) { - return TransformType::CreateScale(scale); + return TransformType::CreateUniformScale(scale); } - SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(FromScale, k_categoryName, "{4B6454BC-015C-41BB-9C78-34ADBCF70187}", "returns a scale matrix and the translation set to zero", "Scale"); + SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(FromScale, k_categoryName, "{4B6454BC-015C-41BB-9C78-34ADBCF70187}", "returns a transform which applies the specified uniform Scale, but no rotation or translation", "Scale"); AZ_INLINE TransformType FromTranslation(Vector3Type translation) { From c9f7cd03bb122190650094412d637336ec5a4569 Mon Sep 17 00:00:00 2001 From: Aaron Ruiz Mora Date: Fri, 28 May 2021 12:26:53 +0100 Subject: [PATCH 301/811] Limit convex and primitive methods of export physx asset to one material --- Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp b/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp index 3aeb3ad797..56042fbc91 100644 --- a/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp +++ b/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp @@ -794,6 +794,9 @@ namespace PhysX ); } + // Convex and primitive methods can only have 1 material + const bool limitToOneMaterial = pxMeshGroup.GetExportAsConvex() || pxMeshGroup.GetExportAsPrimitive(); + for (AZ::u32 faceIndex = 0; faceIndex < faceCount; ++faceIndex) { AZStd::string materialName = DefaultMaterialName; @@ -810,6 +813,14 @@ namespace PhysX } materialName = localFbxMaterialsList[materialId]; + + // Keep using the first material when it has to be limited to one. + if (limitToOneMaterial && + assetMaterialData.m_fbxMaterialNames.size() == 1 && + assetMaterialData.m_fbxMaterialNames[0] != materialName) + { + materialName = assetMaterialData.m_fbxMaterialNames[0]; + } } const AZ::SceneAPI::DataTypes::IMeshData::Face& face = nodeMesh->GetFaceInfo(faceIndex); From e1b9c4f22e7ad1a7a1cacf2f8025d50325ae3b1b Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 13:44:12 +0100 Subject: [PATCH 302/811] remove some vector scale functions from Transform --- Code/Framework/AzCore/AzCore/Math/Transform.cpp | 3 --- Code/Framework/AzCore/AzCore/Math/Transform.h | 4 ---- Code/Framework/AzCore/AzCore/Math/Transform.inl | 14 -------------- .../EditorNonUniformScaleComponentMode.cpp | 2 +- 4 files changed, 1 insertion(+), 22 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.cpp b/Code/Framework/AzCore/AzCore/Math/Transform.cpp index 9090a9e94e..12f8e426cd 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.cpp +++ b/Code/Framework/AzCore/AzCore/Math/Transform.cpp @@ -287,11 +287,8 @@ namespace AZ Method("GetUniformScale", &Transform::GetUniformScale)-> Method("SetScale", &Transform::SetScale)-> Method("SetUniformScale", &Transform::SetUniformScale)-> - Method("ExtractScale", &Transform::ExtractScale)-> - Attribute(Script::Attributes::ExcludeFrom, Script::Attributes::ExcludeFlags::All)-> Method("ExtractUniformScale", &Transform::ExtractUniformScale)-> Attribute(Script::Attributes::ExcludeFrom, Script::Attributes::ExcludeFlags::All)-> - Method("MultiplyByScale", &Transform::MultiplyByScale)-> Method("MultiplyByUniformScale", &Transform::MultiplyByUniformScale)-> Method("GetInverse", &Transform::GetInverse)-> Method("Invert", &Transform::Invert)-> diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.h b/Code/Framework/AzCore/AzCore/Math/Transform.h index 7ae86edd89..e8c4325c7a 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.h +++ b/Code/Framework/AzCore/AzCore/Math/Transform.h @@ -127,13 +127,9 @@ namespace AZ void SetScale(const Vector3& v); void SetUniformScale(const float scale); - //! Sets the transform's scale to a unit value and returns the previous scale value. - Vector3 ExtractScale(); - //! Sets the transform's scale to a unit value and returns the previous scale value. float ExtractUniformScale(); - void MultiplyByScale(const AZ::Vector3& scale); void MultiplyByUniformScale(float scale); Transform operator*(const Transform& rhs) const; diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.inl b/Code/Framework/AzCore/AzCore/Math/Transform.inl index a7d5e72749..7550e2bdd8 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.inl +++ b/Code/Framework/AzCore/AzCore/Math/Transform.inl @@ -182,14 +182,6 @@ namespace AZ m_scale = Vector3(scale); } - AZ_MATH_INLINE Vector3 Transform::ExtractScale() - { - AZ_WarningOnce("Transform", false, "ExtractScale is deprecated, please use ExtractUniformScale instead."); - const Vector3 scale = m_scale; - m_scale = Vector3::CreateOne(); - return scale; - } - AZ_MATH_INLINE float Transform::ExtractUniformScale() { const float scale = m_scale.GetMaxElement(); @@ -197,12 +189,6 @@ namespace AZ return scale; } - AZ_MATH_INLINE void Transform::MultiplyByScale(const Vector3& scale) - { - AZ_WarningOnce("Transform", false, "MultiplyByScale is deprecated, please use MultiplyByUniformScale instead."); - m_scale *= scale; - } - AZ_MATH_INLINE void Transform::MultiplyByUniformScale(float scale) { m_scale *= scale; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponentMode.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponentMode.cpp index 97e27ac748..497bcf15d7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponentMode.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponentMode.cpp @@ -28,7 +28,7 @@ namespace AzToolsFramework AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); AZ::TransformBus::EventResult(worldFromLocal, m_entityComponentIdPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); - worldFromLocal.ExtractScale(); + worldFromLocal.ExtractUniformScale(); m_manipulators = AZStd::make_unique(worldFromLocal); m_manipulators->Register(g_mainManipulatorManagerId); m_manipulators->SetAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ()); From d73566565e768cd2dacc595d72c8f81fa34f32bc Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 14:18:26 +0100 Subject: [PATCH 303/811] remove most vector scale functions from transform bus --- .../AzCore/AzCore/Component/TransformBus.h | 11 ++--------- .../AzFramework/Components/TransformComponent.cpp | 15 +-------------- .../AzFramework/Components/TransformComponent.h | 2 -- .../ToolsComponents/TransformComponent.cpp | 12 +----------- .../ToolsComponents/TransformComponent.h | 2 -- .../SliceStabilityTestFramework.cpp | 2 +- .../Editor/TrackView/TrackViewAnimNode.cpp | 6 +++--- .../EditorReflectionProbeComponent.cpp | 4 ++-- Gems/Blast/Code/Tests/Mocks/BlastMocks.h | 2 -- Gems/PhysX/Code/Source/Utils.cpp | 6 +++--- 10 files changed, 13 insertions(+), 49 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Component/TransformBus.h b/Code/Framework/AzCore/AzCore/Component/TransformBus.h index b180e97332..2a8d82c34c 100644 --- a/Code/Framework/AzCore/AzCore/Component/TransformBus.h +++ b/Code/Framework/AzCore/AzCore/Component/TransformBus.h @@ -219,18 +219,11 @@ namespace AZ //! Scale modifiers //! @{ - //! Set local scale of the transform. - //! @param scale The new scale to set. - virtual void SetLocalScale([[maybe_unused]] const AZ::Vector3& scale) {} - - //! Get the scale value in local space. + //! @deprecated GetLocalScale is deprecated, and is left only to allow migration of legacy vector scale. + //! Get the legacy vector scale value in local space. //! @return The scale value in local space. virtual AZ::Vector3 GetLocalScale() { return AZ::Vector3(FLT_MAX); } - //! Get the scale value in world space. - //! @return The scale value in world space. - virtual AZ::Vector3 GetWorldScale() { return AZ::Vector3(FLT_MAX); } - //! Set the uniform scale value in local space. virtual void SetLocalUniformScale([[maybe_unused]] float scale) {} diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp index 3fd5c4d81c..ef2816d355 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp @@ -406,23 +406,12 @@ namespace AzFramework return m_localTM.GetRotation(); } - void TransformComponent::SetLocalScale(const AZ::Vector3& scale) - { - AZ::Transform newLocalTM = m_localTM; - newLocalTM.SetScale(scale); - SetLocalTM(newLocalTM); - } - AZ::Vector3 TransformComponent::GetLocalScale() { + AZ_WarningOnce("TransformComponent", false, "GetLocalScale is deprecated, please use GetLocalUniformScale instead"); return m_localTM.GetScale(); } - AZ::Vector3 TransformComponent::GetWorldScale() - { - return m_worldTM.GetScale(); - } - void TransformComponent::SetLocalUniformScale(float scale) { AZ::Transform newLocalTM = m_localTM; @@ -756,13 +745,11 @@ namespace AzFramework ->Event("GetLocalRotationQuaternion", &AZ::TransformBus::Events::GetLocalRotationQuaternion) ->Attribute("Rotation", AZ::Edit::Attributes::PropertyRotation) ->VirtualProperty("Rotation", "GetLocalRotationQuaternion", "SetLocalRotationQuaternion") - ->Event("SetLocalScale", &AZ::TransformBus::Events::SetLocalScale) ->Event("GetLocalScale", &AZ::TransformBus::Events::GetLocalScale) ->Attribute("Scale", AZ::Edit::Attributes::PropertyScale) ->Event("SetLocalUniformScale", &AZ::TransformBus::Events::SetLocalUniformScale) ->Event("GetLocalUniformScale", &AZ::TransformBus::Events::GetLocalUniformScale) ->VirtualProperty("Uniform Scale", "GetLocalUniformScale", "SetLocalUniformScale") - ->Event("GetWorldScale", &AZ::TransformBus::Events::GetWorldScale) ->Event("GetChildren", &AZ::TransformBus::Events::GetChildren) ->Event("GetAllDescendants", &AZ::TransformBus::Events::GetAllDescendants) ->Event("GetEntityAndAllDescendants", &AZ::TransformBus::Events::GetEntityAndAllDescendants) diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h index 9009c6bff9..0301334a0d 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h @@ -128,9 +128,7 @@ namespace AzFramework AZ::Quaternion GetLocalRotationQuaternion() override; // Scale Modifiers - void SetLocalScale(const AZ::Vector3& scale) override; AZ::Vector3 GetLocalScale() override; - AZ::Vector3 GetWorldScale() override; void SetLocalUniformScale(float scale) override; float GetLocalUniformScale() override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index 285d962b46..631478fcb0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -599,22 +599,12 @@ namespace AzToolsFramework return result; } - void TransformComponent::SetLocalScale(const AZ::Vector3& scale) - { - m_editorTransform.m_scale = scale; - TransformChanged(); - } - AZ::Vector3 TransformComponent::GetLocalScale() { + AZ_WarningOnce("TransformComponent", false, "GetLocalScale is deprecated, please use GetLocalUniformScale instead"); return m_editorTransform.m_scale; } - AZ::Vector3 TransformComponent::GetWorldScale() - { - return GetWorldTM().GetScale(); - } - void TransformComponent::SetLocalUniformScale(float scale) { m_editorTransform.m_scale = AZ::Vector3(scale); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h index f772b608c1..80db5e10fb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h @@ -115,9 +115,7 @@ namespace AzToolsFramework AZ::Quaternion GetLocalRotationQuaternion() override; // Scale Modifiers - void SetLocalScale(const AZ::Vector3& scale) override; AZ::Vector3 GetLocalScale() override; - AZ::Vector3 GetWorldScale() override; void SetLocalUniformScale(float scale) override; float GetLocalUniformScale() override; diff --git a/Code/Framework/AzToolsFramework/Tests/SliceStabilityTests/SliceStabilityTestFramework.cpp b/Code/Framework/AzToolsFramework/Tests/SliceStabilityTests/SliceStabilityTestFramework.cpp index 8455e6d669..5dcdaa045c 100644 --- a/Code/Framework/AzToolsFramework/Tests/SliceStabilityTests/SliceStabilityTestFramework.cpp +++ b/Code/Framework/AzToolsFramework/Tests/SliceStabilityTests/SliceStabilityTestFramework.cpp @@ -141,7 +141,7 @@ namespace UnitTest // Set the new entity's transform to non zero values // This helps validate in comparison tests that the transform values of created entities persist during slice operations - entityTransform->SetLocalScale(AZ::Vector3(5, 5, 5)); + entityTransform->SetLocalUniformScale(5); entityTransform->SetLocalRotation(AZ::Vector3RadToDeg(AZ::Vector3(90, 90, 90))); entityTransform->SetLocalTranslation(AZ::Vector3(100, 100, 100)); diff --git a/Code/Sandbox/Editor/TrackView/TrackViewAnimNode.cpp b/Code/Sandbox/Editor/TrackView/TrackViewAnimNode.cpp index ae7077b4fc..35306b9535 100644 --- a/Code/Sandbox/Editor/TrackView/TrackViewAnimNode.cpp +++ b/Code/Sandbox/Editor/TrackView/TrackViewAnimNode.cpp @@ -2012,9 +2012,9 @@ void CTrackViewAnimNode::SetPosRotScaleTracksDefaultValues(bool positionAllowed, } if (scaleAllowed) { - AZ::Vector3 scale = AZ::Vector3::CreateOne(); - AZ::TransformBus::EventResult(scale, entityId, &AZ::TransformBus::Events::GetWorldScale); - m_animNode->SetScale(time, AZVec3ToLYVec3(scale)); + float scale = 1.0f; + AZ::TransformBus::EventResult(scale, entityId, &AZ::TransformBus::Events::GetWorldUniformScale); + m_animNode->SetScale(time, Vec3(scale, scale, scale)); } } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp index 735eab5368..7880d5e88c 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp @@ -209,8 +209,8 @@ namespace AZ AZ::Vector3 position = AZ::Vector3::CreateZero(); AZ::TransformBus::EventResult(position, GetEntityId(), &AZ::TransformBus::Events::GetWorldTranslation); - AZ::Vector3 scale = AZ::Vector3::CreateOne(); - AZ::TransformBus::EventResult(scale, GetEntityId(), &AZ::TransformBus::Events::GetLocalScale); + float scale = 1.0f; + AZ::TransformBus::EventResult(scale, GetEntityId(), &AZ::TransformBus::Events::GetLocalUniformScale); // draw AABB at probe position using the inner dimensions Color color(0.0f, 0.0f, 1.0f, 1.0f); diff --git a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h index 00aa12cb84..ca78623a8a 100644 --- a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h +++ b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h @@ -654,9 +654,7 @@ namespace Blast MOCK_METHOD1(RotateAroundLocalZ, void(float)); MOCK_METHOD0(GetLocalRotation, AZ::Vector3()); MOCK_METHOD0(GetLocalRotationQuaternion, AZ::Quaternion()); - MOCK_METHOD1(SetLocalScale, void(const AZ::Vector3&)); MOCK_METHOD0(GetLocalScale, AZ::Vector3()); - MOCK_METHOD0(GetWorldScale, AZ::Vector3()); MOCK_METHOD1(SetLocalUniformScale, void(float)); MOCK_METHOD0(GetLocalUniformScale, float()); MOCK_METHOD0(GetWorldUniformScale, float()); diff --git a/Gems/PhysX/Code/Source/Utils.cpp b/Gems/PhysX/Code/Source/Utils.cpp index 55be7c92f7..a85a80e573 100644 --- a/Gems/PhysX/Code/Source/Utils.cpp +++ b/Gems/PhysX/Code/Source/Utils.cpp @@ -920,9 +920,9 @@ namespace PhysX AZ::Vector3 GetTransformScale(AZ::EntityId entityId) { - AZ::Vector3 worldScale = AZ::Vector3::CreateOne(); - AZ::TransformBus::EventResult(worldScale, entityId, &AZ::TransformBus::Events::GetWorldScale); - return worldScale; + float worldUniformScale = 1.0f; + AZ::TransformBus::EventResult(worldUniformScale, entityId, &AZ::TransformBus::Events::GetWorldUniformScale); + return AZ::Vector3(worldUniformScale); } AZ::Vector3 GetUniformScale(AZ::EntityId entityId) From 36ceff84c9fd6ce9a4dacd4d2543f7ef7bcd4293 Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Fri, 28 May 2021 14:37:17 +0100 Subject: [PATCH 304/811] Support mesh intersection for camera orbit (#982) * wip support for mesh intersection with intersector bus * WIP camera mesh intersection orbit logic * remove unneeded template argument * add bus connect/disconnect * fix intersection logic * small updates, additional comments, some tidy-up * update formatting options slightly * use aznumeric_cast * temp workaround for negative distances with RayIntersection --- .clang-format | 2 +- .../Render/GeometryIntersectionBus.h | 7 +- .../AzFramework/Viewport/CameraInput.cpp | 60 +++++++---- .../AzFramework/Viewport/CameraInput.h | 26 +++-- Code/Sandbox/Editor/EditorViewportWidget.cpp | 101 +++++++++++------- .../Code/Source/Mesh/EditorMeshComponent.h | 3 +- .../Code/Source/Mesh/MeshComponent.h | 3 +- .../Source/Mesh/MeshComponentController.cpp | 73 ++++++++++--- .../Source/Mesh/MeshComponentController.h | 16 +-- 9 files changed, 191 insertions(+), 100 deletions(-) diff --git a/.clang-format b/.clang-format index 565f28130e..04e0284f97 100644 --- a/.clang-format +++ b/.clang-format @@ -46,7 +46,7 @@ SortIncludes: true SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: false SpaceBeforeAssignmentOperators: true -SpaceBeforeCpp11BracedList: true +SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements diff --git a/Code/Framework/AzFramework/AzFramework/Render/GeometryIntersectionBus.h b/Code/Framework/AzFramework/AzFramework/Render/GeometryIntersectionBus.h index ba1d2d1e06..749f457286 100644 --- a/Code/Framework/AzFramework/AzFramework/Render/GeometryIntersectionBus.h +++ b/Code/Framework/AzFramework/AzFramework/Render/GeometryIntersectionBus.h @@ -12,6 +12,7 @@ #pragma once #include +#include #include namespace AzFramework @@ -35,12 +36,12 @@ namespace AzFramework AzFramework::EntityContextId m_contextId; }; - //! Interface for intersection requests, implement this interface for making your component - //! render geometry intersectable. + //! Interface for intersection requests. + //! Implement this interface to make your component 'intersectable'. class IntersectionRequests : public AZ::EBusTraits { - //! Policy for notifying the Intersector bus of entities connected/disconnected to this ebus + //! Policy for notifying the Intersector bus of entities connected/disconnected to this EBus //! so it updates the internal data of the entities template struct IntersectionRequestsConnectionPolicy diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index e4833ccb3c..d5f02c957c 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -144,7 +144,7 @@ namespace AzFramework z = AZStd::atan2(-orientation.GetElement(1, 2), orientation.GetElement(1, 1)); } - return {x, y, z}; + return { x, y, z }; } void UpdateCameraFromTransform(Camera& camera, const AZ::Transform& transform) @@ -179,7 +179,7 @@ namespace AzFramework { const auto nextCamera = m_cameras.StepCamera(targetCamera, m_motionDelta, m_scrollDelta, deltaTime); - m_motionDelta = ScreenVector{0, 0}; + m_motionDelta = ScreenVector{ 0, 0 }; m_scrollDelta = 0.0f; return nextCamera; @@ -213,7 +213,10 @@ namespace AzFramework auto& cameraInput = m_idleCameraInputs[i]; const bool canBegin = cameraInput->Beginning() && AZStd::all_of(m_activeCameraInputs.cbegin(), m_activeCameraInputs.cend(), - [](const auto& input) { return !input->Exclusive(); }) && + [](const auto& input) + { + return !input->Exclusive(); + }) && (!cameraInput->Exclusive() || (cameraInput->Exclusive() && m_activeCameraInputs.empty())); if (canBegin) @@ -231,7 +234,8 @@ namespace AzFramework const Camera nextCamera = AZStd::accumulate( AZStd::begin(m_activeCameraInputs), AZStd::end(m_activeCameraInputs), targetCamera, - [cursorDelta, scrollDelta, deltaTime](Camera acc, auto& camera) { + [cursorDelta, scrollDelta, deltaTime](Camera acc, auto& camera) + { acc = camera->StepCamera(acc, cursorDelta, scrollDelta, deltaTime); return acc; }); @@ -284,7 +288,8 @@ namespace AzFramework bool RotateCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { - const ClickDetector::ClickEvent clickEvent = [&event, this] { + const ClickDetector::ClickEvent clickEvent = [&event, this] + { if (const auto& input = AZStd::get_if(&event)) { if (input->m_channelId == m_rotateChannelId) @@ -330,7 +335,10 @@ namespace AzFramework nextCamera.m_pitch -= float(cursorDelta.m_y) * ed_cameraSystemRotateSpeed; nextCamera.m_yaw -= float(cursorDelta.m_x) * ed_cameraSystemRotateSpeed; - const auto clampRotation = [](const float angle) { return AZStd::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; + const auto clampRotation = [](const float angle) + { + return AZStd::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); + }; nextCamera.m_yaw = clampRotation(nextCamera.m_yaw); // clamp pitch to be +-90 degrees @@ -377,9 +385,10 @@ namespace AzFramework const auto deltaPanX = float(cursorDelta.m_x) * panAxes.m_horizontalAxis * ed_cameraSystemPanSpeed; const auto deltaPanY = float(cursorDelta.m_y) * panAxes.m_verticalAxis * ed_cameraSystemPanSpeed; - const auto inv = [](const bool invert) { - constexpr float Dir[] = {1.0f, -1.0f}; - return Dir[static_cast(invert)]; + const auto inv = [](const bool invert) + { + constexpr float Dir[] = { 1.0f, -1.0f }; + return Dir[aznumeric_cast(invert)]; }; nextCamera.m_lookAt += deltaPanX * inv(ed_cameraSystemPanInvertX); @@ -475,7 +484,8 @@ namespace AzFramework const auto axisY = translationBasis.GetBasisY(); const auto axisZ = translationBasis.GetBasisZ(); - const float speed = [boost = m_boost]() { + const float speed = [boost = m_boost]() + { return ed_cameraSystemTranslateSpeed * (boost ? ed_cameraSystemBoostMultiplier : 1.0f); }(); @@ -555,10 +565,12 @@ namespace AzFramework if (Beginning()) { - const auto hasLookAt = [&nextCamera, &targetCamera, &lookAtFn = m_lookAtFn] { + const auto hasLookAt = [&nextCamera, &targetCamera, &lookAtFn = m_lookAtFn] + { if (lookAtFn) { - if (const auto lookAt = lookAtFn()) + // pass through the camera's position and look vector for use in the lookAt function + if (const auto lookAt = lookAtFn(targetCamera.Translation(), targetCamera.Rotation().GetBasisY())) { auto transform = AZ::Transform::CreateLookAt(targetCamera.m_lookAt, *lookAt); nextCamera.m_lookDist = -lookAt->GetDistance(targetCamera.m_lookAt); @@ -692,14 +704,20 @@ namespace AzFramework Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, const float deltaTime) { - const auto clamp_rotation = [](const float angle) { return AZStd::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; + const auto clamp_rotation = [](const float angle) + { + return AZStd::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); + }; // keep yaw in 0 - 360 range float targetYaw = clamp_rotation(targetCamera.m_yaw); const float currentYaw = clamp_rotation(currentCamera.m_yaw); // return the sign of the float input (-1, 0, 1) - const auto sign = [](const float value) { return aznumeric_cast((0.0f < value) - (value < 0.0f)); }; + const auto sign = [](const float value) + { + return aznumeric_cast((0.0f < value) - (value < 0.0f)); + }; // ensure smooth transition when moving across 0 - 360 boundary const float yawDelta = targetYaw - currentYaw; @@ -727,26 +745,28 @@ namespace AzFramework const auto& inputChannelId = inputChannel.GetInputChannelId(); const auto& inputDeviceId = inputChannel.GetInputDevice().GetInputDeviceId(); - const bool wasMouseButton = - AZStd::any_of(InputDeviceMouse::Button::All.begin(), InputDeviceMouse::Button::All.end(), [inputChannelId](const auto& button) { + const bool wasMouseButton = AZStd::any_of( + InputDeviceMouse::Button::All.begin(), InputDeviceMouse::Button::All.end(), + [inputChannelId](const auto& button) + { return button == inputChannelId; }); if (inputChannelId == InputDeviceMouse::Movement::X) { - return HorizontalMotionEvent{(int)inputChannel.GetValue()}; + return HorizontalMotionEvent{ aznumeric_cast(inputChannel.GetValue()) }; } else if (inputChannelId == InputDeviceMouse::Movement::Y) { - return VerticalMotionEvent{(int)inputChannel.GetValue()}; + return VerticalMotionEvent{ aznumeric_cast(inputChannel.GetValue()) }; } else if (inputChannelId == InputDeviceMouse::Movement::Z) { - return ScrollEvent{inputChannel.GetValue()}; + return ScrollEvent{ inputChannel.GetValue() }; } else if (wasMouseButton || InputDeviceKeyboard::IsKeyboardDevice(inputDeviceId)) { - return DiscreteInputEvent{inputChannelId, inputChannel.GetState()}; + return DiscreteInputEvent{ inputChannelId, inputChannel.GetState() }; } return AZStd::monostate{}; diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index ec70fc00de..a02f796899 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -34,9 +34,9 @@ namespace AzFramework AZ::Vector3 m_lookAt = AZ::Vector3::CreateZero(); //!< Position of camera when m_lookDist is zero, //!< or position of m_lookAt when m_lookDist is greater //!< than zero. - float m_yaw{0.0}; - float m_pitch{0.0}; - float m_lookDist{0.0}; //!< Zero gives first person free look, otherwise orbit about m_lookAt + float m_yaw{ 0.0 }; + float m_pitch{ 0.0 }; + float m_lookDist{ 0.0 }; //!< Zero gives first person free look, otherwise orbit about m_lookAt //! View camera transform (v in MVP). AZ::Transform View() const; @@ -195,7 +195,11 @@ namespace AzFramework inline bool Cameras::Exclusive() const { return AZStd::any_of( - m_activeCameraInputs.begin(), m_activeCameraInputs.end(), [](const auto& cameraInput) { return cameraInput->Exclusive(); }); + m_activeCameraInputs.begin(), m_activeCameraInputs.end(), + [](const auto& cameraInput) + { + return cameraInput->Exclusive(); + }); } //! Responsible for updating a series of cameras given various inputs. @@ -209,7 +213,7 @@ namespace AzFramework private: ScreenVector m_motionDelta; //!< The delta used for look/orbit/pan (rotation + translation) - two dimensional. - float m_scrollDelta = 0.0f; //!< The delta used for dolly/movement (translation) - one dimensional. + float m_scrollDelta = 0.0f; //!< The delta used for dolly/movement (translation) - one dimensional. }; class RotateCameraInput : public CameraInput @@ -237,7 +241,7 @@ namespace AzFramework inline PanAxes LookPan(const Camera& camera) { const AZ::Matrix3x3 orientation = camera.Rotation(); - return {orientation.GetBasisX(), orientation.GetBasisZ()}; + return { orientation.GetBasisX(), orientation.GetBasisZ() }; } inline PanAxes OrbitPan(const Camera& camera) @@ -245,12 +249,13 @@ namespace AzFramework const AZ::Matrix3x3 orientation = camera.Rotation(); const auto basisX = orientation.GetBasisX(); - const auto basisY = [&orientation] { + const auto basisY = [&orientation] + { const auto forward = orientation.GetBasisY(); return AZ::Vector3(forward.GetX(), forward.GetY(), 0.0f).GetNormalized(); }(); - return {basisX, basisY}; + return { basisX, basisY }; } class PanCameraInput : public CameraInput @@ -285,7 +290,8 @@ namespace AzFramework const AZ::Matrix3x3 orientation = camera.Rotation(); const auto basisX = orientation.GetBasisX(); - const auto basisY = [&orientation] { + const auto basisY = [&orientation] + { const auto forward = orientation.GetBasisY(); return AZ::Vector3(forward.GetX(), forward.GetY(), 0.0f).GetNormalized(); }(); @@ -398,7 +404,7 @@ namespace AzFramework class OrbitCameraInput : public CameraInput { public: - using LookAtFn = AZStd::function()>; + using LookAtFn = AZStd::function(const AZ::Vector3& position, const AZ::Vector3& direction)>; // CameraInput overrides ... bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index ecd11da817..989d6e407d 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -1221,50 +1221,73 @@ void EditorViewportWidget::SetViewportId(int id) AzFramework::ReloadCameraKeyBindings(); auto controller = AZStd::make_shared(); - controller->SetCameraListBuilderCallback([](AzFramework::Cameras& cameras) - { - auto firstPersonRotateCamera = AZStd::make_shared(AzFramework::CameraFreeLookButton); - auto firstPersonPanCamera = - AZStd::make_shared(AzFramework::CameraFreePanButton, AzFramework::LookPan); - auto firstPersonTranslateCamera = AZStd::make_shared(AzFramework::LookTranslation); - auto firstPersonWheelCamera = AZStd::make_shared(); + controller->SetCameraListBuilderCallback( + [](AzFramework::Cameras& cameras) + { + auto firstPersonRotateCamera = AZStd::make_shared(AzFramework::CameraFreeLookButton); + auto firstPersonPanCamera = + AZStd::make_shared(AzFramework::CameraFreePanButton, AzFramework::LookPan); + auto firstPersonTranslateCamera = AZStd::make_shared(AzFramework::LookTranslation); + auto firstPersonWheelCamera = AZStd::make_shared(); - auto orbitCamera = AZStd::make_shared(); - orbitCamera->SetLookAtFn([]() -> AZStd::optional { - AZStd::optional manipulatorTransform; - AzToolsFramework::EditorTransformComponentSelectionRequestBus::EventResult( - manipulatorTransform, AzToolsFramework::GetEntityContextId(), - &AzToolsFramework::EditorTransformComponentSelectionRequestBus::Events::GetManipulatorTransform); + auto orbitCamera = AZStd::make_shared(); + orbitCamera->SetLookAtFn( + [](const AZ::Vector3& position, const AZ::Vector3& direction) -> AZStd::optional + { + AZStd::optional manipulatorTransform; + AzToolsFramework::EditorTransformComponentSelectionRequestBus::EventResult( + manipulatorTransform, AzToolsFramework::GetEntityContextId(), + &AzToolsFramework::EditorTransformComponentSelectionRequestBus::Events::GetManipulatorTransform); - if (manipulatorTransform) - { - return manipulatorTransform->GetTranslation(); - } + // initially attempt to use manipulator transform if one exists (there is a selection) + if (manipulatorTransform) + { + return manipulatorTransform->GetTranslation(); + } - return {}; + const float RayDistance = 1000.0f; + AzFramework::RenderGeometry::RayRequest ray; + ray.m_startWorldPosition = position; + ray.m_endWorldPosition = position + direction * RayDistance; + ray.m_onlyVisible = true; + + AzFramework::RenderGeometry::RayResult renderGeometryIntersectionResult; + AzFramework::RenderGeometry::IntersectorBus::EventResult( + renderGeometryIntersectionResult, AzToolsFramework::GetEntityContextId(), + &AzFramework::RenderGeometry::IntersectorInterface::RayIntersect, ray); + + // attempt a ray intersection with any visible mesh and return the intersection position if successful + if (renderGeometryIntersectionResult) + { + return renderGeometryIntersectionResult.m_worldPosition; + } + + // if there is no selection or no intersection, fallback to default camera orbit behavior (ground plane + // intersection) + return {}; + }); + + auto orbitRotateCamera = AZStd::make_shared(AzFramework::CameraOrbitLookButton); + auto orbitTranslateCamera = AZStd::make_shared(AzFramework::OrbitTranslation); + auto orbitDollyWheelCamera = AZStd::make_shared(); + auto orbitDollyMoveCamera = + AZStd::make_shared(AzFramework::CameraOrbitDollyButton); + auto orbitPanCamera = + AZStd::make_shared(AzFramework::CameraOrbitPanButton, AzFramework::OrbitPan); + + orbitCamera->m_orbitCameras.AddCamera(orbitRotateCamera); + orbitCamera->m_orbitCameras.AddCamera(orbitTranslateCamera); + orbitCamera->m_orbitCameras.AddCamera(orbitDollyWheelCamera); + orbitCamera->m_orbitCameras.AddCamera(orbitDollyMoveCamera); + orbitCamera->m_orbitCameras.AddCamera(orbitPanCamera); + + cameras.AddCamera(firstPersonRotateCamera); + cameras.AddCamera(firstPersonPanCamera); + cameras.AddCamera(firstPersonTranslateCamera); + cameras.AddCamera(firstPersonWheelCamera); + cameras.AddCamera(orbitCamera); }); - auto orbitRotateCamera = AZStd::make_shared(AzFramework::CameraOrbitLookButton); - auto orbitTranslateCamera = AZStd::make_shared(AzFramework::OrbitTranslation); - auto orbitDollyWheelCamera = AZStd::make_shared(); - auto orbitDollyMoveCamera = - AZStd::make_shared(AzFramework::CameraOrbitDollyButton); - auto orbitPanCamera = - AZStd::make_shared(AzFramework::CameraOrbitPanButton, AzFramework::OrbitPan); - - orbitCamera->m_orbitCameras.AddCamera(orbitRotateCamera); - orbitCamera->m_orbitCameras.AddCamera(orbitTranslateCamera); - orbitCamera->m_orbitCameras.AddCamera(orbitDollyWheelCamera); - orbitCamera->m_orbitCameras.AddCamera(orbitDollyMoveCamera); - orbitCamera->m_orbitCameras.AddCamera(orbitPanCamera); - - cameras.AddCamera(firstPersonRotateCamera); - cameras.AddCamera(firstPersonPanCamera); - cameras.AddCamera(firstPersonTranslateCamera); - cameras.AddCamera(firstPersonWheelCamera); - cameras.AddCamera(orbitCamera); - }); - m_renderViewport->GetControllerList()->Add(controller); } else diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.h index 1acaa6fdf8..41ea80f8d1 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.h @@ -35,14 +35,13 @@ namespace AZ , private MeshComponentNotificationBus::Handler { public: - using BaseClass = EditorRenderComponentAdapter; AZ_EDITOR_COMPONENT(AZ::Render::EditorMeshComponent, EditorMeshComponentTypeId, BaseClass); static void Reflect(AZ::ReflectContext* context); EditorMeshComponent() = default; - EditorMeshComponent(const MeshComponentConfig& config); + explicit EditorMeshComponent(const MeshComponentConfig& config); // AZ::Component overrides ... void Activate() override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponent.h index a57780c384..fe7f45d7d1 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponent.h @@ -25,12 +25,11 @@ namespace AZ : public AzFramework::Components::ComponentAdapter { public: - using BaseClass = AzFramework::Components::ComponentAdapter; AZ_COMPONENT(AZ::Render::MeshComponent, MeshComponentTypeId, BaseClass); MeshComponent() = default; - MeshComponent(const MeshComponentConfig& config); + explicit MeshComponent(const MeshComponentConfig& config); static void Reflect(AZ::ReflectContext* context); }; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp index a4a91cf708..c089dd01f9 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp @@ -177,28 +177,33 @@ namespace AZ FixUpModelAsset(m_configuration.m_modelAsset); } - void MeshComponentController::Activate(AZ::EntityId entityId) + void MeshComponentController::Activate(const AZ::EntityComponentIdPair& entityComponentIdPair) { FixUpModelAsset(m_configuration.m_modelAsset); - m_entityId = entityId; + const AZ::EntityId entityId = entityComponentIdPair.GetEntityId(); + m_entityComponentIdPair = entityComponentIdPair; - m_transformInterface = TransformBus::FindFirstHandler(m_entityId); + m_transformInterface = TransformBus::FindFirstHandler(entityId); AZ_Warning("MeshComponentController", m_transformInterface, "Unable to attach to a TransformBus handler. This mesh will always be rendered at the origin."); - m_meshFeatureProcessor = RPI::Scene::GetFeatureProcessorForEntity(m_entityId); + m_meshFeatureProcessor = RPI::Scene::GetFeatureProcessorForEntity(entityId); AZ_Error("MeshComponentController", m_meshFeatureProcessor, "Unable to find a MeshFeatureProcessorInterface on the entityId."); m_cachedNonUniformScale = AZ::Vector3::CreateOne(); - AZ::NonUniformScaleRequestBus::EventResult(m_cachedNonUniformScale, m_entityId, &AZ::NonUniformScaleRequests::GetScale); - AZ::NonUniformScaleRequestBus::Event(m_entityId, &AZ::NonUniformScaleRequests::RegisterScaleChangedEvent, + AZ::NonUniformScaleRequestBus::EventResult(m_cachedNonUniformScale, entityId, &AZ::NonUniformScaleRequests::GetScale); + AZ::NonUniformScaleRequestBus::Event(entityId, &AZ::NonUniformScaleRequests::RegisterScaleChangedEvent, m_nonUniformScaleChangedHandler); - MeshComponentRequestBus::Handler::BusConnect(m_entityId); - TransformNotificationBus::Handler::BusConnect(m_entityId); - MaterialReceiverRequestBus::Handler::BusConnect(m_entityId); - MaterialComponentNotificationBus::Handler::BusConnect(m_entityId); - AzFramework::BoundsRequestBus::Handler::BusConnect(m_entityId); + MeshComponentRequestBus::Handler::BusConnect(entityId); + TransformNotificationBus::Handler::BusConnect(entityId); + MaterialReceiverRequestBus::Handler::BusConnect(entityId); + MaterialComponentNotificationBus::Handler::BusConnect(entityId); + AzFramework::BoundsRequestBus::Handler::BusConnect(entityId); + AzFramework::EntityContextId contextId; + AzFramework::EntityIdContextQueryBus::EventResult( + contextId, entityId, &AzFramework::EntityIdContextQueries::GetOwningContextId); + AzFramework::RenderGeometry::IntersectionRequestBus::Handler::BusConnect({entityId, contextId}); //Buses must be connected before RegisterModel in case requests are made as a result of HandleModelChange RegisterModel(); @@ -209,6 +214,7 @@ namespace AZ // Buses must be disconnected after unregistering the model, otherwise they can't deliver the events during the process. UnregisterModel(); + AzFramework::RenderGeometry::IntersectionRequestBus::Handler::BusDisconnect(); AzFramework::BoundsRequestBus::Handler::BusDisconnect(); MeshComponentRequestBus::Handler::BusDisconnect(); TransformNotificationBus::Handler::BusDisconnect(); @@ -219,7 +225,7 @@ namespace AZ m_meshFeatureProcessor = nullptr; m_transformInterface = nullptr; - m_entityId = AZ::EntityId(AZ::EntityId::InvalidEntityId); + m_entityComponentIdPair = AZ::EntityComponentIdPair(AZ::EntityId(), AZ::InvalidComponentId); m_configuration.m_modelAsset.Release(); } @@ -293,10 +299,11 @@ namespace AZ Data::Asset modelAsset = m_meshFeatureProcessor->GetModelAsset(m_meshHandle); if (model && modelAsset) { + const AZ::EntityId entityId = m_entityComponentIdPair.GetEntityId(); m_configuration.m_modelAsset = modelAsset; - MeshComponentNotificationBus::Event(m_entityId, &MeshComponentNotificationBus::Events::OnModelReady, m_configuration.m_modelAsset, model); - MaterialReceiverNotificationBus::Event(m_entityId, &MaterialReceiverNotificationBus::Events::OnMaterialAssignmentsChanged); - AZ::Interface::Get()->RefreshEntityLocalBoundsUnion(m_entityId); + MeshComponentNotificationBus::Event(entityId, &MeshComponentNotificationBus::Events::OnModelReady, m_configuration.m_modelAsset, model); + MaterialReceiverNotificationBus::Event(entityId, &MaterialReceiverNotificationBus::Events::OnMaterialAssignmentsChanged); + AZ::Interface::Get()->RefreshEntityLocalBoundsUnion(entityId); } } @@ -304,8 +311,10 @@ namespace AZ { if (m_meshFeatureProcessor && m_configuration.m_modelAsset.GetId().IsValid()) { + const AZ::EntityId entityId = m_entityComponentIdPair.GetEntityId(); + MaterialAssignmentMap materials; - MaterialComponentRequestBus::EventResult(materials, m_entityId, &MaterialComponentRequests::GetMaterialOverrides); + MaterialComponentRequestBus::EventResult(materials, entityId, &MaterialComponentRequests::GetMaterialOverrides); m_meshFeatureProcessor->ReleaseMesh(m_meshHandle); m_meshHandle = m_meshFeatureProcessor->AcquireMesh(m_configuration.m_modelAsset, materials, @@ -330,7 +339,8 @@ namespace AZ { if (m_meshFeatureProcessor && m_meshHandle.IsValid()) { - MeshComponentNotificationBus::Event(m_entityId, &MeshComponentNotificationBus::Events::OnModelPreDestroy); + MeshComponentNotificationBus::Event( + m_entityComponentIdPair.GetEntityId(), &MeshComponentNotificationBus::Events::OnModelPreDestroy); m_meshFeatureProcessor->ReleaseMesh(m_meshHandle); } } @@ -462,5 +472,34 @@ namespace AZ return Aabb::CreateNull(); } } + + AzFramework::RenderGeometry::RayResult MeshComponentController::RenderGeometryIntersect( + const AzFramework::RenderGeometry::RayRequest& ray) + { + AzFramework::RenderGeometry::RayResult result; + if (const Data::Instance model = GetModel()) + { + float t; + AZ::Vector3 normal; + if (model->RayIntersection( + m_transformInterface->GetWorldTM(), m_cachedNonUniformScale, ray.m_startWorldPosition, + ray.m_endWorldPosition - ray.m_startWorldPosition, t, normal)) + { + // note: this is a temporary workaround to handle cases where model->RayIntersection + // returns negative distances, follow-up ATOM-15673 + const auto absT = AZStd::abs(t); + + // fill in ray result structure after successful intersection + const auto intersectionLine = (ray.m_endWorldPosition - ray.m_startWorldPosition); + result.m_uv = AZ::Vector2::CreateZero(); + result.m_worldPosition = ray.m_startWorldPosition + intersectionLine * absT; + result.m_worldNormal = normal; + result.m_distance = intersectionLine.GetLength() * absT; + result.m_entityAndComponent = m_entityComponentIdPair; + } + } + + return result; + } } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.h index 0cda34ea42..4d63e5e88d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.h @@ -13,11 +13,13 @@ #pragma once #include +#include #include #include #include +#include #include #include @@ -32,9 +34,7 @@ namespace AZ { namespace Render { - /** - * A configuration structure for the MeshComponentController - */ + //! A configuration structure for the MeshComponentController class MeshComponentConfig final : public AZ::ComponentConfig { @@ -57,6 +57,7 @@ namespace AZ class MeshComponentController final : private MeshComponentRequestBus::Handler , public AzFramework::BoundsRequestBus::Handler + , public AzFramework::RenderGeometry::IntersectionRequestBus::Handler , private TransformNotificationBus::Handler , private MaterialReceiverRequestBus::Handler , private MaterialComponentNotificationBus::Handler @@ -77,7 +78,7 @@ namespace AZ MeshComponentController() = default; MeshComponentController(const MeshComponentConfig& config); - void Activate(AZ::EntityId entityId); + void Activate(const AZ::EntityComponentIdPair& entityComponentIdPair); void Deactivate(); void SetConfiguration(const MeshComponentConfig& config); const MeshComponentConfig& GetConfiguration() const; @@ -103,10 +104,13 @@ namespace AZ void SetVisibility(bool visible) override; bool GetVisibility() const override; - // BoundsRequestBus and MeshComponentRequestBus ... + // BoundsRequestBus and MeshComponentRequestBus overrides ... AZ::Aabb GetWorldBounds() override; AZ::Aabb GetLocalBounds() override; + // IntersectionRequestBus overrides ... + AzFramework::RenderGeometry::RayResult RenderGeometryIntersect(const AzFramework::RenderGeometry::RayRequest& ray) override; + // TransformNotificationBus::Handler overrides ... void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; @@ -134,7 +138,7 @@ namespace AZ Render::MeshFeatureProcessorInterface* m_meshFeatureProcessor = nullptr; Render::MeshFeatureProcessorInterface::MeshHandle m_meshHandle; TransformInterface* m_transformInterface = nullptr; - AZ::EntityId m_entityId; + AZ::EntityComponentIdPair m_entityComponentIdPair; bool m_isVisible = true; MeshComponentConfig m_configuration; AZ::Vector3 m_cachedNonUniformScale = AZ::Vector3::CreateOne(); From 0577c0f0dda8db34796ca88edff29f71ee6164d2 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 15:24:02 +0100 Subject: [PATCH 305/811] update transform serialization to handle migration to uniform scale --- Code/Framework/AzCore/AzCore/Math/Aabb.cpp | 2 +- Code/Framework/AzCore/AzCore/Math/Obb.cpp | 2 +- .../AzCore/AzCore/Math/Transform.cpp | 45 +++++++++++++++---- Code/Framework/AzCore/AzCore/Math/Transform.h | 9 ++-- .../AzCore/Math/TransformSerializer.cpp | 2 +- .../AZTestShared/Math/MathTestHelpers.cpp | 2 +- 6 files changed, 46 insertions(+), 16 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Math/Aabb.cpp b/Code/Framework/AzCore/AzCore/Math/Aabb.cpp index 3f7cb4ecf5..367594be63 100644 --- a/Code/Framework/AzCore/AzCore/Math/Aabb.cpp +++ b/Code/Framework/AzCore/AzCore/Math/Aabb.cpp @@ -227,7 +227,7 @@ namespace AZ // the min and max of each part and sum them to get the min and max co-ordinate of the transformed box. For a given new axis, // the coefficients for what proportion of each original axis is rotated onto that new axis are the same as the components we // would get by performing the inverse rotation on the new axis, so we need to take the conjugate to get the inverse rotation. - axisCoeffs = transform.GetScale() * (transform.GetRotation().GetConjugate().TransformVector(axis)); + axisCoeffs = transform.GetUniformScale() * (transform.GetRotation().GetConjugate().TransformVector(axis)); a = axisCoeffs * m_min; b = axisCoeffs * m_max; diff --git a/Code/Framework/AzCore/AzCore/Math/Obb.cpp b/Code/Framework/AzCore/AzCore/Math/Obb.cpp index eb511669d0..9226ddd28f 100644 --- a/Code/Framework/AzCore/AzCore/Math/Obb.cpp +++ b/Code/Framework/AzCore/AzCore/Math/Obb.cpp @@ -154,7 +154,7 @@ namespace AZ return Obb::CreateFromPositionRotationAndHalfLengths( transform.TransformPoint(obb.GetPosition()), transform.GetRotation() * obb.GetRotation(), - transform.GetScale() * obb.GetHalfLengths() + transform.GetUniformScale() * obb.GetHalfLengths() ); } } diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.cpp b/Code/Framework/AzCore/AzCore/Math/Transform.cpp index 12f8e426cd..0ae3e9c0ef 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.cpp +++ b/Code/Framework/AzCore/AzCore/Math/Transform.cpp @@ -130,8 +130,8 @@ namespace AZ const Transform* transform = reinterpret_cast(classPtr); float data[NumFloats]; transform->GetRotation().StoreToFloat4(data); - transform->GetScale().StoreToFloat3(&data[4]); - transform->GetTranslation().StoreToFloat3(&data[7]); + data[4] = transform->GetUniformScale(); + transform->GetTranslation().StoreToFloat3(&data[5]); for (int i = 0; i < NumFloats; i++) { @@ -159,8 +159,8 @@ namespace AZ size_t TransformSerializer::TextToData(const char* text, unsigned int textVersion, IO::GenericStream& stream, bool isDataBigEndian) { - const size_t dataBufferSize = AZStd::max(NumFloatsVersion0, NumFloats); - const size_t numElements = textVersion < 1 ? NumFloatsVersion0 : NumFloats; + const size_t dataBufferSize = AZStd::max(AZStd::max(NumFloatsVersion1, NumFloatsVersion0), NumFloats); + const size_t numElements = textVersion < 1 ? NumFloatsVersion0 : (textVersion == 1 ? NumFloatsVersion1 : NumFloats); size_t nextNumberIndex = 0; AZStd::array data; @@ -201,7 +201,34 @@ namespace AZ return true; } - // otherwise load as a separate rotation, scale and translation + // version 1 had a quaternion rotation, vector3 scale and vector3 translation + else if (version == 1) + { + float data[NumFloatsVersion1]; + if (stream.GetLength() < sizeof(data)) + { + return false; + } + + stream.Read(sizeof(data), reinterpret_cast(data)); + + for (unsigned int i = 0; i < AZ_ARRAY_SIZE(data); ++i) + { + AZ_SERIALIZE_SWAP_ENDIAN(data[i], isDataBigEndian); + } + + Quaternion rotation = Quaternion::CreateFromFloat4(data); + Vector3 vectorScale = Vector3::CreateFromFloat3(&data[4]); + Vector3 translation = Vector3::CreateFromFloat3(&data[7]); + + float uniformScale = vectorScale.GetMaxElement(); + + *reinterpret_cast(classPtr) = + Transform::CreateFromQuaternionAndTranslation(rotation, translation) * Transform::CreateUniformScale(uniformScale); + return true; + } + + // otherwise load as a quaternion rotation, float scale and vector3 translation float data[NumFloats]; if (stream.GetLength() < sizeof(data)) { @@ -216,11 +243,11 @@ namespace AZ } Quaternion rotation = Quaternion::CreateFromFloat4(data); - Vector3 scale = Vector3::CreateFromFloat3(&data[4]); - Vector3 translation = Vector3::CreateFromFloat3(&data[7]); + float scale = data[4]; + Vector3 translation = Vector3::CreateFromFloat3(&data[5]); *reinterpret_cast(classPtr) = - Transform::CreateFromQuaternionAndTranslation(rotation, translation) * Transform::CreateScale(scale); + Transform::CreateFromQuaternionAndTranslation(rotation, translation) * Transform::CreateUniformScale(scale); return true; } @@ -237,7 +264,7 @@ namespace AZ if (serializeContext) { serializeContext->Class() - ->Version(1) + ->Version(2) ->Serializer(); } diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.h b/Code/Framework/AzCore/AzCore/Math/Transform.h index e8c4325c7a..974a0180e8 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.h +++ b/Code/Framework/AzCore/AzCore/Math/Transform.h @@ -25,10 +25,13 @@ namespace AZ : public SerializeContext::IDataSerializer { public: - // number of floats in the serialized representation, 4 for rotation, 3 for scale and 3 for translation - static constexpr int NumFloats = 10; + // number of floats in the serialized representation, 4 for rotation, 1 for scale and 3 for translation + static constexpr int NumFloats = 8; - // number of floats in the old format, which stored a 3x4 matrix + // number of floats in version 1, which used 4 for rotation, 3 for scale and 3 for translation + static constexpr int NumFloatsVersion1 = 10; + + // number of floats in version 0, which stored a 3x4 matrix static constexpr int NumFloatsVersion0 = 12; size_t Save(const void* classPtr, IO::GenericStream& stream, bool isDataBigEndian) override; diff --git a/Code/Framework/AzCore/AzCore/Math/TransformSerializer.cpp b/Code/Framework/AzCore/AzCore/Math/TransformSerializer.cpp index 86bc1c36ea..36c40265af 100644 --- a/Code/Framework/AzCore/AzCore/Math/TransformSerializer.cpp +++ b/Code/Framework/AzCore/AzCore/Math/TransformSerializer.cpp @@ -67,7 +67,7 @@ namespace AZ result.Combine(loadResult); - transformInstance->SetScale(AZ::Vector3(scale)); + transformInstance->SetUniformScale(scale); } return context.Report( diff --git a/Code/Framework/AzCore/Tests/AZTestShared/Math/MathTestHelpers.cpp b/Code/Framework/AzCore/Tests/AZTestShared/Math/MathTestHelpers.cpp index 42b77f6976..f9616702f1 100644 --- a/Code/Framework/AzCore/Tests/AZTestShared/Math/MathTestHelpers.cpp +++ b/Code/Framework/AzCore/Tests/AZTestShared/Math/MathTestHelpers.cpp @@ -68,7 +68,7 @@ namespace AZ return os << "translation: " << transform.GetTranslation() << " rotation: " << transform.GetRotation() - << " scale: " << transform.GetScale(); + << " scale: " << transform.GetUniformScale(); } std::ostream& operator<<(std::ostream& os, const Color& color) From bdf9da820dac872d39077c28f11e383346a1ec27 Mon Sep 17 00:00:00 2001 From: gallowj Date: Fri, 28 May 2021 09:49:44 -0500 Subject: [PATCH 306/811] removing folder with image data we don't own, can't license. --- .../sampleEnvironment/PaperMill_E_3k.exr | 3 - .../PaperMill_E_3k.exr.assetinfo | 69 ------------------- .../sampleEnvironment/exampleBrdf_lut.dds | 3 - .../exampleDiffuseHDR_cm.dds | 3 - .../exampleSpecularHDR_cm.dds | 3 - .../sampleEnvironment/example_iblskyboxcm.dds | 3 - .../sampleEnvironment/papermill_license.txt | 10 --- 7 files changed, 94 deletions(-) delete mode 100644 Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr delete mode 100644 Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr.assetinfo delete mode 100644 Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleBrdf_lut.dds delete mode 100644 Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleDiffuseHDR_cm.dds delete mode 100644 Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleSpecularHDR_cm.dds delete mode 100644 Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/example_iblskyboxcm.dds delete mode 100644 Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/papermill_license.txt diff --git a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr b/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr deleted file mode 100644 index 0fcbcc4746..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bc9981393c88c6d30a0a5a6837e6f6246a9f550042b3c4be39dd34e479b90569 -size 16793931 diff --git a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr.assetinfo b/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr.assetinfo deleted file mode 100644 index 16cb0dd668..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/PaperMill_E_3k.exr.assetinfo +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleBrdf_lut.dds b/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleBrdf_lut.dds deleted file mode 100644 index f2b2ce550d..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleBrdf_lut.dds +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:440bcb1579d4ad667c040bda914ed3121980526a94f23879a0c482c799fd5132 -size 1310848 diff --git a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleDiffuseHDR_cm.dds b/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleDiffuseHDR_cm.dds deleted file mode 100644 index 9585c25dd1..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleDiffuseHDR_cm.dds +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:cf4b22481726214c062ac27fb2d9d8a49e760a76d8fff03330ff9c5f9275a8da -size 1966208 diff --git a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleSpecularHDR_cm.dds b/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleSpecularHDR_cm.dds deleted file mode 100644 index a35fac45fb..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/exampleSpecularHDR_cm.dds +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8b4c99faffc34988c268613948f2004f40e9bd51de915461a4cb74edc5e8bae6 -size 134217920 diff --git a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/example_iblskyboxcm.dds b/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/example_iblskyboxcm.dds deleted file mode 100644 index a89dfdbd3d..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/example_iblskyboxcm.dds +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f7edea42ded8143764654f12c19e0c9b74c74afb21f435ebb59c0a4d203892a3 -size 536871104 diff --git a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/papermill_license.txt b/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/papermill_license.txt deleted file mode 100644 index 83cfe08ab9..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Textures/sampleEnvironment/papermill_license.txt +++ /dev/null @@ -1,10 +0,0 @@ -The papermill 'Image base lighting' (IBL) images are modified from the following: - -http://www.hdrlabs.com/sibl/archive.html -'Papermill Ruins E' - -All sIBL-sets on this page, including the images within, are licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 License. - -Creative Commons License: http://creativecommons.org/licenses/by-nc-sa/3.0/us/ - -Remember: Do what you want with them, but always mention where you got them from... \ No newline at end of file From 42b3e3817a7a15cc6ff1592afb6a78a12bb56eca Mon Sep 17 00:00:00 2001 From: pereslav Date: Fri, 28 May 2021 15:50:02 +0100 Subject: [PATCH 307/811] SPEC-7012 Added rewind-aware scene query utilities. Added frame ID to SimulatedBody --- .../Physics/Common/PhysicsSimulatedBody.h | 18 +++ .../Include/Multiplayer/MultiplayerTypes.h | 3 +- .../Multiplayer/Physics/PhysicsUtils.h | 37 +++++++ .../Code/Source/Physics/PhysicsUtils.cpp | 104 ++++++++++++++++++ Gems/Multiplayer/Code/multiplayer_files.cmake | 2 + 5 files changed, 163 insertions(+), 1 deletion(-) create mode 100644 Gems/Multiplayer/Code/Include/Multiplayer/Physics/PhysicsUtils.h create mode 100644 Gems/Multiplayer/Code/Source/Physics/PhysicsUtils.cpp diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsSimulatedBody.h b/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsSimulatedBody.h index ed8a68dc24..9d45a17edc 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsSimulatedBody.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsSimulatedBody.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -68,6 +69,22 @@ namespace AzPhysics return m_customUserData; } + //! Helper functions for setting frame ID. + //! @param frameId Optionally set frame ID for the systems moving the actors back in time. + void SetFrameId(uint32_t frameId) + { + m_frameId = frameId; + } + + //! Helper functions for getting the set frame ID. + //! @return Will return the frame ID. + uint32_t GetFrameId() const + { + return m_frameId; + } + + static constexpr uint32_t UndefinedFrameId = AZStd::numeric_limits::max(); + //! Perform a ray cast on this Simulated Body. //! @param request The request to make. //! @return Returns the closest hit, if any, against this simulated body. @@ -126,6 +143,7 @@ namespace AzPhysics SimulatedBodyEvents::OnTriggerExit m_triggerExitEvent; void* m_customUserData = nullptr; + uint32_t m_frameId = UndefinedFrameId; // helpers for reflecting to behavior context SimulatedBodyEvents::OnCollisionBegin* GetOnCollisionBeginEvent(); diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h index 16cc4146dd..85c7e85c0a 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -41,7 +42,7 @@ namespace Multiplayer //! This is a strong typedef for representing the number of application frames since application start. AZ_TYPE_SAFE_INTEGRAL(HostFrameId, uint32_t); - static constexpr HostFrameId InvalidHostFrameId = HostFrameId{ 0xFFFFFFFF }; + static constexpr HostFrameId InvalidHostFrameId = HostFrameId{ AzPhysics::SimulatedBody::UndefinedFrameId }; using LongNetworkString = AZ::CVarFixedString; using ReliabilityType = AzNetworking::ReliabilityType; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Physics/PhysicsUtils.h b/Gems/Multiplayer/Code/Include/Multiplayer/Physics/PhysicsUtils.h new file mode 100644 index 0000000000..4013e20a1e --- /dev/null +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Physics/PhysicsUtils.h @@ -0,0 +1,37 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#pragma once + +#include + +namespace Multiplayer +{ + namespace Physics + { + //! Performs rewind-aware ray cast in the default physics world. + //! @param request The ray cast request to make. + //! @return Returns a structure that contains a list of Hits. + AzPhysics::SceneQueryHits RayCast(const AzPhysics::RayCastRequest& request); + + //! Performs rewind-aware shape cast in the default physics world. + //! @param request The shape cast request to make. + //! @return Returns a structure that contains a list of Hits. + AzPhysics::SceneQueryHits ShapeCast(const AzPhysics::ShapeCastRequest& request); + + //! Performs rewind-aware overlap in the default physics world. + //! @param request The overlap request to make. + //! @return Returns a structure that contains a list of Hits. + AzPhysics::SceneQueryHits Overlap(const AzPhysics::OverlapRequest& request); + + } // namespace Physics +} // namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/Physics/PhysicsUtils.cpp b/Gems/Multiplayer/Code/Source/Physics/PhysicsUtils.cpp new file mode 100644 index 0000000000..6341f5b060 --- /dev/null +++ b/Gems/Multiplayer/Code/Source/Physics/PhysicsUtils.cpp @@ -0,0 +1,104 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include + +#include +#include +#include +#include + +namespace +{ + template + AzPhysics::SceneQueryHits SceneQueryInternal(const RequestT& request) + { + auto* sceneInterface = AZ::Interface::Get(); + if (!sceneInterface) + { + return {}; + } + + AzPhysics::SceneHandle sceneHandle = sceneInterface->GetSceneHandle(AzPhysics::DefaultPhysicsSceneName); + if (sceneHandle == AzPhysics::InvalidSceneHandle) + { + return {}; + } + + Multiplayer::INetworkTime* currentNetTime = Multiplayer::GetNetworkTime(); + + if(!currentNetTime->IsTimeRewound()) + { + // If the time is not rewound, we simply execute the scene query as is. + AzPhysics::SceneQueryHits result = sceneInterface->QueryScene(sceneHandle, &request); + return result; + } + + // If the time is rewound, we want to query against rigid bodies present at the same frame ID: the same as the current rewound time is. + RequestT netSceneQueryRequest = request; + netSceneQueryRequest.m_filterCallback = [&request, currentFrameId = (uint32_t)currentNetTime->GetHostFrameId()]( + const AzPhysics::SimulatedBody* body, const ::Physics::Shape* shape) + { + if (body->GetFrameId() == AzPhysics::SimulatedBody::UndefinedFrameId || body->GetFrameId() == currentFrameId) + { + if (request.m_filterCallback) + { + return request.m_filterCallback(body, shape); + } + + // Overlap filter callbacks return true/false rather than Touch/Block/None + if constexpr (AZStd::is_same_v) + { + return true; + } + else + { + return AzPhysics::SceneQuery::QueryHitType::Touch; + } + } + + if constexpr (AZStd::is_same_v) + { + return false; + } + else + { + return AzPhysics::SceneQuery::QueryHitType::None; + } + }; + + // Execute the scene query modified for the time rewind. + AzPhysics::SceneQueryHits result = sceneInterface->QueryScene(sceneHandle, &netSceneQueryRequest); + return result; + } +} + +namespace Multiplayer +{ + namespace Physics + { + AzPhysics::SceneQueryHits RayCast(const AzPhysics::RayCastRequest& request) + { + return SceneQueryInternal(request); + } + + AzPhysics::SceneQueryHits ShapeCast(const AzPhysics::ShapeCastRequest& request) + { + return SceneQueryInternal(request); + } + + AzPhysics::SceneQueryHits Overlap(const AzPhysics::OverlapRequest& request) + { + return SceneQueryInternal(request); + } + } // namespace Physics +} // namespace Multiplayer diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index eb856a48db..28f32e02cc 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -35,6 +35,7 @@ set(FILES Include/Multiplayer/NetworkTime/INetworkTime.h Include/Multiplayer/NetworkTime/RewindableObject.h Include/Multiplayer/NetworkTime/RewindableObject.inl + Include/Multiplayer/Physics/PhysicsUtils.h Include/Multiplayer/ReplicationWindows/IReplicationWindow.h Source/Multiplayer_precompiled.cpp Source/Multiplayer_precompiled.h @@ -103,6 +104,7 @@ set(FILES Source/Pipeline/NetBindMarkerComponent.h Source/Pipeline/NetworkSpawnableHolderComponent.cpp Source/Pipeline/NetworkSpawnableHolderComponent.h + Source/Physics/PhysicsUtils.cpp Source/ReplicationWindows/NullReplicationWindow.cpp Source/ReplicationWindows/NullReplicationWindow.h Source/ReplicationWindows/ServerToClientReplicationWindow.cpp From 96905a26d718b8efdeb6228af4c0ac7599f5b931 Mon Sep 17 00:00:00 2001 From: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> Date: Fri, 28 May 2021 09:57:17 -0500 Subject: [PATCH 308/811] Add support for AP-compliant relative paths (#998) The method "PrefabLoader::GetRelativePathToProject" has been changed to "PrefabLoader::GenerateRelativePath", and reworked to get a correct relative path. GetFullPath has also been modified to get correct relative paths too. This requires an Asset Processor connection - if one isn't available (like during unit tests), the methods have fallback logic to produce project-relative paths. With this change, SliceConverter can't use SaveTemplate() to save the file any more, because GetFullPath now expects to find an existing path, which doesn't work for not-yet-created files. Instead, it now has to use the same technique as the Editor and call SaveTemplateToString then save the string out as a file. --- .../PrefabEditorEntityOwnershipService.cpp | 29 +++--- .../Prefab/Instance/InstanceSerializer.cpp | 2 +- .../AzToolsFramework/Prefab/PrefabLoader.cpp | 95 +++++++++++++++++-- .../AzToolsFramework/Prefab/PrefabLoader.h | 8 +- .../Prefab/PrefabLoaderInterface.h | 8 +- .../Prefab/PrefabPublicHandler.cpp | 2 +- .../Prefab/PrefabSystemComponent.cpp | 2 +- .../UI/Prefab/PrefabIntegrationManager.cpp | 3 +- .../SerializeContextTools/SliceConverter.cpp | 28 ++++-- .../SerializeContextTools/SliceConverter.h | 2 +- 10 files changed, 143 insertions(+), 36 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 439789f11b..7fd11ff9bf 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -57,7 +57,6 @@ namespace AzToolsFramework "Couldn't get prefab loader interface, it's a requirement for PrefabEntityOwnership system to work"); m_rootInstance = AZStd::unique_ptr(m_prefabSystemComponent->CreatePrefab({}, {}, "NewLevel.prefab")); - m_sliceOwnershipService.BusConnect(m_entityContextId); m_sliceOwnershipService.m_shouldAssertForLegacySlicesUsage = m_shouldAssertForLegacySlicesUsage; m_editorSliceOwnershipService.BusConnect(); @@ -91,14 +90,17 @@ namespace AzToolsFramework void PrefabEditorEntityOwnershipService::Reset() { - Prefab::TemplateId templateId = m_rootInstance->GetTemplateId(); - if (templateId != Prefab::InvalidTemplateId) + if (m_rootInstance) { - m_rootInstance->SetTemplateId(Prefab::InvalidTemplateId); - m_prefabSystemComponent->RemoveTemplate(templateId); + Prefab::TemplateId templateId = m_rootInstance->GetTemplateId(); + if (templateId != Prefab::InvalidTemplateId) + { + m_rootInstance->SetTemplateId(Prefab::InvalidTemplateId); + m_prefabSystemComponent->RemoveTemplate(templateId); + } + m_rootInstance->Reset(); + m_rootInstance->SetContainerEntityName("Level"); } - m_rootInstance->Reset(); - m_rootInstance->SetContainerEntityName("Level"); AzFramework::EntityOwnershipServiceNotificationBus::Event( m_entityContextId, &AzFramework::EntityOwnershipServiceNotificationBus::Events::OnEntityOwnershipServiceReset); @@ -202,7 +204,7 @@ namespace AzToolsFramework } m_rootInstance->SetTemplateId(templateId); - m_rootInstance->SetTemplateSourcePath(m_loaderInterface->GetRelativePathToProject(filename)); + m_rootInstance->SetTemplateSourcePath(m_loaderInterface->GenerateRelativePath(filename)); m_rootInstance->SetContainerEntityName("Level"); m_prefabSystemComponent->PropagateTemplateChanges(templateId); @@ -220,7 +222,7 @@ namespace AzToolsFramework bool PrefabEditorEntityOwnershipService::SaveToStream(AZ::IO::GenericStream& stream, AZStd::string_view filename) { - AZ::IO::Path relativePath = m_loaderInterface->GetRelativePathToProject(filename); + AZ::IO::Path relativePath = m_loaderInterface->GenerateRelativePath(filename); AzToolsFramework::Prefab::TemplateId templateId = m_prefabSystemComponent->GetTemplateIdFromFilePath(relativePath); m_rootInstance->SetTemplateSourcePath(relativePath); @@ -267,7 +269,7 @@ namespace AzToolsFramework void PrefabEditorEntityOwnershipService::CreateNewLevelPrefab(AZStd::string_view filename, const AZStd::string& templateFilename) { - AZ::IO::Path relativePath = m_loaderInterface->GetRelativePathToProject(filename); + AZ::IO::Path relativePath = m_loaderInterface->GenerateRelativePath(filename); AzToolsFramework::Prefab::TemplateId templateId = m_prefabSystemComponent->GetTemplateIdFromFilePath(relativePath); m_rootInstance->SetTemplateSourcePath(relativePath); @@ -378,7 +380,12 @@ namespace AzToolsFramework Prefab::InstanceOptionalReference PrefabEditorEntityOwnershipService::GetRootPrefabInstance() { AZ_Assert(m_rootInstance, "A valid root prefab instance couldn't be found in PrefabEditorEntityOwnershipService."); - return *m_rootInstance; + if (m_rootInstance) + { + return *m_rootInstance; + } + + return AZStd::nullopt; } const AZStd::vector>& PrefabEditorEntityOwnershipService::GetPlayInEditorAssetData() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceSerializer.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceSerializer.cpp index 836140eb74..39351df486 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceSerializer.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceSerializer.cpp @@ -124,7 +124,7 @@ namespace AzToolsFramework "PrefabLoaderInterface could not be found. It is required to load Prefab Instances"); // Make sure we have a relative path - instance->m_templateSourcePath = loaderInterface->GetRelativePathToProject(instance->m_templateSourcePath); + instance->m_templateSourcePath = loaderInterface->GenerateRelativePath(instance->m_templateSourcePath); TemplateId templateId = prefabSystemComponentInterface->GetTemplateIdFromFilePath(instance->GetTemplateSourcePath()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp index 2965148172..e4507227b5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp @@ -18,7 +18,9 @@ #include #include +#include #include +#include #include #include #include @@ -112,7 +114,7 @@ namespace AzToolsFramework return InvalidTemplateId; } - AZ::IO::Path relativePath = GetRelativePathToProject(originPath); + AZ::IO::Path relativePath = GenerateRelativePath(originPath); // Cyclical dependency detected if the prefab file is already part of the progressed // file path set. @@ -385,21 +387,100 @@ namespace AzToolsFramework AZ::IO::Path pathWithOSSeparator = AZ::IO::Path(path).MakePreferred(); if (pathWithOSSeparator.IsAbsolute()) { + // If an absolute path was passed in, just return it as-is. return path; } - return AZ::IO::Path(m_projectPathWithOsSeparator).Append(pathWithOSSeparator); + // A relative path was passed in, so try to turn it back into an absolute path. + + AZ::IO::Path fullPath; + + bool pathFound = false; + AZ::Data::AssetInfo assetInfo; + AZStd::string rootFolder; + AZStd::string inputPath(path.Native()); + + // Given an input path that's expected to exist, try to look it up. + AzToolsFramework::AssetSystemRequestBus::BroadcastResult( + pathFound, &AzToolsFramework::AssetSystemRequestBus::Events::GetSourceInfoBySourcePath, + inputPath.c_str(), assetInfo, rootFolder); + + if (pathFound) + { + // The asset system provided us with a valid root folder and relative path, so return it. + fullPath = AZ::IO::Path(rootFolder) / assetInfo.m_relativePath; + } + else + { + // If for some reason the Asset system couldn't provide a relative path, provide some fallback logic. + + // Check to see if the AssetProcessor is ready. If it *is* and we didn't get a path, print an error then follow + // the fallback logic. If it's *not* ready, we're probably either extremely early in a tool startup flow or inside + // a unit test, so just execute the fallback logic without an error. + [[maybe_unused]] bool assetProcessorReady = false; + AzFramework::AssetSystemRequestBus::BroadcastResult( + assetProcessorReady, &AzFramework::AssetSystemRequestBus::Events::AssetProcessorIsReady); + + AZ_Error( + "Prefab", !assetProcessorReady, "Full source path for '%.*s' could not be determined. Using fallback logic.", + AZ_STRING_ARG(path.Native())); + + // If a relative path was passed in, make it relative to the project root. + fullPath = AZ::IO::Path(m_projectPathWithOsSeparator).Append(pathWithOSSeparator); + } + + return fullPath; } - AZ::IO::Path PrefabLoader::GetRelativePathToProject(AZ::IO::PathView path) + AZ::IO::Path PrefabLoader::GenerateRelativePath(AZ::IO::PathView path) { - AZ::IO::Path pathWithOSSeparator = AZ::IO::Path(path.Native()).MakePreferred(); - if (!pathWithOSSeparator.IsAbsolute()) + bool pathFound = false; + + AZStd::string relativePath; + AZStd::string rootFolder; + AZ::IO::Path finalPath; + + // The asset system allows for paths to be relative to multiple root folders, using a priority system. + // This request will make the input path relative to the most appropriate, highest-priority root folder. + AzToolsFramework::AssetSystemRequestBus::BroadcastResult( + pathFound, &AzToolsFramework::AssetSystemRequestBus::Events::GenerateRelativeSourcePath, path.Native(), + relativePath, rootFolder); + + if (pathFound && !relativePath.empty()) { - return path; + // A relative path was generated successfully, so return it. + finalPath = relativePath; + } + else + { + // If for some reason the Asset system couldn't provide a relative path, provide some fallback logic. + + // Check to see if the AssetProcessor is ready. If it *is* and we didn't get a path, print an error then follow + // the fallback logic. If it's *not* ready, we're probably either extremely early in a tool startup flow or inside + // a unit test, so just execute the fallback logic without an error. + [[maybe_unused]] bool assetProcessorReady = false; + AzFramework::AssetSystemRequestBus::BroadcastResult( + assetProcessorReady, &AzFramework::AssetSystemRequestBus::Events::AssetProcessorIsReady); + + AZ_Error("Prefab", !assetProcessorReady, + "Relative source path for '%.*s' could not be determined. Using project path as relative root.", + AZ_STRING_ARG(path.Native())); + + AZ::IO::Path pathWithOSSeparator = AZ::IO::Path(path.Native()).MakePreferred(); + + if (pathWithOSSeparator.IsAbsolute()) + { + // If an absolute path was passed in, make it relative to the project path. + finalPath = AZ::IO::Path(path.Native(), '/').MakePreferred().LexicallyRelative(m_projectPathWithSlashSeparator); + } + else + { + // If a relative path was passed in, just return it. + finalPath = path; + } } - return AZ::IO::Path(path.Native(), '/').MakePreferred().LexicallyRelative(m_projectPathWithSlashSeparator); + return finalPath; } AZ::IO::Path PrefabLoaderInterface::GeneratePath() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.h index d11cb62ca3..aed24e153e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.h @@ -91,9 +91,11 @@ namespace AzToolsFramework //! The path will always have the correct separator for the current OS AZ::IO::Path GetFullPath(AZ::IO::PathView path) override; - //! Converts path into a relative path to the project, this will be the paths in .prefab file. - //! The path will always have '/' separator. - AZ::IO::Path GetRelativePathToProject(AZ::IO::PathView path) override; + //! Converts path into a path that's relative to the highest-priority containing folder of all the folders registered + //! with the engine. + //! This path will be the path that appears in the .prefab file. + //! The path will always use the '/' separator. + AZ::IO::Path GenerateRelativePath(AZ::IO::PathView path) override; //! Returns if the path is a valid path for a prefab static bool IsValidPrefabPath(AZ::IO::PathView path); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoaderInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoaderInterface.h index a4055fb15a..d71fbff80f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoaderInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoaderInterface.h @@ -74,9 +74,11 @@ namespace AzToolsFramework //! The path will always have the correct separator for the current OS virtual AZ::IO::Path GetFullPath(AZ::IO::PathView path) = 0; - //! Converts path into a relative path to the current project, this will be the paths in .prefab file. - //! The path will always have '/' separator. - virtual AZ::IO::Path GetRelativePathToProject(AZ::IO::PathView path) = 0; + //! Converts path into a path that's relative to the highest-priority containing folder of all the folders registered + //! with the engine. + //! This path will be the path that appears in the .prefab file. + //! The path will always use the '/' separator. + virtual AZ::IO::Path GenerateRelativePath(AZ::IO::PathView path) = 0; protected: diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 0181050a32..9dd5199ea2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -318,7 +318,7 @@ namespace AzToolsFramework } //Detect whether this instantiation would produce a cyclical dependency - auto relativePath = m_prefabLoaderInterface->GetRelativePathToProject(filePath); + auto relativePath = m_prefabLoaderInterface->GenerateRelativePath(filePath); Prefab::TemplateId templateId = m_prefabSystemComponentInterface->GetTemplateIdFromFilePath(relativePath); if (templateId == InvalidTemplateId) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index c4e6415b02..0136f791b3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -95,7 +95,7 @@ namespace AzToolsFramework const AZStd::vector& entities, AZStd::vector>&& instancesToConsume, AZ::IO::PathView filePath, AZStd::unique_ptr containerEntity, bool shouldCreateLinks) { - AZ::IO::Path relativeFilePath = m_prefabLoader.GetRelativePathToProject(filePath); + AZ::IO::Path relativeFilePath = m_prefabLoader.GenerateRelativePath(filePath); if (GetTemplateIdFromFilePath(relativeFilePath) != InvalidTemplateId) { AZ_Error("Prefab", false, diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index 3edc190fb7..61d4433c0e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -333,7 +333,8 @@ namespace AzToolsFramework } } - auto createPrefabOutcome = s_prefabPublicInterface->CreatePrefab(selectedEntities, s_prefabLoaderInterface->GetRelativePathToProject(prefabFilePath.data())); + auto createPrefabOutcome = s_prefabPublicInterface->CreatePrefab( + selectedEntities, s_prefabLoaderInterface->GenerateRelativePath(prefabFilePath.data())); if (!createPrefabOutcome.IsSuccess()) { diff --git a/Code/Tools/SerializeContextTools/SliceConverter.cpp b/Code/Tools/SerializeContextTools/SliceConverter.cpp index 3fbf7cb25c..d06534e303 100644 --- a/Code/Tools/SerializeContextTools/SliceConverter.cpp +++ b/Code/Tools/SerializeContextTools/SliceConverter.cpp @@ -244,7 +244,7 @@ namespace AZ } else { - return SavePrefab(templateId); + return SavePrefab(outputPath, templateId); } } @@ -318,7 +318,7 @@ namespace AZ nestedPrefabPath.ReplaceExtension("prefab"); auto prefabLoaderInterface = AZ::Interface::Get(); - nestedPrefabPath = prefabLoaderInterface->GetRelativePathToProject(nestedPrefabPath); + nestedPrefabPath = prefabLoaderInterface->GenerateRelativePath(nestedPrefabPath); AzToolsFramework::Prefab::TemplateId nestedTemplateId = prefabSystemComponentInterface->GetTemplateIdFromFilePath(nestedPrefabPath); @@ -439,17 +439,31 @@ namespace AZ AZ::Debug::Trace::Instance().Output("", "\n"); } - bool SliceConverter::SavePrefab(AzToolsFramework::Prefab::TemplateId templateId) + bool SliceConverter::SavePrefab(AZ::IO::PathView outputPath, AzToolsFramework::Prefab::TemplateId templateId) { auto prefabLoaderInterface = AZ::Interface::Get(); - if (!prefabLoaderInterface->SaveTemplate(templateId)) + AZStd::string out; + if (prefabLoaderInterface->SaveTemplateToString(templateId, out)) { - AZ_Printf("Convert-Slice", " Could not save prefab - internal error (Json write operation failure).\n"); - return false; + IO::SystemFile outputFile; + if (!outputFile.Open( + AZStd::string(outputPath.Native()).c_str(), + IO::SystemFile::OpenMode::SF_OPEN_CREATE | + IO::SystemFile::OpenMode::SF_OPEN_CREATE_PATH | + IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY)) + { + AZ_Error("Convert-Slice", false, " Unable to create output file '%.*s'.", AZ_STRING_ARG(outputPath.Native())); + return false; + } + + outputFile.Write(out.data(), out.size()); + outputFile.Close(); + return true; } - return true; + AZ_Printf("Convert-Slice", " Could not save prefab - internal error (Json write operation failure).\n"); + return false; } bool SliceConverter::ConnectToAssetProcessor() diff --git a/Code/Tools/SerializeContextTools/SliceConverter.h b/Code/Tools/SerializeContextTools/SliceConverter.h index a977095f02..bec893ff56 100644 --- a/Code/Tools/SerializeContextTools/SliceConverter.h +++ b/Code/Tools/SerializeContextTools/SliceConverter.h @@ -56,7 +56,7 @@ namespace AZ AZ::SliceComponent::SliceInstance& instance, AZ::Data::Asset& sliceAsset, AzToolsFramework::Prefab::TemplateReference nestedTemplate, AzToolsFramework::Prefab::Instance* topLevelInstance); static void PrintPrefab(AzToolsFramework::Prefab::TemplateId templateId); - static bool SavePrefab(AzToolsFramework::Prefab::TemplateId templateId); + static bool SavePrefab(AZ::IO::PathView outputPath, AzToolsFramework::Prefab::TemplateId templateId); }; } // namespace SerializeContextTools } // namespace AZ From fc0a720468d56446c8b500aba2879b2cd86ad02b Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 16:01:03 +0100 Subject: [PATCH 309/811] add version converter for editor transform to handle migration to uniform scale --- .../ToolsComponents/TransformComponent.cpp | 24 +++++++++++++++++-- .../ToolsComponents/TransformComponentBus.h | 1 + 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index 631478fcb0..74dfbb266d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -170,6 +170,23 @@ namespace AzToolsFramework return true; } + + bool EditorTransformDataConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) + { + if (classElement.GetVersion() < 3) + { + // version 3 replaces vector scale with uniform scale but does not yet delete the legacy scale data + // in order to allow for migration + AZ::Vector3 vectorScale; + if (classElement.FindSubElementAndGetData(AZ_CRC_CE("Scale"), vectorScale)) + { + const float uniformScale = vectorScale.GetMaxElement(); + classElement.AddElementWithData(context, "UniformScale", uniformScale); + } + } + + return true; + } } // namespace Internal TransformComponent::TransformComponent() @@ -1123,6 +1140,8 @@ namespace AzToolsFramework return AZ::Edit::PropertyRefreshLevels::EntireTree; } + + void TransformComponent::Reflect(AZ::ReflectContext* context) { // reflect data for script, serialization, editing.. @@ -1133,7 +1152,8 @@ namespace AzToolsFramework Field("Rotate", &EditorTransform::m_rotate)-> Field("Scale", &EditorTransform::m_scale)-> Field("Locked", &EditorTransform::m_locked)-> - Version(2); + Field("UniformScale", &EditorTransform::m_uniformScale)-> + Version(3, &Internal::EditorTransformDataConverter); serializeContext->Class()-> Field("Parent Entity", &TransformComponent::m_parentEntityId)-> @@ -1192,7 +1212,7 @@ namespace AzToolsFramework Attribute(AZ::Edit::Attributes::Suffix, " deg")-> Attribute(AZ::Edit::Attributes::ReadOnly, &EditorTransform::m_locked)-> Attribute(AZ::Edit::Attributes::SliceFlags, AZ::Edit::SliceFlags::NotPushableOnSliceRoot)-> - DataElement(TransformScaleHandler, &EditorTransform::m_scale, "Scale", "Local Scale")-> + DataElement(AZ::Edit::UIHandlers::Default, &EditorTransform::m_uniformScale, "Uniform Scale", "Local Uniform Scale")-> Attribute(AZ::Edit::Attributes::Step, 0.1f)-> Attribute(AZ::Edit::Attributes::ReadOnly, &EditorTransform::m_locked) ; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h index 437a39b1a0..48f9c25cf5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h @@ -42,6 +42,7 @@ namespace AzToolsFramework AZ::Vector3 m_translate; //! Translation in engine units (meters) AZ::Vector3 m_scale; + float m_uniformScale; AZ::Vector3 m_rotate; //! Rotation in degrees bool m_locked; }; From 1a0152c063fee575d127c844d1a968f44fc52ba8 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 16:06:05 +0100 Subject: [PATCH 310/811] remove custom transform scale UI handler --- .../ToolsComponents/TransformComponent.cpp | 1 - .../TransformScalePropertyHandler.cpp | 82 ------------------- .../TransformScalePropertyHandler.h | 56 ------------- .../PropertyManagerComponent.cpp | 2 - .../aztoolsframework_files.cmake | 2 - 5 files changed, 143 deletions(-) delete mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformScalePropertyHandler.cpp delete mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformScalePropertyHandler.h diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index 74dfbb266d..aff0684dfb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -32,7 +32,6 @@ #include #include #include -#include #include #include #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformScalePropertyHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformScalePropertyHandler.cpp deleted file mode 100644 index 94d0113bcf..0000000000 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformScalePropertyHandler.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "AzToolsFramework_precompiled.h" -#include -#include -#include - -namespace AzToolsFramework -{ - void RegisterTransformScaleHandler() - { - PropertyTypeRegistrationMessages::Bus::Broadcast(&PropertyTypeRegistrationMessages::RegisterPropertyType, aznew Components::TransformScalePropertyHandler()); - } - - namespace Components - { - AZ::u32 TransformScalePropertyHandler::GetHandlerName(void) const - { - return TransformScaleHandler; - } - - QWidget* TransformScalePropertyHandler::CreateGUI(QWidget* parent) - { - AzQtComponents::DoubleSpinBox* newCtrl = new AzQtComponents::DoubleSpinBox(parent); - connect(newCtrl, QOverload::of(&AzQtComponents::DoubleSpinBox::valueChanged), newCtrl, [newCtrl]() - { - AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestWrite, newCtrl); - }); - - newCtrl->setMinimum(AZ::MinTransformScale); - newCtrl->setMaximum(AZ::MaxTransformScale); - - return newCtrl; - } - - void TransformScalePropertyHandler::ConsumeAttribute(AzQtComponents::DoubleSpinBox* GUI, AZ::u32 attrib, - AzToolsFramework::PropertyAttributeReader* attrValue, [[maybe_unused]] const char* debugName) - { - if (attrib == AZ::Edit::Attributes::Suffix) - { - AZStd::string label; - if (attrValue->Read(label)) - { - GUI->setSuffix(label.c_str()); - } - } - } - - void TransformScalePropertyHandler::WriteGUIValuesIntoProperty([[maybe_unused]] size_t index, AzQtComponents::DoubleSpinBox* GUI, - AZ::Vector3& instance, [[maybe_unused]] AzToolsFramework::InstanceDataNode* node) - { - const float value = aznumeric_cast(GUI->value()); - const float currentMaxElement = instance.GetMaxElement(); - if (currentMaxElement != 0.0f) - { - instance *= value / currentMaxElement; - } - else - { - instance = AZ::Vector3(value); - } - } - - bool TransformScalePropertyHandler::ReadValuesIntoGUI([[maybe_unused]] size_t index, AzQtComponents::DoubleSpinBox* GUI, - const AZ::Vector3& instance, [[maybe_unused]] AzToolsFramework::InstanceDataNode* node) - { - QSignalBlocker signalBlocker(GUI); - GUI->setValue(instance.GetMaxElement()); - return true; - } - } // namespace Components -} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformScalePropertyHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformScalePropertyHandler.h deleted file mode 100644 index f13aa37904..0000000000 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformScalePropertyHandler.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#endif - -namespace AzToolsFramework -{ - namespace Components - { - static const AZ::Crc32 TransformScaleHandler = AZ_CRC_CE("TransformScale"); - - //! Handler to allow the scale field inside the Transform Component to be represented as a single value in - //! the editor, but stored internally as a Vector3. - //! The purpose for this is to prevent any new entities being created with non-uniform scale on the Transform - //! Component, but preserve the data required for migrating any existing entities to use the Non-Uniform Scale - //! Component, until all migration work is completed. - //! The value shown in the editor will be the maximum value from the scale vector, and changing the value in - //! the editor will update the vector so that its maximum value matches the newly edited value, but its - //! components retain their existing proportion. - //! For example, if the current vector scale is (2, 3, 4), the value in the editor will appear as 4. If the value - //! in the editor is updated to 2, then the vector scale will update to (1, 1.5, 2), keeping the same proportion - //! between the x, y and z components. - class TransformScalePropertyHandler - : public QObject - , public AzToolsFramework::PropertyHandler - { - Q_OBJECT //AUTOMOC - public: - AZ_CLASS_ALLOCATOR(TransformScalePropertyHandler, AZ::SystemAllocator, 0); - - AZ::u32 GetHandlerName(void) const override; - QWidget* CreateGUI(QWidget* parent) override; - void ConsumeAttribute(AzQtComponents::DoubleSpinBox* GUI, AZ::u32 attrib, - AzToolsFramework::PropertyAttributeReader* attrValue, const char* debugName) override; - void WriteGUIValuesIntoProperty(size_t index, AzQtComponents::DoubleSpinBox* GUI, - AZ::Vector3& instance, AzToolsFramework::InstanceDataNode* node) override; - bool ReadValuesIntoGUI(size_t index, AzQtComponents::DoubleSpinBox* GUI, - const AZ::Vector3& instance, AzToolsFramework::InstanceDataNode* node) override; - }; - } // namespace Components -} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp index bd61e6ceed..181885cc70 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp @@ -16,7 +16,6 @@ #include #include #include -#include namespace AzToolsFramework { @@ -38,7 +37,6 @@ namespace AzToolsFramework void RegisterButtonPropertyHandlers(); void RegisterMultiLineEditHandler(); void RegisterCrcHandler(); - void RegisterTransformScaleHandler(); void ReflectPropertyEditor(AZ::ReflectContext* context); namespace Components diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index aaf5c86d33..8d0180f6ce 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -293,8 +293,6 @@ set(FILES ToolsComponents/TransformComponent.h ToolsComponents/TransformComponent.cpp ToolsComponents/TransformComponentBus.h - ToolsComponents/TransformScalePropertyHandler.cpp - ToolsComponents/TransformScalePropertyHandler.h ToolsComponents/ScriptEditorComponent.cpp ToolsComponents/ScriptEditorComponent.h ToolsComponents/ToolsAssetCatalogComponent.cpp From 4442ca54857942ac091a4db3e010134576aa329b Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 16:16:21 +0100 Subject: [PATCH 311/811] remove registration of custom transform scale UI handler --- .../UI/PropertyEditor/PropertyManagerComponent.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp index 181885cc70..6dc5bdd001 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp @@ -190,7 +190,6 @@ namespace AzToolsFramework RegisterVectorHandlers(); RegisterButtonPropertyHandlers(); RegisterMultiLineEditHandler(); - RegisterTransformScaleHandler(); // GenericComboBoxHandlers RegisterGenericComboBoxHandler(); From 8d0051bae9aa2ddca1caed78b59e5690fdb34f14 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 16:25:58 +0100 Subject: [PATCH 312/811] update editor transform component to uniform scale --- .../ToolsComponents/TransformComponent.cpp | 30 +++++++++---------- .../ToolsComponents/TransformComponentBus.h | 10 +++---- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index aff0684dfb..3e13e6226b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -49,10 +49,10 @@ namespace AzToolsFramework { const AZ::u32 ParentEntityCRC = AZ_CRC("Parent Entity", 0x5b1b276c); - // Decompose a transform into euler angles in degrees, scale (along basis, any shear will be dropped), and translation. - void DecomposeTransform(const AZ::Transform& transform, AZ::Vector3& translation, AZ::Vector3& rotation, AZ::Vector3& scale) + // Decompose a transform into euler angles in degrees, uniform scale, and translation. + void DecomposeTransform(const AZ::Transform& transform, AZ::Vector3& translation, AZ::Vector3& rotation, float& scale) { - scale = transform.GetScale(); + scale = transform.GetUniformScale(); translation = transform.GetTranslation(); rotation = transform.GetRotation().GetEulerDegrees(); } @@ -119,7 +119,7 @@ namespace AzToolsFramework // Decompose the old slice-relative transform and set it as a our editor transform, // since the entity is now our parent. EditorTransform editorTransform; - DecomposeTransform(sliceRelTransform, editorTransform.m_translate, editorTransform.m_rotate, editorTransform.m_scale); + DecomposeTransform(sliceRelTransform, editorTransform.m_translate, editorTransform.m_rotate, editorTransform.m_uniformScale); editorTransformElement.Convert(context); editorTransformElement.SetData(context, editorTransform); } @@ -373,7 +373,7 @@ namespace AzToolsFramework AZ::Transform TransformComponent::GetLocalScaleTM() const { - return AZ::Transform::CreateUniformScale(m_editorTransform.m_scale.GetMaxElement()); + return AZ::Transform::CreateUniformScale(m_editorTransform.m_uniformScale); } const AZ::Transform& TransformComponent::GetLocalTM() @@ -390,12 +390,13 @@ namespace AzToolsFramework // given a local transform, update local transform. void TransformComponent::SetLocalTM(const AZ::Transform& finalTx) { - AZ::Vector3 tx, rot, scale; - Internal::DecomposeTransform(finalTx, tx, rot, scale); + AZ::Vector3 tx, rot; + float uniformScale; + Internal::DecomposeTransform(finalTx, tx, rot, uniformScale); m_editorTransform.m_translate = tx; m_editorTransform.m_rotate = rot; - m_editorTransform.m_scale = scale; + m_editorTransform.m_uniformScale = uniformScale; TransformChanged(); } @@ -618,18 +619,18 @@ namespace AzToolsFramework AZ::Vector3 TransformComponent::GetLocalScale() { AZ_WarningOnce("TransformComponent", false, "GetLocalScale is deprecated, please use GetLocalUniformScale instead"); - return m_editorTransform.m_scale; + return m_editorTransform.m_legacyScale; } void TransformComponent::SetLocalUniformScale(float scale) { - m_editorTransform.m_scale = AZ::Vector3(scale); + m_editorTransform.m_uniformScale = scale; TransformChanged(); } float TransformComponent::GetLocalUniformScale() { - return m_editorTransform.m_scale.GetMaxElement(); + return m_editorTransform.m_uniformScale; } float TransformComponent::GetWorldUniformScale() @@ -1139,8 +1140,6 @@ namespace AzToolsFramework return AZ::Edit::PropertyRefreshLevels::EntireTree; } - - void TransformComponent::Reflect(AZ::ReflectContext* context) { // reflect data for script, serialization, editing.. @@ -1149,7 +1148,7 @@ namespace AzToolsFramework serializeContext->Class()-> Field("Translate", &EditorTransform::m_translate)-> Field("Rotate", &EditorTransform::m_rotate)-> - Field("Scale", &EditorTransform::m_scale)-> + Field("Scale", &EditorTransform::m_legacyScale)-> Field("Locked", &EditorTransform::m_locked)-> Field("UniformScale", &EditorTransform::m_uniformScale)-> Version(3, &Internal::EditorTransformDataConverter); @@ -1239,7 +1238,8 @@ namespace AzToolsFramework { AzToolsFramework::ScopedUndoBatch undo("Reset transform values"); m_editorTransform.m_translate = AZ::Vector3::CreateZero(); - m_editorTransform.m_scale = AZ::Vector3::CreateOne(); + m_editorTransform.m_legacyScale = AZ::Vector3::CreateOne(); + m_editorTransform.m_uniformScale = 1.0f; m_editorTransform.m_rotate = AZ::Vector3::CreateZero(); OnTransformChanged(); SetDirty(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h index 48f9c25cf5..6e83d8180e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h @@ -30,7 +30,7 @@ namespace AzToolsFramework EditorTransform() { m_translate = AZ::Vector3::CreateZero(); - m_scale = AZ::Vector3::CreateOne(); + m_legacyScale = AZ::Vector3::CreateOne(); m_rotate = AZ::Vector3::CreateZero(); m_locked = false; } @@ -40,10 +40,10 @@ namespace AzToolsFramework return EditorTransform(); } - AZ::Vector3 m_translate; //! Translation in engine units (meters) - AZ::Vector3 m_scale; - float m_uniformScale; - AZ::Vector3 m_rotate; //! Rotation in degrees + AZ::Vector3 m_translate; //!< Translation in engine units (meters) + AZ::Vector3 m_legacyScale; //!< Legacy vector scale value, retained only for migration. + float m_uniformScale; //!< Single scale value applied uniformly. + AZ::Vector3 m_rotate; //!< Rotation in degrees bool m_locked; }; From faa2d4ea6a869042127349783797c4b5e1f2842a Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 16:36:48 +0100 Subject: [PATCH 313/811] fix initialization of uniform scale in editor transform component --- .../AzToolsFramework/ToolsComponents/TransformComponentBus.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h index 6e83d8180e..26fa4d758e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponentBus.h @@ -31,6 +31,7 @@ namespace AzToolsFramework { m_translate = AZ::Vector3::CreateZero(); m_legacyScale = AZ::Vector3::CreateOne(); + m_uniformScale = 1.0f; m_rotate = AZ::Vector3::CreateZero(); m_locked = false; } From 55d3d18c9be9d3777b49a942be3d7724e8fdbaaa Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 16:44:09 +0100 Subject: [PATCH 314/811] update transform component to remove vector scale transform function --- .../AzFramework/AzFramework/Components/TransformComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp index ef2816d355..b3c4f1b256 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp @@ -409,7 +409,7 @@ namespace AzFramework AZ::Vector3 TransformComponent::GetLocalScale() { AZ_WarningOnce("TransformComponent", false, "GetLocalScale is deprecated, please use GetLocalUniformScale instead"); - return m_localTM.GetScale(); + return AZ::Vector3(m_localTM.GetUniformScale()); } void TransformComponent::SetLocalUniformScale(float scale) From 2b35ed1d7f005603fb7cc524ae06170db11d4ca7 Mon Sep 17 00:00:00 2001 From: moudgils Date: Fri, 28 May 2021 08:50:27 -0700 Subject: [PATCH 315/811] Fixes to get monolithic builds working for ios --- Code/LauncherUnified/launcher_generator.cmake | 2 ++ .../AtomViewportDisplayInfo/Code/CMakeLists.txt | 2 +- cmake/Tools/common.py | 6 +++--- cmake/Tools/layout_tool.py | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Code/LauncherUnified/launcher_generator.cmake b/Code/LauncherUnified/launcher_generator.cmake index edb6655411..c5d60eb29e 100644 --- a/Code/LauncherUnified/launcher_generator.cmake +++ b/Code/LauncherUnified/launcher_generator.cmake @@ -179,6 +179,7 @@ function(ly_delayed_generate_static_modules_inl) ${launcher_unified_binary_dir}/${project_name}.GameLauncher/Includes/StaticModules.inl ) + ly_target_link_libraries(${project_name}.GameLauncher PRIVATE ${all_game_gem_dependencies}) if(PAL_TRAIT_BUILD_SERVER_SUPPORTED) get_property(server_gem_dependencies GLOBAL PROPERTY LY_STATIC_MODULE_PROJECTS_DEPENDENCIES_${project_name}.ServerLauncher) @@ -204,6 +205,7 @@ function(ly_delayed_generate_static_modules_inl) ${launcher_unified_binary_dir}/${project_name}.ServerLauncher/Includes/StaticModules.inl ) + ly_target_link_libraries(${project_name}.ServerLauncher PRIVATE ${all_server_gem_dependencies}) endif() endforeach() endif() diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt index de4ee9b4b5..0f134d4218 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt @@ -10,7 +10,7 @@ # ly_add_target( - NAME AtomViewportDisplayInfo GEM_MODULE + NAME AtomViewportDisplayInfo ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} NAMESPACE Gem FILES_CMAKE atomviewportdisplayinfo_files.cmake diff --git a/cmake/Tools/common.py b/cmake/Tools/common.py index 8189bb3ca3..c6a3e89e67 100755 --- a/cmake/Tools/common.py +++ b/cmake/Tools/common.py @@ -149,7 +149,7 @@ def get_bootstrap_values(bootstrap_dir, keys_to_extract): raise logging.error(f'Bootstrap.setreg file {bootstrap_file} does not exist.') result_map = {} - with bootstrap_file.open('r') as f: + with open(bootstrap_file, 'r') as f: try: json_data = json.load(f) except Exception as e: @@ -157,9 +157,9 @@ def get_bootstrap_values(bootstrap_dir, keys_to_extract): else: for search_key in keys_to_extract: try: - search_result = json_data["Amazon"]["AzCore"]["Bootstrap"][f'"{search_key}"'] + search_result = json_data["Amazon"]["AzCore"]["Bootstrap"][search_key] except KeyError as e: - logging.error(f'Bootstrap.setreg cannot find Amazon:AzCore:Bootstrap:{search_result}: {str(e)}') + logging.warning(f'Bootstrap.setreg cannot find /Amazon/AzCore/Bootstrap/{search_key}: {str(e)}') else: result_map[search_key] = search_result diff --git a/cmake/Tools/layout_tool.py b/cmake/Tools/layout_tool.py index 69f5b34ae7..3fcab241d7 100755 --- a/cmake/Tools/layout_tool.py +++ b/cmake/Tools/layout_tool.py @@ -107,7 +107,7 @@ def verify_layout(layout_dir, platform_name, project_path, asset_mode, asset_typ project_name_lower = project_path.lower() layout_path = pathlib.Path(layout_dir) - bootstrap_path = layout_path / 'Registry' + bootstrap_path = pathlib.Path(ROOT_ENGINE_PATH) / 'Registry' bootstrap_values = common.get_bootstrap_values(str(bootstrap_path), [f'{platform_name_lower}_remote_filesystem', f'{platform_name_lower}_connect_to_remote', f'{platform_name_lower}_wait_for_connect', From 1b1a8c0c951fc399dee5c97dea49fe4a80d98160 Mon Sep 17 00:00:00 2001 From: moudgils Date: Fri, 28 May 2021 08:55:03 -0700 Subject: [PATCH 316/811] Reverting changes not related to this PR --- .../Shaders/PostProcessing/LuminanceHistogramGenerator.azsl | 2 +- .../Shaders/PostProcessing/LuminanceHistogramGenerator.shader | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl index 9d01a12fd6..05cc870eea 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl @@ -20,7 +20,7 @@ ShaderResourceGroup PassSrg : SRG_PerPass { Texture2D m_inputTexture; - RWStructuredBuffer m_outputTexture; + RWBuffer m_outputTexture; } groupshared uint shared_histogramBins[NUM_HISTOGRAM_BINS]; diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader index f3dd11e11a..10f94cbff6 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader @@ -12,5 +12,6 @@ "type": "Compute" } ] - } + }, + "DisabledRHIBackends": ["metal"] } From 86a00c4679dbd85f218a1fa304e35e6f8f18781e Mon Sep 17 00:00:00 2001 From: moudgils Date: Fri, 28 May 2021 08:57:05 -0700 Subject: [PATCH 317/811] Reverting a minor change --- .../Shaders/PostProcessing/LuminanceHistogramGenerator.shader | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader index 10f94cbff6..f9040060d6 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader @@ -14,4 +14,5 @@ ] }, "DisabledRHIBackends": ["metal"] + } From 6a81dbe2585eb38eda0f84ed63c26b66b02048c6 Mon Sep 17 00:00:00 2001 From: moudgils Date: Fri, 28 May 2021 08:59:11 -0700 Subject: [PATCH 318/811] Reverting Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader --- .../Shaders/PostProcessing/LuminanceHistogramGenerator.shader | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader index f9040060d6..566144bab8 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader @@ -14,5 +14,5 @@ ] }, "DisabledRHIBackends": ["metal"] - + } From 96080d85e4f1fce178998afd991f56f4d84f2eeb Mon Sep 17 00:00:00 2001 From: AMZN-nggieber <52797929+AMZN-nggieber@users.noreply.github.com> Date: Fri, 28 May 2021 09:32:47 -0700 Subject: [PATCH 319/811] Project Manager Support Add Existing Projects, Removing, Copying, and Deleting (#961) * Add Add/RemoveProject to Python Bindings * Support Project, Add, Remove, Copy, Delete * Open parent directory when duplicating to discourage path in owning dir * Remove extra connects for new projects button * Center project image --- .../Source/ProjectButtonWidget.cpp | 43 ++-- .../Source/ProjectButtonWidget.h | 9 +- .../ProjectManager/Source/ProjectUtils.cpp | 196 ++++++++++++++++++ .../ProjectManager/Source/ProjectUtils.h | 28 +++ .../ProjectManager/Source/ProjectsScreen.cpp | 57 +++-- .../ProjectManager/Source/PythonBindings.cpp | 63 +++++- .../ProjectManager/Source/PythonBindings.h | 2 + .../Source/PythonBindingsInterface.h | 14 ++ .../project_manager_files.cmake | 2 + 9 files changed, 359 insertions(+), 55 deletions(-) create mode 100644 Code/Tools/ProjectManager/Source/ProjectUtils.cpp create mode 100644 Code/Tools/ProjectManager/Source/ProjectUtils.h diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp index 4be876e79f..72ffa686c1 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp @@ -12,6 +12,7 @@ #include + #include #include #include @@ -58,19 +59,15 @@ namespace O3DE::ProjectManager m_overlayLabel->setText(text); } - ProjectButton::ProjectButton(const QString& projectName, QWidget* parent) + ProjectButton::ProjectButton(const ProjectInfo& projectInfo, QWidget* parent) : QFrame(parent) - , m_projectName(projectName) - , m_projectImagePath(":/Resources/DefaultProjectImage.png") + , m_projectInfo(projectInfo) { - Setup(); - } + if (m_projectInfo.m_imagePath.isEmpty()) + { + m_projectInfo.m_imagePath = ":/DefaultProjectImage.png"; + } - ProjectButton::ProjectButton(const QString& projectName, const QString& projectImage, QWidget* parent) - : QFrame(parent) - , m_projectName(projectName) - , m_projectImagePath(projectImage) - { Setup(); } @@ -85,20 +82,22 @@ namespace O3DE::ProjectManager m_projectImageLabel = new LabelButton(this); m_projectImageLabel->setFixedSize(s_projectImageWidth, s_projectImageHeight); + m_projectImageLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); vLayout->addWidget(m_projectImageLabel); - m_projectImageLabel->setPixmap(QPixmap(m_projectImagePath).scaled(m_projectImageLabel->size(), Qt::KeepAspectRatioByExpanding)); + m_projectImageLabel->setPixmap( + QPixmap(m_projectInfo.m_imagePath).scaled(m_projectImageLabel->size(), Qt::KeepAspectRatioByExpanding)); QMenu* newProjectMenu = new QMenu(this); m_editProjectAction = newProjectMenu->addAction(tr("Edit Project Settings...")); - -#ifdef SHOW_ALL_PROJECT_ACTIONS - m_editProjectGemsAction = newProjectMenu->addAction(tr("Cutomize Gems...")); newProjectMenu->addSeparator(); m_copyProjectAction = newProjectMenu->addAction(tr("Duplicate")); newProjectMenu->addSeparator(); m_removeProjectAction = newProjectMenu->addAction(tr("Remove from O3DE")); - m_deleteProjectAction = newProjectMenu->addAction(tr("Delete the Project")); + m_deleteProjectAction = newProjectMenu->addAction(tr("Delete this Project")); + +#ifdef SHOW_ALL_PROJECT_ACTIONS + m_editProjectGemsAction = newProjectMenu->addAction(tr("Cutomize Gems...")); #endif QFrame* footer = new QFrame(this); @@ -106,7 +105,7 @@ namespace O3DE::ProjectManager hLayout->setContentsMargins(0, 0, 0, 0); footer->setLayout(hLayout); { - QLabel* projectNameLabel = new QLabel(m_projectName, this); + QLabel* projectNameLabel = new QLabel(m_projectInfo.m_displayName, this); hLayout->addWidget(projectNameLabel); QPushButton* projectMenuButton = new QPushButton(this); @@ -117,14 +116,14 @@ namespace O3DE::ProjectManager vLayout->addWidget(footer); - connect(m_projectImageLabel, &LabelButton::triggered, [this]() { emit OpenProject(m_projectName); }); - connect(m_editProjectAction, &QAction::triggered, [this]() { emit EditProject(m_projectName); }); + connect(m_projectImageLabel, &LabelButton::triggered, [this]() { emit OpenProject(m_projectInfo.m_path); }); + connect(m_editProjectAction, &QAction::triggered, [this]() { emit EditProject(m_projectInfo.m_path); }); + connect(m_copyProjectAction, &QAction::triggered, [this]() { emit CopyProject(m_projectInfo.m_path); }); + connect(m_removeProjectAction, &QAction::triggered, [this]() { emit RemoveProject(m_projectInfo.m_path); }); + connect(m_deleteProjectAction, &QAction::triggered, [this]() { emit DeleteProject(m_projectInfo.m_path); }); #ifdef SHOW_ALL_PROJECT_ACTIONS - connect(m_editProjectGemsAction, &QAction::triggered, [this]() { emit EditProjectGems(m_projectName); }); - connect(m_copyProjectAction, &QAction::triggered, [this]() { emit CopyProject(m_projectName); }); - connect(m_removeProjectAction, &QAction::triggered, [this]() { emit RemoveProject(m_projectName); }); - connect(m_deleteProjectAction, &QAction::triggered, [this]() { emit DeleteProject(m_projectName); }); + connect(m_editProjectGemsAction, &QAction::triggered, [this]() { emit EditProjectGems(m_projectInfo.m_path); }); #endif } diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h index 671debf6d0..e82b56b3fa 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h @@ -13,7 +13,8 @@ #pragma once #if !defined(Q_MOC_RUN) -#include +#include + #include #endif @@ -52,8 +53,7 @@ namespace O3DE::ProjectManager Q_OBJECT // AUTOMOC public: - explicit ProjectButton(const QString& projectName, QWidget* parent = nullptr); - explicit ProjectButton(const QString& projectName, const QString& projectImage, QWidget* parent = nullptr); + explicit ProjectButton(const ProjectInfo& m_projectInfo, QWidget* parent = nullptr); ~ProjectButton() = default; void SetButtonEnabled(bool enabled); @@ -70,8 +70,7 @@ namespace O3DE::ProjectManager private: void Setup(); - QString m_projectName; - QString m_projectImagePath; + ProjectInfo m_projectInfo; LabelButton* m_projectImageLabel; QAction* m_editProjectAction; QAction* m_editProjectGemsAction; diff --git a/Code/Tools/ProjectManager/Source/ProjectUtils.cpp b/Code/Tools/ProjectManager/Source/ProjectUtils.cpp new file mode 100644 index 0000000000..526e745d82 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ProjectUtils.cpp @@ -0,0 +1,196 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include +#include + +#include +#include +#include +#include + +namespace O3DE::ProjectManager +{ + namespace ProjectUtils + { + static bool WarnDirectoryOverwrite(const QString& path, QWidget* parent) + { + if (!QDir(path).isEmpty()) + { + QMessageBox::StandardButton warningResult = QMessageBox::warning( + parent, + QObject::tr("Overwrite Directory"), + QObject::tr("Directory is not empty! Are you sure you want to overwrite it?"), + QMessageBox::No | QMessageBox::Yes + ); + + if (warningResult != QMessageBox::Yes) + { + return false; + } + } + + return true; + } + + static bool IsDirectoryDescedent(const QString& possibleAncestorPath, const QString& possibleDecedentPath) + { + QDir ancestor(possibleAncestorPath); + QDir descendent(possibleDecedentPath); + + do + { + if (ancestor == descendent) + { + return false; + } + + descendent.cdUp(); + } + while (!descendent.isRoot()); + + return true; + } + + static bool CopyDirectory(const QString& origPath, const QString& newPath) + { + QDir original(origPath); + if (!original.exists()) + { + return false; + } + + for (QString directory : original.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) + { + QString newDirectoryPath = newPath + QDir::separator() + directory; + original.mkpath(newDirectoryPath); + + if (!CopyDirectory(origPath + QDir::separator() + directory, newDirectoryPath)) + { + return false; + } + } + + for (QString file : original.entryList(QDir::Files)) + { + if (!QFile::copy(origPath + QDir::separator() + file, newPath + QDir::separator() + file)) + return false; + } + + return true; + } + + bool AddProjectDialog(QWidget* parent) + { + QString path = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(parent, QObject::tr("Select Project Directory"))); + if (!path.isEmpty()) + { + return RegisterProject(path); + } + + return false; + } + + bool RegisterProject(const QString& path) + { + return PythonBindingsInterface::Get()->AddProject(path); + } + + bool UnregisterProject(const QString& path) + { + return PythonBindingsInterface::Get()->RemoveProject(path); + } + + bool CopyProjectDialog(const QString& origPath, QWidget* parent) + { + bool copyResult = false; + + QDir parentOrigDir(origPath); + parentOrigDir.cdUp(); + QString newPath = QDir::toNativeSeparators( + QFileDialog::getExistingDirectory(parent, QObject::tr("Select New Project Directory"), parentOrigDir.path())); + if (!newPath.isEmpty()) + { + if (!WarnDirectoryOverwrite(newPath, parent)) + { + return false; + } + + // TODO: Block UX and Notify User they need to wait + + copyResult = CopyProject(origPath, newPath); + } + + return copyResult; + } + + bool CopyProject(const QString& origPath, const QString& newPath) + { + // Disallow copying from or into subdirectory + if (!IsDirectoryDescedent(origPath, newPath) || !IsDirectoryDescedent(newPath, origPath)) + { + return false; + } + + if (!CopyDirectory(origPath, newPath)) + { + // Cleanup whatever mess was made + DeleteProjectFiles(newPath, true); + return false; + } + + if (!RegisterProject(newPath)) + { + DeleteProjectFiles(newPath, true); + } + + return true; + } + + bool DeleteProjectFiles(const QString& path, bool force) + { + QDir projectDirectory(path); + if (projectDirectory.exists()) + { + // Check if there is an actual project hereor just force it + if (force || PythonBindingsInterface::Get()->GetProject(path).IsSuccess()) + { + return projectDirectory.removeRecursively(); + } + } + + return false; + } + + bool MoveProject(const QString& origPath, const QString& newPath, QWidget* parent) + { + if (!WarnDirectoryOverwrite(newPath, parent) || !UnregisterProject(origPath)) + { + return false; + } + + QDir directory; + if (directory.rename(origPath, newPath)) + { + return directory.rename(origPath, newPath); + } + + if (!RegisterProject(newPath)) + { + return false; + } + + return true; + } + + } // namespace ProjectUtils +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectUtils.h b/Code/Tools/ProjectManager/Source/ProjectUtils.h new file mode 100644 index 0000000000..5982bff634 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ProjectUtils.h @@ -0,0 +1,28 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ +#pragma once + +#include + +namespace O3DE::ProjectManager +{ + namespace ProjectUtils + { + bool AddProjectDialog(QWidget* parent = nullptr); + bool RegisterProject(const QString& path); + bool UnregisterProject(const QString& path); + bool CopyProjectDialog(const QString& origPath, QWidget* parent = nullptr); + bool CopyProject(const QString& origPath, const QString& newPath); + bool DeleteProjectFiles(const QString& path, bool force = false); + bool MoveProject(const QString& origPath, const QString& newPath, QWidget* parent = nullptr); + } // namespace ProjectUtils +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp index 5f1c0e2b36..dd2e411ec5 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -65,9 +66,6 @@ namespace O3DE::ProjectManager m_stack->addWidget(m_projectsContent); vLayout->addWidget(m_stack); - - connect(m_createNewProjectAction, &QAction::triggered, this, &ProjectsScreen::HandleNewProjectButton); - connect(m_addExistingProjectAction, &QAction::triggered, this, &ProjectsScreen::HandleAddProjectButton); } QFrame* ProjectsScreen::CreateFirstTimeContent() @@ -167,28 +165,27 @@ namespace O3DE::ProjectManager #endif { ProjectButton* projectButton; + QString projectPreviewPath = project.m_path + m_projectPreviewImagePath; QFileInfo doesPreviewExist(projectPreviewPath); if (doesPreviewExist.exists() && doesPreviewExist.isFile()) { - projectButton = new ProjectButton(project.m_projectName, projectPreviewPath, this); - } - else - { - projectButton = new ProjectButton(project.m_projectName, this); + project.m_imagePath = projectPreviewPath; } + projectButton = new ProjectButton(project, this); + flowLayout->addWidget(projectButton); connect(projectButton, &ProjectButton::OpenProject, this, &ProjectsScreen::HandleOpenProject); connect(projectButton, &ProjectButton::EditProject, this, &ProjectsScreen::HandleEditProject); - - #ifdef DISPLAY_PROJECT_DEV_DATA - connect(projectButton, &ProjectButton::EditProjectGems, this, &ProjectsScreen::HandleEditProjectGems); connect(projectButton, &ProjectButton::CopyProject, this, &ProjectsScreen::HandleCopyProject); connect(projectButton, &ProjectButton::RemoveProject, this, &ProjectsScreen::HandleRemoveProject); connect(projectButton, &ProjectButton::DeleteProject, this, &ProjectsScreen::HandleDeleteProject); - #endif + +#ifdef SHOW_ALL_PROJECT_ACTIONS + connect(projectButton, &ProjectButton::EditProjectGems, this, &ProjectsScreen::HandleEditProjectGems); +#endif } layout->addWidget(projectsScrollArea); @@ -242,7 +239,11 @@ namespace O3DE::ProjectManager } void ProjectsScreen::HandleAddProjectButton() { - // Do nothing for now + if (ProjectUtils::AddProjectDialog(this)) + { + emit ResetScreenRequest(ProjectManagerScreen::Projects); + emit ChangeScreenRequest(ProjectManagerScreen::Projects); + } } void ProjectsScreen::HandleOpenProject(const QString& projectPath) { @@ -300,18 +301,36 @@ namespace O3DE::ProjectManager emit NotifyCurrentProject(projectPath); emit ChangeScreenRequest(ProjectManagerScreen::GemCatalog); } - void ProjectsScreen::HandleCopyProject([[maybe_unused]] const QString& projectPath) + void ProjectsScreen::HandleCopyProject(const QString& projectPath) { // Open file dialog and choose location for copied project then register copy with O3DE + if (ProjectUtils::CopyProjectDialog(projectPath, this)) + { + emit ResetScreenRequest(ProjectManagerScreen::Projects); + emit ChangeScreenRequest(ProjectManagerScreen::Projects); + } } - void ProjectsScreen::HandleRemoveProject([[maybe_unused]] const QString& projectPath) + void ProjectsScreen::HandleRemoveProject(const QString& projectPath) { - // Unregister Project from O3DE + // Unregister Project from O3DE and reload projects + if (ProjectUtils::UnregisterProject(projectPath)) + { + emit ResetScreenRequest(ProjectManagerScreen::Projects); + emit ChangeScreenRequest(ProjectManagerScreen::Projects); + } } - void ProjectsScreen::HandleDeleteProject([[maybe_unused]] const QString& projectPath) + void ProjectsScreen::HandleDeleteProject(const QString& projectPath) { - // Remove project from 03DE and delete from disk - ProjectsScreen::HandleRemoveProject(projectPath); + QMessageBox::StandardButton warningResult = QMessageBox::warning( + this, tr("Delete Project"), tr("Are you sure?\nProject will be removed from O3DE and directory will be deleted!"), + QMessageBox::No | QMessageBox::Yes); + + if (warningResult == QMessageBox::Yes) + { + // Remove project from O3DE and delete from disk + HandleRemoveProject(projectPath); + ProjectUtils::DeleteProjectFiles(projectPath); + } } void ProjectsScreen::NotifyCurrentScreen() diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 8c79a153c8..9279ad1291 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -379,13 +379,13 @@ namespace O3DE::ProjectManager pybind11::str defaultTemplatesFolder = engineInfo.m_defaultTemplatesFolder.toStdString(); auto registrationResult = m_registration.attr("register")( - enginePath, // engine_path - pybind11::none(), // project_path - pybind11::none(), // gem_path - pybind11::none(), // template_path - pybind11::none(), // restricted_path - pybind11::none(), // repo_uri - pybind11::none(), // default_engines_folder + enginePath, // engine_path + pybind11::none(), // project_path + pybind11::none(), // gem_path + pybind11::none(), // template_path + pybind11::none(), // restricted_path + pybind11::none(), // repo_uri + pybind11::none(), // default_engines_folder defaultProjectsFolder, defaultGemsFolder, defaultTemplatesFolder @@ -456,6 +456,51 @@ namespace O3DE::ProjectManager } } + bool PythonBindings::AddProject(const QString& path) + { + bool registrationResult = false; + bool result = ExecuteWithLock( + [&] + { + pybind11::str projectPath = path.toStdString(); + auto pythonRegistrationResult = m_registration.attr("register")(pybind11::none(), projectPath); + + // Returns an exit code so boolify it then invert result + registrationResult = !pythonRegistrationResult.cast(); + }); + + return result && registrationResult; + } + + bool PythonBindings::RemoveProject(const QString& path) + { + bool registrationResult = false; + bool result = ExecuteWithLock( + [&] + { + pybind11::str projectPath = path.toStdString(); + auto pythonRegistrationResult = m_registration.attr("register")( + pybind11::none(), // engine_path + projectPath, // project_path + pybind11::none(), // gem_path + pybind11::none(), // template_path + pybind11::none(), // restricted_path + pybind11::none(), // repo_uri + pybind11::none(), // default_engines_folder + pybind11::none(), // default_gems_folder + pybind11::none(), // default_templates_folder + pybind11::none(), // default_restricted_folder + pybind11::none(), // default_restricted_folder + true // remove + ); + + // Returns an exit code so boolify it then invert result + registrationResult = !pythonRegistrationResult.cast(); + }); + + return result && registrationResult; + } + AZ::Outcome PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo) { ProjectInfo createdProjectInfo; @@ -600,7 +645,7 @@ namespace O3DE::ProjectManager pybind11::none(), // gem_target pybind11::none(), // project_name pyProjectPath - ); + ); }); return result; @@ -618,7 +663,7 @@ namespace O3DE::ProjectManager pybind11::none(), // gem_target pybind11::none(), // project_name pyProjectPath - ); + ); }); return result; diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h index 892e13a65b..fb2303c495 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.h +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -46,6 +46,8 @@ namespace O3DE::ProjectManager AZ::Outcome CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo) override; AZ::Outcome GetProject(const QString& path) override; AZ::Outcome> GetProjects() override; + bool AddProject(const QString& path) override; + bool RemoveProject(const QString& path) override; bool UpdateProject(const ProjectInfo& projectInfo) override; bool AddGemToProject(const QString& gemPath, const QString& projectPath) override; bool RemoveGemFromProject(const QString& gemPath, const QString& projectPath) override; diff --git a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h index b5c8f1a76a..a58eea0fe6 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h +++ b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h @@ -88,6 +88,20 @@ namespace O3DE::ProjectManager * @return an outcome with ProjectInfos on success */ virtual AZ::Outcome> GetProjects() = 0; + + /** + * Adds existing project on disk + * @param path the absolute path to the project + * @return true on success, false on failure + */ + virtual bool AddProject(const QString& path) = 0; + + /** + * Adds existing project on disk + * @param path the absolute path to the project + * @return true on success, false on failure + */ + virtual bool RemoveProject(const QString& path) = 0; /** * Update a project diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index 223465f3c8..feaea4c172 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -36,6 +36,8 @@ set(FILES Source/PythonBindingsInterface.h Source/ProjectInfo.h Source/ProjectInfo.cpp + Source/ProjectUtils.h + Source/ProjectUtils.cpp Source/NewProjectSettingsScreen.h Source/NewProjectSettingsScreen.cpp Source/CreateProjectCtrl.h From c630ece43a2cc5c8fda029b5154d575321de58e8 Mon Sep 17 00:00:00 2001 From: Qing Tao <55564570+VickyAtAZ@users.noreply.github.com> Date: Fri, 28 May 2021 09:42:11 -0700 Subject: [PATCH 320/811] Add m_linearDepthTexture as input for transparent pass. This is required by popcornfx and it doesn't add extra cost to the render pipeline. --- .../Feature/Common/Assets/Passes/LowEndPipeline.pass | 7 +++++++ .../Feature/Common/Assets/Passes/MainPipeline.pass | 7 +++++++ .../Feature/Common/Assets/Passes/Transparent.pass | 6 ++++++ .../Common/Assets/Passes/TransparentParent.pass | 11 +++++++++++ .../Atom/Features/PBR/TransparentPassSrg.azsli | 1 + 5 files changed, 32 insertions(+) diff --git a/Gems/Atom/Feature/Common/Assets/Passes/LowEndPipeline.pass b/Gems/Atom/Feature/Common/Assets/Passes/LowEndPipeline.pass index b19569fb9d..38a4524aa2 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/LowEndPipeline.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/LowEndPipeline.pass @@ -243,6 +243,13 @@ "Attachment": "LightListRemapped" } }, + { + "LocalSlot": "InputLinearDepth", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "DepthLinear" + } + }, { "LocalSlot": "DepthStencil", "AttachmentRef": { diff --git a/Gems/Atom/Feature/Common/Assets/Passes/MainPipeline.pass b/Gems/Atom/Feature/Common/Assets/Passes/MainPipeline.pass index ee943f6d39..af7408b48c 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/MainPipeline.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/MainPipeline.pass @@ -251,6 +251,13 @@ "Attachment": "LightListRemapped" } }, + { + "LocalSlot": "InputLinearDepth", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "DepthLinear" + } + }, { "LocalSlot": "DepthStencil", "AttachmentRef": { diff --git a/Gems/Atom/Feature/Common/Assets/Passes/Transparent.pass b/Gems/Atom/Feature/Common/Assets/Passes/Transparent.pass index 415aa2fec0..3bb184a1f8 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/Transparent.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/Transparent.pass @@ -67,6 +67,12 @@ "ShaderInputName": "m_lightListRemapped", "ScopeAttachmentUsage": "Shader" }, + { + "Name": "InputLinearDepth", + "SlotType": "Input", + "ShaderInputName": "m_linearDepthTexture", + "ScopeAttachmentUsage": "Shader" + }, // Input/Outputs { "Name": "DepthStencil", diff --git a/Gems/Atom/Feature/Common/Assets/Passes/TransparentParent.pass b/Gems/Atom/Feature/Common/Assets/Passes/TransparentParent.pass index 32517484f3..b278f2bcb4 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/TransparentParent.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/TransparentParent.pass @@ -32,6 +32,10 @@ "Name": "LightListRemapped", "SlotType": "Input" }, + { + "Name": "InputLinearDepth", + "SlotType": "Input" + }, // Input/Outputs... { "Name": "DepthStencil", @@ -91,6 +95,13 @@ "Attachment": "LightListRemapped" } }, + { + "LocalSlot": "InputLinearDepth", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "InputLinearDepth" + } + }, // Input/Outputs... { "LocalSlot": "DepthStencil", diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/TransparentPassSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/TransparentPassSrg.azsli index 14cff21739..d9367f9d03 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/TransparentPassSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/TransparentPassSrg.azsli @@ -35,4 +35,5 @@ ShaderResourceGroup PassSrg : SRG_PerPass Texture2D m_tileLightData; StructuredBuffer m_lightListRemapped; + Texture2D m_linearDepthTexture; } From 9ad70608e8156017d066bb405424497446f61e7d Mon Sep 17 00:00:00 2001 From: pappeste Date: Fri, 28 May 2021 09:46:27 -0700 Subject: [PATCH 321/811] Fixing compilation failure --- Code/Tools/ProjectManager/Source/PythonBindings.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 9e6e50caf8..d1c1879609 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -466,7 +466,7 @@ namespace O3DE::ProjectManager [&] { pybind11::str projectPath = path.toStdString(); - auto pythonRegistrationResult = m_registration.attr("register")(pybind11::none(), projectPath); + auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath); // Returns an exit code so boolify it then invert result registrationResult = !pythonRegistrationResult.cast(); @@ -482,7 +482,7 @@ namespace O3DE::ProjectManager [&] { pybind11::str projectPath = path.toStdString(); - auto pythonRegistrationResult = m_registration.attr("register")( + auto pythonRegistrationResult = m_register.attr("register")( pybind11::none(), // engine_path projectPath, // project_path pybind11::none(), // gem_path From 7f8bd83d4ae93eba54f215be50245aff4dd4d6b3 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 17:54:30 +0100 Subject: [PATCH 322/811] remove SetScale and CreateScale vector scale functions from Transform --- Code/Framework/AzCore/AzCore/Math/Transform.cpp | 2 -- Code/Framework/AzCore/AzCore/Math/Transform.h | 4 ---- Code/Framework/AzCore/AzCore/Math/Transform.inl | 16 ---------------- .../Manipulators/ManipulatorSpace.cpp | 2 +- 4 files changed, 1 insertion(+), 23 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.cpp b/Code/Framework/AzCore/AzCore/Math/Transform.cpp index 0ae3e9c0ef..03c9578e85 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.cpp +++ b/Code/Framework/AzCore/AzCore/Math/Transform.cpp @@ -312,7 +312,6 @@ namespace AZ Method("SetRotation", &Transform::SetRotation)-> Method("GetScale", &Transform::GetScale)-> Method("GetUniformScale", &Transform::GetUniformScale)-> - Method("SetScale", &Transform::SetScale)-> Method("SetUniformScale", &Transform::SetUniformScale)-> Method("ExtractUniformScale", &Transform::ExtractUniformScale)-> Attribute(Script::Attributes::ExcludeFrom, Script::Attributes::ExcludeFlags::All)-> @@ -334,7 +333,6 @@ namespace AZ Method("CreateFromQuaternionAndTranslation", &Transform::CreateFromQuaternionAndTranslation)-> Method("CreateFromMatrix3x3", &Transform::CreateFromMatrix3x3)-> Method("CreateFromMatrix3x3AndTranslation", &Transform::CreateFromMatrix3x3AndTranslation)-> - Method("CreateScale", &Transform::CreateScale)-> Method("CreateUniformScale", &Transform::CreateUniformScale)-> Method("CreateTranslation", &Transform::CreateTranslation)-> Method("ConstructFromValuesNumeric", &Internal::ConstructTransformFromValues); diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.h b/Code/Framework/AzCore/AzCore/Math/Transform.h index 974a0180e8..ff7df7326b 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.h +++ b/Code/Framework/AzCore/AzCore/Math/Transform.h @@ -92,9 +92,6 @@ namespace AZ static Transform CreateFromMatrix3x4(const Matrix3x4& value); - //! Sets the transform to apply scale only, no rotation or translation. - static Transform CreateScale(const AZ::Vector3& scale); - //! Sets the transform to apply (uniform) scale only, no rotation or translation. static Transform CreateUniformScale(const float scale); @@ -127,7 +124,6 @@ namespace AZ Vector3 GetScale() const; float GetUniformScale() const; - void SetScale(const Vector3& v); void SetUniformScale(const float scale); //! Sets the transform's scale to a unit value and returns the previous scale value. diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.inl b/Code/Framework/AzCore/AzCore/Math/Transform.inl index 7550e2bdd8..3325a29f16 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.inl +++ b/Code/Framework/AzCore/AzCore/Math/Transform.inl @@ -63,16 +63,6 @@ namespace AZ return result; } - AZ_MATH_INLINE Transform Transform::CreateScale(const Vector3& scale) - { - AZ_WarningOnce("Transform", false, "CreateScale is deprecated, please use CreateUniformScale instead."); - Transform result; - result.m_rotation = Quaternion::CreateIdentity(); - result.m_scale = scale; - result.m_translation = Vector3::CreateZero(); - return result; - } - AZ_MATH_INLINE Transform Transform::CreateUniformScale(float scale) { Transform result; @@ -171,12 +161,6 @@ namespace AZ return m_scale.GetMaxElement(); } - AZ_MATH_INLINE void Transform::SetScale(const Vector3& scale) - { - AZ_WarningOnce("Transform", false, "SetScale is deprecated, please use SetUniformScale instead."); - m_scale = scale; - } - AZ_MATH_INLINE void Transform::SetUniformScale(const float scale) { m_scale = Vector3(scale); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.cpp index cd08a95af7..b3f691a62f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.cpp @@ -39,7 +39,7 @@ namespace AzToolsFramework AZ::Transform result; result.SetRotation(m_space.GetRotation() * localTransform.GetRotation()); result.SetTranslation(m_space.TransformPoint(m_nonUniformScale * localTransform.GetTranslation())); - result.SetScale(m_space.GetScale() * localTransform.GetUniformScale()); + result.SetUniformScale(m_space.GetUniformScale() * localTransform.GetUniformScale()); return result; } From ddab4cf53a4ef1f6e7f710530ded564775a3f733 Mon Sep 17 00:00:00 2001 From: pappeste Date: Fri, 28 May 2021 10:06:21 -0700 Subject: [PATCH 323/811] Fix for register python bindings --- Code/Tools/ProjectManager/Source/PythonBindings.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index d1c1879609..8db8492cae 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -384,11 +384,12 @@ namespace O3DE::ProjectManager auto registrationResult = m_register.attr("register")( enginePath, // engine_path pybind11::none(), // project_path - pybind11::none(), // gem_path + pybind11::none(), // gem_path + pybind11::none(), // external_subdir_path pybind11::none(), // template_path pybind11::none(), // restricted_path pybind11::none(), // repo_uri - pybind11::none(), // default_engines_folder + pybind11::none(), // default_engines_folder defaultProjectsFolder, defaultGemsFolder, defaultTemplatesFolder @@ -486,15 +487,19 @@ namespace O3DE::ProjectManager pybind11::none(), // engine_path projectPath, // project_path pybind11::none(), // gem_path + pybind11::none(), // external_subdir_path pybind11::none(), // template_path pybind11::none(), // restricted_path pybind11::none(), // repo_uri pybind11::none(), // default_engines_folder + pybind11::none(), // default_projects_folder pybind11::none(), // default_gems_folder pybind11::none(), // default_templates_folder pybind11::none(), // default_restricted_folder - pybind11::none(), // default_restricted_folder - true // remove + pybind11::none(), // external_subdir_engine_path + pybind11::none(), // external_subdir_project_path + true, // remove + false // force ); // Returns an exit code so boolify it then invert result From e73541c75115636513bab4aea5df1b78ce839ecb Mon Sep 17 00:00:00 2001 From: Terry Michaels Date: Fri, 28 May 2021 12:23:49 -0500 Subject: [PATCH 324/811] Allow selected click to edit entity names in the outliner (#1028) --- .../UI/Outliner/EntityOutlinerWidget.cpp | 9 +++++++-- .../UI/Outliner/EntityOutlinerWidget.hxx | 2 ++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp index cc65b61908..8293614525 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp @@ -172,7 +172,7 @@ namespace AzToolsFramework const int autoExpandDelayMilliseconds = 2500; m_gui->m_objectTree->setSelectionMode(QAbstractItemView::ExtendedSelection); - m_gui->m_objectTree->setEditTriggers(QAbstractItemView::EditKeyPressed); + SetDefaultTreeViewEditTriggers(); m_gui->m_objectTree->setAutoExpandDelay(autoExpandDelayMilliseconds); m_gui->m_objectTree->setDragEnabled(true); m_gui->m_objectTree->setDropIndicatorShown(true); @@ -850,6 +850,11 @@ namespace AzToolsFramework addAction(m_actionGoToEntitiesInViewport); } + void EntityOutlinerWidget::SetDefaultTreeViewEditTriggers() + { + m_gui->m_objectTree->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed); + } + void EntityOutlinerWidget::OnEntityPickModeStarted() { m_gui->m_objectTree->setDragEnabled(false); @@ -862,7 +867,7 @@ namespace AzToolsFramework { m_gui->m_objectTree->setDragEnabled(true); m_gui->m_objectTree->setSelectionMode(QAbstractItemView::ExtendedSelection); - m_gui->m_objectTree->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed); + SetDefaultTreeViewEditTriggers(); m_inObjectPickMode = false; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.hxx index 9a02febab2..6e3979a21e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.hxx @@ -166,6 +166,8 @@ namespace AzToolsFramework // to a given entity void QueueScrollToNewContent(const AZ::EntityId& entityId) override; + void SetDefaultTreeViewEditTriggers(); + void ScrollToNewContent(); bool m_scrollToNewContentQueued; bool m_scrollToSelectedEntity; From 2cfbdb2cc9af2a7dcbc1a21b517bc599e55d71be Mon Sep 17 00:00:00 2001 From: evanchia Date: Fri, 28 May 2021 10:41:37 -0700 Subject: [PATCH 325/811] moving intermittently failing smoke tests to sandbox suite --- AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index d351ec0e6c..7d946ee6e1 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt @@ -11,7 +11,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_pytest( NAME AutomatedTesting::SmokeTest - TEST_SUITE smoke + TEST_SUITE sandbox TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} TIMEOUT 1500 From 1369e29c73308fde5df1d28ca7bfc90af0fbc32f Mon Sep 17 00:00:00 2001 From: AMZN-stankowi Date: Fri, 28 May 2021 10:44:20 -0700 Subject: [PATCH 326/811] =?UTF-8?q?Abort=20calls=20in=20AssImp,=20which=20?= =?UTF-8?q?occur=20when=20an=20assert=20is=20hit=20in=20builds=20th?= =?UTF-8?q?=E2=80=A6=20(#1012)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Abort calls in AssImp, which occur when an assert is hit in builds that have asserts enabled (like debug) no longer generate a popup. Instead, they are captured as errors and an asset processing failure. * Added missing include * Added check for _WRITE_ABORT_MSG, so platforms that don't have it but have signals enabled (Linux profile) compile correctly --- .../SDKWrapper/AssImpSceneWrapper.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp index 2cda1e68ae..791af4bf68 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp @@ -17,6 +17,13 @@ #include #include +#if AZ_TRAIT_COMPILER_SUPPORT_CSIGNAL +#include +#include +#include +#include +#endif // AZ_TRAIT_COMPILER_SUPPORT_CSIGNAL + namespace AZ { namespace AssImpSDKWrapper @@ -34,10 +41,31 @@ namespace AZ { } +#if AZ_TRAIT_COMPILER_SUPPORT_CSIGNAL + void signal_handler(int signal) + { + AZ_TracePrintf( + SceneAPI::Utilities::ErrorWindow, + "Failed to import scene with Asset Importer library. An %s has occured in the library, this scene file cannot be parsed by the library.", + signal == SIGABRT ? "assert" : "unknown error"); + } +#endif // AZ_TRAIT_COMPILER_SUPPORT_CSIGNAL + bool AssImpSceneWrapper::LoadSceneFromFile(const char* fileName) { AZ_TracePrintf(SceneAPI::Utilities::LogWindow, "AssImpSceneWrapper::LoadSceneFromFile %s", fileName); AZ_TraceContext("Filename", fileName); + +#if AZ_TRAIT_COMPILER_SUPPORT_CSIGNAL + // Turn off the abort popup because it can disrupt automation. + // AssImp calls abort when asserts are enabled, and an assert is encountered. +#ifdef _WRITE_ABORT_MSG + _set_abort_behavior(0, _WRITE_ABORT_MSG); +#endif // #ifdef _WRITE_ABORT_MSG + // Instead, capture any calls to abort with a signal handler, and report them. + auto previous_handler = std::signal(SIGABRT, signal_handler); +#endif // AZ_TRAIT_COMPILER_SUPPORT_CSIGNAL + // aiProcess_JoinIdenticalVertices is not enabled because O3DE has a mesh optimizer that also does this, // this flag is disabled to keep AssImp output similar to FBX SDK to reduce downstream bugs for the initial AssImp release. // There's currently a minimum of properties and flags set to maximize compatibility with the existing node graph. @@ -49,6 +77,15 @@ namespace AZ | aiProcess_LimitBoneWeights //Limits the number of bones that can affect a vertex to a maximum value //dropping the least important and re-normalizing | aiProcess_GenNormals); //Generate normals for meshes + +#if AZ_TRAIT_COMPILER_SUPPORT_CSIGNAL + // Reset abort behavior for anything else that may call abort. + std::signal(SIGABRT, previous_handler); +#ifdef _WRITE_ABORT_MSG + _set_abort_behavior(1, _WRITE_ABORT_MSG); +#endif // #ifdef _WRITE_ABORT_MSG +#endif // AZ_TRAIT_COMPILER_SUPPORT_CSIGNAL + if (!m_assImpScene) { AZ_TracePrintf(SceneAPI::Utilities::ErrorWindow, "Failed to import Asset Importer Scene. Error returned: %s", m_importer.GetErrorString()); From 19dc993331ff092149b5066e0a074a470a6e8399 Mon Sep 17 00:00:00 2001 From: sharmajs-amzn <82233357+sharmajs-amzn@users.noreply.github.com> Date: Fri, 28 May 2021 10:47:38 -0700 Subject: [PATCH 327/811] {SPEC-6465} DeltaCatalog.xml does not contain value (#935) * fixes for Asset Bundler Periodic test --- Assets/Engine/SeedAssetList.seed | 492 ++++++++---------- .../bundler_batch_setup_fixture.py | 10 +- .../asset_bundler_batch_tests.py | 30 +- 3 files changed, 235 insertions(+), 297 deletions(-) diff --git a/Assets/Engine/SeedAssetList.seed b/Assets/Engine/SeedAssetList.seed index 45a02f7682..77ec509721 100644 --- a/Assets/Engine/SeedAssetList.seed +++ b/Assets/Engine/SeedAssetList.seed @@ -67,106 +67,98 @@ - + - + - + - + - + - - - - - - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -264,109 +256,101 @@ - - - - - - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -387,498 +371,474 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - - - - - - + - + - + - + - + - + - + - + - + - + - + - + - - - - - - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - - - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -896,14 +856,6 @@ - - - - - - - - @@ -928,29 +880,13 @@ - - - - - - - - - - - - - - - - - + - + @@ -1451,146 +1387,146 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -1699,42 +1635,42 @@ - + - + - + - + - + - + - + - + - + - + diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py index 7a85cb1813..34af4d9115 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py @@ -162,7 +162,7 @@ def bundler_batch_setup_fixture(request, workspace, asset_processor, timeout) -> else: cmd.append(f"--{key}") if append_defaults: - cmd.append(f"--project={workspace.project}") + cmd.append(f"--project-path={workspace.project}") return cmd # ****** @@ -300,9 +300,9 @@ def bundler_batch_setup_fixture(request, workspace, asset_processor, timeout) -> workspace.paths.engine_root(), "Code", "Framework", - "AzFramework", - "AzFramework", - "Platform", + "AzCore", + "AzCore", + "PlatformId", "PlatformDefaults.h", ) @@ -318,7 +318,7 @@ def bundler_batch_setup_fixture(request, workspace, asset_processor, timeout) -> if start_gathering: result = get_platform.match(line) # Try the regex if result: - platform_values[result.group(1).lower()] = counter + platform_values[result.group(1).replace("_ID", "").lower()] = counter counter = counter << 1 elif "(Invalid, -1)" in line: # The line right before the first platform start_gathering = True diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py index 8738e8acdf..1043bbaefa 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py @@ -302,7 +302,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): that generating debug information does not affect asset list creation """ helper = bundler_batch_helper - seed_list = os.path.join(workspace.paths.engine_root(), "Engine", "SeedAssetList.seed") # Engine seed list + seed_list = os.path.join(workspace.paths.engine_root(), "Assets", "Engine", "SeedAssetList.seed") # Engine seed list asset = r"levels\testdependencieslevel\level.pak" # Create Asset list @@ -377,7 +377,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): subcommands. """ helper = bundler_batch_helper - seed_list = os.path.join(workspace.paths.engine_root(), "Engine", "SeedAssetList.seed") # Engine seed list + seed_list = os.path.join(workspace.paths.engine_root(), "Assets", "Engine", "SeedAssetList.seed") # Engine seed list asset = r"levels\testdependencieslevel\level.pak" # Useful bundle locations / names (2 for comparing contents) @@ -465,7 +465,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): "Please rerun with commandline option: '--bundle_platforms=pc,mac'" # fmt:on - seed_list = os.path.join(workspace.paths.engine_root(), "Engine", "SeedAssetList.seed") # Engine seed list + seed_list = os.path.join(workspace.paths.engine_root(), "Assets", "Engine", "SeedAssetList.seed") # Engine seed list # Useful bundle / asset list locations bundle_dir = os.path.dirname(helper["bundle_file"]) @@ -502,13 +502,13 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): for bundle_file in bundle_files.values(): assert os.path.isfile(bundle_file) - # This asset is created on mac platform but not on windows - file_to_check = b"engineassets/shading/defaultprobe_cm.dds.5" # [use byte str because file is in binary] + # This asset is created both on mac and windows platform + file_to_check = b"engineassets/shading/defaultprobe_cm_ibldiffuse.tif.streamingimage" # [use byte str because file is in binary] # Extract the delta catalog file from pc archive. {file_to_check} SHOULD NOT be present for PC file_contents = helper.extract_file_content(bundle_files["pc"], "DeltaCatalog.xml") # fmt:off - assert file_to_check not in file_contents, \ + assert file_to_check in file_contents, \ f"{file_to_check} was found in DeltaCatalog.xml in pc bundle file {bundle_files['pc']}" # fmt:on @@ -619,7 +619,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): # Validate both mac and pc are activated for seed # fmt:off check_seed_platform(helper["seed_list_file"], test_asset, - helper["platform_values"]["pc"] + helper["platform_values"]["osx"]) + helper["platform_values"]["pc"] + helper["platform_values"]["mac"]) # fmt:on # Remove MAC platform @@ -651,7 +651,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): # Validate Mac platform was added back on. Save file contents # fmt:off all_lines = check_seed_platform(helper["seed_list_file"], test_asset, - helper["platform_values"]["pc"] + helper["platform_values"]["osx"]) + helper["platform_values"]["pc"] + helper["platform_values"]["mac"]) # fmt:on # Try to remove platform without specifying a platform to remove (should fail) @@ -1046,7 +1046,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): "--addDefaultSeedListFiles", "--platform=pc", "--print", - f"--project={workspace.project}" + f"--project-path={workspace.project}" ], universal_newlines=True, ) @@ -1115,7 +1115,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): bundle_result_path = os.path.join(bundles_folder, helper.platform_file_name("bundle.pak", workspace.asset_processor_platform)) - bundle_cache_path = os.path.join(workspace.paths.platform_cache(), workspace.project, + bundle_cache_path = os.path.join(workspace.paths.platform_cache(), "Bundles", helper.platform_file_name("bundle.pak", workspace.asset_processor_platform)) @@ -1156,13 +1156,15 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): # fmt:off def test_WindowsAndMac_FilesMarkedSkip_FilesAreSkipped(self, workspace, bundler_batch_helper): expected_assets = [ - "libs/particles/milestone2particles.xml", - "textures/milestone2/particles/fx_sparkstreak_01.dds" + "ui/canvases/lyshineexamples/animation/multiplesequences.uicanvas", + "ui/textures/prefab/button_normal.sprite" ] bundler_batch_helper.call_assetLists( assetListFile=bundler_batch_helper['asset_info_file_request'], - addSeed="libs/particles/milestone2particles.xml", - skip="textures/milestone2/particles/fx_launchermuzzlering_01.dds,textures/milestone2/particles/fx_launchermuzzlefront_01.dds" + addSeed="ui/canvases/lyshineexamples/animation/multiplesequences.uicanvas", + skip="ui/textures/prefab/button_disabled.sprite,ui/scripts/lyshineexamples/animation/multiplesequences.luac," + "ui/textures/prefab/tooltip_sliced.sprite,ui/scripts/lyshineexamples/unloadthiscanvasbutton.luac,fonts/vera.fontfamily,fonts/vera-italic.font," + "fonts/vera.font,fonts/vera-bold.font,fonts/vera-bold-italic.font,fonts/vera-italic.ttf,fonts/vera.ttf,fonts/vera-bold.ttf,fonts/vera-bold-italic.ttf" ) assert os.path.isfile(bundler_batch_helper["asset_info_file_result"]) assets_in_list = [] From 4267c434b10cff07eceaecb606a85d0229ec5c18 Mon Sep 17 00:00:00 2001 From: sconel Date: Fri, 28 May 2021 10:48:22 -0700 Subject: [PATCH 328/811] Add product asset dependency handling to SC builder --- .../Code/Builder/ScriptCanvasBuilderWorker.h | 1 + .../Builder/ScriptCanvasBuilderWorkerUtility.cpp | 13 +++++++++---- .../Libraries/Spawning/SpawnNodeable.cpp | 6 +++--- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorker.h b/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorker.h index 1d1ea1d4aa..fc9613c3a7 100644 --- a/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorker.h +++ b/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorker.h @@ -59,6 +59,7 @@ namespace ScriptCanvasBuilder QuantumLeap, DependencyArguments, DependencyRequirementsData, + AddAssetDependencySearch, // add new entries above Current, }; diff --git a/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorkerUtility.cpp b/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorkerUtility.cpp index ab59ddd840..36d3194632 100644 --- a/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorkerUtility.cpp +++ b/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorkerUtility.cpp @@ -681,6 +681,15 @@ namespace ScriptCanvasBuilder } AssetBuilderSDK::JobProduct jobProduct; + + // Scan our runtime input for any asset references + // Store them as product dependencies + AssetBuilderSDK::OutputObject(&runtimeData.m_input, + azrtti_typeid(), + input.runtimeScriptCanvasOutputPath, + azrtti_typeid(), + AZ_CRC("RuntimeData", 0x163310ae), jobProduct); + jobProduct.m_dependencies.push_back({ runtimeData.m_script.GetId(), {} }); for (const auto& assetDependency : runtimeData.m_requiredAssets) @@ -712,10 +721,6 @@ namespace ScriptCanvasBuilder } } - jobProduct.m_dependenciesHandled = true; - jobProduct.m_productFileName = input.runtimeScriptCanvasOutputPath; - jobProduct.m_productAssetType = azrtti_typeid(); - jobProduct.m_productSubID = AZ_CRC("RuntimeData", 0x163310ae); input.response->m_outputProducts.push_back(AZStd::move(jobProduct)); return AZ::Success(); } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index 1bfd3e2386..b93844b989 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -89,18 +89,18 @@ namespace ScriptCanvas::Nodeables::Spawning rootAssetId.m_subId = rootSubId; m_spawnableAsset = AZ::Data::AssetManager::Instance(). - FindOrCreateAsset(rootAssetId, AZ::Data::AssetLoadBehavior::PreLoad); + FindOrCreateAsset(rootAssetId, AZ::Data::AssetLoadBehavior::Default); } else { - m_spawnableAsset.SetAutoLoadBehavior(AZ::Data::AssetLoadBehavior::PreLoad); + m_spawnableAsset.SetAutoLoadBehavior(AZ::Data::AssetLoadBehavior::Default); } } } void SpawnNodeable::RequestSpawn(Data::Vector3Type translation, Data::Vector3Type rotation, Data::NumberType scale) { - if (!m_spawnableAsset.IsReady()) + if (m_spawnableAsset.GetAutoLoadBehavior() == AZ::Data::AssetLoadBehavior::NoLoad) { return; } From eee7bb219ad900643cb4446577e942bc4223f726 Mon Sep 17 00:00:00 2001 From: Vincent Liu <5900509+onecent1101@users.noreply.github.com> Date: Fri, 28 May 2021 10:50:23 -0700 Subject: [PATCH 329/811] [LYN-3996] Update core editor menu (#1030) --- .../Components/Widgets/Menu.qss | 2 +- .../Images/Notifications/link.svg | 4 + .../AzQtComponents/Images/resources.qrc | 1 + .../Private/Editor/AWSCoreEditorManager.h | 2 +- .../Editor/Constants/AWSCoreEditorMenuLinks.h | 53 +++++++++ .../Editor/Constants/AWSCoreEditorMenuNames.h | 44 ++++++++ .../Private/Editor/UI/AWSCoreEditorMenu.h | 14 +-- .../Source/Editor/AWSCoreEditorManager.cpp | 2 +- .../Source/Editor/UI/AWSCoreEditorMenu.cpp | 102 ++++++++++++++---- .../AWSCoreEditorSystemComponentTest.cpp | 4 +- .../Tests/Editor/UI/AWSCoreEditorMenuTest.cpp | 6 +- Gems/AWSCore/Code/awscore_editor_files.cmake | 2 + 12 files changed, 198 insertions(+), 38 deletions(-) create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Images/Notifications/link.svg create mode 100644 Gems/AWSCore/Code/Include/Private/Editor/Constants/AWSCoreEditorMenuLinks.h create mode 100644 Gems/AWSCore/Code/Include/Private/Editor/Constants/AWSCoreEditorMenuNames.h diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/Menu.qss b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/Menu.qss index af9c675f23..7f48637cc8 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/Menu.qss +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/Menu.qss @@ -49,7 +49,7 @@ QMenu::right-arrow QMenu::icon { - right: 8px; + right: 20px; } QMenu::indicator:checked diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Images/Notifications/link.svg b/Code/Framework/AzQtComponents/AzQtComponents/Images/Notifications/link.svg new file mode 100644 index 0000000000..dfd21d157f --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Images/Notifications/link.svg @@ -0,0 +1,4 @@ + + + + diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Images/resources.qrc b/Code/Framework/AzQtComponents/AzQtComponents/Images/resources.qrc index dbbf0e78e2..7b0c6530ab 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Images/resources.qrc +++ b/Code/Framework/AzQtComponents/AzQtComponents/Images/resources.qrc @@ -13,5 +13,6 @@ Notifications/checkmark.svg Notifications/download.svg + Notifications/link.svg diff --git a/Gems/AWSCore/Code/Include/Private/Editor/AWSCoreEditorManager.h b/Gems/AWSCore/Code/Include/Private/Editor/AWSCoreEditorManager.h index 721cd6dd6a..98467727ea 100644 --- a/Gems/AWSCore/Code/Include/Private/Editor/AWSCoreEditorManager.h +++ b/Gems/AWSCore/Code/Include/Private/Editor/AWSCoreEditorManager.h @@ -18,7 +18,7 @@ namespace AWSCore class AWSCoreEditorManager { public: - static constexpr const char CLOUD_SERVICES_MENU_TEXT[] = "&Cloud services"; + static constexpr const char AWS_MENU_TEXT[] = "&AWS"; AWSCoreEditorManager(); virtual ~AWSCoreEditorManager(); diff --git a/Gems/AWSCore/Code/Include/Private/Editor/Constants/AWSCoreEditorMenuLinks.h b/Gems/AWSCore/Code/Include/Private/Editor/Constants/AWSCoreEditorMenuLinks.h new file mode 100644 index 0000000000..46acfbd4a3 --- /dev/null +++ b/Gems/AWSCore/Code/Include/Private/Editor/Constants/AWSCoreEditorMenuLinks.h @@ -0,0 +1,53 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#pragma once + +namespace AWSCore +{ + static constexpr const char NewToAWSUrl[] = "https://docs.o3de.org/docs/user-guide/gems/reference/aws/"; + + static constexpr const char AWSAndScriptCanvasUrl[] = "https://docs.o3de.org/docs/user-guide/components/reference/aws/"; + static constexpr const char AWSAndComponentsUrl[] = "https://docs.o3de.org/docs/user-guide/components/reference/aws/"; + static constexpr const char CallAWSResourcesUrl[] = "https://docs.o3de.org/docs/user-guide/components/reference/aws/"; + + static constexpr const char AWSCredentialConfigurationUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-core/configuring-credentials/"; + + static constexpr const char AWSClientAuthGemOverviewUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-client-auth/"; + static constexpr const char AWSClientAuthCDKAndResourcesUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-client-auth/"; + static constexpr const char AWSClientAuthScriptCanvasAndLuaUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-client-auth/"; + static constexpr const char AWSClientAuth3rdPartyAuthProviderUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-client-auth/"; + static constexpr const char AWSClientAuthCustomAuthProviderUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-client-auth/"; + static constexpr const char AWSClientAuthPlatformSpecificUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-client-auth/"; + static constexpr const char AWSClientAuthAPIReferenceUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-client-auth/"; + + static constexpr const char AWSMetricsGemOverviewUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-metrics/"; + static constexpr const char AWSMetricsSetupGemUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-metrics/"; + static constexpr const char AWSMetricsScriptingUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-metrics/"; + static constexpr const char AWSMetricsAPIReferenceUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-metrics/"; + static constexpr const char AWSMetricsAdvancedTopicsUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-metrics/"; + static constexpr const char AWSMetricsSettingsUrl[] = + "https://docs.o3de.org/docs/user-guide/gems/reference/aws/aws-metrics/"; +} // namespace AWSCore diff --git a/Gems/AWSCore/Code/Include/Private/Editor/Constants/AWSCoreEditorMenuNames.h b/Gems/AWSCore/Code/Include/Private/Editor/Constants/AWSCoreEditorMenuNames.h new file mode 100644 index 0000000000..a9a8198e52 --- /dev/null +++ b/Gems/AWSCore/Code/Include/Private/Editor/Constants/AWSCoreEditorMenuNames.h @@ -0,0 +1,44 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#pragma once + +namespace AWSCore +{ + static constexpr const char NewToAWSActionText[] = "Getting started with AWS?"; + + static constexpr const char AWSAndO3DEGlobalDocsText[] = "AWS & O3DE global docs"; + static constexpr const char AWSAndScriptCanvasActionText[] = "AWS && ScriptCanvas"; + static constexpr const char AWSAndComponentsActionText[] = "AWS & Components"; + static constexpr const char CallAWSResourcesActionText[] = "Call AWS resources"; + + static constexpr const char AWSCredentialConfigurationActionText[] = "AWS credential configuration"; + + static constexpr const char AWSResourceMappingToolActionText[] = "AWS Resource Mapping Tool..."; + + static constexpr const char AWSClientAuthActionText[] = "Client Auth"; + static constexpr const char AWSClientAuthGemOverviewActionText[] = "Gem Overview"; + static constexpr const char AWSClientAuthCDKAndResourcesActionText[] = "CDK Application and Resource Mappings"; + static constexpr const char AWSClientAuthScriptCanvasAndLuaActionText[] = "Script Canvas and Lua"; + static constexpr const char AWSClientAuth3rdPartyAuthProviderActionText[] = "3rd Party developer Authentication Provider support"; + static constexpr const char AWSClientAuthCustomAuthProviderActionText[] = "Custom developer Authentication Provider support"; + static constexpr const char AWSClientAuthPlatformSpecificActionText[] = "Platform specific Callouts"; + static constexpr const char AWSClientAuthAPIReferenceActionText[] = "API Reference"; + + static constexpr const char AWSMetricsActionText[] = "Metrics"; + static constexpr const char AWSMetricsGemOverviewActionText[] = "Metrics Overview"; + static constexpr const char AWSMetricsSetupGemActionText[] = "Setup Metrics Gem"; + static constexpr const char AWSMetricsScriptingActionText[] = "Scripting with AWS Metrics"; + static constexpr const char AWSMetricsAPIReferenceActionText[] = "C++ API with AWS Metrics Gem"; + static constexpr const char AWSMetricsAdvancedTopicsActionText[] = "Advanced topics"; + static constexpr const char AWSMetricsSettingsActionText[] = "Metrics Settings"; +} // namespace AWSCore diff --git a/Gems/AWSCore/Code/Include/Private/Editor/UI/AWSCoreEditorMenu.h b/Gems/AWSCore/Code/Include/Private/Editor/UI/AWSCoreEditorMenu.h index 19f241e368..c892f86b66 100644 --- a/Gems/AWSCore/Code/Include/Private/Editor/UI/AWSCoreEditorMenu.h +++ b/Gems/AWSCore/Code/Include/Private/Editor/UI/AWSCoreEditorMenu.h @@ -35,29 +35,23 @@ namespace AWSCore static constexpr const char AWSResourceMappingToolIsRunningText[] = "Resource Mapping Tool is running..."; static constexpr const char AWSResourceMappingToolLogWarningText[] = "Failed to launch Resource Mapping Tool, please check logs for details."; - static constexpr const char AWSResourceMappingToolActionText[] = "AWS Resource Mapping Tool..."; - static constexpr const char CredentialConfigurationActionText[] = "Credential Configuration"; - static constexpr const char CredentialConfigurationUrl[] = "https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/credentials.html"; - static constexpr const char NewToAWSActionText[] = "New to AWS?"; - static constexpr const char NewToAWSUrl[] = "https://o3deorg.netlify.app/docs/user-guide/gems/reference/aws"; - static constexpr const char AWSAndScriptCanvasActionText[] = "AWS && ScriptCanvas"; - static constexpr const char AWSAndScriptCanvasUrl[] = "https://o3deorg.netlify.app/docs/user-guide/gems/reference/aws"; - static constexpr const char AWSClientAuthActionText[] = "Client Auth"; - static constexpr const char AWSMetricsActionText[] = "Metrics"; AWSCoreEditorMenu(const QString& text); ~AWSCoreEditorMenu(); private: + QAction* AddExternalLinkAction(const AZStd::string& name, const AZStd::string& url, const AZStd::string& icon = ""); + void InitializeResourceMappingToolAction(); void InitializeAWSDocActions(); + void InitializeAWSGlobalDocsSubMenu(); void InitializeAWSFeatureGemActions(); // AWSCoreEditorRequestBus interface implementation void SetAWSClientAuthEnabled() override; void SetAWSMetricsEnabled() override; - void SetAWSFeatureActionsEnabled(const AZStd::string actionText); + QMenu* SetAWSFeatureSubMenu(const AZStd::string& menuText); // To improve experience, use process watcher to keep track of ongoing tool process AZStd::unique_ptr m_resourceMappingToolWatcher; diff --git a/Gems/AWSCore/Code/Source/Editor/AWSCoreEditorManager.cpp b/Gems/AWSCore/Code/Source/Editor/AWSCoreEditorManager.cpp index 1e3e44255a..89956d61b8 100644 --- a/Gems/AWSCore/Code/Source/Editor/AWSCoreEditorManager.cpp +++ b/Gems/AWSCore/Code/Source/Editor/AWSCoreEditorManager.cpp @@ -16,7 +16,7 @@ namespace AWSCore { AWSCoreEditorManager::AWSCoreEditorManager() - : m_awsCoreEditorMenu(new AWSCoreEditorMenu(CLOUD_SERVICES_MENU_TEXT)) + : m_awsCoreEditorMenu(new AWSCoreEditorMenu(AWS_MENU_TEXT)) { } diff --git a/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreEditorMenu.cpp b/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreEditorMenu.cpp index 754cc32751..c319788547 100644 --- a/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreEditorMenu.cpp +++ b/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreEditorMenu.cpp @@ -13,10 +13,13 @@ #include #include #include +#include #include #include #include +#include +#include #include #include @@ -36,8 +39,8 @@ namespace AWSCore : QMenu(text) , m_resourceMappingToolWatcher(nullptr) { - InitializeResourceMappingToolAction(); InitializeAWSDocActions(); + InitializeResourceMappingToolAction(); this->addSeparator(); InitializeAWSFeatureGemActions(); @@ -58,6 +61,21 @@ namespace AWSCore this->clear(); } + QAction* AWSCoreEditorMenu::AddExternalLinkAction( + const AZStd::string& name, const AZStd::string& url, const AZStd::string& icon) + { + QAction* linkAction = new QAction(QObject::tr(name.c_str())); + QObject::connect(linkAction, &QAction::triggered, this, + [url]() { + QDesktopServices::openUrl(QUrl(url.c_str())); + }); + if (!icon.empty()) + { + linkAction->setIcon(QIcon(icon.c_str())); + } + return linkAction; + } + void AWSCoreEditorMenu::InitializeResourceMappingToolAction() { #ifdef AWSCORE_EDITOR_RESOURCE_MAPPING_TOOL_ENABLED @@ -103,21 +121,21 @@ namespace AWSCore void AWSCoreEditorMenu::InitializeAWSDocActions() { - QAction* credentialConfiguration = new QAction(QObject::tr(CredentialConfigurationActionText)); - QObject::connect(credentialConfiguration, &QAction::triggered, this, []() { - QDesktopServices::openUrl(QUrl(CredentialConfigurationUrl)); - }); - this->addAction(credentialConfiguration); + this->addAction(AddExternalLinkAction(NewToAWSActionText, NewToAWSUrl, ":/Notifications/link.svg")); - QAction* newToAWS = new QAction(QObject::tr(NewToAWSActionText)); - QObject::connect(newToAWS, &QAction::triggered, this, []() { - QDesktopServices::openUrl(QUrl(NewToAWSUrl)); }); - this->addAction(newToAWS); + InitializeAWSGlobalDocsSubMenu(); - QAction* awsAndScriptCanvas = new QAction(QObject::tr(AWSAndScriptCanvasActionText)); - QObject::connect(awsAndScriptCanvas, &QAction::triggered, this, []() { - QDesktopServices::openUrl(QUrl(AWSAndScriptCanvasUrl)); }); - this->addAction(awsAndScriptCanvas); + this->addAction(AddExternalLinkAction( + AWSCredentialConfigurationActionText, AWSCredentialConfigurationUrl, ":/Notifications/link.svg")); + } + + void AWSCoreEditorMenu::InitializeAWSGlobalDocsSubMenu() + { + QMenu* globalDocsMenu = this->addMenu(QObject::tr(AWSAndO3DEGlobalDocsText)); + + globalDocsMenu->addAction(AddExternalLinkAction(AWSAndScriptCanvasActionText, AWSAndScriptCanvasUrl, ":/Notifications/link.svg")); + globalDocsMenu->addAction(AddExternalLinkAction(AWSAndComponentsActionText, AWSAndComponentsUrl, ":/Notifications/link.svg")); + globalDocsMenu->addAction(AddExternalLinkAction(CallAWSResourcesActionText, CallAWSResourcesUrl, ":/Notifications/link.svg")); } void AWSCoreEditorMenu::InitializeAWSFeatureGemActions() @@ -135,25 +153,67 @@ namespace AWSCore void AWSCoreEditorMenu::SetAWSClientAuthEnabled() { - SetAWSFeatureActionsEnabled(AWSClientAuthActionText); + // TODO: instead of creating submenu in core editor, aws feature gem should return submenu component directly + QMenu* subMenu = SetAWSFeatureSubMenu(AWSClientAuthActionText); + + subMenu->addAction(AddExternalLinkAction( + AWSClientAuthGemOverviewActionText, AWSClientAuthGemOverviewUrl, ":/Notifications/link.svg")); + subMenu->addAction(AddExternalLinkAction( + AWSClientAuthCDKAndResourcesActionText, AWSClientAuthCDKAndResourcesUrl, ":/Notifications/link.svg")); + subMenu->addAction(AddExternalLinkAction( + AWSClientAuthScriptCanvasAndLuaActionText, AWSClientAuthScriptCanvasAndLuaUrl, ":/Notifications/link.svg")); + subMenu->addAction(AddExternalLinkAction( + AWSClientAuth3rdPartyAuthProviderActionText, AWSClientAuth3rdPartyAuthProviderUrl, ":/Notifications/link.svg")); + subMenu->addAction(AddExternalLinkAction( + AWSClientAuthCustomAuthProviderActionText, AWSClientAuthCustomAuthProviderUrl, ":/Notifications/link.svg")); + subMenu->addAction(AddExternalLinkAction( + AWSClientAuthPlatformSpecificActionText, AWSClientAuthPlatformSpecificUrl, ":/Notifications/link.svg")); + subMenu->addAction(AddExternalLinkAction( + AWSClientAuthAPIReferenceActionText, AWSClientAuthAPIReferenceUrl, ":/Notifications/link.svg")); } void AWSCoreEditorMenu::SetAWSMetricsEnabled() { - SetAWSFeatureActionsEnabled(AWSMetricsActionText); + // TODO: instead of creating submenu in core editor, aws feature gem should return submenu component directly + QMenu* subMenu = SetAWSFeatureSubMenu(AWSMetricsActionText); + + subMenu->addAction(AddExternalLinkAction( + AWSMetricsGemOverviewActionText, AWSMetricsGemOverviewUrl, ":/Notifications/link.svg")); + subMenu->addAction(AddExternalLinkAction( + AWSMetricsSetupGemActionText, AWSMetricsSetupGemUrl, ":/Notifications/link.svg")); + subMenu->addAction(AddExternalLinkAction( + AWSMetricsScriptingActionText, AWSMetricsScriptingUrl, ":/Notifications/link.svg")); + subMenu->addAction(AddExternalLinkAction( + AWSMetricsAPIReferenceActionText, AWSMetricsAPIReferenceUrl, ":/Notifications/link.svg")); + subMenu->addAction(AddExternalLinkAction( + AWSMetricsAdvancedTopicsActionText, AWSMetricsAdvancedTopicsUrl, ":/Notifications/link.svg")); + + AZStd::string priorAlias = AZ::IO::FileIOBase::GetInstance()->GetAlias("@devroot@"); + AZStd::string configFilePath = priorAlias + "\\Gems\\AWSMetrics\\Code\\" + AZ::SettingsRegistryInterface::RegistryFolder; + AzFramework::StringFunc::Path::Normalize(configFilePath); + + QAction* settingsAction = new QAction(QObject::tr(AWSMetricsSettingsActionText)); + QObject::connect(settingsAction, &QAction::triggered, this, + [configFilePath](){ + QDesktopServices::openUrl(QUrl::fromLocalFile(configFilePath.c_str())); + }); + subMenu->addAction(settingsAction); } - void AWSCoreEditorMenu::SetAWSFeatureActionsEnabled(const AZStd::string actionText) + QMenu* AWSCoreEditorMenu::SetAWSFeatureSubMenu(const AZStd::string& menuText) { auto actionList = this->actions(); for (QList::iterator itr = actionList.begin(); itr != actionList.end(); itr++) { - if (QString::compare((*itr)->text(), actionText.c_str()) == 0) + if (QString::compare((*itr)->text(), menuText.c_str()) == 0) { - (*itr)->setIcon(QIcon(QString(":/Notifications/checkmark.svg"))); - (*itr)->setEnabled(true); - break; + QMenu* subMenu = new QMenu(QObject::tr(menuText.c_str())); + subMenu->setIcon(QIcon(QString(":/Notifications/checkmark.svg"))); + this->insertMenu(*itr, subMenu); + this->removeAction(*itr); + return subMenu; } } + return nullptr; } } // namespace AWSCore diff --git a/Gems/AWSCore/Code/Tests/AWSCoreEditorSystemComponentTest.cpp b/Gems/AWSCore/Code/Tests/AWSCoreEditorSystemComponentTest.cpp index e9c249f1c8..ff78d8e252 100644 --- a/Gems/AWSCore/Code/Tests/AWSCoreEditorSystemComponentTest.cpp +++ b/Gems/AWSCore/Code/Tests/AWSCoreEditorSystemComponentTest.cpp @@ -85,7 +85,7 @@ TEST_F(AWSCoreEditorSystemComponentTest, NotifyMainWindowInitialized_HaveDummyMe testMenuBar->addMenu("dummy menu"); AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::NotifyMainWindowInitialized, &testMainWindow); EXPECT_TRUE(testMenuBar->actions().size() == 2); - EXPECT_TRUE(QString::compare(testMenuBar->actions()[1]->text(), AWSCoreEditorManager::CLOUD_SERVICES_MENU_TEXT) == 0); + EXPECT_TRUE(QString::compare(testMenuBar->actions()[1]->text(), AWSCoreEditorManager::AWS_MENU_TEXT) == 0); } TEST_F(AWSCoreEditorSystemComponentTest, NotifyMainWindowInitialized_HaveHelpMenuInMenuBar_ExpectedMenuGetsAddedAtFront) @@ -95,5 +95,5 @@ TEST_F(AWSCoreEditorSystemComponentTest, NotifyMainWindowInitialized_HaveHelpMen testMenuBar->addMenu(AWSCoreEditorSystemComponent::EDITOR_HELP_MENU_TEXT); AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::NotifyMainWindowInitialized, &testMainWindow); EXPECT_TRUE(testMenuBar->actions().size() == 2); - EXPECT_TRUE(QString::compare(testMenuBar->actions()[0]->text(), AWSCoreEditorManager::CLOUD_SERVICES_MENU_TEXT) == 0); + EXPECT_TRUE(QString::compare(testMenuBar->actions()[0]->text(), AWSCoreEditorManager::AWS_MENU_TEXT) == 0); } diff --git a/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreEditorMenuTest.cpp b/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreEditorMenuTest.cpp index 7a578d2bbe..bde2a43993 100644 --- a/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreEditorMenuTest.cpp +++ b/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreEditorMenuTest.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -35,6 +36,7 @@ class AWSCoreEditorMenuTest { AWSCoreEditorUIFixture::SetUp(); AWSCoreFixture::SetUp(); + m_localFileIO->SetAlias("@devroot@", "dummy engine root"); } void TearDown() override @@ -77,12 +79,12 @@ TEST_F(AWSCoreEditorMenuTest, AWSCoreEditorMenu_BroadcastFeatureGemsAreEnabled_C QList actualActions = testMenu.actions(); for (QList::iterator itr = actualActions.begin(); itr != actualActions.end(); itr++) { - if (QString::compare((*itr)->text(), AWSCoreEditorMenu::AWSClientAuthActionText) == 0) + if (QString::compare((*itr)->text(), AWSClientAuthActionText) == 0) { EXPECT_TRUE((*itr)->isEnabled()); } - if (QString::compare((*itr)->text(), AWSCoreEditorMenu::AWSMetricsActionText) == 0) + if (QString::compare((*itr)->text(), AWSMetricsActionText) == 0) { EXPECT_TRUE((*itr)->isEnabled()); } diff --git a/Gems/AWSCore/Code/awscore_editor_files.cmake b/Gems/AWSCore/Code/awscore_editor_files.cmake index 652f0455e1..13bfbb6102 100644 --- a/Gems/AWSCore/Code/awscore_editor_files.cmake +++ b/Gems/AWSCore/Code/awscore_editor_files.cmake @@ -12,6 +12,8 @@ set(FILES Include/Private/AWSCoreEditorSystemComponent.h Include/Private/Editor/AWSCoreEditorManager.h + Include/Private/Editor/Constants/AWSCoreEditorMenuLinks.h + Include/Private/Editor/Constants/AWSCoreEditorMenuNames.h Include/Private/Editor/UI/AWSCoreEditorMenu.h Include/Private/Editor/UI/AWSCoreResourceMappingToolAction.h Source/AWSCoreEditorSystemComponent.cpp From 984db9c1b48571998f5a19381262ce391ed2727d Mon Sep 17 00:00:00 2001 From: chiyteng Date: Fri, 28 May 2021 10:56:03 -0700 Subject: [PATCH 330/811] Remove selection command and update undo batch in DetachPrefab function --- .../Prefab/PrefabPublicHandler.cpp | 53 ++++--------------- 1 file changed, 10 insertions(+), 43 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 7ec0ddf8ad..e223775add 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -1010,38 +1010,11 @@ namespace AzToolsFramework AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - UndoSystem::URSequencePoint* currentUndoBatch = nullptr; - ToolsApplicationRequests::Bus::BroadcastResult(currentUndoBatch, &ToolsApplicationRequests::Bus::Events::GetCurrentUndoBatch); - - bool createdUndo = false; - if (!currentUndoBatch) - { - createdUndo = true; - ToolsApplicationRequests::Bus::BroadcastResult( - currentUndoBatch, &ToolsApplicationRequests::Bus::Events::BeginUndoBatch, "Detach Prefab"); - AZ_Assert(currentUndoBatch, "Failed to create new undo batch."); - } - - // In order to undo Prefab Instance detachment, we have to create a selection command which selects the current selection - // and then add the detach as children. - // Commands always execute themselves first and then their children (when going forwards) - // and do the opposite when going backwards. - EntityIdList selectedEntities; - ToolsApplicationRequestBus::BroadcastResult(selectedEntities, &ToolsApplicationRequests::GetSelectedEntities); - SelectionCommand* selCommand = aznew SelectionCommand(selectedEntities, "Detach Prefab"); - - // We insert a "deselect all" command before we detach the Prefab Instance. This ensures the detach operations aren't changing - // selection state, which triggers expensive UI updates. By deselecting up front, we are able to do those expensive - // UI updates once at the start instead of once for each entity. - { - EntityIdList deselection; - SelectionCommand* deselectAllCommand = aznew SelectionCommand(deselection, "Deselect Entities"); - deselectAllCommand->SetParent(selCommand); - } - { AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DetachPrefab:UndoCapture"); + ScopedUndoBatch undoBatch("Detach Prefab"); + InstanceOptionalReference parentInstance = owningInstance->get().GetParentInstance(); const auto parentTemplateId = parentInstance->get().GetTemplateId(); @@ -1049,7 +1022,7 @@ namespace AzToolsFramework auto instancePtr = parentInstance->get().DetachNestedInstance(owningInstance->get().GetInstanceAlias()); AZ_Assert(instancePtr, "Can't detach selected Instance from its parent Instance."); - RemoveLink(instancePtr, parentTemplateId, currentUndoBatch); + RemoveLink(instancePtr, parentTemplateId, undoBatch.GetUndoBatch()); Prefab::PrefabDom instanceDomBefore; m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, parentInstance->get()); @@ -1094,12 +1067,10 @@ namespace AzToolsFramework PrefabUndoInstance* command = aznew PrefabUndoInstance("Instance detachment"); command->Capture(instanceDomBefore, instanceDomAfter, parentTemplateId); - command->SetParent(selCommand); - - selCommand->SetParent(currentUndoBatch); + command->SetParent(undoBatch.GetUndoBatch()); { AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DetachPrefab:RunRedo"); - selCommand->RunRedo(); + command->RunRedo(); } const auto instanceTemplateId = instancePtr->GetTemplateId(); @@ -1117,7 +1088,7 @@ namespace AzToolsFramework PrefabDom linkPatchesCopy; linkPatchesCopy.CopyFrom(linkPatches->get(), linkPatchesCopy.GetAllocator()); - RemoveLink(nestedInstancePtr, instanceTemplateId, currentUndoBatch); + RemoveLink(nestedInstancePtr, instanceTemplateId, undoBatch.GetUndoBatch()); PrefabDomUtils::PrintPrefabDomValue("linkPatchesCopy", linkPatchesCopy); //update aliases @@ -1139,17 +1110,13 @@ namespace AzToolsFramework linkPatchesCopy.Parse(previousPatchString.toUtf8().constData()); - CreateLink(*nestedInstancePtr, parentTemplateId, currentUndoBatch, AZStd::move(linkPatchesCopy), true); + CreateLink(*nestedInstancePtr, parentTemplateId, undoBatch.GetUndoBatch(), + AZStd::move(linkPatchesCopy), true); }); } - } - AzToolsFramework::ToolsApplicationRequestBus::Broadcast( - &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); - - if (createdUndo) - { - ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::EndUndoBatch); + AzToolsFramework::ToolsApplicationRequestBus::Broadcast( + &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); } return AZ::Success(); From 17f85be9b5701d8a1a640ca4302072326f2bc8c3 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Fri, 28 May 2021 11:00:54 -0700 Subject: [PATCH 331/811] Switch size check to empty --- .../Code/Source/AutoGen/AutoComponent_Source.jinja | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 97e2085a69..0feff5c07c 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -133,7 +133,7 @@ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PushBack(const {{ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PopBack(const Multiplayer::NetworkInput&) { - if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size() > 0) + if (!GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.empty()) { GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back(); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); @@ -234,7 +234,7 @@ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PushBack(const {{ bool {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}PopBack() { - if (GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.size() > 0) + if (!GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.empty()) { GetParent().m_{{ LowerFirst(Property.attrib['Name']) }}.pop_back(); GetParent().m_currentRecord->m_{{ LowerFirst(AutoComponentMacros.GetNetPropertiesSetName(ReplicateFrom, ReplicateTo)) }}.SetBit(aznumeric_cast({{ AutoComponentMacros.GetNetPropertiesQualifiedPropertyDirtyEnum(Component.attrib['Name'], ReplicateFrom, ReplicateTo, Property, 'Size') }}), true); From def36dcf6343499c65fe529840a1ea8e13bcf0cc Mon Sep 17 00:00:00 2001 From: sconel Date: Fri, 28 May 2021 11:02:56 -0700 Subject: [PATCH 332/811] Add clearer dependencies handled flag logic --- .../Code/Builder/ScriptCanvasBuilderWorkerUtility.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorkerUtility.cpp b/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorkerUtility.cpp index 36d3194632..ba22789cd1 100644 --- a/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorkerUtility.cpp +++ b/Gems/ScriptCanvas/Code/Builder/ScriptCanvasBuilderWorkerUtility.cpp @@ -690,6 +690,10 @@ namespace ScriptCanvasBuilder azrtti_typeid(), AZ_CRC("RuntimeData", 0x163310ae), jobProduct); + // Output Object marks dependencies as handled. + // We still have more to evaluate + jobProduct.m_dependenciesHandled = false; + jobProduct.m_dependencies.push_back({ runtimeData.m_script.GetId(), {} }); for (const auto& assetDependency : runtimeData.m_requiredAssets) @@ -721,6 +725,7 @@ namespace ScriptCanvasBuilder } } + jobProduct.m_dependenciesHandled = true; input.response->m_outputProducts.push_back(AZStd::move(jobProduct)); return AZ::Success(); } From 16c8ae5a3a962fd7d4cf975d553873163e961dd0 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 28 May 2021 19:13:56 +0100 Subject: [PATCH 333/811] refactor vector scale on Transform to float scale --- .../AzCore/AzCore/Math/Transform.cpp | 9 ++-- Code/Framework/AzCore/AzCore/Math/Transform.h | 16 ++++-- .../AzCore/AzCore/Math/Transform.inl | 49 ++++++++----------- .../Json/TransformSerializerTests.cpp | 4 +- .../Components/BlastFamilyComponent.cpp | 2 +- .../Code/Source/Shape/QuadShape.cpp | 4 +- 6 files changed, 41 insertions(+), 43 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.cpp b/Code/Framework/AzCore/AzCore/Math/Transform.cpp index 03c9578e85..62a390c138 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.cpp +++ b/Code/Framework/AzCore/AzCore/Math/Transform.cpp @@ -277,7 +277,7 @@ namespace AZ Attribute(Script::Attributes::ExcludeFrom, Script::Attributes::ExcludeFlags::All)-> Attribute(Script::Attributes::Storage, Script::Attributes::StorageType::Value)-> Attribute(Script::Attributes::GenericConstructorOverride, &Internal::TransformDefaultConstructor)-> - Constructor()-> + Constructor()-> Method("GetBasis", &Transform::GetBasis)-> Method("GetBasisX", &Transform::GetBasisX)-> Method("GetBasisY", &Transform::GetBasisY)-> @@ -310,7 +310,6 @@ namespace AZ Attribute(Script::Attributes::ExcludeFrom, Script::Attributes::ExcludeFlags::All)-> Method("GetRotation", &Transform::GetRotation)-> Method("SetRotation", &Transform::SetRotation)-> - Method("GetScale", &Transform::GetScale)-> Method("GetUniformScale", &Transform::GetUniformScale)-> Method("SetUniformScale", &Transform::SetUniformScale)-> Method("ExtractUniformScale", &Transform::ExtractUniformScale)-> @@ -343,7 +342,7 @@ namespace AZ { Transform result; Matrix3x3 tmp = value; - result.m_scale = tmp.ExtractScale(); + result.m_scale = tmp.ExtractScale().GetMaxElement(); result.m_rotation = Quaternion::CreateFromMatrix3x3(tmp); result.m_translation = Vector3::CreateZero(); return result; @@ -353,7 +352,7 @@ namespace AZ { Transform result; Matrix3x3 tmp = value; - result.m_scale = tmp.ExtractScale(); + result.m_scale = tmp.ExtractScale().GetMaxElement(); result.m_rotation = Quaternion::CreateFromMatrix3x3(tmp); result.m_translation = p; return result; @@ -363,7 +362,7 @@ namespace AZ { Transform result; Matrix3x4 tmp = value; - result.m_scale = tmp.ExtractScale(); + result.m_scale = tmp.ExtractScale().GetMaxElement(); result.m_rotation = Quaternion::CreateFromMatrix3x4(tmp); result.m_translation = value.GetTranslation(); return result; diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.h b/Code/Framework/AzCore/AzCore/Math/Transform.h index ff7df7326b..3fe6ddc98a 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.h +++ b/Code/Framework/AzCore/AzCore/Math/Transform.h @@ -48,7 +48,7 @@ namespace AZ static constexpr float MaxTransformScale = 1e9f; //! @} - //! The basic transformation class, represented using a quaternion rotation, vector scale and vector translation. + //! The basic transformation class, represented using a quaternion rotation, float scale and vector translation. //! By design, cannot represent skew transformations. class Transform { @@ -66,7 +66,7 @@ namespace AZ Transform() = default; //! Construct a transform from components. - Transform(const Vector3& translation, const Quaternion& rotation, const Vector3& scale); + Transform(const Vector3& translation, const Quaternion& rotation, float scale); //! Creates an identity transform. static Transform CreateIdentity(); @@ -85,11 +85,18 @@ namespace AZ static Transform CreateFromQuaternionAndTranslation(const class Quaternion& q, const Vector3& p); //! Constructs from a Matrix3x3, translation is set to zero. + //! Note that Transform only allows uniform scale, so if the matrix has different scale values along its axes, + //! the largest matrix scale value will be used to uniformly scale the Transform. static Transform CreateFromMatrix3x3(const class Matrix3x3& value); - //! Constructs from a Matrix3x3, translation is set to zero. + //! Constructs from a Matrix3x3 and translation Vector3. + //! Note that Transform only allows uniform scale, so if the matrix has different scale values along its axes, + //! the largest matrix scale value will be used to uniformly scale the Transform. static Transform CreateFromMatrix3x3AndTranslation(const class Matrix3x3& value, const Vector3& p); + //! Constructs from a Matrix3x4. + //! Note that Transform only allows uniform scale, so if the matrix has different scale values along its axes, + //! the largest matrix scale value will be used to uniformly scale the Transform. static Transform CreateFromMatrix3x4(const Matrix3x4& value); //! Sets the transform to apply (uniform) scale only, no rotation or translation. @@ -122,7 +129,6 @@ namespace AZ const Quaternion& GetRotation() const; void SetRotation(const Quaternion& rotation); - Vector3 GetScale() const; float GetUniformScale() const; void SetUniformScale(const float scale); @@ -163,7 +169,7 @@ namespace AZ private: Quaternion m_rotation; - Vector3 m_scale; + float m_scale; Vector3 m_translation; }; diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.inl b/Code/Framework/AzCore/AzCore/Math/Transform.inl index 3325a29f16..5f71316b52 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.inl +++ b/Code/Framework/AzCore/AzCore/Math/Transform.inl @@ -12,7 +12,7 @@ namespace AZ { - AZ_MATH_INLINE Transform::Transform(const Vector3& translation, const Quaternion& rotation, const Vector3& scale) + AZ_MATH_INLINE Transform::Transform(const Vector3& translation, const Quaternion& rotation, float scale) : m_translation(translation) , m_rotation(rotation) , m_scale(scale) @@ -25,7 +25,7 @@ namespace AZ { Transform result; result.m_rotation = Quaternion::CreateIdentity(); - result.m_scale = Vector3::CreateOne(); + result.m_scale = 1.0f; result.m_translation = Vector3::CreateZero(); return result; } @@ -49,7 +49,7 @@ namespace AZ { Transform result; result.m_rotation = q; - result.m_scale = Vector3::CreateOne(); + result.m_scale = 1.0f; result.m_translation = Vector3::CreateZero(); return result; } @@ -58,7 +58,7 @@ namespace AZ { Transform result; result.m_rotation = q; - result.m_scale = Vector3::CreateOne(); + result.m_scale = 1.0f; result.m_translation = p; return result; } @@ -67,7 +67,7 @@ namespace AZ { Transform result; result.m_rotation = Quaternion::CreateIdentity(); - result.m_scale = Vector3(scale); + result.m_scale = scale; result.m_translation = Vector3::CreateZero(); return result; } @@ -76,7 +76,7 @@ namespace AZ { Transform result; result.m_rotation = Quaternion::CreateIdentity(); - result.m_scale = Vector3::CreateOne(); + result.m_scale = 1.0f; result.m_translation = translation; return result; } @@ -104,17 +104,17 @@ namespace AZ AZ_MATH_INLINE Vector3 Transform::GetBasisX() const { - return m_rotation.TransformVector(Vector3::CreateAxisX(m_scale.GetX())); + return m_rotation.TransformVector(Vector3::CreateAxisX(m_scale)); } AZ_MATH_INLINE Vector3 Transform::GetBasisY() const { - return m_rotation.TransformVector(Vector3::CreateAxisY(m_scale.GetY())); + return m_rotation.TransformVector(Vector3::CreateAxisY(m_scale)); } AZ_MATH_INLINE Vector3 Transform::GetBasisZ() const { - return m_rotation.TransformVector(Vector3::CreateAxisZ(m_scale.GetZ())); + return m_rotation.TransformVector(Vector3::CreateAxisZ(m_scale)); } AZ_MATH_INLINE void Transform::GetBasisAndTranslation(Vector3* basisX, Vector3* basisY, Vector3* basisZ, Vector3* pos) const @@ -150,26 +150,20 @@ namespace AZ m_rotation = rotation; } - AZ_MATH_INLINE Vector3 Transform::GetScale() const - { - AZ_WarningOnce("Transform", false, "GetScale is deprecated, please use GetUniformScale instead."); - return m_scale; - } - AZ_MATH_INLINE float Transform::GetUniformScale() const { - return m_scale.GetMaxElement(); + return m_scale; } AZ_MATH_INLINE void Transform::SetUniformScale(const float scale) { - m_scale = Vector3(scale); + m_scale = scale; } AZ_MATH_INLINE float Transform::ExtractUniformScale() { - const float scale = m_scale.GetMaxElement(); - m_scale = Vector3::CreateOne(); + const float scale = m_scale; + m_scale = 1.0f; return scale; } @@ -210,10 +204,9 @@ namespace AZ AZ_MATH_INLINE Transform Transform::GetInverse() const { - // note - need to be careful about how to calculate inverse when there is non-uniform scale Transform out; out.m_rotation = m_rotation.GetConjugate(); - out.m_scale = m_scale.GetReciprocal(); + out.m_scale = 1.0f / m_scale; out.m_translation = -out.m_scale * (out.m_rotation.TransformVector(m_translation)); return out; } @@ -225,27 +218,27 @@ namespace AZ AZ_MATH_INLINE bool Transform::IsOrthogonal(float tolerance) const { - return m_scale.IsClose(Vector3::CreateOne(), tolerance); + return AZ::IsClose(m_scale, 1.0f, tolerance); } AZ_MATH_INLINE Transform Transform::GetOrthogonalized() const { Transform result; result.m_rotation = m_rotation; - result.m_scale = Vector3::CreateOne(); + result.m_scale = 1.0f; result.m_translation = m_translation; return result; } AZ_MATH_INLINE void Transform::Orthogonalize() { - m_scale = Vector3::CreateOne(); + m_scale = 1.0f; } AZ_MATH_INLINE bool Transform::IsClose(const Transform& rhs, float tolerance) const { return m_rotation.IsClose(rhs.m_rotation, tolerance) - && m_scale.IsClose(rhs.m_scale, tolerance) + && AZ::IsClose(m_scale, rhs.m_scale, tolerance) && m_translation.IsClose(rhs.m_translation, tolerance); } @@ -274,21 +267,21 @@ namespace AZ AZ_MATH_INLINE void Transform::SetFromEulerDegrees(const Vector3& eulerDegrees) { m_translation = Vector3::CreateZero(); - m_scale = Vector3::CreateOne(); + m_scale = 1.0f; m_rotation.SetFromEulerDegrees(eulerDegrees); } AZ_MATH_INLINE void Transform::SetFromEulerRadians(const Vector3& eulerRadians) { m_translation = Vector3::CreateZero(); - m_scale = Vector3::CreateOne(); + m_scale = 1.0f; m_rotation.SetFromEulerRadians(eulerRadians); } AZ_MATH_INLINE bool Transform::IsFinite() const { return m_rotation.IsFinite() - && m_scale.IsFinite() + && AZ::IsFiniteFloat(m_scale) && m_translation.IsFinite(); } diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/TransformSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/TransformSerializerTests.cpp index 7eabd6e5e0..750f2ebc9c 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/TransformSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/TransformSerializerTests.cpp @@ -44,7 +44,7 @@ namespace JsonSerializationTests AZStd::shared_ptr CreateFullySetInstance() override { return AZStd::make_shared( - AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Quaternion(0.25f, 0.5f, 0.75f, 1.0f), AZ::Vector3(9.0f)); + AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Quaternion(0.25f, 0.5f, 0.75f, 1.0f), 9.0f); } AZStd::string_view GetJsonForFullySetInstance() override @@ -95,7 +95,7 @@ namespace JsonSerializationTests AZ::Transform expectedTransform( AZ::Vector3(2.25f, 3.5f, 4.75f), AZ::Quaternion(0.25f, 0.5f, 0.75f, 1.0f), - AZ::Vector3(5.5f)); + 5.5f); rapidjson::Document json; json.Parse(R"({ "Translation": [ 2.25, 3.5, 4.75 ], "Rotation": [ 0.25, 0.5, 0.75, 1.0 ], "Scale": 5.5 })"); diff --git a/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp b/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp index 0f2668442c..b686cbc5f5 100644 --- a/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp +++ b/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp @@ -274,7 +274,7 @@ namespace Blast m_damageManager = AZStd::make_unique(blastMaterial, m_family->GetActorTracker()); m_actorRenderManager = AZStd::make_unique( AZ::RPI::Scene::GetFeatureProcessorForEntity(GetEntityId()), - m_meshDataComponent, GetEntityId(), m_blastAsset->GetPxAsset()->getChunkCount(), transform.GetScale()); + m_meshDataComponent, GetEntityId(), m_blastAsset->GetPxAsset()->getChunkCount(), AZ::Vector3(transform.GetUniformScale())); // Spawn the family m_family->Spawn(transform); diff --git a/Gems/LmbrCentral/Code/Source/Shape/QuadShape.cpp b/Gems/LmbrCentral/Code/Source/Shape/QuadShape.cpp index 052eac47d0..a395dbac2b 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/QuadShape.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/QuadShape.cpp @@ -205,8 +205,8 @@ namespace LmbrCentral { m_position = currentTransform.GetTranslation(); m_quaternion = currentTransform.GetRotation(); - m_scaledWidth = configuration.m_width * currentTransform.GetScale().GetX() * currentNonUniformScale.GetX(); - m_scaledHeight = configuration.m_height * currentTransform.GetScale().GetY() * currentNonUniformScale.GetY(); + m_scaledWidth = configuration.m_width * currentTransform.GetUniformScale() * currentNonUniformScale.GetX(); + m_scaledHeight = configuration.m_height * currentTransform.GetUniformScale() * currentNonUniformScale.GetY(); } const QuadShapeConfig& QuadShape::GetQuadConfiguration() const From 4ff120ac7309c5fcaeeaeaed580dbaa08f89038a Mon Sep 17 00:00:00 2001 From: evanchia Date: Fri, 28 May 2021 11:28:03 -0700 Subject: [PATCH 334/811] Only moving the failing test via pytest marks --- .../Gem/PythonTests/smoke/CMakeLists.txt | 18 ++++++++++++++++++ .../test_Editor_NewExistingLevels_Works.py | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index 7d946ee6e1..95b6a16ba4 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt @@ -14,6 +14,24 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE sandbox TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} + PYTEST_MARKS "SUITE_smoke" + TIMEOUT 1500 + RUNTIME_DEPENDENCIES + AZ::AssetProcessor + AZ::PythonBindingsExample + Legacy::Editor + AutomatedTesting.GameLauncher + AutomatedTesting.Assets + COMPONENT + Smoke + ) + + ly_add_pytest( + NAME AutomatedTesting::SandboxTest + TEST_SUITE sandbox + TEST_SERIAL + PATH ${CMAKE_CURRENT_LIST_DIR} + PYTEST_MARKS "SUITE_sandbox" TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py index 985740307f..e6b072ba58 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py @@ -15,7 +15,7 @@ from automatedtesting_shared.base import TestAutomationBase import ly_test_tools.environment.file_system as file_system -@pytest.mark.SUITE_smoke +@pytest.mark.SUITE_sandbox @pytest.mark.parametrize("launcher_platform", ["windows_editor"]) @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.parametrize("level", ["temp_level"]) From cd9d21dbb098090660a7aec31a8b5ee2a60223d0 Mon Sep 17 00:00:00 2001 From: evanchia Date: Fri, 28 May 2021 11:29:58 -0700 Subject: [PATCH 335/811] fixing error with suite tag --- AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index 95b6a16ba4..a3b6e36250 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt @@ -11,7 +11,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_pytest( NAME AutomatedTesting::SmokeTest - TEST_SUITE sandbox + TEST_SUITE smoke TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_smoke" From de4cfdb5d7d7ef8c736763eb366013640e6d00b5 Mon Sep 17 00:00:00 2001 From: chiyteng Date: Fri, 28 May 2021 11:33:58 -0700 Subject: [PATCH 336/811] Add helper function to update entity aliases in link patch --- .../Prefab/PrefabPublicHandler.cpp | 67 +++++++++++-------- .../Prefab/PrefabPublicHandler.h | 7 +- 2 files changed, 45 insertions(+), 29 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index e223775add..1c645100d1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -189,24 +189,7 @@ namespace AzToolsFramework if (nestedInstanceLinkPatchesMap.contains(nestedInstance.get())) { previousPatch = AZStd::move(nestedInstanceLinkPatchesMap[nestedInstance.get()]); - rapidjson::StringBuffer buffer; - rapidjson::Writer writer(buffer); - previousPatch.Accept(writer); - QString previousPatchString(buffer.GetString()); - - for (AZ::Entity* entity : entities) - { - AZ::EntityId entityId = entity->GetId(); - AZStd::string oldEntityAlias = oldEntityAliases[entityId]; - EntityAliasOptionalReference newEntityAlias = instanceToCreate->get().GetEntityAlias(entityId); - AZ_Assert( - newEntityAlias.has_value(), - "Could not fetch entity alias for entity with id '%llu' during prefab creation.", - static_cast(entityId)); - ReplaceOldAliases(previousPatchString, oldEntityAlias, newEntityAlias->get()); - } - - previousPatch.Parse(previousPatchString.toUtf8().constData()); + UpdateLinkPatchForNewParent(previousPatch, oldEntityAliases, instanceToCreate->get()); } // These link creations shouldn't be undone because that would put the template in a non-usable state if a user @@ -1015,17 +998,20 @@ namespace AzToolsFramework ScopedUndoBatch undoBatch("Detach Prefab"); - InstanceOptionalReference parentInstance = owningInstance->get().GetParentInstance(); - const auto parentTemplateId = parentInstance->get().GetTemplateId(); + InstanceOptionalReference getParentInstanceResult = owningInstance->get().GetParentInstance(); + AZ_Assert(getParentInstanceResult.has_value(), "Can't get parent Instance from Instance of given container entity."); + + auto& parentInstance = getParentInstanceResult->get(); + const auto parentTemplateId = parentInstance.GetTemplateId(); { - auto instancePtr = parentInstance->get().DetachNestedInstance(owningInstance->get().GetInstanceAlias()); + auto instancePtr = parentInstance.DetachNestedInstance(owningInstance->get().GetInstanceAlias()); AZ_Assert(instancePtr, "Can't detach selected Instance from its parent Instance."); RemoveLink(instancePtr, parentTemplateId, undoBatch.GetUndoBatch()); Prefab::PrefabDom instanceDomBefore; - m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, parentInstance->get()); + m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, parentInstance); AZStd::unordered_map oldEntityAliases; oldEntityAliases.emplace(entityId, instancePtr->GetEntityAlias(entityId)->get()); @@ -1039,7 +1025,7 @@ namespace AzToolsFramework delete editorPrefabComponent; containerEntity.Activate(); - const bool containerEntityAdded = parentInstance->get().AddEntity(containerEntity); + const bool containerEntityAdded = parentInstance.AddEntity(containerEntity); AZ_Assert(containerEntityAdded, "Add target Instance's container entity to its parent Instance failed."); EntityIdList entityIds; @@ -1056,14 +1042,14 @@ namespace AzToolsFramework [&](AZStd::unique_ptr entityPtr) { auto& entity = *entityPtr.release(); - const bool entityAdded = parentInstance->get().AddEntity(entity); + const bool entityAdded = parentInstance.AddEntity(entity); AZ_Assert(entityAdded, "Add target Instance's entity to its parent Instance failed."); entityIds.emplace_back(entity.GetId()); }); Prefab::PrefabDom instanceDomAfter; - m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomAfter, parentInstance->get()); + m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomAfter, parentInstance); PrefabUndoInstance* command = aznew PrefabUndoInstance("Instance detachment"); command->Capture(instanceDomBefore, instanceDomAfter, parentTemplateId); @@ -1074,7 +1060,7 @@ namespace AzToolsFramework } const auto instanceTemplateId = instancePtr->GetTemplateId(); - auto parentContainerEntityId = parentInstance->get().GetContainerEntityId(); + auto parentContainerEntityId = parentInstance.GetContainerEntityId(); instancePtr->GetNestedInstances( [&](AZStd::unique_ptr& nestedInstancePtr) { @@ -1089,8 +1075,8 @@ namespace AzToolsFramework linkPatchesCopy.CopyFrom(linkPatches->get(), linkPatchesCopy.GetAllocator()); RemoveLink(nestedInstancePtr, instanceTemplateId, undoBatch.GetUndoBatch()); - PrefabDomUtils::PrintPrefabDomValue("linkPatchesCopy", linkPatchesCopy); + UpdateLinkPatchForNewParent(linkPatchesCopy, oldEntityAliases, parentInstance); //update aliases rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); @@ -1100,7 +1086,7 @@ namespace AzToolsFramework for (AZ::EntityId entityId : entityIds) { AZStd::string oldEntityAlias = oldEntityAliases[entityId]; - EntityAliasOptionalReference newEntityAlias = parentInstance->get().GetEntityAlias(entityId); + EntityAliasOptionalReference newEntityAlias = parentInstance.GetEntityAlias(entityId); AZ_Assert( newEntityAlias.has_value(), "Could not fetch entity alias for entity with id '%llu' during prefab creation.", @@ -1385,5 +1371,30 @@ namespace AzToolsFramework stringToReplace.replace(oldAliasPathRef, newAliasPathRef); } + + void PrefabPublicHandler::UpdateLinkPatchForNewParent( + PrefabDom& linkPatch, + const AZStd::unordered_map& oldEntityAliases, + Instance& newParent) + { + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + linkPatch.Accept(writer); + QString previousPatchString(buffer.GetString()); + + for (const auto& [entityId, oldEntityAlias] : oldEntityAliases) + { + EntityAliasOptionalReference newEntityAlias = newParent.GetEntityAlias(entityId); + AZ_Assert( + newEntityAlias.has_value(), + "Could not fetch entity alias for entity with id '%llu' during prefab creation.", + static_cast(entityId)); + + ReplaceOldAliases(previousPatchString, oldEntityAlias, newEntityAlias->get()); + } + + linkPatch.Parse(previousPatchString.toUtf8().constData()); + } + } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index f3b3b242dd..c339c17a48 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -134,7 +134,12 @@ namespace AzToolsFramework bool IsCyclicalDependencyFound( InstanceOptionalConstReference instance, const AZStd::unordered_set& templateSourcePaths); - void ReplaceOldAliases(QString& stringToReplace, AZStd::string_view oldAlias, AZStd::string_view newAlias); + static void UpdateLinkPatchForNewParent( + PrefabDom& linkPatch, + const AZStd::unordered_map& oldEntityAliases, + Instance& newParent); + + static void ReplaceOldAliases(QString& stringToReplace, AZStd::string_view oldAlias, AZStd::string_view newAlias); static Instance* GetParentInstance(Instance* instance); static Instance* GetAncestorOfInstanceThatIsChildOfRoot(const Instance* ancestor, Instance* descendant); From da0ab84f1cbd279294eab50ea832e5122f06e147 Mon Sep 17 00:00:00 2001 From: chiyteng Date: Fri, 28 May 2021 11:42:36 -0700 Subject: [PATCH 337/811] Add helper function to update entity aliases in link patch --- .../Prefab/PrefabPublicHandler.cpp | 20 +------------------ 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 1c645100d1..fdc4302c1b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -1077,25 +1077,7 @@ namespace AzToolsFramework RemoveLink(nestedInstancePtr, instanceTemplateId, undoBatch.GetUndoBatch()); UpdateLinkPatchForNewParent(linkPatchesCopy, oldEntityAliases, parentInstance); - //update aliases - rapidjson::StringBuffer buffer; - rapidjson::Writer writer(buffer); - linkPatchesCopy.Accept(writer); - QString previousPatchString(buffer.GetString()); - - for (AZ::EntityId entityId : entityIds) - { - AZStd::string oldEntityAlias = oldEntityAliases[entityId]; - EntityAliasOptionalReference newEntityAlias = parentInstance.GetEntityAlias(entityId); - AZ_Assert( - newEntityAlias.has_value(), - "Could not fetch entity alias for entity with id '%llu' during prefab creation.", - static_cast(entityId)); - ReplaceOldAliases(previousPatchString, oldEntityAlias, newEntityAlias->get()); - } - - linkPatchesCopy.Parse(previousPatchString.toUtf8().constData()); - + CreateLink(*nestedInstancePtr, parentTemplateId, undoBatch.GetUndoBatch(), AZStd::move(linkPatchesCopy), true); }); From 00e860f32600520cd9fa93132c647233738b0411 Mon Sep 17 00:00:00 2001 From: Aaron Ruiz Mora Date: Fri, 28 May 2021 20:16:25 +0100 Subject: [PATCH 338/811] Physics material system for spectra launch - Invalidate 'Physics Materials From Mesh' boolean from collider component - Removed material library from material selector. Default material library will always be used instead. - Marking failing automated test as xfail - Added default material to physics configuration. - Moved material library asset from physx configuration to physics configuration, as it doesn't need to be physx specific. - Refactor physics material system having into account that there is only one material library in the project. - Renaming code from DefaultMaterialLibrary to MaterialLibrary. - All queries about physics materials unified under PhysicsMaterialRequests bus. - PhysXSystem only manages the material library asset. - Saving and reloading the same physics material asset with different content didn't trigger a events that the material library has changed. - Changing Physics Material Request interface to use shared_ptr instead of weak_ptr to be simpler to handle the returned materials and having a more consistent code. - Refactored Material Manager to improve its implementation. Still following the same approach of "creating materials on the fly as they are requested", but now it's doing it consistently across the interface, with private helpers functions FindOrCreateMaterial that simplify vastly the implementation. - Material Manager now listens to change event of material library asset and default material configuration so it updates its materials accordingly. - Complete Material move constructor and operator. --- .../Gem/PythonTests/physics/TestSuite_Main.py | 1 + ...4_Collider_CollisionGroups.setreg_override | 3 + ...9_Material_DynamicFriction.setreg_override | 118 ++++++ ...C4976227_Collider_NewGroup.setreg_override | 3 + ...ameGroupSameLayerCollision.setreg_override | 3 + ...ollider_CollisionLayerTest.setreg_override | 3 + ...ysXCollider_CollisionLayer.setreg_override | 3 + .../Registry/physxsystemconfiguration.setreg | 3 + .../surfacetypemateriallibrary.physmaterial | 11 +- .../AzFramework/Physics/ClassConverters.cpp | 9 +- .../Physics/Common/PhysicsEvents.h | 13 +- .../Configuration/SystemConfiguration.cpp | 6 +- .../Configuration/SystemConfiguration.h | 4 + .../AzFramework/Physics/Material.cpp | 224 +++------- .../AzFramework/Physics/Material.h | 101 ++--- .../AzFramework/Physics/MaterialBus.h | 19 +- .../AzFramework/Physics/PhysicsSystem.h | 17 +- .../Physics/ShapeConfiguration.cpp | 19 +- .../AzFramework/Physics/ShapeConfiguration.h | 2 +- .../AzFramework/Physics/SystemBus.h | 16 +- .../AzFramework/AzFramework/Physics/Utils.cpp | 3 +- .../Code/Source/Actor/BlastActorImpl.cpp | 2 - .../Components/BlastFamilyComponent.cpp | 22 +- .../Editor/EditorBlastFamilyComponent.cpp | 2 +- .../Code/Tests/Mocks/PhysicsSystem.h | 5 - .../Ragdoll/CanCopyPasteColliders.cpp | 3 - .../Ragdoll/CanCopyPasteJointLimits.cpp | 3 - Gems/PhysX/Code/Editor/DebugDraw.cpp | 15 +- Gems/PhysX/Code/Editor/SettingsWidget.cpp | 8 +- Gems/PhysX/Code/Editor/SettingsWidget.h | 2 +- .../Components/EditorSystemComponent.cpp | 77 ++-- .../Source/Components/EditorSystemComponent.h | 4 +- .../PhysX/Configuration/PhysXConfiguration.h | 2 - .../Include/PhysX/MeshColliderComponentBus.h | 4 - .../Configuration/PhysXConfiguration.cpp | 16 +- .../Code/Source/EditorColliderComponent.cpp | 24 +- .../Code/Source/EditorColliderComponent.h | 3 +- .../Source/EditorShapeColliderComponent.cpp | 13 +- .../Source/EditorShapeColliderComponent.h | 2 +- Gems/PhysX/Code/Source/Material.cpp | 388 +++++++++++++----- Gems/PhysX/Code/Source/Material.h | 92 +++-- .../Code/Source/MeshColliderComponent.cpp | 19 +- .../PhysX/Code/Source/MeshColliderComponent.h | 1 - .../PhysXCharacters/API/CharacterUtils.cpp | 38 +- .../Code/Source/Pipeline/MeshExporter.cpp | 8 +- Gems/PhysX/Code/Source/System/PhysXSystem.cpp | 84 ++-- Gems/PhysX/Code/Source/System/PhysXSystem.h | 12 +- Gems/PhysX/Code/Source/SystemComponent.cpp | 134 ------ Gems/PhysX/Code/Source/SystemComponent.h | 7 - Gems/PhysX/Code/Source/Utils.cpp | 42 -- Gems/PhysX/Code/Source/Utils.h | 3 - .../Code/Tests/PhysXMaterialLibraryTest.cpp | 181 -------- Gems/PhysX/Code/physx_tests_files.cmake | 1 - .../Code/Tests/ScriptCanvasPhysicsTest.cpp | 4 +- 54 files changed, 859 insertions(+), 943 deletions(-) create mode 100644 AutomatedTesting/Registry/C4044459_Material_DynamicFriction.setreg_override delete mode 100644 Gems/PhysX/Code/Tests/PhysXMaterialLibraryTest.cpp diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py index 8f1f2f7481..2cf55c7a58 100644 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py @@ -42,6 +42,7 @@ class TestAutomation(TestAutomationBase): self._run_test(request, workspace, editor, test_module) @revert_physics_config + @fm.file_override('physxsystemconfiguration.setreg','C4044459_Material_DynamicFriction.setreg_override', 'AutomatedTesting/Registry') def test_C4044459_Material_DynamicFriction(self, request, workspace, editor, launcher_platform): from . import C4044459_Material_DynamicFriction as test_module self._run_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Registry/C3510644_Collider_CollisionGroups.setreg_override b/AutomatedTesting/Registry/C3510644_Collider_CollisionGroups.setreg_override index 9fa5e26768..696a0a74da 100644 --- a/AutomatedTesting/Registry/C3510644_Collider_CollisionGroups.setreg_override +++ b/AutomatedTesting/Registry/C3510644_Collider_CollisionGroups.setreg_override @@ -119,6 +119,9 @@ ] } }, + "DefaultMaterial": { + "SurfaceType": "Default_1" + }, "MaterialLibrary": { "assetId": { "guid": "{3A055A3F-8CB7-5FEE-B437-EB365FACD0D4}" diff --git a/AutomatedTesting/Registry/C4044459_Material_DynamicFriction.setreg_override b/AutomatedTesting/Registry/C4044459_Material_DynamicFriction.setreg_override new file mode 100644 index 0000000000..c53b04e5c2 --- /dev/null +++ b/AutomatedTesting/Registry/C4044459_Material_DynamicFriction.setreg_override @@ -0,0 +1,118 @@ +{ + "Amazon": { + "Gems": { + "PhysX": { + "PhysXSystemConfiguration": { + "CollisionConfig": { + "Layers": { + "LayerNames": [ + "Default", + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + "TouchBend" + ] + }, + "Groups": { + "GroupPresets": [ + { + "Name": "All", + "ReadOnly": true + }, + { + "Id": { + "GroupId": "{CDB6B8D8-5CD0-40A8-874D-839B00A92EBB}" + }, + "Name": "None", + "Group": { + "Mask": 0 + }, + "ReadOnly": true + }, + { + "Id": { + "GroupId": "{22769429-5D46-429B-829A-0115239D9AAA}" + }, + "Name": "All_NoTouchBend", + "Group": { + "Mask": 9223372036854775807 + }, + "ReadOnly": true + } + ] + } + }, + "DefaultMaterial": { + "SurfaceType": "Default_1" + }, + "MaterialLibrary": { + "assetId": { + "guid": "{6AA79EE4-7EC3-5717-87AE-EDD7D886FD7F}" + }, + "loadBehavior": "QueueLoad", + "assetHint": "levels/physics/c4044459_material_dynamicfriction/dynamic_friction.physmaterial" + } + } + } + } + } +} \ No newline at end of file diff --git a/AutomatedTesting/Registry/C4976227_Collider_NewGroup.setreg_override b/AutomatedTesting/Registry/C4976227_Collider_NewGroup.setreg_override index afbe6a9d38..5e98e08ede 100644 --- a/AutomatedTesting/Registry/C4976227_Collider_NewGroup.setreg_override +++ b/AutomatedTesting/Registry/C4976227_Collider_NewGroup.setreg_override @@ -107,6 +107,9 @@ ] } }, + "DefaultMaterial": { + "SurfaceType": "Default_1" + }, "MaterialLibrary": { "assetId": { "guid": "{3A055A3F-8CB7-5FEE-B437-EB365FACD0D4}" diff --git a/AutomatedTesting/Registry/C4976244_Collider_SameGroupSameLayerCollision.setreg_override b/AutomatedTesting/Registry/C4976244_Collider_SameGroupSameLayerCollision.setreg_override index 9fa5e26768..696a0a74da 100644 --- a/AutomatedTesting/Registry/C4976244_Collider_SameGroupSameLayerCollision.setreg_override +++ b/AutomatedTesting/Registry/C4976244_Collider_SameGroupSameLayerCollision.setreg_override @@ -119,6 +119,9 @@ ] } }, + "DefaultMaterial": { + "SurfaceType": "Default_1" + }, "MaterialLibrary": { "assetId": { "guid": "{3A055A3F-8CB7-5FEE-B437-EB365FACD0D4}" diff --git a/AutomatedTesting/Registry/C4976245_PhysXCollider_CollisionLayerTest.setreg_override b/AutomatedTesting/Registry/C4976245_PhysXCollider_CollisionLayerTest.setreg_override index 9fa5e26768..696a0a74da 100644 --- a/AutomatedTesting/Registry/C4976245_PhysXCollider_CollisionLayerTest.setreg_override +++ b/AutomatedTesting/Registry/C4976245_PhysXCollider_CollisionLayerTest.setreg_override @@ -119,6 +119,9 @@ ] } }, + "DefaultMaterial": { + "SurfaceType": "Default_1" + }, "MaterialLibrary": { "assetId": { "guid": "{3A055A3F-8CB7-5FEE-B437-EB365FACD0D4}" diff --git a/AutomatedTesting/Registry/C4982593_PhysXCollider_CollisionLayer.setreg_override b/AutomatedTesting/Registry/C4982593_PhysXCollider_CollisionLayer.setreg_override index 9fa5e26768..696a0a74da 100644 --- a/AutomatedTesting/Registry/C4982593_PhysXCollider_CollisionLayer.setreg_override +++ b/AutomatedTesting/Registry/C4982593_PhysXCollider_CollisionLayer.setreg_override @@ -119,6 +119,9 @@ ] } }, + "DefaultMaterial": { + "SurfaceType": "Default_1" + }, "MaterialLibrary": { "assetId": { "guid": "{3A055A3F-8CB7-5FEE-B437-EB365FACD0D4}" diff --git a/AutomatedTesting/Registry/physxsystemconfiguration.setreg b/AutomatedTesting/Registry/physxsystemconfiguration.setreg index 02f65b685b..30e9dced44 100644 --- a/AutomatedTesting/Registry/physxsystemconfiguration.setreg +++ b/AutomatedTesting/Registry/physxsystemconfiguration.setreg @@ -101,6 +101,9 @@ ] } }, + "DefaultMaterial": { + "SurfaceType": "Default_1" + }, "MaterialLibrary": { "assetId": { "guid": "{3A055A3F-8CB7-5FEE-B437-EB365FACD0D4}" diff --git a/AutomatedTesting/surfacetypemateriallibrary.physmaterial b/AutomatedTesting/surfacetypemateriallibrary.physmaterial index 3c39d5521e..434d673998 100644 --- a/AutomatedTesting/surfacetypemateriallibrary.physmaterial +++ b/AutomatedTesting/surfacetypemateriallibrary.physmaterial @@ -1,18 +1,19 @@ - + - - - + + + + - + diff --git a/Code/Framework/AzFramework/AzFramework/Physics/ClassConverters.cpp b/Code/Framework/AzFramework/AzFramework/Physics/ClassConverters.cpp index e43bda4c88..4f206858af 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/ClassConverters.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/ClassConverters.cpp @@ -259,11 +259,18 @@ namespace Physics if (success) { - success = success && dataElement.RemoveElementByName(AZ_CRC("MaterialId", 0x9360e002)); + dataElement.RemoveElementByName(AZ_CRC("MaterialId", 0x9360e002)); + success = success && (dataElement.FindElement(AZ_CRC("MaterialId", 0x9360e002)) < 0); success = success && dataElement.AddElementWithData(context, "MaterialIds", AZStd::vector { materialId }); } } + if (success && dataElement.GetVersion() <= 2) + { + dataElement.RemoveElementByName(AZ_CRC_CE("Material")); + success = success && (dataElement.FindElement(AZ_CRC_CE("Material")) < 0); + } + return success; } } // namespace ClassConverters diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsEvents.h b/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsEvents.h index d5a82c0367..a3a34dc1df 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsEvents.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsEvents.h @@ -58,9 +58,18 @@ namespace AzPhysics //! When triggered will send the handle to the old Scene (after this call, the Handle will be invalid). using OnSceneRemovedEvent = AZ::Event; - //! Event that triggers when the default material library changes. + //! Event that triggers when the material library changes. //! When triggered the event will send the Asset Id of the new material library. - using OnDefaultMaterialLibraryChangedEvent = AZ::Event; + using OnMaterialLibraryChangedEvent = AZ::Event; + + enum class MaterialLibraryLoadErrorType : uint8_t + { + InvalidId, + ErrorLoading + }; + + //! Event that triggers when the default material library has loaded with errors. + using OnMaterialLibraryLoadErrorEvent = AZ::Event; //! Event that triggers when the default scene configuration changes. //! When triggered the event will send the new default scene configuration. diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SystemConfiguration.cpp b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SystemConfiguration.cpp index cd250b71a9..d7532cbfea 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SystemConfiguration.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SystemConfiguration.cpp @@ -39,6 +39,8 @@ namespace AzPhysics ->Field("ShapecastBufferSize", &SystemConfiguration::m_shapecastBufferSize) ->Field("OverlapBufferSize", &SystemConfiguration::m_overlapBufferSize) ->Field("CollisionConfig", &SystemConfiguration::m_collisionConfig) + ->Field("DefaultMaterial", &SystemConfiguration::m_defaultMaterialConfiguration) + ->Field("MaterialLibrary", &SystemConfiguration::m_materialLibraryAsset) ; if (AZ::EditContext* editContext = serializeContext->GetEditContext()) @@ -79,7 +81,9 @@ namespace AzPhysics m_overlapBufferSize == other.m_overlapBufferSize && AZ::IsClose(m_maxTimestep, other.m_maxTimestep) && AZ::IsClose(m_fixedTimestep, other.m_fixedTimestep) && - m_collisionConfig == other.m_collisionConfig + m_collisionConfig == other.m_collisionConfig && + m_defaultMaterialConfiguration == other.m_defaultMaterialConfiguration && + m_materialLibraryAsset == other.m_materialLibraryAsset ; } diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SystemConfiguration.h b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SystemConfiguration.h index 0a00d627a7..56fe9a68c4 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SystemConfiguration.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SystemConfiguration.h @@ -13,6 +13,7 @@ #include #include +#include namespace AZ { @@ -45,6 +46,9 @@ namespace AzPhysics //! Each Physics Scene uses this as a base and will override as needed. CollisionConfiguration m_collisionConfig; + Physics::MaterialConfiguration m_defaultMaterialConfiguration; //!< Default material parameters for the project. + AZ::Data::Asset m_materialLibraryAsset = AZ::Data::AssetLoadBehavior::NoLoad; //!< Material Library exposed by the system component SystemBus API. + //! Controls whether the Physics System will self register to the TickBus and call StartSimulation / FinishSimulation on each Scene. //! Disable this to manually control Physics Scene simulation logic. bool m_autoManageSimulationUpdate = true; diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Material.cpp b/Code/Framework/AzFramework/AzFramework/Physics/Material.cpp index 5552cef448..78e0431753 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Material.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/Material.cpp @@ -49,10 +49,7 @@ namespace Physics { materialSelection->SetMaterialSlots(Physics::MaterialSelection::SlotsArray()); } - if (materialSelection->IsDefaultMaterialLibraryAsset()) - { - materialSelection->SyncSelectionToMaterialLibrary(); - } + materialSelection->SyncSelectionToMaterialLibrary(); } }; @@ -122,6 +119,24 @@ namespace Physics } } + bool MaterialConfiguration::operator==(const MaterialConfiguration& other) const + { + return m_surfaceType == other.m_surfaceType && + AZ::IsClose(m_dynamicFriction, other.m_dynamicFriction) && + AZ::IsClose(m_staticFriction, other.m_staticFriction) && + AZ::IsClose(m_restitution, other.m_restitution) && + AZ::IsClose(m_density, other.m_density) && + m_restitutionCombine == other.m_restitutionCombine && + m_frictionCombine == other.m_frictionCombine && + m_debugColor == other.m_debugColor + ; + } + + bool MaterialConfiguration::operator!=(const MaterialConfiguration& other) const + { + return !(*this == other); + } + AZ::Color MaterialConfiguration::GenerateDebugColor(const char* materialName) { static const AZ::Color colors[] = @@ -191,51 +206,25 @@ namespace Physics ////////////////////////////////////////////////////////////////////////// - void MaterialLibraryAssetReflectionWrapper::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serializeContext = azrtti_cast(context); - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ->Field("Asset", &MaterialLibraryAssetReflectionWrapper::m_asset) - ; - - AZ::EditContext* editContext = serializeContext->GetEditContext(); - if (editContext) - { - editContext->Class("", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AutoExpand, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialLibraryAssetReflectionWrapper::m_asset, "Physics Material Library", "Physics Material Library") - ->Attribute("EditButton", "") - ; - } - } - } - - ////////////////////////////////////////////////////////////////////////// - - - void DefaultMaterialLibraryAssetReflectionWrapper::Reflect(AZ::ReflectContext* context) + void MaterialInfoReflectionWrapper::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast(context); if (serializeContext) { - serializeContext->Class() + serializeContext->Class() ->Version(1) - ->Field("Asset", &DefaultMaterialLibraryAssetReflectionWrapper::m_asset) + ->Field("DefaultMaterial", &MaterialInfoReflectionWrapper::m_defaultMaterialConfiguration) + ->Field("Asset", &MaterialInfoReflectionWrapper::m_materialLibraryAsset) ; AZ::EditContext* editContext = serializeContext->GetEditContext(); if (editContext) { - editContext->Class("", "") + editContext->Class("Physics Materials", "") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AutoExpand, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->DataElement(AZ::Edit::UIHandlers::Default, &DefaultMaterialLibraryAssetReflectionWrapper::m_asset, "Default Physics Material Library", "Library to use by default") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialInfoReflectionWrapper::m_defaultMaterialConfiguration, "Default Physics Material", "Material used by default") + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialInfoReflectionWrapper::m_materialLibraryAsset, "Physics Material Library", "Library to use for the project") ->Attribute(AZ::Edit::Attributes::AllowClearAsset, false) ->Attribute("EditButton", "") ; @@ -269,6 +258,17 @@ namespace Physics } } + bool MaterialFromAssetConfiguration::operator==(const MaterialFromAssetConfiguration& other) const + { + return m_configuration == other.m_configuration && + m_id == other.m_id; + } + + bool MaterialFromAssetConfiguration::operator!=(const MaterialFromAssetConfiguration& other) const + { + return !(*this == other); + } + ////////////////////////////////////////////////////////////////////////// bool MaterialLibraryAsset::GetDataForMaterialId(const MaterialId& materialId, MaterialFromAssetConfiguration& configuration) const @@ -370,9 +370,8 @@ namespace Physics if (auto serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(2, &ClassConverters::MaterialSelectionConverter) + ->Version(3, &ClassConverters::MaterialSelectionConverter) ->EventHandler() - ->Field("Material", &MaterialSelection::m_materialLibrary) ->Field("MaterialIds", &MaterialSelection::m_materialIdsAssignedToSlots) ; @@ -381,14 +380,8 @@ namespace Physics editContext->Class("Physics Material", "Select physics material library and which materials to use for the object") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialSelection::m_materialLibrary, "Library", "Physics material library to use for this object") - ->Attribute(AZ::Edit::Attributes::ContainerCanBeModified, true) - ->Attribute("EditButton", "") - ->Attribute("EditDescription", "Open in Asset Editor") - ->Attribute(AZ::Edit::Attributes::DefaultAsset, &MaterialSelection::GetDefaultMaterialLibraryId) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MaterialSelection::OnMaterialLibraryChanged) ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialSelection::m_materialIdsAssignedToSlots, "Mesh Surfaces", "Specify which Physics Material to use for each element of this object") - ->ElementAttribute(Attributes::MaterialLibraryAssetId, &MaterialSelection::GetMaterialLibraryAssetId) + ->ElementAttribute(Attributes::MaterialLibraryAssetId, &MaterialSelection::GetMaterialLibraryId) ->Attribute(AZ::Edit::Attributes::IndexedChildNameLabelOverride, &MaterialSelection::GetMaterialSlotLabel) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->ElementAttribute(AZ::Edit::Attributes::ReadOnly, &MaterialSelection::AreMaterialSlotsReadOnly) @@ -398,12 +391,6 @@ namespace Physics } } - AZ::u32 MaterialSelection::OnMaterialLibraryChanged() - { - SyncSelectionToMaterialLibrary(); - return AZ::Edit::PropertyRefreshLevels::EntireTree; - } - AZStd::string MaterialSelection::GetMaterialSlotLabel(int index) { if (index < m_materialSlots.size()) @@ -425,28 +412,9 @@ namespace Physics } } - AZ::Data::AssetId MaterialSelection::GetMaterialLibraryAssetId() const + void MaterialSelection::OnMaterialLibraryChanged([[maybe_unused]] const AZ::Data::AssetId& defaultMaterialLibraryId) { - return GetMaterialLibraryAsset().GetId(); - } - - const Physics::MaterialLibraryAsset* MaterialSelection::GetMaterialLibraryAssetData() const - { - return GetMaterialLibraryAsset().Get(); - } - - const AZStd::string& MaterialSelection::GetMaterialLibraryAssetHint() const - { - return m_materialLibrary.GetHint(); - } - - void MaterialSelection::OnDefaultMaterialLibraryChanged(const AZ::Data::AssetId& defaultMaterialLibraryId) - { - AZ_UNUSED(defaultMaterialLibraryId); - if (IsDefaultMaterialLibraryAsset()) - { - OnMaterialLibraryChanged(); - } + SyncSelectionToMaterialLibrary(); } void MaterialSelection::SetSlotsReadOnly(bool readOnly) @@ -454,45 +422,6 @@ namespace Physics m_slotsReadOnly = readOnly; } - bool MaterialSelection::IsMaterialLibraryValid() const - { - if (GetMaterialLibraryAssetId().IsValid()) - { - auto materialAsset = LoadAsset(); - const auto& materialsData = materialAsset.Get()->GetMaterialsData(); - - if (materialsData.size() != 0) - { - return true; - } - } - return false; - } - - bool MaterialSelection::GetMaterialConfiguration(Physics::MaterialFromAssetConfiguration& configuration, const Physics::MaterialId& materialId) const - { - if (IsMaterialLibraryValid()) - { - auto materialAsset = LoadAsset(); - if (materialAsset.Get()) - { - return materialAsset.Get()->GetDataForMaterialId(materialId, configuration); - } - } - return false; - } - - void MaterialSelection::SetMaterialLibrary(const AZ::Data::AssetId& assetId) - { - m_materialLibrary = AZ::Data::AssetManager::Instance().GetAsset(assetId, m_materialLibrary.GetAutoLoadBehavior()); - m_materialLibrary.BlockUntilLoadComplete(); - } - - void MaterialSelection::ResetToDefaultMaterialLibrary() - { - m_materialLibrary = {}; - } - void MaterialSelection::SetMaterialSlots(const SlotsArray& slots) { if (slots.empty()) @@ -533,74 +462,45 @@ namespace Physics m_materialIdsAssignedToSlots[slotIndex] = materialId; } - AZ::Data::Asset MaterialSelection::LoadAsset() const - { - AZ::Data::Asset asset = AZ::Data::AssetManager::Instance() - .GetAsset(GetMaterialLibraryAssetId(), AZ::Data::AssetLoadBehavior::Default); - - asset.BlockUntilLoadComplete(); - - return asset; - } - void MaterialSelection::SyncSelectionToMaterialLibrary() { - if (GetMaterialLibraryAssetId().IsValid()) + auto* materialLibrary = GetMaterialLibrary().Get(); + if (!materialLibrary) { - auto materialLibraryAsset = AZ::Data::AssetManager::Instance().GetAsset(GetMaterialLibraryAssetId(), AZ::Data::AssetLoadBehavior::Default); + return; + } - materialLibraryAsset.BlockUntilLoadComplete(); - - // We try to check whether existing selection matches any materials in the newly assigned library and do one of the following: - // 1. If previous MaterialId is invalid for this material library, and it is not the Default material, we set it to the Default material from the library. - // 2. If it's valid, or it is the Default material, we don't change it (useful when user accidentally re-assigns the same library: previous selection won't go away). - - if (materialLibraryAsset.Get()) + for (Physics::MaterialId& materialId : m_materialIdsAssignedToSlots) + { + // Leave nulls (default) unchanged. + if (materialId.IsNull()) { - for (Physics::MaterialId& materialId : m_materialIdsAssignedToSlots) - { - if (!materialLibraryAsset.Get()->HasDataForMaterialId(materialId) - && !materialId.IsNull()) // Null materialId is the Default material. - { - materialId = MaterialId(); - } - } + continue; } - else + + // If the material id is not present in the library anymore, set it to default + if (!materialLibrary->HasDataForMaterialId(materialId)) { - AZ_Warning("PhysX", false, "MaterialSelection: invalid material library"); + materialId = MaterialId(); } } } - const AZ::Data::Asset& MaterialSelection::GetMaterialLibraryAsset() const - { - if (IsDefaultMaterialLibraryAsset()) - { - const AZ::Data::Asset& defaultMaterialLibrary = GetDefaultMaterialLibrary(); - return defaultMaterialLibrary; - } - - return m_materialLibrary; - } - - bool MaterialSelection::IsDefaultMaterialLibraryAsset() const - { - return !m_materialLibrary.GetId().IsValid(); - } - - const AZ::Data::Asset& MaterialSelection::GetDefaultMaterialLibrary() + const AZ::Data::Asset& MaterialSelection::GetMaterialLibrary() { if (auto* physicsSystem = AZ::Interface::Get()) { - return physicsSystem->GetDefaultMaterialLibrary(); + if (const auto* physicsConfiguration = physicsSystem->GetConfiguration()) + { + return physicsConfiguration->m_materialLibraryAsset; + } } return s_invalidMaterialLibrary; } - const AZ::Data::AssetId& MaterialSelection::GetDefaultMaterialLibraryId() + const AZ::Data::AssetId& MaterialSelection::GetMaterialLibraryId() { - return GetDefaultMaterialLibrary().GetId(); + return GetMaterialLibrary().GetId(); } bool MaterialSelection::AreMaterialSlotsReadOnly() const diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Material.h b/Code/Framework/AzFramework/AzFramework/Physics/Material.h index e9eaae929f..69edf3ed25 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Material.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Material.h @@ -29,7 +29,6 @@ namespace Physics /// ========================= /// This is the interface to the wrapper around native material type (such as PxMaterial in PhysX gem) /// that stores extra metadata, like Surface Type name. - /// To see more details about PhysX implementation please refer to PhysX::Material class /// /// Usage example /// ------------------------- @@ -37,14 +36,7 @@ namespace Physics /// /// Physics::MaterialConfiguration materialProperties; /// AZStd::shared_ptr newMaterial = AZ::Interface::Get()->CreateMaterial(materialProperties); - /// - /// To get PxMaterial use GetNativePointer function - /// - /// physx::PxMaterial* material = static_cast(newMaterial->GetNativePointer()); - /// - /// You can use retrieved PxMaterial pointer on its own, provided you increment its reference count. - /// If this class goes out of scope, the PxMaterial pointer will be valid, but its userData - /// will be cleaned up to point to nullptr. + /// class Material { public: @@ -63,9 +55,9 @@ namespace Physics /// Returns AZ::Crc32 of the surface name. virtual AZ::Crc32 GetSurfaceType() const = 0; - virtual void SetSurfaceType(AZ::Crc32 surfaceType) = 0; virtual const AZStd::string& GetSurfaceTypeName() const = 0; + virtual void SetSurfaceTypeName(const AZStd::string& surfaceTypeName) = 0; virtual float GetDynamicFriction() const = 0; virtual void SetDynamicFriction(float dynamicFriction) = 0; @@ -85,6 +77,9 @@ namespace Physics virtual float GetDensity() const = 0; virtual void SetDensity(float density) = 0; + virtual AZ::Color GetDebugColor() const = 0; + virtual void SetDebugColor(const AZ::Color& debugColor) = 0; + /// If the name of this material matches the name of one of the CrySurface types, it will return its CrySurface Id.\n /// If there's no match it will return default CrySurface Id.\n /// CrySurface types are defined in libs/materialeffects/surfacetypes.xml @@ -122,6 +117,10 @@ namespace Physics Material::CombineMode m_frictionCombine = Material::CombineMode::Average; AZ::Color m_debugColor = AZ::Colors::White; + + bool operator==(const MaterialConfiguration& other) const; + bool operator!=(const MaterialConfiguration& other) const; + private: static bool VersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement); static AZ::Color GenerateDebugColor(const char* materialName); @@ -147,6 +146,7 @@ namespace Physics static MaterialId FromUUID(const AZ::Uuid& uuid); bool IsNull() const { return m_id.IsNull(); } bool operator==(const MaterialId& other) const { return m_id == other.m_id; } + bool operator!=(const MaterialId& other) const { return !(*this == other); } const AZ::Uuid& GetUuid() const { return m_id; } private: @@ -166,6 +166,9 @@ namespace Physics MaterialConfiguration m_configuration; MaterialId m_id; + + bool operator==(const MaterialFromAssetConfiguration& other) const; + bool operator!=(const MaterialFromAssetConfiguration& other) const; }; /// An asset that holds a list of materials to be edited and assigned in Open 3D Engine Editor @@ -222,40 +225,27 @@ namespace Physics AZStd::vector m_materialLibrary; }; - /// The class is used to expose a MaterialLibraryAsset to Edit Context + /// The class is used to expose a default material and material library asset to Edit Context /// ======================================================================= /// /// Since AZ::Data::Asset doesn't reflect the data to EditContext /// we have to have a wrapper doing it. - class MaterialLibraryAssetReflectionWrapper + class MaterialInfoReflectionWrapper { public: - AZ_CLASS_ALLOCATOR(MaterialLibraryAssetReflectionWrapper, AZ::SystemAllocator, 0); - AZ_TYPE_INFO(Physics::MaterialLibraryAssetReflectionWrapper, "{3D2EF5DF-EFD0-47EB-B88F-3E6FE1FEE5B0}"); + AZ_CLASS_ALLOCATOR(MaterialInfoReflectionWrapper, AZ::SystemAllocator, 0); + AZ_TYPE_INFO(Physics::MaterialInfoReflectionWrapper, "{02AB8CBC-D35B-4E0F-89BA-A96D94DAD4F9}"); static void Reflect(AZ::ReflectContext* context); - AZ::Data::Asset m_asset = + Physics::MaterialConfiguration m_defaultMaterialConfiguration; + AZ::Data::Asset m_materialLibraryAsset = AZ::Data::AssetLoadBehavior::NoLoad; }; - /// Customized material library for use as default material library - class DefaultMaterialLibraryAssetReflectionWrapper : public Physics::MaterialLibraryAssetReflectionWrapper - { - public: - AZ_CLASS_ALLOCATOR(MaterialLibraryAssetReflectionWrapper, AZ::SystemAllocator, 0); - AZ_TYPE_INFO(Physics::DefaultMaterialLibraryAssetReflectionWrapper, "{02AB8CBC-D35B-4E0F-89BA-A96D94DAD4F9}"); - static void Reflect(AZ::ReflectContext* context); - - AZ::Data::Asset m_asset = - AZ::Data::AssetLoadBehavior::NoLoad; - }; - - /// The class is used to store a MaterialLibraryAsset and a vector of MaterialIds selected from the library + /// The class is used to store a vector of MaterialIds selected from the library /// ======================================================================= /// - /// This class is used to store a reference to the library asset and user's - /// selection of the materials from this library.\n - /// It also reflects UI controls for assigning MaterialLibraryAsset and selecting a material from it. + /// This class is used to store the user's selection of the materials from this library. /// You can reflect this class in EditorContext to provide UI for selecting materials /// on any custom component or QWidget. class MaterialSelection @@ -269,27 +259,6 @@ namespace Physics static void Reflect(AZ::ReflectContext* context); - /// Returns whether MaterialLibraryAsset assigned to this selection exists and valid. Attempts to load - /// the library if it's not loaded yet. - /// @return true if MaterialLibraryAsset has a valid AssetId, loaded and isn't empty - bool IsMaterialLibraryValid() const; - - /// Looks up MaterialLibraryAsset for MaterialFromAssetConfiguration with MaterialId that is stored intrenally. - /// @param configuration contains material data if there is a material selected by user - /// and if it exists in the MaterialLibraryAsset - /// @param materialId MaterialId to retrieve MaterialFromAssetConfiguration for - /// @return true if lookup was successful. - bool GetMaterialConfiguration(Physics::MaterialFromAssetConfiguration& configuration, const Physics::MaterialId& materialId) const; - - /// Sets and loads MaterialLibraryAsset with specified AssetId. - /// It is used to construct MaterialSelection at runtime. - /// It is not a typical use case and mostly needed to convert legacy entities and auto-generate material libraries - /// @param assetId AssetId to create MaterialLibraryAsset with - void SetMaterialLibrary(const AZ::Data::AssetId& assetId); - - /// Sets the material library to none, this will cause to use the project-wide default material library - void ResetToDefaultMaterialLibrary(); - /// Sets an array of material slots to pick MaterialIds for. Having multiple slots is required for assigning multiple materials on a mesh /// or heightfield object. SlotsArray can be empty and in this case Default slot will be created. /// @param slots Array of names for slots. Can be empty, in this case Default slot will be created @@ -298,48 +267,34 @@ namespace Physics /// Returns a list of MaterialId that were assigned for each corresponding slot. const AZStd::vector& GetMaterialIdsAssignedToSlots() const; - /// Sets the MaterialId from MaterialLibraryAsset as the selected material at a specific slotIndex. - /// @param materialId MaterialId that user selected from the MaterialLibraryAsset - /// @param slotIndex index of the slot to set MaterialId for + /// Sets the MaterialId as the selected material at a specific slotIndex. + /// @param materialId MaterialId that user selected + /// @param slotIndex Index of the slot to set the MaterialId void SetMaterialId(const Physics::MaterialId& materialId, int slotIndex = 0); - /// Returns the material library asset id. - AZ::Data::AssetId GetMaterialLibraryAssetId() const; - /// Returns the material id assigned to this selection at a specific slotIndex. - /// @param slotIndex index of the slot to retrieve MaterialId for + /// @param slotIndex Index of the slot to retrieve the MaterialId Physics::MaterialId GetMaterialId(int slotIndex = 0) const; - /// Returns the material library asset. - const Physics::MaterialLibraryAsset* GetMaterialLibraryAssetData() const; - - /// Returns the material library asset hint(UI display string) - const AZStd::string& GetMaterialLibraryAssetHint() const; - /// Called when the material library has changed - void OnDefaultMaterialLibraryChanged(const AZ::Data::AssetId& defaultMaterialLibraryId); + void OnMaterialLibraryChanged(const AZ::Data::AssetId& defaultMaterialLibraryId); /// Set if the material slots are editable in the edit context void SetSlotsReadOnly(bool readOnly); private: - AZ::Data::Asset m_materialLibrary { AZ::Data::AssetLoadBehavior::NoLoad }; AZStd::vector m_materialIdsAssignedToSlots; SlotsArray m_materialSlots; bool m_slotsReadOnly = false; - const AZ::Data::Asset& GetMaterialLibraryAsset() const; - AZ::Data::Asset LoadAsset() const; - bool IsDefaultMaterialLibraryAsset() const; void SyncSelectionToMaterialLibrary(); - static const AZ::Data::Asset& GetDefaultMaterialLibrary(); - static const AZ::Data::AssetId& GetDefaultMaterialLibraryId(); + static const AZ::Data::Asset& GetMaterialLibrary(); + static const AZ::Data::AssetId& GetMaterialLibraryId(); bool AreMaterialSlotsReadOnly() const; // EditorContext callbacks - AZ::u32 OnMaterialLibraryChanged(); AZStd::string GetMaterialSlotLabel(int index); }; diff --git a/Code/Framework/AzFramework/AzFramework/Physics/MaterialBus.h b/Code/Framework/AzFramework/AzFramework/Physics/MaterialBus.h index edfa3096d3..a7e4869df1 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/MaterialBus.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/MaterialBus.h @@ -25,21 +25,26 @@ namespace Physics static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; // Implemented by sole owner of materials, e.g. class MaterialManager in PhysX gem. - /// Get default material + /// Get default material. virtual AZStd::shared_ptr GetGenericDefaultMaterial() = 0; /// Returns weak pointers to physics materials. /// Connect to PhysicsMaterialNotifications::MaterialsReleased to be informed when material pointers are deleted by owner. virtual void GetMaterials(const MaterialSelection& materialSelection - , AZStd::vector>& outMaterials) = 0; + , AZStd::vector>& outMaterials) = 0; + + /// Returns a weak pointer to physics material with the given id. + virtual AZStd::shared_ptr GetMaterialById(Physics::MaterialId id) = 0; /// Returns a weak pointer to physics material with the given name. - virtual AZStd::weak_ptr GetMaterialByName(const AZStd::string& name) = 0; + virtual AZStd::shared_ptr GetMaterialByName(const AZStd::string& name) = 0; - /// Returns index of the first selected material in MaterialSelection's material library. - /// A MaterialSelection can contain multiple material selections. - /// Returned index is 0-based where 0 is the Default material, and materials from the material library are 1 and onwards. - virtual AZ::u32 GetFirstSelectedMaterialIndex(const MaterialSelection& materialSelection) = 0; + /// Updates the material selection from the physics asset or sets it to default if there's no asset provided. + /// @param shapeConfiguration The shape information that contains the physics asset. + /// @param materialSelection The material selection to update. + virtual void UpdateMaterialSelectionFromPhysicsAsset( + const ShapeConfiguration& shapeConfiguration, + MaterialSelection& materialSelection) = 0; }; using PhysicsMaterialRequestBus = AZ::EBus; diff --git a/Code/Framework/AzFramework/AzFramework/Physics/PhysicsSystem.h b/Code/Framework/AzFramework/AzFramework/Physics/PhysicsSystem.h index e3ed449046..36ae4dbecb 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/PhysicsSystem.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/PhysicsSystem.h @@ -130,13 +130,6 @@ namespace AzPhysics //! @param forceReinitialization Flag to force a reinitialization of the physics system. Default false. virtual void UpdateConfiguration(const SystemConfiguration* newConfig, bool forceReinitialization = false) = 0; - //! Update the default material library. - //! @param materialLibrary The new material library asset to use. - virtual void UpdateDefaultMaterialLibrary(const AZ::Data::Asset& materialLibrary) = 0; - - //! Accessor to get the current Material Library. This is also available in the PhysXSystemConfiguration. - virtual const AZ::Data::Asset& GetDefaultMaterialLibrary() const = 0; - //! Update the current default scene configuration. //! This is the configuration used to to create scenes without a custom configuration. //! @param sceneConfiguration The new configuration to apply. @@ -169,9 +162,12 @@ namespace AzPhysics //! Register to receive notifications when the SystemConfiguration changes. //! @param handler The handler to receive the event. void RegisterSystemConfigurationChangedEvent(SystemEvents::OnConfigurationChangedEvent::Handler& handler) { handler.Connect(m_configChangeEvent); } - //! Register a handler to receive an event when the default material library changes. + //! Register a handler to receive an event when the material library changes. //! @param handler The handler to receive the event. - void RegisterOnDefaultMaterialLibraryChangedEventHandler(SystemEvents::OnDefaultMaterialLibraryChangedEvent::Handler& handler) { handler.Connect(m_onDefaultMaterialLibraryChangedEvent); } + void RegisterOnMaterialLibraryChangedEventHandler(SystemEvents::OnMaterialLibraryChangedEvent::Handler& handler) { handler.Connect(m_onMaterialLibraryChangedEvent); } + //! Register a handler to receive an event when the material library fails to load on startup. + //! @param handler The handler to receive the event. + void RegisterOnMaterialLibraryLoadErrorEventHandler(SystemEvents::OnMaterialLibraryLoadErrorEvent::Handler& handler) { handler.Connect(m_onMaterialLibraryLoadErrorEvent); } //! Register a handler to receive an event when the default SceneConfiguration changes. //! @param handler The handler to receive the event. void RegisterOnDefaultSceneConfigurationChangedEventHandler(SystemEvents::OnDefaultSceneConfigurationChangedEvent::Handler& handler) { handler.Connect(m_onDefaultSceneConfigurationChangedEvent); } @@ -185,7 +181,8 @@ namespace AzPhysics SystemEvents::OnSceneAddedEvent m_sceneAddedEvent; SystemEvents::OnSceneRemovedEvent m_sceneRemovedEvent; SystemEvents::OnConfigurationChangedEvent m_configChangeEvent; - SystemEvents::OnDefaultMaterialLibraryChangedEvent m_onDefaultMaterialLibraryChangedEvent; + SystemEvents::OnMaterialLibraryChangedEvent m_onMaterialLibraryChangedEvent; + SystemEvents::OnMaterialLibraryLoadErrorEvent m_onMaterialLibraryLoadErrorEvent; SystemEvents::OnDefaultSceneConfigurationChangedEvent m_onDefaultSceneConfigurationChangedEvent; }; } // namespace AzPhysics diff --git a/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp b/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp index a535f5f65d..275103bc28 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp @@ -17,6 +17,21 @@ namespace Physics { + namespace Internal + { + bool ShapeConfigurationVersionConverter( + [[maybe_unused]] AZ::SerializeContext& context, + AZ::SerializeContext::DataElementNode& classElement) + { + if (classElement.GetVersion() <= 1) + { + classElement.RemoveElementByName(AZ_CRC_CE("UseMaterialsFromAsset")); + } + + return true; + } + } + void ShapeConfiguration::Reflect(AZ::ReflectContext* context) { if (auto serializeContext = azrtti_cast(context)) @@ -166,10 +181,9 @@ namespace Physics ->RegisterGenericType>(); serializeContext->Class() - ->Version(1) + ->Version(2, &Internal::ShapeConfigurationVersionConverter) ->Field("PhysicsAsset", &PhysicsAssetShapeConfiguration::m_asset) ->Field("AssetScale", &PhysicsAssetShapeConfiguration::m_assetScale) - ->Field("UseMaterialsFromAsset", &PhysicsAssetShapeConfiguration::m_useMaterialsFromAsset) ->Field("SubdivisionLevel", &PhysicsAssetShapeConfiguration::m_subdivisionLevel) ; @@ -182,7 +196,6 @@ namespace Physics ->DataElement(AZ::Edit::UIHandlers::Default, &PhysicsAssetShapeConfiguration::m_assetScale, "Asset Scale", "The scale of the asset shape") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Step, 0.01f) - ->DataElement(AZ::Edit::UIHandlers::Default, &PhysicsAssetShapeConfiguration::m_useMaterialsFromAsset, "Physics Materials from Mesh", "Auto-set physics materials using Mesh's material surfaces names") ; } } diff --git a/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.h b/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.h index b3d04a10c9..8234ef9173 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.h @@ -140,7 +140,7 @@ namespace Physics AZ::Data::Asset m_asset{ AZ::Data::AssetLoadBehavior::PreLoad }; AZ::Vector3 m_assetScale = AZ::Vector3::CreateOne(); - bool m_useMaterialsFromAsset = true; + bool m_useMaterialsFromAsset = false; // Not reflected or exposed to the user until there is a way to auto-match mesh's materials with physics materials AZ::u8 m_subdivisionLevel = 4; ///< The level of subdivision if a primitive shape is replaced with a convex mesh due to scaling. }; diff --git a/Code/Framework/AzFramework/AzFramework/Physics/SystemBus.h b/Code/Framework/AzFramework/AzFramework/Physics/SystemBus.h index f198551148..8cdd0e0cf0 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/SystemBus.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/SystemBus.h @@ -142,24 +142,12 @@ namespace Physics virtual AZStd::shared_ptr CreateShape(const ColliderConfiguration& colliderConfiguration, const ShapeConfiguration& configuration) = 0; + virtual AZStd::shared_ptr CreateMaterial(const Physics::MaterialConfiguration& materialConfiguration) = 0; + /// Releases the mesh object created by the physics backend. /// @param nativeMeshObject Pointer to the mesh object. virtual void ReleaseNativeMeshObject(void* nativeMeshObject) = 0; - ////////////////////////////////////////////////////////////////////////// - //// Physics Materials - - virtual AZStd::shared_ptr CreateMaterial(const Physics::MaterialConfiguration& materialConfiguration) = 0; - virtual AZStd::shared_ptr GetDefaultMaterial() = 0; - virtual AZStd::vector> CreateMaterialsFromLibrary(const Physics::MaterialSelection& materialSelection) = 0; - - - /// Updates the collider material selection from the physics asset or sets it to default if there's no asset provided. - /// @param shapeConfiguration The shape information - /// @param colliderConfiguration The collider information - virtual bool UpdateMaterialSelection(const Physics::ShapeConfiguration& shapeConfiguration, - Physics::ColliderConfiguration& colliderConfiguration) = 0; - ////////////////////////////////////////////////////////////////////////// //// Joints diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Utils.cpp b/Code/Framework/AzFramework/AzFramework/Physics/Utils.cpp index b5f113582b..2c3b62bb88 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Utils.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/Utils.cpp @@ -119,8 +119,7 @@ namespace Physics AzPhysics::SceneConfiguration::Reflect(context); MaterialConfiguration::Reflect(context); MaterialLibraryAsset::Reflect(context); - MaterialLibraryAssetReflectionWrapper::Reflect(context); - DefaultMaterialLibraryAssetReflectionWrapper::Reflect(context); + MaterialInfoReflectionWrapper::Reflect(context); JointLimitConfiguration::Reflect(context); AzPhysics::SimulatedBodyConfiguration::Reflect(context); AzPhysics::RigidBodyConfiguration::Reflect(context); diff --git a/Gems/Blast/Code/Source/Actor/BlastActorImpl.cpp b/Gems/Blast/Code/Source/Actor/BlastActorImpl.cpp index 6c4c78c412..8f82f3366f 100644 --- a/Gems/Blast/Code/Source/Actor/BlastActorImpl.cpp +++ b/Gems/Blast/Code/Source/Actor/BlastActorImpl.cpp @@ -151,8 +151,6 @@ namespace Blast colliderConfiguration.m_position = transform.GetTranslation(); colliderConfiguration.m_rotation = transform.GetRotation(); colliderConfiguration.m_isExclusive = true; - colliderConfiguration.m_materialSelection.SetMaterialLibrary( - AZ::Interface::Get()->GetDefaultMaterialLibrary()->GetId()); colliderConfiguration.m_materialSelection.SetMaterialId(material); colliderConfiguration.m_collisionGroupId = actorConfiguration.m_collisionGroupId; colliderConfiguration.m_collisionLayer = actorConfiguration.m_collisionLayer; diff --git a/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp b/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp index 0f2668442c..d5cb16596a 100644 --- a/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp +++ b/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -265,10 +266,23 @@ namespace Blast auto solverPtr = Nv::Blast::ExtStressSolver::create( const_cast(*m_family->GetTkFamily()->getFamilyLL()), stressSolverSettings); m_solver = physx::unique_ptr(solverPtr); - Physics::MaterialFromAssetConfiguration material; - AZ::Interface::Get()->GetDefaultMaterialLibrary()->GetDataForMaterialId( - m_physicsMaterialId, material); - m_solver->setAllNodesInfoFromLL(material.m_configuration.m_density); + + AZStd::shared_ptr physicsMaterial; + Physics::PhysicsMaterialRequestBus::BroadcastResult( + physicsMaterial, + &Physics::PhysicsMaterialRequestBus::Events::GetMaterialById, + m_physicsMaterialId); + if (!physicsMaterial) + { + AZ_Warning("BlastFamilyComponent", false, "Material Id %s was not found, using default material instead.", + m_physicsMaterialId.GetUuid().ToString().c_str()); + + Physics::PhysicsMaterialRequestBus::BroadcastResult( + physicsMaterial, + &Physics::PhysicsMaterialRequestBus::Events::GetGenericDefaultMaterial); + AZ_Assert(physicsMaterial, "BlastFamilyComponent: Invalid default physics material"); + } + m_solver->setAllNodesInfoFromLL(physicsMaterial->GetDensity()); // Create damage and actor render managers m_damageManager = AZStd::make_unique(blastMaterial, m_family->GetActorTracker()); diff --git a/Gems/Blast/Code/Source/Editor/EditorBlastFamilyComponent.cpp b/Gems/Blast/Code/Source/Editor/EditorBlastFamilyComponent.cpp index 9241449483..873ef7248d 100644 --- a/Gems/Blast/Code/Source/Editor/EditorBlastFamilyComponent.cpp +++ b/Gems/Blast/Code/Source/Editor/EditorBlastFamilyComponent.cpp @@ -131,6 +131,6 @@ namespace Blast AZ::Data::AssetId EditorBlastFamilyComponent::GetPhysicsMaterialLibraryAssetId() const { - return AZ::Interface::Get()->GetDefaultMaterialLibrary()->GetId(); + return AZ::Interface::Get()->GetConfiguration()->m_materialLibraryAsset.GetId(); } } // namespace Blast diff --git a/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h b/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h index 22102fd38a..3aafdb4e2b 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h @@ -35,9 +35,6 @@ namespace Physics MOCK_METHOD2(CreateShape, AZStd::shared_ptr(const Physics::ColliderConfiguration& colliderConfiguration, const Physics::ShapeConfiguration& configuration)); MOCK_METHOD1(ReleaseNativeMeshObject, void(void* nativeMeshObject)); MOCK_METHOD1(CreateMaterial, AZStd::shared_ptr(const Physics::MaterialConfiguration& materialConfiguration)); - MOCK_METHOD0(GetDefaultMaterial, AZStd::shared_ptr()); - MOCK_METHOD1(CreateMaterialsFromLibrary, AZStd::vector>(const Physics::MaterialSelection& materialSelection)); - MOCK_METHOD2(UpdateMaterialSelection, bool(const Physics::ShapeConfiguration& shapeConfiguration, Physics::ColliderConfiguration& colliderConfiguration)); MOCK_METHOD0(GetSupportedJointTypes, AZStd::vector()); MOCK_METHOD1(CreateJointLimitConfiguration, AZStd::shared_ptr(AZ::TypeId jointType)); MOCK_METHOD3(CreateJoint, AZStd::shared_ptr(const AZStd::shared_ptr& configuration, AzPhysics::SimulatedBody* parentBody, AzPhysics::SimulatedBody* childBody)); @@ -59,7 +56,6 @@ namespace Physics void Shutdown() override {} void Simulate([[maybe_unused]] float deltaTime) override {} void UpdateConfiguration([[maybe_unused]] const AzPhysics::SystemConfiguration* newConfig, [[maybe_unused]] bool forceReinitialization = false) override {} - void UpdateDefaultMaterialLibrary([[maybe_unused]] const AZ::Data::Asset& materialLibrary) override {} void UpdateDefaultSceneConfiguration([[maybe_unused]] const AzPhysics::SceneConfiguration& sceneConfiguration) override {} void RemoveScene([[maybe_unused]] AzPhysics::SceneHandle handle) override {} void RemoveScenes([[maybe_unused]] const AzPhysics::SceneHandleList& handles) override {} @@ -73,7 +69,6 @@ namespace Physics MOCK_METHOD0(GetAllScenes, AzPhysics::SceneList& ()); MOCK_METHOD1(FindAttachedBodyHandleFromEntityId, AZStd::pair(AZ::EntityId entityId)); MOCK_CONST_METHOD0(GetConfiguration, const AzPhysics::SystemConfiguration* ()); - MOCK_CONST_METHOD0(GetDefaultMaterialLibrary, const AZ::Data::Asset& ()); MOCK_CONST_METHOD0(GetDefaultSceneConfiguration, const AzPhysics::SceneConfiguration& ()); }; diff --git a/Gems/EMotionFX/Code/Tests/ProvidesUI/Ragdoll/CanCopyPasteColliders.cpp b/Gems/EMotionFX/Code/Tests/ProvidesUI/Ragdoll/CanCopyPasteColliders.cpp index 858980fbe8..eaef6f31ee 100644 --- a/Gems/EMotionFX/Code/Tests/ProvidesUI/Ragdoll/CanCopyPasteColliders.cpp +++ b/Gems/EMotionFX/Code/Tests/ProvidesUI/Ragdoll/CanCopyPasteColliders.cpp @@ -54,14 +54,11 @@ namespace EMotionFX [[maybe_unused]] const AZ::Vector3& axis, [[maybe_unused]] const AZStd::vector& exampleLocalRotations) { return AZStd::make_unique(); }); - EXPECT_CALL(m_physicsInterface, GetDefaultMaterialLibrary) - .WillRepeatedly(testing::ReturnRef(m_materialLibraryAsset)); } private: Physics::MockPhysicsSystem m_physicsSystem; Physics::MockPhysicsInterface m_physicsInterface; - AZ::Data::Asset m_materialLibraryAsset; }; #if AZ_TRAIT_DISABLE_FAILED_EMOTION_FX_EDITOR_TESTS diff --git a/Gems/EMotionFX/Code/Tests/ProvidesUI/Ragdoll/CanCopyPasteJointLimits.cpp b/Gems/EMotionFX/Code/Tests/ProvidesUI/Ragdoll/CanCopyPasteJointLimits.cpp index b4b4d14d58..6223af3599 100644 --- a/Gems/EMotionFX/Code/Tests/ProvidesUI/Ragdoll/CanCopyPasteJointLimits.cpp +++ b/Gems/EMotionFX/Code/Tests/ProvidesUI/Ragdoll/CanCopyPasteJointLimits.cpp @@ -59,9 +59,6 @@ namespace EMotionFX .WillRepeatedly(testing::Return(AZStd::vector{azrtti_typeid()})); EXPECT_CALL(physicsSystem, ComputeInitialJointLimitConfiguration(azrtti_typeid(), _, _, _, _)) .WillRepeatedly([]([[maybe_unused]] const AZ::TypeId& jointLimitTypeId, [[maybe_unused]] const AZ::Quaternion& parentWorldRotation, [[maybe_unused]] const AZ::Quaternion& childWorldRotation, [[maybe_unused]] const AZ::Vector3& axis, [[maybe_unused]] const AZStd::vector& exampleLocalRotations) { return AZStd::make_unique(); }); - AZ::Data::Asset materialLibraryAsset; - EXPECT_CALL(physicsInterface, GetDefaultMaterialLibrary) - .WillRepeatedly(testing::ReturnRef(materialLibraryAsset)); AutoRegisteredActor actor {ActorFactory::CreateAndInit(4)}; diff --git a/Gems/PhysX/Code/Editor/DebugDraw.cpp b/Gems/PhysX/Code/Editor/DebugDraw.cpp index 23a9a3cb44..829b776e28 100644 --- a/Gems/PhysX/Code/Editor/DebugDraw.cpp +++ b/Gems/PhysX/Code/Editor/DebugDraw.cpp @@ -17,13 +17,13 @@ #include #include #include +#include #include #include #include #include -#include -#include +#include namespace PhysX { @@ -415,11 +415,16 @@ namespace PhysX { case GlobalCollisionDebugColorMode::MaterialColor: { - Physics::MaterialFromAssetConfiguration materialConfiguration; const Physics::MaterialId materialId = colliderConfig.m_materialSelection.GetMaterialId(elementDebugInfo.m_materialSlotIndex); - if (colliderConfig.m_materialSelection.GetMaterialConfiguration(materialConfiguration, materialId)) + + AZStd::shared_ptr physicsMaterial; + Physics::PhysicsMaterialRequestBus::BroadcastResult( + physicsMaterial, + &Physics::PhysicsMaterialRequestBus::Events::GetMaterialById, + materialId); + if (physicsMaterial) { - debugColor = materialConfiguration.m_configuration.m_debugColor; + debugColor = physicsMaterial->GetDebugColor(); } break; } diff --git a/Gems/PhysX/Code/Editor/SettingsWidget.cpp b/Gems/PhysX/Code/Editor/SettingsWidget.cpp index 38022e8c92..20a67a778d 100644 --- a/Gems/PhysX/Code/Editor/SettingsWidget.cpp +++ b/Gems/PhysX/Code/Editor/SettingsWidget.cpp @@ -37,14 +37,15 @@ namespace PhysX const Debug::DebugDisplayData& debugDisplayData) { m_physxSystemConfiguration = physxSystemConfiguration; - m_defaultPhysicsMaterialLibrary.m_asset = m_physxSystemConfiguration.m_defaultMaterialLibrary; + m_physicsMaterialInfo.m_defaultMaterialConfiguration = m_physxSystemConfiguration.m_defaultMaterialConfiguration; + m_physicsMaterialInfo.m_materialLibraryAsset = m_physxSystemConfiguration.m_materialLibraryAsset; m_defaultSceneConfiguration = defaultSceneConfiguration; m_debugDisplayData = debugDisplayData; blockSignals(true); m_propertyEditor->ClearInstances(); m_propertyEditor->AddInstance(&m_physxSystemConfiguration); - m_propertyEditor->AddInstance(&m_defaultPhysicsMaterialLibrary); + m_propertyEditor->AddInstance(&m_physicsMaterialInfo); m_propertyEditor->AddInstance(&m_defaultSceneConfiguration); m_propertyEditor->AddInstance(&m_debugDisplayData); m_propertyEditor->AddInstance(&m_physxSystemConfiguration.m_windConfiguration); @@ -88,7 +89,8 @@ namespace PhysX void SettingsWidget::SetPropertyEditingComplete(AzToolsFramework::InstanceDataNode* /*node*/) { - m_physxSystemConfiguration.m_defaultMaterialLibrary = m_defaultPhysicsMaterialLibrary.m_asset; + m_physxSystemConfiguration.m_defaultMaterialConfiguration = m_physicsMaterialInfo.m_defaultMaterialConfiguration; + m_physxSystemConfiguration.m_materialLibraryAsset = m_physicsMaterialInfo.m_materialLibraryAsset; emit onValueChanged(m_physxSystemConfiguration, m_defaultSceneConfiguration, m_debugDisplayData diff --git a/Gems/PhysX/Code/Editor/SettingsWidget.h b/Gems/PhysX/Code/Editor/SettingsWidget.h index 78df72b6d3..a4001e13b7 100644 --- a/Gems/PhysX/Code/Editor/SettingsWidget.h +++ b/Gems/PhysX/Code/Editor/SettingsWidget.h @@ -56,7 +56,7 @@ namespace PhysX AzToolsFramework::ReflectedPropertyEditor* m_propertyEditor; DocumentationLinkWidget* m_documentationLinkWidget; - Physics::DefaultMaterialLibraryAssetReflectionWrapper m_defaultPhysicsMaterialLibrary; + Physics::MaterialInfoReflectionWrapper m_physicsMaterialInfo; PhysX::PhysXSystemConfiguration m_physxSystemConfiguration; AzPhysics::SceneConfiguration m_defaultSceneConfiguration; Debug::DebugDisplayData m_debugDisplayData; diff --git a/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp b/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp index e510aa505e..c3f0411d58 100644 --- a/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp +++ b/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp @@ -30,40 +30,45 @@ namespace PhysX { - static bool CreateSurfaceTypeMaterialLibrary(const AZStd::string & targetFilePath) + constexpr const char* DefaultAssetFilename = "SurfaceTypeMaterialLibrary"; + + static AZStd::optional> CreateMaterialLibrary(const AZStd::string& fullTargetFilePath, const AZStd::string& relativePath) { - auto assetType = AZ::AzTypeInfo::Uuid(); - - // Create File - AZ::Data::Asset newAsset = AZ::Data::AssetManager::Instance().CreateAsset(AZ::Uuid::CreateRandom(), assetType, AZ::Data::AssetLoadBehavior::Default); - - AZ::IO::FileIOStream fileStream(targetFilePath.c_str(), AZ::IO::OpenMode::ModeWrite); + AZ::IO::FileIOStream fileStream(fullTargetFilePath.c_str(), AZ::IO::OpenMode::ModeWrite); if (fileStream.IsOpen()) { - Physics::MaterialLibraryAsset* materialLibraryAsset = azrtti_cast(newAsset.GetData()); - if (materialLibraryAsset) + const auto& assetType = AZ::AzTypeInfo::Uuid(); + AZ::Data::AssetId assetId; + + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, relativePath.c_str(), assetType, true); + + AZ::Data::Asset newAsset = + AZ::Data::AssetManager::Instance().GetAsset(assetId, assetType, AZ::Data::AssetLoadBehavior::Default); + + if (Physics::MaterialLibraryAsset* materialLibraryAsset = azrtti_cast(newAsset.GetData())) { // check it out in the source control system AzToolsFramework::SourceControlCommandBus::Broadcast( - &AzToolsFramework::SourceControlCommandBus::Events::RequestEdit, targetFilePath.c_str(), true, + &AzToolsFramework::SourceControlCommandBus::Events::RequestEdit, fullTargetFilePath.c_str(), true, [](bool /*success*/, const AzToolsFramework::SourceControlFileInfo& /*info*/) {}); // Save the material library asset into a file - auto assetHandler = const_cast(AZ::Data::AssetManager::Instance().GetHandler(assetType)); + auto assetHandler = AZ::Data::AssetManager::Instance().GetHandler(assetType); if (assetHandler->SaveAssetData(newAsset, &fileStream)) { - return true; + return newAsset; } else { AZ_Error("PhysX", false, "CreateSurfaceTypeMaterialLibrary: Unable to save Surface Types Material Library Asset to %s", - targetFilePath.c_str()); + fullTargetFilePath.c_str()); } } } - return false; + return AZStd::nullopt; } void EditorSystemComponent::Reflect(AZ::ReflectContext* context) @@ -84,11 +89,26 @@ namespace PhysX { Physics::EditorWorldBus::Handler::BusConnect(); + m_onMaterialLibraryLoadErrorEventHandler = AzPhysics::SystemEvents::OnMaterialLibraryLoadErrorEvent::Handler( + [this]([[maybe_unused]] AzPhysics::SystemEvents::MaterialLibraryLoadErrorType error) + { + // Attempt to set/create the default material library if there was an error + if (auto* physxSystem = GetPhysXSystem()) + { + if (auto retrievedMaterialLibrary = RetrieveDefaultMaterialLibrary()) + { + physxSystem->UpdateMaterialLibrary(retrievedMaterialLibrary.value()); + } + } + } + ); + if (auto* physicsSystem = AZ::Interface::Get()) { AzPhysics::SceneConfiguration editorWorldConfiguration = physicsSystem->GetDefaultSceneConfiguration(); editorWorldConfiguration.m_sceneName = AzPhysics::EditorPhysicsSceneName; m_editorWorldSceneHandle = physicsSystem->AddScene(editorWorldConfiguration); + physicsSystem->RegisterOnMaterialLibraryLoadErrorEventHandler(m_onMaterialLibraryLoadErrorEventHandler); } PhysX::RegisterConfigStringLineEditHandler(); // Register custom unique string line edit control @@ -109,6 +129,8 @@ namespace PhysX physicsSystem->RemoveScene(m_editorWorldSceneHandle); } m_editorWorldSceneHandle = AzPhysics::InvalidSceneHandle; + + m_onMaterialLibraryLoadErrorEventHandler.Disconnect(); } AzPhysics::SceneHandle EditorSystemComponent::GetEditorSceneHandle() const @@ -148,7 +170,7 @@ namespace PhysX PhysX::Editor::EditorWindow::RegisterViewClass(); } - AZ::Data::AssetId EditorSystemComponent::GenerateSurfaceTypesLibrary() + AZStd::optional> EditorSystemComponent::RetrieveDefaultMaterialLibrary() { AZ::Data::AssetId resultAssetId; @@ -159,8 +181,6 @@ namespace PhysX if (assetTypeExtensions.size() == 1) { - const char* DefaultAssetFilename = "SurfaceTypeMaterialLibrary"; - // Constructing the path to the library asset const AZStd::string& assetExtension = assetTypeExtensions[0]; @@ -173,36 +193,39 @@ namespace PhysX if (!resultAssetId.IsValid()) { + // No file for the default material library, create it const char* assetRoot = AZ::IO::FileIOBase::GetInstance()->GetAlias("@devassets@"); - AZStd::string fullPath; AzFramework::StringFunc::Path::ConstructFull(assetRoot, DefaultAssetFilename, assetExtension.c_str(), fullPath); - if (CreateSurfaceTypeMaterialLibrary(fullPath)) + if (auto materialLibraryOpt = CreateMaterialLibrary(fullPath, relativePath)) { - // Find out the asset ID for the material library we've just created - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - resultAssetId, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, - relativePath.c_str(), - azrtti_typeid(), true); + return materialLibraryOpt; } else { AZ_Warning("PhysX", false, - "GenerateSurfaceTypesLibrary: Failed to create material library at %s. " + "CreateMaterialLibrary: Failed to create material library at %s. " "Please check if the file is writable", fullPath.c_str()); } } + else + { + AZ::Data::Asset existingMaterialLibrary = + AZ::Data::AssetManager::Instance().GetAsset(resultAssetId, AZ::Data::AssetLoadBehavior::NoLoad); + + return existingMaterialLibrary; + } } else { AZ_Warning("PhysX", false, - "GenerateSurfaceTypesLibrary: Number of extensions for the physics material library asset is %u" + "RetrieveDefaultMaterialLibrary: Number of extensions for the physics material library asset is %u" " but should be 1. Please check if the asset registered itself with the asset system correctly", assetTypeExtensions.size()) } - return resultAssetId; + return AZStd::nullopt; } } diff --git a/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.h b/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.h index 9ebca05ccd..4bd11a951f 100644 --- a/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.h +++ b/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.h @@ -14,6 +14,7 @@ #include #include +#include #include namespace AzPhysics @@ -65,8 +66,9 @@ namespace PhysX void PopulateEditorGlobalContextMenu(QMenu* menu, const AZ::Vector2& point, int flags) override; void NotifyRegisterViews() override; - AZ::Data::AssetId GenerateSurfaceTypesLibrary(); + AZStd::optional> RetrieveDefaultMaterialLibrary(); + AzPhysics::SystemEvents::OnMaterialLibraryLoadErrorEvent::Handler m_onMaterialLibraryLoadErrorEventHandler; AzPhysics::SceneHandle m_editorWorldSceneHandle = AzPhysics::InvalidSceneHandle; }; } diff --git a/Gems/PhysX/Code/Include/PhysX/Configuration/PhysXConfiguration.h b/Gems/PhysX/Code/Include/PhysX/Configuration/PhysXConfiguration.h index 936eadad18..598cdc1b4c 100644 --- a/Gems/PhysX/Code/Include/PhysX/Configuration/PhysXConfiguration.h +++ b/Gems/PhysX/Code/Include/PhysX/Configuration/PhysXConfiguration.h @@ -13,7 +13,6 @@ #pragma once #include #include -#include #include #include @@ -55,7 +54,6 @@ namespace PhysX static PhysXSystemConfiguration CreateDefault(); WindConfiguration m_windConfiguration; //!< Wind configuration for PhysX. - AZ::Data::Asset m_defaultMaterialLibrary = AZ::Data::AssetLoadBehavior::NoLoad; //!< Material Library exposed by the system component SystemBus API. bool operator==(const PhysXSystemConfiguration& other) const; bool operator!=(const PhysXSystemConfiguration& other) const; diff --git a/Gems/PhysX/Code/Include/PhysX/MeshColliderComponentBus.h b/Gems/PhysX/Code/Include/PhysX/MeshColliderComponentBus.h index 33305be145..ac36ebbc7f 100644 --- a/Gems/PhysX/Code/Include/PhysX/MeshColliderComponentBus.h +++ b/Gems/PhysX/Code/Include/PhysX/MeshColliderComponentBus.h @@ -38,10 +38,6 @@ namespace PhysX /// @param id The asset ID to set it to. virtual void SetMeshAsset(const AZ::Data::AssetId& id) = 0; - /// Sets the material library asset to the collider. - /// @param id The asset ID to set it to. - virtual void SetMaterialAsset(const AZ::Data::AssetId& id) = 0; - /// Sets the material id from the material library. /// @param id The asset ID to set it to. virtual void SetMaterialId(const Physics::MaterialId& id) = 0; diff --git a/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp b/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp index 3ba520513f..a0db4d5d30 100644 --- a/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp +++ b/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp @@ -36,6 +36,18 @@ namespace PhysX return configuration; } + + bool PhysXSystemConfigurationConverter([[maybe_unused]] AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& dataElement) + { + if (dataElement.GetVersion() <= 1) + { + dataElement.RemoveElementByName(AZ_CRC_CE("DefaultMaterialLibrary")); + AZ_Warning("PhysXSystemConfigurationConverter", false, + "Old version of PhysX Configuration data found. Physics material library will be reset to default."); + } + + return true; + } } AZ_CLASS_ALLOCATOR_IMPL(WindConfiguration, AZ::SystemAllocator, 0); @@ -89,9 +101,8 @@ namespace PhysX if (auto* serializeContext = azdynamic_cast(context)) { serializeContext->Class() - ->Version(1) + ->Version(2, &PhysXInternal::PhysXSystemConfigurationConverter) ->Field("WindConfiguration", &PhysXSystemConfiguration::m_windConfiguration) - ->Field("MaterialLibrary", &PhysXSystemConfiguration::m_defaultMaterialLibrary) ; if (AZ::EditContext* editContext = serializeContext->GetEditContext()) @@ -115,7 +126,6 @@ namespace PhysX bool PhysXSystemConfiguration::operator==(const PhysXSystemConfiguration& other) const { return AzPhysics::SystemConfiguration::operator==(other) && - m_defaultMaterialLibrary == other.m_defaultMaterialLibrary && m_windConfiguration == other.m_windConfiguration ; } diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 87bb702184..4454429092 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include #include @@ -352,10 +352,13 @@ namespace PhysX AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); }); - m_onDefaultMaterialLibraryChangedEventHandler = AzPhysics::SystemEvents::OnDefaultMaterialLibraryChangedEvent::Handler( + m_onMaterialLibraryChangedEventHandler = AzPhysics::SystemEvents::OnMaterialLibraryChangedEvent::Handler( [this](const AZ::Data::AssetId& defaultMaterialLibrary) { - m_configuration.m_materialSelection.OnDefaultMaterialLibraryChanged(defaultMaterialLibrary); + m_configuration.m_materialSelection.OnMaterialLibraryChanged(defaultMaterialLibrary); + + AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, + AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); }); AzToolsFramework::Components::EditorComponentBase::Activate(); @@ -463,13 +466,13 @@ namespace PhysX if (auto* physXSystem = GetPhysXSystem()) { physXSystem->RegisterSystemConfigurationChangedEvent(m_physXConfigChangedHandler); - physXSystem->RegisterOnDefaultMaterialLibraryChangedEventHandler(m_onDefaultMaterialLibraryChangedEventHandler); + physXSystem->RegisterOnMaterialLibraryChangedEventHandler(m_onMaterialLibraryChangedEventHandler); } } void EditorColliderComponent::OnDeselected() { - m_onDefaultMaterialLibraryChangedEventHandler.Disconnect(); + m_onMaterialLibraryChangedEventHandler.Disconnect(); m_physXConfigChangedHandler.Disconnect(); } @@ -681,11 +684,6 @@ namespace PhysX } } - void EditorColliderComponent::SetMaterialAsset(const AZ::Data::AssetId& id) - { - m_configuration.m_materialSelection.SetMaterialLibrary(id); - } - void EditorColliderComponent::SetMaterialId(const Physics::MaterialId& id) { m_configuration.m_materialSelection.SetMaterialId(id); @@ -693,8 +691,10 @@ namespace PhysX void EditorColliderComponent::UpdateMaterialSlotsFromMeshAsset() { - Physics::SystemRequestBus::Broadcast(&Physics::SystemRequests::UpdateMaterialSelection, - m_shapeConfiguration.GetCurrent(), m_configuration); + Physics::PhysicsMaterialRequestBus::Broadcast( + &Physics::PhysicsMaterialRequestBus::Events::UpdateMaterialSelectionFromPhysicsAsset, + m_shapeConfiguration.GetCurrent(), + m_configuration.m_materialSelection); AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast(&AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree); diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.h b/Gems/PhysX/Code/Source/EditorColliderComponent.h index 818de62a04..07e1131ea9 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.h +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.h @@ -158,7 +158,6 @@ namespace PhysX AZ::Data::Asset GetMeshAsset() const override; Physics::MaterialId GetMaterialId() const override; void SetMeshAsset(const AZ::Data::AssetId& id) override; - void SetMaterialAsset(const AZ::Data::AssetId& id) override; void SetMaterialId(const Physics::MaterialId& id) override; void UpdateMaterialSlotsFromMeshAsset(); @@ -251,7 +250,7 @@ namespace PhysX DebugDraw::Collider m_colliderDebugDraw; AzPhysics::SystemEvents::OnConfigurationChangedEvent::Handler m_physXConfigChangedHandler; - AzPhysics::SystemEvents::OnDefaultMaterialLibraryChangedEvent::Handler m_onDefaultMaterialLibraryChangedEventHandler; + AzPhysics::SystemEvents::OnMaterialLibraryChangedEvent::Handler m_onMaterialLibraryChangedEventHandler; AZ::Transform m_cachedWorldTransform; AZ::NonUniformScaleChangedEvent::Handler m_nonUniformScaleChangedHandler; //!< Responds to changes in non-uniform scale. diff --git a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp index 692fbf96f3..0cdba94a34 100644 --- a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp @@ -44,11 +44,14 @@ namespace PhysX AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); }) - , m_onDefaultMaterialLibraryChangedEventHandler( + , m_onMaterialLibraryChangedEventHandler( [this](const AZ::Data::AssetId& defaultMaterialLibrary) { - m_colliderConfig.m_materialSelection.OnDefaultMaterialLibraryChanged(defaultMaterialLibrary); + m_colliderConfig.m_materialSelection.OnMaterialLibraryChanged(defaultMaterialLibrary); Physics::ColliderComponentEventBus::Event(GetEntityId(), &Physics::ColliderComponentEvents::OnColliderChanged); + + AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, + AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); }) , m_nonUniformScaleChangedHandler([this](const AZ::Vector3& scale) {OnNonUniformScaleChanged(scale);}) { @@ -694,16 +697,16 @@ namespace PhysX { physXSystem->RegisterSystemConfigurationChangedEvent(m_physXConfigChangedHandler); } - if (!m_onDefaultMaterialLibraryChangedEventHandler.IsConnected()) + if (!m_onMaterialLibraryChangedEventHandler.IsConnected()) { - physXSystem->RegisterOnDefaultMaterialLibraryChangedEventHandler(m_onDefaultMaterialLibraryChangedEventHandler); + physXSystem->RegisterOnMaterialLibraryChangedEventHandler(m_onMaterialLibraryChangedEventHandler); } } } void EditorShapeColliderComponent::OnDeselected() { - m_onDefaultMaterialLibraryChangedEventHandler.Disconnect(); + m_onMaterialLibraryChangedEventHandler.Disconnect(); m_physXConfigChangedHandler.Disconnect(); } diff --git a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.h b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.h index 7b7fab789a..1ee87c9564 100644 --- a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.h +++ b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.h @@ -155,7 +155,7 @@ namespace PhysX mutable GeometryCache m_geometryCache; //!< Cached data for generating sample points inside the attached shape. AzPhysics::SystemEvents::OnConfigurationChangedEvent::Handler m_physXConfigChangedHandler; - AzPhysics::SystemEvents::OnDefaultMaterialLibraryChangedEvent::Handler m_onDefaultMaterialLibraryChangedEventHandler; + AzPhysics::SystemEvents::OnMaterialLibraryChangedEvent::Handler m_onMaterialLibraryChangedEventHandler; AZ::Transform m_cachedWorldTransform; AZ::NonUniformScaleChangedEvent::Handler m_nonUniformScaleChangedHandler; //!< Responds to changes in non-uniform scale. AZ::Vector3 m_currentNonUniformScale = AZ::Vector3::CreateOne(); //!< Caches the current non-uniform scale. diff --git a/Gems/PhysX/Code/Source/Material.cpp b/Gems/PhysX/Code/Source/Material.cpp index e8e5cab76e..5e8e3bf759 100644 --- a/Gems/PhysX/Code/Source/Material.cpp +++ b/Gems/PhysX/Code/Source/Material.cpp @@ -15,6 +15,8 @@ #include "Material.h" #include #include +#include +#include namespace PhysX { @@ -22,6 +24,9 @@ namespace PhysX : m_pxMaterial(AZStd::move(material.m_pxMaterial)) , m_surfaceType(material.m_surfaceType) , m_surfaceString(AZStd::move(material.m_surfaceString)) + , m_cryEngineSurfaceId(material.m_cryEngineSurfaceId) + , m_density(material.m_density) + , m_debugColor(AZStd::move(material.m_debugColor)) { m_pxMaterial->userData = this; } @@ -31,6 +36,11 @@ namespace PhysX m_pxMaterial = AZStd::move(material.m_pxMaterial); m_surfaceType = material.m_surfaceType; m_surfaceString = AZStd::move(material.m_surfaceString); + m_cryEngineSurfaceId = material.m_cryEngineSurfaceId; + m_density = material.m_density; + m_debugColor = AZStd::move(material.m_debugColor); + + m_pxMaterial->userData = this; return *this; } @@ -93,8 +103,10 @@ namespace PhysX pxMaterial->userData = this; m_pxMaterial = PxMaterialUniquePtr(pxMaterial, materialDestructor); - m_surfaceType = AZ::Crc32(materialConfiguration.m_surfaceType.c_str()); - m_surfaceString = materialConfiguration.m_surfaceType; + + SetSurfaceTypeName(materialConfiguration.m_surfaceType); + + SetDebugColor(materialConfiguration.m_debugColor); Physics::LegacySurfaceTypeRequestsBus::BroadcastResult( m_cryEngineSurfaceId, @@ -115,8 +127,9 @@ namespace PhysX SetDensity(configuration.m_density); - m_surfaceType = AZ::Crc32(configuration.m_surfaceType.c_str()); - m_surfaceString = configuration.m_surfaceType; + SetSurfaceTypeName(configuration.m_surfaceType); + + SetDebugColor(configuration.m_debugColor); Physics::LegacySurfaceTypeRequestsBus::BroadcastResult( m_cryEngineSurfaceId, @@ -134,9 +147,15 @@ namespace PhysX return m_surfaceType; } - void Material::SetSurfaceType(AZ::Crc32 surfaceType) + const AZStd::string& Material::GetSurfaceTypeName() const { - m_surfaceType = surfaceType; + return m_surfaceString; + } + + void Material::SetSurfaceTypeName(const AZStd::string& surfaceTypeName) + { + m_surfaceString = surfaceTypeName; + m_surfaceType = AZ::Crc32(m_surfaceString.c_str()); } float Material::GetDynamicFriction() const @@ -232,6 +251,16 @@ namespace PhysX MaterialConfiguration::MinDensityLimit, MaterialConfiguration::MaxDensityLimit); } + AZ::Color Material::GetDebugColor() const + { + return m_debugColor; + } + + void Material::SetDebugColor(const AZ::Color& debugColor) + { + m_debugColor = debugColor; + } + AZ::u32 Material::GetCryEngineSurfaceId() const { return m_cryEngineSurfaceId; @@ -243,6 +272,16 @@ namespace PhysX } MaterialsManager::MaterialsManager() + : m_physicsConfigChangedHandler( + [this](const AzPhysics::SystemConfiguration* config) + { + OnPhysicsConfigurationChanged(config); + }) + , m_materialLibraryChangedHandler( + [this](const AZ::Data::AssetId& materialLibraryAssetId) + { + OnMaterialLibraryChanged(materialLibraryAssetId); + }) { } @@ -254,133 +293,152 @@ namespace PhysX { Physics::PhysicsMaterialRequestBus::Handler::BusConnect(); MaterialManagerRequestsBus::Handler::BusConnect(); + + if (auto* physicsSystem = AZ::Interface::Get()) + { + physicsSystem->RegisterSystemConfigurationChangedEvent(m_physicsConfigChangedHandler); + physicsSystem->RegisterOnMaterialLibraryChangedEventHandler(m_materialLibraryChangedHandler); + } } void MaterialsManager::Disconnect() { + m_materialLibraryChangedHandler.Disconnect(); + m_physicsConfigChangedHandler.Disconnect(); MaterialManagerRequestsBus::Handler::BusDisconnect(); Physics::PhysicsMaterialRequestBus::Handler::BusDisconnect(); } void MaterialsManager::GetMaterials(const Physics::MaterialSelection& materialSelection - , AZStd::vector>& outMaterials) + , AZStd::vector>& outMaterials) { outMaterials.clear(); - outMaterials.reserve(materialSelection.GetMaterialIdsAssignedToSlots().size()); - // Ensure PxMaterial instances are initialized if possible. - InitializeMaterials(materialSelection); - - for (const auto& id : materialSelection.GetMaterialIdsAssignedToSlots()) + const auto& materialIdsAssignedToSlots = materialSelection.GetMaterialIdsAssignedToSlots(); + if (materialIdsAssignedToSlots.empty()) { - Physics::MaterialFromAssetConfiguration configuration; - if (materialSelection.GetMaterialConfiguration(configuration, id)) + // The material selection doesn't have any slots, return empty list. + return; + } + + // It is important to return exactly the amount of materials specified in materialSelection + // If a number of materials different to what was cooked is assigned on a physx mesh it will lead to undefined + // behavior and subtle bugs. Unfortunately, there's no warning or assertion on physx side at the shape creation time, + // nor mention of this in the documentation + outMaterials.resize(materialIdsAssignedToSlots.size(), GetDefaultMaterial()); + + for (size_t slotIndex = 0; slotIndex < materialIdsAssignedToSlots.size(); ++slotIndex) + { + const auto& materialId = materialIdsAssignedToSlots[slotIndex]; + + if (auto iterator = FindOrCreateMaterial(materialId); + iterator != m_materials.end()) { - auto iterator = m_materialsFromAssets.find(id.GetUuid()); - if (iterator != m_materialsFromAssets.end()) - { - outMaterials.push_back(iterator->second); - } - else - { - outMaterials.push_back(GetDefaultMaterial()); - } - } - else - { - // It is important to return exactly the amount of materials specified in materialSelection - // If a number of materials different to what was cooked is assigned on a physx mesh it will lead to undefined - // behavior and subtle bugs. Unfortunately, there's no warning or assertion on physx side at the shape creation time, - // nor mention of this in the documentation - outMaterials.push_back(GetDefaultMaterial()); + outMaterials[slotIndex] = iterator->second; } } } - AZStd::weak_ptr MaterialsManager::GetMaterialByName(const AZStd::string& name) + AZStd::shared_ptr MaterialsManager::GetMaterialById(Physics::MaterialId id) { - auto it = AZStd::find_if(m_materialsFromAssets.begin(), m_materialsFromAssets.end(), - [&name](const AZStd::pair>& elem) - { - return elem.second.get()->GetSurfaceTypeName() == name; - }); - - if (it != m_materialsFromAssets.end()) + if (auto it = FindOrCreateMaterial(id); + it != m_materials.end()) { return it->second; } - return {}; + return nullptr; } - AZ::u32 MaterialsManager::GetFirstSelectedMaterialIndex(const Physics::MaterialSelection& materialSelection) + AZStd::shared_ptr MaterialsManager::GetMaterialByName(const AZStd::string& name) { - const AZ::u32 defaultMaterialIndex = 0; - - if (!materialSelection.IsMaterialLibraryValid()) + if (auto it = FindOrCreateMaterial(name); + it != m_materials.end()) { - return defaultMaterialIndex; + return it->second; } - - auto materialAsset = AZ::Data::AssetManager::Instance().GetAsset(materialSelection.GetMaterialLibraryAssetId(), AZ::Data::AssetLoadBehavior::Default); - - materialAsset.BlockUntilLoadComplete(); - - AZStd::vector materialList = materialAsset.Get()->GetMaterialsData(); - - const AZStd::vector& selectedMaterials = materialSelection.GetMaterialIdsAssignedToSlots(); - if (selectedMaterials.size() == 0) - { - return defaultMaterialIndex; - } - for (AZ::u32 i=0; i < materialList.size(); ++i) - { - if (materialList[i].m_id == selectedMaterials[0]) - { - return i + 1; // Index 0 is reserved for Default material. - } - } - - return defaultMaterialIndex; + return nullptr; } void MaterialsManager::GetPxMaterials(const Physics::MaterialSelection& materialSelection , AZStd::vector& outMaterials) { - outMaterials.clear(); - if (materialSelection.GetMaterialIdsAssignedToSlots().empty()) + AZStd::vector> materials; + GetMaterials(materialSelection, materials); + + outMaterials.reserve(materials.size()); + for (const auto& material : materials) + { + PhysX::Material* physxMaterial = azrtti_cast(material.get()); + AZ_Assert(physxMaterial, "Invalid physx material"); + + outMaterials.emplace_back(physxMaterial->GetPxMaterial()); + } + } + + void MaterialsManager::UpdateMaterialSelectionFromPhysicsAsset( + const Physics::ShapeConfiguration& shapeConfiguration, + Physics::MaterialSelection& materialSelection) + { + if (shapeConfiguration.GetShapeType() != Physics::ShapeType::PhysicsAsset) { - // if the materialSelection is invalid we still - // return a default material as a fallback behavior - outMaterials.push_back(GetDefaultMaterial()->GetPxMaterial()); return; } - outMaterials.reserve(materialSelection.GetMaterialIdsAssignedToSlots().size()); - // Ensure PxMaterial instances are initialized if possible. - InitializeMaterials(materialSelection); + const Physics::PhysicsAssetShapeConfiguration& assetConfiguration = + static_cast(shapeConfiguration); - for (const auto& id : materialSelection.GetMaterialIdsAssignedToSlots()) + if (!assetConfiguration.m_asset.GetId().IsValid()) { - Physics::MaterialFromAssetConfiguration configuration; - if (materialSelection.GetMaterialConfiguration(configuration, id)) + // Set the default selection if there's no physics asset. + materialSelection.SetMaterialSlots(Physics::MaterialSelection::SlotsArray()); + return; + } + + if (!assetConfiguration.m_asset.IsReady()) + { + // The asset is valid but is still loading, + // Do not set the empty slots in this case to avoid the entity being in invalid state + return; + } + + Pipeline::MeshAsset* meshAsset = assetConfiguration.m_asset.GetAs(); + if (!meshAsset) + { + materialSelection.SetMaterialSlots(Physics::MaterialSelection::SlotsArray()); + AZ_Warning("PhysX", false, "UpdateMaterialSelectionFromPhysicsAsset: MeshAsset is invalid"); + return; + } + + // Set the slots from the mesh asset + materialSelection.SetMaterialSlots(meshAsset->m_assetData.m_surfaceNames); + + if (!assetConfiguration.m_useMaterialsFromAsset) + { + // Not using the materials from the asset. Nothing else to do. + return; + } + + // Update material IDs in the selection for each slot + const AZStd::vector& meshMaterialNames = meshAsset->m_assetData.m_materialNames; + for (size_t slotIndex = 0; slotIndex < meshMaterialNames.size(); ++slotIndex) + { + const AZStd::string& physicsMaterialNameFromPhysicsAsset = meshMaterialNames[slotIndex]; + if (physicsMaterialNameFromPhysicsAsset == DefaultPhysicsMaterialNameFromPhysicsAsset) { - auto iterator = m_materialsFromAssets.find(id.GetUuid()); - if (iterator != m_materialsFromAssets.end()) - { - outMaterials.push_back(iterator->second->GetPxMaterial()); - } - else - { - outMaterials.push_back(GetDefaultMaterial()->GetPxMaterial()); - } + continue; + } + + if (auto it = FindOrCreateMaterial(physicsMaterialNameFromPhysicsAsset); + it != m_materials.end()) + { + materialSelection.SetMaterialId(Physics::MaterialId::FromUUID(it->first), slotIndex); } else { - // It is important to return exactly the amount of materials specified in materialSelection - // If a number of materials different to what was cooked is assigned on a physx mesh it will lead to undefined - // behavior and subtle bugs. Unfortunately, there's no warning or assertion on physx side at the shape creation time, - // nor mention of this in the documentation - outMaterials.push_back(GetDefaultMaterial()->GetPxMaterial()); + AZ_Warning("PhysX", false, + "UpdateMaterialSelectionFromPhysicsAsset: Physics material '%s' not found in the material library. Mesh surface '%s' will use the default material.", + physicsMaterialNameFromPhysicsAsset.c_str(), + meshAsset->m_assetData.m_surfaceNames[slotIndex].c_str()); } } } @@ -390,11 +448,21 @@ namespace PhysX return GetDefaultMaterial(); } - const AZStd::shared_ptr& MaterialsManager::GetDefaultMaterial() + AZStd::shared_ptr MaterialsManager::GetDefaultMaterial() { if (!m_defaultMaterial) { - m_defaultMaterial = AZStd::make_shared(Physics::MaterialConfiguration()); + // Get default material from physics configuration + if (auto* physicsSystem = AZ::Interface::Get()) + { + m_defaultMaterialConfiguration = physicsSystem->GetConfiguration()->m_defaultMaterialConfiguration; + } + else + { + AZ_Warning("MaterialsManager", false, "Unable to get Physics System, default material will not be in sync with PhysX Configuration"); + } + + m_defaultMaterial = AZStd::make_shared(m_defaultMaterialConfiguration); } return m_defaultMaterial; @@ -403,38 +471,138 @@ namespace PhysX void MaterialsManager::ReleaseAllMaterials() { m_defaultMaterial = nullptr; - m_materialsFromAssets.clear(); + m_materials.clear(); Physics::PhysicsMaterialNotificationsBus::Broadcast(&Physics::PhysicsMaterialNotificationsBus::Events::MaterialsReleased); } - void MaterialsManager::InitializeMaterials(const Physics::MaterialSelection& materialSelection) + MaterialsManager::Materials::iterator MaterialsManager::FindOrCreateMaterial(Physics::MaterialId materialId) { - const AZStd::vector& materialIds = materialSelection.GetMaterialIdsAssignedToSlots(); - for (const auto& id : materialIds) + if (materialId.IsNull()) { - Physics::MaterialFromAssetConfiguration configuration; - if (!materialSelection.GetMaterialConfiguration(configuration, id)) - { - continue; // Default material skips code below. - } - - auto materialId = configuration.m_id; + return m_materials.end(); + } + if (auto it = m_materials.find(materialId.GetUuid()); + it != m_materials.end()) + { + return it; + } + else + { + auto* materialLibrary = GetMaterialLibrary(); + if (!materialLibrary) + { + return m_materials.end(); + } + + Physics::MaterialFromAssetConfiguration configuration; + if (!materialLibrary->GetDataForMaterialId(materialId, configuration)) + { + return m_materials.end(); + } + + auto newMaterial = AZStd::make_shared(configuration.m_configuration); + auto insertedPair = m_materials.emplace(materialId.GetUuid(), AZStd::move(newMaterial)); + return insertedPair.first; + } + } + + MaterialsManager::Materials::iterator MaterialsManager::FindOrCreateMaterial(const AZStd::string& materialName) + { + if (materialName.empty()) + { + return m_materials.end(); + } + + auto it = AZStd::find_if(m_materials.begin(), m_materials.end(), [&materialName](const auto& data) + { + return data.second->GetSurfaceTypeName() == materialName; + }); + if (it != m_materials.end()) + { + return it; + } + else + { + auto* materialLibrary = GetMaterialLibrary(); + if (!materialLibrary) + { + return m_materials.end(); + } + + Physics::MaterialFromAssetConfiguration configuration; + if (!materialLibrary->GetDataForMaterialName(materialName, configuration)) + { + return m_materials.end(); + } + + auto newMaterial = AZStd::make_shared(configuration.m_configuration); + auto insertedPair = m_materials.emplace(configuration.m_id.GetUuid(), AZStd::move(newMaterial)); + return insertedPair.first; + } + } + + Physics::MaterialLibraryAsset* MaterialsManager::GetMaterialLibrary() + { + if (auto* physicsSystem = AZ::Interface::Get()) + { + if (const auto* physicsConfiguration = physicsSystem->GetConfiguration()) + { + return physicsConfiguration->m_materialLibraryAsset.Get(); + } + } + return nullptr; + } + + void MaterialsManager::OnPhysicsConfigurationChanged(const AzPhysics::SystemConfiguration* config) + { + if (m_defaultMaterial && + m_defaultMaterialConfiguration != config->m_defaultMaterialConfiguration) + { + m_defaultMaterialConfiguration = config->m_defaultMaterialConfiguration; + + m_defaultMaterial->UpdateWithConfiguration(m_defaultMaterialConfiguration); + } + } + + void MaterialsManager::OnMaterialLibraryChanged([[maybe_unused]] const AZ::Data::AssetId& materialLibraryAssetId) + { + auto* materialLibrary = GetMaterialLibrary(); + if (!materialLibrary) + { + AZ_Warning("PhysX", false, "MaterialsManager: invalid material library"); + return; + } + + AZStd::vector materialsToRemove; + + for (auto& idMaterialPair : m_materials) + { + const Physics::MaterialId materialId = Physics::MaterialId::FromUUID(idMaterialPair.first); + + // Remove null materials if (materialId.IsNull()) { - materialId = Physics::MaterialId::Create(); + materialsToRemove.push_back(materialId.GetUuid()); + continue; } - auto iterator = m_materialsFromAssets.find(materialId.GetUuid()); - if (iterator != m_materialsFromAssets.end()) + Physics::MaterialFromAssetConfiguration configuration; + if (materialLibrary->GetDataForMaterialId(materialId, configuration)) { - iterator->second->UpdateWithConfiguration(configuration.m_configuration); + // Update materials found in the library. + idMaterialPair.second->UpdateWithConfiguration(configuration.m_configuration); } else { - auto newMaterial = AZStd::make_shared(configuration.m_configuration); - m_materialsFromAssets.emplace(materialId.GetUuid(), newMaterial); + // Add for removal the materials not present in the library anymore. + materialsToRemove.push_back(materialId.GetUuid()); } } + + for (const auto& id : materialsToRemove) + { + m_materials.erase(id); + } } } diff --git a/Gems/PhysX/Code/Source/Material.h b/Gems/PhysX/Code/Source/Material.h index a44c9766fc..1541d156d8 100644 --- a/Gems/PhysX/Code/Source/Material.h +++ b/Gems/PhysX/Code/Source/Material.h @@ -15,11 +15,18 @@ #include #include #include -#include +#include +#include #include namespace PhysX { + /// Name used by physx asset exporter to indicate that the default + /// physics material should be used for a mesh surface. The exporter + /// will use it as the fallback option when it's not possible to obtain + /// the surface information from the mesh material. + static const char* const DefaultPhysicsMaterialNameFromPhysicsAsset = ""; + /// PhysX implementation of Physics::Material interface /// =================================================== /// @@ -58,9 +65,9 @@ namespace PhysX // Physics::Material AZ::Crc32 GetSurfaceType() const override; - void SetSurfaceType(AZ::Crc32 surfaceType) override; - const AZStd::string& GetSurfaceTypeName() const override { return m_surfaceString; } + const AZStd::string& GetSurfaceTypeName() const override; + void SetSurfaceTypeName(const AZStd::string& surfaceTypeName) override; float GetDynamicFriction() const override; void SetDynamicFriction(float dynamicFriction) override; @@ -80,6 +87,9 @@ namespace PhysX float GetDensity() const override; void SetDensity(float density) override; + AZ::Color GetDebugColor() const override; + void SetDebugColor(const AZ::Color& debugColor) override; + AZ::u32 GetCryEngineSurfaceId() const override; void* GetNativePointer() override; @@ -92,6 +102,7 @@ namespace PhysX AZ::u32 m_cryEngineSurfaceId = -1; AZStd::string m_surfaceString; float m_density = 1000.0f; + AZ::Color m_debugColor = AZ::Colors::White; }; /// Bus with requests to MaterialsManager @@ -108,9 +119,17 @@ namespace PhysX static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + /// Returns weak pointers to physx::PxMaterial. + /// Equivalent to PhysicsMaterialRequests::GetMaterials but it returns physx::PxMaterial pointers instead. + /// @param materialSelection MaterialSelection instance to create or get materials for + /// @param outMaterials vector of pointers to physx::PxMaterial to fill with. The vector will be cleared inside the function. virtual void GetPxMaterials(const Physics::MaterialSelection& materialSelection, AZStd::vector& outMaterials) = 0; - virtual const AZStd::shared_ptr& GetDefaultMaterial() = 0; + /// Returns default material + /// @return default PhysX::Material instance + virtual AZStd::shared_ptr GetDefaultMaterial() = 0; + + /// Releases ownership of all materials created before. virtual void ReleaseAllMaterials() = 0; }; using MaterialManagerRequestsBus = AZ::EBus; @@ -120,6 +139,9 @@ namespace PhysX /// /// Material managers creates PhysX::Material instances from MaterialLibraryAsset and assumes their ownership. /// Also keeps a reference to the default material. + /// + /// Note: Materials will be created on the fly while doing queries and + /// they will be updated when the material library changes. class MaterialsManager : public MaterialManagerRequestsBus::Handler , public Physics::PhysicsMaterialRequestBus::Handler @@ -131,35 +153,19 @@ namespace PhysX MaterialsManager(); ~MaterialsManager() override; - /// Returns a vector of weak pointers to materials selected. - /// To be notified if the pointers are deleted, connect to PhysicsMaterialNotifications::MaterialsReleased(). - /// @param materialSelection MaterialSelection instance to create or get materials for. - /// @param outMaterials Collection of material weak pointers corresponding to the material selection to be returned. + // PhysicsMaterialRequestBus::Handler overrides... void GetMaterials(const Physics::MaterialSelection& materialSelection - , AZStd::vector>& outMaterials) override; - - /// Returns a weak pointer to physics material with the given name. - AZStd::weak_ptr GetMaterialByName(const AZStd::string& name) override; - - /// Returns index of selected material in its material library. 0 is the Default material. - /// @param materialSelection Selection of materials. - AZ::u32 GetFirstSelectedMaterialIndex(const Physics::MaterialSelection& materialSelection) override; - - /// Slightly faster version of GetMaterials that returns physx::PxMaterial pointers instead. \n - /// The rest is equivalent to GetMaterials function. - /// @param materialSelection MaterialSelection instance to create or get materials for - /// @param outMaterials vector of pointers to physx::PxMaterial to fill with. The vector will be cleared inside the function. - void GetPxMaterials(const Physics::MaterialSelection& materialSelection, AZStd::vector& outMaterials) override; - - /// Returns default material - /// @return default PhysX::Material instance - const AZStd::shared_ptr& GetDefaultMaterial() override; - - /// Return default material - /// @return default Physics::Material instance + , AZStd::vector>& outMaterials) override; + AZStd::shared_ptr GetMaterialById(Physics::MaterialId id) override; + AZStd::shared_ptr GetMaterialByName(const AZStd::string& name) override; + void UpdateMaterialSelectionFromPhysicsAsset( + const Physics::ShapeConfiguration& shapeConfiguration, + Physics::MaterialSelection& materialSelection) override; AZStd::shared_ptr GetGenericDefaultMaterial() override; - /// Releases ownership of all materials created before. + // MaterialManagerRequestsBus::Handler overrides... + void GetPxMaterials(const Physics::MaterialSelection& materialSelection, AZStd::vector& outMaterials) override; + AZStd::shared_ptr GetDefaultMaterial() override; void ReleaseAllMaterials() override; /// Connect to any necessary buses @@ -169,9 +175,31 @@ namespace PhysX void Disconnect(); private: - void InitializeMaterials(const Physics::MaterialSelection& materialSelection); + using Materials = AZStd::unordered_map>; - AZStd::unordered_map> m_materialsFromAssets; + /// Search a material by id, if it exists already it returns its iterator, + /// if it doesn't exist it tries to create it and add it to the list. + /// If the material id is null or not part of the material library then the + /// iterator returned is end of material list. + Materials::iterator FindOrCreateMaterial(Physics::MaterialId materialId); + + /// Search a material by name, if it exists already it returns its iterator, + /// if it doesn't exist it tries to create it and add it to the list. + /// If the material id is null or not part of the material library then the + /// iterator returned is end of material list. + Materials::iterator FindOrCreateMaterial(const AZStd::string& materialName); + + /// Returns the material library of the project. + Physics::MaterialLibraryAsset* GetMaterialLibrary(); + + void OnPhysicsConfigurationChanged(const AzPhysics::SystemConfiguration* config); + void OnMaterialLibraryChanged(const AZ::Data::AssetId& materialLibraryAssetId); + + Materials m_materials; AZStd::shared_ptr m_defaultMaterial; + Physics::MaterialConfiguration m_defaultMaterialConfiguration; + + AzPhysics::SystemEvents::OnConfigurationChangedEvent::Handler m_physicsConfigChangedHandler; + AzPhysics::SystemEvents::OnMaterialLibraryChangedEvent::Handler m_materialLibraryChangedHandler; }; } diff --git a/Gems/PhysX/Code/Source/MeshColliderComponent.cpp b/Gems/PhysX/Code/Source/MeshColliderComponent.cpp index d383ba97de..1c6fdca640 100644 --- a/Gems/PhysX/Code/Source/MeshColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/MeshColliderComponent.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include @@ -85,11 +85,6 @@ namespace PhysX UpdateMeshAsset(); } - void MeshColliderComponent::SetMaterialAsset(const AZ::Data::AssetId& id) - { - m_colliderConfiguration->m_materialSelection.SetMaterialLibrary(id); - } - void MeshColliderComponent::SetMaterialId(const Physics::MaterialId& id) { m_colliderConfiguration->m_materialSelection.SetMaterialId(id); @@ -111,8 +106,10 @@ namespace PhysX { m_shapeConfiguration->m_asset = asset; - Physics::SystemRequestBus::Broadcast(&Physics::SystemRequests::UpdateMaterialSelection, - *m_shapeConfiguration, *m_colliderConfiguration); + Physics::PhysicsMaterialRequestBus::Broadcast( + &Physics::PhysicsMaterialRequestBus::Events::UpdateMaterialSelectionFromPhysicsAsset, + *m_shapeConfiguration, + m_colliderConfiguration->m_materialSelection); } } @@ -122,8 +119,10 @@ namespace PhysX { m_shapeConfiguration->m_asset = asset; - Physics::SystemRequestBus::Broadcast(&Physics::SystemRequests::UpdateMaterialSelection, - *m_shapeConfiguration, *m_colliderConfiguration); + Physics::PhysicsMaterialRequestBus::Broadcast( + &Physics::PhysicsMaterialRequestBus::Events::UpdateMaterialSelectionFromPhysicsAsset, + *m_shapeConfiguration, + m_colliderConfiguration->m_materialSelection); } } diff --git a/Gems/PhysX/Code/Source/MeshColliderComponent.h b/Gems/PhysX/Code/Source/MeshColliderComponent.h index 4014f7ab5a..9d781fd6eb 100644 --- a/Gems/PhysX/Code/Source/MeshColliderComponent.h +++ b/Gems/PhysX/Code/Source/MeshColliderComponent.h @@ -40,7 +40,6 @@ namespace PhysX AZ::Data::Asset GetMeshAsset() const override; Physics::MaterialId GetMaterialId() const override; void SetMeshAsset(const AZ::Data::AssetId& id) override; - void SetMaterialAsset(const AZ::Data::AssetId& id) override; void SetMaterialId(const Physics::MaterialId& id) override; // BaseColliderComponent diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.cpp index d1502a0c65..87e3304a90 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.cpp @@ -15,9 +15,7 @@ #include #include #include -#include -#include -#include +#include #include #include #include @@ -51,18 +49,32 @@ namespace PhysX static void AppendShapeIndependentProperties(physx::PxControllerDesc& controllerDesc, const Physics::CharacterConfiguration& characterConfig, CharacterControllerCallbackManager* callbackManager) { - AZStd::vector > materials; + AZStd::vector> materials; - Physics::SystemRequestBus::BroadcastResult( - materials, - &Physics::SystemRequests::CreateMaterialsFromLibrary, - characterConfig.m_materialSelection - ); - - if (materials.empty()) + if (characterConfig.m_materialSelection.GetMaterialIdsAssignedToSlots().empty()) { - AZ_Error("PhysX Character Controller", false, "Could not create character controller, material was invalid."); - return; + // If material selection has no slots, falling back to default material. + AZStd::shared_ptr defaultMaterial; + Physics::PhysicsMaterialRequestBus::BroadcastResult(defaultMaterial, + &Physics::PhysicsMaterialRequestBus::Events::GetGenericDefaultMaterial); + if (!defaultMaterial) + { + AZ_Error("PhysX Character Controller", false, "Invalid default material."); + return; + } + materials.push_back(AZStd::move(defaultMaterial)); + } + else + { + Physics::PhysicsMaterialRequestBus::Broadcast( + &Physics::PhysicsMaterialRequestBus::Events::GetMaterials, + characterConfig.m_materialSelection, + materials); + if (materials.empty()) + { + AZ_Error("PhysX Character Controller", false, "Could not create character controller, material list was empty."); + return; + } } physx::PxMaterial* pxMaterial = static_cast(materials.front()->GetNativePointer()); diff --git a/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp b/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp index 56042fbc91..24e532e2d1 100644 --- a/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp +++ b/Gems/PhysX/Code/Source/Pipeline/MeshExporter.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include #include @@ -153,7 +153,7 @@ namespace PhysX AZ::SerializeContext* serializeContext = azrtti_cast(context); if (serializeContext) { - serializeContext->Class()->Version(3); + serializeContext->Class()->Version(4); } } @@ -215,7 +215,7 @@ namespace PhysX if (nameAttribute) { AZStd::string materialName = nameAttribute->value(); - AZStd::string surfaceTypeName = DefaultMaterialName; + AZStd::string surfaceTypeName = DefaultPhysicsMaterialNameFromPhysicsAsset; AZ::rapidxml::xml_attribute* surfaceTypeNode = materialNode->first_attribute("SurfaceType"); if (surfaceTypeNode && surfaceTypeNode->value_size() != 0) @@ -268,7 +268,7 @@ namespace PhysX } else { - materialName = DefaultMaterialName; + materialName = DefaultPhysicsMaterialNameFromPhysicsAsset; } materialNames.emplace_back(AZStd::move(materialName)); diff --git a/Gems/PhysX/Code/Source/System/PhysXSystem.cpp b/Gems/PhysX/Code/Source/System/PhysXSystem.cpp index 8df9e9a86f..92f68ea13b 100644 --- a/Gems/PhysX/Code/Source/System/PhysXSystem.cpp +++ b/Gems/PhysX/Code/Source/System/PhysXSystem.cpp @@ -40,8 +40,8 @@ namespace PhysX } #endif - PhysXSystem::MaterialLibraryAssetHelper::MaterialLibraryAssetHelper(PhysXSystem* physXSystem) - : m_physXSystem(physXSystem) + PhysXSystem::MaterialLibraryAssetHelper::MaterialLibraryAssetHelper(OnMaterialLibraryReloadedCallback callback) + : m_onMaterialLibraryReloadedCallback(callback) { } @@ -62,16 +62,16 @@ namespace PhysX void PhysXSystem::MaterialLibraryAssetHelper::OnAssetReloaded(AZ::Data::Asset asset) { - if (m_physXSystem == nullptr || m_physXSystem->GetDefaultMaterialLibrary() != asset) - { - return; - } - m_physXSystem->UpdateDefaultMaterialLibrary(asset); + m_onMaterialLibraryReloadedCallback(asset); } PhysXSystem::PhysXSystem(PhysXSettingsRegistryManager* registryManager, const physx::PxCookingParams& cookingParams) : m_registryManager(*registryManager) - , m_materialLibraryAssetHelper(this) + , m_materialLibraryAssetHelper( + [this](const AZ::Data::Asset& materialLibrary) + { + UpdateMaterialLibrary(materialLibrary); + }) , m_sceneInterface(this) { // Start PhysX allocator @@ -127,7 +127,7 @@ namespace PhysX m_materialLibraryAssetHelper.Disconnect(); // Clear the asset reference in deactivate. The asset system is shut down before destructors are called // for system components, causing any hanging asset references to become crashes on shutdown in release builds. - m_systemConfig.m_defaultMaterialLibrary.Reset(); + m_systemConfig.m_materialLibraryAsset.Reset(); m_accumulatedTime = 0.0f; m_state = State::Shutdown; @@ -369,8 +369,18 @@ namespace PhysX void PhysXSystem::OnCatalogLoaded([[maybe_unused]]const char* catalogFile) { - //now that assets can be resolved, lets load the default material library. - LoadDefaultMaterialLibrary(); + // now that assets can be resolved, lets load the default material library. + + if (!m_systemConfig.m_materialLibraryAsset.GetId().IsValid()) + { + m_onMaterialLibraryLoadErrorEvent.Signal(AzPhysics::SystemEvents::MaterialLibraryLoadErrorType::InvalidId); + } + + bool success = LoadMaterialLibrary(); + if (!success) + { + m_onMaterialLibraryLoadErrorEvent.Signal(AzPhysics::SystemEvents::MaterialLibraryLoadErrorType::ErrorLoading); + } } void PhysXSystem::UpdateConfiguration(const AzPhysics::SystemConfiguration* newConfig, [[maybe_unused]] bool forceReinitialization /*= false*/) @@ -378,7 +388,7 @@ namespace PhysX if (const auto* physXConfig = azdynamic_cast(newConfig); m_systemConfig != (*physXConfig)) { - const bool newMaterialLibrary = m_systemConfig.m_defaultMaterialLibrary != physXConfig->m_defaultMaterialLibrary; + const bool newMaterialLibrary = m_systemConfig.m_materialLibraryAsset != physXConfig->m_materialLibraryAsset; m_systemConfig = (*physXConfig); m_configChangeEvent.Signal(physXConfig); @@ -386,9 +396,11 @@ namespace PhysX if (newMaterialLibrary) { - LoadDefaultMaterialLibrary(); - m_onDefaultMaterialLibraryChangedEvent.Signal(m_systemConfig.m_defaultMaterialLibrary.GetId()); + LoadMaterialLibrary(); + m_onMaterialLibraryChangedEvent.Signal(m_systemConfig.m_materialLibraryAsset.GetId()); } + // This function is not called from reloading the material library asset, + // which means we don't need to check if the materials inside the library have been modified. } } @@ -445,23 +457,6 @@ namespace PhysX return m_systemConfig; } - void PhysXSystem::UpdateDefaultMaterialLibrary(const AZ::Data::Asset& materialLibrary) - { - if (m_systemConfig.m_defaultMaterialLibrary == materialLibrary) - { - return; - } - m_systemConfig.m_defaultMaterialLibrary = materialLibrary; - - LoadDefaultMaterialLibrary(); - m_onDefaultMaterialLibraryChangedEvent.Signal(materialLibrary.GetId()); - } - - const AZ::Data::Asset& PhysXSystem::GetDefaultMaterialLibrary() const - { - return m_systemConfig.m_defaultMaterialLibrary; - } - void PhysXSystem::UpdateDefaultSceneConfiguration(const AzPhysics::SceneConfiguration& sceneConfiguration) { if (m_defaultSceneConfiguration != sceneConfiguration) @@ -482,9 +477,30 @@ namespace PhysX return m_registryManager; } - bool PhysXSystem::LoadDefaultMaterialLibrary() + void PhysXSystem::UpdateMaterialLibrary(const AZ::Data::Asset& materialLibrary) { - AZ::Data::Asset& materialLibrary = m_systemConfig.m_defaultMaterialLibrary; + if (m_systemConfig.m_materialLibraryAsset == materialLibrary) + { + // Same library asset, check if its data has changed. + if (m_systemConfig.m_materialLibraryAsset->GetMaterialsData() != materialLibrary->GetMaterialsData()) + { + m_systemConfig.m_materialLibraryAsset = materialLibrary; + m_onMaterialLibraryChangedEvent.Signal(materialLibrary.GetId()); + } + } + else + { + // New material library asset + m_systemConfig.m_materialLibraryAsset = materialLibrary; + + LoadMaterialLibrary(); + m_onMaterialLibraryChangedEvent.Signal(materialLibrary.GetId()); + } + } + + bool PhysXSystem::LoadMaterialLibrary() + { + AZ::Data::Asset& materialLibrary = m_systemConfig.m_materialLibraryAsset; const AZ::Data::AssetId& materialLibraryId = materialLibrary.GetId(); if (!materialLibraryId.IsValid()) { @@ -503,7 +519,7 @@ namespace PhysX AZ_Warning("PhysX", (materialLibrary.GetData() != nullptr), "LoadDefaultMaterialLibrary: Default Material Library asset data is invalid."); - return materialLibrary.GetData() != nullptr; + return materialLibrary.GetData() != nullptr && !materialLibrary.IsError(); } //TEMP -- until these are fully moved over here diff --git a/Gems/PhysX/Code/Source/System/PhysXSystem.h b/Gems/PhysX/Code/Source/System/PhysXSystem.h index 04d23ad47d..533685bbd1 100644 --- a/Gems/PhysX/Code/Source/System/PhysXSystem.h +++ b/Gems/PhysX/Code/Source/System/PhysXSystem.h @@ -64,8 +64,6 @@ namespace PhysX AZStd::pair FindAttachedBodyHandleFromEntityId(AZ::EntityId entityId) override; const AzPhysics::SystemConfiguration* GetConfiguration() const override; void UpdateConfiguration(const AzPhysics::SystemConfiguration* newConfig, bool forceReinitialization = false) override; - void UpdateDefaultMaterialLibrary(const AZ::Data::Asset& materialLibrary) override; - const AZ::Data::Asset& GetDefaultMaterialLibrary() const override; void UpdateDefaultSceneConfiguration(const AzPhysics::SceneConfiguration& sceneConfiguration) override; const AzPhysics::SceneConfiguration& GetDefaultSceneConfiguration() const override; @@ -75,6 +73,8 @@ namespace PhysX //! Accessor to get the Settings Registry Manager. const PhysXSettingsRegistryManager& GetSettingsRegistryManager() const; + void UpdateMaterialLibrary(const AZ::Data::Asset& materialLibrary); + //TEMP -- until these are fully moved over here physx::PxPhysics* GetPxPhysics() { return m_physXSdk.m_physics; } physx::PxCooking* GetPxCooking() { return m_physXSdk.m_cooking; } @@ -92,7 +92,7 @@ namespace PhysX //! @param cookingParams The cooking params to use when setting up PhysX cooking interface. void InitializePhysXSdk(const physx::PxCookingParams& cookingParams); void ShutdownPhysXSdk(); - bool LoadDefaultMaterialLibrary(); + bool LoadMaterialLibrary(); // AzFramework::AssetCatalogEventBus::Handler ... void OnCatalogLoaded(const char* catalogFile) override; @@ -133,7 +133,9 @@ namespace PhysX : private AZ::Data::AssetBus::Handler { public: - MaterialLibraryAssetHelper(PhysXSystem* physXSystem); + using OnMaterialLibraryReloadedCallback = AZStd::function& materialLibrary)>; + + MaterialLibraryAssetHelper(OnMaterialLibraryReloadedCallback callback); void Connect(const AZ::Data::AssetId& materialLibraryId); void Disconnect(); @@ -142,7 +144,7 @@ namespace PhysX // AZ::Data::AssetBus::Handler void OnAssetReloaded(AZ::Data::Asset asset) override; - PhysXSystem* m_physXSystem; + OnMaterialLibraryReloadedCallback m_onMaterialLibraryReloadedCallback; }; MaterialLibraryAssetHelper m_materialLibraryAssetHelper; }; diff --git a/Gems/PhysX/Code/Source/SystemComponent.cpp b/Gems/PhysX/Code/Source/SystemComponent.cpp index 9ef4dc5099..b4c17f672d 100644 --- a/Gems/PhysX/Code/Source/SystemComponent.cpp +++ b/Gems/PhysX/Code/Source/SystemComponent.cpp @@ -347,27 +347,6 @@ namespace PhysX return AZStd::make_shared(materialConfiguration); } - AZStd::vector> SystemComponent::CreateMaterialsFromLibrary(const Physics::MaterialSelection& materialSelection) - { - AZStd::vector pxMaterials; - m_materialManager.GetPxMaterials(materialSelection, pxMaterials); - - AZStd::vector> genericMaterials; - genericMaterials.reserve(pxMaterials.size()); - - for (physx::PxMaterial* pxMaterial : pxMaterials) - { - genericMaterials.push_back(static_cast(pxMaterial->userData)->shared_from_this()); - } - - return genericMaterials; - } - - AZStd::shared_ptr SystemComponent::GetDefaultMaterial() - { - return m_materialManager.GetDefaultMaterial(); - } - AZStd::vector SystemComponent::GetSupportedJointTypes() { return JointUtils::GetSupportedJointTypes(); @@ -484,58 +463,6 @@ namespace PhysX return m_physXSystem->GetPxCooking(); } - bool SystemComponent::UpdateMaterialSelection(const Physics::ShapeConfiguration& shapeConfiguration, - Physics::ColliderConfiguration& colliderConfiguration) - { - Physics::MaterialSelection& materialSelection = colliderConfiguration.m_materialSelection; - - // If the material library is still not set, we can't update the material selection - if (!materialSelection.IsMaterialLibraryValid()) - { - AZ_Warning("PhysX", false, - "UpdateMaterialSelection: Material Selection tried to use an invalid/non-existing Physics material library: \"%s\". " - "Please make sure the file exists or re-assign another library", materialSelection.GetMaterialLibraryAssetHint().c_str()); - return false; - } - - // If there's no material library data loaded, try to load it - if (materialSelection.GetMaterialLibraryAssetData() == nullptr) - { - AZ::Data::AssetId materialLibraryAssetId = materialSelection.GetMaterialLibraryAssetId(); - materialSelection.SetMaterialLibrary(materialLibraryAssetId); - } - - // If there's still not material library data, we can't update the material selection - if (materialSelection.GetMaterialLibraryAssetData() == nullptr) - { - AZ::Data::AssetId materialLibraryAssetId = materialSelection.GetMaterialLibraryAssetId(); - - auto materialLibraryAsset = - AZ::Data::AssetManager::Instance().GetAsset(materialLibraryAssetId, AZ::Data::AssetLoadBehavior::Default); - - materialLibraryAsset.BlockUntilLoadComplete(); - - // Log the asset path to help find out the incorrect library reference - AZStd::string assetPath = materialLibraryAsset.GetHint(); - AZ_Warning("PhysX", false, - "UpdateMaterialSelection: Unable to load the material library for a material selection." - " Please check if the asset %s exists in the asset cache.", assetPath.c_str()); - - return false; - } - - if (shapeConfiguration.GetShapeType() == Physics::ShapeType::PhysicsAsset) - { - const Physics::PhysicsAssetShapeConfiguration& assetConfiguration = - static_cast(shapeConfiguration); - - // Use the materials data from the asset to update the collider data - return UpdateMaterialSelectionFromPhysicsAsset(assetConfiguration, colliderConfiguration); - } - - return true; - } - void SystemComponent::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { if (m_physXSystem) @@ -614,65 +541,4 @@ namespace PhysX m_windProvider = AZStd::make_unique(); } - - bool SystemComponent::UpdateMaterialSelectionFromPhysicsAsset( - const Physics::PhysicsAssetShapeConfiguration& assetConfiguration, - Physics::ColliderConfiguration& colliderConfiguration) - { - Physics::MaterialSelection& materialSelection = colliderConfiguration.m_materialSelection; - - if (!assetConfiguration.m_asset.GetId().IsValid()) - { - // Set the default selection if there's no physics asset. - materialSelection.SetMaterialSlots(Physics::MaterialSelection::SlotsArray()); - return false; - } - - if (!assetConfiguration.m_asset.IsReady()) - { - // The asset is valid but is still loading, - // Do not set the empty slots in this case to avoid the entity being in invalid state - return false; - } - - Pipeline::MeshAsset* meshAsset = assetConfiguration.m_asset.GetAs(); - if (!meshAsset) - { - materialSelection.SetMaterialSlots(Physics::MaterialSelection::SlotsArray()); - AZ_Warning("PhysX", false, "UpdateMaterialSelectionFromPhysicsAsset: MeshAsset is invalid"); - return false; - } - - // Set the slots from the mesh asset - materialSelection.SetMaterialSlots(meshAsset->m_assetData.m_surfaceNames); - - if (!assetConfiguration.m_useMaterialsFromAsset) - { - return false; - } - - const Physics::MaterialLibraryAsset* materialLibrary = materialSelection.GetMaterialLibraryAssetData(); - const AZStd::vector& meshMaterialNames = meshAsset->m_assetData.m_materialNames; - - // Update material IDs in the selection for each slot - int slotIndex = 0; - for (const AZStd::string& meshMaterialName : meshMaterialNames) - { - Physics::MaterialFromAssetConfiguration materialData; - bool found = materialLibrary->GetDataForMaterialName(meshMaterialName, materialData); - - AZ_Warning("PhysX", found, - "UpdateMaterialSelectionFromPhysicsAsset: No material found for surfaceType (%s) in the collider material library", - meshMaterialName.c_str()); - - if (found) - { - materialSelection.SetMaterialId(materialData.m_id, slotIndex); - } - - slotIndex++; - } - - return true; - } } // namespace PhysX diff --git a/Gems/PhysX/Code/Source/SystemComponent.h b/Gems/PhysX/Code/Source/SystemComponent.h index 8871adfeeb..4609fde0ce 100644 --- a/Gems/PhysX/Code/Source/SystemComponent.h +++ b/Gems/PhysX/Code/Source/SystemComponent.h @@ -114,8 +114,6 @@ namespace PhysX // Physics::SystemRequestBus::Handler AZStd::shared_ptr CreateShape(const Physics::ColliderConfiguration& colliderConfiguration, const Physics::ShapeConfiguration& configuration) override; AZStd::shared_ptr CreateMaterial(const Physics::MaterialConfiguration& materialConfiguration) override; - AZStd::shared_ptr GetDefaultMaterial() override; - AZStd::vector> CreateMaterialsFromLibrary(const Physics::MaterialSelection& materialSelection) override; AZStd::vector GetSupportedJointTypes() override; AZStd::shared_ptr CreateJointLimitConfiguration(AZ::TypeId jointType) override; @@ -147,8 +145,6 @@ namespace PhysX static bool VersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement); - bool UpdateMaterialSelection(const Physics::ShapeConfiguration& shapeConfiguration, - Physics::ColliderConfiguration& colliderConfiguration) override; private: // AZ::TickBus::Handler ... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; @@ -157,9 +153,6 @@ namespace PhysX void EnableAutoManagedPhysicsTick(bool shouldTick); void ActivatePhysXSystem(); - bool UpdateMaterialSelectionFromPhysicsAsset( - const Physics::PhysicsAssetShapeConfiguration& assetConfiguration, - Physics::ColliderConfiguration& colliderConfiguration); bool m_enabled; ///< If false, this component will not activate itself in the Activate() function. diff --git a/Gems/PhysX/Code/Source/Utils.cpp b/Gems/PhysX/Code/Source/Utils.cpp index 55be7c92f7..70091ba970 100644 --- a/Gems/PhysX/Code/Source/Utils.cpp +++ b/Gems/PhysX/Code/Source/Utils.cpp @@ -607,48 +607,6 @@ namespace PhysX return true; } - void GetMaterialList( - AZStd::vector& pxMaterials, const AZStd::vector& terrainSurfaceIdIndexMapping, - const Physics::TerrainMaterialSurfaceIdMap& terrainMaterialsToSurfaceIds) - { - pxMaterials.reserve(terrainSurfaceIdIndexMapping.size()); - - AZStd::shared_ptr defaultMaterial; - MaterialManagerRequestsBus::BroadcastResult(defaultMaterial, &MaterialManagerRequestsBus::Events::GetDefaultMaterial); - - if (terrainSurfaceIdIndexMapping.empty()) - { - pxMaterials.push_back(defaultMaterial->GetPxMaterial()); - return; - } - - AZStd::vector materials; - - for (auto& surfaceId : terrainSurfaceIdIndexMapping) - { - const auto& userAssignedMaterials = terrainMaterialsToSurfaceIds; - const auto& matSelectionIterator = userAssignedMaterials.find(surfaceId); - if (matSelectionIterator != userAssignedMaterials.end()) - { - MaterialManagerRequestsBus::Broadcast(&MaterialManagerRequests::GetPxMaterials, matSelectionIterator->second, materials); - - if (!materials.empty()) - { - pxMaterials.push_back(materials.front()); - } - else - { - AZ_Error("PhysX", false, "Creating materials: array with materials can't be empty"); - pxMaterials.push_back(defaultMaterial->GetPxMaterial()); - } - } - else - { - pxMaterials.push_back(defaultMaterial->GetPxMaterial()); - } - } - } - AZStd::string ReplaceAll(AZStd::string str, const AZStd::string& fromString, const AZStd::string& toString) { size_t positionBegin = 0; while ((positionBegin = str.find(fromString, positionBegin)) != AZStd::string::npos) diff --git a/Gems/PhysX/Code/Source/Utils.h b/Gems/PhysX/Code/Source/Utils.h index 2885e86a09..73ce813b77 100644 --- a/Gems/PhysX/Code/Source/Utils.h +++ b/Gems/PhysX/Code/Source/Utils.h @@ -115,9 +115,6 @@ namespace PhysX bool MeshDataToPxGeometry(physx::PxBase* meshData, physx::PxGeometryHolder &pxGeometry, const AZ::Vector3& scale); - void GetMaterialList( - AZStd::vector& pxMaterials, const AZStd::vector& materialIndexMapping, - const Physics::TerrainMaterialSurfaceIdMap& terrainMaterialsToSurfaceIds); //! Returns all connected busIds of the specified type. template AZStd::vector FindConnectedBusIds() diff --git a/Gems/PhysX/Code/Tests/PhysXMaterialLibraryTest.cpp b/Gems/PhysX/Code/Tests/PhysXMaterialLibraryTest.cpp deleted file mode 100644 index 2e09ec8dca..0000000000 --- a/Gems/PhysX/Code/Tests/PhysXMaterialLibraryTest.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace PhysX -{ - class MaterialLibraryTest_MockCatalog - : public AZ::Data::AssetCatalog - , public AZ::Data::AssetCatalogRequestBus::Handler - { - - private: - AZ::Uuid m_randomUuid = AZ::Uuid::CreateRandom(); - AZStd::vector m_mockAssetIds; - - public: - AZ_CLASS_ALLOCATOR(MaterialLibraryTest_MockCatalog, AZ::SystemAllocator, 0); - - MaterialLibraryTest_MockCatalog() - { - AZ::Data::AssetCatalogRequestBus::Handler::BusConnect(); - } - - ~MaterialLibraryTest_MockCatalog() - { - AZ::Data::AssetCatalogRequestBus::Handler::BusDisconnect(); - } - - AZ::Data::AssetId GenerateMockAssetId() - { - AZ::Data::AssetId assetId = AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 0); - m_mockAssetIds.push_back(assetId); - return assetId; - } - - ////////////////////////////////////////////////////////////////////////// - // AssetCatalogRequestBus - AZ::Data::AssetInfo GetAssetInfoById(const AZ::Data::AssetId& id) override - { - AZ::Data::AssetInfo result; - result.m_assetType = AZ::AzTypeInfo::Uuid(); - auto foundId = AZStd::find(m_mockAssetIds.begin(), m_mockAssetIds.end(), id); - if (foundId != m_mockAssetIds.end()) - { - result.m_assetId = *foundId; - } - - return result; - } - ////////////////////////////////////////////////////////////////////////// - - AZ::Data::AssetStreamInfo GetStreamInfoForLoad(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override - { - EXPECT_TRUE(type == AZ::AzTypeInfo::Uuid()); - AZ::Data::AssetStreamInfo info; - info.m_dataOffset = 0; - info.m_streamFlags = AZ::IO::OpenMode::ModeRead; - - for (int i = 0; i < m_mockAssetIds.size(); ++i) - { - if (m_mockAssetIds[i] == id) - { - info.m_streamName = AZStd::string::format("MaterialLibraryAssetName%d", i); - } - } - - if (!info.m_streamName.empty()) - { - // this ensures tha parallel running unit tests do not overlap their files that they use. - AZStd::string fullName = AZStd::string::format("%s-%s", m_randomUuid.ToString().c_str(), info.m_streamName.c_str()); - info.m_streamName = fullName; - info.m_dataLen = static_cast(AZ::IO::SystemFile::Length(info.m_streamName.c_str())); - } - else - { - info.m_dataLen = 0; - } - - return info; - } - - AZ::Data::AssetStreamInfo GetStreamInfoForSave(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override - { - AZ::Data::AssetStreamInfo info; - info = GetStreamInfoForLoad(id, type); - info.m_streamFlags = AZ::IO::OpenMode::ModeWrite; - return info; - } - - bool SaveAsset(AZ::Data::Asset& asset) - { - volatile bool isDone = false; - volatile bool succeeded = false; - AZ::Data::AssetBusCallbacks callbacks; - callbacks.SetCallbacks(nullptr, nullptr, nullptr, - [&isDone, &succeeded](const AZ::Data::Asset& /*asset*/, bool isSuccessful, AZ::Data::AssetBusCallbacks& /*callbacks*/) - { - isDone = true; - succeeded = isSuccessful; - }, nullptr, nullptr, nullptr); - - callbacks.BusConnect(asset.GetId()); - asset.Save(); - - while (!isDone) - { - AZ::Data::AssetManager::Instance().DispatchEvents(); - } - return succeeded; - } - }; - - class DISABLED_PhysXMaterialLibraryTest - : public ::testing::Test - { - protected: - void SetUp() override - { - m_catalog = AZStd::make_unique(); - AZ::Data::AssetManager::Instance().RegisterCatalog(m_catalog.get(), AZ::AzTypeInfo::Uuid()); - } - - void TearDown() override - { - AZ::Data::AssetManager::Instance().UnregisterCatalog(m_catalog.get()); - } - - AZStd::unique_ptr m_catalog; - }; - - TEST_F(DISABLED_PhysXMaterialLibraryTest, DISABLED_DefaultMaterialLibrary_CorrectMaterialLibraryIsInferred) - { - AZ::Data::Asset materialLibrary = AZ::Interface::Get()->GetDefaultMaterialLibrary(); - - AZ::Data::AssetId dummyAssetId = AZ::Data::AssetId(AZ::Uuid::CreateName("DummyLibrary.physmaterial")); - AZ::Data::Asset dummyMaterialLibAsset = AZ::Data::AssetManager::Instance().GetAsset(dummyAssetId, AZ::Data::AssetLoadBehavior::Default); - materialLibrary = dummyMaterialLibAsset; - AZ::Interface::Get()->UpdateDefaultMaterialLibrary(materialLibrary); - - // We must have now a default material library setup - ASSERT_TRUE(materialLibrary.GetId().IsValid()); - - AZ::Data::AssetId otherDummyAssetId = AZ::Data::AssetId(AZ::Uuid::CreateName("OtherDummyLibrary.physmaterial")); - AZ::Data::Asset otherDummyMaterialLibAsset = AZ::Data::AssetManager::Instance().GetAsset(otherDummyAssetId, AZ::Data::AssetLoadBehavior::Default); - - // Set selection's material library to a different one than default material library - Physics::MaterialSelection selectionTest; - selectionTest.SetMaterialLibrary(otherDummyAssetId); - - ASSERT_TRUE(selectionTest.GetMaterialLibraryAssetId().IsValid()); - ASSERT_EQ(selectionTest.GetMaterialLibraryAssetId(), selectionTest.GetMaterialLibraryAssetId()); - ASSERT_NE(selectionTest.GetMaterialLibraryAssetId(), materialLibrary.GetId()); - - // By reseting the selection, now it should infer to the default material library set in the global configuration - selectionTest.ResetToDefaultMaterialLibrary(); - - ASSERT_TRUE(selectionTest.GetMaterialLibraryAssetId().IsValid()); - ASSERT_EQ(selectionTest.GetMaterialLibraryAssetId(), materialLibrary.GetId()); - - // Release material library so we exit gracefully - materialLibrary = {}; - AZ::Interface::Get()->UpdateDefaultMaterialLibrary(materialLibrary); - } -} diff --git a/Gems/PhysX/Code/physx_tests_files.cmake b/Gems/PhysX/Code/physx_tests_files.cmake index 406aed64a7..79999c5f74 100644 --- a/Gems/PhysX/Code/physx_tests_files.cmake +++ b/Gems/PhysX/Code/physx_tests_files.cmake @@ -23,7 +23,6 @@ set(FILES Tests/PhysXGenericTest.cpp Tests/PhysXSpecificTest.cpp Tests/PhysXForceRegionTest.cpp - Tests/PhysXMaterialLibraryTest.cpp Tests/PhysXCollisionFilteringTest.cpp Tests/PhysXJointsTest.cpp Tests/PhysXSceneTests.cpp diff --git a/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp b/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp index 4b04434e13..07ccdc5011 100644 --- a/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp +++ b/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp @@ -207,8 +207,8 @@ namespace ScriptCanvasPhysicsTests { public: MOCK_CONST_METHOD0(GetSurfaceType, AZ::Crc32()); - MOCK_METHOD1(SetSurfaceType, void(AZ::Crc32)); MOCK_CONST_METHOD0(GetSurfaceTypeName, const AZStd::string&()); + MOCK_METHOD1(SetSurfaceTypeName, void(const AZStd::string&)); MOCK_CONST_METHOD0(GetDynamicFriction, float()); MOCK_METHOD1(SetDynamicFriction, void(float)); MOCK_CONST_METHOD0(GetStaticFriction, float()); @@ -223,6 +223,8 @@ namespace ScriptCanvasPhysicsTests MOCK_METHOD0(GetNativePointer, void*()); MOCK_CONST_METHOD0(GetDensity, float()); MOCK_METHOD1(SetDensity, void(float)); + MOCK_CONST_METHOD0(GetDebugColor, AZ::Color()); + MOCK_METHOD1(SetDebugColor, void(const AZ::Color&)); }; class ScriptCanvasPhysicsTestEnvironment From 9fb4ce59c4d366e15cf5fddd2b8ae76e386bb711 Mon Sep 17 00:00:00 2001 From: Vincent Liu <5900509+onecent1101@users.noreply.github.com> Date: Fri, 28 May 2021 12:19:17 -0700 Subject: [PATCH 339/811] [LYN-2151] Add argument to override aws profile and config file path (#994) --- .../Code/Include/Private/AWSCoreInternalBus.h | 5 ++++ .../Configuration/AWSCoreConfiguration.h | 1 + .../Configuration/AWSCoreConfiguration.cpp | 15 +++++++++- .../UI/AWSCoreResourceMappingToolAction.cpp | 16 ++++++++--- .../AWSDefaultCredentialHandlerTest.cpp | 4 ++- .../AWSResourceMappingManagerTest.cpp | 1 + .../manager/configuration_manager.py | 9 ++++-- .../resource_mapping_tool.py | 8 +++++- .../manager/test_configuration_manager.py | 28 ++++++++++++++++++- .../tests/unit/manager/test_view_manager.py | 2 +- .../tests/unit/utils/test_aws_utils.py | 7 ++--- .../ResourceMappingTool/utils/aws_utils.py | 13 +++++++-- 12 files changed, 90 insertions(+), 19 deletions(-) diff --git a/Gems/AWSCore/Code/Include/Private/AWSCoreInternalBus.h b/Gems/AWSCore/Code/Include/Private/AWSCoreInternalBus.h index 738d41c796..27487ed481 100644 --- a/Gems/AWSCore/Code/Include/Private/AWSCoreInternalBus.h +++ b/Gems/AWSCore/Code/Include/Private/AWSCoreInternalBus.h @@ -38,6 +38,11 @@ namespace AWSCore //! @return The path of AWS resource mapping config file virtual AZStd::string GetResourceMappingConfigFilePath() const = 0; + //! GetResourceMappingConfigFolderPath + //! Get the path of AWS resource mapping config folder + //! @return The path of AWS resource mapping config folder + virtual AZStd::string GetResourceMappingConfigFolderPath() const = 0; + //! ReloadConfiguration //! Reload AWSCore configuration without restarting application virtual void ReloadConfiguration() = 0; diff --git a/Gems/AWSCore/Code/Include/Private/Configuration/AWSCoreConfiguration.h b/Gems/AWSCore/Code/Include/Private/Configuration/AWSCoreConfiguration.h index bd30af3ce7..92082617b7 100644 --- a/Gems/AWSCore/Code/Include/Private/Configuration/AWSCoreConfiguration.h +++ b/Gems/AWSCore/Code/Include/Private/Configuration/AWSCoreConfiguration.h @@ -53,6 +53,7 @@ namespace AWSCore // AWSCoreInternalRequestBus interface implementation AZStd::string GetResourceMappingConfigFilePath() const override; + AZStd::string GetResourceMappingConfigFolderPath() const override; AZStd::string GetProfileName() const override; void ReloadConfiguration() override; diff --git a/Gems/AWSCore/Code/Source/Configuration/AWSCoreConfiguration.cpp b/Gems/AWSCore/Code/Source/Configuration/AWSCoreConfiguration.cpp index 3c0f48c058..b22749dbaa 100644 --- a/Gems/AWSCore/Code/Source/Configuration/AWSCoreConfiguration.cpp +++ b/Gems/AWSCore/Code/Source/Configuration/AWSCoreConfiguration.cpp @@ -58,6 +58,19 @@ namespace AWSCore return configFilePath; } + AZStd::string AWSCoreConfiguration::GetResourceMappingConfigFolderPath() const + { + if (m_sourceProjectFolder.empty()) + { + AZ_Warning(AWSCoreConfigurationName, false, ProjectSourceFolderNotFoundErrorMessage); + return ""; + } + AZStd::string configFolderPath = AZStd::string::format( + "%s/%s", m_sourceProjectFolder.c_str(), AWSCoreResourceMappingConfigFolderName); + AzFramework::StringFunc::Path::Normalize(configFolderPath); + return configFolderPath; + } + void AWSCoreConfiguration::InitConfig() { InitSourceProjectFolderPath(); @@ -123,7 +136,7 @@ namespace AWSCore auto profileNamePath = AZStd::string::format("%s%s", AZ::SettingsRegistryMergeUtils::OrganizationRootKey, AWSCoreProfileNameKey); m_settingsRegistry.Remove(profileNamePath); - m_profileName.clear(); + m_profileName = AWSCoreDefaultProfileName; auto resourceMappingConfigFileNamePath = AZStd::string::format("%s%s", AZ::SettingsRegistryMergeUtils::OrganizationRootKey, AWSCoreResourceMappingConfigFileNameKey); diff --git a/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreResourceMappingToolAction.cpp b/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreResourceMappingToolAction.cpp index fb46a8a700..18d437a66c 100644 --- a/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreResourceMappingToolAction.cpp +++ b/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreResourceMappingToolAction.cpp @@ -14,6 +14,7 @@ #include #include +#include #include namespace AWSCore @@ -108,17 +109,24 @@ namespace AWSCore { return ""; } + + AZStd::string profileName = "default"; + AWSCoreInternalRequestBus::BroadcastResult(profileName, &AWSCoreInternalRequests::GetProfileName); + + AZStd::string configPath = ""; + AWSCoreInternalRequestBus::BroadcastResult(configPath, &AWSCoreInternalRequests::GetResourceMappingConfigFolderPath); + if (m_isDebug) { return AZStd::string::format( - "%s debug %s --binaries_path %s --debug", - m_enginePythonEntryPath.c_str(), m_toolScriptPath.c_str(), m_toolQtBinDirectoryPath.c_str()); + "%s debug %s --binaries_path %s --debug --profile %s --config_path %s", m_enginePythonEntryPath.c_str(), + m_toolScriptPath.c_str(), m_toolQtBinDirectoryPath.c_str(), profileName.c_str(), configPath.c_str()); } else { return AZStd::string::format( - "%s %s --binaries_path %s", - m_enginePythonEntryPath.c_str(), m_toolScriptPath.c_str(), m_toolQtBinDirectoryPath.c_str()); + "%s %s --binaries_path %s --profile %s --config_path %s", m_enginePythonEntryPath.c_str(), + m_toolScriptPath.c_str(), m_toolQtBinDirectoryPath.c_str(), profileName.c_str(), configPath.c_str()); } } diff --git a/Gems/AWSCore/Code/Tests/Credential/AWSDefaultCredentialHandlerTest.cpp b/Gems/AWSCore/Code/Tests/Credential/AWSDefaultCredentialHandlerTest.cpp index 297e56fc33..7f00adaae7 100644 --- a/Gems/AWSCore/Code/Tests/Credential/AWSDefaultCredentialHandlerTest.cpp +++ b/Gems/AWSCore/Code/Tests/Credential/AWSDefaultCredentialHandlerTest.cpp @@ -34,7 +34,8 @@ public: MOCK_METHOD0(GetAWSCredentials, Aws::Auth::AWSCredentials()); }; -class AWSDefaultCredentialHandlerMock : public AWSDefaultCredentialHandler +class AWSDefaultCredentialHandlerMock + : public AWSDefaultCredentialHandler { public: void SetupMocks( @@ -76,6 +77,7 @@ public: // AWSCoreInternalRequestBus interface implementation AZStd::string GetProfileName() const override { return m_profileName; } AZStd::string GetResourceMappingConfigFilePath() const override { return ""; } + AZStd::string GetResourceMappingConfigFolderPath() const override { return ""; } void ReloadConfiguration() override {} std::shared_ptr m_environmentCredentialsProviderMock; diff --git a/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp b/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp index 3adebc9a24..b46a840d40 100644 --- a/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp +++ b/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp @@ -119,6 +119,7 @@ public: // AWSCoreInternalRequestBus interface implementation AZStd::string GetProfileName() const override { return ""; } AZStd::string GetResourceMappingConfigFilePath() const override { return m_normalizedConfigFilePath; } + AZStd::string GetResourceMappingConfigFolderPath() const override { return m_normalizedConfigFolderPath; } void ReloadConfiguration() override { m_reloadConfigurationCounter++; } AZStd::unique_ptr m_resourceMappingManager; diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/manager/configuration_manager.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/manager/configuration_manager.py index ee305c750a..b679921196 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/manager/configuration_manager.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/manager/configuration_manager.py @@ -48,11 +48,14 @@ class ConfigurationManager(object): def configuration(self, new_configuration: ConfigurationManager) -> None: self._configuration = new_configuration - def setup(self) -> None: + def setup(self, config_path: str) -> None: logger.info("Setting up default configuration ...") - # TODO: remove config directory and files default setup once integrating with user input try: - self._configuration.config_directory = file_utils.get_current_directory_path() + normalized_config_path: str = file_utils.normalize_file_path(config_path); + if normalized_config_path: + self._configuration.config_directory = normalized_config_path + else: + self._configuration.config_directory = file_utils.get_current_directory_path() self._configuration.config_files = \ file_utils.find_files_with_suffix_under_directory(self._configuration.config_directory, constants.RESOURCE_MAPPING_CONFIG_FILE_NAME_SUFFIX) diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py index 0ee7455e6c..e99bf5d441 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py @@ -13,13 +13,16 @@ from argparse import (ArgumentParser, Namespace) import logging import sys +from utils import aws_utils from utils import environment_utils from utils import file_utils # arguments setup argument_parser: ArgumentParser = ArgumentParser() argument_parser.add_argument('--binaries_path', help='Path to QT Binaries necessary for PySide.') +argument_parser.add_argument('--config_path', help='Path to resource mapping config directory.') argument_parser.add_argument('--debug', action='store_true', help='Execute on debug mode to enable DEBUG logging level') +argument_parser.add_argument('--profile', default='default', help='Named AWS profile to use for querying AWS resources') arguments: Namespace = argument_parser.parse_args() # logging setup @@ -70,9 +73,12 @@ if __name__ == "__main__": except FileNotFoundError: logger.warning("Failed to load style sheet for resource mapping tool") + logger.info("Initializing boto3 default session ...") + aws_utils.setup_default_session(arguments.profile) + logger.info("Initializing configuration manager ...") configuration_manager: ConfigurationManager = ConfigurationManager() - configuration_manager.setup() + configuration_manager.setup(arguments.config_path) logger.info("Initializing thread manager ...") thread_manager: ThreadManager = ThreadManager() diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/manager/test_configuration_manager.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/manager/test_configuration_manager.py index a9dcf97af9..552f9fff01 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/manager/test_configuration_manager.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/manager/test_configuration_manager.py @@ -43,7 +43,7 @@ class TestConfigurationManager(TestCase): mock_find_files_with_suffix_under_directory: MagicMock, mock_get_default_account_id: MagicMock, mock_get_default_region: MagicMock) -> None: - TestConfigurationManager._expected_configuration_manager.setup() + TestConfigurationManager._expected_configuration_manager.setup("") mock_get_current_directory_path.assert_called_once() mock_check_path_exists.assert_called_once_with(TestConfigurationManager._expected_directory_path) mock_find_files_with_suffix_under_directory.assert_called_once_with( @@ -58,3 +58,29 @@ class TestConfigurationManager(TestCase): TestConfigurationManager._expected_account_id assert TestConfigurationManager._expected_configuration_manager.configuration.region == \ TestConfigurationManager._expected_region + + @patch("utils.aws_utils.get_default_region", return_value=_expected_region) + @patch("utils.aws_utils.get_default_account_id", return_value=_expected_account_id) + @patch("utils.file_utils.find_files_with_suffix_under_directory", return_value=_expected_config_files) + @patch("utils.file_utils.check_path_exists", return_value=True) + @patch("utils.file_utils.normalize_file_path", return_value=_expected_directory_path) + def test_setup_get_configuration_setup_with_path_as_expected(self, mock_normalize_file_path: MagicMock, + mock_check_path_exists: MagicMock, + mock_find_files_with_suffix_under_directory: MagicMock, + mock_get_default_account_id: MagicMock, + mock_get_default_region: MagicMock) -> None: + TestConfigurationManager._expected_configuration_manager.setup(TestConfigurationManager._expected_directory_path) + mock_normalize_file_path.assert_called_once() + mock_check_path_exists.assert_called_once_with(TestConfigurationManager._expected_directory_path) + mock_find_files_with_suffix_under_directory.assert_called_once_with( + TestConfigurationManager._expected_directory_path, constants.RESOURCE_MAPPING_CONFIG_FILE_NAME_SUFFIX) + mock_get_default_account_id.assert_called_once() + mock_get_default_region.assert_called_once() + assert TestConfigurationManager._expected_configuration_manager.configuration.config_directory == \ + TestConfigurationManager._expected_directory_path + assert TestConfigurationManager._expected_configuration_manager.configuration.config_files == \ + TestConfigurationManager._expected_config_files + assert TestConfigurationManager._expected_configuration_manager.configuration.account_id == \ + TestConfigurationManager._expected_account_id + assert TestConfigurationManager._expected_configuration_manager.configuration.region == \ + TestConfigurationManager._expected_region diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/manager/test_view_manager.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/manager/test_view_manager.py index eb8304182f..e5c84c6579 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/manager/test_view_manager.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/manager/test_view_manager.py @@ -36,7 +36,7 @@ class TestViewManager(TestCase): main_window_patcher: patch = patch("manager.view_manager.QMainWindow") cls._mock_main_window = main_window_patcher.start() - window_icon_patcher: patch = patch("manager.view_manager.QPixmap") + window_icon_patcher: patch = patch("manager.view_manager.QIcon") window_icon_patcher.start() stacked_pages_patcher: patch = patch("manager.view_manager.QStackedWidget") 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 7244431e76..51bd6ade23 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 @@ -37,13 +37,12 @@ class TestAWSUtils(TestCase): .build() def setUp(self) -> None: - client_patcher: patch = patch("boto3.client") - self.addCleanup(client_patcher.stop) - self._mock_client: MagicMock = client_patcher.start() - session_patcher: patch = patch("boto3.session.Session") self.addCleanup(session_patcher.stop) self._mock_session: MagicMock = session_patcher.start() + self._mock_client: MagicMock = self._mock_session.return_value.client + + aws_utils.setup_default_session("default") def test_get_default_account_id_return_expected_account_id(self) -> None: mocked_sts_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 329d3ff44e..b0c3c9c1b3 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/aws_utils.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/aws_utils.py @@ -26,6 +26,8 @@ aws account, region, resources, etc. _PAGINATION_MAX_ITEMS: int = 10 _PAGINATION_PAGE_SIZE: int = 10 +default_session: boto3.session.Session = None + class AWSConstants(object): CLOUDFORMATION_SERVICE_NAME: str = "cloudformation" @@ -53,15 +55,20 @@ def _close_client_connection(client: BaseClient) -> None: def _initialize_boto3_aws_client(service: str, region: str = "") -> BaseClient: if region: - boto3_client: BaseClient = boto3.client(service, region_name=region) + boto3_client: BaseClient = default_session.client(service, region_name=region) else: - boto3_client: BaseClient = boto3.client(service) + boto3_client: BaseClient = default_session.client(service) boto3_client.meta.events.register( f"after-call.{service}.*", lambda **kwargs: _close_client_connection(boto3_client) ) return boto3_client +def setup_default_session(profile: str) -> None: + global default_session + default_session = boto3.session.Session(profile_name=profile) + + def get_default_account_id() -> str: sts_client: BaseClient = _initialize_boto3_aws_client(AWSConstants.STS_SERVICE_NAME) try: @@ -72,7 +79,7 @@ def get_default_account_id() -> str: def get_default_region() -> str: - region: str = boto3.session.Session().region_name + region: str = default_session.region_name if region: return region From e79c65d4549298822b861ea40eecd4d9c10c6df3 Mon Sep 17 00:00:00 2001 From: Terry Michaels Date: Fri, 28 May 2021 14:28:36 -0500 Subject: [PATCH 340/811] Clear dirty flag after doing an initial save or save as in Asset Editor (#1033) --- .../AzToolsFramework/AssetEditor/AssetEditorWidget.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetEditor/AssetEditorWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetEditor/AssetEditorWidget.cpp index 706d8243e2..a59b29ddf8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetEditor/AssetEditorWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetEditor/AssetEditorWidget.cpp @@ -483,6 +483,8 @@ namespace AzToolsFramework } } + m_dirty = false; + AddRecentPath(targetFilePath); SetStatusText(Status::assetCreated); From 00a529ad74d139419ea2e4f331b21509a01dcf85 Mon Sep 17 00:00:00 2001 From: amzn-mike <80125227+amzn-mike@users.noreply.github.com> Date: Fri, 28 May 2021 14:56:52 -0500 Subject: [PATCH 341/811] Fix AssImpTransformImporter logic for bone nodes For bone nodes, the Transform is computed by multiplying the parent offsetMatrix by the inverse of the node's offsetMatrix Note that this currently disables the LimitBoneWeights option since that results in the removal of bone nodes that are not attached to a mesh. Without the bones there is no way to retrieve the offsetMatrix, so the Transform cannot be computed correctly Fixes LYN-3755 --- .../Importers/AssImpTransformImporter.cpp | 59 ++++++++++++++++--- .../SDKWrapper/AssImpSceneWrapper.cpp | 5 +- 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpTransformImporter.cpp b/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpTransformImporter.cpp index 5357c32fa9..bcc007e3a7 100644 --- a/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpTransformImporter.cpp +++ b/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpTransformImporter.cpp @@ -46,22 +46,69 @@ namespace AZ serializeContext->Class()->Version(1); } } - + + void GetAllBones(const aiScene* scene, AZStd::unordered_map& boneLookup) + { + for (unsigned meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex) + { + const aiMesh* mesh = scene->mMeshes[meshIndex]; + + for (unsigned boneIndex = 0; boneIndex < mesh->mNumBones; ++boneIndex) + { + const aiBone* bone = mesh->mBones[boneIndex]; + + boneLookup[bone->mName.C_Str()] = bone; + } + } + } + Events::ProcessingResult AssImpTransformImporter::ImportTransform(AssImpSceneNodeAppendedContext& context) { AZ_TraceContext("Importer", "transform"); const aiNode* currentNode = context.m_sourceNode.GetAssImpNode(); const aiScene* scene = context.m_sourceScene.GetAssImpScene(); - + if (currentNode == scene->mRootNode || IsPivotNode(currentNode->mName)) { return Events::ProcessingResult::Ignored; } - aiMatrix4x4 combinedTransform = GetConcatenatedLocalTransform(currentNode); + AZStd::unordered_map boneLookup; + GetAllBones(scene, boneLookup); + + auto boneIterator = boneLookup.find(currentNode->mName.C_Str()); + const bool isBone = boneIterator != boneLookup.end(); + + aiMatrix4x4 combinedTransform; + + if (isBone) + { + auto parentNode = currentNode->mParent; + + aiMatrix4x4 offsetMatrix = boneIterator->second->mOffsetMatrix; + aiMatrix4x4 parentOffset {}; + + auto parentBoneIterator = boneLookup.find(parentNode->mName.C_Str()); + + if (parentNode && parentBoneIterator != boneLookup.end()) + { + const auto& parentBone = parentBoneIterator->second; + + parentOffset = parentBone->mOffsetMatrix; + } + + auto inverseOffset = offsetMatrix; + inverseOffset.Inverse(); + + combinedTransform = parentOffset * inverseOffset; + } + else + { + combinedTransform = GetConcatenatedLocalTransform(currentNode); + } DataTypes::MatrixType localTransform = AssImpSDKWrapper::AssImpTypeConverter::ToTransform(combinedTransform); - + context.m_sourceSceneSystem.SwapTransformForUpAxis(localTransform); context.m_sourceSceneSystem.ConvertUnit(localTransform); @@ -105,9 +152,7 @@ namespace AZ } else { - bool addedData = context.m_scene.GetGraph().SetContent( - context.m_currentGraphPosition, - transformData); + bool addedData = context.m_scene.GetGraph().SetContent(context.m_currentGraphPosition, transformData); AZ_Error(SceneAPI::Utilities::ErrorWindow, addedData, "Failed to add node data"); return addedData ? Events::ProcessingResult::Success : Events::ProcessingResult::Failure; diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp index 791af4bf68..9186a2fb7a 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp @@ -69,13 +69,14 @@ namespace AZ // aiProcess_JoinIdenticalVertices is not enabled because O3DE has a mesh optimizer that also does this, // this flag is disabled to keep AssImp output similar to FBX SDK to reduce downstream bugs for the initial AssImp release. // There's currently a minimum of properties and flags set to maximize compatibility with the existing node graph. + + // aiProcess_LimitBoneWeights is not enabled because it will remove bones which are not associated with a mesh. + // This results in the loss of the offset matrix data for nodes without a mesh which is required for the Transform Importer. m_importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false); m_importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_OPTIMIZE_EMPTY_ANIMATION_CURVES, false); m_sceneFileName = fileName; m_assImpScene = m_importer.ReadFile(fileName, aiProcess_Triangulate //Triangulates all faces of all meshes - | aiProcess_LimitBoneWeights //Limits the number of bones that can affect a vertex to a maximum value - //dropping the least important and re-normalizing | aiProcess_GenNormals); //Generate normals for meshes #if AZ_TRAIT_COMPILER_SUPPORT_CSIGNAL From 50c6c9b1c62131f1075b8b06d86bef82699eba10 Mon Sep 17 00:00:00 2001 From: clujames Date: Fri, 28 May 2021 13:23:28 -0700 Subject: [PATCH 342/811] Added an optional variable to the cdk deploy function to allow additional flags and arguments. --- AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py index 455b3f94cb..a45ce3f49e 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py @@ -82,16 +82,19 @@ class Cdk: env=self._cdk_env, shell=True) - def deploy(self, context_variable: str = '') -> List[str]: + def deploy(self, context_variable: str = '', additonal_params: List[str] = None) -> List[str]: """ Deploys all the CDK stacks. :param context_variable: Context variable for enabling optional features. + :param additonal_params: Additonal parameters like --all can be passed in this way. :return List of deployed stack arns. """ if not self._cdk_path: return [] deploy_cdk_application_cmd = ['cdk', 'deploy', '--require-approval', 'never'] + if additonal_params: + deploy_cdk_application_cmd += additonal_params if context_variable: deploy_cdk_application_cmd.extend(['-c', f'{context_variable}']) From de4e6957e8606fb3ca7fa49cc0fefaf81f8af357 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Fri, 28 May 2021 13:38:56 -0700 Subject: [PATCH 343/811] Made a bunch of display name and description updates to core material types. - Renamed "Details" group to "Overview". - Renamed "UV Names" group to "UV Sets". - Renamed "General" group to "General Settings". - Renamed "Parallax" group to "Displacement". - Renamed "Texture Map" properties to just "Texture". In cases where a specific type of texture is mentioned like "roughness texture map" I called this "roughness map" (which is more common according to google). - Renamed "Heightmap" to "Height map" (which is more common according to google). ATOM-14002 [Material Editor] Revisit user facing organization and layout of material types --- .../Materials/Types/EnhancedPBR.materialtype | 128 ++++----- .../Assets/Materials/Types/Skin.materialtype | 72 ++--- .../Types/StandardMultilayerPBR.materialtype | 256 +++++++++--------- .../Materials/Types/StandardPBR.materialtype | 114 ++++---- .../RPI.Edit/Material/MaterialSourceData.h | 2 +- .../Document/MaterialDocumentRequestBus.h | 2 +- .../Code/Source/Document/MaterialDocument.cpp | 10 +- .../MaterialInspector/MaterialInspector.cpp | 16 +- .../MaterialInspector/MaterialInspector.h | 2 +- .../EditorMaterialComponentInspector.cpp | 2 +- 10 files changed, 302 insertions(+), 302 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index 3696188514..3b5a653f43 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -60,8 +60,8 @@ }, { "id": "parallax", - "displayName": "Parallax Mapping", - "description": "Properties for parallax effect produced by depthmap." + "displayName": "Displacement", + "description": "Properties for parallax effect produced by a height map." }, { "id": "subsurfaceScattering", @@ -86,7 +86,7 @@ }, { "id": "general", - "displayName": "General", + "displayName": "General Settings", "description": "General settings." } ], @@ -197,7 +197,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "Base color texture map", "type": "Image", "connection": { @@ -208,14 +208,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Base color texture map UV set", + "description": "Base color map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -227,7 +227,7 @@ { "id": "textureBlendMode", "displayName": "Texture Blend Mode", - "description": "Selects the equation to use when combining Color, Factor, and Texture Map.", + "description": "Selects the equation to use when combining Color, Factor, and Texture.", "type": "Enum", "enumValues": [ "Multiply", "LinearLight", "Lerp", "Overlay" ], "defaultValue": "Multiply", @@ -253,7 +253,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "", "type": "Image", "connection": { @@ -264,14 +264,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Metallic texture map UV set", + "description": "Metallic map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -284,8 +284,8 @@ "roughness": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface roughness.", + "displayName": "Texture", + "description": "Texture for defining surface roughness.", "type": "Image", "connection": { "type": "ShaderInput", @@ -295,14 +295,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -315,7 +315,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "lowerBound", "displayName": "Lower Bound", - "description": "The roughness value that corresponds to black in the texture map.", + "description": "The roughness value that corresponds to black in the texture.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -329,7 +329,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "upperBound", "displayName": "Upper Bound", - "description": "The roughness value that corresponds to white in the texture map.", + "description": "The roughness value that corresponds to white in the texture.", "type": "Float", "defaultValue": 1.0, "min": 0.0, @@ -409,8 +409,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface reflectance.", + "displayName": "Texture", + "description": "Texture for defining surface reflectance.", "type": "Image", "connection": { "type": "ShaderInput", @@ -420,14 +420,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Specular reflection texture map UV set", + "description": "Specular reflection map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -472,7 +472,7 @@ { "id": "influenceMap", "displayName": " Influence Map", - "description": "Strength factor texture map", + "description": "Strength factor texture", "type": "Image", "connection": { "type": "ShaderInput", @@ -482,14 +482,14 @@ { "id": "useInfluenceMap", "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "influenceMapUv", "displayName": " UV", - "description": "Strength factor texture map UV set", + "description": "Strength factor map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -514,7 +514,7 @@ { "id": "roughnessMap", "displayName": " Roughness Map", - "description": "Roughness texture map", + "description": "Texture for defining surface roughness", "type": "Image", "connection": { "type": "ShaderInput", @@ -524,14 +524,14 @@ { "id": "useRoughnessMap", "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the roughness value.", + "description": "Whether to use the texture, or just default to the roughness value.", "type": "Bool", "defaultValue": true }, { "id": "roughnessMapUv", "displayName": " UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -573,7 +573,7 @@ { "id": "normalMapUv", "displayName": " UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -586,8 +586,8 @@ "normal": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface normal direction.", + "displayName": "Texture", + "description": "Texture for defining surface normal direction.", "type": "Image", "connection": { "type": "ShaderInput", @@ -597,14 +597,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just rely on vertex normals.", + "description": "Whether to use the texture, or just rely on vertex normals.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -653,7 +653,7 @@ { "id": "mode", "displayName": "Opacity Mode", - "description": "Opacity mode for this texture.", + "description": "Indicates the general approach how transparency is to be applied.", "type": "Enum", "enumValues": [ "Opaque", "Cutout", "Blended", "TintedTransparent" ], "defaultValue": "Opaque", @@ -665,7 +665,7 @@ { "id": "alphaSource", "displayName": "Alpha Source", - "description": "Source texture of alpha value.", + "description": "Indicates whether to get the opacity texture from the Base Color map (Packed) or from a separate greyscale texture (Split).", "type": "Enum", "enumValues": [ "Packed", "Split", "None" ], "defaultValue": "Packed", @@ -676,8 +676,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface opacity.", + "displayName": "Texture", + "description": "Texture for defining surface opacity.", "type": "Image", "connection": { "type": "ShaderInput", @@ -687,7 +687,7 @@ { "id": "textureMapUv", "displayName": "UV", - "description": "Opacity texture map UV set", + "description": "Opacity map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -782,7 +782,7 @@ { "id": "diffuseTextureMap", "displayName": "Diffuse AO", - "description": "Texture map for defining occlusion area for diffuse ambient lighting.", + "description": "Texture for defining occlusion area for diffuse ambient lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -792,14 +792,14 @@ { "id": "diffuseUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Diffuse AO texture map.", + "description": "Whether to use the Diffuse AO map.", "type": "Bool", "defaultValue": true }, { "id": "diffuseTextureMapUv", "displayName": " UV", - "description": "Diffuse AO texture map UV set.", + "description": "Diffuse AO map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -824,7 +824,7 @@ { "id": "specularTextureMap", "displayName": "Specular Cavity", - "description": "Texture map for defining occlusion area for specular lighting.", + "description": "Texture for defining occlusion area for specular lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -834,14 +834,14 @@ { "id": "specularUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Specular Cavity texture map.", + "description": "Whether to use the Specular Cavity map.", "type": "Bool", "defaultValue": true }, { "id": "specularTextureMapUv", "displayName": " UV", - "description": "Specular Cavity texture map UV set.", + "description": "Specular Cavity map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -904,8 +904,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining emissive area.", + "displayName": "Texture", + "description": "Texture for defining emissive area.", "type": "Image", "connection": { "type": "ShaderInput", @@ -915,14 +915,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Emissive texture map UV set", + "description": "Emissive map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -935,8 +935,8 @@ "parallax": [ { "id": "textureMap", - "displayName": "Heightmap", - "description": "Displacement heightmap to create parallax effect.", + "displayName": "Height Map", + "description": "Displacement height map to create parallax effect.", "type": "Image", "connection": { "type": "ShaderInput", @@ -946,14 +946,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the heightmap.", + "description": "Whether to use the height map.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Heightmap UV set", + "description": "Height map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -964,8 +964,8 @@ }, { "id": "factor", - "displayName": "Heightmap Scale", - "description": "The total height of the heightmap in local model units.", + "displayName": "Height Map Scale", + "description": "The total height of the height map in local model units.", "type": "Float", "defaultValue": 0.05, "min": 0.0, @@ -1026,7 +1026,7 @@ { "id": "showClipping", "displayName": "Show Clipping", - "description": "Highlight areas where the heightmap is clipped by the mesh surface.", + "description": "Highlight areas where the height map is clipped by the mesh surface.", "type": "Bool", "defaultValue": false, "connection": { @@ -1063,7 +1063,7 @@ { "id": "influenceMap", "displayName": " Influence Map", - "description": "Use texture map to control the strength of subsurface scattering", + "description": "Texture for controlling the strength of subsurface scattering", "type": "Image", "connection": { "type": "ShaderInput", @@ -1073,7 +1073,7 @@ { "id": "useInfluenceMap", "displayName": " Use Influence Map", - "description": "Whether to use the texture map as influence mask.", + "description": "Whether to use the influence map.", "type": "Bool", "defaultValue": true }, @@ -1142,7 +1142,7 @@ { "id": "thicknessMap", "displayName": " Thickness Map", - "description": "Use a greyscale texture for per pixel thickness", + "description": "Texture for controlling per pixel thickness", "type": "Image", "connection": { "type": "ShaderInput", @@ -1171,7 +1171,7 @@ { "id": "transmissionTint", "displayName": " Transmission Tint", - "description": "Color of the volume light travelling through", + "description": "Color of the volume light traveling through", "type": "Color", "defaultValue": [ 1.0, 0.8, 0.6 ] }, @@ -1246,7 +1246,7 @@ { "id": "enableDetailMaskTexture", "displayName": " Use Texture", - "description": "Enable detail mask texture", + "description": "Enable detail blend mask", "type": "Bool", "defaultValue": true }, @@ -1265,7 +1265,7 @@ { "id": "textureMapUv", "displayName": "Detail Map UVs", - "description": "Which UV set to use for detail map texture sampling", + "description": "Which UV set to use for detail map sampling", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1283,8 +1283,8 @@ }, { "id": "baseColorDetailMap", - "displayName": " Texture Map", - "description": "Detailed Base Color Texture map", + "displayName": " Texture", + "description": "Detailed Base Color Texture", "type": "Image", "connection": { "type": "ShaderInput", @@ -1307,7 +1307,7 @@ { "id": "enableNormals", "displayName": "Enable Normal", - "description": "Enable detail normal texture to be used for fine detail normal such as scratches and small dents", + "description": "Enable detail normal map to be used for fine detail normal such as scratches and small dents", "type": "Bool", "defaultValue": false }, @@ -1326,8 +1326,8 @@ }, { "id": "normalDetailMap", - "displayName": " Texture Map", - "description": "Detailed Normal Texture map", + "displayName": " Texture", + "description": "Detailed Normal map", "type": "Image", "connection": { "type": "ShaderInput", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype index f8c49d579c..ab36853723 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype @@ -50,7 +50,7 @@ }, { "id": "general", - "displayName": "General", + "displayName": "General Settings", "description": "General settings." } ], @@ -150,7 +150,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "Base color texture map", "type": "Image", "connection": { @@ -161,14 +161,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Base color texture map UV set", + "description": "Base color map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Unwrapped", @@ -180,7 +180,7 @@ { "id": "textureBlendMode", "displayName": "Texture Blend Mode", - "description": "Selects the equation to use when combining Color, Factor, and Texture Map.", + "description": "Selects the equation to use when combining Color, Factor, and Texture.", "type": "Enum", "enumValues": [ "Multiply", "LinearLight", "Lerp", "Overlay" ], "defaultValue": "Multiply", @@ -193,8 +193,8 @@ "roughness": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface roughness.", + "displayName": "Texture", + "description": "Texture for defining surface roughness.", "type": "Image", "connection": { "type": "ShaderInput", @@ -204,14 +204,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Unwrapped", @@ -224,7 +224,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "lowerBound", "displayName": "Lower Bound", - "description": "The roughness value that corresponds to black in the texture map.", + "description": "The roughness value that corresponds to black in the texture.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -238,7 +238,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "upperBound", "displayName": "Upper Bound", - "description": "The roughness value that corresponds to white in the texture map.", + "description": "The roughness value that corresponds to white in the texture.", "type": "Float", "defaultValue": 1.0, "min": 0.0, @@ -279,8 +279,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface reflectance.", + "displayName": "Texture", + "description": "Texture for defining surface reflectance.", "type": "Image", "connection": { "type": "ShaderInput", @@ -290,14 +290,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Specular reflection texture map UV set", + "description": "Specular reflection map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Unwrapped", @@ -321,8 +321,8 @@ "normal": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface normal direction.", + "displayName": "Texture", + "description": "Texture for defining surface normal direction.", "type": "Image", "connection": { "type": "ShaderInput", @@ -332,14 +332,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just rely on vertex normals.", + "description": "Whether to use the texture, or just rely on vertex normals.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Unwrapped", @@ -388,7 +388,7 @@ { "id": "diffuseTextureMap", "displayName": "Diffuse AO", - "description": "Texture map for defining occlusion area for diffuse ambient lighting.", + "description": "Texture for defining occlusion area for diffuse ambient lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -398,14 +398,14 @@ { "id": "diffuseUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Diffuse AO texture map.", + "description": "Whether to use the Diffuse AO map.", "type": "Bool", "defaultValue": true }, { "id": "diffuseTextureMapUv", "displayName": " UV", - "description": "Diffuse AO texture map UV set.", + "description": "Diffuse AO map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -430,7 +430,7 @@ { "id": "specularTextureMap", "displayName": "Specular Cavity", - "description": "Texture map for defining occlusion area for specular lighting.", + "description": "Texture for defining occlusion area for specular lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -440,14 +440,14 @@ { "id": "specularUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Specular Cavity texture map.", + "description": "Whether to use the Specular Cavity map.", "type": "Bool", "defaultValue": true }, { "id": "specularTextureMapUv", "displayName": " UV", - "description": "Specular Cavity texture map UV set.", + "description": "Specular Cavity map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -498,7 +498,7 @@ { "id": "influenceMap", "displayName": " Influence Map", - "description": "Use texture map to control the strength of subsurface scattering", + "description": "Texture for controlling the strength of subsurface scattering", "type": "Image", "connection": { "type": "ShaderInput", @@ -508,7 +508,7 @@ { "id": "useInfluenceMap", "displayName": " Use Influence Map", - "description": "Whether to use the texture map as influence mask.", + "description": "Whether to use the influence map.", "type": "Bool", "defaultValue": true }, @@ -577,7 +577,7 @@ { "id": "thicknessMap", "displayName": " Thickness Map", - "description": "Use a greyscale texture for per pixel thickness", + "description": "Texture for controlling per pixel thickness", "type": "Image", "connection": { "type": "ShaderInput", @@ -606,7 +606,7 @@ { "id": "transmissionTint", "displayName": " Transmission Tint", - "description": "Color of the volume light travelling through", + "description": "Color of the volume light traveling through", "type": "Color", "defaultValue": [ 1.0, 0.8, 0.6 ] }, @@ -792,7 +792,7 @@ { "id": "enableDetailMaskTexture", "displayName": " Use Texture", - "description": "Enable detail mask texture", + "description": "Enable detail blend mask", "type": "Bool", "defaultValue": true }, @@ -811,7 +811,7 @@ { "id": "textureMapUv", "displayName": "Detail Map UVs", - "description": "Which UV set to use for detail map texture sampling", + "description": "Which UV set to use for detail map sampling", "type": "Enum", "enumIsUv": true, "defaultValue": "Unwrapped", @@ -829,8 +829,8 @@ }, { "id": "baseColorDetailMap", - "displayName": " Texture Map", - "description": "Detailed Base Color Texture map", + "displayName": " Texture", + "description": "Detailed Base Color Texture", "type": "Image", "connection": { "type": "ShaderInput", @@ -853,7 +853,7 @@ { "id": "enableNormals", "displayName": "Enable Normal", - "description": "Enable detail normal texture to be used for fine detail normal such as scratches and small dents", + "description": "Enable detail normal map to be used for fine detail normal such as scratches and small dents", "type": "Bool", "defaultValue": false }, @@ -872,8 +872,8 @@ }, { "id": "normalDetailMap", - "displayName": " Texture Map", - "description": "Detailed Normal Texture map", + "displayName": " Texture", + "description": "Detailed Normal map", "type": "Image", "connection": { "type": "ShaderInput", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype index ca6cb77b0a..5b6e5f30bc 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype @@ -26,7 +26,7 @@ }, { "id": "general", - "displayName": "General", + "displayName": "General Settings", "description": "General settings." }, //############################################################################################## @@ -428,7 +428,7 @@ { "id": "showClipping", "displayName": "Show Clipping", - "description": "Highlight areas where the heightmap is clipped by the mesh surface.", + "description": "Highlight areas where the height map is clipped by the mesh surface.", "type": "Bool", "defaultValue": false, "connection": { @@ -550,7 +550,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "Base color texture map", "type": "Image", "connection": { @@ -561,14 +561,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Base color texture map UV set", + "description": "Base color map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -580,7 +580,7 @@ { "id": "textureBlendMode", "displayName": "Texture Blend Mode", - "description": "Selects the equation to use when combining Color, Factor, and Texture Map.", + "description": "Selects the equation to use when combining Color, Factor, and Texture.", "type": "Enum", "enumValues": [ "Multiply", "LinearLight", "Lerp", "Overlay" ], "defaultValue": "Multiply", @@ -606,7 +606,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "", "type": "Image", "connection": { @@ -617,14 +617,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Metallic texture map UV set", + "description": "Metallic map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -637,8 +637,8 @@ "layer1_roughness": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface roughness.", + "displayName": "Texture", + "description": "Texture for defining surface roughness.", "type": "Image", "connection": { "type": "ShaderInput", @@ -648,14 +648,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -668,7 +668,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "lowerBound", "displayName": "Lower Bound", - "description": "The roughness value that corresponds to black in the texture map.", + "description": "The roughness value that corresponds to black in the texture.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -682,7 +682,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "upperBound", "displayName": "Upper Bound", - "description": "The roughness value that corresponds to white in the texture map.", + "description": "The roughness value that corresponds to white in the texture.", "type": "Float", "defaultValue": 1.0, "min": 0.0, @@ -723,8 +723,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface reflectance.", + "displayName": "Texture", + "description": "Texture for defining surface reflectance.", "type": "Image", "connection": { "type": "ShaderInput", @@ -734,14 +734,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Specular reflection texture map UV set", + "description": "Specular reflection map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -754,8 +754,8 @@ "layer1_normal": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface normal direction.", + "displayName": "Texture", + "description": "Texture for defining surface normal direction.", "type": "Image", "connection": { "type": "ShaderInput", @@ -765,14 +765,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just rely on vertex normals.", + "description": "Whether to use the texture, or just rely on vertex normals.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -841,7 +841,7 @@ { "id": "influenceMap", "displayName": " Influence Map", - "description": "Strength factor texture map", + "description": "Strength factor texture", "type": "Image", "connection": { "type": "ShaderInput", @@ -851,14 +851,14 @@ { "id": "useInfluenceMap", "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "influenceMapUv", "displayName": " UV", - "description": "Strength factor texture map UV set", + "description": "Strength factor map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -883,7 +883,7 @@ { "id": "roughnessMap", "displayName": " Roughness Map", - "description": "Roughness texture map", + "description": "Texture for defining surface roughness", "type": "Image", "connection": { "type": "ShaderInput", @@ -893,14 +893,14 @@ { "id": "useRoughnessMap", "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the roughness value.", + "description": "Whether to use the texture, or just default to the roughness value.", "type": "Bool", "defaultValue": true }, { "id": "roughnessMapUv", "displayName": " UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -942,7 +942,7 @@ { "id": "normalMapUv", "displayName": " UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -956,7 +956,7 @@ { "id": "diffuseTextureMap", "displayName": "Diffuse AO", - "description": "Texture map for defining occlusion area for diffuse ambient lighting.", + "description": "Texture for defining occlusion area for diffuse ambient lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -966,14 +966,14 @@ { "id": "diffuseUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Diffuse AO texture map.", + "description": "Whether to use the Diffuse AO map.", "type": "Bool", "defaultValue": true }, { "id": "diffuseTextureMapUv", "displayName": " UV", - "description": "Diffuse AO texture map UV set.", + "description": "Diffuse AO map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -998,7 +998,7 @@ { "id": "specularTextureMap", "displayName": "Specular Cavity", - "description": "Texture map for defining occlusion area for specular lighting.", + "description": "Texture for defining occlusion area for specular lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -1008,14 +1008,14 @@ { "id": "specularUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Specular Cavity texture map.", + "description": "Whether to use the Specular Cavity map.", "type": "Bool", "defaultValue": true }, { "id": "specularTextureMapUv", "displayName": " UV", - "description": "Specular Cavity texture map UV set.", + "description": "Specular Cavity map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1078,8 +1078,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining emissive area.", + "displayName": "Texture", + "description": "Texture for defining emissive area.", "type": "Image", "connection": { "type": "ShaderInput", @@ -1089,14 +1089,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Emissive texture map UV set", + "description": "Emissive map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1109,8 +1109,8 @@ "layer1_parallax": [ { "id": "textureMap", - "displayName": "Heightmap", - "description": "Displacement heightmap, which can be used for layer blending and/or a parallax effect.", + "displayName": "Height Map", + "description": "Displacement height map, which can be used for layer blending and/or a parallax effect.", "type": "Image", "connection": { "type": "ShaderInput", @@ -1120,14 +1120,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the heightmap.", + "description": "Whether to use the height map.", "type": "Bool", "defaultValue": true }, { "id": "factor", "displayName": "Scale", - "description": "The total height of the heightmap in local model units.", + "description": "The total height of the height map in local model units.", "type": "Float", "defaultValue": 0.05, "min": 0.0, @@ -1245,7 +1245,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "Base color texture map", "type": "Image", "connection": { @@ -1256,14 +1256,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Base color texture map UV set", + "description": "Base color map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1275,7 +1275,7 @@ { "id": "textureBlendMode", "displayName": "Texture Blend Mode", - "description": "Selects the equation to use when combining Color, Factor, and Texture Map.", + "description": "Selects the equation to use when combining Color, Factor, and Texture.", "type": "Enum", "enumValues": [ "Multiply", "LinearLight", "Lerp", "Overlay" ], "defaultValue": "Multiply", @@ -1301,7 +1301,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "", "type": "Image", "connection": { @@ -1312,14 +1312,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Metallic texture map UV set", + "description": "Metallic map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1332,8 +1332,8 @@ "layer2_roughness": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface roughness.", + "displayName": "Texture", + "description": "Texture for defining surface roughness.", "type": "Image", "connection": { "type": "ShaderInput", @@ -1343,14 +1343,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1363,7 +1363,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "lowerBound", "displayName": "Lower Bound", - "description": "The roughness value that corresponds to black in the texture map.", + "description": "The roughness value that corresponds to black in the texture.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -1377,7 +1377,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "upperBound", "displayName": "Upper Bound", - "description": "The roughness value that corresponds to white in the texture map.", + "description": "The roughness value that corresponds to white in the texture.", "type": "Float", "defaultValue": 1.0, "min": 0.0, @@ -1418,8 +1418,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface reflectance.", + "displayName": "Texture", + "description": "Texture for defining surface reflectance.", "type": "Image", "connection": { "type": "ShaderInput", @@ -1429,14 +1429,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Specular reflection texture map UV set", + "description": "Specular reflection map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1449,8 +1449,8 @@ "layer2_normal": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface normal direction.", + "displayName": "Texture", + "description": "Texture for defining surface normal direction.", "type": "Image", "connection": { "type": "ShaderInput", @@ -1460,14 +1460,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just rely on vertex normals.", + "description": "Whether to use the texture, or just rely on vertex normals.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1536,7 +1536,7 @@ { "id": "influenceMap", "displayName": " Influence Map", - "description": "Strength factor texture map", + "description": "Strength factor texture", "type": "Image", "connection": { "type": "ShaderInput", @@ -1546,14 +1546,14 @@ { "id": "useInfluenceMap", "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "influenceMapUv", "displayName": " UV", - "description": "Strength factor texture map UV set", + "description": "Strength factor map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1578,7 +1578,7 @@ { "id": "roughnessMap", "displayName": " Roughness Map", - "description": "Roughness texture map", + "description": "Texture for defining surface roughness", "type": "Image", "connection": { "type": "ShaderInput", @@ -1588,14 +1588,14 @@ { "id": "useRoughnessMap", "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the roughness value.", + "description": "Whether to use the texture, or just default to the roughness value.", "type": "Bool", "defaultValue": true }, { "id": "roughnessMapUv", "displayName": " UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1637,7 +1637,7 @@ { "id": "normalMapUv", "displayName": " UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1651,7 +1651,7 @@ { "id": "diffuseTextureMap", "displayName": "Diffuse AO", - "description": "Texture map for defining occlusion area for diffuse ambient lighting.", + "description": "Texture for defining occlusion area for diffuse ambient lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -1661,14 +1661,14 @@ { "id": "diffuseUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Diffuse AO texture map.", + "description": "Whether to use the Diffuse AO map.", "type": "Bool", "defaultValue": true }, { "id": "diffuseTextureMapUv", "displayName": " UV", - "description": "Diffuse AO texture map UV set.", + "description": "Diffuse AO map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1693,7 +1693,7 @@ { "id": "specularTextureMap", "displayName": "Specular Cavity", - "description": "Texture map for defining occlusion area for specular lighting.", + "description": "Texture for defining occlusion area for specular lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -1703,14 +1703,14 @@ { "id": "specularUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Specular Cavity texture map.", + "description": "Whether to use the Specular Cavity map.", "type": "Bool", "defaultValue": true }, { "id": "specularTextureMapUv", "displayName": " UV", - "description": "Specular Cavity texture map UV set.", + "description": "Specular Cavity map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1773,8 +1773,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining emissive area.", + "displayName": "Texture", + "description": "Texture for defining emissive area.", "type": "Image", "connection": { "type": "ShaderInput", @@ -1784,14 +1784,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Emissive texture map UV set", + "description": "Emissive map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1804,8 +1804,8 @@ "layer2_parallax": [ { "id": "textureMap", - "displayName": "Heightmap", - "description": "Displacement heightmap, which can be used for layer blending and/or a parallax effect.", + "displayName": "Height Map", + "description": "Displacement height map, which can be used for layer blending and/or a parallax effect.", "type": "Image", "connection": { "type": "ShaderInput", @@ -1815,14 +1815,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the heightmap.", + "description": "Whether to use the height map.", "type": "Bool", "defaultValue": true }, { "id": "factor", "displayName": "Scale", - "description": "The total height of the heightmap in local model units.", + "description": "The total height of the height map in local model units.", "type": "Float", "defaultValue": 0.05, "min": 0.0, @@ -1940,7 +1940,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "Base color texture map", "type": "Image", "connection": { @@ -1951,14 +1951,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Base color texture map UV set", + "description": "Base color map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -1970,7 +1970,7 @@ { "id": "textureBlendMode", "displayName": "Texture Blend Mode", - "description": "Selects the equation to use when combining Color, Factor, and Texture Map.", + "description": "Selects the equation to use when combining Color, Factor, and Texture.", "type": "Enum", "enumValues": [ "Multiply", "LinearLight", "Lerp", "Overlay" ], "defaultValue": "Multiply", @@ -1996,7 +1996,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "", "type": "Image", "connection": { @@ -2007,14 +2007,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Metallic texture map UV set", + "description": "Metallic map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -2027,8 +2027,8 @@ "layer3_roughness": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface roughness.", + "displayName": "Texture", + "description": "Texture for defining surface roughness.", "type": "Image", "connection": { "type": "ShaderInput", @@ -2038,14 +2038,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -2058,7 +2058,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "lowerBound", "displayName": "Lower Bound", - "description": "The roughness value that corresponds to black in the texture map.", + "description": "The roughness value that corresponds to black in the texture.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -2072,7 +2072,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "upperBound", "displayName": "Upper Bound", - "description": "The roughness value that corresponds to white in the texture map.", + "description": "The roughness value that corresponds to white in the texture.", "type": "Float", "defaultValue": 1.0, "min": 0.0, @@ -2113,8 +2113,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface reflectance.", + "displayName": "Texture", + "description": "Texture for defining surface reflectance.", "type": "Image", "connection": { "type": "ShaderInput", @@ -2124,14 +2124,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Specular reflection texture map UV set", + "description": "Specular reflection map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -2144,8 +2144,8 @@ "layer3_normal": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface normal direction.", + "displayName": "Texture", + "description": "Texture for defining surface normal direction.", "type": "Image", "connection": { "type": "ShaderInput", @@ -2155,14 +2155,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just rely on vertex normals.", + "description": "Whether to use the texture, or just rely on vertex normals.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -2231,7 +2231,7 @@ { "id": "influenceMap", "displayName": " Influence Map", - "description": "Strength factor texture map", + "description": "Strength factor texture", "type": "Image", "connection": { "type": "ShaderInput", @@ -2241,14 +2241,14 @@ { "id": "useInfluenceMap", "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "influenceMapUv", "displayName": " UV", - "description": "Strength factor texture map UV set", + "description": "Strength factor map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -2273,7 +2273,7 @@ { "id": "roughnessMap", "displayName": " Roughness Map", - "description": "Roughness texture map", + "description": "Texture for defining surface roughness", "type": "Image", "connection": { "type": "ShaderInput", @@ -2283,14 +2283,14 @@ { "id": "useRoughnessMap", "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the roughness value.", + "description": "Whether to use the texture, or just default to the roughness value.", "type": "Bool", "defaultValue": true }, { "id": "roughnessMapUv", "displayName": " UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -2332,7 +2332,7 @@ { "id": "normalMapUv", "displayName": " UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -2346,7 +2346,7 @@ { "id": "diffuseTextureMap", "displayName": "Diffuse AO", - "description": "Texture map for defining occlusion area for diffuse ambient lighting.", + "description": "Texture for defining occlusion area for diffuse ambient lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -2356,14 +2356,14 @@ { "id": "diffuseUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Diffuse AO texture map.", + "description": "Whether to use the Diffuse AO map.", "type": "Bool", "defaultValue": true }, { "id": "diffuseTextureMapUv", "displayName": " UV", - "description": "Diffuse AO texture map UV set.", + "description": "Diffuse AO map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -2388,7 +2388,7 @@ { "id": "specularTextureMap", "displayName": "Specular Cavity", - "description": "Texture map for defining occlusion area for specular lighting.", + "description": "Texture for defining occlusion area for specular lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -2398,14 +2398,14 @@ { "id": "specularUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Specular Cavity texture map.", + "description": "Whether to use the Specular Cavity map.", "type": "Bool", "defaultValue": true }, { "id": "specularTextureMapUv", "displayName": " UV", - "description": "Specular Cavity texture map UV set.", + "description": "Specular Cavity map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -2468,8 +2468,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining emissive area.", + "displayName": "Texture", + "description": "Texture for defining emissive area.", "type": "Image", "connection": { "type": "ShaderInput", @@ -2479,14 +2479,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Emissive texture map UV set", + "description": "Emissive map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -2499,8 +2499,8 @@ "layer3_parallax": [ { "id": "textureMap", - "displayName": "Heightmap", - "description": "Displacement heightmap, which can be used for layer blending and/or a parallax effect.", + "displayName": "Height Map", + "description": "Displacement height map, which can be used for layer blending and/or a parallax effect.", "type": "Image", "connection": { "type": "ShaderInput", @@ -2510,14 +2510,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the heightmap.", + "description": "Whether to use the height map.", "type": "Bool", "defaultValue": true }, { "id": "factor", "displayName": "Scale", - "description": "The total height of the heightmap in local model units.", + "description": "The total height of the height map in local model units.", "type": "Float", "defaultValue": 0.05, "min": 0.0, diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index 183cddd4cb..0904302085 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -55,8 +55,8 @@ }, { "id": "parallax", - "displayName": "Parallax Mapping", - "description": "Properties for parallax effect produced by depthmap." + "displayName": "Displacement", + "description": "Properties for parallax effect produced by a height map." }, { "id": "subsurfaceScattering", @@ -71,7 +71,7 @@ }, { "id": "general", - "displayName": "General", + "displayName": "General Settings", "description": "General settings." } ], @@ -182,7 +182,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "Base color texture map", "type": "Image", "connection": { @@ -193,14 +193,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Base color texture map UV set", + "description": "Base color map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -212,7 +212,7 @@ { "id": "textureBlendMode", "displayName": "Texture Blend Mode", - "description": "Selects the equation to use when combining Color, Factor, and Texture Map.", + "description": "Selects the equation to use when combining Color, Factor, and Texture.", "type": "Enum", "enumValues": [ "Multiply", "LinearLight", "Lerp", "Overlay" ], "defaultValue": "Multiply", @@ -238,7 +238,7 @@ }, { "id": "textureMap", - "displayName": "Texture Map", + "displayName": "Texture", "description": "", "type": "Image", "connection": { @@ -249,14 +249,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Metallic texture map UV set", + "description": "Metallic map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -269,8 +269,8 @@ "roughness": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface roughness.", + "displayName": "Texture", + "description": "Texture for defining surface roughness.", "type": "Image", "connection": { "type": "ShaderInput", @@ -280,14 +280,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -300,7 +300,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "lowerBound", "displayName": "Lower Bound", - "description": "The roughness value that corresponds to black in the texture map.", + "description": "The roughness value that corresponds to black in the texture.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -314,7 +314,7 @@ // Note that "factor" is mutually exclusive with "lowerBound"/"upperBound". These are swapped by a lua functor. "id": "upperBound", "displayName": "Upper Bound", - "description": "The roughness value that corresponds to white in the texture map.", + "description": "The roughness value that corresponds to white in the texture.", "type": "Float", "defaultValue": 1.0, "min": 0.0, @@ -355,8 +355,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface reflectance.", + "displayName": "Texture", + "description": "Texture for defining surface reflectance.", "type": "Image", "connection": { "type": "ShaderInput", @@ -366,14 +366,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Specular reflection texture map UV set", + "description": "Specular reflection map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -418,7 +418,7 @@ { "id": "influenceMap", "displayName": " Influence Map", - "description": "Strength factor texture map", + "description": "Strength factor texture", "type": "Image", "connection": { "type": "ShaderInput", @@ -428,14 +428,14 @@ { "id": "useInfluenceMap", "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the Factor value.", + "description": "Whether to use the texture, or just default to the Factor value.", "type": "Bool", "defaultValue": true }, { "id": "influenceMapUv", "displayName": " UV", - "description": "Strength factor texture map UV set", + "description": "Strength factor map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -460,7 +460,7 @@ { "id": "roughnessMap", "displayName": " Roughness Map", - "description": "Roughness texture map", + "description": "Texture for defining surface roughness", "type": "Image", "connection": { "type": "ShaderInput", @@ -470,14 +470,14 @@ { "id": "useRoughnessMap", "displayName": " Use Texture", - "description": "Whether to use the texture map, or just default to the roughness value.", + "description": "Whether to use the texture, or just default to the roughness value.", "type": "Bool", "defaultValue": true }, { "id": "roughnessMapUv", "displayName": " UV", - "description": "Roughness texture map UV set", + "description": "Roughness map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -519,7 +519,7 @@ { "id": "normalMapUv", "displayName": " UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -532,8 +532,8 @@ "normal": [ { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface normal direction.", + "displayName": "Texture", + "description": "Texture for defining surface normal direction.", "type": "Image", "connection": { "type": "ShaderInput", @@ -543,14 +543,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map, or just rely on vertex normals.", + "description": "Whether to use the texture, or just rely on vertex normals.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Normal texture map UV set", + "description": "Normal map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -599,7 +599,7 @@ { "id": "mode", "displayName": "Opacity Mode", - "description": "Opacity mode for this texture.", + "description": "Indicates the general approach how transparency is to be applied.", "type": "Enum", "enumValues": [ "Opaque", "Cutout", "Blended", "TintedTransparent" ], "defaultValue": "Opaque", @@ -611,7 +611,7 @@ { "id": "alphaSource", "displayName": "Alpha Source", - "description": "Source texture of alpha value.", + "description": "Indicates whether to get the opacity texture from the Base Color map (Packed) or from a separate greyscale texture (Split).", "type": "Enum", "enumValues": [ "Packed", "Split", "None" ], "defaultValue": "Packed", @@ -622,8 +622,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface opacity.", + "displayName": "Texture", + "description": "Texture for defining surface opacity.", "type": "Image", "connection": { "type": "ShaderInput", @@ -633,7 +633,7 @@ { "id": "textureMapUv", "displayName": "UV", - "description": "Opacity texture map UV set", + "description": "Opacity map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -728,7 +728,7 @@ { "id": "diffuseTextureMap", "displayName": "Diffuse AO", - "description": "Texture map for defining occlusion area for diffuse ambient lighting.", + "description": "Texture for defining occlusion area for diffuse ambient lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -738,14 +738,14 @@ { "id": "diffuseUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Diffuse AO texture map.", + "description": "Whether to use the Diffuse AO map.", "type": "Bool", "defaultValue": true }, { "id": "diffuseTextureMapUv", "displayName": " UV", - "description": "Diffuse AO texture map UV set.", + "description": "Diffuse AO map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -770,7 +770,7 @@ { "id": "specularTextureMap", "displayName": "Specular Cavity", - "description": "Texture map for defining occlusion area for specular lighting.", + "description": "Texture for defining occlusion area for specular lighting.", "type": "Image", "connection": { "type": "ShaderInput", @@ -780,14 +780,14 @@ { "id": "specularUseTexture", "displayName": " Use Texture", - "description": "Whether to use the Specular Cavity texture map.", + "description": "Whether to use the Specular Cavity map.", "type": "Bool", "defaultValue": true }, { "id": "specularTextureMapUv", "displayName": " UV", - "description": "Specular Cavity texture map UV set.", + "description": "Specular Cavity map UV set.", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -850,8 +850,8 @@ }, { "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining emissive area.", + "displayName": "Texture", + "description": "Texture for defining emissive area.", "type": "Image", "connection": { "type": "ShaderInput", @@ -861,14 +861,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the texture map.", + "description": "Whether to use the texture.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Emissive texture map UV set", + "description": "Emissive map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -881,8 +881,8 @@ "parallax": [ { "id": "textureMap", - "displayName": "Heightmap", - "description": "Displacement heightmap to create parallax effect.", + "displayName": "Height Map", + "description": "Displacement height map to create parallax effect.", "type": "Image", "connection": { "type": "ShaderInput", @@ -892,14 +892,14 @@ { "id": "useTexture", "displayName": "Use Texture", - "description": "Whether to use the heightmap.", + "description": "Whether to use the height map.", "type": "Bool", "defaultValue": true }, { "id": "textureMapUv", "displayName": "UV", - "description": "Heightmap UV set", + "description": "Height map UV set", "type": "Enum", "enumIsUv": true, "defaultValue": "Tiled", @@ -910,8 +910,8 @@ }, { "id": "factor", - "displayName": "Heightmap Scale", - "description": "The total height of the heightmap in local model units.", + "displayName": "Height Map Scale", + "description": "The total height of the height map in local model units.", "type": "Float", "defaultValue": 0.05, "min": 0.0, @@ -972,7 +972,7 @@ { "id": "showClipping", "displayName": "Show Clipping", - "description": "Highlight areas where the heightmap is clipped by the mesh surface.", + "description": "Highlight areas where the height map is clipped by the mesh surface.", "type": "Bool", "defaultValue": false, "connection": { @@ -1009,7 +1009,7 @@ { "id": "influenceMap", "displayName": " Influence Map", - "description": "Use texture map to control the strength of subsurface scattering", + "description": "Texture for controlling the strength of subsurface scattering", "type": "Image", "connection": { "type": "ShaderInput", @@ -1019,7 +1019,7 @@ { "id": "useInfluenceMap", "displayName": " Use Influence Map", - "description": "Whether to use the texture map as influence mask.", + "description": "Whether to use the influence map.", "type": "Bool", "defaultValue": true }, @@ -1088,7 +1088,7 @@ { "id": "thicknessMap", "displayName": " Thickness Map", - "description": "Use a greyscale texture for per pixel thickness", + "description": "Texture for controlling per pixel thickness", "type": "Image", "connection": { "type": "ShaderInput", @@ -1117,7 +1117,7 @@ { "id": "transmissionTint", "displayName": " Transmission Tint", - "description": "Color of the volume light travelling through", + "description": "Color of the volume light traveling through", "type": "Color", "defaultValue": [ 1.0, 0.8, 0.6 ] }, diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialSourceData.h index 9baf80bae0..c8b406f94b 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialSourceData.h @@ -32,7 +32,7 @@ namespace AZ //! In the source data, properties and UV names are loaded separately. //! However, treating UV names as a special property group can greatly simplify the editor code. //! See MaterialInspector::AddUvNamesGroup() for more details. - static constexpr const char UvGroupName[] = "UvNames"; + static constexpr const char UvGroupName[] = "uvSets"; class MaterialAsset; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentRequestBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentRequestBus.h index c71d500d8c..7f36d3fabc 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentRequestBus.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentRequestBus.h @@ -33,7 +33,7 @@ namespace AZ namespace MaterialEditor { //! UVs are processed in a property group but will be handled differently. - static constexpr const char UvGroupName[] = "UvNames"; + static constexpr const char UvGroupName[] = "uvSets"; class MaterialDocumentRequests : public AZ::EBusTraits diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index 301fd69025..2242d3af1b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -819,10 +819,10 @@ namespace MaterialEditor // is implemented. AtomToolsFramework::DynamicPropertyConfig propertyConfig; propertyConfig.m_dataType = AtomToolsFramework::DynamicPropertyType::Asset; - propertyConfig.m_id = "details.materialType"; + propertyConfig.m_id = "overview.materialType"; propertyConfig.m_nameId = "materialType"; propertyConfig.m_displayName = "Material Type"; - propertyConfig.m_groupName = "Details"; + propertyConfig.m_groupName = "Overview"; propertyConfig.m_description = "The material type defines the layout, properties, default values, shader connections, and other " "data needed to create and edit a derived material."; propertyConfig.m_defaultValue = AZStd::any(materialTypeAsset); @@ -834,10 +834,10 @@ namespace MaterialEditor propertyConfig = {}; propertyConfig.m_dataType = AtomToolsFramework::DynamicPropertyType::Asset; - propertyConfig.m_id = "details.parentMaterial"; + propertyConfig.m_id = "overview.parentMaterial"; propertyConfig.m_nameId = "parentMaterial"; propertyConfig.m_displayName = "Parent Material"; - propertyConfig.m_groupName = "Details"; + propertyConfig.m_groupName = "Overview"; propertyConfig.m_description = "The parent material provides an initial configuration whose properties are inherited and overriden by a derived material."; propertyConfig.m_defaultValue = AZStd::any(parentMaterialAsset); @@ -860,7 +860,7 @@ namespace MaterialEditor propertyConfig.m_id = MaterialPropertyId(UvGroupName, shaderInput).GetCStr(); propertyConfig.m_nameId = shaderInput; propertyConfig.m_displayName = shaderInput; - propertyConfig.m_groupName = "UV Names"; + propertyConfig.m_groupName = "UV Sets"; propertyConfig.m_description = shaderInput; propertyConfig.m_defaultValue = uvName; propertyConfig.m_originalValue = uvName; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp index 706d365027..560c82be9b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp @@ -79,8 +79,8 @@ namespace MaterialEditor if (!m_documentId.IsNull() && isOpen) { - // Create the top group for displaying details about the material - AddDetailsGroup(); + // Create the top group for displaying overview info about the material + AddOverviewGroup(); // Create groups for displaying editable UV names AddUvNamesGroup(); // Create groups for displaying editable properties @@ -105,25 +105,25 @@ namespace MaterialEditor return property && AtomToolsFramework::ArePropertyValuesEqual(property->GetValue(), property->GetConfig().m_parentValue); } - void MaterialInspector::AddDetailsGroup() + void MaterialInspector::AddOverviewGroup() { const AZ::RPI::MaterialTypeSourceData* materialTypeSourceData = nullptr; MaterialDocumentRequestBus::EventResult( materialTypeSourceData, m_documentId, &MaterialDocumentRequestBus::Events::GetMaterialTypeSourceData); - const AZStd::string groupNameId = "details"; - const AZStd::string groupDisplayName = "Details"; + const AZStd::string groupNameId = "overview"; + const AZStd::string groupDisplayName = "Overview"; const AZStd::string groupDescription = materialTypeSourceData->m_description; auto& group = m_groups[groupNameId]; AtomToolsFramework::DynamicProperty property; MaterialDocumentRequestBus::EventResult( - property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::Name("details.materialType")); + property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::Name("overview.materialType")); group.m_properties.push_back(property); property = {}; MaterialDocumentRequestBus::EventResult( - property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::Name("details.parentMaterial")); + property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::Name("overview.parentMaterial")); group.m_properties.push_back(property); // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties @@ -139,7 +139,7 @@ namespace MaterialEditor MaterialDocumentRequestBus::EventResult(materialAsset, m_documentId, &MaterialDocumentRequestBus::Events::GetAsset); const AZStd::string groupNameId = UvGroupName; - const AZStd::string groupDisplayName = "UV Names"; + const AZStd::string groupDisplayName = "UV Sets"; const AZStd::string groupDescription = "UV set names in this material, which can be renamed to match those in the model."; auto& group = m_groups[groupNameId]; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h index 4080430ff5..65d095f42f 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h @@ -52,7 +52,7 @@ namespace MaterialEditor bool CompareInstanceNodeProperties( const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) const; - void AddDetailsGroup(); + void AddOverviewGroup(); void AddUvNamesGroup(); void AddPropertiesGroup(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index 3192900ca4..229606a238 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -184,7 +184,7 @@ namespace AZ void MaterialPropertyInspector::AddUvNamesGroup() { const AZStd::string groupNameId = AZ::RPI::UvGroupName; - const AZStd::string groupDisplayName = "UV Names"; + const AZStd::string groupDisplayName = "UV Sets"; const AZStd::string groupDescription = "UV set names in this material, which can be renamed to match those in the model."; auto& group = m_groups[groupNameId]; From aedc27030402c3108f459280fabdec7d8e5bae5d Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Fri, 28 May 2021 13:40:08 -0700 Subject: [PATCH 344/811] Fix path not showing up in asset property control (#1037) --- .../UI/PropertyEditor/PropertyAssetCtrl.cpp | 15 ++++++++++----- .../Code/Editor/PropertyHandlerDirectory.cpp | 5 +++-- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp index dd39cf9b97..169a90497b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp @@ -953,11 +953,16 @@ namespace AzToolsFramework return; } - const AZ::Data::AssetId assetID = GetCurrentAssetID(); - m_currentAssetHint = ""; - - if (!m_unnamedType) + const AZStd::string& folderPath = GetFolderSelection(); + if (!folderPath.empty()) { + m_currentAssetHint = folderPath; + } + else + { + const AZ::Data::AssetId assetID = GetCurrentAssetID(); + m_currentAssetHint = ""; + AZ::Outcome jobOutcome = AZ::Failure(); AssetSystemJobRequestBus::BroadcastResult(jobOutcome, &AssetSystemJobRequestBus::Events::GetAssetJobsInfoByAssetID, assetID, false, false); @@ -971,7 +976,7 @@ namespace AzToolsFramework if (!jobs.empty()) { - // The default behavior is show to the source filename. + // The default behavior is to show the source filename. assetPath = jobs[0].m_sourceFile; AZStd::string errorLog; diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp index 61f6e0f3dc..893790d0f5 100644 --- a/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp +++ b/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp @@ -158,7 +158,10 @@ bool PropertyHandlerDirectory::ReadValuesIntoGUI(size_t index, PropertyDirectory ctrl->blockSignals(true); { + // Set currently selected folder path + // Note: this must be done before setting asset type below which updates the GUI display ctrl->SetCurrentAssetHint(instance); + ctrl->SetFolderSelection(instance); // We need to set the asset type so the property panel labels get // populated properly (via SetCurrentAssetType). To avoid defining @@ -166,8 +169,6 @@ bool PropertyHandlerDirectory::ReadValuesIntoGUI(size_t index, PropertyDirectory // logic to run (otherwise it will early-out due to invalid asset type). const char* throwAwayAssetType = "{43EDD212-F589-43C8-BC02-A8F9243271CB}"; ctrl->SetCurrentAssetType(AZ::Data::AssetType(throwAwayAssetType)); - - ctrl->SetFolderSelection(instance); } ctrl->blockSignals(false); From fe8803291a759db566cfaa09a4ad64454dc50583 Mon Sep 17 00:00:00 2001 From: sconel Date: Fri, 28 May 2021 13:53:09 -0700 Subject: [PATCH 345/811] Fix for referencing now deprecated AZ::Transform constructor --- .../Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index b93844b989..21d1fc5264 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -118,7 +118,7 @@ namespace ScriptCanvas::Nodeables::Spawning AZ::Vector3 rotationCopy = rotation; AZ::Quaternion rotationQuat = AZ::Quaternion::CreateFromEulerAnglesDegrees(rotationCopy); - entityTransform->SetWorldTM(AZ::Transform(translation, rotationQuat, AZ::Vector3(scale, scale, scale))); + entityTransform->SetWorldTM(AZ::Transform(translation, rotationQuat, scale)); } }; From 0495d26d72284dc95d1d51363ca603eef8311213 Mon Sep 17 00:00:00 2001 From: AMZN-AlexOteiza <82234181+AMZN-AlexOteiza@users.noreply.github.com> Date: Fri, 28 May 2021 22:11:15 +0100 Subject: [PATCH 346/811] Added template for creation of default material library (#1040) --- .../TemplateMaterialLibrary.physmaterial | 158 ++++++++++++++++++ .../Components/EditorSystemComponent.cpp | 83 +++++++-- 2 files changed, 223 insertions(+), 18 deletions(-) create mode 100644 Gems/PhysX/Assets/PhysX/TemplateMaterialLibrary.physmaterial diff --git a/Gems/PhysX/Assets/PhysX/TemplateMaterialLibrary.physmaterial b/Gems/PhysX/Assets/PhysX/TemplateMaterialLibrary.physmaterial new file mode 100644 index 0000000000..481cd2fbfa --- /dev/null +++ b/Gems/PhysX/Assets/PhysX/TemplateMaterialLibrary.physmaterial @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp b/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp index c3f0411d58..b28bf6ab4a 100644 --- a/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp +++ b/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp @@ -31,6 +31,36 @@ namespace PhysX { constexpr const char* DefaultAssetFilename = "SurfaceTypeMaterialLibrary"; + constexpr const char* TemplateAssetFilename = "PhysX/TemplateMaterialLibrary"; + + static AZStd::optional> GetMaterialLibraryTemplate() + { + const auto& assetType = AZ::AzTypeInfo::Uuid(); + + AZStd::vector assetTypeExtensions; + AZ::AssetTypeInfoBus::Event(assetType, &AZ::AssetTypeInfo::GetAssetTypeExtensions, assetTypeExtensions); + + if (assetTypeExtensions.size() == 1) + { + // Constructing the path to the library asset + const AZStd::string& assetExtension = assetTypeExtensions[0]; + + // Use the path relative to the asset root to avoid hardcoding full path in the configuration + AZStd::string relativePath = TemplateAssetFilename; + AzFramework::StringFunc::Path::ReplaceExtension(relativePath, assetExtension.c_str()); + + AZ::Data::AssetId assetId; + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, relativePath.c_str(), assetType, false /*autoRegisterIfNotFound*/); + + if (assetId.IsValid()) + { + return AZ::Data::AssetManager::Instance().GetAsset(assetId, AZ::Data::AssetLoadBehavior::NoLoad); + } + } + + return AZStd::nullopt; + } static AZStd::optional> CreateMaterialLibrary(const AZStd::string& fullTargetFilePath, const AZStd::string& relativePath) { @@ -41,29 +71,45 @@ namespace PhysX AZ::Data::AssetId assetId; AZ::Data::AssetCatalogRequestBus::BroadcastResult( - assetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, relativePath.c_str(), assetType, true); + assetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, relativePath.c_str(), assetType, true /*autoRegisterIfNotFound*/); AZ::Data::Asset newAsset = AZ::Data::AssetManager::Instance().GetAsset(assetId, assetType, AZ::Data::AssetLoadBehavior::Default); - if (Physics::MaterialLibraryAsset* materialLibraryAsset = azrtti_cast(newAsset.GetData())) + if (auto* newMaterialLibraryData = azrtti_cast(newAsset.GetData())) { - // check it out in the source control system - AzToolsFramework::SourceControlCommandBus::Broadcast( - &AzToolsFramework::SourceControlCommandBus::Events::RequestEdit, fullTargetFilePath.c_str(), true, - [](bool /*success*/, const AzToolsFramework::SourceControlFileInfo& /*info*/) {}); + if (auto templateLibraryOpt = GetMaterialLibraryTemplate()) + { + if (const auto* templateMaterialLibData = azrtti_cast(templateLibraryOpt->GetData())) + { + templateLibraryOpt->QueueLoad(); + templateLibraryOpt->BlockUntilLoadComplete(); - // Save the material library asset into a file - auto assetHandler = AZ::Data::AssetManager::Instance().GetHandler(assetType); - if (assetHandler->SaveAssetData(newAsset, &fileStream)) - { - return newAsset; - } - else - { - AZ_Error("PhysX", false, - "CreateSurfaceTypeMaterialLibrary: Unable to save Surface Types Material Library Asset to %s", - fullTargetFilePath.c_str()); + // Fill the newly created material library using the template data + for (const auto& materialData : templateMaterialLibData->GetMaterialsData()) + { + newMaterialLibraryData->AddMaterialData(materialData); + } + + // check it out in the source control system + AzToolsFramework::SourceControlCommandBus::Broadcast( + &AzToolsFramework::SourceControlCommandBus::Events::RequestEdit, fullTargetFilePath.c_str(), true /*allowMultiCheckout*/, + [](bool /*success*/, const AzToolsFramework::SourceControlFileInfo& /*info*/) {}); + + // Save the material library asset into a file + auto assetHandler = AZ::Data::AssetManager::Instance().GetHandler(assetType); + if (assetHandler->SaveAssetData(newAsset, &fileStream)) + { + return newAsset; + } + else + { + AZ_Error( + "PhysX", false, + "CreateSurfaceTypeMaterialLibrary: Unable to save Surface Types Material Library Asset to %s", + fullTargetFilePath.c_str()); + } + } } } } @@ -189,7 +235,8 @@ namespace PhysX AzFramework::StringFunc::Path::ReplaceExtension(relativePath, assetExtension.c_str()); // Try to find an already existing material library - AZ::Data::AssetCatalogRequestBus::BroadcastResult(resultAssetId, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, relativePath.c_str(), azrtti_typeid(), false); + AZ::Data::AssetCatalogRequestBus::BroadcastResult(resultAssetId, + &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, relativePath.c_str(), azrtti_typeid(), false /*autoRegisterIfNotFound*/); if (!resultAssetId.IsValid()) { From 17024d6cf4bc30343604ebeb9bfb4e3727998436 Mon Sep 17 00:00:00 2001 From: clujames Date: Fri, 28 May 2021 14:21:55 -0700 Subject: [PATCH 347/811] Updating according to feedback --- AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py index a45ce3f49e..ea40001c31 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py @@ -94,7 +94,7 @@ class Cdk: deploy_cdk_application_cmd = ['cdk', 'deploy', '--require-approval', 'never'] if additonal_params: - deploy_cdk_application_cmd += additonal_params + deploy_cdk_application_cmd.extend(additonal_params) if context_variable: deploy_cdk_application_cmd.extend(['-c', f'{context_variable}']) From 2112da5f85b91533e6f9f3f804f2ccdc9d850c3f Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Fri, 28 May 2021 14:34:07 -0700 Subject: [PATCH 348/811] Reordered material property groups according to design review. - Base Color - Metallic - Roughness - Specular Reflectance F0 - Normal - Occlusion - Emissive - Subsurface - Clear Coat - Displacement - Opacity - UVs - Irradiance - General Settings ATOM-14002 [Material Editor] Revisit user facing organization and layout of material types --- .../Materials/Types/EnhancedPBR.materialtype | 54 +++++++++---------- .../Assets/Materials/Types/Skin.materialtype | 20 +++---- .../Types/StandardMultilayerPBR.materialtype | 30 +++++------ .../Materials/Types/StandardPBR.materialtype | 36 ++++++------- 4 files changed, 70 insertions(+), 70 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index 3b5a653f43..79c4ca3cc3 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -13,11 +13,6 @@ "displayName": "Metallic", "description": "Properties for configuring whether the surface is metallic or not." }, - { - "id": "anisotropy", - "displayName": "Anisotropic Material Response", - "description": "How much is this material response anisotropic." - }, { "id": "roughness", "displayName": "Roughness", @@ -28,25 +23,25 @@ "displayName": "Specular Reflectance f0", "description": "The constant f0 represents the specular reflectance at normal incidence (Fresnel 0 Angle). Used to adjust reflectance of non-metal surfaces." }, - { - "id": "clearCoat", - "displayName": "Clear Coat", - "description": "Properties for configuring gloss clear coat" - }, { "id": "normal", "displayName": "Normal", "description": "Properties related to configuring surface normal." }, { - "id": "opacity", - "displayName": "Opacity", - "description": "Properties for configuring the materials transparency." + "id": "detailLayerGroup", + "displayName": "Detail Layer", + "description": "Properties for Fine Details Layer." }, { - "id": "uv", - "displayName": "UVs", - "description": "Properties for configuring UV transforms." + "id": "detailUV", + "displayName": "Detail Layer UV", + "description": "Properties for modifying detail layer UV." + }, + { + "id": "anisotropy", + "displayName": "Anisotropic Material Response", + "description": "How much is this material response anisotropic." }, { "id": "occlusion", @@ -58,25 +53,30 @@ "displayName": "Emissive", "description": "Properties to add light emission, independent of other lights in the scene." }, - { - "id": "parallax", - "displayName": "Displacement", - "description": "Properties for parallax effect produced by a height map." - }, { "id": "subsurfaceScattering", "displayName": "Subsurface Scattering", "description": "Properties for configuring subsurface scattering effects." }, { - "id": "detailLayerGroup", - "displayName": "Detail Layer", - "description": "Properties for Fine Details Layer." + "id": "clearCoat", + "displayName": "Clear Coat", + "description": "Properties for configuring gloss clear coat" + }, + { + "id": "parallax", + "displayName": "Displacement", + "description": "Properties for parallax effect produced by a height map." }, { - "id": "detailUV", - "displayName": "Detail Layer UV", - "description": "Properties for modifying detail layer UV." + "id": "opacity", + "displayName": "Opacity", + "description": "Properties for configuring the materials transparency." + }, + { + "id": "uv", + "displayName": "UVs", + "description": "Properties for configuring UV transforms." }, { // Note: this property group is used in the DiffuseGlobalIllumination pass and not by the main forward shader diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype index ab36853723..9ead0376bb 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype @@ -23,6 +23,16 @@ "displayName": "Normal", "description": "Properties related to configuring surface normal." }, + { + "id": "detailLayerGroup", + "displayName": "Detail Layer", + "description": "Properties for Fine Details Layer." + }, + { + "id": "detailUV", + "displayName": "Detail Layer UV", + "description": "Properties for modifying detail layer UV." + }, { "id": "occlusion", "displayName": "Occlusion", @@ -38,16 +48,6 @@ "displayName": "Wrinkle Layers", "description": "Properties for wrinkle maps to support morph animation, using vertex color blend weights." }, - { - "id": "detailLayerGroup", - "displayName": "Detail Layer", - "description": "Properties for Fine Details Layer." - }, - { - "id": "detailUV", - "displayName": "Detail Layer UV", - "description": "Properties for modifying detail layer UV." - }, { "id": "general", "displayName": "General Settings", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype index 5b6e5f30bc..c07eac3d47 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype @@ -57,11 +57,6 @@ "displayName": "Layer 1: Normal", "description": "Properties related to configuring surface normal." }, - { - "id": "layer1_clearCoat", - "displayName": "Layer 1: Clear Coat", - "description": "Properties for configuring gloss clear coat" - }, { "id": "layer1_occlusion", "displayName": "Layer 1: Occlusion", @@ -72,6 +67,11 @@ "displayName": "Layer 1: Emissive", "description": "Properties to add light emission, independent of other lights in the scene." }, + { + "id": "layer1_clearCoat", + "displayName": "Layer 1: Clear Coat", + "description": "Properties for configuring gloss clear coat" + }, { "id": "layer1_parallax", "displayName": "Layer 1: Displacement", @@ -110,11 +110,6 @@ "displayName": "Layer 2: Normal", "description": "Properties related to configuring surface normal." }, - { - "id": "layer2_clearCoat", - "displayName": "Layer 2: Clear Coat", - "description": "Properties for configuring gloss clear coat" - }, { "id": "layer2_occlusion", "displayName": "Layer 2: Occlusion", @@ -125,6 +120,11 @@ "displayName": "Layer 2: Emissive", "description": "Properties to add light emission, independent of other lights in the scene." }, + { + "id": "layer2_clearCoat", + "displayName": "Layer 2: Clear Coat", + "description": "Properties for configuring gloss clear coat" + }, { "id": "layer2_parallax", "displayName": "Layer 2: Displacement", @@ -163,11 +163,6 @@ "displayName": "Layer 3: Normal", "description": "Properties related to configuring surface normal." }, - { - "id": "layer3_clearCoat", - "displayName": "Layer 3: Clear Coat", - "description": "Properties for configuring gloss clear coat" - }, { "id": "layer3_occlusion", "displayName": "Layer 3: Occlusion", @@ -178,6 +173,11 @@ "displayName": "Layer 3: Emissive", "description": "Properties to add light emission, independent of other lights in the scene." }, + { + "id": "layer3_clearCoat", + "displayName": "Layer 3: Clear Coat", + "description": "Properties for configuring gloss clear coat" + }, { "id": "layer3_parallax", "displayName": "Layer 3: Displacement", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index 0904302085..658aaeeee9 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -23,26 +23,11 @@ "displayName": "Specular Reflectance f0", "description": "The constant f0 represents the specular reflectance at normal incidence (Fresnel 0 Angle). Used to adjust reflectance of non-metal surfaces." }, - { - "id": "clearCoat", - "displayName": "Clear Coat", - "description": "Properties for configuring gloss clear coat" - }, { "id": "normal", "displayName": "Normal", "description": "Properties related to configuring surface normal." }, - { - "id": "opacity", - "displayName": "Opacity", - "description": "Properties for configuring the materials transparency." - }, - { - "id": "uv", - "displayName": "UVs", - "description": "Properties for configuring UV transforms." - }, { "id": "occlusion", "displayName": "Occlusion", @@ -53,15 +38,30 @@ "displayName": "Emissive", "description": "Properties to add light emission, independent of other lights in the scene." }, + { + "id": "subsurfaceScattering", + "displayName": "Subsurface Scattering", + "description": "Properties for configuring subsurface scattering effects." + }, + { + "id": "clearCoat", + "displayName": "Clear Coat", + "description": "Properties for configuring gloss clear coat" + }, { "id": "parallax", "displayName": "Displacement", "description": "Properties for parallax effect produced by a height map." }, { - "id": "subsurfaceScattering", - "displayName": "Subsurface Scattering", - "description": "Properties for configuring subsurface scattering effects." + "id": "opacity", + "displayName": "Opacity", + "description": "Properties for configuring the materials transparency." + }, + { + "id": "uv", + "displayName": "UVs", + "description": "Properties for configuring UV transforms." }, { // Note: this property group is used in the DiffuseGlobalIllumination pass, it is not read by the StandardPBR shader From f7e03a2f37b96ffb8ebd96994848f573838ea091 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 28 May 2021 16:48:24 -0500 Subject: [PATCH 349/811] Updating the README.md to account for the O3DE as an SDK changes (#1041) Moved the registration of the engine to the "Setting up new projects" section. The engine is no longer required to be registered in order to build it. --- README.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index e0442adc16..0c59837a62 100644 --- a/README.md +++ b/README.md @@ -118,11 +118,6 @@ If you have the Git credential manager core or other credential helpers installe ``` python\get_python.bat ``` - -1. While still within the repo folder, register the engine with this command: - ``` - scripts\o3de.bat register --this-engine - ``` 1. Configure the source into a solution using this command line, replacing and <3rdParty cache path> to a path you've created: ``` @@ -146,7 +141,11 @@ If you have the Git credential manager core or other credential helpers installe 1. This will compile after some time and binaries will be available in the build path you've specified -### Setting up new projects +### Setting up new projects +1. While still within the repo folder, register the engine with this command: + ``` + scripts\o3de.bat register --this-engine + ``` 1. Setup new projects using the `o3de create-project` command. In the 0.5 branch, the project directory must be a subdirectory in the repo folder. ``` \scripts\o3de.bat create-project --project-path @@ -160,10 +159,10 @@ If you have the Git credential manager core or other credential helpers installe cmake -B -S -G "Visual Studio 16" -DLY_3RDPARTY_PATH=<3rdParty cache path> // For the 0.5 branch, you must build a new Editor for each project: - cmake --build --target Editor --config profile -- /m + cmake --build --target .GameLauncher Editor --config profile -- /m // For all other branches, just build the project: - cmake --build --target --config profile -- /m + cmake --build --target .GameLauncher --config profile -- /m ``` For a tutorial on project configuration, see [Creating Projects Using the Command Line](https://docs.o3de.org/docs/welcome-guide/get-started/project-config/creating-projects-using-cli) in the documentation. From 147f0084a8e4c0f8a88535e00e7bef300888ecdd Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Fri, 28 May 2021 15:47:25 -0700 Subject: [PATCH 350/811] Removed subsurface scattering and transmission features from StandardPBR.materialtype. ATOM-4120 Stabilize Standard PBR Regarding Subsurface and Translucency --- .../Materials/Types/EnhancedPBR.materialtype | 2 +- ...te.lua => EnhancedPBR_SubsurfaceState.lua} | 0 .../Assets/Materials/Types/Skin.materialtype | 2 +- .../Materials/Types/StandardPBR.materialtype | 207 ------------------ .../Materials/Types/StandardPBR_Common.azsli | 19 -- .../Types/StandardPBR_ForwardPass.azsl | 32 +-- .../Features/PBR/Lighting/LightingData.azsli | 8 +- .../PBR/Lighting/StandardLighting.azsli | 1 - .../PBR/Surfaces/StandardSurface.azsli | 2 +- .../atom_feature_common_asset_files.cmake | 2 +- 10 files changed, 15 insertions(+), 260 deletions(-) rename Gems/Atom/Feature/Common/Assets/Materials/Types/{StandardPBR_SubsurfaceState.lua => EnhancedPBR_SubsurfaceState.lua} (100%) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index 79c4ca3cc3..ff0c4c59da 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -1636,7 +1636,7 @@ { "type": "Lua", "args": { - "file": "StandardPBR_SubsurfaceState.lua" + "file": "EnhancedPBR_SubsurfaceState.lua" } }, { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_SubsurfaceState.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_SubsurfaceState.lua similarity index 100% rename from Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_SubsurfaceState.lua rename to Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_SubsurfaceState.lua diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype index 9ead0376bb..dfe2fad60f 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.materialtype @@ -1080,7 +1080,7 @@ { "type": "Lua", "args": { - "file": "StandardPBR_SubsurfaceState.lua" + "file": "EnhancedPBR_SubsurfaceState.lua" } }, { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index 658aaeeee9..2d94f66edf 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -38,11 +38,6 @@ "displayName": "Emissive", "description": "Properties to add light emission, independent of other lights in the scene." }, - { - "id": "subsurfaceScattering", - "displayName": "Subsurface Scattering", - "description": "Properties for configuring subsurface scattering effects." - }, { "id": "clearCoat", "displayName": "Clear Coat", @@ -981,183 +976,6 @@ } } ], - "subsurfaceScattering": [ - { - "id": "enableSubsurfaceScattering", - "displayName": "Subsurface Scattering", - "description": "Enable subsurface scattering feature, this will disable metallic and parallax mapping property due to incompatibility", - "type": "Bool", - "defaultValue": false, - "connection": { - "type": "ShaderOption", - "id": "o_enableSubsurfaceScattering" - } - }, - { - "id": "subsurfaceScatterFactor", - "displayName": " Factor", - "description": "Strength factor for scaling percentage of subsurface scattering effect applied", - "type": "float", - "defaultValue": 1.0, - "min": 0.0, - "max": 1.0, - "connection": { - "type": "ShaderInput", - "id": "m_subsurfaceScatteringFactor" - } - }, - { - "id": "influenceMap", - "displayName": " Influence Map", - "description": "Texture for controlling the strength of subsurface scattering", - "type": "Image", - "connection": { - "type": "ShaderInput", - "id": "m_subsurfaceScatteringInfluenceMap" - } - }, - { - "id": "useInfluenceMap", - "displayName": " Use Influence Map", - "description": "Whether to use the influence map.", - "type": "Bool", - "defaultValue": true - }, - { - "id": "influenceMapUv", - "displayName": " UV", - "description": "Influence map UV set", - "type": "Enum", - "enumIsUv": true, - "defaultValue": "Tiled", - "connection": { - "type": "ShaderInput", - "id": "m_subsurfaceScatteringInfluenceMapUvIndex" - } - }, - { - "id": "scatterColor", - "displayName": " Scatter color", - "description": "Color of volume light traveled through", - "type": "Color", - "defaultValue": [ 1.0, 0.27, 0.13 ] - }, - { - "id": "scatterDistance", - "displayName": " Scatter distance", - "description": "How far light traveled inside the volume", - "type": "float", - "defaultValue": 8, - "min": 0.0, - "softMax": 20.0 - }, - { - "id": "quality", - "displayName": " Quality", - "description": "How much percent of sample will be used for each pixel, more samples improve quality and reduce artifacts, especially when the scatter distance is relatively large, but slow down computation time, 1.0 = full set 200 samples per pixel", - "type": "float", - "defaultValue": 0.4, - "min": 0.2, - "max": 1.0, - "connection": { - "type": "ShaderInput", - "id": "m_subsurfaceScatteringQuality" - } - }, - { - "id": "transmissionMode", - "displayName": "Transmission", - "description": "Algorithm used for calculating transmission", - "type": "Enum", - "enumValues": [ "None", "ThickObject", "ThinObject" ], - "defaultValue": "None", - "connection": { - "type": "ShaderOption", - "id": "o_transmission_mode" - } - }, - { - "id": "thickness", - "displayName": " Thickness", - "description": "Normalized global thickness, the maxima between this value (multiplied by thickness map if enabled) and thickness from shadow map (if applicable) will be used as final thickness of pixel", - "type": "float", - "defaultValue": 0.5, - "min": 0.0, - "max": 1.0 - }, - { - "id": "thicknessMap", - "displayName": " Thickness Map", - "description": "Texture for controlling per pixel thickness", - "type": "Image", - "connection": { - "type": "ShaderInput", - "id": "m_transmissionThicknessMap" - } - }, - { - "id": "useThicknessMap", - "displayName": " Use Thickness Map", - "description": "Whether to use the thickness map", - "type": "Bool", - "defaultValue": true - }, - { - "id": "thicknessMapUv", - "displayName": " UV", - "description": "Thickness map UV set", - "type": "Enum", - "enumIsUv": true, - "defaultValue": "Tiled", - "connection": { - "type": "ShaderInput", - "id": "m_transmissionThicknessMapUvIndex" - } - }, - { - "id": "transmissionTint", - "displayName": " Transmission Tint", - "description": "Color of the volume light traveling through", - "type": "Color", - "defaultValue": [ 1.0, 0.8, 0.6 ] - }, - { - "id": "transmissionPower", - "displayName": " Power", - "description": "How much transmitted light scatter radially ", - "type": "float", - "defaultValue": 6.0, - "min": 0.0, - "softMax": 20.0 - }, - { - "id": "transmissionDistortion", - "displayName": " Distortion", - "description": "How much light direction distorted towards surface normal", - "type": "float", - "defaultValue": 0.1, - "min": 0.0, - "max": 1.0 - }, - { - "id": "transmissionAttenuation", - "displayName": " Attenuation", - "description": "How fast transmitted light fade with thickness", - "type": "float", - "defaultValue": 4.0, - "min": 0.0, - "softMax": 20.0 - }, - { - "id": "transmissionScale", - "displayName": " Scale", - "description": "Strength of transmission", - "type": "float", - "defaultValue": 3.0, - "min": 0.0, - "softMax": 20.0 - } - ], "irradiance": [ // Note: this property group is used in the DiffuseGlobalIllumination pass and not by the main forward shader { @@ -1261,25 +1079,6 @@ "nitMinMax": [0.001, 100000.0] } }, - { - // Preprocess & build parameter set for subsurface scattering and translucency - "type": "HandleSubsurfaceScatteringParameters", - "args": { - "mode": "subsurfaceScattering.transmissionMode", - "scale": "subsurfaceScattering.transmissionScale", - "power": "subsurfaceScattering.transmissionPower", - "distortion": "subsurfaceScattering.transmissionDistortion", - "attenuation": "subsurfaceScattering.transmissionAttenuation", - "tintColor": "subsurfaceScattering.transmissionTint", - "thickness": "subsurfaceScattering.thickness", - "enabled": "subsurfaceScattering.enableSubsurfaceScattering", - "scatterDistanceColor": "subsurfaceScattering.scatterColor", - "scatterDistanceIntensity": "subsurfaceScattering.scatterDistance", - "scatterDistanceShaderInput": "m_scatterDistance", - "parametersShaderInput": "m_transmissionParams", - "tintThickenssShaderInput": "m_transmissionTintThickness" - } - }, { "type": "UseTexture", "args": { @@ -1364,12 +1163,6 @@ "file": "StandardPBR_Roughness.lua" } }, - { - "type": "Lua", - "args": { - "file": "StandardPBR_SubsurfaceState.lua" - } - }, { "type": "Lua", "args": { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli index 87562c3d20..f339642a4d 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli @@ -73,25 +73,6 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial MagFilter = Linear; MipFilter = Linear; }; - - // Parameters for subsurface scattering - float m_subsurfaceScatteringFactor; - float m_subsurfaceScatteringQuality; - float3 m_scatterDistance; - Texture2D m_subsurfaceScatteringInfluenceMap; - uint m_subsurfaceScatteringInfluenceMapUvIndex; - - // Parameters for transmission - - // Elements of m_transmissionParams: - // Thick object mode: (attenuation coefficient, power, distortion, scale) - // Thin object mode: (float3 scatter distance, scale) - float4 m_transmissionParams; - - // (float3 TintColor, thickness) - float4 m_transmissionTintThickness; - Texture2D m_transmissionThicknessMap; - uint m_transmissionThicknessMapUvIndex; } // Callback function for ParallaxMapping.azsli diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl index 286b9b23df..b221ee0a33 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -47,13 +47,6 @@ COMMON_OPTIONS_EMISSIVE() // Alpha #include "MaterialInputs/AlphaInput.azsli" -// Subsurface -#include "MaterialInputs/SubsurfaceInput.azsli" - -// Transmission -#include "MaterialInputs/TransmissionInput.azsli" - - // ---------- Vertex Shader ---------- struct VSInput @@ -113,7 +106,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3 tangents[UvSetCount] = { IN.m_tangent.xyz, IN.m_tangent.xyz }; float3 bitangents[UvSetCount] = { IN.m_bitangent.xyz, IN.m_bitangent.xyz }; - if ((o_parallax_feature_enabled && !o_enableSubsurfaceScattering) || o_normal_useTexture || (o_clearCoat_enabled && o_clearCoat_normal_useTexture)) + if (ShouldHandleParallax() || o_normal_useTexture || (o_clearCoat_enabled && o_clearCoat_normal_useTexture)) { PrepareGeneratedTangent(IN.m_normal, IN.m_worldPosition, isFrontFace, IN.m_uv, UvSetCount, tangents, bitangents); } @@ -124,7 +117,6 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float bool displacementIsClipped = false; - // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled if(ShouldHandleParallax()) { @@ -174,12 +166,8 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Metallic ------- - float metallic = 0; - if(!o_enableSubsurfaceScattering) // If subsurface scattering is enabled skip texture lookup for metallic, as this quantity won't be used anyway - { - float2 metallicUv = IN.m_uv[MaterialSrg::m_metallicMapUvIndex]; - metallic = GetMetallicInput(MaterialSrg::m_metallicMap, MaterialSrg::m_sampler, metallicUv, MaterialSrg::m_metallicFactor, o_metallic_useTexture); - } + float2 metallicUv = IN.m_uv[MaterialSrg::m_metallicMapUvIndex]; + float metallic = GetMetallicInput(MaterialSrg::m_metallicMap, MaterialSrg::m_sampler, metallicUv, MaterialSrg::m_metallicFactor, o_metallic_useTexture); // ------- Specular ------- @@ -195,11 +183,6 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float MaterialSrg::m_roughnessLowerBound, MaterialSrg::m_roughnessUpperBound, o_roughness_useTexture); surface.CalculateRoughnessA(); - // ------- Subsurface ------- - - float surfaceScatteringFactor = 0.0f; - surface.transmission.InitializeToZero(); - // ------- Lighting Data ------- LightingData lightingData; @@ -271,7 +254,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float ApplyIBL(surface, lightingData); // Finalize Lighting - lightingData.FinalizeLighting(surface.transmission.tint); + lightingData.FinalizeLighting(); if (o_opacity_mode == OpacityMode::Blended || o_opacity_mode == OpacityMode::TintedTransparent) @@ -312,13 +295,6 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float lightingOutput.m_diffuseColor.rgb += lightingOutput.m_specularColor.rgb; // add specular lightingOutput.m_specularColor.rgb = baseColor * (1.0 - lightingOutput.m_diffuseColor.w); } - else - { - // Pack factor and quality, drawback: because of precision limit of float16 cannot represent exact 1, maximum representable value is 0.9961 - uint factorAndQuality = dot(round(float2(saturate(surfaceScatteringFactor), MaterialSrg::m_subsurfaceScatteringQuality) * 255), float2(256, 1)); - lightingOutput.m_diffuseColor.w = factorAndQuality * (o_enableSubsurfaceScattering ? 1.0 : -1.0); - lightingOutput.m_scatterDistance = MaterialSrg::m_scatterDistance; - } return lightingOutput; } diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lighting/LightingData.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lighting/LightingData.azsli index 37cae0acb1..e37aa55c09 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lighting/LightingData.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lighting/LightingData.azsli @@ -54,6 +54,7 @@ class LightingData void Init(float3 positionWS, float3 normal, float roughnessLinear); void CalculateMultiscatterCompensation(float3 specularF0, bool enabled); + void FinalizeLighting(); void FinalizeLighting(float3 transmissionTint); }; @@ -80,10 +81,15 @@ void LightingData::CalculateMultiscatterCompensation(float3 specularF0, bool ena multiScatterCompensation = GetMultiScatterCompensation(specularF0, brdf, enabled); } -void LightingData::FinalizeLighting(float3 transmissionTint) +void LightingData::FinalizeLighting() { specularLighting *= specularOcclusion; specularLighting += emissiveLighting; +} + +void LightingData::FinalizeLighting(float3 transmissionTint) +{ + FinalizeLighting(); // Transmitted light if(o_transmission_mode != TransmissionMode::None) diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lighting/StandardLighting.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lighting/StandardLighting.azsli index 45aabeede4..f690163a58 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lighting/StandardLighting.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lighting/StandardLighting.azsli @@ -75,7 +75,6 @@ struct PbrLightingOutput float4 m_albedo; float4 m_specularF0; float4 m_normal; - float3 m_scatterDistance; }; diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Surfaces/StandardSurface.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Surfaces/StandardSurface.azsli index 1a74a68e96..bc4e41d2c2 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Surfaces/StandardSurface.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Surfaces/StandardSurface.azsli @@ -20,7 +20,7 @@ class Surface { ClearCoatSurfaceData clearCoat; - TransmissionSurfaceData transmission; + TransmissionSurfaceData transmission; // This is not actually used for Standard PBR, but must be present for common lighting code to compile // ------- BasePbrSurfaceData ------- diff --git a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake index 841cdf67c8..359c0b9b20 100644 --- a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake +++ b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake @@ -23,6 +23,7 @@ set(FILES Materials/Types/EnhancedPBR_ForwardPass_EDS.shader Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl Materials/Types/EnhancedPBR_Shadowmap_WithPS.shader + Materials/Types/EnhancedPBR_SubsurfaceState.lua Materials/Types/Skin.azsl Materials/Types/Skin.materialtype Materials/Types/Skin.shader @@ -61,7 +62,6 @@ set(FILES Materials/Types/StandardPBR_ShaderEnable.lua Materials/Types/StandardPBR_Shadowmap_WithPS.azsl Materials/Types/StandardPBR_Shadowmap_WithPS.shader - Materials/Types/StandardPBR_SubsurfaceState.lua Materials/Types/MaterialInputs/AlphaInput.azsli Materials/Types/MaterialInputs/BaseColorInput.azsli Materials/Types/MaterialInputs/ClearCoatInput.azsli From 75cb293b2a0309335d9b7aea78ca9f0cd61fa41a Mon Sep 17 00:00:00 2001 From: hershey5045 <43485729+hershey5045@users.noreply.github.com> Date: Fri, 28 May 2021 16:40:44 -0700 Subject: [PATCH 351/811] Png fix for vulkan rhi (#962) * Add supported formats for pngs in frame capture system. Add conversion logic from bgra to rgba. --- .../Source/FrameCaptureSystemComponent.cpp | 65 ++++++++++++++++--- 1 file changed, 57 insertions(+), 8 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/FrameCaptureSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/FrameCaptureSystemComponent.cpp index 90499be8b8..f8c1258fc0 100644 --- a/Gems/Atom/Feature/Common/Code/Source/FrameCaptureSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/FrameCaptureSystemComponent.cpp @@ -21,6 +21,8 @@ #include #include +#include +#include #include #include @@ -55,6 +57,43 @@ namespace AZ FrameCaptureOutputResult PngFrameCaptureOutput( const AZStd::string& outputFilePath, const AZ::RPI::AttachmentReadback::ReadbackResult& readbackResult) { + AZStd::shared_ptr> buffer = readbackResult.m_dataBuffer; + + // convert bgra to rgba by swapping channels + const int numChannels = AZ::RHI::GetFormatComponentCount(readbackResult.m_imageDescriptor.m_format); + if (readbackResult.m_imageDescriptor.m_format == RHI::Format::B8G8R8A8_UNORM) + { + buffer = AZStd::make_shared>(readbackResult.m_dataBuffer->size()); + AZStd::copy(readbackResult.m_dataBuffer->begin(), readbackResult.m_dataBuffer->end(), buffer->begin()); + + AZ::JobCompletion jobCompletion; + const int numThreads = 8; + const int numPixelsPerThread = buffer->size() / numChannels / numThreads; + for (int i = 0; i < numThreads; ++i) + { + int startPixel = i * numPixelsPerThread; + + AZ::Job* job = AZ::CreateJobFunction( + [&, startPixel, numPixelsPerThread]() + { + for (int pixelOffset = 0; pixelOffset < numPixelsPerThread; ++pixelOffset) + { + if (startPixel * numChannels + numChannels < buffer->size()) + { + AZStd::swap( + buffer->data()[(startPixel + pixelOffset) * numChannels], + buffer->data()[(startPixel + pixelOffset) * numChannels + 2] + ); + } + } + }, true, nullptr); + + job->SetDependent(&jobCompletion); + job->Start(); + } + jobCompletion.StartAndWaitForCompletion(); + } + using namespace OIIO; AZStd::unique_ptr out = ImageOutput::create(outputFilePath.c_str()); if (out) @@ -62,13 +101,13 @@ namespace AZ ImageSpec spec( readbackResult.m_imageDescriptor.m_size.m_width, readbackResult.m_imageDescriptor.m_size.m_height, - AZ::RHI::GetFormatComponentCount(readbackResult.m_imageDescriptor.m_format) + numChannels ); spec.attribute("png:compressionLevel", r_pngCompressionLevel); if (out->open(outputFilePath.c_str(), spec)) { - out->write_image(TypeDesc::UINT8, readbackResult.m_dataBuffer->data()); + out->write_image(TypeDesc::UINT8, buffer->data()); out->close(); return FrameCaptureOutputResult{FrameCaptureResult::Success, AZStd::nullopt}; } @@ -460,13 +499,23 @@ namespace AZ #if defined(OPEN_IMAGE_IO_ENABLED) else if (extension == "png") { - AZStd::string folderPath; - AzFramework::StringFunc::Path::GetFolderPath(m_outputFilePath.c_str(), folderPath); - AZ::IO::SystemFile::CreateDir(folderPath.c_str()); + if (readbackResult.m_imageDescriptor.m_format == RHI::Format::R8G8B8A8_UNORM || + readbackResult.m_imageDescriptor.m_format == RHI::Format::B8G8R8A8_UNORM) + { + AZStd::string folderPath; + AzFramework::StringFunc::Path::GetFolderPath(m_outputFilePath.c_str(), folderPath); + AZ::IO::SystemFile::CreateDir(folderPath.c_str()); - const auto frameCaptureResult = PngFrameCaptureOutput(m_outputFilePath, readbackResult); - m_result = frameCaptureResult.m_result; - m_latestCaptureInfo = frameCaptureResult.m_errorMessage.value_or(""); + const auto frameCaptureResult = PngFrameCaptureOutput(m_outputFilePath, readbackResult); + m_result = frameCaptureResult.m_result; + m_latestCaptureInfo = frameCaptureResult.m_errorMessage.value_or(""); + } + else + { + m_latestCaptureInfo = AZStd::string::format( + "Can't save image with format %s to a png file", RHI::ToString(readbackResult.m_imageDescriptor.m_format)); + m_result = FrameCaptureResult::UnsupportedFormat; + } } #endif else From ab45ea7efa3cacea1e0e809a3bc8e638bf183900 Mon Sep 17 00:00:00 2001 From: mnaumov Date: Fri, 28 May 2021 17:15:20 -0700 Subject: [PATCH 352/811] [ATOM-15631] First pass on exposing Display Mapper properties to Behavior Context --- .../Common/Code/3rdParty/ACES/ACES/Aces.h | 1 + .../DisplayMapperConfigurationDescriptor.h | 8 ++- .../DisplayMapperConfigurationDescriptor.cpp | 26 +++++++++ .../DisplayMapper/DisplayMapperComponentBus.h | 55 +++++++++++++++++++ .../DisplayMapper/DisplayMapperComponent.cpp | 1 - .../DisplayMapperComponentController.cpp | 33 +++++++++++ .../DisplayMapperComponentController.h | 10 ++++ .../EditorDisplayMapperComponent.cpp | 13 ++++- ...egration_commonfeatures_public_files.cmake | 1 + 9 files changed, 142 insertions(+), 6 deletions(-) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h diff --git a/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.h b/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.h index 472ef160be..cd9dca68e3 100644 --- a/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.h +++ b/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.h @@ -177,4 +177,5 @@ namespace AZ } // namespace Render AZ_TYPE_INFO_SPECIALIZE(Render::DisplayMapperOperationType, "{41CA80B1-9E0D-41FB-A235-9638D2A905A5}"); + AZ_TYPE_INFO_SPECIALIZE(Render::OutputDeviceTransformType, "{B94085B7-C0D4-466A-A791-188A4559EC8D}"); } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperConfigurationDescriptor.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperConfigurationDescriptor.h index 4dc090b831..22c866447e 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperConfigurationDescriptor.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperConfigurationDescriptor.h @@ -12,11 +12,13 @@ #pragma once +#include + #include + #include #include #include -#include namespace AZ { @@ -33,6 +35,7 @@ namespace AZ AZ_TYPE_INFO(AcesParameterOverrides, "{3EE8C0D4-3792-46C0-B91C-B89A81C36B91}"); static void Reflect(ReflectContext* context); + // Load preconfigured preset for specific ODT mode defined by m_preset void LoadPreset(); // When enabled allows parameter overrides for ACES configuration @@ -98,6 +101,5 @@ namespace AZ DisplayMapperConfigurationDescriptor m_config; }; - - } // namespace RPI + } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperConfigurationDescriptor.cpp b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperConfigurationDescriptor.cpp index e91e125b40..0858381fc5 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperConfigurationDescriptor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperConfigurationDescriptor.cpp @@ -23,6 +23,15 @@ namespace AZ { if (auto serializeContext = azrtti_cast(context)) { + serializeContext->Enum() + ->Version(0) + ->Value("48Nits", OutputDeviceTransformType::OutputDeviceTransformType_48Nits) + ->Value("1000Nits", OutputDeviceTransformType::OutputDeviceTransformType_1000Nits) + ->Value("2000Nits", OutputDeviceTransformType::OutputDeviceTransformType_2000Nits) + ->Value("4000Nits", OutputDeviceTransformType::OutputDeviceTransformType_4000Nits) + ->Value("NumOutputDeviceTransformTypes", OutputDeviceTransformType::NumOutputDeviceTransformTypes) + ; + serializeContext->Class() ->Version(0) ->Field("OverrideDefaults", &AcesParameterOverrides::m_overrideDefaults) @@ -38,6 +47,22 @@ namespace AZ ->Field("SurroundGamma", &AcesParameterOverrides::m_surroundGamma) ->Field("Gamma", &AcesParameterOverrides::m_gamma); } + + if (auto behaviorContext = azrtti_cast(context)) + { + behaviorContext->Class("AcesParameterOverrides") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "render") + ->Attribute(AZ::Script::Attributes::Module, "render") + ->Constructor() + ->Method("LoadPreset", &AcesParameterOverrides::LoadPreset) + ->Property("overrideDefaults", BehaviorValueProperty(&AcesParameterOverrides::m_overrideDefaults)) + ->Property("preset", BehaviorValueProperty(&AcesParameterOverrides::m_preset)) + ->Property("alterSurround", BehaviorValueProperty(&AcesParameterOverrides::m_alterSurround)) + ->Property("applyDesaturation", BehaviorValueProperty(&AcesParameterOverrides::m_applyDesaturation)) + ->Property("applyCATD60toD65", BehaviorValueProperty(&AcesParameterOverrides::m_applyCATD60toD65)) + ; + } } void AcesParameterOverrides::LoadPreset() @@ -76,6 +101,7 @@ namespace AZ ->Field("OperationType", &DisplayMapperConfigurationDescriptor::m_operationType) ->Field("LdrGradingLutEnabled", &DisplayMapperConfigurationDescriptor::m_ldrGradingLutEnabled) ->Field("LdrColorGradingLut", &DisplayMapperConfigurationDescriptor::m_ldrColorGradingLut) + ->Field("AcesParameterOverrides", &DisplayMapperConfigurationDescriptor::m_acesParameterOverrides) ; } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h new file mode 100644 index 0000000000..af57b69d3b --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h @@ -0,0 +1,55 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include +#include +#include + +namespace AZ +{ + namespace Render + { + struct AcesParameterOverrides; + + //! DisplayMapperComponentRequests provides an interface to request operations on a DisplayMapperComponent + class DisplayMapperComponentRequests + : public ComponentBus + { + public: + //! Load preconfigured preset for specific ODT mode + virtual void LoadPreset(OutputDeviceTransformType preset) = 0; + //! Set display mapper type + virtual void SetDisplayMapperOperationType(DisplayMapperOperationType displayMapperOperationType) = 0; + //! Set custom ACES parameters for ACES mapping, display mapper must be set to Aces to see the difference + virtual void SetAcesParameterOverrides(const AcesParameterOverrides& parameterOverrides) = 0; + }; + using DisplayMapperComponentRequestBus = EBus; + + //! DisplayMapperComponent can send out notifications on the DisplayMapperComponentNotifications + class DisplayMapperComponentNotifications : public ComponentBus + { + public: + //! Notifies that display mapper type changed + virtual void OntDisplayMapperOperationTypeUpdated([[maybe_unused]] const DisplayMapperOperationType& displayMapperOperationType) + { + } + + //! Notifies that ACES parameter overrides changed + virtual void OnAcesParameterOverridesUpdated([[maybe_unused]] const AcesParameterOverrides& acesParameterOverrides) + { + } + }; + using DisplayMapperComponentNotificationBus = EBus; + + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponent.cpp index 9642072cd2..b8d8336c30 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponent.cpp @@ -39,6 +39,5 @@ namespace AZ ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common); } } - } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp index 0e283199e7..7831c0a4c6 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp @@ -76,6 +76,39 @@ namespace AZ return m_configuration; } + void DisplayMapperComponentController::LoadPreset(OutputDeviceTransformType preset) + { + AcesParameterOverrides propertyOverrides; + propertyOverrides.m_preset = preset; + propertyOverrides.m_overrideDefaults = true; + propertyOverrides.LoadPreset(); + SetAcesParameterOverrides(propertyOverrides); + } + + void DisplayMapperComponentController::SetDisplayMapperOperationType(DisplayMapperOperationType displayMapperOperationType) + { + if (m_configuration.m_displayMapperOperation != displayMapperOperationType) + { + m_configuration.m_displayMapperOperation = displayMapperOperationType; + OnConfigChanged(); + DisplayMapperComponentNotificationBus::Broadcast( + &DisplayMapperComponentNotificationBus::Handler::OntDisplayMapperOperationTypeUpdated, + m_configuration.m_displayMapperOperation); + } + } + + void DisplayMapperComponentController::SetAcesParameterOverrides(const AcesParameterOverrides& parameterOverrides) + { + m_configuration.m_acesParameterOverrides = parameterOverrides; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + DisplayMapperComponentNotificationBus::Broadcast( + &DisplayMapperComponentNotificationBus::Handler::OnAcesParameterOverridesUpdated, + m_configuration.m_acesParameterOverrides); + } + void DisplayMapperComponentController::OnConfigChanged() { // Register the configuration with the AcesDisplayMapperFeatureProcessor for this scene. diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.h index 3cc6a7e5d9..efa2070828 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.h @@ -12,10 +12,12 @@ #pragma once + #include #include #include +#include #include #include @@ -24,7 +26,10 @@ namespace AZ { namespace Render { + struct AcesParameterOverrides; + class DisplayMapperComponentController final + : DisplayMapperComponentRequestBus::Handler { public: friend class EditorDisplayMapperComponent; @@ -43,6 +48,11 @@ namespace AZ void SetConfiguration(const DisplayMapperComponentConfig& config); const DisplayMapperComponentConfig& GetConfiguration() const; + //! DisplayMapperComponentRequestBus::Handler overrides... + void LoadPreset(OutputDeviceTransformType preset) override; + void SetDisplayMapperOperationType(DisplayMapperOperationType displayMapperOperationType) override; + void SetAcesParameterOverrides(const AcesParameterOverrides& parameterOverrides) override; + private: AZ_DISABLE_COPY(DisplayMapperComponentController); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp index 64cd450940..aadb0cc22b 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp @@ -76,23 +76,32 @@ namespace AZ Edit::UIHandlers::Default, &AcesParameterOverrides::m_cinemaLimitsBlack, "Cinema Limit (black)", "Reference black luminance value") + ->Attribute(AZ::Edit::Attributes::Min, 0.02f) + ->Attribute(AZ::Edit::Attributes::Max, &AcesParameterOverrides::m_cinemaLimitsWhite) ->DataElement( Edit::UIHandlers::Default, &AcesParameterOverrides::m_cinemaLimitsWhite, "Cinema Limit (white)", "Reference white luminance value") + ->Attribute(AZ::Edit::Attributes::Min, &AcesParameterOverrides::m_cinemaLimitsBlack) + ->Attribute(AZ::Edit::Attributes::Max, 4000) ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->DataElement( Edit::UIHandlers::Vector2, &AcesParameterOverrides::m_minPoint, "Min Point (luminance)", "Linear extension below this") + ->Attribute(AZ::Edit::Attributes::Min, 0.002f) + ->Attribute(AZ::Edit::Attributes::Max, &AcesParameterOverrides::m_midPoint) ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->DataElement( - Edit::UIHandlers::Vector2, &AcesParameterOverrides::m_midPoint, "Mid Point (luminance)", - "Middle gray") + Edit::UIHandlers::Vector2, &AcesParameterOverrides::m_midPoint, "Mid Point (luminance)", "Middle gray") + ->Attribute(AZ::Edit::Attributes::Min, &AcesParameterOverrides::m_minPoint) + ->Attribute(AZ::Edit::Attributes::Max, &AcesParameterOverrides::m_maxPoint) ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->DataElement( Edit::UIHandlers::Vector2, &AcesParameterOverrides::m_maxPoint, "Max Point (luminance)", "Linear extension above this") + ->Attribute(AZ::Edit::Attributes::Min, &AcesParameterOverrides::m_midPoint) + ->Attribute(AZ::Edit::Attributes::Max, 4000) ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->DataElement( diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_public_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_public_files.cmake index 7b8d0a6e21..31a90e7ceb 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_public_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_public_files.cmake @@ -36,6 +36,7 @@ set(FILES Include/AtomLyIntegration/CommonFeatures/PostProcess/Bloom/BloomComponentConfig.h Include/AtomLyIntegration/CommonFeatures/PostProcess/DepthOfField/DepthOfFieldBus.h Include/AtomLyIntegration/CommonFeatures/PostProcess/DepthOfField/DepthOfFieldComponentConfig.h + Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentConfig.h Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentConstants.h Include/AtomLyIntegration/CommonFeatures/PostProcess/ExposureControl/ExposureControlBus.h From ddbed2f222ec279ef5472df56cc305ef8b29df72 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Fri, 28 May 2021 17:31:33 -0700 Subject: [PATCH 353/811] Sorting occlusion planes. --- .../RPI/Code/Source/RPI.Public/Culling.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index 7bed2d3232..e105f7bca5 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -480,8 +480,33 @@ namespace AZ MaskedOcclusionCulling* maskedOcclusionCulling = m_occlusionCullingPlanes.empty() ? nullptr : view.GetMaskedOcclusionCulling(); if (maskedOcclusionCulling) { + // frustum cull and sort the occlusion planes by view space distance, front-to-back + using OccluderEntry = AZStd::pair; + AZStd::vector visibleOccluders; for (const AZ::Transform& transform : m_occlusionCullingPlanes) { + Aabb occluderAabb = Aabb::CreateCenterHalfExtents(transform.GetTranslation(), AZ::Vector3(AZ::Vector2(transform.GetUniformScale() / 2.0f))); + occluderAabb.SetMin(transform.TransformPoint(occluderAabb.GetMin())); + occluderAabb.SetMax(transform.TransformPoint(occluderAabb.GetMax())); + if (ShapeIntersection::Contains(frustum, occluderAabb)) + { + // occluder is visible, compute view space distance and add to list + float depth = (view.GetWorldToViewMatrix() * occluderAabb.GetMin()).GetZ(); + depth = AZStd::min(depth, (view.GetWorldToViewMatrix() * occluderAabb.GetMax()).GetZ()); + + visibleOccluders.push_back(AZStd::make_pair(transform, depth)); + } + } + + AZStd::sort(visibleOccluders.begin(), visibleOccluders.end(), [](const OccluderEntry& LHS, const OccluderEntry& RHS) + { + return LHS.second < RHS.second; + }); + + for (const OccluderEntry& occluder : visibleOccluders) + { + const AZ::Transform& transform = occluder.first; + // find the corners of the plane static const Vector3 BL = Vector3(-0.5f, -0.5f, 0.0f); static const Vector3 BR = Vector3(0.5f, -0.5f, 0.0f); From 50a9e94eca9d5cc68567c30cfe3142b50dee5e58 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 28 May 2021 18:28:29 -0700 Subject: [PATCH 354/811] Fix old method call (#1049) --- .../Code/Source/RayTracing/RayTracingFeatureProcessor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp index f51fa4b81b..10c7c2d378 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp @@ -234,7 +234,7 @@ namespace AZ { AZ::Transform meshTransform = transformFeatureProcessor->GetTransformForId(TransformServiceFeatureProcessorInterface::ObjectId(mesh.first)); AZ::Transform noScaleTransform = meshTransform; - noScaleTransform.ExtractScale(); + noScaleTransform.ExtractUniformScale(); AZ::Matrix3x3 rotationMatrix = Matrix3x3::CreateFromTransform(noScaleTransform); rotationMatrix = rotationMatrix.GetInverseFull().GetTranspose(); From 74ec7a362b25cd55d9429142188892e1cbe937ba Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Fri, 28 May 2021 23:24:51 -0700 Subject: [PATCH 355/811] Update Android Project Generation to support AGP 4.2.0, Cmake 3.20, and newer versions of NDK&SDK - build.gradle format updates for newer Android Gradle Plugin - Remove hard coded Android Gradle Plugin version 3.6.4 to be passed in from command args - Set Android Gradle Plugin min version 4.2.0 in order to support Min CMake version 3.20 - Add ability to use the android sdk to install missing components if needed rather than doing it externally - Removed argument to pass in the NDK folder to use the android, use the android-sdk instead. Can request specific NDK versions if possible - Android Gradle Plugin has dependencies by version and is being managed - More defaults based on tools on path, agp version made possible so they are no longer needed in the command args --- .../Android/ProjectBuilder/build.gradle.in | 4 +- .../ProjectBuilder/local.properties.in | 1 - .../ProjectBuilder/root.build.gradle.in | 7 +- .../Tools/Platform/Android/android_support.py | 615 +++++++++--------- .../Android/generate_android_project.py | 164 +++-- .../unit_test_generate_android_project.py | 114 ---- cmake/Tools/common.py | 37 +- .../build/Platform/Android/build_config.json | 6 +- .../build/Platform/Android/gradle_windows.cmd | 39 +- scripts/build/Platform/Android/pipeline.json | 4 +- 10 files changed, 490 insertions(+), 501 deletions(-) diff --git a/Code/Tools/Android/ProjectBuilder/build.gradle.in b/Code/Tools/Android/ProjectBuilder/build.gradle.in index 66f58294ab..5980984516 100644 --- a/Code/Tools/Android/ProjectBuilder/build.gradle.in +++ b/Code/Tools/Android/ProjectBuilder/build.gradle.in @@ -15,14 +15,14 @@ android { ${SIGNING_CONFIGS} compileSdkVersion sdkVer buildToolsVersion buildToolsVer - + ndkVersion ndkPlatformVer lintOptions { abortOnError false checkReleaseBuilds false } defaultConfig { - minSdkVersion ndkPlatformVer + minSdkVersion minSdkVer targetSdkVersion sdkVer ${NATIVE_CMAKE_SECTION_DEFAULT_CONFIG} } diff --git a/Code/Tools/Android/ProjectBuilder/local.properties.in b/Code/Tools/Android/ProjectBuilder/local.properties.in index 559ea67bcb..4e82cb2940 100644 --- a/Code/Tools/Android/ProjectBuilder/local.properties.in +++ b/Code/Tools/Android/ProjectBuilder/local.properties.in @@ -16,6 +16,5 @@ # For customization when using a Version Control System, please read the # header note. # ${GENERATION_TIMESTAMP} -ndk.dir=${ANDROID_NDK_PATH} sdk.dir=${ANDROID_SDK_PATH} ${CMAKE_DIR_LINE} diff --git a/Code/Tools/Android/ProjectBuilder/root.build.gradle.in b/Code/Tools/Android/ProjectBuilder/root.build.gradle.in index 782a1f26b5..dfce99c3c7 100644 --- a/Code/Tools/Android/ProjectBuilder/root.build.gradle.in +++ b/Code/Tools/Android/ProjectBuilder/root.build.gradle.in @@ -12,10 +12,9 @@ buildscript { repositories { google() jcenter() - } dependencies { - classpath 'com.android.tools.build:gradle:3.6.4' + classpath 'com.android.tools.build:gradle:${ANDROID_GRADLE_PLUGIN_VERSION}' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files @@ -26,14 +25,14 @@ allprojects { repositories { google() jcenter() - } } subprojects { ext { + minSdkVer = ${MIN_SDK_VER} sdkVer = ${SDK_VER} - ndkPlatformVer = ${NDK_PLATFORM_VER} + ndkPlatformVer = '${NDK_VERSION}' buildToolsVer = '${SDK_BUILD_TOOL_VER}' lyEngineRoot = '${LY_ENGINE_ROOT}' } diff --git a/cmake/Tools/Platform/Android/android_support.py b/cmake/Tools/Platform/Android/android_support.py index 6443077457..75e0cd2970 100755 --- a/cmake/Tools/Platform/Android/android_support.py +++ b/cmake/Tools/Platform/Android/android_support.py @@ -10,7 +10,9 @@ # import imghdr +import configparser import datetime +import fnmatch import logging import os import json @@ -33,6 +35,13 @@ if ROOT_DEV_PATH not in sys.path: from cmake.Tools import common +ANDROID_GRADLE_PLUGIN_COMPATIBILITY_MAP = { + '4.2.0': {'min_gradle_version': '6.7.1', + 'sdk_build': '30.0.2', + 'default_ndk': '21.4.7075529', + 'min_cmake_version': '3.20'} +} + APP_NAME = 'app' ANDROID_MANIFEST_FILE = 'AndroidManifest.xml' ANDROID_LIBRARIES_JSON_FILE = 'android_libraries.json' @@ -86,83 +95,93 @@ PYTHON_SCRIPT = 'python.cmd' if platform.system() == 'Windows' else 'python.sh' ANDROID_LAUNCHER_NAME_PATTERN = "{project_name}.GameLauncher" + class AndroidProjectManifestEnvironment(object): """ - This class manages the environment for the AndroidManifiest.xml template file, based on project settings and environments + This class manages the environment for the AndroidManifest.xml template file, based on project settings and environments that were passed in or calculated from the command line arguments. """ - def __init__(self, engine_root, project_path, android_sdk_version_number, android_ndk_platform_number, is_test:bool): + def __init__(self, engine_root, project_path, android_sdk_version_number, is_test:bool): """ Initialize the object with the project specific parameters and values for the game project :param engine_root: The path where the engine is located :param project_path: The path were the project is located :param android_sdk_version_number: The android SDK platform version - :param android_ndk_platform_number: The android NDK platform version :param is_test: Indicates if theAzTestRunner application should be run """ - if is_test: - # The AzTestRunner project.json is located under {engine_root}/Code/Tools/AzTestRunner/Platform/Android/android_project.json - project_properties_path = engine_root / 'Code' / 'Tools' / 'AzTestRunner' / 'Platform' / 'Android' / 'android_project.json' - else: - # The project.json file is located under the game name folder - project_properties_path = project_path / 'project.json' - # Read and parse the project.json file into a dictionary to process the specific attributes needed for the manifest template - project_properties_content = project_properties_path.resolve(strict=True)\ - .read_text(encoding=common.DEFAULT_TEXT_READ_ENCODING, - errors=common.ENCODING_ERROR_HANDLINGS) - self.project_path = project_path + try: + if is_test: + # The AzTestRunner project.json is located under {engine_root}/Code/Tools/AzTestRunner/Platform/Android/android_project.json + project_properties_path = engine_root / 'Code' / 'Tools' / 'AzTestRunner' / 'Platform' / 'Android' / 'android_project.json' + assert project_properties_path.is_file(), f'Missing required android settings file {project_properties_path.resolve()}' + project_properties_content = project_properties_path.read_text(encoding=common.DEFAULT_TEXT_READ_ENCODING, + errors=common.ENCODING_ERROR_HANDLINGS) + project_json = json.loads(project_properties_content) - # Extract the key attributes we need to process and build up our environment table - project_json = json.loads(project_properties_content) + android_settings = project_json['android_settings'] - project_name = project_json.get('project_name') - if not project_name: - raise common.LmbrCmdError(f"Missing required 'project_name' from project.json for project at '{str(project_path)}'") - product_name = project_json.get('product_name', project_name) + else: + # O3DE projects have both a project.json and an android_project.json files (unless its internal) + project_properties_path = project_path / 'project.json' + assert project_properties_path.is_file(), f'Missing required project settings file {project_properties_path.resolve()}' + project_properties_content = project_properties_path.read_text(encoding=common.DEFAULT_TEXT_READ_ENCODING, + errors=common.ENCODING_ERROR_HANDLINGS) + project_json = json.loads(project_properties_content) - game_project_android_settings = project_json['android_settings'] + android_project_properties_path = project_path / 'Platform' / 'Android' / 'android_project.json' + if android_project_properties_path.is_file(): + android_project_properties_content = android_project_properties_path.read_text(encoding=common.DEFAULT_TEXT_READ_ENCODING, + errors=common.ENCODING_ERROR_HANDLINGS) + android_project_json = json.loads(android_project_properties_content) + android_settings = android_project_json['android_settings'] + else: + android_settings = project_json['android_settings'] - package_name = game_project_android_settings["package_name"] + self.project_path = project_path - package_path = package_name.replace('.', '/') + project_name = project_json['project_name'] + product_name = project_json.get('product_name', project_name) + package_name = android_settings["package_name"] + package_path = package_name.replace('.', '/') - project_activity = f'{TEST_RUNNER_PROJECT}Activity' if is_test else f'{project_name}Activity' + project_activity = f'{TEST_RUNNER_PROJECT}Activity' if is_test else f'{project_name}Activity' - # Multiview options require special processing - multi_window_options = AndroidProjectManifestEnvironment.process_android_multi_window_options(game_project_android_settings) + # Multiview options require special processing + multi_window_options = AndroidProjectManifestEnvironment.process_android_multi_window_options(android_settings) - self.internal_dict = { - 'ANDROID_PACKAGE': package_name, - 'ANDROID_PACKAGE_PATH': package_path, - 'ANDROID_VERSION_NUMBER': game_project_android_settings["version_number"], - "ANDROID_VERSION_NAME": game_project_android_settings["version_name"], - "ANDROID_SCREEN_ORIENTATION": game_project_android_settings["orientation"], - 'ANDROID_APP_NAME': TEST_RUNNER_PROJECT if is_test else product_name, # external facing name - 'ANDROID_PROJECT_NAME': TEST_RUNNER_PROJECT if is_test else project_name, # internal facing name - 'ANDROID_PROJECT_ACTIVITY': project_activity, - 'ANDROID_LAUNCHER_NAME': TEST_RUNNER_PROJECT if is_test else ANDROID_LAUNCHER_NAME_PATTERN.format(project_name=project_name), - 'ANDROID_CONFIG_CHANGES': multi_window_options['ANDROID_CONFIG_CHANGES'], - 'ANDROID_APP_PUBLIC_KEY': game_project_android_settings.get('app_public_key', 'NoKey'), - 'ANDROID_APP_OBFUSCATOR_SALT': game_project_android_settings.get('app_obfuscator_salt', ''), - 'ANDROID_USE_MAIN_OBB': game_project_android_settings.get('use_main_obb', 'false'), - 'ANDROID_USE_PATCH_OBB': game_project_android_settings.get('use_patch_obb', 'false'), - 'ANDROID_ENABLE_KEEP_SCREEN_ON': game_project_android_settings.get('enable_keep_screen_on', 'false'), - 'ANDROID_DISABLE_IMMERSIVE_MODE': game_project_android_settings.get('disable_immersive_mode', 'false'), - 'ANDROID_MIN_SDK_VERSION': android_ndk_platform_number, - 'ANDROID_TARGET_SDK_VERSION': android_sdk_version_number, - 'ICONS': game_project_android_settings.get('icons', None), - 'SPLASH_SCREEN': game_project_android_settings.get('splash_screen', None), + self.internal_dict = { + 'ANDROID_PACKAGE': package_name, + 'ANDROID_PACKAGE_PATH': package_path, + 'ANDROID_VERSION_NUMBER': android_settings["version_number"], + "ANDROID_VERSION_NAME": android_settings["version_name"], + "ANDROID_SCREEN_ORIENTATION": android_settings["orientation"], + 'ANDROID_APP_NAME': TEST_RUNNER_PROJECT if is_test else product_name, # external facing name + 'ANDROID_PROJECT_NAME': TEST_RUNNER_PROJECT if is_test else project_name, # internal facing name + 'ANDROID_PROJECT_ACTIVITY': project_activity, + 'ANDROID_LAUNCHER_NAME': TEST_RUNNER_PROJECT if is_test else ANDROID_LAUNCHER_NAME_PATTERN.format(project_name=project_name), + 'ANDROID_CONFIG_CHANGES': multi_window_options['ANDROID_CONFIG_CHANGES'], + 'ANDROID_APP_PUBLIC_KEY': android_settings.get('app_public_key', 'NoKey'), + 'ANDROID_APP_OBFUSCATOR_SALT': android_settings.get('app_obfuscator_salt', ''), + 'ANDROID_USE_MAIN_OBB': android_settings.get('use_main_obb', 'false'), + 'ANDROID_USE_PATCH_OBB': android_settings.get('use_patch_obb', 'false'), + 'ANDROID_ENABLE_KEEP_SCREEN_ON': android_settings.get('enable_keep_screen_on', 'false'), + 'ANDROID_DISABLE_IMMERSIVE_MODE': android_settings.get('disable_immersive_mode', 'false'), + 'ANDROID_TARGET_SDK_VERSION': android_sdk_version_number, + 'ICONS': android_settings.get('icons', None), + 'SPLASH_SCREEN': android_settings.get('splash_screen', None), - 'ANDROID_MULTI_WINDOW': multi_window_options['ANDROID_MULTI_WINDOW'], - 'ANDROID_MULTI_WINDOW_PROPERTIES': multi_window_options['ANDROID_MULTI_WINDOW_PROPERTIES'], + 'ANDROID_MULTI_WINDOW': multi_window_options['ANDROID_MULTI_WINDOW'], + 'ANDROID_MULTI_WINDOW_PROPERTIES': multi_window_options['ANDROID_MULTI_WINDOW_PROPERTIES'], - 'SAMSUNG_DEX_KEEP_ALIVE': multi_window_options['SAMSUNG_DEX_KEEP_ALIVE'], - 'SAMSUNG_DEX_LAUNCH_WIDTH': multi_window_options['SAMSUNG_DEX_LAUNCH_WIDTH'], - 'SAMSUNG_DEX_LAUNCH_HEIGHT': multi_window_options['SAMSUNG_DEX_LAUNCH_HEIGHT'] - } + 'SAMSUNG_DEX_KEEP_ALIVE': multi_window_options['SAMSUNG_DEX_KEEP_ALIVE'], + 'SAMSUNG_DEX_LAUNCH_WIDTH': multi_window_options['SAMSUNG_DEX_LAUNCH_WIDTH'], + 'SAMSUNG_DEX_LAUNCH_HEIGHT': multi_window_options['SAMSUNG_DEX_LAUNCH_HEIGHT'] + } + except KeyError as e: + raise common.LmbrCmdError(f"Missing key from android project settings for project at {project_path}:'{e}' ") def __getitem__(self, item): return self.internal_dict.get(item) @@ -306,6 +325,7 @@ asset_deploy_type={asset_type} android_sdk_path={android_sdk_path} embed_assets_in_apk={embed_assets_in_apk} is_unit_test={is_unit_test} +android_gradle_plugin={android_gradle_plugin_version} """ NATIVE_CMAKE_SECTION_ANDROID_FORMAT = """ @@ -425,26 +445,28 @@ class AndroidProjectGenerator(object): Class the manages the process to generate an android project folder in order to build with gradle/android studio """ - def __init__(self, engine_root, build_dir, android_ndk_path, android_sdk_path, android_sdk_version, android_ndk_platform, - project_path, third_party_path, cmake_version, override_cmake_path, override_gradle_path, override_ninja_path, - android_sdk_build_tool_version, include_assets_in_apk, asset_mode, asset_type, signing_config, is_test_project=False, + def __init__(self, engine_root, build_dir, android_sdk_path, build_tool, android_sdk_platform, android_native_api_level, android_ndk, + project_path, third_party_path, cmake_version, override_cmake_path, override_gradle_path, gradle_version, gradle_plugin_version, + override_ninja_path, include_assets_in_apk, asset_mode, asset_type, signing_config, is_test_project=False, overwrite_existing=True): """ Initialize the object with all the required parameters needed to create an Android Project. The parameters should be verified before initializing this object - + :param engine_root: The engine root that contains the engine :param build_dir: The target folder under the where the android project folder will be created - :param android_ndk_path: The path to the ANDROID_NDK used for building the native android code :param android_sdk_path: The path to the ANDROID_SDK used for building the android java code - :param android_sdk_version: The android platform version number to use for the Android SDK related builds - :param android_ndk_platform: The android platform version number to use for the Android NDK related builds + :param build_tool: The android SDK build-tool version. + :param android_sdk_platform: The android sdk platform version number to use for the Android SDK related builds + :param android_native_api_level:The android native API level (ANDROID_NATIVE_API_LEVEL) to set + :param android_ndk: The android ndk version number to use for the native builds :param project_path: The path to the project :param third_party_path: The required path to the lumberyard 3rd party path :param cmake_version: The version number of cmake that will be used by gradle :param override_cmake_path: The override path to cmake if it does not exists in the system path :param override_gradle_path: The override path to gradle if it does not exists in the system path + :param gradle_version: The detected version of gradle being used + :param gradle_plugin_version: The android gradle plugin version :param override_ninja_path: The override path to ninja if it does not exists in the system path - :param android_sdk_build_tool_version: The preferred android SDK build-tool version. Will default to the first one detected in the android sdk path :param include_assets_in_apk: :param asset_mode: :param asset_type: @@ -458,17 +480,16 @@ class AndroidProjectGenerator(object): self.build_dir = build_dir - self.android_ndk_path = android_ndk_path - self.android_sdk_path = android_sdk_path self.android_project_builder_path = self.engine_root / 'Code/Tools/Android/ProjectBuilder' - self.android_sdk_version = android_sdk_version + self.android_sdk_platform = android_sdk_platform + self.android_sdk_build_tool_version = build_tool.version - self.android_sdk_build_tool_version = android_sdk_build_tool_version - - self.android_ndk_platform = android_ndk_platform + self.android_ndk = android_ndk + self.android_ndk_version = android_ndk.version + self.android_native_api_level = android_native_api_level self.project_path = project_path @@ -480,6 +501,10 @@ class AndroidProjectGenerator(object): self.override_gradle_path = override_gradle_path + self.gradle_version = gradle_version + + self.gradle_plugin_version = gradle_plugin_version + self.override_ninja_path = override_ninja_path self.include_assets_in_apk = include_assets_in_apk @@ -511,8 +536,10 @@ class AndroidProjectGenerator(object): project_names.extend(self.create_lumberyard_app(project_names)) root_gradle_env = { - 'SDK_VER': self.android_sdk_version, - 'NDK_PLATFORM_VER': self.android_ndk_platform, + 'ANDROID_GRADLE_PLUGIN_VERSION': str(self.gradle_plugin_version), + 'SDK_VER': self.android_sdk_platform, + 'MIN_SDK_VER': self.android_sdk_platform, + 'NDK_VERSION': self.android_ndk_version, 'SDK_BUILD_TOOL_VER': self.android_sdk_build_tool_version, 'LY_ENGINE_ROOT': common.normalize_path_for_settings(self.engine_root) } @@ -557,7 +584,7 @@ class AndroidProjectGenerator(object): if self.override_gradle_path: gradle_wrapper_cmd = [self.override_gradle_path] else: - gradle_wrapper_cmd = ['gradle.bat' if platform.system() == 'Windows' else 'gradle'] + gradle_wrapper_cmd = ['gradle'] gradle_wrapper_cmd.extend(['wrapper', '-p', str(self.build_dir.resolve())]) @@ -580,7 +607,8 @@ class AndroidProjectGenerator(object): asset_type='', android_sdk_path=str(self.android_sdk_path), embed_assets_in_apk=True, - is_unit_test=True) + is_unit_test=True, + android_gradle_plugin_version=self.gradle_plugin_version) else: platform_settings_content = PLATFORM_SETTINGS_FORMAT.format(generation_timestamp=str(datetime.datetime.now().strftime("%c")), platform='android', @@ -589,16 +617,28 @@ class AndroidProjectGenerator(object): asset_type=self.asset_type, android_sdk_path=str(self.android_sdk_path), embed_assets_in_apk=str(self.include_assets_in_apk), - is_unit_test=False) + is_unit_test=False, + android_gradle_plugin_version=self.gradle_plugin_version) platform_settings_file = self.build_dir / 'platform.settings' + + # Check if there already exists the build folder and a 'platform.settings' file. If there is an android gradle + # plugin version set and it is different than the one configured here, we will always overwrite it since + # there could be significant differences from one plug-in to the next + if platform_settings_file.is_file(): + config = configparser.ConfigParser() + config.read([str(platform_settings_file.resolve(strict=True))]) + if config.has_option('android', 'android_gradle_plugin'): + exist_agp_version = config.get('android', 'android_gradle_plugin') + if exist_agp_version != self.gradle_plugin_version: + self.overwrite_existing = True + platform_settings_file.open('w').write(platform_settings_content) def create_default_local_properties(self): """ Create the default 'local.properties' file in the build folder """ - template_android_ndk_path = common.normalize_path_for_settings(self.android_ndk_path, True) template_android_sdk_path = common.normalize_path_for_settings(self.android_sdk_path, True) if self.override_cmake_path: # The cmake dir references the base cmake folder, not the executable path itself, so resolve to the base folder @@ -608,7 +648,6 @@ class AndroidProjectGenerator(object): local_properties_env = { "GENERATION_TIMESTAMP": str(datetime.datetime.now().strftime("%c")), - "ANDROID_NDK_PATH": template_android_ndk_path, "ANDROID_SDK_PATH": template_android_sdk_path, "CMAKE_DIR_LINE": f'cmake.dir={template_cmake_path}' if template_cmake_path else '' } @@ -626,8 +665,7 @@ class AndroidProjectGenerator(object): # before we can process it. android_libraries_substitution_table = { "ANDROID_SDK_HOME": common.normalize_path_for_settings(self.android_sdk_path, False), - "ANDROID_NDK_HOME": common.normalize_path_for_settings(self.android_ndk_path, False), - "ANDROID_SDK_VERSION": "android-".format(self.android_sdk_version) + "ANDROID_SDK_VERSION": f"android-{self.android_sdk_platform}" } android_libraries_template_json_path = self.android_project_builder_path / ANDROID_LIBRARIES_JSON_FILE @@ -717,7 +755,7 @@ class AndroidProjectGenerator(object): template_engine_root = common.normalize_path_for_settings(self.engine_root) template_third_party_path = common.normalize_path_for_settings(self.third_party_path) - template_ndk_path = common.normalize_path_for_settings(self.android_ndk_path) + template_ndk_path = common.normalize_path_for_settings(os.path.join(self.android_sdk_path, self.android_ndk.location)) gradle_build_env = dict() @@ -733,7 +771,6 @@ class AndroidProjectGenerator(object): gradle_build_env['OVERRIDE_JAVA_SOURCESET'] = OVERRIDE_JAVA_SOURCESET_STR.format(absolute_azandroid_path=absolute_azandroid_path) - gradle_build_env['OPTIONAL_JNI_SRC_LIB_SET'] = ', "outputs/native-lib"' for native_config in BUILD_CONFIGURATIONS: @@ -755,7 +792,7 @@ class AndroidProjectGenerator(object): cmake_argument_list.append('"-DLY_TEST_PROJECT=1"') cmake_argument_list.extend([ - f'"-DANDROID_NATIVE_API_LEVEL={self.android_ndk_platform}"', + f'"-DANDROID_NATIVE_API_LEVEL={self.android_native_api_level}"', f'"-DLY_NDK_DIR={template_ndk_path}"', '"-DANDROID_STL=c++_shared"', '"-Wno-deprecated"', @@ -835,8 +872,7 @@ class AndroidProjectGenerator(object): dest_src_main_path.mkdir(parents=True) az_android_package_env = AndroidProjectManifestEnvironment(engine_root=self.engine_root, project_path=self.project_path, - android_sdk_version_number=self.android_sdk_version, - android_ndk_platform_number=self.android_ndk_platform, + android_sdk_version_number=self.android_sdk_platform, is_test=self.is_test_project) self.create_file_from_project_template(src_template_file=ANDROID_MANIFEST_FILE, template_env=az_android_package_env, @@ -1304,218 +1340,7 @@ class AndroidProjectGenerator(object): self.new = new -ANDROID_PLATFORM_PATTERN = re.compile(r'([\w\d]*-)?(\d+\d*)') # Regex to handle android platform naming for both SDKs and NDKs - - -def validate_android_platform_input(input_android_platform, platform_variable_type, min_version, max_version): - """ - Helper tool to support android platform number inputs and perform min/max version validation - - :param input_android_platform: The inpuit argument to evaluate - :param platform_variable_type: The type of platform version to validate (android sdk / android ndk) - :param min_version: The minimum version to validate against - :param max_version: The maximum version to validate against - :return: The int version of the extracted platform number from the input - """ - # Validate the platform number's format and against the supported versions - platform_number_match = ANDROID_PLATFORM_PATTERN.search(input_android_platform) - if not platform_number_match or not platform_number_match.group(2) or (platform_number_match.group(1) and platform_number_match.group(1) != 'android-'): - raise common.LmbrCmdError(f"Invalid {platform_variable_type} version value ({input_android_platform}). It must be " - f"either 'XX' or android-'XX' where 'XX' is a platform number.", - common.ERROR_CODE_INVALID_PARAMETER) - - android_platform_number = int(platform_number_match.group(2)) - if android_platform_number < min_version: - raise common.LmbrCmdError(f"Invalid {platform_variable_type} version value ({input_android_platform}) is less than the minimum " - f"supported version ({min_version}).", - common.ERROR_CODE_INVALID_PARAMETER) - if android_platform_number > max_version: - raise common.LmbrCmdError(f"Invalid {platform_variable_type} version value ({input_android_platform}) is greater than the maximum " - f"supported version ({max_version}).", - common.ERROR_CODE_INVALID_PARAMETER) - return android_platform_number - - ANDROID_SDK_ENV_NAME = 'ANDROID_SDK' -ANDROID_SDK_MIN_PLATFORM = 28 -ANDROID_SDK_MAX_PLATFORM = 29 - - -def verify_android_sdk(android_sdk_platform, argument_name, override_android_sdk_path=None, preferred_sdk_build_tools_ver=None): - """ - Verify the android sdk and the requested platform platform against the android sdk path - - :param android_sdk_platform: The android sdk platform to use (e.g. '28' or 'android-28') - :param argument_name: The name of the argument for descriptive errors to present - :param override_android_sdk_path: The location of the android SDK path if not set through the environment variable - :param preferred_sdk_build_tools_ver: Option prefered built tool version under the android SDK if available. Will fallback to the first one discovered - :returns tuple of the verified android sdk platform number, path to the Android SDK path and the build tool version - """ - android_sdk_platform_number = validate_android_platform_input(input_android_platform=android_sdk_platform, - platform_variable_type='android sdk', - min_version=ANDROID_SDK_MIN_PLATFORM, - max_version=ANDROID_SDK_MAX_PLATFORM) - - # Get the candidate android sdk path from either the override argument or the system environment variable - if override_android_sdk_path: - check_android_sdk_path = override_android_sdk_path - else: - check_android_sdk_path = os.environ.get(ANDROID_SDK_ENV_NAME) - if not check_android_sdk_path: - raise common.LmbrCmdError(f"Android SDK path not set. Make sure that either the '{ANDROID_SDK_ENV_NAME}' environment is " - f"set or it is passed in through the {argument_name} argument") - - # The android sdk folder structure is expected to have a 'platforms' sub folder based on the android sdk-platform number - check_android_sdk_path = pathlib.Path(check_android_sdk_path) - android_sdk_platforms_path = check_android_sdk_path / 'platforms' - if not android_sdk_platforms_path.is_dir(): - raise common.LmbrCmdError(f"Invalid Android SDK path '{str(check_android_sdk_path)}': Missing 'platforms' directory.") - - # Collect the available platform numbers from the platforms subdirectory - validated_android_platforms = [] - for dir_item in android_sdk_platforms_path.iterdir(): - if not dir_item.is_dir(): - continue - check_file = dir_item / 'package.xml' - if check_file.is_file(): - validated_android_platforms.append(dir_item.name) - - if not validated_android_platforms: - raise common.LmbrCmdError(f"Invalid Android SDK path '{str(check_android_sdk_path)}': Unable to find any android platforms.") - - # Normalize the android_sdk argument to fit the same folder name pattern - android_sdk_platform_name = f'android-{android_sdk_platform_number}' - if android_sdk_platform_name not in validated_android_platforms: - raise common.LmbrCmdError(f"Android SDK platform {android_sdk_platform_name} is not a valid for the android SDK located under '{str(check_android_sdk_path)}'") - - # Enumerate through the build tools under android sdk - android_sdk_build_tools_dir = check_android_sdk_path / 'build-tools' - if not android_sdk_build_tools_dir.is_dir(): - raise common.LmbrCmdError(f"Invalid Android SDK path '{str(check_android_sdk_path)}': Unable to find any built-tools folder.") - supported_build_tools = [str(build_tool.name) for build_tool in android_sdk_build_tools_dir.iterdir() if build_tool.is_dir()] - if not supported_build_tools: - raise common.LmbrCmdError(f"Invalid Android SDK path '{str(check_android_sdk_path)}': Unable to find any built-tools.") - if preferred_sdk_build_tools_ver: - if preferred_sdk_build_tools_ver in supported_build_tools: - validated_build_tool = preferred_sdk_build_tools_ver - else: - validated_build_tool = supported_build_tools[0] - logging.warning("Unable to locate android sdk build tool version {preferred_sdk_build_tools_ver}. Defaulting to version {validated_build_tool}") - - else: - validated_build_tool = supported_build_tools[0] - - return android_sdk_platform_number, check_android_sdk_path, validated_build_tool - - -ANDROID_NDK_ENV_NAME = 'ANDROID_NDK' -ANDROID_NDK_MIN_PLATFORM = 21 -ANDROID_NDK_MAX_PLATFORM = 29 -ANDROID_NDK_SOURCE_PROPERTIES_REVISION_PATTERN = re.compile(r'Pkg.Revision\s*=\s*(\d+.\d+.\d+)') - - -def verify_android_ndk(android_ndk_platform, argument_name, override_android_ndk_path=None): - """ - Verify the android ndk and requested platform against the android ndk path - - :param android_ndk_platform: The android ndk platform to use (e.g. '21' or 'android-21') - :param argument_name: The name of the argument for descriptive errors to present - :param override_android_ndk_path: The location of the android NDK path if not set through the environment variable - :returns tuple of the verified android ndk platform number and the Path to the Android SDK path and the - """ - - android_ndk_platform_number = validate_android_platform_input(input_android_platform=android_ndk_platform, - platform_variable_type='android ndk', - min_version=ANDROID_NDK_MIN_PLATFORM, - max_version=ANDROID_NDK_MAX_PLATFORM) - - # Get the candidate android ndk path from either the override argument or the system environment variable - if override_android_ndk_path: - check_android_ndk_path = str(override_android_ndk_path) - else: - check_android_ndk_path = os.environ.get(ANDROID_NDK_ENV_NAME) - if not check_android_ndk_path: - raise common.LmbrCmdError(f"Android NDK path not set. Make sure that either the {ANDROID_NDK_ENV_NAME} environment " - f"is set or it is passed in through the {argument_name} argument") - check_android_ndk_path = pathlib.Path(check_android_ndk_path) - - # Validate the android ndk path - - # Determine the NDK revision by reading the source.properties file - ndk_source_properties_file = check_android_ndk_path / 'source.properties' - if not ndk_source_properties_file.is_file(): - raise common.LmbrCmdError(f"Invalid Android NDK path '{str(check_android_ndk_path)}'. Missing 'source.properties' file.", - common.ERROR_CODE_INVALID_PARAMETER) - ndk_source_properties_file_content = ndk_source_properties_file.read_text(encoding=common.DEFAULT_TEXT_READ_ENCODING, - errors=common.ENCODING_ERROR_HANDLINGS) - - ndk_revision_match = ANDROID_NDK_SOURCE_PROPERTIES_REVISION_PATTERN.search(ndk_source_properties_file_content) - if not ndk_revision_match: - raise common.LmbrCmdError(f"Invalid Android NDK path '{str(check_android_ndk_path)}'. Unable to extract version from 'source.properties' file.", - common.ERROR_CODE_INVALID_PARAMETER) - ndk_revision_number = LooseVersion(ndk_revision_match.group(1)) - logging.info(f"Detected Android NDK Revision {str(ndk_revision_number)}") - - # Collect the supported android platforms from the required 'platforms' folder under the ndk path - android_ndk_platforms_path = check_android_ndk_path / 'platforms' - if not android_ndk_platforms_path.is_dir(): - raise common.LmbrCmdError(f"Invalid Android NDK path '{str(check_android_ndk_path)}'. Missing 'platforms' folder.", - common.ERROR_CODE_INVALID_PARAMETER) - - validated_android_platforms = [] - for dir_item in android_ndk_platforms_path.iterdir(): - if not dir_item.is_dir(): - continue - api_version_match = ANDROID_PLATFORM_PATTERN.search(dir_item.name) - if not api_version_match or api_version_match.group(1) != 'android-': - continue - - check_lib_path = dir_item / 'arch-arm64/usr/lib' - if check_lib_path.is_dir(): - validated_android_platforms.append(dir_item.name) - - # For NDK revisions 19 and up, there is a mapping file for version numbers that map to other version. - platforms_map_aliases = {} - if ndk_revision_number >= LooseVersion('19.0.0'): - platforms_map_file = check_android_ndk_path / 'meta/platforms.json' - if platforms_map_file.exists(): - with open(platforms_map_file, 'r') as platforms_map_file_handle: - platforms_map_file_json = json.load(platforms_map_file_handle) - platforms_map_aliases = platforms_map_file_json['aliases'] - elif validated_android_platforms: - # Revisions before 19 does not have a mapping file for API versions, they fall back to the previous one - # So we need to make a mapping file that does the same - platforms_map_aliases = {} - validated_android_platforms.sort() - max_supported_api_number = int(ANDROID_PLATFORM_PATTERN.search(validated_android_platforms[-1]).group(2)) - for validated_android_platform in validated_android_platforms: - current_api_version = int(ANDROID_PLATFORM_PATTERN.search(validated_android_platform).group(2)) - next_api_version = current_api_version + 1 - while f'android-{next_api_version}' not in validated_android_platforms and next_api_version <= max_supported_api_number: - platforms_map_aliases[str(next_api_version)] = current_api_version - next_api_version += 1 - - # Go through the aliases and add to the validated platforms if it is mapped to an existing platform - for alias_key, alias_value in platforms_map_aliases.items(): - if not ANDROID_PLATFORM_PATTERN.search(f'android-{alias_key}'): - # Skip any non android-XX (XX = number) aliases - continue - aliased_platform_key = f'android-{alias_value}' - if aliased_platform_key in validated_android_platforms: - validated_android_platforms.append(f'android-{alias_key}') - - if not validated_android_platforms: - raise common.LmbrCmdError(f"Invalid Android NDK path {str(check_android_ndk_path)}") - - # Verify the ndk platform against the ndk path - android_ndk_platform_name = f'android-{android_ndk_platform_number}' - if android_ndk_platform_name not in validated_android_platforms: - raise common.LmbrCmdError(f"Android NDK platform {android_ndk_platform_name} is not a valid for the Android NDK located under '{str(check_android_ndk_path)}'") - - return android_ndk_platform_number, check_android_ndk_path - - -ADB_TARGET = 'adb.exe' if platform.system() == 'Windows' else 'adb' def resolve_adb_tool(android_sdk_path): @@ -1528,9 +1353,16 @@ def resolve_adb_tool(android_sdk_path): if isinstance(android_sdk_path, str): android_sdk_path = pathlib.Path(android_sdk_path) - check_adb_target = android_sdk_path / 'platform-tools' / ADB_TARGET - if not check_adb_target.exists(): - raise common.LmbrCmdError(f"Invalid Android SDK path '{str(android_sdk_path)}': Unable to locate '{ADB_TARGET}'.") + file_found = False + for executable_path_ext in common.PLATFORM_EXECUTABLE_EXTENSIONS: + check_adb_target = android_sdk_path / 'platform-tools' / f'adb{executable_path_ext}' + if check_adb_target.is_file(): + file_found = True + break + + if not file_found: + raise common.LmbrCmdError(f"Invalid Android SDK path '{str(android_sdk_path)}': Unable to locate 'adb'.") + return check_adb_target @@ -1633,3 +1465,196 @@ class AdbTool(common.CommandLineExec): else: adb_params = arguments return super().popen(adb_params, cwd) + + +class AndroidGradlePluginInfo(object): + + def __init__(self, android_gradle_plugin_version): + + if android_gradle_plugin_version not in ANDROID_GRADLE_PLUGIN_COMPATIBILITY_MAP.keys(): + raise common.LmbrCmdError(f"Android Gradle Plugin version {android_gradle_plugin_version} is not supported. " + f"Only the following version(s) are supported: {','.join(ANDROID_GRADLE_PLUGIN_COMPATIBILITY_MAP.keys())}") + + details = ANDROID_GRADLE_PLUGIN_COMPATIBILITY_MAP[android_gradle_plugin_version] + self.default_sdk_build_tools_version = LooseVersion(details.get('sdk_build')) + + self.default_ndk_version = LooseVersion(details.get('default_ndk')) + + self.min_gradle_version = LooseVersion(details.get('min_gradle_version')) + + self.min_cmake_version = LooseVersion(details.get('min_cmake_version')) + + max_cmake_version_number = details.get('max_cmake_version') + self.max_cmake_version = None if max_cmake_version_number is None else LooseVersion(max_cmake_version_number) + + +class AndroidSDKResolver(object): + """ + Class that manages the Android SDK tool to validate, install packages (e.g. built tools, sdk platforms, ndk, etc) + """ + + class InstalledPackage(object): + def __init__(self, installed_package_components): + assert len(installed_package_components) == 4, '4 sections expected for installed package components (path, version, description, location)' + self.path = installed_package_components[0] + self.version = LooseVersion(installed_package_components[1]) + self.description = installed_package_components[2] + self.location = installed_package_components[3] + + class AvailablePackage(object): + def __init__(self, available_package_components): + assert len(available_package_components) == 3, '3 sections expected for installed package components (path, version, description)' + self.path = available_package_components[0] + self.version = LooseVersion(available_package_components[1]) + self.description = available_package_components[2] + + class AvailableUpdate(object): + def __init__(self, available_update_components): + assert len(available_update_components) == 3, '3 sections expected for installed package components (path, version, available)' + self.path = available_update_components[0] + self.version = LooseVersion(available_update_components[1]) + self.available = available_update_components[2] + + def __init__(self, android_sdk_path): + + self.android_sdk_path = android_sdk_path or os.environ.get(ANDROID_SDK_ENV_NAME) + if not self.android_sdk_path: + raise common.LmbrCmdError(f"Android SDK path not set or it was not passed into the command to generate the android project") + if not os.path.isdir(self.android_sdk_path): + raise common.LmbrCmdError(f"Android SDK path {self.android_sdk_path} is not valid") + if platform.system() == 'Windows': + self.sdk_manager_path = pathlib.Path(self.android_sdk_path) / 'tools' / 'bin' / 'sdkmanager.bat' + else: + raise common.LmbrCmdError(f"This tool is not supported on the current platform {platform.system()}") + if not self.sdk_manager_path.is_file(): + raise common.LmbrCmdError(f"Android SDK path {self.android_sdk_path} is not valid or complete. Missing {self.sdk_manager_path}") + + self.sdk_manager = common.CommandLineExec(str(self.sdk_manager_path.resolve())) + + self.installed_packages = {} + self.available_packages = {} + self.available_updates = {} + self.refresh_sdk_installation() + + def refresh_sdk_installation(self): + """ + Utilize the sdk_manager command line tool from the Android SDK to collect / refresh the list of + installed, available, and updateable packages that are managed by the android SDK. + """ + self.installed_packages = {} + self.available_packages = {} + self.available_updates = {} + + def _factory_installed_package(package_map, item_components): + package_map[item_components[0]] = AndroidSDKResolver.InstalledPackage(item_components) + + def _factory_available_package(package_map, item_components): + package_map[item_components[0]] = AndroidSDKResolver.AvailablePackage(item_components) + + def _factory_available_update(package_map, item_components): + package_map[item_components[0]] = AndroidSDKResolver.AvailableUpdate(item_components) + + # Use the SDK manager to collect the available and installed packages + result_code, result_stdout, result_stderr = self.sdk_manager.exec(['--list'], capture_stdout=True, suppress_stderr=True) + + current_append_map = None + current_item_factory = None + for package_item in result_stdout.split('\n'): + package_item_stripped = package_item.strip() + if not package_item_stripped: + continue + if '|' not in package_item_stripped: + if package_item_stripped.upper() == 'INSTALLED PACKAGES:': + current_append_map = self.installed_packages + current_item_factory = _factory_installed_package + elif package_item_stripped.upper() == 'AVAILABLE PACKAGES:': + current_append_map = self.available_packages + current_item_factory = _factory_available_package + elif package_item_stripped.upper() == 'AVAILABLE UPDATES:': + current_append_map = self.available_updates + current_item_factory = _factory_available_update + else: + current_append_map = None + current_item_factory = None + continue + item_parts = [split.strip() for split in package_item_stripped.split('|')] + if len(item_parts) < 3: + continue + elif item_parts[1].upper() in ('VERSION', 'INSTALLED', '-------'): + continue + elif current_append_map is None: + continue + if current_append_map is not None and current_item_factory is not None: + current_item_factory(current_append_map, item_parts) + + def is_package_installed(self, search_package_path): + """ + Check if a package path to see if its a package that is installed. The path can use wildcard '*'s + The function will return a list of the results that match the package paths, ordered by the newest version first + """ + def _package_sort(package): + return package.version + package_detail_result_list = [] + for installed_package_path, installed_package_details in self.installed_packages.items(): + if fnmatch.fnmatch(installed_package_path, search_package_path): + package_detail_result_list.append(installed_package_details) + package_detail_result_list.sort(reverse=True, key=_package_sort) + return package_detail_result_list + + def is_package_available(self, search_package_path): + """ + Check if a package path to see if its an available package to install. The path can use wildcard '*'s + The function will return a list of the results that match the package paths, ordered by the newest version first + """ + def _package_sort(package): + return package.version + package_detail_result_list = [] + for available_package_path, available_package_details in self.available_packages.items(): + if fnmatch.fnmatch(available_package_path, search_package_path): + package_detail_result_list.append(available_package_details) + package_detail_result_list.sort(reverse=True, key=_package_sort) + return package_detail_result_list + + def install_package(self, package_install_path, package_description): + """ + Install a package based on the path of an available android sdk package + """ + + # Skip installation if the package is already installed + package_result_list = self.is_package_installed(package_install_path) + if package_result_list: + installed_package_detail = package_result_list[0] + logging.info(f"{installed_package_detail.description} (version {installed_package_detail.version}) Detected") + return installed_package_detail + + # Make sure the package name is available + package_result_list = self.is_package_available(package_install_path) + if not package_result_list: + raise common.LmbrCmdError(f"Invalid Android SDK Package {package_description}: Bad package path {package_install_path}") + + # Reverse sort and pick the first item, which should be the latest (if the install path contains wildcards) + def _available_sort(item): + return item.path + + package_result_list.sort(reverse=True, key=_available_sort) + + available_package_to_install = package_result_list[0] # For multiple hits, resolve to the first item which will be the latest version + + # Perform the package installation + logging.info(f"Installing {available_package_to_install.description} ...") + result_code, result_stdout, result_stderr = self.sdk_manager.exec(['--install', available_package_to_install.path], capture_stdout=True, suppress_stderr=True) + if result_code != 0: + raise common.LmbrCmdError(f"Error installing package {available_package_to_install.path}: \n{result_stderr}") + + # Refresh the tracked SDK Contents + self.refresh_sdk_installation() + + # Get the package details to verify + package_result_list = self.is_package_installed(package_install_path) + if package_result_list: + installed_package_detail = package_result_list[0] + logging.info(f"{installed_package_detail.description} (version {installed_package_detail.version}) Installed") + return installed_package_detail + else: + raise common.LmbrCmdError(f"Error installing package {available_package_to_install.path}: \n{result_stderr}") + diff --git a/cmake/Tools/Platform/Android/generate_android_project.py b/cmake/Tools/Platform/Android/generate_android_project.py index 9a0e2760f5..d25b62dde8 100755 --- a/cmake/Tools/Platform/Android/generate_android_project.py +++ b/cmake/Tools/Platform/Android/generate_android_project.py @@ -27,7 +27,7 @@ from cmake.Tools import common from cmake.Tools.Platform.Android import android_support GRADLE_ARGUMENT_NAME = '--gradle-install-path' -GRADLE_MIN_VERSION = LooseVersion('4.10.1') +GRADLE_MIN_VERSION = LooseVersion('6.5') GRADLE_MAX_VERSION = LooseVersion('7.0.0') GRADLE_VERSION_REGEX = re.compile(r"Gradle\s(\d+.\d+.?\d*)") GRADLE_EXECUTABLE = 'gradle.bat' if platform.system() == 'Windows' else 'gradle' @@ -48,9 +48,9 @@ def verify_gradle(override_gradle_path=None): CMAKE_ARGUMENT_NAME = '--cmake-install-path' -CMAKE_MIN_VERSION = LooseVersion('3.17.0') +CMAKE_MIN_VERSION = LooseVersion('3.19.0') CMAKE_VERSION_REGEX = re.compile(r'cmake version (\d+.\d+.?\d*)') -CMAKE_EXECUTABLE = 'cmake.exe' if platform.system() == 'Windows' else 'cmake' +CMAKE_EXECUTABLE = 'cmake' def verify_cmake(override_cmake_path=None): @@ -69,7 +69,7 @@ def verify_cmake(override_cmake_path=None): NINJA_ARGUMENT_NAME = '--ninja-install-path' NINJA_VERSION_REGEX = re.compile(r'(\d+.\d+.?\d*)') -NINJA_EXECUTABLE = 'ninja.exe' if platform.system() == 'Windows' else 'ninja' +NINJA_EXECUTABLE = 'ninja' def verify_ninja(override_ninja_path=None): @@ -78,7 +78,7 @@ def verify_ninja(override_ninja_path=None): """ return common.verify_tool(override_tool_path=override_ninja_path, tool_name='ninja', - tool_filename='ninja.exe' if platform.system() == 'Windows' else 'ninja', + tool_filename='ninja', argument_name=NINJA_ARGUMENT_NAME, tool_version_argument='--version', tool_version_regex=NINJA_VERSION_REGEX, @@ -103,13 +103,21 @@ def build_optional_signing_profile(store_file, store_password, key_alias, key_pa ANDROID_SDK_ARGUMENT_NAME = '--android-sdk-path' -ANDROID_SDK_PLATFORM_ARGUMENT_NAME = '--android-sdk-version' +ANDROID_SDK_PLATFORM_ARGUMENT_NAME = '--android-sdk-platform' ANDROID_SDK_PREFERRED_TOOL_VER = '--android-sdk-build-tool-version' +ANDROID_NATIVE_API_LEVEL = '--android-native-api-level' + + +MIN_ANDROID_SDK_PLATFORM = 28 # The minimum platform/api level that is supported for the SDK Platform +MIN_NATIVE_API_LEVEL = 24 # The minimum Native API level that is supported for the NDK + -ANDROID_NDK_ARGUMENT_NAME = '--android-ndk-path' ANDROID_NDK_PLATFORM_ARGUMENT_NAME = '--android-ndk-version' +ANDROID_GRADLE_PLUGIN_ARGUMENT_NAME = '--gradle-plugin-version' +ANDROID_GRADLE_MIN_PLUGIN_VERSION = LooseVersion("4.2.0") + # Constants for asset-related options for APK generation INCLUDE_APK_ASSETS_ARGUMENT_NAME = "--include-apk-assets" ASSET_MODE_ARGUMENT_NAME = "--asset-mode" @@ -147,6 +155,7 @@ def main(args): parser = argparse.ArgumentParser(description="Prepare the android studio subfolder") + # Required Arguments parser.add_argument('--engine-root', help='The path to the engine root. Defaults to the current working directory.', default=os.getcwd()) @@ -160,32 +169,42 @@ def main(args): help='The path to the 3rd Party root directory', required=True) - parser.add_argument(ANDROID_NDK_ARGUMENT_NAME, - help='The path to the android NDK', - required=True) - parser.add_argument(ANDROID_SDK_ARGUMENT_NAME, help='The path to the android SDK', required=True) - parser.add_argument(ANDROID_SDK_PLATFORM_ARGUMENT_NAME, - help='The android SDK version', + parser.add_argument('-g', '--project-path', + help='The project path to generate an android project', required=True) + parser.add_argument(ANDROID_SDK_PLATFORM_ARGUMENT_NAME, + help=f'The android SDK platform number version to use for the APK. (Minimum {MIN_ANDROID_SDK_PLATFORM})', + type=int, + default=-1) + + parser.add_argument(ANDROID_NATIVE_API_LEVEL, + help=f'The android native API level to use for the APK. If not set, this will default to the android SDK platform. (Minimum {MIN_ANDROID_SDK_PLATFORM})', + type=int, + default=-1) + + # Override arguments parser.add_argument(ANDROID_SDK_PREFERRED_TOOL_VER, - help='The preferred android sdk build version (i.e. 28.0.3). Will default to the first one detected under the android sdk', - default=None, + help='The android SDK build tools version.', required=False) parser.add_argument(ANDROID_NDK_PLATFORM_ARGUMENT_NAME, help='The android NDK version', - required=True) + required=False) parser.add_argument(GRADLE_ARGUMENT_NAME, help=f'The path to installed gradle. The version of gradle must fall in between {str(GRADLE_MIN_VERSION)} and {str(GRADLE_MAX_VERSION)}.', default=None, required=False) + parser.add_argument(ANDROID_GRADLE_PLUGIN_ARGUMENT_NAME, + help=f'The version of the android gradle plugin to use. Defaults to the minimum version ({ANDROID_GRADLE_MIN_PLUGIN_VERSION})', + default=str(ANDROID_GRADLE_MIN_PLUGIN_VERSION)) + parser.add_argument(CMAKE_ARGUMENT_NAME, help=f'The path to cmake build tool if not installed on the system path. The version of cmake must be at least version {str(CMAKE_MIN_VERSION)}.', default=None, @@ -196,9 +215,6 @@ def main(args): default=None, required=False) - parser.add_argument('-g', '--project-path', - help='The project path to generate an android project') - # Asset Options parser.add_argument(INCLUDE_APK_ASSETS_ARGUMENT_NAME, action='store_true', @@ -207,11 +223,11 @@ def main(args): parser.add_argument(ASSET_MODE_ARGUMENT_NAME, choices=ALL_ASSET_MODES, default=ASSET_MODE_LOOSE, - help='Asset Mode (vfs|pak|loose) to use when including assets into the APK') + help=f'Asset Mode (vfs|pak|loose) to use when including assets into the APK. (Defaults to {ASSET_MODE_LOOSE})') parser.add_argument(ASSET_TYPE_ARGUMENT_NAME, default=DEFAULT_ASSET_TYPE, - help='Asset Type to use when including assets into the APK') + help=f'Asset Type to use when including assets into the APK. (Defaults to {DEFAULT_ASSET_TYPE})') parser.add_argument('--debug', action='store_true', @@ -260,16 +276,81 @@ def main(args): ninja_version, override_ninja_path = verify_ninja(override_ninja_path=parsed_args.get_argument(NINJA_ARGUMENT_NAME)) logging.info("Detected Ninja version %s", str(ninja_version)) - # Verify the android sdk path and sdk version - verified_android_sdk_platform, verified_android_sdk_path, android_sdk_build_tool_ver = android_support.verify_android_sdk(android_sdk_platform=parsed_args.get_argument(ANDROID_SDK_PLATFORM_ARGUMENT_NAME), - argument_name=ANDROID_SDK_ARGUMENT_NAME, - override_android_sdk_path=parsed_args.get_argument(ANDROID_SDK_ARGUMENT_NAME), - preferred_sdk_build_tools_ver=parsed_args.get_argument(ANDROID_SDK_PREFERRED_TOOL_VER)) + # Get the android sdk platform version to use from the arguments, but also handle the deprecated argument name + android_sdk_platform_version = parsed_args.get_argument(ANDROID_SDK_PLATFORM_ARGUMENT_NAME) - # Verify the android ndk path and ndk version - verified_android_ndk_platform, verified_android_ndk_path = android_support.verify_android_ndk(android_ndk_platform=parsed_args.get_argument(ANDROID_NDK_PLATFORM_ARGUMENT_NAME), - argument_name=ANDROID_NDK_ARGUMENT_NAME, - override_android_ndk_path=parsed_args.get_argument(ANDROID_NDK_ARGUMENT_NAME)) + # Get the gradle plugin details and validate against the current environment + android_gradle_plugin_version = parsed_args.get_argument(ANDROID_GRADLE_PLUGIN_ARGUMENT_NAME) + android_gradle_plugin = android_support.AndroidGradlePluginInfo(android_gradle_plugin_version) + logging.info(f"Generating Android Gradle Plugin version {android_gradle_plugin_version} based project") + + if gradle_version < android_gradle_plugin.min_gradle_version: + raise common.LmbrCmdError(f"The current version of gradle ({gradle_version}) does not satisfy the minimum version " + f"({android_gradle_plugin.min_gradle_version}) needed for the android gradle plugin " + f"({android_gradle_plugin_version}). Please upgrade your gradle.") + if cmake_version < android_gradle_plugin.min_cmake_version: + raise common.LmbrCmdError(f"The current version of cmake ({cmake_version}) does not satisfy the minimum version " + f"({android_gradle_plugin.min_cmake_version}) needed for the android gradle plugin " + f"({android_gradle_plugin_version}). Please upgrade your cmake.") + if android_gradle_plugin.max_cmake_version and cmake_version > android_gradle_plugin.max_cmake_version: + raise common.LmbrCmdError(f"The current version of cmake ({cmake_version}) exceeds the maximum version " + f"({android_gradle_plugin.max_cmake_version}) of the android gradle plugin " + f"({android_gradle_plugin_version}).") + + # Use the SDK Resolver to make sure the build tools and ndk + android_sdk = android_support.AndroidSDKResolver(android_sdk_path=parsed_args.get_argument(ANDROID_SDK_ARGUMENT_NAME)) + + # If no SDK platform is provided, check for any installed one + if android_sdk_platform_version < 0: + android_sdk_platform_version = MIN_ANDROID_SDK_PLATFORM + installed_android_sdk_platforms = android_sdk.is_package_installed('platforms;*') + if installed_android_sdk_platforms: + # If there are installed platforms, check the most recent one + latest_platform_version = -1 + for installed_android_sdk_platform in installed_android_sdk_platforms: + platform_number_match = re.match(r'platforms;android-([0-9]*)', installed_android_sdk_platform.path) + if not platform_number_match: + continue + check_platform_version = int(platform_number_match.group(1)) + if check_platform_version > latest_platform_version: + latest_platform_version = check_platform_version + if latest_platform_version >= MIN_ANDROID_SDK_PLATFORM: + android_sdk_platform_version = latest_platform_version + else: + if android_sdk_platform_version < MIN_ANDROID_SDK_PLATFORM: + raise common.LmbrCmdError(f"Invalid argument for {ANDROID_SDK_PLATFORM_ARGUMENT_NAME} ({android_sdk_platform_version}). Must be greater than the minimum value supported {MIN_ANDROID_SDK_PLATFORM}.") + + # Get the android native api level from the arguments. Default to the sdk platform version if not provided + android_native_api_level = parsed_args.get_argument(ANDROID_NATIVE_API_LEVEL) + if android_native_api_level < 0: + android_native_api_level = android_sdk_platform_version + else: + if android_native_api_level < MIN_NATIVE_API_LEVEL: + raise common.LmbrCmdError(f"Invalid argument for {ANDROID_NATIVE_API_LEVEL} ({android_native_api_level}). Must be greater than the minimum value supported {MIN_NATIVE_API_LEVEL}.") + + # Check and make sure that the requested sdk platform exists, download if necessary + platform_package_name = f"platforms;android-{android_sdk_platform_version}" + android_sdk.install_package(package_install_path=platform_package_name, + package_description=f'Android SDK Platform {android_sdk_platform_version}') + + # Make sure we have the extra android packages "market_apk_expansion" and "market_licensing" which is needed by the APK + android_sdk.install_package(package_install_path='extras;google;market_apk_expansion', + package_description='Google APK Expansion Library') + + android_sdk.install_package(package_install_path='extras;google;market_licensing', + package_description='Google Play Licensing Library') + + # Install either the requested SDK build tools or the default one for the android gradle plugin version + build_tools_version = parsed_args.get_argument(ANDROID_SDK_PREFERRED_TOOL_VER) or android_gradle_plugin.default_sdk_build_tools_version + build_tools_package_name = f'build-tools;{build_tools_version}' + build_tools_package = android_sdk.install_package(package_install_path=build_tools_package_name, + package_description='Android SDK Build Tools') + + # Install either the requested NDK version or the default one for the android gradle plugin version + android_ndk_version = parsed_args.get_argument(ANDROID_NDK_PLATFORM_ARGUMENT_NAME) or android_gradle_plugin.default_ndk_version + android_ndk_package_name = f'ndk;{android_ndk_version}' + android_ndk_package = android_sdk.install_package(package_install_path=android_ndk_package_name, + package_description='Android NDK') # Verify the engine root path and project path verified_project_path, verified_engine_root = common.verify_project_and_engine_root(project_root=parsed_args.project_path, @@ -277,10 +358,9 @@ def main(args): is_test_project = parsed_args.unit_test # Verify the 3rd Party Root Path - third_party_path = pathlib.Path(parsed_args.third_party_path) / '3rdParty.txt' - if not third_party_path.is_file(): - raise common.LmbrCmdError("Invalid --third-party-path '{}'. Make sure it exists and contains " - "3rdParty.txt".format(parsed_args.third_party_path), + third_party_path = pathlib.Path(parsed_args.third_party_path) + if not third_party_path.is_dir(): + raise common.LmbrCmdError(f"Invalid --third-party-path '{parsed_args.third_party_path}'.", common.ERROR_CODE_INVALID_PARAMETER) third_party_path = third_party_path.parent @@ -293,23 +373,23 @@ def main(args): logging.debug("Engine Root : %s", str(verified_engine_root.resolve())) logging.debug("Build Path : %s", str(build_dir.resolve())) - logging.debug("Android NDK Path : %s", str(verified_android_ndk_path.resolve())) - logging.debug("Android SDK Path : %s", str(verified_android_sdk_path.resolve())) # Prepare the generator and execute generator = android_support.AndroidProjectGenerator(engine_root=verified_engine_root, - project_path=verified_project_path, build_dir=build_dir, - android_sdk_path=verified_android_sdk_path, - android_ndk_path=verified_android_ndk_path, - android_sdk_version=verified_android_sdk_platform, - android_ndk_platform=verified_android_ndk_platform, + android_sdk_path=android_sdk.android_sdk_path, + build_tool=build_tools_package, + android_sdk_platform=android_sdk_platform_version, + android_native_api_level=android_native_api_level, + android_ndk=android_ndk_package, + project_path=verified_project_path, third_party_path=third_party_path, cmake_version=cmake_version, override_cmake_path=override_cmake_path, override_gradle_path=override_gradle_path, + gradle_version=gradle_version, + gradle_plugin_version=android_gradle_plugin_version, override_ninja_path=override_ninja_path, - android_sdk_build_tool_version=android_sdk_build_tool_ver, include_assets_in_apk=parsed_args.get_argument(INCLUDE_APK_ASSETS_ARGUMENT_NAME), asset_mode=parsed_args.get_argument(ASSET_MODE_ARGUMENT_NAME), asset_type=parsed_args.get_argument(ASSET_TYPE_ARGUMENT_NAME), diff --git a/cmake/Tools/Platform/Android/unit_test_generate_android_project.py b/cmake/Tools/Platform/Android/unit_test_generate_android_project.py index 5598942046..0cd0f16eaf 100755 --- a/cmake/Tools/Platform/Android/unit_test_generate_android_project.py +++ b/cmake/Tools/Platform/Android/unit_test_generate_android_project.py @@ -170,117 +170,3 @@ def test_verify_ninja(tmpdir, from_override, version_str, expected_result): finally: subprocess.check_output = orig_check_output - -TEST_VALIDATE_VERSION_MIN = 19 -TEST_VALIDATE_VERSION_MAX = 21 - - -@pytest.mark.parametrize( - "test_input, expected", [ - pytest.param('20', 20), - pytest.param('android-20', 20), - pytest.param('bad-21', "android-'XX'"), - pytest.param('10', "minimum"), - pytest.param('30', "maximum") - ] -) -def test_validate_android_platform_input(test_input, expected): - try: - result = android_support.validate_android_platform_input(input_android_platform=test_input, - platform_variable_type='test', - min_version=TEST_VALIDATE_VERSION_MIN, - max_version=TEST_VALIDATE_VERSION_MAX) - assert isinstance(expected, int) - assert result == expected - except Exception as e: - assert expected in str(e) - - -def test_verify_android_sdk_success(tmpdir): - - test_android_path = 'android_sdk' - sdk_version_number = 28 - sdk_version = f'android-{sdk_version_number}' - - tmpdir.ensure(f'{test_android_path}/platforms/{sdk_version}/package.xml') - - tmpdir.ensure(f'{test_android_path}/build-tools/28.0.3/package.xml') - tmpdir.ensure(f'{test_android_path}/build-tools/29.0.3/package.xml') - - input_sdk_path = tmpdir.join(test_android_path).realpath() - argument_name = '--android-sdk' - - requested_build_tool_version = '29.0.3' - - result_sdk_version, result_sdk_path, result_build_tool_version = android_support.verify_android_sdk(android_sdk_platform=sdk_version, - argument_name=argument_name, - override_android_sdk_path=input_sdk_path, - preferred_sdk_build_tools_ver=requested_build_tool_version) - assert result_sdk_version == sdk_version_number - assert result_sdk_path == input_sdk_path - assert result_build_tool_version == requested_build_tool_version - - sdk_version_number_only = str(sdk_version_number) - result_sdk_version, result_sdk_path, result_build_tool_version = android_support.verify_android_sdk(android_sdk_platform=sdk_version_number_only, - argument_name=argument_name, - override_android_sdk_path=input_sdk_path) - assert result_sdk_version == sdk_version_number - assert result_sdk_path == input_sdk_path - assert result_build_tool_version == '28.0.3' - - requested_build_tool_version = '30.0.3' - result_sdk_version, result_sdk_path, result_build_tool_version = android_support.verify_android_sdk(android_sdk_platform=sdk_version, - argument_name=argument_name, - override_android_sdk_path=input_sdk_path, - preferred_sdk_build_tools_ver=requested_build_tool_version) - assert result_sdk_version == sdk_version_number - assert result_sdk_path == input_sdk_path - assert result_build_tool_version == '28.0.3' - - -@pytest.mark.parametrize( - "desired_ndk_version_number, available_ndk_revisions, pkg_revision, mappings, expect_error", [ - pytest.param(21, [21, 22, 24], '15.2.4203891', None, False, id='preNdk19ExactMatch'), - pytest.param(23, [21, 22, 24], '15.2.4203891', None, False, id='preNdk19FallbackMatch'), - pytest.param(22, [21, 22, 24], '19.2.4203891', {'23': 21}, False, id='postNdk19ExactMatch'), - pytest.param(23, [21, 22, 24], '21.2.4203891', {'23': 21}, False, id='postNdk19MappingMatch'), - pytest.param(android_support.ANDROID_NDK_MIN_PLATFORM-1, [21, 22, 24], '15.2.4203891', None, True, id='preNdk19BelowMinVer'), - pytest.param(android_support.ANDROID_NDK_MAX_PLATFORM+1, [21, 22, 24], '15.2.4203891', None, True, id='preNdk19AboveMaxVer'), - pytest.param(25, [21, 22, 24], '19.2.4203891', {'23': 21}, True, id='postNdk19NoMatch') - ] -) -def test_verify_android_ndk_success(tmpdir, desired_ndk_version_number, available_ndk_revisions, pkg_revision, mappings, expect_error): - - test_android_path = 'android_ndk' - for ndk_number in available_ndk_revisions: - tmpdir.ensure(f'{test_android_path}/platforms/android-{ndk_number}/arch-arm64/usr/lib/libc.so') - - tmpdir.ensure(f'{test_android_path}/source.properties') - test_ndk_source_properties_file = tmpdir / test_android_path / 'source.properties' - test_ndk_source_properties_file.write_text(f'Pkg.Desc = Android NDK\nPkg.Revision = {pkg_revision}\n', encoding='ASCII') - - if mappings: - platform_mapping = { - # min and max are arbitrary for now since we dont use it during evaluation, but if we do, parameterize it here as well - "min": 16, # - "max": 29, - "aliases": {} - } - for key, value in mappings.items(): - platform_mapping['aliases'][key] = value - tmpdir.ensure(f'{test_android_path}/meta/platforms.json') - platform_mapping_file = tmpdir / test_android_path / 'meta/platforms.json' - platform_mapping_file.write_text(json.dumps(platform_mapping), encoding='ASCII') - - input_ndk_path = tmpdir.join(test_android_path).realpath() - - try: - android_ndk_platform_number, android_ndk_path = android_support.verify_android_ndk(android_ndk_platform=str(desired_ndk_version_number), - argument_name="--android-ndk", - override_android_ndk_path=input_ndk_path) - assert not expect_error - assert android_ndk_platform_number == desired_ndk_version_number - assert android_ndk_path == input_ndk_path - except Exception: - assert expect_error - diff --git a/cmake/Tools/common.py b/cmake/Tools/common.py index c6a3e89e67..9c0d31cd53 100755 --- a/cmake/Tools/common.py +++ b/cmake/Tools/common.py @@ -55,6 +55,7 @@ ENGINE_ROOT_CHECK_FILE = 'engine.json' HASH_CHUNK_SIZE = 200000 + class LmbrCmdError(Exception): """ Wrapper class to the general exception class where will absorb and prevent the printing of stack. @@ -244,6 +245,19 @@ def load_template_file(template_file_path, template_env): raise FileNotFoundError(f"Invalid file path. Cannot find template file located at {str(template_file_path)}") +# Determine the possible file extensions for executable files based on the host platform +PLATFORM_EXECUTABLE_EXTENSIONS = [''] # Files without extensions are always considered + +if platform.system() == 'Windows': + # Windows manages its executable extensions through the %PATHEXT% environment variable + path_extensions_str = os.environ.get('PATHEXT', default='.EXE;.COM;.BAT;.CMD') + PLATFORM_EXECUTABLE_EXTENSIONS.extend([pathext.lower() for pathext in path_extensions_str.split(';')]) +elif platform.system() == 'Linux': + PLATFORM_EXECUTABLE_EXTENSIONS = ['', '.out'] +else: + PLATFORM_EXECUTABLE_EXTENSIONS = [''] + + def verify_tool(override_tool_path, tool_name, tool_filename, argument_name, tool_version_argument, tool_version_regex, min_version, max_version): """ Support method to validate a required system tool needed for the build either through an installed tool in the @@ -270,12 +284,21 @@ def verify_tool(override_tool_path, tool_name, tool_filename, argument_name, too elif not isinstance(override_tool_path, pathlib.Path): raise LmbrCmdError(f"Invalid {tool_name} path argument. '{override_tool_path}' must be a string or Path", ERROR_CODE_INVALID_PARAMETER) - check_tool_path = override_tool_path / tool_filename - if not check_tool_path.is_file(): - check_tool_path = pathlib.Path(override_tool_path) / 'bin' / tool_filename + file_found = False + for executable_path_ext in PLATFORM_EXECUTABLE_EXTENSIONS: + check_tool_filename = f'{tool_filename}{executable_path_ext}' - if not check_tool_path.is_file(): + check_tool_path = override_tool_path / check_tool_filename + if check_tool_path.is_file(): + file_found = True + break + check_tool_path = override_tool_path / 'bin' / check_tool_filename + if check_tool_path.is_file(): + file_found = True + break + + if not file_found: raise LmbrCmdError(f"Invalid {tool_name} path argument. '{override_tool_path}' is not a valid {tool_name} path", ERROR_CODE_INVALID_PARAMETER) resolved_override_tool_path = str(check_tool_path.resolve()) @@ -284,7 +307,7 @@ def verify_tool(override_tool_path, tool_name, tool_filename, argument_name, too else: resolved_override_tool_path = None tool_source = tool_name - tool_desc = "installed gradle in the system path" + tool_desc = f"installed {tool_name} in the system path" # Extract the version and verify version_output = subprocess.check_output([tool_source, tool_version_argument], @@ -296,10 +319,10 @@ def verify_tool(override_tool_path, tool_name, tool_filename, argument_name, too result_version = LooseVersion(str(version_match.group(1)).strip()) if min_version and result_version < min_version: - raise LmbrCmdError(f"The {tool_desc} does not meet the minimum version of gradle required ({str(min_version)}).", + raise LmbrCmdError(f"The {tool_desc} does not meet the minimum version of {tool_name} required ({str(min_version)}).", ERROR_CODE_ENVIRONMENT_ERROR) elif max_version and result_version > max_version: - raise LmbrCmdError(f"The {tool_desc} exceeds maximum version of gradle supported ({str(max_version)}).", + raise LmbrCmdError(f"The {tool_desc} exceeds maximum version of {tool_name} supported ({str(max_version)}).", ERROR_CODE_ENVIRONMENT_ERROR) return result_version, resolved_override_tool_path diff --git a/scripts/build/Platform/Android/build_config.json b/scripts/build/Platform/Android/build_config.json index adaa417380..b871670cd0 100644 --- a/scripts/build/Platform/Android/build_config.json +++ b/scripts/build/Platform/Android/build_config.json @@ -141,10 +141,8 @@ "COMMAND":"gradle_windows.cmd", "PARAMETERS": { "CONFIGURATION":"profile", - "OUTPUT_DIRECTORY":"build\\android_gradle", + "OUTPUT_DIRECTORY":"build\\ad_grd", "GAME_PROJECT": "AutomatedTesting", - "ANDROID_NDK_PLATFORM": "21", - "ANDROID_SDK_PLATFORM": "29", "SIGN_APK": "false", "GRADLE_BUILD_CMD": "build", "ADDITIONAL_GENERATE_ARGS": "" @@ -158,8 +156,6 @@ "CONFIGURATION":"profile", "OUTPUT_DIRECTORY":"build\\android_unittest", "GAME_PROJECT": "AutomatedTesting", - "ANDROID_NDK_PLATFORM": "21", - "ANDROID_SDK_PLATFORM": "29", "SIGN_APK": "true", "GRADLE_BUILD_CMD": "assemble", "ADDITIONAL_GENERATE_ARGS": "--unit-test" diff --git a/scripts/build/Platform/Android/gradle_windows.cmd b/scripts/build/Platform/Android/gradle_windows.cmd index 56423af95a..dd5285bdbf 100644 --- a/scripts/build/Platform/Android/gradle_windows.cmd +++ b/scripts/build/Platform/Android/gradle_windows.cmd @@ -17,20 +17,12 @@ IF NOT EXIST "%LY_3RDPARTY_PATH%" ( GOTO :error ) -IF NOT EXIST "%GRADLE_HOME%" ( +IF NOT EXIST "%GRADLE_BUILD_HOME%" ( REM This is the default for developers - SET GRADLE_HOME=C:\Gradle\gradle-5.6.4 + SET GRADLE_BUILD_HOME=C:\Gradle\gradle-7.0 ) -IF NOT EXIST "%GRADLE_HOME%" ( - ECHO [ci_build] FAIL: GRADLE_HOME=%GRADLE_HOME% - GOTO :error -) - -IF NOT EXIST "%CMAKE_HOME%" ( - SET CMAKE_HOME=%LY_3RDPARTY_PATH%/CMake/3.19.1/Windows/ -) -IF NOT EXIST "%CMAKE_HOME%" ( - ECHO [ci_build] FAIL: CMAKE_HOME=%CMAKE_HOME% +IF NOT EXIST "%GRADLE_BUILD_HOME%" ( + ECHO [ci_build] FAIL: GRADLE_BUILD_HOME=%GRADLE_BUILD_HOME% GOTO :error ) @@ -50,20 +42,9 @@ ECHO Ninja wasnt in the call path, add the value set by LY_NINJA_PATH SET PATH=%PATH%;%LY_NINJA_PATH% :ninja_on_path -IF NOT EXIST "%LY_ANDROID_SDK%" ( - SET LY_ANDROID_SDK=!LY_3RDPARTY_PATH!/android-sdk/platform-29 -) -IF NOT EXIST "%LY_ANDROID_SDK%" ( - ECHO [ci_build] FAIL: LY_ANDROID_SDK=!LY_ANDROID_SDK! - GOTO :error -) -IF NOT EXIST "%LY_ANDROID_NDK%" ( - set LY_ANDROID_NDK=!LY_3RDPARTY_PATH!/android-ndk/r21d -) -IF NOT EXIST "%LY_ANDROID_NDK%" ( - ECHO [ci_build] LY_ANDROID_NDK=!LY_ANDROID_NDK! - GOTO :error +IF NOT "%ANDROID_GRADLE_PLUGIN%" == "" ( + set ANDROID_GRADLE_PLUGIN_OPTION=--gradle-plugin-version=%ANDROID_GRADLE_PLUGIN% ) IF NOT EXIST %OUTPUT_DIRECTORY% ( @@ -154,11 +135,11 @@ IF "%GENERATE_SIGNED_APK%"=="true" ( ECHO Using keystore file at %CI_ANDROID_KEYSTORE_FILE_ABS% ) - ECHO [ci_build] %PYTHON% cmake\Tools\Platform\Android\generate_android_project.py --engine-root=. --build-dir=%OUTPUT_DIRECTORY% -g %GAME_PROJECT% --gradle-install-path=%GRADLE_HOME% --cmake-install-path=%CMAKE_HOME% --ninja-install-path=%LY_NINJA_PATH% --third-party-path=%LY_3RDPARTY_PATH% --android-ndk-path=%LY_ANDROID_NDK% --android-sdk-path=%LY_ANDROID_SDK% --android-ndk-version=%ANDROID_NDK_PLATFORM% --android-sdk-version=%ANDROID_SDK_PLATFORM% --signconfig-store-file %CI_ANDROID_KEYSTORE_FILE_ABS% --signconfig-store-password %CI_ANDROID_KEYSTORE_PASSWORD% --signconfig-key-alias %CI_ANDROID_KEYSTORE_ALIAS% --signconfig-key-password %CI_ANDROID_KEYSTORE_PASSWORD% %OPTIONAL_TEST_FLAG% %ADDITIONAL_GENERATE_ARGS% --overwrite-existing - CALL %PYTHON% cmake\Tools\Platform\Android\generate_android_project.py --engine-root=. --build-dir=%OUTPUT_DIRECTORY% -g %GAME_PROJECT% --gradle-install-path=%GRADLE_HOME% --cmake-install-path=%CMAKE_HOME% --ninja-install-path=%LY_NINJA_PATH% --third-party-path=%LY_3RDPARTY_PATH% --android-ndk-path=%LY_ANDROID_NDK% --android-sdk-path=%LY_ANDROID_SDK% --android-ndk-version=%ANDROID_NDK_PLATFORM% --android-sdk-version=%ANDROID_SDK_PLATFORM% --signconfig-store-file %CI_ANDROID_KEYSTORE_FILE_ABS% --signconfig-store-password %CI_ANDROID_KEYSTORE_PASSWORD% --signconfig-key-alias %CI_ANDROID_KEYSTORE_ALIAS% --signconfig-key-password %CI_ANDROID_KEYSTORE_PASSWORD% %ADDITIONAL_GENERATE_ARGS% --overwrite-existing + ECHO [ci_build] %PYTHON% cmake\Tools\Platform\Android\generate_android_project.py --engine-root=. --build-dir=%OUTPUT_DIRECTORY% -g %GAME_PROJECT% --gradle-install-path=%GRADLE_BUILD_HOME% --ninja-install-path=%LY_NINJA_PATH% --third-party-path=%LY_3RDPARTY_PATH% --android-sdk-path=%ANDROID_HOME% %ANDROID_GRADLE_PLUGIN_OPTION% --signconfig-store-file %CI_ANDROID_KEYSTORE_FILE_ABS% --signconfig-store-password %CI_ANDROID_KEYSTORE_PASSWORD% --signconfig-key-alias %CI_ANDROID_KEYSTORE_ALIAS% --signconfig-key-password %CI_ANDROID_KEYSTORE_PASSWORD% %ADDITIONAL_GENERATE_ARGS% --overwrite-existing + CALL %PYTHON% cmake\Tools\Platform\Android\generate_android_project.py --engine-root=. --build-dir=%OUTPUT_DIRECTORY% -g %GAME_PROJECT% --gradle-install-path=%GRADLE_BUILD_HOME% --ninja-install-path=%LY_NINJA_PATH% --third-party-path=%LY_3RDPARTY_PATH% --android-sdk-path=%ANDROID_HOME% %ANDROID_GRADLE_PLUGIN_OPTION% --signconfig-store-file %CI_ANDROID_KEYSTORE_FILE_ABS% --signconfig-store-password %CI_ANDROID_KEYSTORE_PASSWORD% --signconfig-key-alias %CI_ANDROID_KEYSTORE_ALIAS% --signconfig-key-password %CI_ANDROID_KEYSTORE_PASSWORD% %ADDITIONAL_GENERATE_ARGS% --overwrite-existing ) ELSE ( - ECHO [ci_build] %PYTHON% cmake\Tools\Platform\Android\generate_android_project.py --engine-root=. --build-dir=%OUTPUT_DIRECTORY% -g %GAME_PROJECT% --gradle-install-path=%GRADLE_HOME% --cmake-install-path=%CMAKE_HOME% --ninja-install-path=%LY_NINJA_PATH% --third-party-path=%LY_3RDPARTY_PATH% --android-ndk-path=%LY_ANDROID_NDK% --android-sdk-path=%LY_ANDROID_SDK% --android-ndk-version=%ANDROID_NDK_PLATFORM% --android-sdk-version=%ANDROID_SDK_PLATFORM% %ADDITIONAL_GENERATE_ARGS% --overwrite-existing - CALL %PYTHON% cmake\Tools\Platform\Android\generate_android_project.py --engine-root=. --build-dir=%OUTPUT_DIRECTORY% -g %GAME_PROJECT% --gradle-install-path=%GRADLE_HOME% --cmake-install-path=%CMAKE_HOME% --ninja-install-path=%LY_NINJA_PATH% --third-party-path=%LY_3RDPARTY_PATH% --android-ndk-path=%LY_ANDROID_NDK% --android-sdk-path=%LY_ANDROID_SDK% --android-ndk-version=%ANDROID_NDK_PLATFORM% --android-sdk-version=%ANDROID_SDK_PLATFORM% %ADDITIONAL_GENERATE_ARGS% --overwrite-existing + ECHO [ci_build] %PYTHON% cmake\Tools\Platform\Android\generate_android_project.py --engine-root=. --build-dir=%OUTPUT_DIRECTORY% -g %GAME_PROJECT% %GRADLE_OVERRIDE_OPTION% --ninja-install-path=%LY_NINJA_PATH% --third-party-path=%LY_3RDPARTY_PATH% %ANDROID_GRADLE_PLUGIN_OPTION% --android-sdk-path=%ANDROID_HOME% %ADDITIONAL_GENERATE_ARGS% --overwrite-existing + CALL %PYTHON% cmake\Tools\Platform\Android\generate_android_project.py --engine-root=. --build-dir=%OUTPUT_DIRECTORY% -g %GAME_PROJECT% --gradle-install-path=%GRADLE_BUILD_HOME% --ninja-install-path=%LY_NINJA_PATH% --third-party-path=%LY_3RDPARTY_PATH% %ANDROID_GRADLE_PLUGIN_OPTION% --android-sdk-path=%ANDROID_HOME% %ADDITIONAL_GENERATE_ARGS% --overwrite-existing ) REM Validate the android project generation diff --git a/scripts/build/Platform/Android/pipeline.json b/scripts/build/Platform/Android/pipeline.json index ed10e7022d..551374a027 100644 --- a/scripts/build/Platform/Android/pipeline.json +++ b/scripts/build/Platform/Android/pipeline.json @@ -1,7 +1,7 @@ { "ENV": { - "GRADLE_HOME": "C:/Gradle/gradle-5.6.4", - "NODE_LABEL": "windows-047e5cdf", + "GRADLE_HOME": "C:/Gradle/gradle-7.0", + "NODE_LABEL": "windows-b3c8994f1", "LY_3RDPARTY_PATH": "C:/ly/3rdParty", "TIMEOUT": 30, "WORKSPACE": "D:/workspace", From 59ab6edaefc08768f2b1f933097df07c339103fa Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Mon, 31 May 2021 01:38:13 -0700 Subject: [PATCH 356/811] Added occlusion culling plane visualization --- ...lingPlaneTransparentVisualization.material | 22 ++++ ...cclusionCullingPlaneVisualization.material | 22 ++++ .../Assets/Models/OcclusionCullingPlane.fbx | 3 + ...ionCullingPlaneFeatureProcessorInterface.h | 2 + .../OcclusionCullingPlane.cpp | 113 ++++++++++++++++++ .../OcclusionCullingPlane.h | 65 ++++++++++ .../OcclusionCullingPlaneFeatureProcessor.cpp | 13 ++ .../OcclusionCullingPlaneFeatureProcessor.h | 21 +--- .../Code/atom_feature_common_files.cmake | 2 + .../RPI/Code/Source/RPI.Public/Culling.cpp | 72 ++++++++--- Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp | 6 +- .../EditorOcclusionCullingPlaneComponent.cpp | 6 +- ...clusionCullingPlaneComponentController.cpp | 8 +- ...OcclusionCullingPlaneComponentController.h | 3 + 14 files changed, 321 insertions(+), 37 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Assets/Materials/OcclusionCullingPlane/OcclusionCullingPlaneTransparentVisualization.material create mode 100644 Gems/Atom/Feature/Common/Assets/Materials/OcclusionCullingPlane/OcclusionCullingPlaneVisualization.material create mode 100644 Gems/Atom/Feature/Common/Assets/Models/OcclusionCullingPlane.fbx create mode 100644 Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlane.cpp create mode 100644 Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlane.h diff --git a/Gems/Atom/Feature/Common/Assets/Materials/OcclusionCullingPlane/OcclusionCullingPlaneTransparentVisualization.material b/Gems/Atom/Feature/Common/Assets/Materials/OcclusionCullingPlane/OcclusionCullingPlaneTransparentVisualization.material new file mode 100644 index 0000000000..981e392eef --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Materials/OcclusionCullingPlane/OcclusionCullingPlaneTransparentVisualization.material @@ -0,0 +1,22 @@ +{ + "materialType": "Materials\\Types\\StandardPBR.materialtype", + "propertyLayoutVersion": 3, + "properties": { + "general": { + "enableShadows": false, + "enableDirectionalLights": false, + "enablePunctualLights": false, + "enableAreaLights": false, + "enableIBL": true + }, + "baseColor": { + "color": [ 0.0, 1.0, 0.0 ] + }, + "opacity": { + "alphaSource": "None", + "doubleSided": true, + "factor": 0.25, + "mode": "TintedTransparent" + } + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Materials/OcclusionCullingPlane/OcclusionCullingPlaneVisualization.material b/Gems/Atom/Feature/Common/Assets/Materials/OcclusionCullingPlane/OcclusionCullingPlaneVisualization.material new file mode 100644 index 0000000000..4446cc2d9d --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Materials/OcclusionCullingPlane/OcclusionCullingPlaneVisualization.material @@ -0,0 +1,22 @@ +{ + "materialType": "Materials\\Types\\StandardPBR.materialtype", + "propertyLayoutVersion": 3, + "properties": { + "general": { + "enableShadows": false, + "enableDirectionalLights": false, + "enablePunctualLights": false, + "enableAreaLights": false, + "enableIBL": true + }, + "baseColor": { + "color": [ 0.0, 1.0, 0.0 ] + }, + "opacity": { + "alphaSource": "None", + "doubleSided": true, + "factor": 1.0, + "mode": "TintedTransparent" + } + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Models/OcclusionCullingPlane.fbx b/Gems/Atom/Feature/Common/Assets/Models/OcclusionCullingPlane.fbx new file mode 100644 index 0000000000..b274bfa282 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Models/OcclusionCullingPlane.fbx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a1f8d75dcd85e8b4aa57f6c0c81af0300ff96915ba3c2b591095c215d5e1d8c +size 12072 diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessorInterface.h index 07a6179e78..8ffbb7f235 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessorInterface.h @@ -36,6 +36,8 @@ namespace AZ virtual bool IsValidOcclusionCullingPlaneHandle(const OcclusionCullingPlaneHandle& occlusionCullingPlane) const = 0; virtual void SetTransform(const OcclusionCullingPlaneHandle& occlusionCullingPlane, const AZ::Transform& transform) = 0; virtual void SetEnabled(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool enabled) = 0; + virtual void ShowVisualization(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool showVisualization) = 0; + virtual void SetTransparentVisualization(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool transparentVisualization) = 0; }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlane.cpp b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlane.cpp new file mode 100644 index 0000000000..10004a72e4 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlane.cpp @@ -0,0 +1,113 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + static const char* OcclusionCullingPlaneDrawListTag("occlusioncullingplanevisualization"); + + OcclusionCullingPlane::~OcclusionCullingPlane() + { + Data::AssetBus::MultiHandler::BusDisconnect(); + m_meshFeatureProcessor->ReleaseMesh(m_visualizationMeshHandle); + } + + void OcclusionCullingPlane::Init(RPI::Scene* scene) + { + AZ_Assert(scene, "OcclusionCullingPlane::Init called with a null Scene pointer"); + + m_meshFeatureProcessor = scene->GetFeatureProcessor(); + + // load visualization plane model and material + m_visualizationModelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath( + "Models/OcclusionCullingPlane.azmodel", + AZ::RPI::AssetUtils::TraceLevel::Assert); + + m_visualizationMeshHandle = m_meshFeatureProcessor->AcquireMesh(m_visualizationModelAsset); + m_meshFeatureProcessor->SetExcludeFromReflectionCubeMaps(m_visualizationMeshHandle, true); + m_meshFeatureProcessor->SetRayTracingEnabled(m_visualizationMeshHandle, false); + m_meshFeatureProcessor->SetTransform(m_visualizationMeshHandle, AZ::Transform::CreateIdentity()); + + SetVisualizationMaterial(); + } + + void OcclusionCullingPlane::SetVisualizationMaterial() + { + AZStd::string materialAssetPath; + if (m_transparentVisualization) + { + materialAssetPath = "Materials/OcclusionCullingPlane/OcclusionCullingPlaneTransparentVisualization.azmaterial"; + } + else + { + materialAssetPath = "Materials/OcclusionCullingPlane/OcclusionCullingPlaneVisualization.azmaterial"; + } + + RPI::AssetUtils::TraceLevel traceLevel = AZ::RPI::AssetUtils::TraceLevel::Assert; + m_visualizationMaterialAsset = AZ::RPI::AssetUtils::GetAssetByProductPath(materialAssetPath.c_str(), traceLevel); + m_visualizationMaterialAsset.QueueLoad(); + Data::AssetBus::MultiHandler::BusConnect(m_visualizationMaterialAsset.GetId()); + } + + void OcclusionCullingPlane::OnAssetReady(Data::Asset asset) + { + if (m_visualizationMaterialAsset.GetId() == asset.GetId()) + { + m_visualizationMaterialAsset = asset; + Data::AssetBus::MultiHandler::BusDisconnect(asset.GetId()); + + m_visualizationMaterial = AZ::RPI::Material::FindOrCreate(m_visualizationMaterialAsset); + m_meshFeatureProcessor->SetMaterialAssignmentMap(m_visualizationMeshHandle, m_visualizationMaterial); + } + } + + void OcclusionCullingPlane::OnAssetError(Data::Asset asset) + { + AZ_Error("OcclusionCullingPlane", false, "Failed to load OcclusionCullingPlane visualization asset %s", asset.ToString().c_str()); + Data::AssetBus::MultiHandler::BusDisconnect(asset.GetId()); + } + + void OcclusionCullingPlane::SetTransform(const AZ::Transform& transform) + { + m_transform = transform; + + // update visualization plane transform + m_meshFeatureProcessor->SetTransform(m_visualizationMeshHandle, transform); + } + + void OcclusionCullingPlane::ShowVisualization(bool showVisualization) + { + if (m_showVisualization != showVisualization) + { + m_meshFeatureProcessor->SetVisible(m_visualizationMeshHandle, showVisualization); + SetVisualizationMaterial(); + } + } + + void OcclusionCullingPlane::SetTransparentVisualization(bool transparentVisualization) + { + if (m_transparentVisualization != transparentVisualization) + { + m_transparentVisualization = transparentVisualization; + SetVisualizationMaterial(); + } + } + + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlane.h b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlane.h new file mode 100644 index 0000000000..4701c4977f --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlane.h @@ -0,0 +1,65 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include + +namespace AZ +{ + namespace Render + { + //! This class represents an OcclusionCullingPlane which is used to cull meshes that are inside the view frustum + class OcclusionCullingPlane final + : public AZ::Data::AssetBus::MultiHandler + { + public: + OcclusionCullingPlane() = default; + ~OcclusionCullingPlane(); + + void Init(RPI::Scene* scene); + + void SetTransform(const AZ::Transform& transform); + const AZ::Transform& GetTransform() const { return m_transform; } + + void SetEnabled(bool enabled) { m_enabled = enabled; } + bool GetEnabled() const { return m_enabled; } + + // enables or disables rendering of the visualization plane + void ShowVisualization(bool showVisualization); + + // sets the visualization to transparent mode + void SetTransparentVisualization(bool transparentVisualization); + + private: + + void SetVisualizationMaterial(); + + // AZ::Data::AssetBus::Handler overrides... + void OnAssetReady(Data::Asset asset) override; + void OnAssetError(Data::Asset asset) override; + + AZ::Transform m_transform; + bool m_enabled = true; + bool m_showVisualization = true; + bool m_transparentVisualization = false; + + // visualization + AZ::Render::MeshFeatureProcessorInterface* m_meshFeatureProcessor = nullptr; + Data::Asset m_visualizationModelAsset; + Data::Asset m_visualizationMaterialAsset; + Data::Instance m_visualizationMaterial; + AZ::Render::MeshFeatureProcessorInterface::MeshHandle m_visualizationMeshHandle; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp index bed008a3da..b9866a925f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp @@ -60,6 +60,7 @@ namespace AZ OcclusionCullingPlaneHandle OcclusionCullingPlaneFeatureProcessor::AddOcclusionCullingPlane(const AZ::Transform& transform) { AZStd::shared_ptr occlusionCullingPlane = AZStd::make_shared(); + occlusionCullingPlane->Init(GetParentScene()); occlusionCullingPlane->SetTransform(transform); m_occlusionCullingPlanes.push_back(occlusionCullingPlane); return occlusionCullingPlane; @@ -90,5 +91,17 @@ namespace AZ AZ_Assert(occlusionCullingPlane.get(), "Enable called with an invalid handle"); occlusionCullingPlane->SetEnabled(enabled); } + + void OcclusionCullingPlaneFeatureProcessor::ShowVisualization(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool showVisualization) + { + AZ_Assert(occlusionCullingPlane.get(), "ShowVisualization called with an invalid handle"); + occlusionCullingPlane->ShowVisualization(showVisualization); + } + + void OcclusionCullingPlaneFeatureProcessor::SetTransparentVisualization(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool transparentVisualization) + { + AZ_Assert(occlusionCullingPlane.get(), "SetTransparentVisualization called with an invalid handle"); + occlusionCullingPlane->SetTransparentVisualization(transparentVisualization); + } } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h index 5319666745..211254742f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h @@ -13,29 +13,12 @@ #pragma once #include +#include namespace AZ { namespace Render { - //! This class represents an OcclusionCullingPlane which is used to cull meshes that are inside the view frustum - class OcclusionCullingPlane final - { - public: - OcclusionCullingPlane() = default; - ~OcclusionCullingPlane() = default; - - void SetTransform(const AZ::Transform& transform) { m_transform = transform; } - const AZ::Transform& GetTransform() const { return m_transform; } - - void SetEnabled(bool enabled) { m_enabled = enabled; } - bool GetEnabled() const { return m_enabled; } - - private: - AZ::Transform m_transform; - bool m_enabled = true; - }; - //! This class manages OcclusionCullingPlanes which are used to cull meshes that are inside the view frustum class OcclusionCullingPlaneFeatureProcessor final : public OcclusionCullingPlaneFeatureProcessorInterface @@ -54,6 +37,8 @@ namespace AZ bool IsValidOcclusionCullingPlaneHandle(const OcclusionCullingPlaneHandle& occlusionCullingPlane) const override { return (occlusionCullingPlane.get() != nullptr); } void SetTransform(const OcclusionCullingPlaneHandle& occlusionCullingPlane, const AZ::Transform& transform) override; void SetEnabled(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool enable) override; + void ShowVisualization(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool showVisualization) override; + void SetTransparentVisualization(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool transparentVisualization) override; // FeatureProcessor overrides void Activate() override; diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake index c545a2c974..b796a5b356 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -175,6 +175,8 @@ set(FILES Source/MorphTargets/MorphTargetDispatchItem.h Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp + Source/OcclusionCullingPlane/OcclusionCullingPlane.h + Source/OcclusionCullingPlane/OcclusionCullingPlane.cpp Source/PostProcess/PostProcessBase.cpp Source/PostProcess/PostProcessBase.h Source/PostProcess/PostProcessFeatureProcessor.cpp diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index e105f7bca5..d8ed850309 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -428,20 +428,52 @@ namespace AZ return MaskedOcclusionCulling::CullingResult::VISIBLE; } - // convert the bounding box of the visibility entry to NDC - AZ::Vector4 clipSpaceMin = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(visibleEntry->m_boundingVolume.GetMin()); - float depth = clipSpaceMin.GetW(); - AZ::Vector4 ndcMin = clipSpaceMin / clipSpaceMin.GetW(); + if (visibleEntry->m_boundingVolume.Contains(m_jobData->m_view->GetCameraTransform().GetTranslation())) + { + // camera is inside bounding volume + return MaskedOcclusionCulling::CullingResult::VISIBLE; + } - AZ::Vector4 clipSpaceMax = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(visibleEntry->m_boundingVolume.GetMax()); - depth = AZStd::min(depth, clipSpaceMax.GetW()); - AZ::Vector4 ndcMax = clipSpaceMax / clipSpaceMax.GetW(); + const Vector3& minBound = visibleEntry->m_boundingVolume.GetMin(); + const Vector3& maxBound = visibleEntry->m_boundingVolume.GetMax(); - Vector2 rectMin(AZStd::min(ndcMin.GetX(), ndcMax.GetX()), AZStd::min(ndcMin.GetY(), ndcMax.GetY())); - Vector2 rectMax(AZStd::max(ndcMin.GetX(), ndcMax.GetX()), AZStd::max(ndcMin.GetY(), ndcMax.GetY())); + // compute bounding volume corners + Vector4 corners[8]; + corners[0] = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(minBound.GetX(), minBound.GetY(), minBound.GetZ(), 1.0f); + corners[1] = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(minBound.GetX(), minBound.GetY(), maxBound.GetZ(), 1.0f); + corners[2] = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(maxBound.GetX(), minBound.GetY(), maxBound.GetZ(), 1.0f); + corners[3] = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(maxBound.GetX(), minBound.GetY(), minBound.GetZ(), 1.0f); + corners[4] = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(minBound.GetX(), maxBound.GetY(), minBound.GetZ(), 1.0f); + corners[5] = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(minBound.GetX(), maxBound.GetY(), maxBound.GetZ(), 1.0f); + corners[6] = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(maxBound.GetX(), maxBound.GetY(), maxBound.GetZ(), 1.0f); + corners[7] = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(maxBound.GetX(), maxBound.GetY(), minBound.GetZ(), 1.0f); + // find min clip-space depth and NDC min/max + float ndcMinX = FLT_MAX; + float ndcMinY = FLT_MAX; + float ndcMaxX = -FLT_MAX; + float ndcMaxY = -FLT_MAX; + float minDepth = FLT_MAX; + for (uint32_t index = 0; index < 8; ++index) + { + minDepth = AZStd::min(minDepth, corners[index].GetW()); + + // convert to NDC + corners[index] /= corners[index].GetW(); + + ndcMinX = AZStd::min(ndcMinX, corners[index].GetX()); + ndcMinY = AZStd::min(ndcMinY, corners[index].GetY()); + ndcMaxX = AZStd::max(ndcMaxX, corners[index].GetX()); + ndcMaxY = AZStd::max(ndcMaxY, corners[index].GetY()); + } + + if (minDepth < 0.00000001f) + { + return MaskedOcclusionCulling::VISIBLE; + } + // test against the occlusion buffer, which contains only the manually placed occlusion planes - return m_jobData->m_maskedOcclusionCulling->TestRect(rectMin.GetX(), rectMin.GetY(), rectMax.GetX(), rectMax.GetY(), depth); + return m_jobData->m_maskedOcclusionCulling->TestRect(ndcMinX, ndcMinY, ndcMaxX, ndcMaxY, minDepth); } }; @@ -480,15 +512,22 @@ namespace AZ MaskedOcclusionCulling* maskedOcclusionCulling = m_occlusionCullingPlanes.empty() ? nullptr : view.GetMaskedOcclusionCulling(); if (maskedOcclusionCulling) { - // frustum cull and sort the occlusion planes by view space distance, front-to-back + // frustum cull occlusion planes using OccluderEntry = AZStd::pair; AZStd::vector visibleOccluders; for (const AZ::Transform& transform : m_occlusionCullingPlanes) { - Aabb occluderAabb = Aabb::CreateCenterHalfExtents(transform.GetTranslation(), AZ::Vector3(AZ::Vector2(transform.GetUniformScale() / 2.0f))); - occluderAabb.SetMin(transform.TransformPoint(occluderAabb.GetMin())); - occluderAabb.SetMax(transform.TransformPoint(occluderAabb.GetMax())); - if (ShapeIntersection::Contains(frustum, occluderAabb)) + static const AZ::Vector3 BL(-0.5f, -0.5f, 0.0f); + static const AZ::Vector3 TR(0.5f, 0.5f, 0.0f); + + AZ::Vector3 P1 = transform.TransformPoint(BL); + AZ::Vector3 P2 = transform.TransformPoint(TR); + + AZ::Vector3 aabbMin = P1.GetMin(P2); + AZ::Vector3 aabbMax = P1.GetMax(P2); + + AZ::Aabb occluderAabb = Aabb::CreateFromMinMax(aabbMin, aabbMax); + if (ShapeIntersection::Overlaps(frustum, occluderAabb)) { // occluder is visible, compute view space distance and add to list float depth = (view.GetWorldToViewMatrix() * occluderAabb.GetMin()).GetZ(); @@ -498,9 +537,10 @@ namespace AZ } } + // sort the occlusion planes by view space distance, front-to-back AZStd::sort(visibleOccluders.begin(), visibleOccluders.end(), [](const OccluderEntry& LHS, const OccluderEntry& RHS) { - return LHS.second < RHS.second; + return LHS.second > RHS.second; }); for (const OccluderEntry& occluder : visibleOccluders) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index edae0f88b7..6e4dec112f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -28,6 +28,10 @@ namespace AZ { namespace RPI { + // fixed-size software occlusion culling buffer + const uint32_t MaskedSoftwareOcclusionCullingWidth = 1920; + const uint32_t MaskedSoftwareOcclusionCullingHeight = 1080; + ViewPtr View::CreateView(const AZ::Name& name, UsageFlags usage) { View* view = aznew View(name, usage); @@ -54,7 +58,7 @@ namespace AZ } m_maskedOcclusionCulling = MaskedOcclusionCulling::Create(); - m_maskedOcclusionCulling->SetResolution(1920, 1080); + m_maskedOcclusionCulling->SetResolution(MaskedSoftwareOcclusionCullingWidth, MaskedSoftwareOcclusionCullingHeight); } View::~View() diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.cpp index 9a655727d6..b027be3171 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.cpp @@ -53,8 +53,12 @@ namespace AZ editContext->Class( "OcclusionCullingPlaneComponentConfig", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->ClassElement(AZ::Edit::ClassElements::Group, "Settings") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::CheckBox, &OcclusionCullingPlaneComponentConfig::m_showVisualization, "Show Visualization", "Show the occlusion culling plane visualization") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + ->DataElement(AZ::Edit::UIHandlers::CheckBox, &OcclusionCullingPlaneComponentConfig::m_transparentVisualization, "Transparent Visualization", "Sets the occlusion culling plane visualization as transparent") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ; } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.cpp index bd03bec0f4..cf8107776f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.cpp @@ -38,7 +38,9 @@ namespace AZ { serializeContext->Class() ->Version(0) - ; + ->Field("ShowVisualization", &OcclusionCullingPlaneComponentConfig::m_showVisualization) + ->Field("TransparentVisualization", &OcclusionCullingPlaneComponentConfig::m_transparentVisualization) + ; } } @@ -98,6 +100,10 @@ namespace AZ // add this occlusion plane to the feature processor const AZ::Transform& transform = m_transformInterface->GetWorldTM(); m_handle = m_featureProcessor->AddOcclusionCullingPlane(transform); + + // set visualization + m_featureProcessor->ShowVisualization(m_handle, m_configuration.m_showVisualization); + m_featureProcessor->SetTransparentVisualization(m_handle, m_configuration.m_transparentVisualization); } void OcclusionCullingPlaneComponentController::Deactivate() diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.h index 5f0be5315f..2d977a2cf3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneComponentController.h @@ -32,6 +32,9 @@ namespace AZ AZ_CLASS_ALLOCATOR(OcclusionCullingPlaneComponentConfig, SystemAllocator, 0); static void Reflect(AZ::ReflectContext* context); + bool m_showVisualization = true; + bool m_transparentVisualization = false; + OcclusionCullingPlaneComponentConfig() = default; }; From 370f28f69cc06a471534c69f691e3b8e906669c1 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 1 Jun 2021 01:28:13 -0700 Subject: [PATCH 357/811] Missing PHYSX_ENABLE_MULTI_THREADING for PhysX.Editor --- Gems/PhysX/Code/CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Gems/PhysX/Code/CMakeLists.txt b/Gems/PhysX/Code/CMakeLists.txt index b0318af9f2..d281270ce4 100644 --- a/Gems/PhysX/Code/CMakeLists.txt +++ b/Gems/PhysX/Code/CMakeLists.txt @@ -128,6 +128,9 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) AUTOMOC FILES_CMAKE physx_editor_shared_files.cmake + COMPILE_DEFINITIONS + PUBLIC + PHYSX_ENABLE_MULTI_THREADING INCLUDE_DIRECTORIES PRIVATE . From 3947dcf213e0b5326d7d33b25868e2363497869a Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Tue, 1 Jun 2021 09:36:00 +0100 Subject: [PATCH 358/811] Add some extra cvars to control orbit point appearance and remove unused ones (#1032) --- .../AzFramework/Viewport/CameraInput.cpp | 3 +-- .../ModularViewportCameraController.cpp | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index d5f02c957c..559f7ce460 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -29,7 +29,7 @@ namespace AzFramework AZ_CVAR(float, ed_cameraSystemOrbitDollyScrollSpeed, 0.02f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemOrbitDollyCursorSpeed, 0.01f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemScrollTranslateSpeed, 0.02f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); - AZ_CVAR(float, ed_cameraSystemMinOrbitDistance, 6.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemMinOrbitDistance, 10.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemMaxOrbitDistance, 50.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemLookSmoothness, 5.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemTranslateSmoothness, 5.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); @@ -37,7 +37,6 @@ namespace AzFramework AZ_CVAR(float, ed_cameraSystemPanSpeed, 0.01f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(bool, ed_cameraSystemPanInvertX, true, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(bool, ed_cameraSystemPanInvertY, true, nullptr, AZ::ConsoleFunctorFlags::Null, ""); - AZ_CVAR(float, ed_cameraSystemLookDeadzone, 2.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR( AZ::CVarFixedString, ed_cameraSystemTranslateForwardKey, "keyboard_key_alphanumeric_W", nullptr, AZ::ConsoleFunctorFlags::Null, ""); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp index 6fb3edfa22..896d9f8043 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -24,6 +25,11 @@ namespace AtomToolsFramework { + AZ_CVAR( + AZ::Color, ed_cameraSystemOrbitPointColor, AZ::Color::CreateFromRgba(255, 255, 255, 255), nullptr, AZ::ConsoleFunctorFlags::Null, + ""); + AZ_CVAR(float, ed_cameraSystemOrbitPointSize, 0.5f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + // debug void DrawPreviewAxis(AzFramework::DebugDisplayRequests& display, const AZ::Transform& transform, const float axisLength) { @@ -73,7 +79,8 @@ namespace AtomToolsFramework if (auto viewportContext = RetrieveViewportContext(GetViewportId())) { - auto handleCameraChange = [this, viewportContext](const AZ::Matrix4x4&) { + auto handleCameraChange = [this, viewportContext](const AZ::Matrix4x4&) + { if (!m_updatingTransform) { UpdateCameraFromTransform(m_targetCamera, viewportContext->GetCameraTransform()); @@ -137,7 +144,10 @@ namespace AtomToolsFramework } else if (m_cameraMode == CameraMode::Animation) { - const auto smootherStepFn = [](const float t) { return t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f); }; + const auto smootherStepFn = [](const float t) + { + return t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f); + }; const float transitionT = smootherStepFn(m_animationT); const AZ::Transform current = AZ::Transform::CreateFromQuaternionAndTranslation( @@ -169,8 +179,9 @@ namespace AtomToolsFramework { if (const float alpha = AZStd::min(-m_camera.m_lookDist / 5.0f, 1.0f); alpha > AZ::Constants::FloatEpsilon) { - debugDisplay.SetColor(1.0f, 1.0f, 1.0f, alpha); - debugDisplay.DrawWireSphere(m_camera.m_lookAt, 0.5f); + const AZ::Color orbitPointColor = ed_cameraSystemOrbitPointColor; + debugDisplay.SetColor(orbitPointColor.GetR(), orbitPointColor.GetG(), orbitPointColor.GetB(), alpha); + debugDisplay.DrawWireSphere(m_camera.m_lookAt, ed_cameraSystemOrbitPointSize); } } From 99ba89a02b82a408089ea55983bab77b78d6ec31 Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Tue, 1 Jun 2021 09:37:02 +0100 Subject: [PATCH 359/811] Add console function to print entity name from entity id (#1021) * Add console function to print entity name from entity id * update name of console function an improve description --- .../AzCore/Component/ComponentApplication.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index 1010ae3473..7b33359023 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -77,6 +77,27 @@ #endif // defined(AZ_ENABLE_DEBUG_TOOLS) #include +#include + +static void PrintEntityName(const AZ::ConsoleCommandContainer& arguments) +{ + if (arguments.empty()) + { + return; + } + + const auto entityIdStr = AZStd::string(arguments.front()); + const auto entityIdValue = AZStd::stoull(entityIdStr); + + AZStd::string entityName; + AZ::ComponentApplicationBus::BroadcastResult( + entityName, &AZ::ComponentApplicationBus::Events::GetEntityName, AZ::EntityId(entityIdValue)); + + AZ_Printf("Entity Debug", "EntityId: %" PRIu64 ", Entity Name: %s", entityIdValue, entityName.c_str()); +} + +AZ_CONSOLEFREEFUNC( + PrintEntityName, AZ::ConsoleFunctorFlags::Null, "Parameter: EntityId value, Prints the name of the entity to the console"); namespace AZ { From c03669df72886ce3c51ecb9d0526976a16fbcc81 Mon Sep 17 00:00:00 2001 From: Aaron Ruiz Mora Date: Tue, 1 Jun 2021 15:16:50 +0100 Subject: [PATCH 360/811] Updating default physics material library with the latest materials (#1056) --- .../surfacetypemateriallibrary.physmaterial | 153 ++++++++++++++++-- 1 file changed, 144 insertions(+), 9 deletions(-) diff --git a/AutomatedTesting/surfacetypemateriallibrary.physmaterial b/AutomatedTesting/surfacetypemateriallibrary.physmaterial index 434d673998..481cd2fbfa 100644 --- a/AutomatedTesting/surfacetypemateriallibrary.physmaterial +++ b/AutomatedTesting/surfacetypemateriallibrary.physmaterial @@ -4,17 +4,152 @@ - - - - - - - - + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 7d1fedc10c442269811ce4531bf9434e653acb2c Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 1 Jun 2021 08:29:35 -0700 Subject: [PATCH 361/811] LYN-4128 EditorPythonBindings.Editor in debug does not load (missing python_d.dll) --- Gems/PythonAssetBuilder/Code/CMakeLists.txt | 26 ++++++------------- .../Common/RuntimeDependencies_common.cmake | 2 +- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/Gems/PythonAssetBuilder/Code/CMakeLists.txt b/Gems/PythonAssetBuilder/Code/CMakeLists.txt index 4af266f56d..73fa90ab67 100644 --- a/Gems/PythonAssetBuilder/Code/CMakeLists.txt +++ b/Gems/PythonAssetBuilder/Code/CMakeLists.txt @@ -13,24 +13,11 @@ if(NOT PAL_TRAIT_BUILD_HOST_TOOLS) return() endif() -set(static_files pythonassetbuilder_common_files.cmake) -set(editor_files pythonassetbuilder_editor_files.cmake) -set(shared_files pythonassetbuilder_shared_files.cmake) -set(static_dependencies - 3rdParty::Python - Gem::EditorPythonBindings.Static - AZ::AssetBuilderSDK -) -set(editor_dependencies - Gem::EditorPythonBindings.Static - AZ::AssetBuilderSDK -) - ly_add_target( NAME PythonAssetBuilder.Static STATIC NAMESPACE Gem FILES_CMAKE - ${static_files} + pythonassetbuilder_common_files.cmake PLATFORM_INCLUDE_FILES Source/Platform/Common/${PAL_TRAIT_COMPILER_ID}/pythonassetbuilder_static_${PAL_TRAIT_COMPILER_ID_LOWERCASE}.cmake INCLUDE_DIRECTORIES @@ -43,7 +30,9 @@ ly_add_target( PRIVATE AZ::AzCore PUBLIC - ${static_dependencies} + 3rdParty::Python + Gem::EditorPythonBindings.Static + AZ::AssetBuilderSDK AZ::AzToolsFramework ) @@ -52,8 +41,8 @@ ly_add_target( NAMESPACE Gem FILES_CMAKE - ${editor_files} - ${shared_files} + pythonassetbuilder_editor_files.cmake + pythonassetbuilder_shared_files.cmake PLATFORM_INCLUDE_FILES Source/Platform/Common/${PAL_TRAIT_COMPILER_ID}/pythonassetbuilder_static_${PAL_TRAIT_COMPILER_ID_LOWERCASE}.cmake INCLUDE_DIRECTORIES @@ -64,7 +53,8 @@ ly_add_target( Include BUILD_DEPENDENCIES PRIVATE - ${editor_dependencies} + Gem::EditorPythonBindings.Static + AZ::AssetBuilderSDK RUNTIME_DEPENDENCIES Gem::EditorPythonBindings.Editor ) diff --git a/cmake/Platform/Common/RuntimeDependencies_common.cmake b/cmake/Platform/Common/RuntimeDependencies_common.cmake index d9d0fe4c7f..4ae914744f 100644 --- a/cmake/Platform/Common/RuntimeDependencies_common.cmake +++ b/cmake/Platform/Common/RuntimeDependencies_common.cmake @@ -105,7 +105,7 @@ function(ly_get_runtime_dependencies ly_RUNTIME_DEPENDENCIES ly_TARGET) set(skip_imported TRUE) endif() endif() - if(target_type MATCHES "(INTERFACE_LIBRARY|STATIC_LIBRARY)") + if(target_type MATCHES "(STATIC_LIBRARY)") # No need to copy these dependencies since the outputs are not used at runtime set(skip_imported TRUE) endif() From 895bbafa9e61cb5366e8a36a74b5b0664b73fcf3 Mon Sep 17 00:00:00 2001 From: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> Date: Tue, 1 Jun 2021 10:50:10 -0500 Subject: [PATCH 362/811] Fixed CreatePrefab to use correct absolute path (#1044) The initial CreatePrefab flow was trying to go from absolute -> relative -> absolute path before the file had ever been saved, so the relative -> absolute path conversion generated an error and always produced a project-relative path, even if the initial path was in a gem. For example, trying to save "c:/o3de/Gems/Camera/Assets/Entity1.prefab" would instead create "c:/o3de/AutomatedTesting/Entity1.prefab". This change preserves the absolute path throughout the initial creation flow so that the file is saved in the correct location. --- .../AzToolsFramework/Prefab/PrefabLoader.cpp | 39 +++++++++++++++++++ .../AzToolsFramework/Prefab/PrefabLoader.h | 10 +++++ .../Prefab/PrefabLoaderInterface.h | 10 +++++ .../Prefab/PrefabPublicHandler.cpp | 9 +++-- .../Prefab/PrefabPublicHandler.h | 2 +- .../Prefab/PrefabPublicInterface.h | 4 +- .../UI/Prefab/PrefabIntegrationManager.cpp | 3 +- 7 files changed, 69 insertions(+), 8 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp index e4507227b5..d7de634c11 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp @@ -303,6 +303,45 @@ namespace AzToolsFramework return true; } + bool PrefabLoader::SaveTemplateToFile(TemplateId templateId, AZ::IO::PathView absolutePath) + { + AZ_Assert(absolutePath.IsAbsolute(), "SaveTemplateToFile requires an absolute path for saving the initial prefab file."); + + const auto& domAndFilepath = StoreTemplateIntoFileFormat(templateId); + if (!domAndFilepath) + { + return false; + } + + // Verify that the absolute path provided to this matches the relative path saved in the template. + // Otherwise, the saved prefab won't be able to be loaded. + auto relativePath = GenerateRelativePath(absolutePath); + if (relativePath != domAndFilepath->second) + { + AZ_Error( + "Prefab", false, + "PrefabLoader::SaveTemplateToFile - " + "Failed to save template '%s' to location '%.*s'." + "Error: Relative path '%.*s' for location didn't match template name.", + domAndFilepath->second.c_str(), AZ_STRING_ARG(absolutePath.Native()), AZ_STRING_ARG(relativePath.Native())); + return false; + } + + auto outcome = AzFramework::FileFunc::WriteJsonFile(domAndFilepath->first, absolutePath); + if (!outcome.IsSuccess()) + { + AZ_Error( + "Prefab", false, + "PrefabLoader::SaveTemplateToFile - " + "Failed to save template '%s' to location '%.*s'." + "Error: %s", + domAndFilepath->second.c_str(), AZ_STRING_ARG(absolutePath.Native()), outcome.GetError().c_str()); + return false; + } + m_prefabSystemComponentInterface->SetTemplateDirtyFlag(templateId, false); + return true; + } + bool PrefabLoader::SaveTemplateToString(TemplateId templateId, AZStd::string& output) { const auto& domAndFilepath = StoreTemplateIntoFileFormat(templateId); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.h index aed24e153e..3722e14a97 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.h @@ -72,6 +72,16 @@ namespace AzToolsFramework */ bool SaveTemplate(TemplateId templateId) override; + /** + * Saves a Prefab Template to the provided absolute source path, which needs to match the relative path in the template. + * Converts Prefab Template form into .prefab form by collapsing nested Template info + * into a source path and patches. + * @param templateId Id of the template to be saved + * @param absolutePath Absolute path to save the file to + * @return bool on whether the operation succeeded or not + */ + bool SaveTemplateToFile(TemplateId templateId, AZ::IO::PathView absolutePath) override; + /** * Saves a Prefab Template into the provided output string. * Converts Prefab Template form into .prefab form by collapsing nested Template info diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoaderInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoaderInterface.h index d71fbff80f..0e551cee6b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoaderInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoaderInterface.h @@ -60,6 +60,16 @@ namespace AzToolsFramework */ virtual bool SaveTemplate(TemplateId templateId) = 0; + /** + * Saves a Prefab Template to the provided absolute source path, which needs to match the relative path in the template. + * Converts Prefab Template form into .prefab form by collapsing nested Template info + * into a source path and patches. + * @param templateId Id of the template to be saved + * @param absolutePath Absolute path to save the file to + * @return bool on whether the operation succeeded or not + */ + virtual bool SaveTemplateToFile(TemplateId templateId, AZ::IO::PathView absolutePath) = 0; + /** * Saves a Prefab Template into the provided output string. * Converts Prefab Template form into .prefab form by collapsing nested Template info diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 9dd5199ea2..fadcc1b81f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -64,7 +64,7 @@ namespace AzToolsFramework m_prefabUndoCache.Destroy(); } - PrefabOperationResult PrefabPublicHandler::CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView filePath) + PrefabOperationResult PrefabPublicHandler::CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) { EntityList inputEntityList, topLevelEntities; AZ::EntityId commonRootEntityId; @@ -76,6 +76,8 @@ namespace AzToolsFramework return findCommonRootOutcome; } + AZ_Assert(absolutePath.IsAbsolute(), "CreatePrefab requires an absolute path for saving the initial prefab file."); + InstanceOptionalReference instanceToCreate; { // Initialize Undo Batch object @@ -144,7 +146,8 @@ namespace AzToolsFramework // Create the Prefab instanceToCreate = prefabEditorEntityOwnershipInterface->CreatePrefab( - entities, AZStd::move(instancePtrs), filePath, commonRootEntityOwningInstance); + entities, AZStd::move(instancePtrs), m_prefabLoaderInterface->GenerateRelativePath(absolutePath), + commonRootEntityOwningInstance); if (!instanceToCreate) { @@ -254,7 +257,7 @@ namespace AzToolsFramework } // Save Template to file - m_prefabLoaderInterface->SaveTemplate(instanceToCreate->get().GetTemplateId()); + m_prefabLoaderInterface->SaveTemplateToFile(instanceToCreate->get().GetTemplateId(), absolutePath); return AZ::Success(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 7e2357dd44..e68a3e0b1e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -46,7 +46,7 @@ namespace AzToolsFramework void UnregisterPrefabPublicHandlerInterface(); // PrefabPublicInterface... - PrefabOperationResult CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView filePath) override; + PrefabOperationResult CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) override; PrefabOperationResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; PrefabOperationResult SavePrefab(AZ::IO::Path filePath) override; PrefabEntityResult CreateEntity(AZ::EntityId parentId, const AZ::Vector3& position) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h index 0750c4d264..2e9152fd1b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h @@ -46,10 +46,10 @@ namespace AzToolsFramework * Create a prefab out of the entities provided, at the path provided. * Automatically detects descendants of entities, and discerns between entities and child instances. * @param entityIds The entities that should form the new prefab (along with their descendants). - * @param filePath The path for the new prefab file. + * @param filePath The absolute path for the new prefab file. * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. */ - virtual PrefabOperationResult CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView filePath) = 0; + virtual PrefabOperationResult CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) = 0; /** * Instantiate a prefab from a prefab file. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index 61d4433c0e..021b97a7dd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -333,8 +333,7 @@ namespace AzToolsFramework } } - auto createPrefabOutcome = s_prefabPublicInterface->CreatePrefab( - selectedEntities, s_prefabLoaderInterface->GenerateRelativePath(prefabFilePath.data())); + auto createPrefabOutcome = s_prefabPublicInterface->CreatePrefab(selectedEntities, prefabFilePath.data()); if (!createPrefabOutcome.IsSuccess()) { From d115eae84a4470a8272a7a1ce91e06b9a335a34f Mon Sep 17 00:00:00 2001 From: guthadam Date: Tue, 1 Jun 2021 11:43:05 -0500 Subject: [PATCH 363/811] LYN-3871/3872 Added JSON serializer for MaterialAssignment property overrides --- .../Source/Material/MaterialAssignment.cpp | 8 + .../Material/MaterialAssignmentSerializer.cpp | 214 ++++++++++++++++++ .../Material/MaterialAssignmentSerializer.h | 50 ++++ ...m_feature_common_staticlibrary_files.cmake | 2 + .../Material/EditorMaterialComponentSlot.cpp | 4 +- 5 files changed, 275 insertions(+), 3 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.cpp create mode 100644 Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.h diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp index ffb5469aef..b4d8200dbc 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp @@ -12,8 +12,11 @@ #include #include +#include #include +#include "MaterialAssignmentSerializer.h" + namespace AZ { namespace Render @@ -22,6 +25,11 @@ namespace AZ { MaterialAssignmentId::Reflect(context); + if (auto jsonContext = azrtti_cast(context)) + { + jsonContext->Serializer()->HandlesType(); + } + if (auto serializeContext = azrtti_cast(context)) { serializeContext->RegisterGenericType(); diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.cpp new file mode 100644 index 0000000000..bb68a05a3e --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.cpp @@ -0,0 +1,214 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include "MaterialAssignmentSerializer.h" +#include + +namespace AZ +{ + namespace Render + { + AZ_CLASS_ALLOCATOR_IMPL(JsonMaterialAssignmentSerializer, AZ::SystemAllocator, 0); + + JsonSerializationResult::Result JsonMaterialAssignmentSerializer::Load( + void* outputValue, [[maybe_unused]] const Uuid& outputValueTypeId, const rapidjson::Value& inputValue, + JsonDeserializerContext& context) + { + namespace JSR = JsonSerializationResult; + + AZ_Assert( + azrtti_typeid() == outputValueTypeId, + "Unable to deserialize MaterialAssignment from json because the provided type is %s.", + outputValueTypeId.ToString().c_str()); + + AZ::Render::MaterialAssignment* materialAssignment = reinterpret_cast(outputValue); + AZ_Assert(materialAssignment, "Output value for JsonMaterialAssignmentSerializer can't be null."); + + JSR::ResultCode result(JSR::Tasks::ReadField); + { + result.Combine(ContinueLoadingFromJsonObjectField( + &materialAssignment->m_materialAsset, azrtti_typeidm_materialAsset)>(), inputValue, + "MaterialAsset", context)); + } + + if (inputValue.HasMember("PropertyOverrides") && inputValue["PropertyOverrides"].IsObject()) + { + // Attempt to load material property override values for a subset of types + for (const auto& inputPropertyPair : inputValue["PropertyOverrides"].GetObject()) + { + const AZ::Name propertyName(inputPropertyPair.name.GetString()); + if (!propertyName.IsEmpty()) + { + AZStd::any propertyValue; + if (LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny(propertyValue, inputPropertyPair.value, context, result) || + LoadAny>(propertyValue, inputPropertyPair.value, context, result) || + LoadAny>(propertyValue, inputPropertyPair.value, context, result)) + { + materialAssignment->m_propertyOverrides[propertyName] = propertyValue; + } + } + } + } + + return context.Report( + result, + result.GetProcessing() != JSR::Processing::Halted ? "Succesfully loaded MaterialAssignment information." + : "Failed to load MaterialAssignment information."); + } + + JsonSerializationResult::Result JsonMaterialAssignmentSerializer::Store( + rapidjson::Value& outputValue, const void* inputValue, const void* defaultValue, [[maybe_unused]] const Uuid& valueTypeId, + JsonSerializerContext& context) + { + namespace JSR = AZ::JsonSerializationResult; + + AZ_Assert( + azrtti_typeid() == valueTypeId, + "Unable to Serialize MaterialAssignment because the provided type is %s.", valueTypeId.ToString().c_str()); + + const AZ::Render::MaterialAssignment* materialAssignment = reinterpret_cast(inputValue); + AZ_Assert(materialAssignment, "Input value for JsonMaterialAssignmentSerializer can't be null."); + const AZ::Render::MaterialAssignment* defaultMaterialAssignmentInstance = + reinterpret_cast(defaultValue); + + outputValue.SetObject(); + + JSR::ResultCode result(JSR::Tasks::WriteValue); + { + AZ::ScopedContextPath subPathMaterialAsset(context, "m_materialAsset"); + const AZ::Data::Asset* materialAsset = &materialAssignment->m_materialAsset; + const AZ::Data::Asset* defaultmaterialAsset = + defaultMaterialAssignmentInstance ? &defaultMaterialAssignmentInstance->m_materialAsset : nullptr; + + result.Combine(ContinueStoringToJsonObjectField( + outputValue, "MaterialAsset", materialAsset, defaultmaterialAsset, + azrtti_typeidm_materialAsset)>(), context)); + } + + { + AZ::ScopedContextPath subPathPropertyOverrides(context, "m_propertyOverrides"); + if (!materialAssignment->m_propertyOverrides.empty()) + { + rapidjson::Value outputPropertyValueContainer; + outputPropertyValueContainer.SetObject(); + + // Attempt to extract and store material property override values for a subset of types + for (const auto& propertyPair : materialAssignment->m_propertyOverrides) + { + const AZ::Name& propertyName = propertyPair.first; + const AZStd::any& propertyValue = propertyPair.second; + if (!propertyName.IsEmpty() && !propertyValue.empty()) + { + rapidjson::Value outputPropertyValue; + if (StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny(propertyValue, outputPropertyValue, context, result) || + StoreAny>(propertyValue, outputPropertyValue, context, result) || + StoreAny>( + propertyValue, outputPropertyValue, context, result)) + { + outputPropertyValueContainer.AddMember( + rapidjson::Value::StringRefType(propertyName.GetCStr()), outputPropertyValue, + context.GetJsonAllocator()); + } + } + } + + if (outputPropertyValueContainer.MemberCount() > 0) + { + outputValue.AddMember("PropertyOverrides", outputPropertyValueContainer, context.GetJsonAllocator()); + } + } + } + + return context.Report( + result, + result.GetProcessing() != JSR::Processing::Halted ? "Successfully stored MaterialAssignment information." + : "Failed to store MaterialAssignment information."); + } + + template + bool JsonMaterialAssignmentSerializer::LoadAny( + AZStd::any& propertyValue, const rapidjson::Value& inputPropertyValue, AZ::JsonDeserializerContext& context, + AZ::JsonSerializationResult::ResultCode& result) + { + if (inputPropertyValue.IsObject() && inputPropertyValue.HasMember("Value") && inputPropertyValue.HasMember("$type")) + { + // Requiring explicit type info to differentiate be=tween colors versus vectors and numeric types + const AZ::Uuid baseTypeId = azrtti_typeid(); + AZ::Uuid typeId = AZ::Uuid::CreateNull(); + result.Combine(LoadTypeId(typeId, inputPropertyValue, context, &baseTypeId)); + + if (typeId == azrtti_typeid()) + { + T value = {}; + result.Combine(ContinueLoadingFromJsonObjectField(&value, azrtti_typeid(), inputPropertyValue, "Value", context)); + propertyValue = value; + return true; + } + } + return false; + } + + template + bool JsonMaterialAssignmentSerializer::StoreAny( + const AZStd::any& propertyValue, rapidjson::Value& outputPropertyValue, AZ::JsonSerializerContext& context, + AZ::JsonSerializationResult::ResultCode& result) + { + if (propertyValue.is()) + { + outputPropertyValue.SetObject(); + + // Storing explicit type info to differentiate be=tween colors versus vectors and numeric types + rapidjson::Value typeValue; + result.Combine(StoreTypeId(typeValue, azrtti_typeid(), context)); + outputPropertyValue.AddMember("$type", typeValue, context.GetJsonAllocator()); + + T value = AZStd::any_cast(propertyValue); + result.Combine( + ContinueStoringToJsonObjectField(outputPropertyValue, "Value", &value, nullptr, azrtti_typeid(), context)); + return true; + } + return false; + } + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.h b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.h new file mode 100644 index 0000000000..14db019668 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.h @@ -0,0 +1,50 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#pragma once + +#include +#include +#include + +namespace AZ +{ + namespace Render + { + // Custom JSON serializer for material assignment objects containing AZStd::any property overrides, + // which aren't supported by the system + class JsonMaterialAssignmentSerializer : public BaseJsonSerializer + { + public: + AZ_RTTI(JsonMaterialAssignmentSerializer, "{3D33653E-4582-483F-91F5-BBCC347C3DF0}", BaseJsonSerializer); + AZ_CLASS_ALLOCATOR_DECL; + + JsonSerializationResult::Result Load( + void* outputValue, const Uuid& outputValueTypeId, const rapidjson::Value& inputValue, + JsonDeserializerContext& context) override; + + JsonSerializationResult::Result Store( + rapidjson::Value& outputValue, const void* inputValue, const void* defaultValue, const Uuid& valueTypeId, + JsonSerializerContext& context) override; + + private: + template + bool LoadAny( + AZStd::any& propertyValue, const rapidjson::Value& inputPropertyValue, AZ::JsonDeserializerContext& context, + AZ::JsonSerializationResult::ResultCode& result); + template + bool StoreAny( + const AZStd::any& propertyValue, rapidjson::Value& outputPropertyValue, AZ::JsonSerializerContext& context, + AZ::JsonSerializationResult::ResultCode& result); + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_staticlibrary_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_staticlibrary_files.cmake index 553f307409..285659ab82 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_staticlibrary_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_staticlibrary_files.cmake @@ -16,6 +16,8 @@ set(FILES Include/Atom/Feature/Utils/ModelPreset.h Source/Material/MaterialAssignment.cpp Source/Material/MaterialAssignmentId.cpp + Source/Material/MaterialAssignmentSerializer.cpp + Source/Material/MaterialAssignmentSerializer.h Source/Utils/LightingPreset.cpp Source/Utils/ModelPreset.cpp ) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp index 7ebf25454d..bdc82acda6 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp @@ -78,11 +78,9 @@ namespace AZ if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(4, &EditorMaterialComponentSlot::ConvertVersion) + ->Version(5, &EditorMaterialComponentSlot::ConvertVersion) ->Field("id", &EditorMaterialComponentSlot::m_id) ->Field("materialAsset", &EditorMaterialComponentSlot::m_materialAsset) - ->Field("propertyOverrides", &EditorMaterialComponentSlot::m_propertyOverrides) - ->Field("matModUvOverrides", &EditorMaterialComponentSlot::m_matModUvOverrides) ; if (AZ::EditContext* editContext = serializeContext->GetEditContext()) From 0d5247be345493fb699e54dc0eaad41af35fa87b Mon Sep 17 00:00:00 2001 From: moudgils Date: Tue, 1 Jun 2021 09:58:45 -0700 Subject: [PATCH 364/811] Fix metal shader pipeline crashes for LuminanceHistogramGenerator and MorphTargetCS due to the use of atomic operations with typed buffers. Switching them to use Structured buffers. Plus misc cleanup --- .../Common/Assets/Shaders/MorphTargets/MorphTargetCS.shader | 4 +--- .../Common/Assets/Shaders/MorphTargets/MorphTargetSRG.azsli | 2 +- .../Assets/Shaders/PostProcessing/LuminanceHeatmap.azsl | 4 ++-- .../Shaders/PostProcessing/LuminanceHistogramGenerator.azsl | 2 +- .../PostProcessing/LuminanceHistogramGenerator.shader | 4 +--- .../Assets/Shaders/SkinnedMesh/LinearSkinningPassSRG.azsli | 2 +- .../PostProcessing/LuminanceHistogramGeneratorPass.cpp | 2 +- .../Source/SkinnedMesh/SkinnedMeshOutputStreamManager.cpp | 4 ++-- .../RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h | 1 - Gems/Atom/RHI/DX12/Code/Source/RHI/CommandList.h | 6 ++++++ 10 files changed, 16 insertions(+), 15 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetCS.shader b/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetCS.shader index 95ffc36a11..08b1e7c298 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetCS.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetCS.shader @@ -10,7 +10,5 @@ "type": "Compute" } ] - }, - "DisabledRHIBackends": ["metal"] - + } } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetSRG.azsli b/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetSRG.azsli index 7ec5b43368..171e803c2c 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetSRG.azsli +++ b/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetSRG.azsli @@ -16,7 +16,7 @@ ShaderResourceGroup MorphTargetPassSrg : SRG_PerPass { - RWBuffer m_accumulatedDeltas; + RWStruturedBuffer m_accumulatedDeltas; } // This class represents the data that is passed to the morph target compute shader of an individual delta diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHeatmap.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHeatmap.azsl index df92e36f9a..4559b6c9ef 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHeatmap.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHeatmap.azsl @@ -1,4 +1,4 @@ -/* + /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * @@ -37,7 +37,7 @@ ShaderResourceGroup PassSrg : SRG_PerPass Texture2D m_sceneLuminance; // This should be of size NUM_HISTOGRAM_BINS. - Buffer m_histogram; + StructuredBuffer m_histogram; Sampler LinearSampler { diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl index 05cc870eea..9d01a12fd6 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.azsl @@ -20,7 +20,7 @@ ShaderResourceGroup PassSrg : SRG_PerPass { Texture2D m_inputTexture; - RWBuffer m_outputTexture; + RWStructuredBuffer m_outputTexture; } groupshared uint shared_histogramBins[NUM_HISTOGRAM_BINS]; diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader index 566144bab8..f3dd11e11a 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LuminanceHistogramGenerator.shader @@ -12,7 +12,5 @@ "type": "Compute" } ] - }, - "DisabledRHIBackends": ["metal"] - + } } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/SkinnedMesh/LinearSkinningPassSRG.azsli b/Gems/Atom/Feature/Common/Assets/Shaders/SkinnedMesh/LinearSkinningPassSRG.azsli index 5a9e44bade..e5407d2d9e 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/SkinnedMesh/LinearSkinningPassSRG.azsli +++ b/Gems/Atom/Feature/Common/Assets/Shaders/SkinnedMesh/LinearSkinningPassSRG.azsli @@ -16,7 +16,7 @@ ShaderResourceGroup PassSrg : SRG_PerPass { - RWBuffer m_skinnedMeshOutputStream; + RWStructuredBuffer m_skinnedMeshOutputStream; } ShaderResourceGroup InstanceSrg : SRG_PerDraw diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp index 758c21bc4e..a3c494dee9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp @@ -72,7 +72,7 @@ namespace AZ desc.m_bufferName = AZStd::string::format("LuminanceHistogramBuffer_%s", uuidString.c_str()); desc.m_elementSize = sizeof(uint32_t); desc.m_byteCount = NumHistogramBins * sizeof(uint32_t); - desc.m_elementFormat = RHI::Format::R32_UINT; + desc.m_elementFormat = RHI::Format::Unknown; m_histogram = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); AZ_Assert(m_histogram != nullptr, "Unable to allocate buffer"); } diff --git a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshOutputStreamManager.cpp b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshOutputStreamManager.cpp index 1cb782d8b1..1b14611e84 100644 --- a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshOutputStreamManager.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshOutputStreamManager.cpp @@ -67,8 +67,8 @@ namespace AZ creator.SetBuffer(nullptr, 0, bufferDescriptor); RHI::BufferViewDescriptor viewDescriptor; - viewDescriptor.m_elementFormat = RHI::Format::R32_FLOAT; - viewDescriptor.m_elementSize = RHI::GetFormatSize(viewDescriptor.m_elementFormat); + viewDescriptor.m_elementFormat = RHI::Format::Unknown; + viewDescriptor.m_elementSize = sizeof(float); viewDescriptor.m_elementCount = aznumeric_cast(m_sizeInBytes) / viewDescriptor.m_elementSize; viewDescriptor.m_elementOffset = 0; creator.SetBufferViewDescriptor(viewDescriptor); diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h index ce2c6c77ec..afcab28a1d 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h @@ -410,7 +410,6 @@ namespace AZ // For any other type the buffer view's element size should match the stride. if (shaderInputBuffer.m_strideSize != bufferViewDescriptor.m_elementSize) { - // [GFX TODO][ATOM-5735][AZSL] ByteAddressBuffer shader input is setting a stride of 16 instead of 4 AZ_Error("ShaderResourceGroupData", false, "Buffer Input '%s[%d]': Does not match expected stride size %d", shaderInputBuffer.m_name.GetCStr(), arrayIndex, bufferViewDescriptor.m_elementSize); return false; diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandList.h b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandList.h index a6fe57f6d8..6f09ea1d5f 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandList.h +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandList.h @@ -271,6 +271,12 @@ namespace AZ ShaderResourceBindings& bindings = GetShaderResourceBindingsByPipelineType(pipelineType); const PipelineState* pipelineState = static_cast(item.m_pipelineState); + if(!pipelineState) + { + AZ_Assert(false, "Pipeline state not provided"); + return false; + } + bool updatePipelineState = m_state.m_pipelineState != pipelineState; // The pipeline state gets set first. if (updatePipelineState) From 71013c383581016f71f9e67ace36c90838d1775a Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Tue, 1 Jun 2021 17:51:06 +0000 Subject: [PATCH 365/811] Rename tests that reference issue numbers to have descriptive names (#913) This also enables one such test that was named after an issue tracker id, that was disabled because of an already resolved issue. --- .../AnimGraphParameterConditionTests.cpp | 25 ++++++------------- .../Code/Tests/BlendTreeBlendNNodeTests.cpp | 4 +-- ...eletionAndRestoreBlendTreeConnections.cpp} | 6 ++--- ...-93621.cpp => CanAdjustGroupParameter.cpp} | 2 +- ...teAnimGraphNode_AnimGraphModelUpdates.cpp} | 6 ++--- ...nRenameParameter_ParameterNodeUpdates.cpp} | 2 +- .../Code/emotionfx_editor_tests_files.cmake | 8 +++--- 7 files changed, 22 insertions(+), 31 deletions(-) rename Gems/EMotionFX/Code/Tests/Bugs/{LY-92860.cpp => CanUndoParameterDeletionAndRestoreBlendTreeConnections.cpp} (98%) rename Gems/EMotionFX/Code/Tests/UI/{LY-93621.cpp => CanAdjustGroupParameter.cpp} (95%) rename Gems/EMotionFX/Code/Tests/UI/{LY-92748.cpp => CanDeleteAnimGraphNode_AnimGraphModelUpdates.cpp} (95%) rename Gems/EMotionFX/Code/Tests/UI/{LY-92269.cpp => CanRenameParameter_ParameterNodeUpdates.cpp} (98%) diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphParameterConditionTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphParameterConditionTests.cpp index ef3e9820a5..b1ddede059 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphParameterConditionTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphParameterConditionTests.cpp @@ -10,6 +10,7 @@ * */ +#include "EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h" #include #include #include @@ -87,26 +88,16 @@ namespace EMotionFX const AnimGraphParameterCondition* condition = GetAnimGraph()->GetParameterCondition(); EXPECT_EQ(condition->GetParameterType(), azrtti_typeid()); - { - AZStd::string result; - EXPECT_TRUE(manager.ExecuteCommand("AnimGraphRemoveParameter -animGraphID 0 -name P0", result)) << result.c_str(); - } - + EXPECT_TRUE(CommandSystem::BuildRemoveParametersCommandGroup(GetAnimGraph(), {"P0"})); EXPECT_EQ(condition->GetParameterType(), azrtti_typeid()); - { - AZStd::string result; - EXPECT_TRUE(manager.ExecuteCommand("AnimGraphRemoveParameter -animGraphID 0 -name P1", result)) << result.c_str(); - } - + EXPECT_TRUE(CommandSystem::BuildRemoveParametersCommandGroup(GetAnimGraph(), {"P1"})); EXPECT_EQ(condition->GetParameterType(), AZ::TypeId::CreateNull()); - // Will be fixed by LY-109269 - //{ - // AZStd::string result; - // EXPECT_TRUE(manager.Undo(result)) << result.c_str(); - //} - - //EXPECT_EQ(condition->GetParameterType(), azrtti_typeid()); + { + AZStd::string result; + EXPECT_TRUE(manager.Undo(result)) << result.c_str(); + } + EXPECT_EQ(condition->GetParameterType(), azrtti_typeid()); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeBlendNNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeBlendNNodeTests.cpp index 657599bcc9..1e910fb62d 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeBlendNNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeBlendNNodeTests.cpp @@ -264,8 +264,8 @@ namespace EMotionFX BlendTreeBlendNNode* m_blendNNode = nullptr; }; - // Make sure we don't crash when we have no inputs, such as reported by bug LY-114828 - // Also make sure removing connections on BlendN doesn't crash, as reported by LY-114846 + // Make sure we don't crash when we have no inputs + // Also make sure removing connections on BlendN doesn't crash TEST_F(BlendTreeBlendNNodeTests, NoInputsNoCrashTest) { // Remove all input connections of the blendN node. diff --git a/Gems/EMotionFX/Code/Tests/Bugs/LY-92860.cpp b/Gems/EMotionFX/Code/Tests/Bugs/CanUndoParameterDeletionAndRestoreBlendTreeConnections.cpp similarity index 98% rename from Gems/EMotionFX/Code/Tests/Bugs/LY-92860.cpp rename to Gems/EMotionFX/Code/Tests/Bugs/CanUndoParameterDeletionAndRestoreBlendTreeConnections.cpp index cd4773b221..0d47b86606 100644 --- a/Gems/EMotionFX/Code/Tests/Bugs/LY-92860.cpp +++ b/Gems/EMotionFX/Code/Tests/Bugs/CanUndoParameterDeletionAndRestoreBlendTreeConnections.cpp @@ -106,7 +106,7 @@ namespace EMotionFX R"str(AnimGraphCreateConnection -animGraphID 0 -sourceNode Parameters0 -targetNode Smoothing2 -sourcePort 2 -targetPort 0 -startOffsetX 119 -startOffsetY 70 -endOffsetX -2 -endOffsetY 40)str" }; - class LY92860Fixture + class UndoParameterDeletionTests : public CommandRunnerFixture { public: @@ -183,10 +183,10 @@ namespace EMotionFX } }; - TEST_P(LY92860Fixture, ExecuteCommands) + TEST_P(UndoParameterDeletionTests, CanUndoParameterDeletionAndRestoreBlendTreeConnections) { Run(); }; - INSTANTIATE_TEST_CASE_P(LY92860, LY92860Fixture, ::testing::Values(prepareLY92860Commands)); + INSTANTIATE_TEST_CASE_P(UndoParameterDeletionTests, UndoParameterDeletionTests, ::testing::Values(prepareLY92860Commands)); } // EMotionFX diff --git a/Gems/EMotionFX/Code/Tests/UI/LY-93621.cpp b/Gems/EMotionFX/Code/Tests/UI/CanAdjustGroupParameter.cpp similarity index 95% rename from Gems/EMotionFX/Code/Tests/UI/LY-93621.cpp rename to Gems/EMotionFX/Code/Tests/UI/CanAdjustGroupParameter.cpp index 8e4f9a1fc9..4568dd1b03 100644 --- a/Gems/EMotionFX/Code/Tests/UI/LY-93621.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanAdjustGroupParameter.cpp @@ -14,7 +14,7 @@ namespace EMotionFX { - INSTANTIATE_TEST_CASE_P(LY93621, CommandRunnerFixture, + INSTANTIATE_TEST_CASE_P(CanAdjustGroupParameter, CommandRunnerFixture, ::testing::Values(std::vector { R"str(CreateAnimGraph)str", R"str(AnimGraphAddGroupParameter -animGraphID 0 -name Group0)str", diff --git a/Gems/EMotionFX/Code/Tests/UI/LY-92748.cpp b/Gems/EMotionFX/Code/Tests/UI/CanDeleteAnimGraphNode_AnimGraphModelUpdates.cpp similarity index 95% rename from Gems/EMotionFX/Code/Tests/UI/LY-92748.cpp rename to Gems/EMotionFX/Code/Tests/UI/CanDeleteAnimGraphNode_AnimGraphModelUpdates.cpp index 9534edb8eb..ad6172d02b 100644 --- a/Gems/EMotionFX/Code/Tests/UI/LY-92748.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanDeleteAnimGraphNode_AnimGraphModelUpdates.cpp @@ -21,12 +21,12 @@ namespace EMotionFX { - class LY92748Fixture + class CanDeleteAnimGraphNode : public CommandRunnerFixture { }; - TEST_P(LY92748Fixture, ExecuteCommands) + TEST_P(CanDeleteAnimGraphNode, CanDeleteAnimGraphNode_AnimGraphModelUpdates) { ExecuteCommands(GetParam()); @@ -68,7 +68,7 @@ namespace EMotionFX } - INSTANTIATE_TEST_CASE_P(DISABLED_LY92748, LY92748Fixture, + INSTANTIATE_TEST_CASE_P(CanDeleteAnimGraphNode_AnimGraphModelUpdates, CanDeleteAnimGraphNode, ::testing::Values(std::vector { R"str(CreateAnimGraph)str", R"str(Select -animGraphID 0)str", diff --git a/Gems/EMotionFX/Code/Tests/UI/LY-92269.cpp b/Gems/EMotionFX/Code/Tests/UI/CanRenameParameter_ParameterNodeUpdates.cpp similarity index 98% rename from Gems/EMotionFX/Code/Tests/UI/LY-92269.cpp rename to Gems/EMotionFX/Code/Tests/UI/CanRenameParameter_ParameterNodeUpdates.cpp index 95f42f7e33..fac6f51943 100644 --- a/Gems/EMotionFX/Code/Tests/UI/LY-92269.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanRenameParameter_ParameterNodeUpdates.cpp @@ -14,7 +14,7 @@ namespace EMotionFX { - INSTANTIATE_TEST_CASE_P(LY92269, CommandRunnerFixture, + INSTANTIATE_TEST_CASE_P(CanRenameParameter_ParameterNodeUpdates, CommandRunnerFixture, ::testing::Values(std::vector { R"str(CreateAnimGraph)str", R"str(AnimGraphCreateNode -animGraphID 0 -type {A8B5BB1E-5BA9-4B0A-88E9-21BB7A199ED2} -parentName Root -xPos 240 -yPos 230 -name GENERATE -namePrefix BlendTree)str", diff --git a/Gems/EMotionFX/Code/emotionfx_editor_tests_files.cmake b/Gems/EMotionFX/Code/emotionfx_editor_tests_files.cmake index 4a7d1414f9..e2670c20f7 100644 --- a/Gems/EMotionFX/Code/emotionfx_editor_tests_files.cmake +++ b/Gems/EMotionFX/Code/emotionfx_editor_tests_files.cmake @@ -54,15 +54,15 @@ set(FILES Tests/UI/AnimGraphUIFixture.h Tests/UI/MenuUIFixture.cpp Tests/UI/MenuUIFixture.h - Tests/UI/LY-92269.cpp - Tests/UI/LY-92748.cpp - Tests/UI/LY-93621.cpp + Tests/UI/CanRenameParameter_ParameterNodeUpdates.cpp + Tests/UI/CanDeleteAnimGraphNode_AnimGraphModelUpdates.cpp + Tests/UI/CanAdjustGroupParameter.cpp Tests/UI/CanAddJointAndChildren.cpp Tests/Integration/CanAddActor.cpp Tests/Integration/CanAddSimpleMotionComponent.cpp Tests/Integration/CanDeleteJackEntity.cpp Tests/Bugs/CanDeleteMotionWhenMotionIsBeingBlended.cpp - Tests/Bugs/LY-92860.cpp + Tests/Bugs/CanUndoParameterDeletionAndRestoreBlendTreeConnections.cpp Tests/D6JointLimitConfiguration.cpp Tests/D6JointLimitConfiguration.h Tests/Editor/FileManagerTests.cpp From ed55158b35fa6b263a5c0158fe4f384f46c95ff1 Mon Sep 17 00:00:00 2001 From: Fuzzy Carter Date: Tue, 1 Jun 2021 11:03:07 -0700 Subject: [PATCH 366/811] Helios spec-6686 decouple tests (#978) * * Remove test repository references * * Update asset_builder_tests.py docstring to include test steps * * Update test docstrings in asset_bundler_batch_tests.py to include test steps * * Update asset_processor_batch_dependency_tests.py docstrings to contain test steps * * Update asset_processor_batch_dependency_tests2.py docstrings to have test steps * * Update asset_processor_batch_tests.py docstring to include test steps * * Update asset_processor_batch_tests_2.py docstrings to include test steps * Removed a references to a JIRA ticket ID * * Update asset_processor_guit_tests.py docstrings to include test steps * * Update asset_processor_gui_tests_2.py docstrings to have Test Steps * * Update asset_relocator_tests.py docstrings to include test steps * * update missing_dependency_tests.py docstrings to have test steps * * Update auxiliary_content_tests.py docstrings to have test steps * * Update fbx_tests.py docstrings to have test steps. * * Update bank_info_parser_tests.py docstrings to have test steps * * Removed Jira issue ids from Asset Pipline owned code * * Undid two errornous code changes. * * Addressed dbbronso PR-978 feedback. * Steps declared and not populated. 1 - Removed errornous. 2 - Added missing step * Fixed line formatting by removing bad blank line in Docstring * Addressed PR-978 feedback from AMZN-stankowi * Removed commented out entry from cmakefile * Fixed several casing and spelling/typo issues caught in review * Added a missing test step in asset_bundler_batch_tests.py * Removed a test dealing with external projects, cut LYN-4116 to replace * Calarfied test steps in asset_processor_gui_tests.py * Noted test in asset_processor_gui_tests that cannot be ran manually * Clarified test steps for fbx_tests * Added in a comment and whitespace to a disguised operation. Co-authored-by: stankowi --- .../asset_processor_tests/CMakeLists.txt | 11 - .../asset_builder_tests.py | 9 + .../asset_bundler_batch_tests.py | 108 ++++++++- .../asset_processor_batch_dependency_tests.py | 17 ++ ...asset_processor_batch_dependency_tests2.py | 9 + .../asset_processor_batch_tests.py | 155 +++++++++++++ .../asset_processor_batch_tests_2.py | 97 +++----- .../asset_processor_gui_tests.py | 79 ++++++- .../asset_processor_gui_tests_2.py | 48 +++- .../asset_relocator_tests.py | 92 +++++++- .../missing_dependency_tests.py | 142 ++++++++++-- .../auxiliary_content_tests.py | 10 + .../assetpipeline/fbx_tests/fbx_tests.py | 30 +++ .../bank_info_parser_tests.py | 209 ++++++++++++++---- 14 files changed, 882 insertions(+), 134 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt index a2002f2d15..2e7516db27 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt @@ -128,16 +128,5 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) RUNTIME_DEPENDENCIES AZ::AssetProcessorBatch ) - -# Need performance improvements LYN-1218 -# ly_add_pytest( -# NAME AssetPipelineTests.AssetRelocator -# PATH ${CMAKE_CURRENT_LIST_DIR}/asset_relocator_tests.py -# EXCLUDE_TEST_RUN_TARGET_FROM_IDE -# TEST_SUITE periodic -# TEST_SERIAL -# RUNTIME_DEPENDENCIES -# AZ::AssetProcessorBatch -# ) endif() diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py index e3d52e8260..fb82f180c6 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py @@ -64,6 +64,15 @@ class TestsAssetBuilder_WindowsAndMac(object): ): """ Verifying -debug parameter for AssetBuilder + + Test Steps: + 1. Create temporary workspace + 2. Launch Asset Processor GUI + 3. Add test assets to workspace + 4. Run Asset Builder with debug on an intact slice + 5. Check Asset Builder didn't fail to build + 6. Run Asset Builder with debug on a corrupted slice + 7. Verify corrupted slice produced an error """ env = ap_setup_fixture intact_slice_failed = False diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py index 1043bbaefa..e1091b9b82 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py @@ -80,6 +80,8 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): def test_WindowsAndMac_RunHelpCmd_ZeroExitCode(self, workspace, bundler_batch_helper): """ Simple calls to all AssetBundlerBatch --help to make sure a non-zero exit codes are returned. + + Test will call each Asset Bundler Batch sub-command with help and will error on a non-0 exit code """ bundler_batch_helper.call_bundlerbatch(help="") bundler_batch_helper.call_seeds(help="") @@ -98,6 +100,12 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): r""" Tests that an asset list created maps dependencies correctly. testdependencieslevel\level.pak and lists of known dependencies are used for validation + + Test Steps: + 1. Create an asset list from the level.pak + 2. Create Lists of expected assets in the level.pak + 3. Add lists of expected assets to a single list + 4. Compare list of expected assets to actual assets """ helper = bundler_batch_helper @@ -300,6 +308,15 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): """ Validates destructive overwriting for asset lists and that generating debug information does not affect asset list creation + + 1. Create an asset list from seed_list + 2. Validate asset list was created + 3. Read and store contents of asset list into memory + 4. Attempt to create a new asset list in without using --allowOverwrites + 5. Verify that Asset Bundler returns false + 6. Verify that file contents of the orignally created asset list did not change from what was stored in memory + 7. Attempt to create a new asset list without debug while allowing overwrites + 8. Verify that file contents of the orignally created asset list changed from what was stored in memory """ helper = bundler_batch_helper seed_list = os.path.join(workspace.paths.engine_root(), "Assets", "Engine", "SeedAssetList.seed") # Engine seed list @@ -375,6 +392,14 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): """ Validates bundle creation both through the 'bundles' and 'bundlesettings' subcommands. + + Test Steps: + 1. Create an asset list + 2. Create a bundle with the asset list and without a bundle settings file + 3. Create a bundle with the asset list and a bundle settings file + 4. Validate calling bundle doesn't perform destructive overwrite without --allowOverwrites + 5. Calling bundle again with --alowOverwrites performs destructive overwrite + 6. Validate contents of original bundle and overwritten bundle """ helper = bundler_batch_helper seed_list = os.path.join(workspace.paths.engine_root(), "Assets", "Engine", "SeedAssetList.seed") # Engine seed list @@ -457,6 +482,16 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): """ Creates bundles using the same asset list and compares that they are created equally. Also validates that platform bundles exclude/include an expected file. (excluded for WIN, included for MAC) + + Test Steps: + 1. Create an asset list + 2. Create bundles for both PC & Mac + 3. Validate that bundles were created + 4. Verify that expected missing file is not in windows bundle + 5. Verify that expected file is in the mac bundle + 6. Create duplicate bundles with allowOverwrites + 7. Verify that files were generated + 8. Verify original bundle checksums are equal to new bundle checksums """ helper = bundler_batch_helper # fmt:off @@ -571,6 +606,24 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): """ Validates that the 'seeds' subcommand can add and remove seeds and seed platforms properly. Also checks that destructive overwrites require the --allowOverwrites flag + + Test Steps: + + 1. Create a PC Seed List from a test asset + 2. Validate that seed list was generated with proper platform flag + 3. Add Mac & PC as platforms to the seed list + 4. Verify that seed has both Mac & PC platform flags + 5. Remove Mac as a platform from the seed list + 6. Verify that seed only has PC as a platform flag + 7. Attempt to add a platform without using the --platform argument + 8. Verify that asset bundler returns False and file contents did not change + 9. Add Mac platform via --addPlatformToSeeds + 10. Validate that seed has both Mac & PC platform flags + 11. Attempt to remove platform without specifying a platform + 12. Validate that seed has both Mac & PC platform flags + 13. Validate that seed list contents did not change + 14. Remove seed + 15. Validate that seed was removed from the seed list """ helper = bundler_batch_helper @@ -692,6 +745,12 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): """ Tests asset list comparison, both by file and by comparison type. Uses a set of controlled test assets to compare resulting output asset lists + + 1. Create comparison rules files + 2. Create seed files for different sets of test assets + 3. Create assetlist files for seed files + 4. Validate assetlists were created properly + 5. Compare using comparison rules files and just command line arguments """ helper = bundler_batch_helper env = ap_setup_fixture @@ -1021,6 +1080,16 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): """ Tests that assetlists are created equivalent to the output while being created, and makes sure overwriting an existing file without the --allowOverwrites fails + + Test Steps: + 1. Check that Asset List creation requires PC platform flag + 2. Create a PC Asset List using asset info file and default seed lists using --print + 3. Validate all assets output are present in the asset list + 4. Create a seed file + 5. Attempt to overwrite Asset List without using --allowOverwrites + 6. Validate that command returned an error and file contents did not change + 7. Specifying platform but not "add" or "remove" should fail + 8. Verify file Has changed """ helper = bundler_batch_helper @@ -1102,7 +1171,16 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): def test_WindowsAndMac_AP_BundleProcessing_BundleProcessedAtRuntime(self, workspace, bundler_batch_helper, asset_processor, request): # fmt:on - """Test to make sure the AP GUI will process a newly created bundle file""" + """ + Test to make sure the AP GUI will process a newly created bundle file + + Test Steps: + 1. Make asset list file (used for bundle creation) + 2. Start Asset Processor GUI + 3. Make bundle in /Bundles + 4. Validate file was created in Bundles folder + 5. Make sure bundle now exists in cache + """ # Set up helpers and variables helper = bundler_batch_helper @@ -1131,6 +1209,8 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): addSeed=level_pak, assetListFile=helper["asset_info_file_request"], ) + + # Run Asset Processor GUI result, _ = asset_processor.gui_process() assert result, "AP GUI failed" @@ -1155,6 +1235,12 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): @pytest.mark.assetpipeline # fmt:off def test_WindowsAndMac_FilesMarkedSkip_FilesAreSkipped(self, workspace, bundler_batch_helper): + """ + Test Steps: + 1. Create an asset list with a file marked as skip + 2. Verify file was created + 3. Verify that only the expected assets are present in the created asset list + """ expected_assets = [ "ui/canvases/lyshineexamples/animation/multiplesequences.uicanvas", "ui/textures/prefab/button_normal.sprite" @@ -1178,6 +1264,12 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): # fmt:off def test_WindowsAndMac_AssetListSkipOneOfTwoParents_SharedDependencyIsIncluded(self, workspace, bundler_batch_helper): + """ + Test Steps: + 1. Create Asset List with a parent asset that is skipped + 2. Verify that Asset List was created + 3. Verify that only the expected assets are present in the asset list + """ expected_assets = [ "testassets/bundlerskiptest_grandparent.dynamicslice", "testassets/bundlerskiptest_parenta.dynamicslice", @@ -1206,6 +1298,13 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): @pytest.mark.assetpipeline # fmt:off def test_WindowsAndMac_AssetLists_SkipRoot_ExcludesAll(self, workspace, bundler_batch_helper): + """ + Negative scenario test that skips the same file being used as the parent seed. + + Test Steps: + 1. Create an asset list that skips the root asset + 2. Verify that asset list was not generated + """ result, _ = bundler_batch_helper.call_assetLists( assetListFile=bundler_batch_helper['asset_info_file_request'], @@ -1222,6 +1321,13 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): @pytest.mark.assetpipeline # fmt:off def test_WindowsAndMac_AssetLists_SkipUniversalWildcard_ExcludesAll(self, workspace, bundler_batch_helper): + """ + Negative scenario test that uses the all wildcard when generating an asset list. + + Test Steps: + 1. Create an Asset List while using the universal all wildcard "*" + 2. Verify that asset list was not generated + """ result, _ = bundler_batch_helper.call_assetLists( assetListFile=bundler_batch_helper['asset_info_file_request'], diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests.py index e329846554..0c6924f3a2 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests.py @@ -67,7 +67,19 @@ class TestsAssetProcessorBatch_DependenycyTests(object): libs/materialeffects/surfacetypes.xml is listed as an entry engine_dependencies.xml libs/materialeffects/surfacetypes.xml is not listed as a missing dependency in the 'assetprocessorbatch' console output + + Test Steps: + 1. Assets are pre-processed + 2. Verify that engine_dependencies.xml exists + 3. Verify engine_dependencies.xml has surfacetypes.xml present + 4. Run Missing Dependency scanner against the engine_dependenciese.xml + 5. Verify that Surfacetypes.xml is NOT in the missing depdencies output + 6. Add the schema file which allows our xml parser to understand dependencies for our engine_dependencies file + 7. Process assets + 8. Run Missing Dependency scanner against the engine_dependenciese.xml + 9. Verify that surfacetypes.xml is in the missing dependencies out """ + env = ap_setup_fixture BATCH_LOG_PATH = env["ap_batch_log_file"] asset_processor.create_temp_asset_root() @@ -137,6 +149,11 @@ class TestsAssetProcessorBatch_DependenycyTests(object): def test_WindowsMacPlatforms_BatchCheckSchema_ValidateErrorChecking(self, workspace, asset_processor, ap_setup_fixture, folder, schema): # fmt:on + """ + Test Steps: + 1. Run the Missing Dependency Scanner against everything + 2. Verify that there are no missing dependencies. + """ env = ap_setup_fixture def missing_dependency_log_lines(log) -> [str]: diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests2.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests2.py index 4f33e0df4e..f184ff2392 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests2.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests2.py @@ -60,6 +60,15 @@ class TestsAssetProcessorBatch_DependenycyTests(object): Verify that Schemas can be loaded via Gems utilizing the fonts schema :returns: None + + Test Steps: + 1. Run Missing Dependency Scanner against %fonts%.xml when no fonts are present + 2. Verify fonts are scanned + 3. Verify that missing dependencies are found for fonts + 4. Add fonts to game project + 5. Run Missing Dependency Scanner against %fonts%.xml when fonts are present + 6. Verify that same amount of fonts are scanned + 7. Verify that there are no missing dependencies. """ schema_name = "Font.xmlschema" asset_processor.create_temp_asset_root() diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py index 0d830b39e2..3efd9e7fce 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py @@ -100,6 +100,14 @@ class TestsAssetProcessorBatch_AllPlatforms(object): @pytest.mark.BAT @pytest.mark.assetpipeline def test_RunAPBatch_TwoPlatforms_ExitCodeZero(self, asset_processor): + """ + Tests Process assets for PC & Mac and verifies that processing exited without error + + Test Steps: + 1. Add Mac and PC as enabled platforms + 2. Process Assets + 3. Validate that AP exited cleanly + """ asset_processor.create_temp_asset_root() asset_processor.enable_asset_processor_platform("pc") asset_processor.enable_asset_processor_platform("mac") @@ -111,6 +119,14 @@ class TestsAssetProcessorBatch_AllPlatforms(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id('C1571826') def test_RunAPBatch_OnlyIncludeInvalidAssets_NoAssetsAdded(self, asset_processor, ap_setup_fixture): + """ + Tests processing invalid assets and validating that no assets were moved to the cache + + Test Steps: + 1. Create a test environment with invalid assets + 2. Run asset processor + 3. Validate that no assets were found in the cache + """ asset_processor.prepare_test_environment(ap_setup_fixture["tests_dir"], "test_ProcessAssets_OnlyIncludeInvalidAssets_NoAssetsAdded") result, _ = asset_processor.batch_process() @@ -127,6 +143,16 @@ class TestsAssetProcessorBatch_AllPlatforms(object): "recognized as failing in the logs. There appears to be a window where the AutoFailJob doesn't complete" "before the shutdown completes and the failure doesn't end up counting") def test_ProcessAssets_IncludeTwoAssetsWithSameProduct_FailingOnSecondAsset(self, asset_processor, ap_setup_fixture): + """ + Tests processing two source assets with the same product file and validates that the second source will error + + Test Steps: + 1. Create a test environment that has two source files with the same product + 2. Run asset processor + 3. Validate that 1 asset failed to process + 4. Validate that only one product file with the expected name is found in the cache + """ + asset_processor.prepare_test_environment(ap_setup_fixture["tests_dir"], "test_ProcessAssets_IncludeTwoAssetsWithSameProduct_FailingOnSecondAsset") result, output = asset_processor.batch_process(capture_output = True, expect_failure = True) @@ -143,6 +169,17 @@ class TestsAssetProcessorBatch_AllPlatforms(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id('C1587615') def test_ProcessAndDeleteCache_APBatchShouldReprocess(self, asset_processor, ap_setup_fixture): + """ + Tests processing once, deleting the generated cache, then processing again and validates the cache is created + + Test Steps: + 1. Run asset processor + 2. Compare the cache with expected output + 3. Delete Cache + 4. Compare the cache with expected output to verify that cache is gone + 5. Run asset processor with fastscan disabled + 6. Compare the cache with expected output + """ # Deleting assets from Cache will make them re-processed in AP (after start) # Copying test assets to project folder and deleting them from cache to make sure APBatch will process them @@ -174,6 +211,18 @@ class TestsAssetProcessorBatch_AllPlatforms(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id('C1591564') def test_ProcessAndChangeSource_APBatchShouldReprocess(self, asset_processor, ap_setup_fixture): + """ + Tests reprocessing of a modified asset and verifies that it was reprocessed + + Test Steps: + 1. Prepare test environment and copy test asset over + 2. Run asset processor + 3. Verify asset processed + 4. Verify asset is in cache + 4. Modify asset + 5. Re-run asset processor + 6. Verify asset was processed + """ # AP Batch Processing changed files (after start) # Copying test assets to project folder and deleting them from cache to make sure APBatch will process them @@ -208,6 +257,18 @@ class TestsAssetProcessorBatch_AllPlatforms(object): @pytest.mark.BAT @pytest.mark.assetpipeline def test_ProcessByBothApAndBatch_Md5ShouldMatch(self, asset_processor, ap_setup_fixture): + """ + Tests that a cache generated by AP GUI is the same as AP Batch + + Test Steps: + 1. Create test environment with test assets + 2. Call asset processor batch + 3. Get checksum for file cache + 4. Clean up test environment + 5. Call asset processor gui with quitonidle + 6. Get checksum for file cache + 7. Verify that checksums are equal + """ # AP Batch and AP app processed assets MD5 sums should be the same # Copying test assets to project folder and deleting them from cache to make sure APBatch will process them @@ -240,6 +301,16 @@ class TestsAssetProcessorBatch_AllPlatforms(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id('C1612446') def test_AddSameAssetsDifferentNames_ShouldProcess(self, asset_processor, ap_setup_fixture): + """ + Tests Asset Processing of duplicate assets with different names and verifies that both assets are processed + + Test Steps: + 1. Create test environment with two identical source assets with different names + 2. Run asset processor + 3. Verify that assets didn't fail to process + 4. Verify the correct number of jobs were performed + 5. Verify that product files are in the cache + """ # Feed two similar slices and texture with different names - should process without any issues # Copying test assets to project folder and deleting them from cache to make sure APBatch will process them @@ -277,6 +348,19 @@ class TestsAssetProcessorBatch_AllPlatforms(object): "recognized as failing in the logs. There appears to be a window where the AutoFailJob doesn't complete" "before the shutdown completes and the failure doesn't end up counting") def test_AddTwoTexturesWithSameName_ShouldProcessAfterRename(self, asset_processor, ap_setup_fixture): + """ + Tests processing of two textures with the same name then verifies that AP will successfully process after + renaming one of the textures + + Test Steps: + 1. Create test environment with two textures that have the same name + 2. Launch Asset Processor + 3. Validate that Asset Processor generates an error + 4. Rename texture files + 5. Run asset processor + 6. Verify that asset processor does not error + 7. Verify that expected product files are in the cache + """ # Feed two different textures with same name (but different extensions) - ap will fail # Rename one of textures and failure should go away @@ -312,6 +396,15 @@ class TestsAssetProcessorBatch_AllPlatforms(object): @pytest.mark.BAT @pytest.mark.assetpipeline def test_InvalidServerAddress_Warning_Logs(self, asset_processor): + """ + Tests running Asset Processor with an invalid server address and verifies that AP returns a warning about + an invalid server address + + Test Steps: + 1. Launch asset processor while providing an invalid server address + 2. Verify asset processor does not fail + 3. Verify that asset processor generated a warning informing the user about an invalid server address + """ asset_processor.create_temp_asset_root() # Launching AP and making sure that the warning exists @@ -327,6 +420,12 @@ class TestsAssetProcessorBatch_AllPlatforms(object): def test_AllSupportedPlatforms_IncludeValidAssets_AssetsProcessed(self, asset_processor, ap_setup_fixture): """ AssetProcessorBatch is successfully processing newly added assets + + Test Steps: + 1. Create a test environment with test assets + 2. Launch Asset Processor + 3. Verify that asset processor does not fail to process + 4. Verify assets are not missing from the cache """ env = ap_setup_fixture @@ -350,6 +449,14 @@ class TestsAssetProcessorBatch_AllPlatforms(object): def test_AllSupportedPlatforms_DeletedAssets_DeletedFromCache(self, asset_processor, ap_setup_fixture): """ AssetProcessor successfully deletes cached items when removed from project + + Test Steps: + 1. Create a test environment with test assets + 2. Run asset processor + 3. Verify expected assets are in the cache + 4. Delete test assets + 5. Run asset processor + 6. Verify expected assets are in the cache """ env = ap_setup_fixture @@ -385,6 +492,10 @@ class TestsAssetProcessorBatch_AllPlatforms(object): """ Tests that when cache is deleted (no cache) and AssetProcessorBatch runs, it successfully starts and processes assets. + + Test Steps: + 1. Run asset processor + 2. Verify asset processor exits cleanly """ asset_processor.create_temp_asset_root() @@ -402,6 +513,14 @@ class TestsAssetProcessorBatch_AllPlatforms(object): # fmt:on """ AssetProcessor successfully recovers assets from cache when deleted. + + Test Steps: + 1. Create test enviornment with test assets + 2. Run Asset Processor and verify it exits cleanly + 3. Make sure cache folder was generated + 4. Delete temp cache assets but leave database behind + 5. Run asset processor and verify it exits cleanly + 6. Verify expected files were generated in the cache """ env = ap_setup_fixture @@ -434,6 +553,14 @@ class TestsAssetProcessorBatch_AllPlatforms(object): @pytest.mark.assetpipeline # fmt:off def test_AllSupportedPlatforms_RunFastScanOnEmptyCache_FullScanRuns(self, ap_setup_fixture, asset_processor): + """ + Tests fast scan processing on an empty cache and verifies that a full analyis will be peformed + + Test Steps: + 1. Create a test environment + 2. Execute asset processor batch with fast scan enabled + 3. Verify that a full analysis is performed + """ # fmt:on env = ap_setup_fixture asset_processor.create_temp_asset_root() @@ -455,6 +582,11 @@ class TestsAssetProcessorBatch_AllPlatforms(object): """ After running the APBatch and AP GUI, Logs directory should exist (C1564055), JobLogs, Batch log, and GUI log should exist in the logs directory (C1564056) + + Test Steps: + 1. Run asset processor batch + 2. Run asset processor gui with quit on idle + 3. Verify that logs exist for both AP Batch & AP GUI """ asset_processor.create_temp_asset_root() LOG_PATH = { @@ -536,6 +668,11 @@ class TestsAssetProcessorBatch_AllPlatforms(object): """ Utilizing corrupted test assets, run the batch process to verify the AP logs the failure to process the corrupted file. + + Test Steps: + 1. Create test environment with corrupted slice + 2. Launch Asset Processor + 3. Verify that asset processor fails to process corrupted slice """ env = ap_setup_fixture error_line_found = False @@ -552,6 +689,15 @@ class TestsAssetProcessorBatch_AllPlatforms(object): @pytest.mark.BAT @pytest.mark.assetpipeline def test_validateDirectPreloadDependency_Found(self, asset_processor, ap_setup_fixture, workspace): + """ + Tests processing an asset with a circular dependency and verifies that Asset Processor will return an error + notifying the user about a circular dependency. + + Test Steps: + 1. Create test environment with an asset that has a circular dependency + 2. Launch asset processor + 3. Verify that error is returned informing the user that the asset has a circular dependency + """ env = ap_setup_fixture error_line_found = False @@ -567,6 +713,15 @@ class TestsAssetProcessorBatch_AllPlatforms(object): @pytest.mark.BAT @pytest.mark.assetpipeline def test_validateNestedPreloadDependency_Found(self, asset_processor, ap_setup_fixture, workspace): + """ + Tests processing of a nested circular dependency and verifies that Asset Processor will return an error + notifying the user about a circular depdency + + Test Steps: + 1. Create test environment with an asset that has a nested circular dependency + 2. Launch asset processor + 3. Verify that error is returned informing the user that the asset has a circular dependency + """ env = ap_setup_fixture error_line_found = False diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests_2.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests_2.py index 5c42af2139..fec5df8eb7 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests_2.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests_2.py @@ -80,6 +80,15 @@ class TestsAssetProcessorBatch_AllPlatforms(object): # fmt:on """ Tests that fast scan mode can be used and is faster than full scan mode. + + Test Steps: + 1. Ensure all assets are processed + 2. Run Asset Processor without fast scan and measure the time it takes to run + 3. Capture Full Analysis was performed and number of assets processed + 4. Run Asset Processor with full scan and measure the time it takes to run + 5. Capture Full Analysis wans't performed and number of assets processed + 6. Verify that fast scan was faster than full scan + 7. Verify that full scan scanned more assets """ asset_processor.create_temp_asset_root() @@ -111,76 +120,23 @@ class TestsAssetProcessorBatch_AllPlatforms(object): assert full_scan_time > fast_scan_time, "Fast scan was slower that full scan" assert full_scan_analysis[0] > fast_scan_analysis[0], "Full scan did not process more assets than fast scan" - @pytest.mark.test_case_id("C18787404") - @pytest.mark.BAT - @pytest.mark.assetpipeline - @pytest.mark.skip(reason="External project is currently broken.") # LY-119863 - def test_AllSupportedPlatforms_ExternalProject_APRuns(self, workspace, ap_external_project_setup_fixture): - - external_resources = ap_external_project_setup_fixture - logger.info(f"Running external project test at path {external_resources['project_dir']}") - # Delete existing "external project" build if it exists - if os.path.exists(external_resources["project_dir"]): - fs.delete([external_resources["project_dir"]], True, True) - - # fmt:off - assert not os.path.exists(external_resources["project_dir"]), \ - f'{external_resources["project_dir"]} was not deleted' - # fmt:on - - lmbr_cmd = [ - workspace.paths.lmbr(), - "projects", - "create", - external_resources["project_name"], - "--template", - "EmptyTemplate", - "--app-root", - external_resources["project_dir"], - ] - - logger.info(f"Running lmbr projects create command '{lmbr_cmd}'") - - try: - subprocess.check_call(lmbr_cmd) - except subprocess.CalledProcessError as e: - assert False, f"lmbr projects create failed\n{e.stderr}" - - logger.info("...lmbr finished") - assert os.path.exists(external_resources["project_dir"]), "Project folder was not created" - - # AssetProcessor for new External project. Uses mock workspace to emulate external project workspace - external_ap = AssetProcessor(external_resources["external_workspace"]) - - # fmt:off - assert external_ap.batch_process(fastscan=False), \ - "Asset Processor Batch failed on external project" - # fmt:on - - # Parse log looking for errors or failures - log = APLogParser(workspace.paths.ap_batch_log()) - failures, errors = log.runs[-1]["Failures"], log.runs[-1]["Errors"] - assert failures == 0, f"There were {failures} asset processing failures" - assert errors == 0, f"There were {errors} asset processing errors" - - # Check that project cache was created (DNE until AP makes it) - project_cache = os.path.join(external_resources["project_dir"], "Cache") - assert os.path.exists(project_cache), f"{project_cache} was not created by AP" - - # Clean up external project - fs.delete([external_resources["project_dir"]], True, True) - - # fmt:off - assert not os.path.exists(external_resources["project_dir"]), \ - f"{external_resources['project_dir']} was not deleted" - # fmt:on - @pytest.mark.test_case_id("C4874121") @pytest.mark.BAT @pytest.mark.assetpipeline @pytest.mark.parametrize("clear_type", ["rewrite", "delete_asset", "delete_dir"]) def test_AllSupportedPlatforms_DeleteBadAssets_BatchFailedJobsCleared( self, workspace, request, ap_setup_fixture, asset_processor, clear_type): + """ + Tests the ability of Asset Processor to recover from processing of bad assets by removing them from scan folder + + Test Steps: + 1. Create testing environment with good and multiple bad assets + 2. Run Asset Processor + 3. Verify that bad assets fail to process + 4. Fix a bad asset & delete the others + 5. Run Asset Processor + 6. Verify Asset Processor does not have any asset failues + """ env = ap_setup_fixture error_search_terms = ["WWWWWWWWWWWW"] @@ -250,6 +206,14 @@ class TestsAssetProcessorBatch_Windows(object): Verify the AP batch and Gui can run and process assets independent of the Editor We do not want or need to kill running Editors here as they can be involved in other tests or simply being run locally in this branch or another + + Test Steps: + 1. Create temporary testing environment + 2. Run asset processor GUI + 3. Verify AP GUI doesn't error + 4. Stop AP GUI + 5. Run Asset Processor Batch with Fast Scan + 5. Verify Asset Processor Batch exits cleanly """ asset_processor.create_temp_asset_root() @@ -272,6 +236,11 @@ class TestsAssetProcessorBatch_Windows(object): """ Request a run for an invalid platform "AssetProcessor: Error: Platform in config file or command line 'notaplatform'" should be present in the logs + + Test Steps: + 1. Create temporary testing environment + 2. Run Asset Processor with an invalid platform + 3. Check that asset processor returns an Error notifying the user that the invalid platform is not supported """ asset_processor.create_temp_asset_root() error_search_terms = 'AssetProcessor: Error: The list of enabled platforms in the settings registry does not contain platform ' \ diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests.py index ed5651755c..88fa1a77b4 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests.py @@ -77,6 +77,13 @@ class TestsAssetProcessorGUI_Windows(object): def test_SendInputOnControlChannel_ReceivedAndResponded(self, asset_processor): """ Test that the control channel connects and that communication works both directions + + Test Steps: + 1. Start Asset Processor + 2. Send a Ping message to Asset Processor + 3. Listen for Asset Processor response + 4. Verify Asset Processor responds + 5. Stop asset Processor """ asset_processor.create_temp_asset_root() @@ -129,7 +136,15 @@ class TestsAssetProcessorGUI_Windows(object): # fmt:on """ Asset Processor Deletes processed assets when source is removed from project folder (while running) + + Test Steps: + 1. Create a temporary test environment + 2. Run Asset Processor GUI set to stay open on idle and verify that it does not fail + 3. Verify that assets were copied to the cache + 4. Delete the source test asset directory + 5. Verify assets are deleted from the cache """ + env = ap_setup_fixture # Copy test assets to project folder and verify test assets folder exists @@ -170,7 +185,18 @@ class TestsAssetProcessorGUI_Windows(object): # fmt:on """ Processing changed files (while running) + + Test Steps: + 1. Create temporary test environment with test assets + 2. Open Asset Processor GUI with set to stay open after idle and verify it does not fail + 3. Verify contents of source asset for later comparison + 4. Verify contents of product asset for later comparison + 5. Modify contents of source asset + 6. Wait for Asset Processor to go back to idle state + 7. Verify contents of source asset are the modified version + 8. Verify contents of product asset are the modified version """ + env = ap_setup_fixture # Copy test assets to project folder and verify test assets folder exists @@ -184,7 +210,7 @@ class TestsAssetProcessorGUI_Windows(object): result, _ = asset_processor.gui_process(quitonidle=False) assert result, "AP GUI failed" - # Verify contents of test asset in project folder before modication + # Verify contents of test asset in project folder before modification with open(project_asset_path, "r") as project_asset_file: assert project_asset_file.read() == "before_state" @@ -217,7 +243,14 @@ class TestsAssetProcessorGUI_Windows(object): def test_WindowsPlatforms_RunAP_ProcessesIdle(self, asset_processor): """ Asset Processor goes idle + + Test Steps: + 1. Create a temporary testing evnironment + 2. Run Asset Processor GUI without quitonidle + 3. Verify AP Goes Idle + 4. Verify AP goes below 1% CPU usage """ + CPU_USAGE_THRESHOLD = 1.0 # CPU usage percentage delimiting idle from active CPU_USAGE_WIND_DOWN = 10 # Time allowed in seconds for idle processes to stop using CPU @@ -245,7 +278,16 @@ class TestsAssetProcessorGUI_Windows(object): ): """ Processing newly added files to project folder (while running) + + Test Steps: + 1. Create a temporary testing environment with test assets + 2. Create a secondary set of testing assets that have not been copied into the the testing environment + 3. Start Asset Processor without quitonidle + 4. While Asset Processor is running add secondary set of testing assets to the testing environment + 5. Wait for Asset Processor to go idle + 6. Verify that all assets are in the cache """ + env = ap_setup_fixture level_name = "C1564064_level" new_asset = "C1564064.scriptcanvas" @@ -316,7 +358,14 @@ class TestsAssetProcessorGUI_Windows(object): def test_WindowsPlatforms_LaunchAP_LogReportsIdle(self, asset_processor, workspace, ap_idle): """ Asset Processor creates a log entry when it goes idle + + Test Steps: + 1. Create temporary testing environment + 2. Run Asset Processor batch to pre-process assets + 3. Run Asset Processor GUI + 4. Check if Asset Processor GUI reports that it has gone idle """ + asset_processor.create_temp_asset_root() # Run batch process to ensure project assets are processed assert asset_processor.batch_process(), "AP Batch failed" @@ -331,6 +380,17 @@ class TestsAssetProcessorGUI_Windows(object): @pytest.mark.assetpipeline def test_APStopTimesOut_ExceptionThrown(self, ap_setup_fixture, asset_processor): + """ + Tests whether or not Asset Processor will Time Out + + Test Steps: + 1. Create a temporary testing environment + 2. Start the Asset Processor + 3. Copy in assets to the test environment + 4. Try to stop the Asset Processor with a timeout of 1 second (This cannot be done manually). + 5. Verify that Asset Processor times out and returns the expected error + """ + asset_processor.create_temp_asset_root() asset_processor.start() @@ -347,9 +407,20 @@ class TestsAssetProcessorGUI_Windows(object): @pytest.mark.assetpipeline def test_APStopDefaultTimeout_NoException(self, asset_processor): - # If this test fails, it means other tests using the default timeout may have issues. - # In that case, either the default timeout should either be raised, or the performance - # of AP launching should be improved. + """ + Tests the default timeout of the Asset Processor + + If this test fails, it means other tests using the default timeout may have issues. + In that case, either the default timeout should either be raised, or the performance + of AP launching should be improved. + + Test Steps: + 1. Create a temporary testing environment + 2. Start the Asset Processor + 3. Stop the asset Processor without sending a timeout to it + 4. Verify that the asset processor times out and returns the expected error + """ + asset_processor.create_temp_asset_root() asset_processor.start() ap_quit_timed_out = False diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests_2.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests_2.py index b25ee081a1..3fb9ae5a81 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests_2.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests_2.py @@ -75,10 +75,17 @@ class TestsAssetProcessorGUI_WindowsAndMac(object): @pytest.mark.test_case_id("C3540434") @pytest.mark.BAT @pytest.mark.assetpipeline - def test_WindowsAndMacPlatforms_AP_GUI_FastScanSettingCreated(self, asset_processor, fast_scan_backup): + def test_WindowsAndMacPlatforms_GUIFastScanNoSettingSet_FastScanSettingCreated(self, asset_processor, fast_scan_backup): """ Tests that a fast scan settings entry gets created for the AP if it does not exist and ensures that the entry is defaulted to fast-scan enabled + + Test Steps: + 1. Create temporary testing environment + 2. Delete existing fast scan setting if exists + 3. Run Asset Processor GUI without setting FastScan setting (default:true) and without quitonidle + 4. Wait and check to see if Windows Registry fast scan setting is created + 5. Verify that Fast Scan setting is set to true """ asset_processor.create_temp_asset_root() @@ -119,6 +126,14 @@ class TestsAssetProcessorGUI_WindowsAndMac(object): Make sure game launcher working with Asset Processor set to turbo mode Validate that no fatal errors (crashes) are reported within a certain time frame for the AP and the GameLauncher + + Test Steps: + 1. Create temporary testing environment + 2. Set fast scan to true + 3. Verify fast scan is set to true + 4. Launch game launcher + 5. Verify launcher has launched without error + 6. Verify that asset processor has launched """ CHECK_ALIVE_SECONDS = 15 @@ -166,6 +181,14 @@ class TestsAssetProcessorGUI_AllPlatforms(object): # fmt:on """ Deleting slices and uicanvases while AP is running + + Test Steps: + 1. Create temporary testing environment with test assets + 2. Launch Asset Processor and wait for it to go idle + 3. Verify product assets were created in the cache + 4. Delete test assets from the cache + 5. Wait for Asset Processor to go idle + 6. Verify product assets were regenerated in the cache """ env = ap_setup_fixture @@ -201,6 +224,15 @@ class TestsAssetProcessorGUI_AllPlatforms(object): ): """ Process slice files and uicanvas files from the additional scanfolder + + Test Steps: + 1. Create temporary testing environment + 2. Run asset processor batch + 3. Validate that product assets were generated in the cache + 4. Create an additional scan folder with assets + 5. Create additional scan folder params to pass to Asset Processor + 6. Run Asset Processor GUI with QuitOnIdle and pass in params for the additional scan folder settings + 7. Verify additional product assets from additional scan folder are present in the cache """ env = ap_setup_fixture # Copy test assets to new folder in dev folder @@ -250,6 +282,12 @@ class TestsAssetProcessorGUI_AllPlatforms(object): """ Launch AP with invalid address in bootstrap.cfg Assets should process regardless of the new address + + Test Steps: + 1. Create a temporary testing environment + 2. Set an invalid ip address in Asset Processor settings file + 3. Launch Asset Processor GUI + 4. Verify that it processes assets and exits cleanly even though it has an invalid IP. """ test_ip_address = "1.1.1.1" # an IP address without Asset Processor @@ -269,6 +307,14 @@ class TestsAssetProcessorGUI_AllPlatforms(object): def test_AllSupportedPlatforms_ModifyAssetInfo_AssetsReprocessed(self, ap_setup_fixture, asset_processor): """ Modifying assetinfo files triggers file reprocessing + + Test Steps: + 1. Create temporary testing environment with test assets + 2. Run Asset Processor GUI + 3. Verify that Asset Processor exited cleanly and product assets are in the cache + 4. Modify the .assetinfo file by adding a newline + 5. Wait for Asset Processor to go idle + 6. Verify that product files were regenerated (Time Stamp compare) """ env = ap_setup_fixture diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_relocator_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_relocator_tests.py index 2d3872bf31..30044fa9e2 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_relocator_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_relocator_tests.py @@ -85,6 +85,18 @@ class TestsAssetRelocator_WindowsAndMac(object): def test_WindowsMacPlatforms_RelocatorMoveFileWithConfirm_MoveSuccess(self, request, workspace, asset_processor, ap_setup_fixture, testId, readonly, confirm, success): + """ + Tests whether tests with Move File Confirm are successful + + Test Steps: + 1. Create temporary testing environment + 2. Set move location + 3. Determine if confirm flag is set + 4. Attempt to move the files + 5. If confirm flag set: + * Validate Move was successful + * Else: Validate move was not successful + """ env = ap_setup_fixture copied_asset = '' @@ -141,6 +153,11 @@ class TestsAssetRelocator_WindowsAndMac(object): User should be warned that LeaveEmptyFolders needs to be used with the move or delete command :return: None + + Test Steps: + 1. Create temporary testing environment + 2. Attempt to move with --LeaveEmptyFolders set + 3. Verify user is given a message that command requires to be used with --move or --delete """ env = ap_setup_fixture expected_message = "Command --leaveEmptyFolders must be used with command --move or --delete" @@ -162,6 +179,11 @@ class TestsAssetRelocator_WindowsAndMac(object): Asset with UUID/AssetId reference in non-standard format is successfully scanned and relocated to the MoveOutput folder. This test uses a pre-corrupted .slice file. + + Test Steps: + 1. Create temporary testing environment with a corrupted slice + 2. Attempt to move the corrupted slice + 3. Verify that corrupted slice was moved successfully """ env = ap_setup_fixture @@ -194,6 +216,11 @@ class TestsAssetRelocator_WindowsAndMac(object): def test_WindowsMacPlatforms_UpdateReferences_MoveCommandMessage(self, ap_setup_fixture, asset_processor): """ UpdateReferences without move or delete + + Test Steps: + 1. Create temporary testing environment + 2. Attempt to move with UpdateReferences but without move or delete flags + 3. Verify that message is returned to the user that additional flags are required """ env = ap_setup_fixture expected_message = "Command --updateReferences must be used with command --move" @@ -215,6 +242,11 @@ class TestsAssetRelocator_WindowsAndMac(object): """ When running the relocator command --AllowBrokenDependencies without the move or delete flags, the user should be warned that the flags are necessary for the functionality to be used + + Test Steps: + 1. Create temporary testing environment + 2. Attempt to move with AllowBrokenDependencies without the move or delete flag + 3. Verify that message is returned to the user that additional flags are required """ env = ap_setup_fixture @@ -302,10 +334,19 @@ class TestsAssetRelocator_WindowsAndMac(object): project ): """ + Dynamic data test for deleting a file with Asset Relocator: + C21968355 Delete a file with confirm C21968356 Delete a file without confirm C21968359 Delete a file that is marked as ReadOnly C21968360 Delete a file that is not marked as ReadOnly + + Test Steps: + 1. Create temporary testing environment + 2. Set the read-only status of the file based on the test case + 3. Run asset relocator with --delete and the confirm status based on the test case + 4. Assert file existence or nonexistence based on the test case + 5. Validate the relocation report based on expected and unexpected messages """ env = ap_setup_fixture test_file = "testFile.txt" @@ -430,6 +471,15 @@ class TestsAssetRelocator_WindowsAndMac(object): Test the LeaveEmptyFolders flag in various configurations :returns: None + + Test Steps: + 1. Create temporary testing environment + 2. Build the various move/delete commands here based on test data + 3. Run the move command with the various triggers based on test data + 4. Verify the original assets folder still exists based on test data + 5. Verify the files successfully moved to new location based on test data + 6. Verify that the files were removed from original location based on test data + 7. Verify the files have not been deleted or moved from original location based on test data """ # # Start test setup # # env = ap_setup_fixture @@ -517,6 +567,12 @@ class TestsAssetRelocator_WindowsAndMac(object): """ The test will attempt to move test assets that are not tracked under P4 source control using the EnableSCM flag Because the files are not tracked by source control, the relocation should fail + + Test Steps: + 1. Create temporary testing environment + 2. Set ReadOnly or Not-ReadOnly for the test files based on test data + 3. Generate and run the enableSCM command + 4. Verify the move failed and expected messages are present """ # Move the test assets into the project folder env = ap_setup_fixture @@ -1037,6 +1093,13 @@ class TestsAssetRelocator_WindowsAndMac(object): C21968370 AllowBrokenDependencies with move and confirm C21968371 AllowBrokenDependencies with move and without confirm C21968375 AllowBrokenDependencies with delete + + Test Steps: + 1. Create temporary testing environment + 2. Run Asset Processor to Process Assets + 3. Build primary AP Batch parameter value and destination paths + 4. Validate resulting file paths in source and output directories + 5. Validate the log based on expected and unexpected messages """ env = ap_setup_fixture all_test_asset_rel_paths = [ @@ -1254,6 +1317,18 @@ class TestsAssetRelocator_WindowsAndMac(object): @pytest.mark.parametrize("test", tests) def test_WindowsAndMac_MoveMetadataFiles_PathExistenceAndMessage(self, workspace, request, ap_setup_fixture, asset_processor, test): + """ + Tests whether moving metadata files can be moved + + Test Steps: + 1. Create temporary testing environment + 2. Determine if using wildcards on paths or not + 3. Determine if excludeMetaDataFiles is set or not + 4. Build primary AP Batch parameter value and destination paths + 5. Build and run the AP Batch command with parameters + 6. Validate resulting file paths in source and output directories + 7. Validate the log based on expected and unexpected messages + """ env = ap_setup_fixture def teardown(): @@ -1342,7 +1417,7 @@ class TestsAssetRelocator_WindowsAndMac(object): @dataclass class MoveTest: - description: str # test case title directly copied from Testrail + description: str # test case title asset_folder: str # which folder in ./assets will be used for this test encoded_command: str # the command to execute encoded_output_dir: str # the destination directory to validate @@ -1350,7 +1425,7 @@ class MoveTest: name_change_map: dict = None files_that_stay: List[str] = field(default_factory=lambda: []) output_messages: List[str] = field(default_factory=lambda: []) - step: str = None # the step of the test from Testrail + step: str = None # the step of the test from test repository prefix_commands: List[str] = field(default_factory=lambda: ["AssetProcessorBatch", "--zeroAnalysisMode"]) suffix_commands: List[str] = field(default_factory=lambda: ["--confirm"]) env: dict = field(init=False, default=None) # inject the ap_setup_fixture at runtime @@ -3718,7 +3793,18 @@ class TestsAssetProcessorMove_WindowsAndMac: # -k C19462747 @pytest.mark.parametrize("test", move_a_file_tests + move_a_folder_tests) - def test_WindowsMacPlatforms_MoveCommand(self, asset_processor, ap_setup_fixture, test: MoveTest, project): + def test_WindowsMacPlatforms_MoveCommand_CommandResult(self, asset_processor, ap_setup_fixture, test: MoveTest, project): + """ + + Test Steps: + 1. Create temporary testing environment based on test data + 2. Validate that temporary testing environment was created successfully + 3. Execute the move command based upon the test data + 4. Validate that files are where they're expected according to the test data + 5. Validate unexpected files are not found according to the test data + 6. Validate output messages according to the test data + 7. Validate move status according to the test data + """ source_folder, _ = asset_processor.prepare_test_environment(ap_setup_fixture["tests_dir"], test.asset_folder) test.map_env(ap_setup_fixture, source_folder) diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/missing_dependency_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/missing_dependency_tests.py index 432b6cdfc8..74f6de1129 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/missing_dependency_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/missing_dependency_tests.py @@ -75,6 +75,15 @@ class TestsMissingDependencies_WindowsAndMac(object): def do_missing_dependency_test(self, source_product, expected_dependencies, dsp_param, platforms=None, max_iterations=0): + """ + Test Steps: + 1. Determine what platforms to run against + 2. Process assets for that platform + 3. Determine the missing dependency params to set + 4. Set the max iteration param + 5. Run missing dependency scanner against target platforms and search params based on test data + 6. Validate missing dependencies against test data + """ platforms = platforms or ASSET_PROCESSOR_PLATFORM_MAP[self._workspace.asset_processor_platform] if not isinstance(platforms, list): @@ -104,7 +113,14 @@ class TestsMissingDependencies_WindowsAndMac(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id("C17226567") def test_WindowsAndMac_ValidUUIDNotDependency_ReportsMissingDependency(self): - """Tests that a valid UUID referenced in a file will report any missing dependencies""" + """ + Tests that a valid UUID referenced in a file will report any missing dependencies + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ # Relative path to the txt file with missing dependencies expected_product = f"testassets\\validuuidsnotdependency.txt" @@ -141,7 +157,14 @@ class TestsMissingDependencies_WindowsAndMac(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id("C17226567") def test_WindowsAndMac_InvalidUUIDsNotDependencies_NoReportedMessage(self): - """Tests that invalid UUIDs do not count as missing dependencies""" + """ + Tests that invalid UUIDs do not count as missing dependencies + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ # Relative path to the txt file with invalid UUIDs expected_product = f"testassets\\invaliduuidnoreport.txt" expected_dependencies = [] # No expected missing dependencies @@ -153,7 +176,14 @@ class TestsMissingDependencies_WindowsAndMac(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id("C17226567") def test_WindowsAndMac_ValidAssetIdsNotDependencies_ReportsMissingDependency(self): - """Tests that valid asset IDs but not dependencies, show missing dependencies""" + """ + Tests that valid asset IDs but not dependencies, show missing dependencies + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ # Relative path to the txt file with valid asset ids but not dependencies expected_product = f"testassets\\validassetidnotdependency.txt" @@ -173,7 +203,14 @@ class TestsMissingDependencies_WindowsAndMac(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id("C17226567") def test_WindowsAndMac_InvalidAssetsIDNotDependencies_NoReportedMessage(self): - """Tests that invalid asset IDs do not count as missing dependencies""" + """ + Tests that invalid asset IDs do not count as missing dependencies + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ # Relative path to the txt file with invalid asset IDs expected_product = f"testassets\\invalidassetidnoreport.txt" @@ -188,7 +225,14 @@ class TestsMissingDependencies_WindowsAndMac(object): # fmt:off def test_WindowsAndMac_ValidSourcePathsNotDependencies_ReportsMissingDependencies(self): # fmt:on - """Tests that valid source paths can translate to missing dependencies""" + """ + Tests that valid source paths can translate to missing dependencies + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ # Relative path to the txt file with missing dependencies as source paths expected_product = f"testassets\\relativesourcepathsnotdependencies.txt" @@ -212,7 +256,14 @@ class TestsMissingDependencies_WindowsAndMac(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id("C17226567") def test_WindowsAndMac_InvalidARelativePathsNotDependencies_NoReportedMessage(self): - """Tests that invalid relative paths do not resolve to missing dependencies""" + """ + Tests that invalid relative paths do not resolve to missing dependencies + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ # Relative path to the txt file with invalid relative paths expected_product = f"testassets\\invalidrelativepathsnoreport.txt" @@ -227,7 +278,14 @@ class TestsMissingDependencies_WindowsAndMac(object): # fmt:off def test_WindowsAndMac_ValidProductPathsNotDependencies_ReportsMissingDependencies(self): # fmt:on - """Tests that valid product paths can resolve to missing dependencies""" + """ + Tests that valid product paths can resolve to missing dependencies + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ self._asset_processor.add_source_folder_assets(f"Gems\\LyShineExamples\\Assets\\UI\\Fonts\\LyShineExamples") self._asset_processor.add_scan_folder(f"Gems\\LyShineExamples\\Assets") @@ -260,7 +318,14 @@ class TestsMissingDependencies_WindowsAndMac(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id("C17226567") def test_WindowsAndMac_WildcardScan_FindsAllExpectedFiles(self): - """Tests that the wildcard scanning will pick up multiple files""" + """ + Tests that the wildcard scanning will pick up multiple files + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ helper = self._missing_dep_helper @@ -291,6 +356,11 @@ class TestsMissingDependencies_WindowsAndMac(object): For these references that are valid, all but one have available, matching dependencies. This test is primarily meant to verify that the missing dependency reporter checks the product dependency table before emitting missing dependencies. + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test """ # Relative path to target test file expected_product = f"testassets\\reportonemissingdependency.txt" @@ -305,7 +375,14 @@ class TestsMissingDependencies_WindowsAndMac(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id("C17226567") def test_WindowsAndMac_ReferencesSelfPath_NoReportedMessage(self): - """Tests that a file that references itself via relative path does not report itself as a missing dependency""" + """ + Tests that a file that references itself via relative path does not report itself as a missing dependency + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ # Relative path to file that references itself via relative path expected_product = f"testassets\\selfreferencepath.txt" expected_dependencies = [] @@ -317,7 +394,14 @@ class TestsMissingDependencies_WindowsAndMac(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id("C17226567") def test_WindowsAndMac_ReferencesSelfUUID_NoReportedMessage(self): - """Tests that a file that references itself via its UUID does not report itself as a missing dependency""" + """ + Tests that a file that references itself via its UUID does not report itself as a missing dependency + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ # Relative path to file that references itself via its UUID expected_product = f"testassets\\selfreferenceuuid.txt" @@ -330,7 +414,14 @@ class TestsMissingDependencies_WindowsAndMac(object): @pytest.mark.assetpipeline @pytest.mark.test_case_id("C17226567") def test_WindowsAndMac_ReferencesSelfAssetID_NoReportedMessage(self): - """Tests that a file that references itself via its Asset ID does not report itself as a missing dependency""" + """ + Tests that a file that references itself via its Asset ID does not report itself as a missing dependency + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ # Relative path to file that references itself via its Asset ID expected_product = f"testassets\\selfreferenceassetid.txt" @@ -347,6 +438,11 @@ class TestsMissingDependencies_WindowsAndMac(object): Tests that the scan limit fails to find a missing dependency that is out of reach. The max iteration count is set to just under where a valid missing dependency is on a line in the file, so this will not report any missing dependencies. + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test """ # Relative path to file that has a missing dependency at 31 iterations deep @@ -364,7 +460,13 @@ class TestsMissingDependencies_WindowsAndMac(object): Tests that the scan limit succeeds in finding a missing dependency that is barely in reach. In the previous test, the scanner was set to stop recursion just before a missing dependency was found. This test runs with the recursion limit set deep enough to actually find the missing dependency. + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test """ + # Relative path to file that has a missing dependency at 31 iterations deep expected_product = f"testassets\\maxiteration31deep.txt" @@ -383,7 +485,14 @@ class TestsMissingDependencies_WindowsAndMac(object): # fmt:off def test_WindowsAndMac_PotentialMatchesLongerThanUUIDString_OnlyReportsCorrectLengthUUIDs(self): # fmt:on - """Tests that dependency references that are longer than expected are ignored""" + """ + Tests that dependency references that are longer than expected are ignored + + Test Steps: + 1. Set the expected product + 2. Set the expected missing dependencies + 3. Execute test + """ # Relative path to text file with varying length UUID references expected_product = f"testassets\\onlymatchescorrectlengthuuids.txt" @@ -408,7 +517,14 @@ class TestsMissingDependencies_WindowsAndMac(object): def test_WindowsAndMac_MissingDependencyScanner_GradImageSuccess( self, ap_setup_fixture ): - """Tests the Missing Dependency Scanner can scan gradimage files""" + """ + Tests the Missing Dependency Scanner can scan gradimage files + + Test Steps: + 1. Create temporary testing environment + 2. Run the move dependency scanner against the gradimage + 2. Validate that the expected product files and and expected depdencies match + """ env = ap_setup_fixture helper = self._missing_dep_helper diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/auxiliary_content_tests/auxiliary_content_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/auxiliary_content_tests/auxiliary_content_tests.py index 7e9f65de60..452dc66352 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/auxiliary_content_tests/auxiliary_content_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/auxiliary_content_tests/auxiliary_content_tests.py @@ -51,6 +51,11 @@ class TestAuxiliaryContent: def test_CreateAuxiliaryContent_DontSkipLevelPaks(self, workspace, level): """ This test ensure that Auxiliary Content contain level.pak files + + Test Steps: + 1. Run auxiliary content against project under test + 2. Validate auxiliary content exists + 3. Verifies that level.pak exists """ path_to_dev = workspace.paths.engine_root() @@ -70,6 +75,11 @@ class TestAuxiliaryContent: def test_CreateAuxiliaryContent_SkipLevelPaks(self, workspace, level): """ This test ensure that Auxiliary Content contain no level.pak file + + Test Steps: + 1. Run auxiliary content against project under test with skiplevelPaks flag + 2. Validate auxiliary content exists + 3. Validate level.pak was added to auxiliary content """ path_to_dev = workspace.paths.engine_root() diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/fbx_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/fbx_tests.py index b66984666b..afd7190c1b 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/fbx_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/fbx_tests.py @@ -533,6 +533,14 @@ class TestsFBX_AllPlatforms(object): def test_FBXBlackboxTest_SourceFiles_Processed_ResultInExpectedProducts(self, workspace, ap_setup_fixture, asset_processor, project, blackbox_param): + """ + Please see run_fbx_test(...) for details + + Test Steps: + 1. Determine if blackbox is set to none + 2. Run FBX Test + """ + if blackbox_param == None: return self.run_fbx_test(workspace, ap_setup_fixture, @@ -544,6 +552,15 @@ class TestsFBX_AllPlatforms(object): workspace, ap_setup_fixture, asset_processor, project, blackbox_param): + """ + Please see run_fbx_test(...) for details + + Test Steps: + 1. Determine if blackbox is set to none + 2. Run FBX Test + 2. Re-run FBX test and validate the information in override assets + """ + if blackbox_param == None: return self.run_fbx_test(workspace, ap_setup_fixture, @@ -567,6 +584,19 @@ class TestsFBX_AllPlatforms(object): def run_fbx_test(self, workspace, ap_setup_fixture, asset_processor, project, blackbox_params: BlackboxAssetTest, overrideAsset = False): + """ + These tests work by having the test case ingest the test data and determine the run pattern. + Tests will process scene settings files and will additionally do a verification against a provided debug file + Additionally, if an override is passed, the output is checked against the override. + + Test Steps: + 1. Create temporary test environment + 2. Process Assets + 3. Determine what assets to validate based upon test data + 4. Validate assets were created in cache + 5. If debug file provided, verify scene files were generated correctly + 6. Verify that each given source asset resulted in the expected jobs and products + """ test_assets_folder = blackbox_params.override_asset_folder if overrideAsset else blackbox_params.asset_folder logger.info(f"{blackbox_params.test_name}: Processing assets in folder '" diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/bank_info_parser_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/bank_info_parser_tests.py index 0db13bf53c..764b7723bf 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/bank_info_parser_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/bank_info_parser_tests.py @@ -26,6 +26,18 @@ def soundbank_metadata_generator_setup_fixture(workspace): def success_case_test(test_folder, expected_dependencies_dict, bank_info, expected_result_code=0): + """ + Test Steps: + 1. Make sure the return code is what was expected, and that the expected number of banks were returned. + 2. Validate bank is in the expected dependencies dictionary. + 3. Validate the path to output the metadata file to was assembled correctly. + 4. Validate metadata object for this bank is set, and that it has an object assigned to its dependencies field + and its includedEvents field + 5. Validate metadata object has the correct number of dependencies, and validated that every expected dependency + exists in the dependencies list of the metadata object. + 6. Validate metadata object has the correct number of events, and validate that every expected event exists in the + events of the metadata object. + """ expected_bank_count = len(expected_dependencies_dict) banks, result_code = bank_info.generate_metadata( @@ -80,8 +92,17 @@ class TestSoundBankMetadataGenerator: def test_NoMetadataTooFewBanks_ReturnCodeIsError(self, workspace, soundbank_metadata_generator_setup_fixture): - # Trying to generate metadata for banks in a folder with one or fewer banks and no metadata is not possible - # and should fail. + """ + Trying to generate metadata for banks in a folder with one or fewer banks and no metadata is not possible + and should fail. + + Test Steps: + 1. Setup testing environment with only 1 bank file + 2. Get Sound Bank Info + 3. Attempt to generate sound bank metadata + 4. Verify that proper error code is returned + """ + # test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_NoMetadataTooFewBanks_ReturnCodeIsError') if not os.path.isdir(test_assets_folder): @@ -97,15 +118,30 @@ class TestSoundBankMetadataGenerator: assert error_code is 2, 'Metadata was generated when there were fewer than two banks in the target directory.' def test_NoMetadataNoContentBank_NoMetadataGenerated(self, workspace, soundbank_metadata_generator_setup_fixture): + """ + Test Steps: + 1. Setup testing environment + 2. No expected dependencies + 3. Call success case test + """ test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_NoMetadataNoContentBank_NoMetadataGenerated') expected_dependencies = dict() success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace)) def test_NoMetadataOneContentBank_NoStreamedFiles_OneDependency(self, workspace, soundbank_metadata_generator_setup_fixture): - # When no Wwise metadata is present, and there is only one content bank in the target directory with no wem - # files, then only the content bank should have metadata associated with it. The generated metadata should - # only describe a dependency on the init bank. + """ + When no Wwise metadata is present, and there is only one content bank in the target directory with no wem + files, then only the content bank should have metadata associated with it. The generated metadata should + only describe a dependency on the init bank. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_NoMetadataOneContentBank_NoStreamedFiles_OneDependency') @@ -116,9 +152,18 @@ class TestSoundBankMetadataGenerator: def test_NoMetadataOneContentBank_StreamedFiles_MultipleDependencies(self, workspace, soundbank_metadata_generator_setup_fixture): - # When no Wwise metadata is present, and there is only one content bank in the target directory with wem files - # present, then only the content bank should have metadata associated with it. The generated metadata should - # describe a dependency on the init bank and all wem files in the folder. + """ + When no Wwise metadata is present, and there is only one content bank in the target directory with wem files + present, then only the content bank should have metadata associated with it. The generated metadata should + describe a dependency on the init bank and all wem files in the folder. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_NoMetadataOneContentBank_StreamedFiles_MultipleDependencies') @@ -136,10 +181,19 @@ class TestSoundBankMetadataGenerator: success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace)) def test_NoMetadataMultipleBanks_OneDependency_ReturnCodeIsWarning(self, workspace, soundbank_metadata_generator_setup_fixture): - # When no Wwise metadata is present, and there are multiple content banks in the target directory with wem files - # present, there is no way to tell which bank requires which wem files. A warning should be emitted, - # stating that the full dependency graph could not be created, and only dependencies on the init bank are - # described in the generated metadata files. + """ + When no Wwise metadata is present, and there are multiple content banks in the target directory with wem files + present, there is no way to tell which bank requires which wem files. A warning should be emitted, + stating that the full dependency graph could not be created, and only dependencies on the init bank are + described in the generated metadata files. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_NoMetadataMultipleBanks_OneDependency_ReturnCodeIsWarning') bank_info = get_bank_info(workspace) @@ -150,8 +204,17 @@ class TestSoundBankMetadataGenerator: success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace), expected_result_code=1) def test_OneContentBank_NoStreamedFiles_OneDependency(self, workspace, soundbank_metadata_generator_setup_fixture): - # Wwise metadata describes one content bank that contains all media needed by its events. Generated metadata - # describes a dependency only on the init bank. + """ + Wwise metadata describes one content bank that contains all media needed by its events. Generated metadata + describes a dependency only on the init bank. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_OneContentBank_NoStreamedFiles_OneDependency') @@ -165,8 +228,17 @@ class TestSoundBankMetadataGenerator: success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace)) def test_OneContentBank_StreamedFiles_MultipleDependencies(self, workspace, soundbank_metadata_generator_setup_fixture): - # Wwise metadata describes one content bank that references streamed media files needed by its events. Generated - # metadata describes dependencies on the init bank and wems named by the IDs of referenced streamed media. + """ + Wwise metadata describes one content bank that references streamed media files needed by its events. Generated + metadata describes dependencies on the init bank and wems named by the IDs of referenced streamed media. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_OneContentBank_StreamedFiles_MultipleDependencies') @@ -187,8 +259,17 @@ class TestSoundBankMetadataGenerator: success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace)) def test_MultipleContentBanks_NoStreamedFiles_OneDependency(self, workspace, soundbank_metadata_generator_setup_fixture): - # Wwise metadata describes multiple content banks. Each bank contains all media needed by its events. Generated - # metadata describes each bank having a dependency only on the init bank. + """ + Wwise metadata describes multiple content banks. Each bank contains all media needed by its events. Generated + metadata describes each bank having a dependency only on the init bank. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_MultipleContentBanks_NoStreamedFiles_OneDependency') @@ -206,8 +287,17 @@ class TestSoundBankMetadataGenerator: success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace)) def test_MultipleContentBanks_Bank1StreamedFiles(self, workspace, soundbank_metadata_generator_setup_fixture): - # Wwise metadata describes multiple content banks. Bank 1 references streamed media files needed by its events, - # while bank 2 contains all media need by its events. + """ + Wwise metadata describes multiple content banks. Bank 1 references streamed media files needed by its events, + while bank 2 contains all media need by its events. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_MultipleContentBanks_Bank1StreamedFiles') @@ -228,9 +318,18 @@ class TestSoundBankMetadataGenerator: success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace)) def test_MultipleContentBanks_SplitBanks_OnlyBankDependenices(self, workspace, soundbank_metadata_generator_setup_fixture): - # Wwise metadata describes multiple content banks. Bank 3 events require media that is contained in bank 4. - # Generated metadata describes each bank having a dependency on the init bank, while bank 3 has an additional - # dependency on bank 4. + """ + Wwise metadata describes multiple content banks. Bank 3 events require media that is contained in bank 4. + Generated metadata describes each bank having a dependency on the init bank, while bank 3 has an additional + dependency on bank 4. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_MultipleContentBanks_SplitBanks_OnlyBankDependenices') @@ -248,9 +347,18 @@ class TestSoundBankMetadataGenerator: success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace)) def test_MultipleContentBanks_ReferencedEvent_MediaEmbeddedInBank(self, workspace, soundbank_metadata_generator_setup_fixture): - # Wwise metadata describes multiple content banks. Bank 1 contains all media required by its events, while bank - # 5 contains a reference to an event in bank 1, but no media for that event. Generated metadata describes both - # banks having a dependency on the init bank, while bank 5 has an additional dependency on bank 1. + """ + Wwise metadata describes multiple content banks. Bank 1 contains all media required by its events, while bank + 5 contains a reference to an event in bank 1, but no media for that event. Generated metadata describes both + banks having a dependency on the init bank, while bank 5 has an additional dependency on bank 1. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_MultipleContentBanks_ReferencedEvent_MediaEmbeddedInBank') @@ -271,10 +379,19 @@ class TestSoundBankMetadataGenerator: success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace)) def test_MultipleContentBanks_ReferencedEvent_MediaStreamed(self, workspace, soundbank_metadata_generator_setup_fixture): - # Wwise metadata describes multiple content banks. Bank 1 references streamed media files needed by its events, - # while bank 5 contains a reference to an event in bank 1. This causes bank 5 to also describe a reference to - # the streamed media file referenced by the event from bank 1. Generated metadata describes both banks having - # dependencies on the init bank, as well as the wem named by the ID of referenced streamed media. + """ + Wwise metadata describes multiple content banks. Bank 1 references streamed media files needed by its events, + while bank 5 contains a reference to an event in bank 1. This causes bank 5 to also describe a reference to + the streamed media file referenced by the event from bank 1. Generated metadata describes both banks having + dependencies on the init bank, as well as the wem named by the ID of referenced streamed media. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_MultipleContentBanks_ReferencedEvent_MediaStreamed') @@ -298,11 +415,20 @@ class TestSoundBankMetadataGenerator: success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace)) def test_MultipleContentBanks_ReferencedEvent_MixedSources(self, workspace, soundbank_metadata_generator_setup_fixture): - # Wwise metadata describes multiple content banks. Bank 1 references a streamed media files needed by one of its - # events, and contains all media needed for its other events, while bank 5 contains a reference to two events - # in bank 1: one that requires streamed media, and one that requires media embedded in bank 1. Generated - # metadata describes both banks having dependencies on the init bank and the wem named by the ID of referenced - # streamed media, while bank 5 has an additional dependency on bank 1. + """ + Wwise metadata describes multiple content banks. Bank 1 references a streamed media files needed by one of its + events, and contains all media needed for its other events, while bank 5 contains a reference to two events + in bank 1: one that requires streamed media, and one that requires media embedded in bank 1. Generated + metadata describes both banks having dependencies on the init bank and the wem named by the ID of referenced + streamed media, while bank 5 has an additional dependency on bank 1. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_MultipleContentBanks_ReferencedEvent_MixedSources') @@ -332,8 +458,17 @@ class TestSoundBankMetadataGenerator: success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace)) def test_MultipleContentBanks_VaryingDependencies_MixedSources(self, workspace, soundbank_metadata_generator_setup_fixture): - # Wwise metadata describes multiple content banks that have varying dependencies on each other, and dependencies - # on streamed media files. + """ + Wwise metadata describes multiple content banks that have varying dependencies on each other, and dependencies + on streamed media files. + + Test Steps: + 1. Setup testing environment + 2. Get current bank info + 3. Build expected dependencies + 4. Call success case test + """ + test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets', 'test_MultipleContentBanks_VaryingDependencies_MixedSources') From e8e9096dda7ea79d6275f26db4eb0dbf8eb82932 Mon Sep 17 00:00:00 2001 From: srikappa Date: Tue, 1 Jun 2021 11:11:13 -0700 Subject: [PATCH 367/811] Changed a function name and removed a comment --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 9 +++------ .../AzToolsFramework/Prefab/PrefabPublicHandler.h | 2 +- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index fdc4302c1b..3187b55721 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -189,7 +189,7 @@ namespace AzToolsFramework if (nestedInstanceLinkPatchesMap.contains(nestedInstance.get())) { previousPatch = AZStd::move(nestedInstanceLinkPatchesMap[nestedInstance.get()]); - UpdateLinkPatchForNewParent(previousPatch, oldEntityAliases, instanceToCreate->get()); + UpdateLinkPatchesWithNewEntityAliases(previousPatch, oldEntityAliases, instanceToCreate->get()); } // These link creations shouldn't be undone because that would put the template in a non-usable state if a user @@ -366,9 +366,6 @@ namespace AzToolsFramework CreateLink(instanceToCreate->get(), instanceToParentUnder->get().GetTemplateId(), undoBatch.GetUndoBatch(), AZStd::move(patch)); - // Update the cache - this prevents these changes from being stored in the regular undo/redo nodes - //m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter)); - AzToolsFramework::ToolsApplicationRequestBus::Broadcast( &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); } @@ -1076,7 +1073,7 @@ namespace AzToolsFramework RemoveLink(nestedInstancePtr, instanceTemplateId, undoBatch.GetUndoBatch()); - UpdateLinkPatchForNewParent(linkPatchesCopy, oldEntityAliases, parentInstance); + UpdateLinkPatchesWithNewEntityAliases(linkPatchesCopy, oldEntityAliases, parentInstance); CreateLink(*nestedInstancePtr, parentTemplateId, undoBatch.GetUndoBatch(), AZStd::move(linkPatchesCopy), true); @@ -1354,7 +1351,7 @@ namespace AzToolsFramework stringToReplace.replace(oldAliasPathRef, newAliasPathRef); } - void PrefabPublicHandler::UpdateLinkPatchForNewParent( + void PrefabPublicHandler::UpdateLinkPatchesWithNewEntityAliases( PrefabDom& linkPatch, const AZStd::unordered_map& oldEntityAliases, Instance& newParent) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index c339c17a48..acaf9b5753 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -134,7 +134,7 @@ namespace AzToolsFramework bool IsCyclicalDependencyFound( InstanceOptionalConstReference instance, const AZStd::unordered_set& templateSourcePaths); - static void UpdateLinkPatchForNewParent( + void UpdateLinkPatchesWithNewEntityAliases( PrefabDom& linkPatch, const AZStd::unordered_map& oldEntityAliases, Instance& newParent); From 7ee55cce3a858ca5dae0fd1acfb130f9a468cd75 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Tue, 1 Jun 2021 11:19:03 -0700 Subject: [PATCH 368/811] Post merge fixes for spawning entities --- .../ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index 21d1fc5264..ad53236108 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -105,7 +105,7 @@ namespace ScriptCanvas::Nodeables::Spawning return; } - auto preSpawnCB = [this, translation, rotation, scale]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, + auto preSpawnCB = [this, translation, rotation, scale]([[maybe_unused]] AzFramework::EntitySpawnTicket::Id ticketId, AzFramework::SpawnableEntityContainerView view) { AZ::Entity* rootEntity = *view.begin(); @@ -122,7 +122,7 @@ namespace ScriptCanvas::Nodeables::Spawning } }; - auto spawnCompleteCB = [this]([[maybe_unused]] AzFramework::EntitySpawnTicket& ticket, + auto spawnCompleteCB = [this]([[maybe_unused]] AzFramework::EntitySpawnTicket::Id ticketId, AzFramework::SpawnableConstEntityContainerView view) { AZStd::lock_guard lock(m_idBatchMutex); @@ -134,6 +134,7 @@ namespace ScriptCanvas::Nodeables::Spawning m_spawnBatchSizes.push_back(view.size()); }; - AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_spawnTicket, preSpawnCB, spawnCompleteCB); + AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities( + m_spawnTicket, AzFramework::SpawnablePriority_Default, preSpawnCB, spawnCompleteCB); } } From 50277cc17838eb832e6392491a11acab34380ae0 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 1 Jun 2021 11:31:21 -0700 Subject: [PATCH 369/811] LYN-4132 Disable SIMD exceptions in profile (#1052) * Fix old method call * Disable SIMD exceptions in profile --- Code/CryEngine/CrySystem/SystemInit.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 79041fa233..52744519bb 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -2017,8 +2017,8 @@ void CSystem::CreateSystemVars() REGISTER_CVAR2("sys_streaming_in_blocks", &g_cvars.sys_streaming_in_blocks, 1, VF_NULL, "Streaming of large files happens in blocks"); -#if (defined(WIN32) || defined(WIN64)) && !defined(_RELEASE) - REGISTER_CVAR2("sys_float_exceptions", &g_cvars.sys_float_exceptions, 3, 0, "Use or not use floating point exceptions."); +#if (defined(WIN32) || defined(WIN64)) && defined(_DEBUG) + REGISTER_CVAR2("sys_float_exceptions", &g_cvars.sys_float_exceptions, 2, 0, "Use or not use floating point exceptions."); #else // Float exceptions by default disabled for console builds. REGISTER_CVAR2("sys_float_exceptions", &g_cvars.sys_float_exceptions, 0, 0, "Use or not use floating point exceptions."); #endif From a9a42a540550507258b77b5fed933bf73a267734 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Tue, 1 Jun 2021 12:17:48 -0700 Subject: [PATCH 370/811] Added AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED --- Gems/Atom/RPI/Code/CMakeLists.txt | 17 ++++++++-- .../Code/Include/Atom/RPI.Public/Culling.h | 1 - .../RPI/Code/Include/Atom/RPI.Public/View.h | 3 +- .../Android/Atom_RPI_Traits_Android.h | 14 +++++++++ .../Android/Atom_RPI_Traits_Platform.h | 14 +++++++++ .../Android/platform_android_files.cmake | 15 +++++++++ .../Platform/Linux/Atom_RPI_Traits_Linux.h | 14 +++++++++ .../Platform/Linux/Atom_RPI_Traits_Platform.h | 14 +++++++++ .../Platform/Linux/platform_linux_files.cmake | 15 +++++++++ .../Source/Platform/Mac/Atom_RPI_Traits_Mac.h | 14 +++++++++ .../Platform/Mac/Atom_RPI_Traits_Platform.h | 14 +++++++++ .../Platform/Mac/platform_mac_files.cmake | 15 +++++++++ .../Windows/Atom_RPI_Traits_Platform.h | 14 +++++++++ .../Windows/Atom_RPI_Traits_Windows.h | 14 +++++++++ .../Source/Platform/Windows/PAL_windows.cmake | 7 +++-- .../Windows/platform_windows_files.cmake | 15 +++++++++ .../Platform/iOS/Atom_RPI_Traits_Platform.h | 14 +++++++++ .../Source/Platform/iOS/Atom_RPI_Traits_iOS.h | 14 +++++++++ .../Platform/iOS/platform_ios_files.cmake | 15 +++++++++ .../RPI/Code/Source/RPI.Public/Culling.cpp | 31 +++++++++++++++---- Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp | 13 ++++++-- .../atom_rpi_masked_occlusion_files.cmake | 18 +++++++++++ .../Atom/RPI/Code/atom_rpi_public_files.cmake | 6 +--- 23 files changed, 291 insertions(+), 20 deletions(-) create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Android.h create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Platform.h create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Android/platform_android_files.cmake create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Linux.h create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Platform.h create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Linux/platform_linux_files.cmake create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Mac.h create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Platform.h create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Mac/platform_mac_files.cmake create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Windows/Atom_RPI_Traits_Platform.h create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Windows/Atom_RPI_Traits_Windows.h create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Windows/platform_windows_files.cmake create mode 100644 Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_Platform.h create mode 100644 Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_iOS.h create mode 100644 Gems/Atom/RPI/Code/Source/Platform/iOS/platform_ios_files.cmake create mode 100644 Gems/Atom/RPI/Code/atom_rpi_masked_occlusion_files.cmake diff --git a/Gems/Atom/RPI/Code/CMakeLists.txt b/Gems/Atom/RPI/Code/CMakeLists.txt index d2b7fba071..2898967add 100644 --- a/Gems/Atom/RPI/Code/CMakeLists.txt +++ b/Gems/Atom/RPI/Code/CMakeLists.txt @@ -9,6 +9,17 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +ly_get_list_relative_pal_filename(pal_source_dir ${CMAKE_CURRENT_LIST_DIR}/Source/Platform/${PAL_PLATFORM_NAME}) + +#for PAL_TRAIT_BUILD_ATOM_RPI_ASSETS_SUPPORTED and PAL_TRAIT_BUILD_ATOM_RPI_MASKED_OCCLUSION_CULLING_SUPPORTED +include(${pal_source_dir}/PAL_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) + +if(PAL_TRAIT_BUILD_ATOM_RPI_MASKED_OCCLUSION_CULLING_SUPPORTED) + set(MASKED_OCCLUSION_CULLING_FILES "atom_rpi_masked_occlusion_files.cmake") +else() + set(MASKED_OCCLUSION_CULLING_FILES "") +endif() + ly_add_target( NAME Atom_RPI.Public STATIC NAMESPACE Gem @@ -16,11 +27,15 @@ ly_add_target( atom_rpi_reflect_files.cmake atom_rpi_public_files.cmake ../Assets/atom_rpi_asset_files.cmake + ${pal_source_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake + ${MASKED_OCCLUSION_CULLING_FILES} INCLUDE_DIRECTORIES PRIVATE Source + ${pal_source_dir} PUBLIC Include + External BUILD_DEPENDENCIES PRIVATE AZ::AtomCore @@ -159,8 +174,6 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) ly_get_list_relative_pal_filename(pal_source_dir ${CMAKE_CURRENT_LIST_DIR}/Source/Platform/${PAL_PLATFORM_NAME}) ly_get_list_relative_pal_filename(common_source_dir ${CMAKE_CURRENT_LIST_DIR}/Source/Platform/Common) - include(${pal_source_dir}/PAL_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) #for PAL_TRAIT_BUILD_ATOM_RPI_ASSETS_SUPPORTED - if(NOT PAL_TRAIT_BUILD_ATOM_RPI_ASSETS_SUPPORTED) # Create a stub diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h index 8892266683..3f03fb9dcb 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h @@ -31,7 +31,6 @@ #include #include -#include #include #include diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h index 0b6b41c8b0..7d192ea62a 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h @@ -18,13 +18,14 @@ #include #include #include -#include #include #include #include #include +class MaskedOcclusionCulling; + namespace AZ { namespace RHI diff --git a/Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Android.h b/Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Android.h new file mode 100644 index 0000000000..e1c8d827bf --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Android.h @@ -0,0 +1,14 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#define AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED 0 diff --git a/Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Platform.h b/Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Platform.h new file mode 100644 index 0000000000..27e0af7f35 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Platform.h @@ -0,0 +1,14 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include "Atom_Feature_Traits_Android.h" diff --git a/Gems/Atom/RPI/Code/Source/Platform/Android/platform_android_files.cmake b/Gems/Atom/RPI/Code/Source/Platform/Android/platform_android_files.cmake new file mode 100644 index 0000000000..357d8f0381 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Android/platform_android_files.cmake @@ -0,0 +1,15 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(FILES + Atom_Feature_Traits_Platform.h + Atom_Feature_Traits_Android.h +) diff --git a/Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Linux.h b/Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Linux.h new file mode 100644 index 0000000000..e1c8d827bf --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Linux.h @@ -0,0 +1,14 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#define AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED 0 diff --git a/Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Platform.h b/Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Platform.h new file mode 100644 index 0000000000..39c6a3e572 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Platform.h @@ -0,0 +1,14 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include "Atom_Feature_Traits_Linux.h" diff --git a/Gems/Atom/RPI/Code/Source/Platform/Linux/platform_linux_files.cmake b/Gems/Atom/RPI/Code/Source/Platform/Linux/platform_linux_files.cmake new file mode 100644 index 0000000000..19be7951f6 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Linux/platform_linux_files.cmake @@ -0,0 +1,15 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(FILES + Atom_Feature_Traits_Platform.h + Atom_Feature_Traits_Linux.h +) diff --git a/Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Mac.h b/Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Mac.h new file mode 100644 index 0000000000..e1c8d827bf --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Mac.h @@ -0,0 +1,14 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#define AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED 0 diff --git a/Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Platform.h b/Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Platform.h new file mode 100644 index 0000000000..19816f2bd1 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Platform.h @@ -0,0 +1,14 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include "Atom_Feature_Traits_Mac.h" diff --git a/Gems/Atom/RPI/Code/Source/Platform/Mac/platform_mac_files.cmake b/Gems/Atom/RPI/Code/Source/Platform/Mac/platform_mac_files.cmake new file mode 100644 index 0000000000..bde67ff340 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Mac/platform_mac_files.cmake @@ -0,0 +1,15 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(FILES + Atom_Feature_Traits_Platform.h + Atom_Feature_Traits_Mac.h +) diff --git a/Gems/Atom/RPI/Code/Source/Platform/Windows/Atom_RPI_Traits_Platform.h b/Gems/Atom/RPI/Code/Source/Platform/Windows/Atom_RPI_Traits_Platform.h new file mode 100644 index 0000000000..dc655ed3a9 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Windows/Atom_RPI_Traits_Platform.h @@ -0,0 +1,14 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include "Atom_RPI_Traits_Windows.h" diff --git a/Gems/Atom/RPI/Code/Source/Platform/Windows/Atom_RPI_Traits_Windows.h b/Gems/Atom/RPI/Code/Source/Platform/Windows/Atom_RPI_Traits_Windows.h new file mode 100644 index 0000000000..0deebe4706 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Windows/Atom_RPI_Traits_Windows.h @@ -0,0 +1,14 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#define AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED 1 diff --git a/Gems/Atom/RPI/Code/Source/Platform/Windows/PAL_windows.cmake b/Gems/Atom/RPI/Code/Source/Platform/Windows/PAL_windows.cmake index 51e42d5216..b989233ccd 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Windows/PAL_windows.cmake +++ b/Gems/Atom/RPI/Code/Source/Platform/Windows/PAL_windows.cmake @@ -10,16 +10,17 @@ # set (PAL_TRAIT_BUILD_ATOM_RPI_ASSETS_SUPPORTED TRUE) +set (PAL_TRAIT_BUILD_ATOM_RPI_MASKED_OCCLUSION_CULLING_SUPPORTED TRUE) ly_add_source_properties( - SOURCES Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX2.cpp + SOURCES External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX2.cpp PROPERTY COMPILE_OPTIONS VALUES /arch:AVX2 /W3 ) ly_add_source_properties( SOURCES - Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX512.cpp - Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCulling.cpp + External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX512.cpp + External/MaskedOcclusionCulling/MaskedOcclusionCulling.cpp PROPERTY COMPILE_OPTIONS VALUES /W3 ) \ No newline at end of file diff --git a/Gems/Atom/RPI/Code/Source/Platform/Windows/platform_windows_files.cmake b/Gems/Atom/RPI/Code/Source/Platform/Windows/platform_windows_files.cmake new file mode 100644 index 0000000000..e49944d8ef --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Windows/platform_windows_files.cmake @@ -0,0 +1,15 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(FILES + Atom_RPI_Traits_Platform.h + Atom_RPI_Traits_Windows.h +) diff --git a/Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_Platform.h b/Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_Platform.h new file mode 100644 index 0000000000..4403d741dc --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_Platform.h @@ -0,0 +1,14 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include "Atom_Feature_Traits_iOS.h" diff --git a/Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_iOS.h b/Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_iOS.h new file mode 100644 index 0000000000..e1c8d827bf --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_iOS.h @@ -0,0 +1,14 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#define AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED 0 diff --git a/Gems/Atom/RPI/Code/Source/Platform/iOS/platform_ios_files.cmake b/Gems/Atom/RPI/Code/Source/Platform/iOS/platform_ios_files.cmake new file mode 100644 index 0000000000..7f603e4bfd --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/iOS/platform_ios_files.cmake @@ -0,0 +1,15 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(FILES + Atom_Feature_Traits_Platform.h + Atom_Feature_Traits_iOS.h +) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index d8ed850309..79d152f661 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -20,15 +20,20 @@ #include +#include #include #include - #include #include #include #include #include #include +#include + +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED +#include +#endif //Enables more inner-loop profiling scopes (can create high overhead in RadTelemetry if there are many-many objects in a scene) //#define AZ_CULL_PROFILE_DETAILED @@ -265,10 +270,12 @@ namespace AZ struct JobData { CullingDebugContext* m_debugCtx = nullptr; - MaskedOcclusionCulling* m_maskedOcclusionCulling = nullptr; const Scene* m_scene = nullptr; View* m_view = nullptr; Frustum m_frustum; +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED + MaskedOcclusionCulling* m_maskedOcclusionCulling = nullptr; +#endif }; private: @@ -308,7 +315,9 @@ namespace AZ //Add all objects within this node to the view, without any extra culling for (AzFramework::VisibilityEntry* visibleEntry : nodeData.m_entries) { +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED if (TestOcclusionCulling(visibleEntry) == MaskedOcclusionCulling::CullingResult::VISIBLE) +#endif { if (visibleEntry->m_typeFlags & AzFramework::VisibilityEntry::TYPE_RPI_Cullable) { @@ -347,7 +356,9 @@ namespace AZ } else if (res == IntersectResult::Interior || ShapeIntersection::Overlaps(m_jobData->m_frustum, c->m_cullData.m_boundingObb)) { +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED if (TestOcclusionCulling(visibleEntry) == MaskedOcclusionCulling::CullingResult::VISIBLE) +#endif { numDrawPackets += AddLodDataToView(c->m_cullData.m_boundingSphere.GetCenter(), c->m_lodData, *m_jobData->m_view); ++numVisibleCullables; @@ -421,6 +432,7 @@ namespace AZ } } +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED MaskedOcclusionCulling::CullingResult TestOcclusionCulling(AzFramework::VisibilityEntry* visibleEntry) { if (!m_jobData->m_maskedOcclusionCulling) @@ -471,10 +483,11 @@ namespace AZ { return MaskedOcclusionCulling::VISIBLE; } - + // test against the occlusion buffer, which contains only the manually placed occlusion planes return m_jobData->m_maskedOcclusionCulling->TestRect(ndcMinX, ndcMinY, ndcMaxX, ndcMaxY, minDepth); } +#endif }; void CullingScene::ProcessCullables(const Scene& scene, View& view, AZ::Job& parentJob) @@ -508,6 +521,7 @@ namespace AZ cullStats.m_cameraViewToWorld = view.GetViewToWorldMatrix(); } +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED // setup occlusion culling, if necessary MaskedOcclusionCulling* maskedOcclusionCulling = m_occlusionCullingPlanes.empty() ? nullptr : view.GetMaskedOcclusionCulling(); if (maskedOcclusionCulling) @@ -577,15 +591,19 @@ namespace AZ maskedOcclusionCulling->RenderTriangles((float*)verts, indices, 2, nullptr, MaskedOcclusionCulling::BACKFACE_NONE); } } +#endif WorkListType worklist; AZStd::shared_ptr jobData = AZStd::make_shared(); jobData->m_debugCtx = &m_debugCtx; - jobData->m_maskedOcclusionCulling = maskedOcclusionCulling; jobData->m_scene = &scene; jobData->m_view = &view; jobData->m_frustum = frustum; +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED + jobData->m_maskedOcclusionCulling = maskedOcclusionCulling; +#endif + auto nodeVisitorLambda = [this, jobData, &parentJob, &frustum, &worklist](const AzFramework::IVisibilityScene::NodeData& nodeData) -> void { @@ -620,11 +638,12 @@ namespace AZ { AZStd::shared_ptr remainingJobData = AZStd::make_shared(); remainingJobData->m_debugCtx = &m_debugCtx; - remainingJobData->m_maskedOcclusionCulling = maskedOcclusionCulling; remainingJobData->m_scene = &scene; remainingJobData->m_view = &view; remainingJobData->m_frustum = frustum; - +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED + remainingJobData->m_maskedOcclusionCulling = maskedOcclusionCulling; +#endif //Kick off a job to process any remaining workitems AddObjectsToViewJob* job = aznew AddObjectsToViewJob(remainingJobData, worklist); //pool allocated (cheap), auto-deletes when job finishes parentJob.SetContinuation(job); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index 6e4dec112f..bd0e15fb2e 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -23,6 +23,11 @@ #include #include #include +#include + +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED +#include +#endif namespace AZ { @@ -56,18 +61,21 @@ namespace AZ { m_shaderResourceGroup = ShaderResourceGroup::Create(viewSrgAsset); } - +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED m_maskedOcclusionCulling = MaskedOcclusionCulling::Create(); m_maskedOcclusionCulling->SetResolution(MaskedSoftwareOcclusionCullingWidth, MaskedSoftwareOcclusionCullingHeight); +#endif } View::~View() { +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED if (m_maskedOcclusionCulling) { MaskedOcclusionCulling::Destroy(m_maskedOcclusionCulling); m_maskedOcclusionCulling = nullptr; } +#endif } void View::SetDrawListMask(const RHI::DrawListMask& drawListMask) @@ -394,13 +402,14 @@ namespace AZ void View::BeginCulling() { +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED m_maskedOcclusionCulling->ClearBuffer(); +#endif } MaskedOcclusionCulling* View::GetMaskedOcclusionCulling() { return m_maskedOcclusionCulling; } - } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/atom_rpi_masked_occlusion_files.cmake b/Gems/Atom/RPI/Code/atom_rpi_masked_occlusion_files.cmake new file mode 100644 index 0000000000..5828848c81 --- /dev/null +++ b/Gems/Atom/RPI/Code/atom_rpi_masked_occlusion_files.cmake @@ -0,0 +1,18 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(FILES + External/MaskedOcclusionCulling/MaskedOcclusionCulling.h + External/MaskedOcclusionCulling/MaskedOcclusionCullingCommon.inl + External/MaskedOcclusionCulling/MaskedOcclusionCulling.cpp + External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX2.cpp + External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX512.cpp +) \ No newline at end of file diff --git a/Gems/Atom/RPI/Code/atom_rpi_public_files.cmake b/Gems/Atom/RPI/Code/atom_rpi_public_files.cmake index 35003d268a..a1d98bbd38 100644 --- a/Gems/Atom/RPI/Code/atom_rpi_public_files.cmake +++ b/Gems/Atom/RPI/Code/atom_rpi_public_files.cmake @@ -102,7 +102,6 @@ set(FILES Include/Atom/RPI.Public/GpuQuery/Query.h Include/Atom/RPI.Public/GpuQuery/QueryPool.h Include/Atom/RPI.Public/GpuQuery/TimestampQueryPool.h - Include/Atom/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCulling.h Source/RPI.Public/Culling.cpp Source/RPI.Public/FeatureProcessor.cpp Source/RPI.Public/FeatureProcessorFactory.cpp @@ -181,7 +180,4 @@ set(FILES Source/RPI.Public/GpuQuery/Query.cpp Source/RPI.Public/GpuQuery/QueryPool.cpp Source/RPI.Public/GpuQuery/TimestampQueryPool.cpp - Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCulling.cpp - Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX2.cpp - Source/RPI.Public/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX512.cpp -) +) \ No newline at end of file From 087677b3266d48270c0419bd19352cfc2bf8d3e1 Mon Sep 17 00:00:00 2001 From: Nicholas Van Sickle Date: Tue, 1 Jun 2021 12:20:15 -0700 Subject: [PATCH 371/811] Fix several viewport issues (#1045) * Fix some FOV calculation viewport issues: -Avoid calculating FOV if we've got an invalid viewport -Don't override game mode FOV, let the active camera components manage it instead * Fix viewport font positioning This updates code in a few places to respect an API change/fix made to AtomFont - also switched the default value of m_virtual800x600ScreenSize to false as it's really behavior you want to opt into * Don't activate CameraComponentController when in the Editor / not in game mode --- .../AzFramework/Font/FontInterface.h | 2 +- Code/Sandbox/Editor/EditorViewportWidget.cpp | 34 ++++++++++++------- .../AtomDebugDisplayViewportInterface.cpp | 4 +-- ...AtomViewportDisplayInfoSystemComponent.cpp | 2 +- .../Code/Source/CameraComponentController.cpp | 4 ++- .../Code/Source/EditorCameraComponent.cpp | 11 ------ 6 files changed, 28 insertions(+), 29 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h b/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h index 04a0572bb9..dae5fa9fe7 100644 --- a/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h @@ -54,7 +54,7 @@ namespace AzFramework AZ::Matrix3x4 m_transform = AZ::Matrix3x4::Identity(); //!< Transform to apply to text quads bool m_monospace = false; //!< disable character proportional spacing bool m_depthTest = false; //!< Test character against the depth buffer - bool m_virtual800x600ScreenSize = true; //!< Text placement and size are scaled relative to a virtual 800x600 resolution + bool m_virtual800x600ScreenSize = false; //!< Text placement and size are scaled relative to a virtual 800x600 resolution bool m_scaleWithWindow = false; //!< Font gets bigger as the window gets bigger bool m_multiline = true; //!< text respects ascii newline characters }; diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 989d6e407d..24d1590808 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -463,16 +463,20 @@ void EditorViewportWidget::Update() m_renderViewport->GetViewportContext()->SetCameraTransform(LYTransformToAZTransform(m_Camera.GetMatrix())); } - AZ::Matrix4x4 clipMatrix; - AZ::MakePerspectiveFovMatrixRH( - clipMatrix, - m_Camera.GetFov(), - aznumeric_cast(width()) / aznumeric_cast(height()), - m_Camera.GetNearPlane(), - m_Camera.GetFarPlane(), - true - ); - m_renderViewport->GetViewportContext()->SetCameraProjectionMatrix(clipMatrix); + // Don't override the game mode FOV + if (!GetIEditor()->IsInGameMode()) + { + 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); + } m_updatingCameraPosition = false; @@ -870,6 +874,13 @@ void EditorViewportWidget::OnBeginPrepareRender() 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 @@ -1782,9 +1793,6 @@ void EditorViewportWidget::SetViewTM(const Matrix34& viewTM, bool bMoveOnly) cameraObject->SetWorldTM(camMatrix * AZMatrix3x3ToLYMatrix3x3(lookThroughEntityCorrection)); } } - - using namespace AzToolsFramework; - ComponentEntityObjectRequestBus::Event(cameraObject, &ComponentEntityObjectRequestBus::Events::UpdatePreemptiveUndoCache); } else if (m_viewEntityId.IsValid()) { diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp index 6c68618f78..620d5d1fb8 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp @@ -1328,7 +1328,7 @@ namespace AZ::AtomBridge params.m_hAlign = center ? AzFramework::TextHorizontalAlignment::Center : AzFramework::TextHorizontalAlignment::Left; //! Horizontal text alignment params.m_monospace = false; //! disable character proportional spacing params.m_depthTest = false; //! Test character against the depth buffer - params.m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution + params.m_virtual800x600ScreenSize = false; //! Text placement and size are scaled in viewport pixel coordinates params.m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger params.m_multiline = true; //! text respects ascii newline characters @@ -1364,7 +1364,7 @@ namespace AZ::AtomBridge params.m_hAlign = center ? AzFramework::TextHorizontalAlignment::Center : AzFramework::TextHorizontalAlignment::Left; //! Horizontal text alignment params.m_monospace = false; //! disable character proportional spacing params.m_depthTest = false; //! Test character against the depth buffer - params.m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution + params.m_virtual800x600ScreenSize = false; //! Text placement and size are scaled in viewport pixel coordinates params.m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger params.m_multiline = true; //! text respects ascii newline characters diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp index 146c0c67d0..d47ce44ab2 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp @@ -162,7 +162,7 @@ namespace AZ::Render m_drawParams.m_hAlign = AzFramework::TextHorizontalAlignment::Right; m_drawParams.m_monospace = false; m_drawParams.m_depthTest = false; - m_drawParams.m_virtual800x600ScreenSize = true; + m_drawParams.m_virtual800x600ScreenSize = false; m_drawParams.m_scaleWithWindow = false; m_drawParams.m_multiline = true; m_drawParams.m_lineSpacing = 0.5f; diff --git a/Gems/Camera/Code/Source/CameraComponentController.cpp b/Gems/Camera/Code/Source/CameraComponentController.cpp index 3dcee68169..d0a124067b 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.cpp +++ b/Gems/Camera/Code/Source/CameraComponentController.cpp @@ -240,7 +240,9 @@ namespace Camera CameraBus::Handler::BusConnect(); CameraNotificationBus::Broadcast(&CameraNotificationBus::Events::OnCameraAdded, m_entityId); - if (m_config.m_makeActiveViewOnActivation) + // Activate our camera if we're running from the launcher or Editor game mode + // Otherwise, let the Editor keep managing the active camera + if (m_config.m_makeActiveViewOnActivation && (!gEnv || !gEnv->IsEditor() || gEnv->IsEditorGameMode())) { MakeActiveView(); } diff --git a/Gems/Camera/Code/Source/EditorCameraComponent.cpp b/Gems/Camera/Code/Source/EditorCameraComponent.cpp index 359fa936bc..80057e7a77 100644 --- a/Gems/Camera/Code/Source/EditorCameraComponent.cpp +++ b/Gems/Camera/Code/Source/EditorCameraComponent.cpp @@ -34,20 +34,9 @@ namespace Camera auto controllerConfig = m_controller.GetConfiguration(); controllerConfig.m_editorEntityId = GetEntityId().operator AZ::u64(); - // The Editor manages active camera state, so while we're in Editor we explicitly - // disable the request to make this the active view at edit component activation time. - bool prevShouldActivateViewOnActivation = controllerConfig.m_makeActiveViewOnActivation; - controllerConfig.m_makeActiveViewOnActivation = false; - - m_controller.SetConfiguration(controllerConfig); - // Call base class activate, which in turn calls Activate on our controller. EditorCameraComponentBase::Activate(); - // Reset the original `m_makeActiveViewOnActivation' setting, so that the intended value is serialized, used in BuildGameEntity, etc. - controllerConfig.m_makeActiveViewOnActivation = prevShouldActivateViewOnActivation; - m_controller.SetConfiguration(controllerConfig); - AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(GetEntityId()); EditorCameraNotificationBus::Handler::BusConnect(); EditorCameraViewRequestBus::Handler::BusConnect(GetEntityId()); From 940439d247ee7a46cf6f7a4591ce5a3857e1c2e7 Mon Sep 17 00:00:00 2001 From: Terry Michaels Date: Tue, 1 Jun 2021 14:25:38 -0500 Subject: [PATCH 372/811] Resaved Simple Level to remove deleted components (#1066) --- AutomatedTesting/Levels/Simple/Simple.ly | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AutomatedTesting/Levels/Simple/Simple.ly b/AutomatedTesting/Levels/Simple/Simple.ly index 0148ee6e34..0a063bf8f8 100644 --- a/AutomatedTesting/Levels/Simple/Simple.ly +++ b/AutomatedTesting/Levels/Simple/Simple.ly @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:804193a2afd68cd1e6bec8155ea11400566f2941fbd6eb0c324839ebcd10192d -size 8492 +oid sha256:302d6172156e8ed665e44e206d81f54f1b0f1008d73327300ea92f8c1159780b +size 11820 From 4070a9ec303573915b2b98af0dea3e0665946970 Mon Sep 17 00:00:00 2001 From: Junbo Liang <68558268+junbo75@users.noreply.github.com> Date: Tue, 1 Jun 2021 13:57:55 -0700 Subject: [PATCH 373/811] [LYN-2243] Create end-to-end automation tests for the metrics gem (#23) [LYN-2243] Create end-to-end automation tests for the metrics gem --- .../AWS/Windows/aws_metrics/__init__.py | 10 + .../aws_metrics_automation_test.py | 237 ++++++++++++++++ .../Windows/aws_metrics/aws_metrics_utils.py | 252 ++++++++++++++++++ .../aws_metrics/aws_metrics_waiters.py | 142 ++++++++++ .../Gem/PythonTests/AWS/Windows/cdk/cdk.py | 57 +++- .../PythonTests/AWS/common/aws_credentials.py | 134 ++++++++++ .../Gem/PythonTests/AWS/common/aws_utils.py | 172 ++++++------ .../PythonTests/AWS/common/custom_waiter.py | 91 +++++++ .../Registry/awscoreconfiguration.setreg | 2 +- .../cdk/aws_metrics/batch_processing.py | 5 +- .../cdk/aws_metrics/data_ingestion.py | 4 +- 11 files changed, 1017 insertions(+), 89 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/__init__.py create mode 100644 AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py create mode 100644 AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py create mode 100644 AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py create mode 100644 AutomatedTesting/Gem/PythonTests/AWS/common/aws_credentials.py create mode 100644 AutomatedTesting/Gem/PythonTests/AWS/common/custom_waiter.py diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/__init__.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/__init__.py new file mode 100644 index 0000000000..cdee4b5a56 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/__init__.py @@ -0,0 +1,10 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py new file mode 100644 index 0000000000..04be31759d --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py @@ -0,0 +1,237 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +import logging +import os +import pytest +import time +import typing + +from datetime import datetime +import ly_test_tools.log.log_monitor + +from assetpipeline.ap_fixtures.asset_processor_fixture import asset_processor as asset_processor +from AWS.common.aws_utils import aws_utils +from AWS.common.aws_credentials import aws_credentials +from AWS.Windows.resource_mappings.resource_mappings import resource_mappings +from AWS.Windows.cdk.cdk import cdk +from .aws_metrics_utils import aws_metrics_utils + +AWS_METRICS_FEATURE_NAME = 'AWSMetrics' +GAME_LOG_NAME = 'Game.log' + +logger = logging.getLogger(__name__) + + +def setup(launcher: ly_test_tools.launchers.Launcher, + cdk: cdk, + asset_processor: asset_processor, + resource_mappings: resource_mappings, + context_variable: str = '') -> typing.Tuple[ly_test_tools.log.log_monitor.LogMonitor, str, str]: + """ + Set up the CDK application and start the log monitor. + :param launcher: Client launcher for running the test level. + :param cdk: CDK application for deploying the AWS resources. + :param asset_processor: asset_processor fixture. + :param resource_mappings: resource_mappings fixture. + :param context_variable: context_variable for enable optional CDK feature. + :return log monitor object, metrics file path and the metrics stack name. + """ + logger.info(f'Cdk stack names:\n{cdk.list()}') + stacks = cdk.deploy(context_variable=context_variable) + resource_mappings.populate_output_keys(stacks) + + asset_processor.start() + asset_processor.wait_for_idle() + + metrics_file_path = os.path.join(launcher.workspace.paths.project(), 'user', + AWS_METRICS_FEATURE_NAME, 'metrics.json') + remove_file(metrics_file_path) + + file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), GAME_LOG_NAME) + remove_file(file_to_monitor) + + # Initialize the log monitor. + log_monitor = ly_test_tools.log.log_monitor.LogMonitor(launcher=launcher, log_file_path=file_to_monitor) + + return log_monitor, metrics_file_path, stacks[0] + + +def monitor_metrics_submission(log_monitor: ly_test_tools.log.log_monitor.LogMonitor) -> None: + """ + Monitor the messages and notifications for submitting metrics. + :param log_monitor: Log monitor to check the log messages. + """ + expected_lines = [ + '(Script) - Submitted metrics without buffer.', + '(Script) - Submitted metrics with buffer.', + '(Script) - Metrics is sent successfully.' + ] + + unexpected_lines = [ + '(Script) - Failed to submit metrics without buffer.', + '(Script) - Failed to submit metrics with buffer.', + '(Script) - Failed to send metrics.' + ] + + result = log_monitor.monitor_log_for_lines( + expected_lines=expected_lines, + unexpected_lines=unexpected_lines, + halt_on_unexpected=True) + + # Assert the log monitor detected expected lines and did not detect any unexpected lines. + assert result, ( + f'Log monitoring failed. Used expected_lines values: {expected_lines} & ' + f'unexpected_lines values: {unexpected_lines}') + + +def remove_file(file_path: str) -> None: + """ + Remove a local file and its directory. + :param file_path: Path to the local file. + """ + if os.path.exists(file_path): + os.remove(file_path) + + file_dir = os.path.dirname(file_path) + if os.path.exists(file_dir) and len(os.listdir(file_dir)) == 0: + os.rmdir(file_dir) + + +@pytest.mark.SUITE_periodic +@pytest.mark.usefixtures('automatic_process_killer') +@pytest.mark.parametrize('project', ['AutomatedTesting']) +@pytest.mark.parametrize('level', ['AWS/Metrics']) +@pytest.mark.parametrize('feature_name', [AWS_METRICS_FEATURE_NAME]) +@pytest.mark.parametrize('resource_mappings_filename', ['aws_resource_mappings.json']) +@pytest.mark.parametrize('profile_name', ['AWSAutomationTest']) +@pytest.mark.parametrize('region_name', ['us-west-2']) +@pytest.mark.parametrize('assume_role_arn', ['arn:aws:iam::645075835648:role/o3de-automation-tests']) +@pytest.mark.parametrize('session_name', ['o3de-Automation-session']) +class TestAWSMetrics_Windows(object): + def test_AWSMetrics_RealTimeAnalytics_MetricsSentToCloudWatch(self, + level: str, + launcher: ly_test_tools.launchers.Launcher, + asset_processor: pytest.fixture, + workspace: pytest.fixture, + aws_utils: aws_utils, + aws_credentials: aws_credentials, + resource_mappings: resource_mappings, + cdk: cdk, + aws_metrics_utils: aws_metrics_utils, + ): + """ + Tests that the submitted metrics are sent to CloudWatch for real-time analytics. + """ + log_monitor, metrics_file_path, stack_name = setup(launcher, cdk, asset_processor, resource_mappings) + + # Start the Kinesis Data Analytics application for real-time analytics. + analytics_application_name = f'{stack_name}-AnalyticsApplication' + aws_metrics_utils.start_kinesis_data_analytics_application(analytics_application_name) + + launcher.args = ['+LoadLevel', level] + launcher.args.extend(['-rhi=null']) + + with launcher.start(launch_ap=False): + start_time = datetime.utcnow() + monitor_metrics_submission(log_monitor) + # Verify that operational health metrics are delivered to CloudWatch. + aws_metrics_utils.verify_cloud_watch_delivery( + 'AWS/Lambda', + 'Invocations', + [{'Name': 'FunctionName', + 'Value': f'{stack_name}-AnalyticsProcessingLambda'}], + start_time) + logger.info('Operational health metrics sent to CloudWatch.') + + aws_metrics_utils.verify_cloud_watch_delivery( + AWS_METRICS_FEATURE_NAME, + 'TotalLogins', + [], + start_time) + logger.info('Real-time metrics sent to CloudWatch.') + + # Stop the Kinesis Data Analytics application. + aws_metrics_utils.stop_kinesis_data_analytics_application(analytics_application_name) + + def test_AWSMetrics_UnauthorizedUser_RequestRejected(self, + level: str, + launcher: ly_test_tools.launchers.Launcher, + cdk: cdk, + aws_credentials: aws_credentials, + asset_processor: pytest.fixture, + resource_mappings: resource_mappings, + workspace: pytest.fixture): + """ + Tests that unauthorized users cannot send metrics events to the AWS backed backend. + """ + log_monitor, metrics_file_path, stack_name = setup(launcher, cdk, asset_processor, resource_mappings) + # Set invalid AWS credentials. + launcher.args = ['+LoadLevel', level, '+cl_awsAccessKey', 'AKIAIOSFODNN7EXAMPLE', + '+cl_awsSecretKey', 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'] + launcher.args.extend(['-rhi=null']) + + with launcher.start(launch_ap=False): + result = log_monitor.monitor_log_for_lines( + expected_lines=['(Script) - Failed to send metrics.'], + unexpected_lines=['(Script) - Metrics is sent successfully.'], + halt_on_unexpected=True) + assert result, 'Metrics events are sent successfully by unauthorized user' + logger.info('Unauthorized user is rejected to send metrics.') + + def test_AWSMetrics_BatchAnalytics_MetricsDeliveredToS3(self, + level: str, + launcher: ly_test_tools.launchers.Launcher, + cdk: cdk, + aws_credentials: aws_credentials, + asset_processor: pytest.fixture, + resource_mappings: resource_mappings, + aws_utils: aws_utils, + aws_metrics_utils: aws_metrics_utils, + workspace: pytest.fixture): + """ + Tests that the submitted metrics are sent to the data lake for batch analytics. + """ + log_monitor, metrics_file_path, stack_name = setup(launcher, cdk, asset_processor, resource_mappings, + context_variable='batch_processing=true') + + analytics_bucket_name = aws_metrics_utils.get_analytics_bucket_name(stack_name) + + launcher.args = ['+LoadLevel', level] + launcher.args.extend(['-rhi=null']) + + with launcher.start(launch_ap=False): + start_time = datetime.utcnow() + monitor_metrics_submission(log_monitor) + # Verify that operational health metrics are delivered to CloudWatch. + aws_metrics_utils.verify_cloud_watch_delivery( + 'AWS/Lambda', + 'Invocations', + [{'Name': 'FunctionName', + 'Value': f'{stack_name}-EventsProcessingLambda'}], + start_time) + logger.info('Operational health metrics sent to CloudWatch.') + + aws_metrics_utils.verify_s3_delivery(analytics_bucket_name) + logger.info('Metrics sent to S3.') + + # Run the glue crawler to populate the AWS Glue Data Catalog with tables. + aws_metrics_utils.run_glue_crawler(f'{stack_name}-EventsCrawler') + # Run named queries on the table to verify the batch analytics. + aws_metrics_utils.run_named_queries(f'{stack_name}-AthenaWorkGroup') + logger.info('Query metrics from S3 successfully.') + + # Kinesis Data Firehose buffers incoming data before it delivers it to Amazon S3. Sleep for the + # default interval (60s) to make sure that all the metrics are sent to the bucket before cleanup. + time.sleep(60) + # Empty the S3 bucket. S3 buckets can only be deleted successfully when it doesn't contain any object. + aws_metrics_utils.empty_s3_bucket(analytics_bucket_name) + diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py new file mode 100644 index 0000000000..686feda3d9 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py @@ -0,0 +1,252 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +import logging +import pathlib +import pytest +import typing + +from datetime import datetime +from botocore.exceptions import WaiterError + +from AWS.common.aws_utils import AwsUtils +from .aws_metrics_waiters import KinesisAnalyticsApplicationUpdatedWaiter, \ + CloudWatchMetricsDeliveredWaiter, DataLakeMetricsDeliveredWaiter, GlueCrawlerReadyWaiter + +logging.getLogger('boto').setLevel(logging.CRITICAL) + +# Expected directory and file extension for the S3 objects. +EXPECTED_S3_DIRECTORY = 'firehose_events/' +EXPECTED_S3_OBJECT_EXTENSION = '.parquet' + + +class AWSMetricsUtils: + """ + Provide utils functions for the AWSMetrics gem to interact with the deployed resources. + """ + + def __init__(self, aws_utils: AwsUtils): + self._aws_util = aws_utils + + def start_kinesis_data_analytics_application(self, application_name: str) -> None: + """ + Start the Kenisis Data Analytics application for real-time analytics. + :param application_name: Name of the Kenisis Data Analytics application. + """ + input_id = self.get_kinesis_analytics_application_input_id(application_name) + assert input_id, 'invalid Kinesis Data Analytics application input.' + + client = self._aws_util.client('kinesisanalytics') + try: + client.start_application( + ApplicationName=application_name, + InputConfigurations=[ + { + 'Id': input_id, + 'InputStartingPositionConfiguration': { + 'InputStartingPosition': 'NOW' + } + }, + ] + ) + except client.exceptions.ResourceInUseException: + # The application has been started. + return + + try: + KinesisAnalyticsApplicationUpdatedWaiter(client, 'RUNNING').wait(application_name=application_name) + except WaiterError as e: + assert False, f'Failed to start the Kinesis Data Analytics application: {str(e)}.' + + def get_kinesis_analytics_application_input_id(self, application_name: str) -> str: + """ + Get the input ID for the Kenisis Data Analytics application. + :param application_name: Name of the Kenisis Data Analytics application. + :return: Input ID for the Kenisis Data Analytics application. + """ + client = self._aws_util.client('kinesisanalytics') + response = client.describe_application( + ApplicationName=application_name + ) + if not response: + return '' + input_descriptions = response.get('ApplicationDetail', {}).get('InputDescriptions', []) + if len(input_descriptions) != 1: + return '' + + return input_descriptions[0].get('InputId', '') + + def stop_kinesis_data_analytics_application(self, application_name: str) -> None: + """ + Stop the Kenisis Data Analytics application. + :param application_name: Name of the Kenisis Data Analytics application. + """ + client = self._aws_util.client('kinesisanalytics') + client.stop_application( + ApplicationName=application_name + ) + + try: + KinesisAnalyticsApplicationUpdatedWaiter(client, 'READY').wait(application_name=application_name) + except WaiterError as e: + assert False, f'Failed to stop the Kinesis Data Analytics application: {str(e)}.' + + def verify_cloud_watch_delivery(self, namespace: str, metrics_name: str, + dimensions: typing.List[dict], start_time: datetime) -> None: + """ + Verify that the expected metrics is delivered to CloudWatch. + :param namespace: Namespace of the metrics. + :param metrics_name: Name of the metrics. + :param dimensions: Dimensions of the metrics. + :param start_time: Start time for generating the metrics. + """ + client = self._aws_util.client('cloudwatch') + + try: + CloudWatchMetricsDeliveredWaiter(client).wait( + namespace=namespace, + metrics_name=metrics_name, + dimensions=dimensions, + start_time=start_time + ) + except WaiterError as e: + assert False, f'Failed to deliver metrics to CloudWatch: {str(e)}.' + + def verify_s3_delivery(self, analytics_bucket_name: str) -> None: + """ + Verify that metrics are delivered to S3 for batch analytics successfully. + :param analytics_bucket_name: Name of the deployed S3 bucket. + """ + client = self._aws_util.client('s3') + bucket_name = analytics_bucket_name + + try: + DataLakeMetricsDeliveredWaiter(client).wait(bucket_name=bucket_name, prefix=EXPECTED_S3_DIRECTORY) + except WaiterError as e: + assert False, f'Failed to find the S3 directory for storing metrics data: {str(e)}.' + + # Check whether the data is converted to the expected data format. + response = client.list_objects_v2( + Bucket=bucket_name, + Prefix=EXPECTED_S3_DIRECTORY + ) + assert response.get('KeyCount', 0) != 0, f'Failed to deliver metrics to the S3 bucket {bucket_name}.' + + s3_objects = response.get('Contents', []) + for s3_object in s3_objects: + key = s3_object.get('Key', '') + assert pathlib.Path(key).suffix == EXPECTED_S3_OBJECT_EXTENSION, \ + f'Invalid data format is found in the S3 bucket {bucket_name}' + + def run_glue_crawler(self, crawler_name: str) -> None: + """ + Run the Glue crawler and wait for it to finish. + :param crawler_name: Name of the Glue crawler + """ + client = self._aws_util.client('glue') + try: + client.start_crawler( + Name=crawler_name + ) + except client.exceptions.CrawlerRunningException: + # The crawler has already been started. + return + + try: + GlueCrawlerReadyWaiter(client).wait(crawler_name=crawler_name) + except WaiterError as e: + assert False, f'Failed to run the Glue crawler: {str(e)}.' + + def run_named_queries(self, work_group: str) -> None: + """ + Run the named queries under the specific Athena work group. + :param work_group: Name of the Athena work group. + """ + client = self._aws_util.client('athena') + # List all the named queries. + response = client.list_named_queries( + WorkGroup=work_group + ) + named_query_ids = response.get('NamedQueryIds', []) + + # Run each of the queries. + for named_query_id in named_query_ids: + get_named_query_response = client.get_named_query( + NamedQueryId=named_query_id + ) + named_query = get_named_query_response.get('NamedQuery', {}) + + start_query_execution_response = client.start_query_execution( + QueryString=named_query.get('QueryString', ''), + QueryExecutionContext={ + 'Database': named_query.get('Database', '') + }, + WorkGroup=work_group + ) + + # Wait for the query to finish. + state = 'RUNNING' + while state == 'QUEUED' or state == 'RUNNING': + get_query_execution_response = client.get_query_execution( + QueryExecutionId=start_query_execution_response.get('QueryExecutionId', '') + ) + + state = get_query_execution_response.get('QueryExecution', {}).get('Status', {}).get('State', '') + + assert state == 'SUCCEEDED', f'Failed to run the named query {named_query.get("Name", {})}' + + def empty_s3_bucket(self, bucket_name: str) -> None: + """ + Empty the S3 bucket following: + https://boto3.amazonaws.com/v1/documentation/api/latest/guide/migrations3.html + + :param bucket_name: Name of the S3 bucket. + """ + + s3 = self._aws_util.resource('s3') + bucket = s3.Bucket(bucket_name) + + for key in bucket.objects.all(): + key.delete() + + def get_analytics_bucket_name(self, stack_name: str) -> str: + """ + Get the name of the deployed S3 bucket. + :param stack_name: Name of the CloudFormation stack. + :return: Name of the deployed S3 bucket. + """ + + client = self._aws_util.client('cloudformation') + + response = client.describe_stack_resources( + StackName=stack_name + ) + resources = response.get('StackResources', []) + + for resource in resources: + if resource.get('ResourceType') == 'AWS::S3::Bucket': + return resource.get('PhysicalResourceId', '') + + return '' + + +@pytest.fixture(scope='function') +def aws_metrics_utils( + request: pytest.fixture, + aws_utils: pytest.fixture): + """ + Fixture for the AWS metrics util functions. + :param request: _pytest.fixtures.SubRequest class that handles getting + a pytest fixture from a pytest function/fixture. + :param aws_utils: aws_utils fixture. + """ + aws_utils_obj = AWSMetricsUtils(aws_utils) + return aws_utils_obj diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py new file mode 100644 index 0000000000..7ce5551fd4 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py @@ -0,0 +1,142 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +import botocore.client +import logging + +from datetime import timedelta +from AWS.common.custom_waiter import CustomWaiter, WaitState + +logging.getLogger('boto').setLevel(logging.CRITICAL) + + +class KinesisAnalyticsApplicationUpdatedWaiter(CustomWaiter): + """ + Subclass of the base custom waiter class. + Wait for the Kinesis analytics application being updated to a specific status. + """ + def __init__(self, client: botocore.client, status: str): + """ + Initialize the waiter. + + :param client: Boto3 client to use. + :param status: Expected status. + """ + super().__init__( + 'KinesisAnalyticsApplicationUpdated', + 'DescribeApplication', + 'ApplicationDetail.ApplicationStatus', + {status: WaitState.SUCCESS}, + client) + + def wait(self, application_name: str): + """ + Wait for the expected status. + + :param application_name: Name of the Kinesis analytics application. + """ + self._wait(ApplicationName=application_name) + + +class GlueCrawlerReadyWaiter(CustomWaiter): + """ + Subclass of the base custom waiter class. + Wait for the Glue crawler to finish its processing. + """ + def __init__(self, client: botocore.client): + """ + Initialize the waiter. + + :param client: Boto3 client to use. + """ + super().__init__( + 'GlueCrawlerReady', + 'GetCrawler', + 'Crawler.State', + {'READY': WaitState.SUCCESS}, + client) + + def wait(self, crawler_name): + """ + Wait for the expected status. + + :param crawler_name: Name of the Glue crawler. + """ + self._wait(Name=crawler_name) + + +class DataLakeMetricsDeliveredWaiter(CustomWaiter): + """ + Subclass of the base custom waiter class. + Wait for the expected directory being created in the S3 bucket. + """ + def __init__(self, client: botocore.client): + """ + Initialize the waiter. + + :param client: Boto3 client to use. + """ + super().__init__( + 'DataLakeMetricsDelivered', + 'ListObjectsV2', + 'KeyCount > `0`', + {True: WaitState.SUCCESS}, + client) + + def wait(self, bucket_name, prefix): + """ + Wait for the expected directory being created. + + :param bucket_name: Name of the S3 bucket. + :param prefix: Name of the expected directory prefix. + """ + self._wait(Bucket=bucket_name, Prefix=prefix) + + +class CloudWatchMetricsDeliveredWaiter(CustomWaiter): + """ + Subclass of the base custom waiter class. + Wait for the expected metrics being delivered to CloudWatch. + """ + def __init__(self, client: botocore.client): + """ + Initialize the waiter. + + :param client: Boto3 client to use. + """ + super().__init__( + 'CloudWatchMetricsDelivered', + 'GetMetricStatistics', + 'length(Datapoints) > `0`', + {True: WaitState.SUCCESS}, + client) + + def wait(self, namespace, metrics_name, dimensions, start_time): + """ + Wait for the expected metrics being delivered. + + :param namespace: Namespace of the metrics. + :param metrics_name: Name of the metrics. + :param dimensions: Dimensions of the metrics. + :param start_time: Start time for generating the metrics. + """ + self._wait( + Namespace=namespace, + MetricName=metrics_name, + Dimensions=dimensions, + StartTime=start_time, + EndTime=start_time + timedelta(0, self.timeout), + Period=60, + Statistics=[ + 'SampleCount' + ], + Unit='Count' + ) diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py index 455b3f94cb..5dbde29b9d 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk.py @@ -16,12 +16,15 @@ import boto3 import ly_test_tools.environment.process_utils as process_utils from typing import List +BOOTSTRAP_STACK_NAME = 'CDKToolkit' +BOOTSTRAP_STAGING_BUCKET_LOGIC_ID = 'StagingBucket' class Cdk: """ Cdk class that provides methods to run cdk application commands. Expects system to have NodeJS, AWS CLI and CDK installed globally and have their paths setup as env variables. """ + def __init__(self, cdk_path: str, project: str, account_id: str, workspace: pytest.fixture, session: boto3.session.Session): """ @@ -49,12 +52,24 @@ class Cdk: env=self._cdk_env, shell=True) + def bootstrap(self) -> None: + """ + Deploy the bootstrap stack. + """ + bootstrap_cmd = ['cdk', 'bootstrap', + f'aws://{self._cdk_env["O3DE_AWS_DEPLOY_ACCOUNT"]}/{self._cdk_env["O3DE_AWS_DEPLOY_REGION"]}'] + + process_utils.check_call( + bootstrap_cmd, + cwd=self._cdk_path, + env=self._cdk_env, + shell=True) + def list(self) -> List[str]: """ lists cdk stack names :return List of cdk stack names """ - if not self._cdk_path: return [] @@ -123,6 +138,38 @@ class Cdk: self._stacks = [] self._cdk_path = '' + @staticmethod + def remove_bootstrap_stack(aws_utils: pytest.fixture) -> None: + """ + Remove the CDK bootstrap stack. + :param aws_utils: aws_utils fixture. + """ + # Check if the bootstrap stack exists. + response = aws_utils.client('cloudformation').describe_stacks( + StackName=BOOTSTRAP_STACK_NAME + ) + stacks = response.get('Stacks', []) + if not stacks: + return + + # Clear the bootstrap staging bucket before deleting the bootstrap stack. + response = aws_utils.client('cloudformation').describe_stack_resource( + StackName=BOOTSTRAP_STACK_NAME, + LogicalResourceId=BOOTSTRAP_STAGING_BUCKET_LOGIC_ID + ) + + staging_bucket_name = response.get('StackResourceDetail', {}).get('PhysicalResourceId', '') + if staging_bucket_name: + s3 = aws_utils.resource('s3') + bucket = s3.Bucket(staging_bucket_name) + for key in bucket.objects.all(): + key.delete() + + # Delete the bootstrap stack. + aws_utils.client('cloudformation').delete_stack( + StackName=BOOTSTRAP_STACK_NAME + ) + @pytest.fixture(scope='function') def cdk( @@ -131,6 +178,7 @@ def cdk( feature_name: str, workspace: pytest.fixture, aws_utils: pytest.fixture, + bootstrap_required: bool = True, destroy_stacks_on_teardown: bool = True) -> Cdk: """ Fixture for setting up a Cdk @@ -140,6 +188,8 @@ def cdk( :param feature_name: Feature gem name to expect cdk folder in. :param workspace: ly_test_tools workspace fixture. :param aws_utils: aws_utils fixture. + :param bootstrap_required: Whether the bootstrap stack needs to be created to + provision resources the AWS CDK needs to perform the deployment. :param destroy_stacks_on_teardown: option to control calling destroy ot the end of test. :return Cdk class object. """ @@ -147,9 +197,14 @@ def cdk( cdk_path = f'{workspace.paths.engine_root()}/Gems/{feature_name}/cdk' cdk_obj = Cdk(cdk_path, project, aws_utils.assume_account_id(), workspace, aws_utils.assume_session()) + if bootstrap_required: + cdk_obj.bootstrap() + def teardown(): if destroy_stacks_on_teardown: cdk_obj.destroy() + cdk_obj.remove_bootstrap_stack(aws_utils) + request.addfinalizer(teardown) return cdk_obj diff --git a/AutomatedTesting/Gem/PythonTests/AWS/common/aws_credentials.py b/AutomatedTesting/Gem/PythonTests/AWS/common/aws_credentials.py new file mode 100644 index 0000000000..fbce772d40 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/AWS/common/aws_credentials.py @@ -0,0 +1,134 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +import boto3 +import configparser +import logging +import os +import pytest +import typing + +logger = logging.getLogger(__name__) +logging.getLogger('boto').setLevel(logging.CRITICAL) + + +class AwsCredentials: + def __init__(self, profile_name: str): + self._profile_name = profile_name + + self._credentials_path = os.environ.get('AWS_SHARED_CREDENTIALS_FILE') + if not self._credentials_path: + # Home directory location varies based on the operating system, but is referred to using the environment + # variables %UserProfile% in Windows and $HOME or ~ (tilde) in Unix-based systems. + self._credentials_path = os.path.join(os.environ.get('UserProfile', os.path.expanduser('~')), + '.aws', 'credentials') + self._credentials_file_exists = os.path.exists(self._credentials_path) + + self._credentials = configparser.ConfigParser() + self._credentials.read(self._credentials_path) + + def get_aws_credentials(self) -> typing.Tuple[str, str, str]: + """ + Get aws credentials stored in the specific named profile. + + :return AWS credentials. + """ + access_key_id = self._get_aws_credential_attribute_value('aws_access_key_id') + secret_access_key = self._get_aws_credential_attribute_value('aws_secret_access_key') + session_token = self._get_aws_credential_attribute_value('aws_session_token') + + return access_key_id, secret_access_key, session_token + + def set_aws_credentials_by_session(self, session: boto3.Session) -> None: + """ + Set AWS credentials stored in the specific named profile using an assumed role session. + + :param session: assumed role session. + """ + credentials = session.get_credentials().get_frozen_credentials() + self.set_aws_credentials(credentials.access_key, credentials.secret_key, credentials.token) + + def set_aws_credentials(self, aws_access_key_id: str, aws_secret_access_key: str, + aws_session_token: str) -> None: + """ + Set AWS credentials stored in the specific named profile. + + :param aws_access_key_id: AWS access key id. + :param aws_secret_access_key: AWS secrete access key. + :param aws_session_token: AWS assumed role session. + """ + self._set_aws_credential_attribute_value('aws_access_key_id', aws_access_key_id) + self._set_aws_credential_attribute_value('aws_secret_access_key', aws_secret_access_key) + self._set_aws_credential_attribute_value('aws_session_token', aws_session_token) + + if (len(self._credentials.sections()) == 0) and (not self._credentials_file_exists): + os.remove(self._credentials_path) + return + + with open(self._credentials_path, 'w+') as credential_file: + self._credentials.write(credential_file) + + def _get_aws_credential_attribute_value(self, attribute_name: str) -> str: + """ + Get the value of an AWS credential attribute stored in the specific named profile. + + :param attribute_name: Name of the AWS credential attribute. + :return Value of the AWS credential attribute. + """ + try: + value = self._credentials.get(self._profile_name, attribute_name) + except configparser.NoSectionError: + # Named profile or key doesn't exist + value = None + except configparser.NoOptionError: + # Named profile doesn't have the specified attribute + value = None + + return value + + def _set_aws_credential_attribute_value(self, attribute_name: str, attribute_value: str) -> None: + """ + Set the value of an AWS credential attribute stored in the specific named profile. + + :param attribute_name: Name of the AWS credential attribute. + :param attribute_value: Value of the AWS credential attribute. + """ + if self._profile_name not in self._credentials: + self._credentials[self._profile_name] = {} + + if attribute_value is None: + self._credentials.remove_option(self._profile_name, attribute_name) + # Remove the named profile if it doesn't have any AWS credential attribute. + if len(self._credentials[self._profile_name]) == 0: + self._credentials.remove_section(self._profile_name) + else: + self._credentials[self._profile_name][attribute_name] = attribute_value + + +@pytest.fixture(scope='function') +def aws_credentials(request: pytest.fixture, aws_utils: pytest.fixture, profile_name: str): + """ + Fixture for setting up temporary AWS credentials from assume role. + + :param request: _pytest.fixtures.SubRequest class that handles getting + a pytest fixture from a pytest function/fixture. + :param aws_utils: aws_utils fixture. + :param profile_name: Named AWS profile to store temporary credentials. + """ + aws_credentials_obj = AwsCredentials(profile_name) + original_access_key, original_secret_access_key, original_token = aws_credentials_obj.get_aws_credentials() + aws_credentials_obj.set_aws_credentials_by_session(aws_utils.assume_session()) + + def teardown(): + # Reset to the named profile using the original AWS credentials + aws_credentials_obj.set_aws_credentials(original_access_key, original_secret_access_key, original_token) + request.addfinalizer(teardown) + + return aws_credentials_obj diff --git a/AutomatedTesting/Gem/PythonTests/AWS/common/aws_utils.py b/AutomatedTesting/Gem/PythonTests/AWS/common/aws_utils.py index 7a15ba0abe..ff33f58d1d 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/common/aws_utils.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/common/aws_utils.py @@ -1,82 +1,90 @@ -""" -All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -its licensors. -For complete copyright and license terms please see the LICENSE at the root of this -distribution (the "License"). All use of this software is governed by the License, -or, if provided, by the license below or the license accompanying this file. Do not -remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -""" -import boto3 -import pytest -import logging - -logger = logging.getLogger(__name__) - - -class AwsUtils: - - def __init__(self, arn: str, session_name: str, region_name: str): - local_session = boto3.Session(profile_name='default') - local_sts_client = local_session.client('sts') - self._local_account_id = local_sts_client.get_caller_identity()["Account"] - logger.info(f'Local Account Id: {self._local_account_id}') - - response = local_sts_client.assume_role(RoleArn=arn, RoleSessionName=session_name) - - self._assume_session = boto3.Session(aws_access_key_id=response['Credentials']['AccessKeyId'], - aws_secret_access_key=response['Credentials']['SecretAccessKey'], - aws_session_token=response['Credentials']['SessionToken'], - region_name=region_name) - - assume_sts_client = self._assume_session.client('sts') - assume_account_id = assume_sts_client.get_caller_identity()["Account"] - logger.info(f'Assume Account Id: {assume_account_id}') - self._assume_account_id = assume_account_id - - def client(self, service: str): - """ - Get the client for a specific AWS service from configured session - :return: Client for the AWS service. - """ - return self._assume_session.client(service) - - def assume_session(self): - return self._assume_session - - def local_account_id(self): - return self._local_account_id - - def assume_account_id(self): - return self._assume_account_id - - def destroy(self) -> None: - """ - clears stored session - """ - self._assume_session = None - - -@pytest.fixture(scope='function') -def aws_utils( - request: pytest.fixture, - assume_role_arn: str, - session_name: str, - region_name: str): - """ - Fixture for setting up a Cdk - :param request: _pytest.fixtures.SubRequest class that handles getting - a pytest fixture from a pytest function/fixture. - :param assume_role_arn: Role used to fetch temporary aws credentials, configure service clients with obtained credentials. - :param session_name: Session name to set. - :param region_name: AWS account region to set for session. - :return AWSUtils class object. - """ - aws_utils_obj = AwsUtils(assume_role_arn, session_name, region_name) - - def teardown(): - aws_utils_obj.destroy() - - request.addfinalizer(teardown) - - return aws_utils_obj +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" +import boto3 +import pytest +import logging + +logger = logging.getLogger(__name__) +logging.getLogger('boto').setLevel(logging.CRITICAL) + + +class AwsUtils: + + def __init__(self, arn: str, session_name: str, region_name: str): + local_session = boto3.Session(profile_name='default') + local_sts_client = local_session.client('sts') + self._local_account_id = local_sts_client.get_caller_identity()["Account"] + logger.info(f'Local Account Id: {self._local_account_id}') + + response = local_sts_client.assume_role(RoleArn=arn, RoleSessionName=session_name) + + self._assume_session = boto3.Session(aws_access_key_id=response['Credentials']['AccessKeyId'], + aws_secret_access_key=response['Credentials']['SecretAccessKey'], + aws_session_token=response['Credentials']['SessionToken'], + region_name=region_name) + + assume_sts_client = self._assume_session.client('sts') + assume_account_id = assume_sts_client.get_caller_identity()["Account"] + logger.info(f'Assume Account Id: {assume_account_id}') + self._assume_account_id = assume_account_id + + def client(self, service: str): + """ + Get the client for a specific AWS service from configured session + :return: Client for the AWS service. + """ + return self._assume_session.client(service) + + def resource(self, service: str): + """ + Get the resource for a specific AWS service from configured session + :return: Client for the AWS service. + """ + return self._assume_session.resource(service) + + def assume_session(self): + return self._assume_session + + def local_account_id(self): + return self._local_account_id + + def assume_account_id(self): + return self._assume_account_id + + def destroy(self) -> None: + """ + clears stored session + """ + self._assume_session = None + + +@pytest.fixture(scope='function') +def aws_utils( + request: pytest.fixture, + assume_role_arn: str, + session_name: str, + region_name: str): + """ + Fixture for AWS util functions + :param request: _pytest.fixtures.SubRequest class that handles getting + a pytest fixture from a pytest function/fixture. + :param assume_role_arn: Role used to fetch temporary aws credentials, configure service clients with obtained credentials. + :param session_name: Session name to set. + :param region_name: AWS account region to set for session. + :return AWSUtils class object. + """ + aws_utils_obj = AwsUtils(assume_role_arn, session_name, region_name) + + def teardown(): + aws_utils_obj.destroy() + + request.addfinalizer(teardown) + + return aws_utils_obj diff --git a/AutomatedTesting/Gem/PythonTests/AWS/common/custom_waiter.py b/AutomatedTesting/Gem/PythonTests/AWS/common/custom_waiter.py new file mode 100644 index 0000000000..7c0a65e8a3 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/AWS/common/custom_waiter.py @@ -0,0 +1,91 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +from enum import Enum +import botocore.client +import botocore.waiter +import logging + +logging.getLogger('boto').setLevel(logging.CRITICAL) + + +class WaitState(Enum): + SUCCESS = 'success' + FAILURE = 'failure' + + +class CustomWaiter: + """ + Base class for a custom waiter. + + Modified from: + https://docs.aws.amazon.com/code-samples/latest/catalog/python-demo_tools-custom_waiter.py.html + """ + def __init__( + self, name: str, operation: str, argument: str, + acceptors: dict, client: botocore.client, delay: int = 30, max_tries: int = 10, + matcher='path'): + """ + Subclasses should pass specific operations, arguments, and acceptors to + their superclass. + + :param name: The name of the waiter. This can be any descriptive string. + :param operation: The operation to wait for. This must match the casing of + the underlying operation model, which is typically in + CamelCase. + :param argument: The dict keys used to access the result of the operation, in + dot notation. For example, 'Job.Status' will access + result['Job']['Status']. + :param acceptors: The list of acceptors that indicate the wait is over. These + can indicate either success or failure. The acceptor values + are compared to the result of the operation after the + argument keys are applied. + :param client: The Boto3 client. + :param delay: The number of seconds to wait between each call to the operation. Default to 30 seconds. + :param max_tries: The maximum number of tries before exiting. Default to 10. + :param matcher: The kind of matcher to use. Default to 'path'. + """ + self.name = name + self.operation = operation + self.argument = argument + self.client = client + self.waiter_model = botocore.waiter.WaiterModel({ + 'version': 2, + 'waiters': { + name: { + "delay": delay, + "operation": operation, + "maxAttempts": max_tries, + "acceptors": [{ + "state": state.value, + "matcher": matcher, + "argument": argument, + "expected": expected + } for expected, state in acceptors.items()] + }}}) + self.waiter = botocore.waiter.create_waiter_with_client( + self.name, self.waiter_model, self.client) + + self._timeout = delay * max_tries + + def _wait(self, **kwargs): + """ + Starts the botocore wait loop. + + :param kwargs: Keyword arguments that are passed to the operation being polled. + """ + self.waiter.wait(**kwargs) + + @property + def timeout(self): + return self._timeout + + diff --git a/AutomatedTesting/Registry/awscoreconfiguration.setreg b/AutomatedTesting/Registry/awscoreconfiguration.setreg index ca110eb103..b7c60b0fb9 100644 --- a/AutomatedTesting/Registry/awscoreconfiguration.setreg +++ b/AutomatedTesting/Registry/awscoreconfiguration.setreg @@ -3,7 +3,7 @@ { "AWSCore": { - "ProfileName": "default", + "ProfileName": "AWSAutomationTest", "ResourceMappingConfigFileName": "aws_resource_mappings.json" } } diff --git a/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py b/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py index fe85615d8d..22f6ad6903 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py @@ -111,8 +111,7 @@ class BatchProcessing: self._events_firehose_delivery_stream = kinesisfirehose.CfnDeliveryStream( self._stack, - id='EventsFirehoseDeliveryStream', - delivery_stream_name=f'{self._stack.stack_name}-EventsFirehoseDeliveryStream', + id=f'{self._stack.stack_name}-EventsFirehoseDeliveryStream', delivery_stream_type='KinesisStreamAsSource', kinesis_stream_source_configuration=kinesisfirehose.CfnDeliveryStream.KinesisStreamSourceConfigurationProperty( kinesis_stream_arn=self._input_stream_arn, @@ -327,7 +326,7 @@ class BatchProcessing: @property def delivery_stream_name(self) -> kinesisfirehose.CfnDeliveryStream.delivery_stream_name: - return self._events_firehose_delivery_stream.delivery_stream_name + return self._events_firehose_delivery_stream.ref @property def delivery_stream_role_arn(self) -> iam.Role.role_arn: diff --git a/Gems/AWSMetrics/cdk/aws_metrics/data_ingestion.py b/Gems/AWSMetrics/cdk/aws_metrics/data_ingestion.py index a3ab99fccf..fbd332a577 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/data_ingestion.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/data_ingestion.py @@ -73,14 +73,14 @@ class DataIngestion: api_id_output = core.CfnOutput( self._stack, - id='RestApiId', + id='RESTApiId', description='Service API Id for the analytics pipeline', export_name=f"{application_name}:RestApiId", value=self._rest_api.rest_api_id) stage_output = core.CfnOutput( self._stack, - id='DeploymentStage', + id='RESTApiStage', description='Stage for the REST API deployment', export_name=f"{application_name}:DeploymentStage", value=self._rest_api.deployment_stage.stage_name) From 9e3b7b45d95e6a8fe4af6340569f1d7f356674c4 Mon Sep 17 00:00:00 2001 From: hershey5045 <43485729+hershey5045@users.noreply.github.com> Date: Tue, 1 Jun 2021 14:21:02 -0700 Subject: [PATCH 374/811] Fix window handle retrieval in frame capture system. (#1073) Capturing screenshots via hydra should work now. --- .../Common/Code/Source/FrameCaptureSystemComponent.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/FrameCaptureSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/FrameCaptureSystemComponent.cpp index f8c1258fc0..0d9e46a418 100644 --- a/Gems/Atom/Feature/Common/Code/Source/FrameCaptureSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/FrameCaptureSystemComponent.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -289,11 +290,7 @@ namespace AZ bool FrameCaptureSystemComponent::CaptureScreenshot(const AZStd::string& filePath) { - AzFramework::NativeWindowHandle windowHandle = nullptr; - AzFramework::WindowSystemRequestBus::BroadcastResult( - windowHandle, - &AzFramework::WindowSystemRequestBus::Events::GetDefaultWindowHandle); - + AzFramework::NativeWindowHandle windowHandle = AZ::RPI::ViewportContextRequests::Get()->GetDefaultViewportContext()->GetWindowHandle(); if (windowHandle) { return CaptureScreenshotForWindow(filePath, windowHandle); From afe20906db9c9f02003eed21a460627b51523ea5 Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Tue, 1 Jun 2021 15:30:14 -0700 Subject: [PATCH 375/811] Add Project Manager File menu options to Editor --- .../ProjectManager/ProjectManager.cpp | 6 ++-- .../ProjectManager/ProjectManager.h | 15 ++++++-- .../Editor/Core/LevelEditorMenuHandler.cpp | 11 +++--- Code/Sandbox/Editor/CryEdit.cpp | 34 +++++++++++++++++++ Code/Sandbox/Editor/CryEdit.h | 4 +++ Code/Sandbox/Editor/LyViewPaneNames.h | 2 +- Code/Sandbox/Editor/MainWindow.cpp | 3 ++ Code/Sandbox/Editor/Resource.h | 3 ++ .../Source/ProjectManagerWindow.cpp | 18 ++++++++-- .../Source/ProjectManagerWindow.h | 4 ++- .../ProjectManager/Source/ProjectUtils.cpp | 11 ++++++ .../ProjectManager/Source/ProjectUtils.h | 2 ++ Code/Tools/ProjectManager/Source/ScreenDefs.h | 23 ++++++++++++- Code/Tools/ProjectManager/Source/main.cpp | 28 ++++++++++++++- 14 files changed, 147 insertions(+), 17 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp b/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp index 2742b90f4c..22598595fc 100644 --- a/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp @@ -78,7 +78,7 @@ namespace AzFramework::ProjectManager projectJsonPath.c_str()); } - if (LaunchProjectManager(engineRootPath)) + if (LaunchProjectManager()) { AZ_TracePrintf("ProjectManager", "Project Manager launched successfully, requesting exit."); return ProjectPathCheckResult::ProjectManagerLaunched; @@ -87,7 +87,7 @@ namespace AzFramework::ProjectManager return ProjectPathCheckResult::ProjectManagerLaunchFailed; } - bool LaunchProjectManager([[maybe_unused]] const AZ::IO::FixedMaxPath& engineRootPath) + bool LaunchProjectManager(const AZStd::string& commandLineArgs) { bool launchSuccess = false; #if (AZ_TRAIT_AZFRAMEWORK_USE_PROJECT_MANAGER) @@ -109,7 +109,7 @@ namespace AzFramework::ProjectManager } AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; - processLaunchInfo.m_commandlineParameters = executablePath.String(); + processLaunchInfo.m_commandlineParameters = executablePath.String() + commandLineArgs; launchSuccess = AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo); } if (ownsSystemAllocator) diff --git a/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.h b/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.h index cc79bd4184..d0ef7172b0 100644 --- a/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.h +++ b/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.h @@ -12,6 +12,7 @@ #pragma once #include +#include namespace AzFramework::ProjectManager { @@ -21,8 +22,16 @@ namespace AzFramework::ProjectManager ProjectManagerLaunched = 0, ProjectPathFound = 1 }; - // Check for a project name, if not found, attempts to launch project manager and returns false + + //! Check for a project name, if not found, attempts to launch project manager and returns false + //! @param argc the number of arguments in argv + //! @param argv arguments provided to this executable + //! @return a ProjectPathCheckResult ProjectPathCheckResult CheckProjectPathProvided(const int argc, char* argv[]); - // Attempt to Launch the project manager. Requires locating the engine root, project manager script, and python. - bool LaunchProjectManager(const AZ::IO::FixedMaxPath& engineRootPath); + + //! Attempt to Launch the project manager, assuming the o3de executable exists in same folder as + //! current executable. Requires the o3de cli and python. + //! @param commandLineArgs additional command line arguments to provide to the project manager + //! @return true on success, false if failed to find or launch the executable + bool LaunchProjectManager(const AZStd::string& commandLineArgs = ""); } // AzFramework::ProjectManager diff --git a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp index 0ce3fa55f5..8f6e927a84 100644 --- a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp +++ b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp @@ -421,17 +421,18 @@ QMenu* LevelEditorMenuHandler::CreateFileMenu() fileMenu.AddSeparator(); // Project Settings - auto projectSettingMenu = fileMenu.AddMenu(tr("Project Settings")); + fileMenu.AddAction(ID_FILE_PROJECT_MANAGER_SETTINGS); - // Project Settings Tool + // Platform Settings - Project Settings Tool // Shortcut must be set while adding the action otherwise it doesn't work - projectSettingMenu.Get()->addAction( + fileMenu.Get()->addAction( tr(LyViewPane::ProjectSettingsTool), []() { QtViewPaneManager::instance()->OpenPane(LyViewPane::ProjectSettingsTool); }, tr("Ctrl+Shift+P")); - projectSettingMenu.AddSeparator(); - + fileMenu.AddSeparator(); + fileMenu.AddAction(ID_FILE_PROJECT_MANAGER_NEW); + fileMenu.AddAction(ID_FILE_PROJECT_MANAGER_OPEN); fileMenu.AddSeparator(); // NEWMENUS: NEEDS IMPLEMENTATION diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index a0ff5d7eff..c60f32560b 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -58,6 +58,7 @@ AZ_POP_DISABLE_WARNING #include #include #include +#include // AzToolsFramework #include @@ -477,6 +478,11 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_FILE_SAVE_LEVEL, OnFileSave) ON_COMMAND(ID_FILE_EXPORTOCCLUSIONMESH, OnFileExportOcclusionMesh) + + // 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) } CCryEditApp* CCryEditApp::s_currentInstance = nullptr; @@ -2854,6 +2860,34 @@ void CCryEditApp::OnPreferences() */ } +void CCryEditApp::OnOpenProjectManagerSettings() +{ + OpenProjectManager("UpdateProject"); +} + +void CCryEditApp::OnOpenProjectManagerNew() +{ + OpenProjectManager("CreateProject"); +} + +void CCryEditApp::OnOpenProjectManager() +{ + OpenProjectManager("Projects"); +} + +void CCryEditApp::OpenProjectManager(const AZStd::string& screen) +{ + // provide the current project path for in case we want to update the project + AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath(); + const AZStd::string commandLineOptions = AZStd::string::format(" --screen %s --project_path %s", screen.c_str(), projectPath.c_str()); + bool launchSuccess = AzFramework::ProjectManager::LaunchProjectManager(commandLineOptions); + if (!launchSuccess) + { + QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Failed to launch O3DE Project Manager"), QObject::tr("Failed to find or start the O3dE Project Manager")); + } +} + + ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUndo() { diff --git a/Code/Sandbox/Editor/CryEdit.h b/Code/Sandbox/Editor/CryEdit.h index d4c1304b6a..dc4f015faf 100644 --- a/Code/Sandbox/Editor/CryEdit.h +++ b/Code/Sandbox/Editor/CryEdit.h @@ -229,6 +229,9 @@ public: void OnFileResaveSlices(); void OnFileEditEditorini(); void OnPreferences(); + void OnOpenProjectManagerSettings(); + void OnOpenProjectManagerNew(); + void OnOpenProjectManager(); void OnRedo(); void OnUpdateRedo(QAction* action); void OnUpdateUndo(QAction* action); @@ -366,6 +369,7 @@ private: AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING friend struct PythonTestOutputHandler; + void OpenProjectManager(const AZStd::string& screen); void OnWireframe(); void OnUpdateWireframe(QAction* action); void OnViewConfigureLayout(); diff --git a/Code/Sandbox/Editor/LyViewPaneNames.h b/Code/Sandbox/Editor/LyViewPaneNames.h index e95191ce06..b94cda3c52 100644 --- a/Code/Sandbox/Editor/LyViewPaneNames.h +++ b/Code/Sandbox/Editor/LyViewPaneNames.h @@ -30,7 +30,7 @@ namespace LyViewPane static const char* const EntityInspector = "Entity Inspector"; static const char* const EntityInspectorPinned = "Pinned Entity Inspector"; static const char* const LevelInspector = "Level Inspector"; - static const char* const ProjectSettingsTool = "Project Settings Tool"; + static const char* const ProjectSettingsTool = "Edit Platform Settings..."; static const char* const ErrorReport = "Error Report"; static const char* const Console = "Console"; static const char* const ConsoleMenuName = "&Console"; diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index 8086293207..9e983c3593 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -748,6 +748,9 @@ void MainWindow::InitActions() am->AddAction(ID_FILE_EXPORTOCCLUSIONMESH, tr("Export Occlusion Mesh")); am->AddAction(ID_FILE_EDITLOGFILE, tr("Show Log File")); am->AddAction(ID_FILE_RESAVESLICES, tr("Resave All Slices")); + am->AddAction(ID_FILE_PROJECT_MANAGER_SETTINGS, tr("Edit Project Settings...")); + am->AddAction(ID_FILE_PROJECT_MANAGER_NEW, tr("New Project...")); + am->AddAction(ID_FILE_PROJECT_MANAGER_OPEN, tr("Open Project...")); am->AddAction(ID_GAME_PC_ENABLEVERYHIGHSPEC, tr("Very High")).SetCheckable(true) .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateGameSpec); am->AddAction(ID_GAME_PC_ENABLEHIGHSPEC, tr("High")).SetCheckable(true) diff --git a/Code/Sandbox/Editor/Resource.h b/Code/Sandbox/Editor/Resource.h index 31fc9909f1..9c50045367 100644 --- a/Code/Sandbox/Editor/Resource.h +++ b/Code/Sandbox/Editor/Resource.h @@ -313,6 +313,9 @@ #define ID_CREATE_LEVEL_FG_MODULE_FROM_SELECTION 35077 #define ID_GRAPHVIEW_ADD_BLACK_BOX 35078 #define ID_GRAPHVIEW_UNGROUP 35079 +#define ID_FILE_PROJECT_MANAGER_NEW 35080 +#define ID_FILE_PROJECT_MANAGER_OPEN 35081 +#define ID_FILE_PROJECT_MANAGER_SETTINGS 35082 #define ID_TV_TRACKS_TOOLBAR_BASE 35083 // range between ID_TV_TRACKS_TOOLBAR_BASE to ID_TV_TRACKS_TOOLBAR_LAST reserved #define ID_TV_TRACKS_TOOLBAR_LAST 35183 // for up to 100 "Add Tracks..." dynamically added Track View Track buttons #define ID_OPEN_TERRAIN_EDITOR 36007 diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp index 76bcc2eb99..cb1398cc61 100644 --- a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp @@ -14,13 +14,16 @@ #include #include +#include #include +#include +#include #include namespace O3DE::ProjectManager { - ProjectManagerWindow::ProjectManagerWindow(QWidget* parent, const AZ::IO::PathView& engineRootPath) + ProjectManagerWindow::ProjectManagerWindow(QWidget* parent, const AZ::IO::PathView& engineRootPath, const AZ::IO::PathView& projectPath, ProjectManagerScreen startScreen) : QMainWindow(parent) { m_pythonBindings = AZStd::make_unique(engineRootPath); @@ -50,7 +53,18 @@ namespace O3DE::ProjectManager // set stylesheet after creating the screens or their styles won't get updated AzQtComponents::StyleManager::setStyleSheet(this, QStringLiteral("style:ProjectManager.qss")); - screensCtrl->ForceChangeToScreen(ProjectManagerScreen::Projects, false); + // always push the projects screen first so we have something to come back to + if (startScreen != ProjectManagerScreen::Projects) + { + screensCtrl->ForceChangeToScreen(ProjectManagerScreen::Projects); + } + screensCtrl->ForceChangeToScreen(startScreen); + + if (!projectPath.empty()) + { + const QString path = QString::fromUtf8(projectPath.Native().data(), aznumeric_cast(projectPath.Native().size())); + emit screensCtrl->NotifyCurrentProject(path); + } } ProjectManagerWindow::~ProjectManagerWindow() diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h index 74db3467c5..758af8fc00 100644 --- a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h +++ b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h @@ -14,6 +14,7 @@ #if !defined(Q_MOC_RUN) #include #include +#include #endif namespace O3DE::ProjectManager @@ -24,7 +25,8 @@ namespace O3DE::ProjectManager Q_OBJECT public: - explicit ProjectManagerWindow(QWidget* parent, const AZ::IO::PathView& engineRootPath); + explicit ProjectManagerWindow(QWidget* parent, const AZ::IO::PathView& engineRootPath, const AZ::IO::PathView& projectPath, + ProjectManagerScreen startScreen = ProjectManagerScreen::Projects); ~ProjectManagerWindow(); private: diff --git a/Code/Tools/ProjectManager/Source/ProjectUtils.cpp b/Code/Tools/ProjectManager/Source/ProjectUtils.cpp index 526e745d82..58e4c5c60f 100644 --- a/Code/Tools/ProjectManager/Source/ProjectUtils.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectUtils.cpp @@ -192,5 +192,16 @@ namespace O3DE::ProjectManager return true; } + ProjectManagerScreen GetProjectManagerScreen(const QString& screen) + { + auto iter = s_ProjectManagerStringNames.find(screen); + if (iter != s_ProjectManagerStringNames.end()) + { + return iter.value(); + } + + return ProjectManagerScreen::Invalid; + } + } // namespace ProjectUtils } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectUtils.h b/Code/Tools/ProjectManager/Source/ProjectUtils.h index 5982bff634..d556d682f2 100644 --- a/Code/Tools/ProjectManager/Source/ProjectUtils.h +++ b/Code/Tools/ProjectManager/Source/ProjectUtils.h @@ -11,6 +11,7 @@ */ #pragma once +#include #include namespace O3DE::ProjectManager @@ -24,5 +25,6 @@ namespace O3DE::ProjectManager bool CopyProject(const QString& origPath, const QString& newPath); bool DeleteProjectFiles(const QString& path, bool force = false); bool MoveProject(const QString& origPath, const QString& newPath, QWidget* parent = nullptr); + ProjectManagerScreen GetProjectManagerScreen(const QString& screen); } // namespace ProjectUtils } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ScreenDefs.h b/Code/Tools/ProjectManager/Source/ScreenDefs.h index 46d243f677..43ed303461 100644 --- a/Code/Tools/ProjectManager/Source/ScreenDefs.h +++ b/Code/Tools/ProjectManager/Source/ScreenDefs.h @@ -11,9 +11,13 @@ */ #pragma once +#include +#include +#include + namespace O3DE::ProjectManager { - enum ProjectManagerScreen + enum class ProjectManagerScreen { Invalid = -1, Empty, @@ -25,4 +29,21 @@ namespace O3DE::ProjectManager ProjectSettings, EngineSettings }; + + static QHash s_ProjectManagerStringNames = { + { "Empty", ProjectManagerScreen::Empty}, + { "CreateProject", ProjectManagerScreen::CreateProject}, + { "NewProjectSettings", ProjectManagerScreen::NewProjectSettings}, + { "GemCatalog", ProjectManagerScreen::GemCatalog}, + { "Projects", ProjectManagerScreen::Projects}, + { "UpdateProject", ProjectManagerScreen::UpdateProject}, + { "ProjectSettings", ProjectManagerScreen::ProjectSettings}, + { "EngineSettings", ProjectManagerScreen::EngineSettings} + }; + + // need to define qHash for ProjectManagerScreen when using scoped enums + inline uint qHash(ProjectManagerScreen key, uint seed) + { + return ::qHash(static_cast(key), seed); + } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/main.cpp b/Code/Tools/ProjectManager/Source/main.cpp index cbeacbaf65..c597b8a729 100644 --- a/Code/Tools/ProjectManager/Source/main.cpp +++ b/Code/Tools/ProjectManager/Source/main.cpp @@ -15,13 +15,17 @@ #include #include #include +#include #include +#include #include #include #include +using namespace O3DE::ProjectManager; + int main(int argc, char* argv[]) { QApplication::setOrganizationName("O3DE"); @@ -51,7 +55,29 @@ int main(int argc, char* argv[]) AzQtComponents::StyleManager styleManager(&app); styleManager.initialize(&app, engineRootPath); - O3DE::ProjectManager::ProjectManagerWindow window(nullptr, engineRootPath); + // Get the initial start screen if one is provided via command line + constexpr char optionPrefix[] = "--"; + AZ::CommandLine commandLine(optionPrefix); + commandLine.Parse(argc, argv); + + ProjectManagerScreen startScreen = ProjectManagerScreen::Projects; + if(commandLine.HasSwitch("screen")) + { + QString screenOption = commandLine.GetSwitchValue("screen", 0).c_str(); + ProjectManagerScreen screen = ProjectUtils::GetProjectManagerScreen(screenOption); + if (screen != ProjectManagerScreen::Invalid) + { + startScreen = screen; + } + } + + AZ::IO::FixedMaxPath projectPath; + if (commandLine.HasSwitch("project-path")) + { + projectPath = commandLine.GetSwitchValue("project-path", 0).c_str(); + } + + ProjectManagerWindow window(nullptr, engineRootPath, projectPath, startScreen); window.show(); // somethings is preventing us from moving the window to the center of the From a3e73948c53820bc70406641eadb8f49a3234332 Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Tue, 1 Jun 2021 15:32:57 -0700 Subject: [PATCH 376/811] Improved project creation validation No longer requires project name to be part of the project path. --- AutomatedTesting/preview.png | 4 +- .../Source/CreateProjectCtrl.cpp | 12 +++ .../ProjectManager/Source/CreateProjectCtrl.h | 1 + .../Source/FormLineEditWidget.cpp | 8 ++ .../Source/FormLineEditWidget.h | 1 + .../Source/NewProjectSettingsScreen.cpp | 81 ++++++++++++++----- .../Source/NewProjectSettingsScreen.h | 5 ++ .../ProjectManager/Source/ProjectsScreen.cpp | 10 +++ .../ProjectManager/Source/PythonBindings.cpp | 9 ++- .../ProjectManager/Source/ScreensCtrl.cpp | 27 ++++++- .../Tools/ProjectManager/Source/ScreensCtrl.h | 2 + Templates/DefaultProject/Template/preview.png | 4 +- scripts/o3de/o3de/engine_template.py | 23 ++++-- 13 files changed, 157 insertions(+), 30 deletions(-) diff --git a/AutomatedTesting/preview.png b/AutomatedTesting/preview.png index 3d4fe78063..c6928d31fc 100644 --- a/AutomatedTesting/preview.png +++ b/AutomatedTesting/preview.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:40949893ed7009eeaa90b7ce6057cb6be9dfaf7b162e3c26ba9dadf985939d7d -size 2038 +oid sha256:b9cd9d6f67440c193a85969ec5c082c6343e6d1fff3b6f209a0a6931eb22dd47 +size 2949 diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp index 69f0a3983d..60e351cdb4 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp @@ -67,6 +67,15 @@ namespace O3DE::ProjectManager return ProjectManagerScreen::CreateProject; } + void CreateProjectCtrl::NotifyCurrentScreen() + { + ScreenWidget* currentScreen = reinterpret_cast(m_stack->currentWidget()); + if (currentScreen) + { + currentScreen->NotifyCurrentScreen(); + } + } + void CreateProjectCtrl::HandleBackButton() { if (m_stack->currentIndex() > 0) @@ -110,6 +119,9 @@ namespace O3DE::ProjectManager auto result = PythonBindingsInterface::Get()->CreateProject(m_projectTemplatePath, m_projectInfo); if (result.IsSuccess()) { + // automatically register the project + PythonBindingsInterface::Get()->AddProject(m_projectInfo.m_path); + // adding gems is not implemented yet because we don't know what targets to add or how to add them emit ChangeScreenRequest(ProjectManagerScreen::Projects); } diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h index 01e3349b21..355ba3941d 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h @@ -31,6 +31,7 @@ namespace O3DE::ProjectManager explicit CreateProjectCtrl(QWidget* parent = nullptr); ~CreateProjectCtrl() = default; ProjectManagerScreen GetScreenEnum() override; + void NotifyCurrentScreen() override; protected slots: void HandleBackButton(); diff --git a/Code/Tools/ProjectManager/Source/FormLineEditWidget.cpp b/Code/Tools/ProjectManager/Source/FormLineEditWidget.cpp index 7ef7e3c7d8..6c08393910 100644 --- a/Code/Tools/ProjectManager/Source/FormLineEditWidget.cpp +++ b/Code/Tools/ProjectManager/Source/FormLineEditWidget.cpp @@ -78,6 +78,14 @@ namespace O3DE::ProjectManager m_errorLabel->setText(labelText); } + void FormLineEditWidget::setErrorLabelVisible(bool visible) + { + m_errorLabel->setVisible(visible); + m_frame->setProperty("Valid", !visible); + + refreshStyle(); + } + QLineEdit* FormLineEditWidget::lineEdit() const { return m_lineEdit; diff --git a/Code/Tools/ProjectManager/Source/FormLineEditWidget.h b/Code/Tools/ProjectManager/Source/FormLineEditWidget.h index 3094442cbd..76534f46f7 100644 --- a/Code/Tools/ProjectManager/Source/FormLineEditWidget.h +++ b/Code/Tools/ProjectManager/Source/FormLineEditWidget.h @@ -39,6 +39,7 @@ namespace O3DE::ProjectManager //! Set the error message for to display when invalid. void setErrorLabelText(const QString& labelText); + void setErrorLabelVisible(bool visible); //! Returns a pointer to the underlying LineEdit. QLineEdit* lineEdit() const; diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp index b57a2b35b2..53400b3193 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -49,16 +50,16 @@ namespace O3DE::ProjectManager vLayout->setContentsMargins(0,0,0,0); vLayout->setAlignment(Qt::AlignTop); { - m_projectName = new FormLineEditWidget(tr("Project name"), tr("New Project"), this); - m_projectName->setErrorLabelText( - tr("A project with this name already exists at this location. Please choose a new name or location.")); + const QString defaultName{ "NewProject" }; + const QString defaultPath = QDir::toNativeSeparators(GetDefaultProjectPath() + "/" + defaultName); + + m_projectName = new FormLineEditWidget(tr("Project name"), defaultName, this); + connect(m_projectName->lineEdit(), &QLineEdit::textChanged, this, &NewProjectSettingsScreen::ValidateProjectPath); vLayout->addWidget(m_projectName); - m_projectPath = - new FormBrowseEditWidget(tr("Project Location"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), this); + m_projectPath = new FormBrowseEditWidget(tr("Project Location"), defaultPath, this); m_projectPath->lineEdit()->setReadOnly(true); - m_projectPath->setErrorLabelText(tr("Please provide a valid path to a folder that exists")); - m_projectPath->lineEdit()->setValidator(new PathValidator(PathValidator::PathMode::ExistingFolder, this)); + connect(m_projectPath->lineEdit(), &QLineEdit::textChanged, this, &NewProjectSettingsScreen::ValidateProjectPath); vLayout->addWidget(m_projectPath); // if we don't use a QFrame we cannot "contain" the widgets inside and move them around @@ -112,17 +113,41 @@ namespace O3DE::ProjectManager this->setLayout(hLayout); } + QString NewProjectSettingsScreen::GetDefaultProjectPath() + { + QString defaultPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); + AZ::Outcome engineInfoResult = PythonBindingsInterface::Get()->GetEngineInfo(); + if (engineInfoResult.IsSuccess()) + { + QDir path(QDir::toNativeSeparators(engineInfoResult.GetValue().m_defaultProjectsFolder)); + if (path.exists()) + { + defaultPath = path.absolutePath(); + } + } + return defaultPath; + } + ProjectManagerScreen NewProjectSettingsScreen::GetScreenEnum() { return ProjectManagerScreen::NewProjectSettings; } + void NewProjectSettingsScreen::ValidateProjectPath() + { + Validate(); + } + + void NewProjectSettingsScreen::NotifyCurrentScreen() + { + Validate(); + } ProjectInfo NewProjectSettingsScreen::GetProjectInfo() { ProjectInfo projectInfo; projectInfo.m_projectName = m_projectName->lineEdit()->text(); - projectInfo.m_path = QDir::toNativeSeparators(m_projectPath->lineEdit()->text() + "/" + projectInfo.m_projectName); + projectInfo.m_path = m_projectPath->lineEdit()->text(); return projectInfo; } @@ -133,24 +158,44 @@ namespace O3DE::ProjectManager bool NewProjectSettingsScreen::Validate() { - bool projectNameIsValid = true; - if (m_projectName->lineEdit()->text().isEmpty()) - { - projectNameIsValid = false; - } - bool projectPathIsValid = true; if (m_projectPath->lineEdit()->text().isEmpty()) { projectPathIsValid = false; + m_projectPath->setErrorLabelText(tr("Please provide a valid location.")); } - - QDir path(QDir::toNativeSeparators(m_projectPath->lineEdit()->text() + "/" + m_projectName->lineEdit()->text())); - if (path.exists() && !path.isEmpty()) + else { - projectPathIsValid = false; + QDir path(m_projectPath->lineEdit()->text()); + if (path.exists() && !path.isEmpty()) + { + projectPathIsValid = false; + m_projectPath->setErrorLabelText(tr("This folder exists and isn't empty. Please choose a different location.")); + } } + bool projectNameIsValid = true; + if (m_projectName->lineEdit()->text().isEmpty()) + { + projectNameIsValid = false; + m_projectName->setErrorLabelText(tr("Please provide a project name.")); + } + else + { + // this validation should roughly match the utils.validate_identifier which the cli + // uses to validate project names + QRegExp validProjectNameRegex("[A-Za-z][A-Za-z0-9_-]{0,63}"); + const bool result = validProjectNameRegex.exactMatch(m_projectName->lineEdit()->text()); + if (!result) + { + projectNameIsValid = false; + m_projectName->setErrorLabelText(tr("Project names must start with a letter and consist of up to 64 letter, number, '_' or '-' characters")); + } + + } + + m_projectName->setErrorLabelVisible(!projectNameIsValid); + m_projectPath->setErrorLabelVisible(!projectPathIsValid); return projectNameIsValid && projectPathIsValid; } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h index f0e9609fdc..0560f8728d 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h +++ b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h @@ -36,10 +36,15 @@ namespace O3DE::ProjectManager bool Validate(); + void NotifyCurrentScreen() override; + protected slots: void HandleBrowseButton(); + void ValidateProjectPath(); private: + QString GetDefaultProjectPath(); + FormLineEditWidget* m_projectName; FormBrowseEditWidget* m_projectPath; QButtonGroup* m_projectTemplateButtonGroup; diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp index dd2e411ec5..7b9e3ecb9d 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp @@ -341,6 +341,16 @@ namespace O3DE::ProjectManager } else { + // refresh the projects content by re-creating it for now + if (m_projectsContent) + { + m_stack->removeWidget(m_projectsContent); + m_projectsContent->deleteLater(); + } + + m_projectsContent = CreateProjectsContent(); + + m_stack->addWidget(m_projectsContent); m_stack->setCurrentWidget(m_projectsContent); } } diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 8db8492cae..c0481d6c87 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -513,10 +513,15 @@ namespace O3DE::ProjectManager { ProjectInfo createdProjectInfo; bool result = ExecuteWithLock([&] { - pybind11::str projectPath = projectInfo.m_path.toStdString(); + pybind11::str projectName = projectInfo.m_projectName.toStdString(); pybind11::str templatePath = projectTemplatePath.toStdString(); - auto createProjectResult = m_engineTemplate.attr("create_project")(projectPath, templatePath); + + auto createProjectResult = m_engineTemplate.attr("create_project")( + projectPath, + projectName, + templatePath + ); if (createProjectResult.cast() == 0) { createdProjectInfo = ProjectInfoFromPath(projectPath); diff --git a/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp b/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp index 7d31d02f6c..6206d4cee9 100644 --- a/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp @@ -136,6 +136,7 @@ namespace O3DE::ProjectManager { shouldRestoreCurrentScreen = true; } + int tabIndex = GetScreenTabIndex(screen); // Delete old screen if it exists to start fresh DeleteScreen(screen); @@ -144,11 +145,19 @@ namespace O3DE::ProjectManager ScreenWidget* newScreen = BuildScreen(this, screen); if (newScreen->IsTab()) { - m_tabWidget->addTab(newScreen, newScreen->GetTabText()); + if (tabIndex > -1) + { + m_tabWidget->insertTab(tabIndex, newScreen, newScreen->GetTabText()); + } + else + { + m_tabWidget->addTab(newScreen, newScreen->GetTabText()); + } if (shouldRestoreCurrentScreen) { m_tabWidget->setCurrentWidget(newScreen); m_screenStack->setCurrentWidget(m_tabWidget); + newScreen->NotifyCurrentScreen(); } } else @@ -157,6 +166,7 @@ namespace O3DE::ProjectManager if (shouldRestoreCurrentScreen) { m_screenStack->setCurrentWidget(newScreen); + newScreen->NotifyCurrentScreen(); } } @@ -219,4 +229,19 @@ namespace O3DE::ProjectManager screen->NotifyCurrentScreen(); } } + + int ScreensCtrl::GetScreenTabIndex(ProjectManagerScreen screen) + { + const auto iter = m_screenMap.find(screen); + if (iter != m_screenMap.end()) + { + ScreenWidget* screenWidget = iter.value(); + if (screenWidget->IsTab()) + { + return m_tabWidget->indexOf(screenWidget); + } + } + + return -1; + } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ScreensCtrl.h b/Code/Tools/ProjectManager/Source/ScreensCtrl.h index 935fc78e25..3b51ed529a 100644 --- a/Code/Tools/ProjectManager/Source/ScreensCtrl.h +++ b/Code/Tools/ProjectManager/Source/ScreensCtrl.h @@ -51,6 +51,8 @@ namespace O3DE::ProjectManager void TabChanged(int index); private: + int GetScreenTabIndex(ProjectManagerScreen screen); + QStackedWidget* m_screenStack; QHash m_screenMap; QStack m_screenVisitOrder; diff --git a/Templates/DefaultProject/Template/preview.png b/Templates/DefaultProject/Template/preview.png index 3d4fe78063..a3e13481c9 100644 --- a/Templates/DefaultProject/Template/preview.png +++ b/Templates/DefaultProject/Template/preview.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:40949893ed7009eeaa90b7ce6057cb6be9dfaf7b162e3c26ba9dadf985939d7d -size 2038 +oid sha256:4a5881b8d6cfbc4ceefb14ab96844484fe19407ee030824768f9fcce2f729d35 +size 2949 diff --git a/scripts/o3de/o3de/engine_template.py b/scripts/o3de/o3de/engine_template.py index 63dec3e765..9bb62eff35 100755 --- a/scripts/o3de/o3de/engine_template.py +++ b/scripts/o3de/o3de/engine_template.py @@ -1279,6 +1279,7 @@ def create_from_template(destination_path: str, def create_project(project_path: str, + project_name: str = None, template_path: str = None, template_name: str = None, project_restricted_path: str = None, @@ -1297,6 +1298,7 @@ def create_project(project_path: str, Template instantiation specialization that makes all default assumptions for a Project template instantiation, reducing the effort needed in instancing a project :param project_path: the project path, can be absolute or relative to default projects path + :param project_name: the project name, defaults to project_path basename if not provided :param template_path: the path to the template you want to instance, can be absolute or relative to default templates path :param template_name: the name the registered template you want to instance, defaults to DefaultProject, resolves template_path :param project_restricted_path: path to the projects restricted folder, can be absolute or relative to the restricted='projects' @@ -1489,12 +1491,17 @@ def create_project(project_path: str, elif not os.path.isdir(project_path): os.makedirs(project_path) - # project name is now the last component of the project_path - project_name = os.path.basename(project_path) + if not project_name: + # project name is now the last component of the project_path + project_name = os.path.basename(project_path) + + if not utils.validate_identifier(project_name): + logger.error(f'Project name must be fewer than 64 characters, contain only alphanumeric, "_" or "-" characters, and start with a letter. {project_name}') + return 1 # project name cannot be the same as a restricted platform name if project_name in restricted_platforms: - logger.error(f'Project path cannot be a restricted name. {project_name}') + logger.error(f'Project name cannot be a restricted name. {project_name}') return 1 # project restricted name @@ -2079,6 +2086,7 @@ def _run_create_from_template(args: argparse) -> int: def _run_create_project(args: argparse) -> int: return create_project(args.project_path, + args.project_name, args.template_path, args.template_name, args.project_restricted_path, @@ -2262,10 +2270,15 @@ def add_args(subparsers) -> None: # creation of a project from a template (like create from template but makes project assumptions) create_project_subparser = subparsers.add_parser('create-project') create_project_subparser.add_argument('-pp', '--project-path', type=str, required=True, - help='The name of the project you wish to create from the template,' + help='The location of the project you wish to create from the template,' ' can be an absolute path or dev root relative.' ' Ex. C:/o3de/TestProject' - ' TestProject = ') + ' TestProject = if --project-name not provided') + create_project_subparser.add_argument('-pn', '--project-name', type=str, required=False, + help='The name of the project you wish to use, must be alphanumeric, ' + ' and can contain _ and - characters.' + ' If no name is provided, will use last component of project path.' + ' Ex. New_Project-123') group = create_project_subparser.add_mutually_exclusive_group(required=False) group.add_argument('-tp', '--template-path', type=str, required=False, From 38819c630aa7313c49cb8073876b6f401df95efb Mon Sep 17 00:00:00 2001 From: mnaumov Date: Tue, 1 Jun 2021 15:34:01 -0700 Subject: [PATCH 377/811] PR feedback --- .../DisplayMapper/DisplayMapperComponentBus.h | 63 ++++- .../DisplayMapperComponentController.cpp | 231 +++++++++++++++++- .../DisplayMapperComponentController.h | 24 ++ .../EditorDisplayMapperComponent.cpp | 60 +++-- 4 files changed, 359 insertions(+), 19 deletions(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h index af57b69d3b..4a01f71325 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h @@ -30,8 +30,67 @@ namespace AZ virtual void LoadPreset(OutputDeviceTransformType preset) = 0; //! Set display mapper type virtual void SetDisplayMapperOperationType(DisplayMapperOperationType displayMapperOperationType) = 0; - //! Set custom ACES parameters for ACES mapping, display mapper must be set to Aces to see the difference + //! Get display mapper type + virtual DisplayMapperOperationType GetDisplayMapperOperationType() const = 0; + //! Set ACES parameter overrides for ACES mapping, display mapper must be set to Aces to see the difference virtual void SetAcesParameterOverrides(const AcesParameterOverrides& parameterOverrides) = 0; + //! Get ACES parameter overrides + virtual const AcesParameterOverrides& GetAcesParameterOverrides() const = 0; + + // Enable or disable ACES parameter overrides + virtual void SetOverrideAcesParameters(bool value) = 0; + // Check if ACES parameters are overriding default preset values + virtual bool GetOverrideAcesParameters() const = 0; + + // Set gamma adjustment to compensate for dim surround + virtual void SetAlterSurround(bool value) = 0; + // Get gamma adjustment to compensate for dim surround + virtual bool GetAlterSurround() const = 0; + + // Set desaturation to compensate for luminance difference + virtual void SetApplyDesaturation(bool value) = 0; + // Get desaturation to compensate for luminance difference + virtual bool GetApplyDesaturation() const = 0; + + // Set color appearance transform (CAT) from ACES white point to assumed observer adapted white point + virtual void SetApplyCATD60toD65(bool value) = 0; + // Get color appearance transform (CAT) from ACES white point to assumed observer adapted white point + virtual bool GetApplyCATD60toD65() const = 0; + + // Set reference black luminance value + virtual void SetCinemaLimitsBlack(float value) = 0; + // Get reference black luminance value + virtual float GetCinemaLimitsBlack() const = 0; + + // Set reference white luminance value + virtual void SetCinemaLimitsWhite(float value) = 0; + // Get reference white luminance value + virtual float GetCinemaLimitsWhite() const = 0; + + // Set min luminance value + virtual void SetMinPoint(float value) = 0; + // Get min luminance value + virtual float GetMinPoint() const = 0; + + // Set mid luminance value + virtual void SetMidPoint(float value) = 0; + // Get mid luminance value + virtual float GetMidPoint() const = 0; + + // Set max luminance value + virtual void SetMaxPoint(float value) = 0; + // Get max luminance value + virtual float GetMaxPoint() const = 0; + + // Set gamma adjustment value + virtual void SetSurroundGamma(float value) = 0; + // Get gamma adjustment value + virtual float GetSurroundGamma() const = 0; + + // Set optional gamma value that is applied as basic gamma curve OETF + virtual void SetGamma(float value) = 0; + // Get optional gamma value that is applied as basic gamma curve OETF + virtual float GetGamma() const = 0; }; using DisplayMapperComponentRequestBus = EBus; @@ -40,7 +99,7 @@ namespace AZ { public: //! Notifies that display mapper type changed - virtual void OntDisplayMapperOperationTypeUpdated([[maybe_unused]] const DisplayMapperOperationType& displayMapperOperationType) + virtual void OnDisplayMapperOperationTypeUpdated([[maybe_unused]] const DisplayMapperOperationType& displayMapperOperationType) { } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp index 7831c0a4c6..06c549f560 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp @@ -10,6 +10,8 @@ * */ +#include "AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h" + #include #include @@ -32,6 +34,69 @@ namespace AZ ->Version(0) ->Field("Configuration", &DisplayMapperComponentController::m_configuration); } + + if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) + { + behaviorContext->EBus("DisplayMapperComponentRequestBus") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "render") + ->Attribute(AZ::Script::Attributes::Module, "render") + // LoadPreset + ->Event("LoadPreset", &DisplayMapperComponentRequestBus::Events::LoadPreset) + // DisplayMapperOperationType + ->Event("SetDisplayMapperOperationType", &DisplayMapperComponentRequestBus::Events::SetDisplayMapperOperationType) + ->Event("GetDisplayMapperOperationType", &DisplayMapperComponentRequestBus::Events::GetDisplayMapperOperationType) + ->VirtualProperty("DisplayMapperOperationType", "GetDisplayMapperOperationType", "SetDisplayMapperOperationType") + // AcesParameterOverrides + ->Event("SetAcesParameterOverrides", &DisplayMapperComponentRequestBus::Events::SetAcesParameterOverrides) + ->Event("GetAcesParameterOverrides", &DisplayMapperComponentRequestBus::Events::GetAcesParameterOverrides) + ->VirtualProperty("AcesParameterOverrides", "GetAcesParameterOverrides", "SetAcesParameterOverrides") + // OverrideAcesParameters + ->Event("SetOverrideAcesParameters", &DisplayMapperComponentRequestBus::Events::SetOverrideAcesParameters) + ->Event("GetOverrideAcesParameters", &DisplayMapperComponentRequestBus::Events::GetOverrideAcesParameters) + ->VirtualProperty("OverrideAcesParameters", "GetOverrideAcesParameters", "SetOverrideAcesParameters") + // AlterSurround + ->Event("SetAlterSurround", &DisplayMapperComponentRequestBus::Events::SetAlterSurround) + ->Event("GetAlterSurround", &DisplayMapperComponentRequestBus::Events::GetAlterSurround) + ->VirtualProperty("AlterSurround", "GetAlterSurround", "SetAlterSurround") + // ApplyDesaturation + ->Event("SetApplyDesaturation", &DisplayMapperComponentRequestBus::Events::SetApplyDesaturation) + ->Event("GetApplyDesaturation", &DisplayMapperComponentRequestBus::Events::GetApplyDesaturation) + ->VirtualProperty("ApplyDesaturation", "GetApplyDesaturation", "SetApplyDesaturation") + // ApplyCATD60toD65 + ->Event("SetApplyCATD60toD65", &DisplayMapperComponentRequestBus::Events::SetApplyCATD60toD65) + ->Event("GetApplyCATD60toD65", &DisplayMapperComponentRequestBus::Events::GetApplyCATD60toD65) + ->VirtualProperty("ApplyCATD60toD65", "GetApplyCATD60toD65", "SetApplyCATD60toD65") + // CinemaLimitsBlack + ->Event("SetCinemaLimitsBlack", &DisplayMapperComponentRequestBus::Events::SetCinemaLimitsBlack) + ->Event("GetCinemaLimitsBlack", &DisplayMapperComponentRequestBus::Events::GetCinemaLimitsBlack) + ->VirtualProperty("CinemaLimitsBlack", "GetCinemaLimitsBlack", "SetCinemaLimitsBlack") + // CinemaLimitsWhite + ->Event("SetCinemaLimitsWhite", &DisplayMapperComponentRequestBus::Events::SetCinemaLimitsWhite) + ->Event("GetCinemaLimitsWhite", &DisplayMapperComponentRequestBus::Events::GetCinemaLimitsWhite) + ->VirtualProperty("CinemaLimitsWhite", "GetCinemaLimitsWhite", "SetCinemaLimitsWhite") + // MinPoint + ->Event("SetMinPoint", &DisplayMapperComponentRequestBus::Events::SetMinPoint) + ->Event("GetMinPoint", &DisplayMapperComponentRequestBus::Events::GetMinPoint) + ->VirtualProperty("MinPoint", "GetMinPoint", "SetMinPoint") + // MidPoint + ->Event("SetMidPoint", &DisplayMapperComponentRequestBus::Events::SetMidPoint) + ->Event("GetMidPoint", &DisplayMapperComponentRequestBus::Events::GetMidPoint) + ->VirtualProperty("MidPoint", "GetMidPoint", "SetMidPoint") + // MaxPoint + ->Event("SetMaxPoint", &DisplayMapperComponentRequestBus::Events::SetMaxPoint) + ->Event("GetMaxPoint", &DisplayMapperComponentRequestBus::Events::GetMaxPoint) + ->VirtualProperty("MaxPoint", "GetMaxPoint", "SetMaxPoint") + // SurroundGamma + ->Event("SetSurroundGamma", &DisplayMapperComponentRequestBus::Events::SetSurroundGamma) + ->Event("GetSurroundGamma", &DisplayMapperComponentRequestBus::Events::GetSurroundGamma) + ->VirtualProperty("SurroundGamma", "GetSurroundGamma", "SetSurroundGamma") + // Gamma + ->Event("SetGamma", &DisplayMapperComponentRequestBus::Events::SetGamma) + ->Event("GetGamma", &DisplayMapperComponentRequestBus::Events::GetGamma) + ->VirtualProperty("Gamma", "GetGamma", "SetGamma") + ; + } } void DisplayMapperComponentController::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) @@ -92,11 +157,16 @@ namespace AZ m_configuration.m_displayMapperOperation = displayMapperOperationType; OnConfigChanged(); DisplayMapperComponentNotificationBus::Broadcast( - &DisplayMapperComponentNotificationBus::Handler::OntDisplayMapperOperationTypeUpdated, + &DisplayMapperComponentNotificationBus::Handler::OnDisplayMapperOperationTypeUpdated, m_configuration.m_displayMapperOperation); } } + DisplayMapperOperationType DisplayMapperComponentController::GetDisplayMapperOperationType() const + { + return m_configuration.m_displayMapperOperation; + } + void DisplayMapperComponentController::SetAcesParameterOverrides(const AcesParameterOverrides& parameterOverrides) { m_configuration.m_acesParameterOverrides = parameterOverrides; @@ -109,6 +179,165 @@ namespace AZ m_configuration.m_acesParameterOverrides); } + const AcesParameterOverrides& DisplayMapperComponentController::GetAcesParameterOverrides() const + { + return m_configuration.m_acesParameterOverrides; + } + + void DisplayMapperComponentController::SetOverrideAcesParameters(bool value) + { + m_configuration.m_acesParameterOverrides.m_overrideDefaults = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + bool DisplayMapperComponentController::GetOverrideAcesParameters() const + { + return m_configuration.m_acesParameterOverrides.m_overrideDefaults; + } + + void DisplayMapperComponentController::SetAlterSurround(bool value) + { + m_configuration.m_acesParameterOverrides.m_alterSurround = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + bool DisplayMapperComponentController::GetAlterSurround() const + { + return m_configuration.m_acesParameterOverrides.m_alterSurround; + } + + void DisplayMapperComponentController::SetApplyDesaturation(bool value) + { + m_configuration.m_acesParameterOverrides.m_applyDesaturation = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + bool DisplayMapperComponentController::GetApplyDesaturation() const + { + return m_configuration.m_acesParameterOverrides.m_applyDesaturation; + } + + void DisplayMapperComponentController::SetApplyCATD60toD65(bool value) + { + m_configuration.m_acesParameterOverrides.m_applyCATD60toD65 = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + bool DisplayMapperComponentController::GetApplyCATD60toD65() const + { + return m_configuration.m_acesParameterOverrides.m_applyCATD60toD65; + } + + void DisplayMapperComponentController::SetCinemaLimitsBlack(float value) + { + m_configuration.m_acesParameterOverrides.m_cinemaLimitsBlack = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + float DisplayMapperComponentController::GetCinemaLimitsBlack() const + { + return m_configuration.m_acesParameterOverrides.m_cinemaLimitsBlack; + } + + void DisplayMapperComponentController::SetCinemaLimitsWhite(float value) + { + m_configuration.m_acesParameterOverrides.m_cinemaLimitsWhite = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + float DisplayMapperComponentController::GetCinemaLimitsWhite() const + { + return m_configuration.m_acesParameterOverrides.m_cinemaLimitsWhite; + } + + void DisplayMapperComponentController::SetMinPoint(float value) + { + m_configuration.m_acesParameterOverrides.m_minPoint = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + float DisplayMapperComponentController::GetMinPoint() const + { + return m_configuration.m_acesParameterOverrides.m_minPoint; + } + + void DisplayMapperComponentController::SetMidPoint(float value) + { + m_configuration.m_acesParameterOverrides.m_midPoint = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + float DisplayMapperComponentController::GetMidPoint() const + { + return m_configuration.m_acesParameterOverrides.m_midPoint; + } + + void DisplayMapperComponentController::SetMaxPoint(float value) + { + m_configuration.m_acesParameterOverrides.m_maxPoint = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + float DisplayMapperComponentController::GetMaxPoint() const + { + return m_configuration.m_acesParameterOverrides.m_maxPoint; + } + + void DisplayMapperComponentController::SetSurroundGamma(float value) + { + m_configuration.m_acesParameterOverrides.m_surroundGamma = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + float DisplayMapperComponentController::GetSurroundGamma() const + { + return m_configuration.m_acesParameterOverrides.m_surroundGamma; + } + + void DisplayMapperComponentController::SetGamma(float value) + { + m_configuration.m_acesParameterOverrides.m_gamma = value; + if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) + { + OnConfigChanged(); + } + } + + float DisplayMapperComponentController::GetGamma() const + { + return m_configuration.m_acesParameterOverrides.m_gamma; + } + void DisplayMapperComponentController::OnConfigChanged() { // Register the configuration with the AcesDisplayMapperFeatureProcessor for this scene. diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.h index efa2070828..412bdc8524 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.h @@ -51,7 +51,31 @@ namespace AZ //! DisplayMapperComponentRequestBus::Handler overrides... void LoadPreset(OutputDeviceTransformType preset) override; void SetDisplayMapperOperationType(DisplayMapperOperationType displayMapperOperationType) override; + DisplayMapperOperationType GetDisplayMapperOperationType() const override; void SetAcesParameterOverrides(const AcesParameterOverrides& parameterOverrides) override; + const AcesParameterOverrides& GetAcesParameterOverrides() const override; + void SetOverrideAcesParameters(bool value) override; + bool GetOverrideAcesParameters() const override; + void SetAlterSurround(bool value) override; + bool GetAlterSurround() const override; + void SetApplyDesaturation(bool value) override; + bool GetApplyDesaturation() const override; + void SetApplyCATD60toD65(bool value) override; + bool GetApplyCATD60toD65() const override; + void SetCinemaLimitsBlack(float value) override; + float GetCinemaLimitsBlack() const override; + void SetCinemaLimitsWhite(float value) override; + float GetCinemaLimitsWhite() const override; + void SetMinPoint(float value) override; + float GetMinPoint() const override; + void SetMidPoint(float value) override; + float GetMidPoint() const override; + void SetMaxPoint(float value) override; + float GetMaxPoint() const override; + void SetSurroundGamma(float value) override; + float GetSurroundGamma() const override; + void SetGamma(float value) override; + float GetGamma() const override; private: AZ_DISABLE_COPY(DisplayMapperComponentController); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp index aadb0cc22b..4a03c6f712 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp @@ -54,63 +54,89 @@ namespace AZ ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + // m_overrideDefaults ->DataElement( AZ::Edit::UIHandlers::CheckBox, &AcesParameterOverrides::m_overrideDefaults, "Override Defaults", "When enabled allows parameter overrides for ACES configuration") ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + // m_alterSurround ->DataElement( AZ::Edit::UIHandlers::CheckBox, &AcesParameterOverrides::m_alterSurround, "Alter Surround", "Apply gamma adjustment to compensate for dim surround") ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + + // m_applyDesaturation ->DataElement( AZ::Edit::UIHandlers::CheckBox, &AcesParameterOverrides::m_applyDesaturation, "Alter Desaturation", "Apply desaturation to compensate for luminance difference") ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + + // m_applyCATD60toD65 ->DataElement( AZ::Edit::UIHandlers::CheckBox, &AcesParameterOverrides::m_applyCATD60toD65, "Alter CAT D60 to D65", "Apply Color appearance transform (CAT) from ACES white point to assumed observer adapted white point") ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - + + // m_cinemaLimitsBlack ->DataElement( - Edit::UIHandlers::Default, &AcesParameterOverrides::m_cinemaLimitsBlack, + Edit::UIHandlers::Slider, &AcesParameterOverrides::m_cinemaLimitsBlack, "Cinema Limit (black)", "Reference black luminance value") ->Attribute(AZ::Edit::Attributes::Min, 0.02f) ->Attribute(AZ::Edit::Attributes::Max, &AcesParameterOverrides::m_cinemaLimitsWhite) + ->Attribute(AZ::Edit::Attributes::Step, 0.005f) + ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + + // m_cinemaLimitsWhite ->DataElement( - Edit::UIHandlers::Default, &AcesParameterOverrides::m_cinemaLimitsWhite, + Edit::UIHandlers::Slider, &AcesParameterOverrides::m_cinemaLimitsWhite, "Cinema Limit (white)", "Reference white luminance value") ->Attribute(AZ::Edit::Attributes::Min, &AcesParameterOverrides::m_cinemaLimitsBlack) - ->Attribute(AZ::Edit::Attributes::Max, 4000) + ->Attribute(AZ::Edit::Attributes::Max, 4000.f) + ->Attribute(AZ::Edit::Attributes::Step, 0.005f) ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + // m_minPoint ->DataElement( - Edit::UIHandlers::Vector2, &AcesParameterOverrides::m_minPoint, "Min Point (luminance)", + Edit::UIHandlers::Slider, &AcesParameterOverrides::m_minPoint, "Min Point (luminance)", "Linear extension below this") ->Attribute(AZ::Edit::Attributes::Min, 0.002f) ->Attribute(AZ::Edit::Attributes::Max, &AcesParameterOverrides::m_midPoint) - ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - ->DataElement( - Edit::UIHandlers::Vector2, &AcesParameterOverrides::m_midPoint, "Mid Point (luminance)", "Middle gray") + ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::AttributesAndValues) + + // m_midPoint + ->DataElement(Edit::UIHandlers::Slider, &AcesParameterOverrides::m_midPoint, + "Mid Point (luminance)", "Middle gray") ->Attribute(AZ::Edit::Attributes::Min, &AcesParameterOverrides::m_minPoint) ->Attribute(AZ::Edit::Attributes::Max, &AcesParameterOverrides::m_maxPoint) - ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::AttributesAndValues) + + // m_maxPoint ->DataElement( - Edit::UIHandlers::Vector2, &AcesParameterOverrides::m_maxPoint, "Max Point (luminance)", + Edit::UIHandlers::Slider, &AcesParameterOverrides::m_maxPoint, "Max Point (luminance)", "Linear extension above this") ->Attribute(AZ::Edit::Attributes::Min, &AcesParameterOverrides::m_midPoint) - ->Attribute(AZ::Edit::Attributes::Max, 4000) + ->Attribute(AZ::Edit::Attributes::Max, 4000.f) + ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::AttributesAndValues) + + // m_surroundGamma + ->DataElement( + AZ::Edit::UIHandlers::Slider, &AcesParameterOverrides::m_surroundGamma, "Surround Gamma", + "Gamma adjustment to be applied to compensate for the condition of the viewing environment") + ->Attribute(AZ::Edit::Attributes::Min, 0.6f) + ->Attribute(AZ::Edit::Attributes::Max, 1.2f) + ->Attribute(AZ::Edit::Attributes::Step, 0.005f) ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + // m_gamma ->DataElement( - AZ::Edit::UIHandlers::Default, &AcesParameterOverrides::m_surroundGamma, "Surround Gamma", - "Gamma adjustment to be applied to compensate for the condition of the viewing environment") - ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - ->DataElement( - AZ::Edit::UIHandlers::Default, &AcesParameterOverrides::m_gamma, "Gamma", + AZ::Edit::UIHandlers::Slider, &AcesParameterOverrides::m_gamma, "Gamma", "Optional gamma value that is applied as basic gamma curve OETF") + ->Attribute(AZ::Edit::Attributes::Min, 0.2f) + ->Attribute(AZ::Edit::Attributes::Max, 4.0f) + ->Attribute(AZ::Edit::Attributes::Step, 0.005f) ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) // Load preset group @@ -154,6 +180,8 @@ namespace AZ if (auto behaviorContext = azrtti_cast(context)) { + behaviorContext->Class()->RequestBus("DisplayMapperComponentRequestBus"); + behaviorContext->ConstantProperty("EditorDisplayMapperComponentTypeId", BehaviorConstant(Uuid(EditorDisplayMapperComponentTypeId))) ->Attribute(AZ::Script::Attributes::Module, "render") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation); From 5884fc1096f6742e956d9b309fce1f710711c436 Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Tue, 1 Jun 2021 15:48:57 -0700 Subject: [PATCH 378/811] Fix LyShine instance not being initialized (#1078) --- Gems/LyShine/Code/Source/LyShineSystemComponent.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp b/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp index 902752a03c..0eab7705f6 100644 --- a/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp +++ b/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp @@ -157,6 +157,7 @@ namespace LyShine UiSystemBus::Handler::BusConnect(); UiSystemToolsBus::Handler::BusConnect(); UiFrameworkBus::Handler::BusConnect(); + CrySystemEventBus::Handler::BusConnect(); // register all the component types internal to the LyShine module // These are registered in the order we want them to appear in the Add Component menu @@ -201,6 +202,7 @@ namespace LyShine UiSystemToolsBus::Handler::BusDisconnect(); UiFrameworkBus::Handler::BusDisconnect(); LyShineRequestBus::Handler::BusDisconnect(); + CrySystemEventBus::Handler::BusDisconnect(); LyShineAllocatorScope::DeactivateAllocators(); } From dfd63737c390090e33fcd02002fdc1f2dd04f623 Mon Sep 17 00:00:00 2001 From: Vincent Liu <5900509+onecent1101@users.noreply.github.com> Date: Tue, 1 Jun 2021 15:59:43 -0700 Subject: [PATCH 379/811] [SPEC-6720] Update session common interfaces (#956) --- .../Session/ISessionHandlingRequests.h | 22 +++++++++++++++---- .../AzFramework/Session/ISessionRequests.h | 3 +++ .../Session/SessionNotifications.h | 3 +++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h b/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h index 47388c56c3..a0731626ef 100644 --- a/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h +++ b/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h @@ -12,6 +12,7 @@ #pragma once +#include #include namespace AzFramework @@ -49,13 +50,17 @@ namespace AzFramework class ISessionHandlingClientRequests { public: - // Handle the player join session process + AZ_RTTI(ISessionHandlingClientRequests, "{41DE6BD3-72BC-4443-BFF9-5B1B9396657A}"); + ISessionHandlingClientRequests() = default; + virtual ~ISessionHandlingClientRequests() = default; + + // Request the player join session // @param sessionConnectionConfig The required properties to handle the player join session process // @return The result of player join session process - virtual bool HandlePlayerJoinSession(const SessionConnectionConfig& sessionConnectionConfig) = 0; + virtual bool RequestPlayerJoinSession(const SessionConnectionConfig& sessionConnectionConfig) = 0; - // Handle the player leave session process - virtual void HandlePlayerLeaveSession() = 0; + // Request the connected player leave session + virtual void RequestPlayerLeaveSession() = 0; }; //! ISessionHandlingServerRequests @@ -63,6 +68,10 @@ namespace AzFramework class ISessionHandlingServerRequests { public: + AZ_RTTI(ISessionHandlingServerRequests, "{4F0C17BA-F470-4242-A8CB-EC7EA805257C}"); + ISessionHandlingServerRequests() = default; + virtual ~ISessionHandlingServerRequests() = default; + // Handle the destroy session process virtual void HandleDestroySession() = 0; @@ -74,5 +83,10 @@ namespace AzFramework // Handle the player leave session process // @param playerConnectionConfig The required properties to handle the player leave session process virtual void HandlePlayerLeaveSession(const PlayerConnectionConfig& playerConnectionConfig) = 0; + + // Retrieves the file location of a pem-encoded TLS certificate + // @return If successful, returns the file location of TLS certificate file; if not successful, returns + // empty string. + virtual AZStd::string GetSessionCertificate() = 0; }; } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Session/ISessionRequests.h b/Code/Framework/AzFramework/AzFramework/Session/ISessionRequests.h index 9d21a7f282..da65eb47f0 100644 --- a/Code/Framework/AzFramework/AzFramework/Session/ISessionRequests.h +++ b/Code/Framework/AzFramework/AzFramework/Session/ISessionRequests.h @@ -167,6 +167,9 @@ namespace AzFramework : public AZ::EBusTraits { public: + // Safeguard handler for multi-threaded use case + using MutexType = AZStd::recursive_mutex; + ////////////////////////////////////////////////////////////////////////// // EBusTraits overrides static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; diff --git a/Code/Framework/AzFramework/AzFramework/Session/SessionNotifications.h b/Code/Framework/AzFramework/AzFramework/Session/SessionNotifications.h index a61c995db7..c472fcb228 100644 --- a/Code/Framework/AzFramework/AzFramework/Session/SessionNotifications.h +++ b/Code/Framework/AzFramework/AzFramework/Session/SessionNotifications.h @@ -24,6 +24,9 @@ namespace AzFramework : public AZ::EBusTraits { public: + // Safeguard handler for multi-threaded use case + using MutexType = AZStd::recursive_mutex; + ////////////////////////////////////////////////////////////////////////// // EBusTraits overrides static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; From b3b5864f763cf5bcb9f14a9f783133d411f73f50 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 1 Jun 2021 11:59:31 -0500 Subject: [PATCH 380/811] Added key checks for the o3de_manifest.json query functions to avoid python exceptions being raised --- scripts/o3de/o3de/manifest.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index 9436e1dd29..2a7e5bba11 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -215,12 +215,12 @@ def get_this_engine() -> dict: def get_engines() -> list: json_data = load_o3de_manifest() - return json_data['engines'] + return json_data['engines'] if 'engines' in json_data else [] def get_projects() -> list: json_data = load_o3de_manifest() - return json_data['projects'] + return json_data['projects'] if 'projects' in json_data else [] def get_gems() -> list: @@ -233,22 +233,22 @@ def get_gems() -> list: def get_external_subdirectories() -> list: json_data = load_o3de_manifest() - return json_data['external_subdirectories'] + return json_data['external_subdirectories'] if 'external_subdirectories' in json_data else [] def get_templates() -> list: json_data = load_o3de_manifest() - return json_data['templates'] + return json_data['templates'] if 'templates' in json_data else [] def get_restricted() -> list: json_data = load_o3de_manifest() - return json_data['restricted'] + return json_data['restricted'] if 'restricted' in json_data else [] def get_repos() -> list: json_data = load_o3de_manifest() - return json_data['repos'] + return json_data['repos'] if 'repos' in json_data else [] # engine.json queries def get_engine_projects() -> list: From 810d6a8deb2da1dbdbe365e3f42cc240c2c7231e Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 1 Jun 2021 12:04:08 -0500 Subject: [PATCH 381/811] Moved the add_gem_dependency and remove_gem_dependency methods to the cmake.py file Fixed the add_gem_dependency method to append the newly added gem right after the 'set(ENABLED_GEMS...' line --- scripts/o3de/o3de/cmake.py | 91 +++++++++++++++++++++++++++++++- scripts/o3de/o3de/disable_gem.py | 36 +------------ scripts/o3de/o3de/enable_gem.py | 54 +------------------ 3 files changed, 92 insertions(+), 89 deletions(-) diff --git a/scripts/o3de/o3de/cmake.py b/scripts/o3de/o3de/cmake.py index dfcce708eb..f8e8d6ce0c 100644 --- a/scripts/o3de/o3de/cmake.py +++ b/scripts/o3de/o3de/cmake.py @@ -21,6 +21,95 @@ from o3de import manifest logger = logging.getLogger() logging.basicConfig() +enable_gem_start_marker = 'set(ENABLED_GEMS' +enable_gem_end_marker = ')' + + +def add_gem_dependency(cmake_file: pathlib.Path, + gem_name: str) -> int: + """ + adds a gem dependency to a cmake file + :param cmake_file: path to the cmake file + :param gem_name: name of the gem + :return: 0 for success or non 0 failure code + """ + if not cmake_file.is_file(): + logger.error(f'Failed to locate cmake file {str(cmake_file)}') + return 1 + + # on a line by basis, see if there already is {gem_name} + # find the first occurrence of a gem, copy its formatting and replace + # the gem name with the new one and append it + # if the gem is already present fail + t_data = [] + added = False + line_index_to_append = None + with open(cmake_file, 'r') as s: + line_index = 0 + for line in s: + if line.strip().startswith(enable_gem_start_marker): + line_index_to_append = line_index + if f'{gem_name}' == line.strip(): + logger.warning(f'{gem_name} is already enabled in file {str(cmake_file)}.') + return 0 + t_data.append(line) + line_index += 1 + + + indent = 4 + if line_index_to_append: + # Insert the gem after the 'set(ENABLED_GEMS)...` line + t_data.insert(line_index_to_append + 1, f'{" " * indent}{gem_name}\n') + added = True + + # if we didn't add, then create a new set(ENABLED_GEMS) variable + # add a new gem, if empty the correct format is 1 tab=4spaces + if not added: + t_data.append('\n') + t_data.append(f'{enable_gem_start_marker}\n') + t_data.append(f'{" " * indent}{gem_name}\n') + t_data.append(f'{enable_gem_end_marker}\n') + + # write the cmake + with open(cmake_file, 'w') as s: + s.writelines(t_data) + + return 0 + +def remove_gem_dependency(cmake_file: pathlib.Path, + gem_name: str) -> int: + """ + removes a gem dependency from a cmake file + :param cmake_file: path to the cmake file + :param gem_name: name of the gem + :return: 0 for success or non 0 failure code + """ + if not cmake_file.is_file(): + logger.error(f'Failed to locate cmake file {cmake_file}') + return 1 + + # on a line by basis, remove any line with {gem_name} + t_data = [] + # Remove the gem from the enabled_gem file by skipping the gem name entry + removed = False + with open(cmake_file, 'r') as s: + for line in s: + if gem_name == line.strip(): + removed = True + else: + t_data.append(line) + + if not removed: + logger.error(f'Failed to remove {gem_name} from cmake file {cmake_file}') + return 1 + + # write the cmake + with open(cmake_file, 'w') as s: + s.writelines(t_data) + + return 0 + + def get_project_gems(project_path: pathlib.Path, platform: str = 'Common') -> set: return get_gems_from_cmake_file(get_enabled_gem_cmake_file(project_path=project_path, platform=platform)) @@ -38,8 +127,6 @@ def get_enabled_gems(cmake_file: pathlib.Path) -> set: logger.error(f'Failed to locate cmake file {cmake_file}') return set() - enable_gem_start_marker = 'set(ENABLED_GEMS' - enable_gem_end_marker = ')' gem_target_set = set() with cmake_file.open('r') as s: in_gem_list = False diff --git a/scripts/o3de/o3de/disable_gem.py b/scripts/o3de/o3de/disable_gem.py index 61d71445f0..82fe9c8ac6 100644 --- a/scripts/o3de/o3de/disable_gem.py +++ b/scripts/o3de/o3de/disable_gem.py @@ -24,40 +24,6 @@ logger = logging.getLogger() logging.basicConfig() -def remove_gem_dependency(cmake_file: pathlib.Path, - gem_name: str) -> int: - """ - removes a gem dependency from a cmake file - :param cmake_file: path to the cmake file - :param gem_name: name of the gem - :return: 0 for success or non 0 failure code - """ - if not cmake_file.is_file(): - logger.error(f'Failed to locate cmake file {cmake_file}') - return 1 - - # on a line by basis, remove any line with {gem_name} - t_data = [] - # Remove the gem from the enabled_gem file by skipping the gem name entry - removed = False - with open(cmake_file, 'r') as s: - for line in s: - if gem_name == line.strip(): - removed = True - else: - t_data.append(line) - - if not removed: - logger.error(f'Failed to remove {gem_name} from cmake file {cmake_file}') - return 1 - - # write the cmake - with open(cmake_file, 'w') as s: - s.writelines(t_data) - - return 0 - - def disable_gem_in_project(gem_name: str = None, gem_path: pathlib.Path = None, project_name: str = None, @@ -128,7 +94,7 @@ def disable_gem_in_project(gem_name: str = None, logger.error(f'Enabled gem file {enabled_gem_file} is not present.') return 1 # remove the gem - error_code = remove_gem_dependency(enabled_gem_file, gem_json_data['gem_name']) + error_code = cmake.remove_gem_dependency(enabled_gem_file, gem_json_data['gem_name']) if error_code: ret_val = error_code diff --git a/scripts/o3de/o3de/enable_gem.py b/scripts/o3de/o3de/enable_gem.py index 0dee01e05e..0e007f6370 100644 --- a/scripts/o3de/o3de/enable_gem.py +++ b/scripts/o3de/o3de/enable_gem.py @@ -24,56 +24,6 @@ from o3de import cmake, manifest, validation logger = logging.getLogger() logging.basicConfig() -def add_gem_dependency(cmake_file: pathlib.Path, - gem_name: str) -> int: - """ - adds a gem dependency to a cmake file - :param cmake_file: path to the cmake file - :param gem_name: name of the gem - :return: 0 for success or non 0 failure code - """ - if not cmake_file.is_file(): - logger.error(f'Failed to locate cmake file {str(cmake_file)}') - return 1 - - # on a line by basis, see if there already is {gem_name} - # find the first occurrence of a gem, copy its formatting and replace - # the gem name with the new one and append it - # if the gem is already present fail - t_data = [] - added = False - line_index_to_append = None - with open(cmake_file, 'r') as s: - line_index = 0 - for line in s: - if 'ENABLED_GEMS' in line: - line_index_to_append = line_index - if f'{gem_name}' == line.strip(): - logger.warning(f'{gem_name} is already enabled in file {str(cmake_file)}.') - return 0 - t_data.append(line) - line_index += 1 - - - indent = 4 - if line_index_to_append: - t_data[line_index_to_append] = f'{" " * indent}{gem_name}\n' - added = True - - # if we didn't add, then create a new set(ENABLED_GEMS) variable - # add a new gem, if empty the correct format is 1 tab=4spaces - if not added: - t_data.append('\n') - t_data.append('set(ENABLED_GEMS\n') - t_data.append(f'{" " * indent}{gem_name}\n') - t_data.append(')\n') - - # write the cmake - with open(cmake_file, 'w') as s: - s.writelines(t_data) - - return 0 - def enable_gem_in_project(gem_name: str = None, gem_path: pathlib.Path = None, @@ -141,7 +91,7 @@ def enable_gem_in_project(gem_name: str = None, logger.error(f'Enabled gem file {enabled_gem_file} is not present.') return 1 # add the gem - ret_val = add_gem_dependency(enabled_gem_file, gem_json_data['gem_name']) + ret_val = cmake.add_gem_dependency(enabled_gem_file, gem_json_data['gem_name']) else: # Find the path to enabled gem file. @@ -150,7 +100,7 @@ def enable_gem_in_project(gem_name: str = None, if not project_enabled_gem_file.is_file(): project_enabled_gem_file.touch() # add the gem - ret_val = add_gem_dependency(project_enabled_gem_file, gem_json_data['gem_name']) + ret_val = cmake.add_gem_dependency(project_enabled_gem_file, gem_json_data['gem_name']) return ret_val From bf0df4b36962fa7dcbbe5b62d59e8e65ace2b5ca Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Tue, 1 Jun 2021 16:37:30 -0700 Subject: [PATCH 382/811] Add Android 'gradle' job as a default job (#1082) * Add Android 'gradle' job as a default job * Replace warning about version checking type with string preprocessing of the captured version before comparisons --- cmake/Tools/common.py | 6 +++++- scripts/build/Platform/Android/build_config.json | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/cmake/Tools/common.py b/cmake/Tools/common.py index 9c0d31cd53..1990041c86 100755 --- a/cmake/Tools/common.py +++ b/cmake/Tools/common.py @@ -316,7 +316,11 @@ def verify_tool(override_tool_path, tool_name, tool_filename, argument_name, too version_match = tool_version_regex.search(version_output) if not version_match: raise RuntimeError() - result_version = LooseVersion(str(version_match.group(1)).strip()) + + + # Since we are doing a compare, strip out any non-numeric and non . character from the version otherwise we will get a TypeError on the LooseVersion comparison + result_version_str = re.sub(r"[^\.0-9]", "", str(version_match.group(1)).strip()) + result_version = LooseVersion(result_version_str) if min_version and result_version < min_version: raise LmbrCmdError(f"The {tool_desc} does not meet the minimum version of {tool_name} required ({str(min_version)}).", diff --git a/scripts/build/Platform/Android/build_config.json b/scripts/build/Platform/Android/build_config.json index b871670cd0..33248ffe26 100644 --- a/scripts/build/Platform/Android/build_config.json +++ b/scripts/build/Platform/Android/build_config.json @@ -136,6 +136,7 @@ }, "gradle": { "TAGS":[ + "default", "weekly-build-metrics" ], "COMMAND":"gradle_windows.cmd", From 9fd690f0048a2d84abdec52271346ab86c28d553 Mon Sep 17 00:00:00 2001 From: srikappa Date: Tue, 1 Jun 2021 17:03:50 -0700 Subject: [PATCH 383/811] Changed a function parameter name --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 12 ++++++------ .../AzToolsFramework/Prefab/PrefabPublicHandler.h | 2 +- .../AzToolsFramework/Prefab/PrefabPublicInterface.h | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index afda2aef09..b44d8fde14 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -973,20 +973,20 @@ namespace AzToolsFramework return AZ::Success(); } - PrefabOperationResult PrefabPublicHandler::DetachPrefab(const AZ::EntityId& entityId) + PrefabOperationResult PrefabPublicHandler::DetachPrefab(const AZ::EntityId& containerEntityId) { - if (!entityId.IsValid()) + if (!containerEntityId.IsValid()) { return AZ::Failure(AZStd::string("Cannot detach Prefab Instance with invalid container entity.")); } - if (IsLevelInstanceContainerEntity(entityId)) + if (IsLevelInstanceContainerEntity(containerEntityId)) { return AZ::Failure(AZStd::string("Cannot detach level Prefab Instance.")); } - InstanceOptionalReference owningInstance = GetOwnerInstanceByEntityId(entityId); - if (owningInstance->get().GetContainerEntityId() != entityId) + InstanceOptionalReference owningInstance = GetOwnerInstanceByEntityId(containerEntityId); + if (owningInstance->get().GetContainerEntityId() != containerEntityId) { return AZ::Failure(AZStd::string("Input entity should be its owning Instance's container entity.")); } @@ -1014,7 +1014,7 @@ namespace AzToolsFramework m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, parentInstance); AZStd::unordered_map oldEntityAliases; - oldEntityAliases.emplace(entityId, instancePtr->GetEntityAlias(entityId)->get()); + oldEntityAliases.emplace(containerEntityId, instancePtr->GetEntityAlias(containerEntityId)->get()); auto containerEntityPtr = instancePtr->DetachContainerEntity(); auto& containerEntity = *containerEntityPtr.release(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index f73af93195..e7b6f8c932 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -64,7 +64,7 @@ namespace AzToolsFramework PrefabOperationResult DeleteEntitiesAndAllDescendantsInInstance(const EntityIdList& entityIds) override; PrefabOperationResult DuplicateEntitiesInInstance(const EntityIdList& entityIds) override; - PrefabOperationResult DetachPrefab(const AZ::EntityId& entityId) override; + PrefabOperationResult DetachPrefab(const AZ::EntityId& containerEntityId) override; private: PrefabOperationResult DeleteFromInstance(const EntityIdList& entityIds, bool deleteDescendants); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h index ad6a28cb3e..1dbed53223 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h @@ -157,10 +157,10 @@ namespace AzToolsFramework * instance and the parent, removing links between this instance and it's nested instances, adding entities directly * owned by this instance under the parent instance. * Bails if the entity is not a container entity or belongs to the level prefab instance. - * @param entityId The container entity id of the instance to detach. + * @param containerEntityId The container entity id of the instance to detach. * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. */ - virtual PrefabOperationResult DetachPrefab(const AZ::EntityId& entityId) = 0; + virtual PrefabOperationResult DetachPrefab(const AZ::EntityId& containerEntityId) = 0; }; } // namespace Prefab From eab3db3d6dbdfdf9d1d179470e8e889c343ebfe1 Mon Sep 17 00:00:00 2001 From: Terry Michaels Date: Tue, 1 Jun 2021 20:19:12 -0500 Subject: [PATCH 384/811] Fixed a few 'too big' dialog issues with various dialogs (#1083) --- Code/Sandbox/Editor/CryEdit.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index c60f32560b..c723e6049a 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -281,6 +281,8 @@ BOOL CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT n [[maybe_unused]] DWORD lFlags, BOOL bOpenFileDialog, [[maybe_unused]] CDocTemplate* pTemplate) { CLevelFileDialog levelFileDialog(bOpenFileDialog); + levelFileDialog.show(); + levelFileDialog.adjustSize(); if (levelFileDialog.exec() == QDialog::Accepted) { @@ -2079,6 +2081,8 @@ void CCryEditApp::OnDocumentationAWSSupport() void CCryEditApp::OnDocumentationFeedback() { FeedbackDialog dialog; + dialog.show(); + dialog.adjustSize(); dialog.exec(); } @@ -3347,6 +3351,8 @@ void CCryEditApp::OnCreateSlice() void CCryEditApp::OnOpenLevel() { CLevelFileDialog levelFileDialog(true); + levelFileDialog.show(); + levelFileDialog.adjustSize(); if (levelFileDialog.exec() == QDialog::Accepted) { From 262c1c1132b153093c863c50945edf4ce128e1f2 Mon Sep 17 00:00:00 2001 From: Mike Chang <62353586+amzn-changml@users.noreply.github.com> Date: Tue, 1 Jun 2021 19:14:13 -0700 Subject: [PATCH 385/811] Change node label for Mac/iOS for new AMI update (#1086) Changes the default node label for Mac/iOS to the newest AMI - This AMI contains updates for XCode and CMake - CMake is now on 3.20.2 --- scripts/build/Platform/Mac/pipeline.json | 2 +- scripts/build/Platform/iOS/pipeline.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/build/Platform/Mac/pipeline.json b/scripts/build/Platform/Mac/pipeline.json index 58f62b421d..81c57002b6 100644 --- a/scripts/build/Platform/Mac/pipeline.json +++ b/scripts/build/Platform/Mac/pipeline.json @@ -1,6 +1,6 @@ { "ENV": { - "NODE_LABEL": "mac", + "NODE_LABEL": "mac-catalina-7ad2e45b", "LY_3RDPARTY_PATH": "/Users/lybuilder/3rdParty", "TIMEOUT": 30, "WORKSPACE": "/Users/lybuilder/workspace", diff --git a/scripts/build/Platform/iOS/pipeline.json b/scripts/build/Platform/iOS/pipeline.json index 58f62b421d..81c57002b6 100644 --- a/scripts/build/Platform/iOS/pipeline.json +++ b/scripts/build/Platform/iOS/pipeline.json @@ -1,6 +1,6 @@ { "ENV": { - "NODE_LABEL": "mac", + "NODE_LABEL": "mac-catalina-7ad2e45b", "LY_3RDPARTY_PATH": "/Users/lybuilder/3rdParty", "TIMEOUT": 30, "WORKSPACE": "/Users/lybuilder/workspace", From 3fcc1b64fce369a6129b9419187f2d78d7d39339 Mon Sep 17 00:00:00 2001 From: mnaumov Date: Tue, 1 Jun 2021 20:24:23 -0700 Subject: [PATCH 386/811] [ATOM-15692] Ebus for registering custom feature processors for thumbnail generation --- .../ThumbnailFeatureProcessorProviderBus.h | 37 +++++++++++++++ .../Rendering/CommonThumbnailRenderer.cpp | 28 ++++++++++++ .../Rendering/CommonThumbnailRenderer.h | 11 ++++- .../ThumbnailRendererSteps/InitializeStep.cpp | 45 ++++++++++--------- 4 files changed, 99 insertions(+), 22 deletions(-) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h new file mode 100644 index 0000000000..71e101bcef --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h @@ -0,0 +1,37 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include +#include + +namespace AZ +{ + namespace LyIntegration + { + namespace Thumbnails + { + //! ThumbnailFeatureProcessorProviderRequests allows registering custom Feature Processors for thumbnail generation + //! Duplicates will be ignored + //! You can check minimal feature processors that are already registered in CommonThumbnailRenderer.cpp + class ThumbnailFeatureProcessorProviderRequests + : public AZ::EBusTraits + { + public: + //! Get a list of custom feature processors to register with thumbnail renderer + virtual const AZStd::vector& GetCustomFeatureProcessors() const = 0; + }; + + using ThumbnailFeatureProcessorProviderBus = AZ::EBus; + } // namespace Thumbnails + } // namespace LyIntegration +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp index 06d54a20b3..b002a0bb66 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp @@ -34,12 +34,34 @@ namespace AZ AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::MaterialAsset::RTTI_Type()); AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::ModelAsset::RTTI_Type()); SystemTickBus::Handler::BusConnect(); + ThumbnailFeatureProcessorProviderBus::Handler::BusConnect(); m_steps[Step::Initialize] = AZStd::make_shared(this); m_steps[Step::FindThumbnailToRender] = AZStd::make_shared(this); m_steps[Step::WaitForAssetsToLoad] = AZStd::make_shared(this); m_steps[Step::Capture] = AZStd::make_shared(this); m_steps[Step::ReleaseResources] = AZStd::make_shared(this); + + m_minimalFeatureProcessors = + { + "AZ::Render::TransformServiceFeatureProcessor", + "AZ::Render::MeshFeatureProcessor", + "AZ::Render::SimplePointLightFeatureProcessor", + "AZ::Render::SimpleSpotLightFeatureProcessor", + "AZ::Render::PointLightFeatureProcessor", + // There is currently a bug where having multiple DirectionalLightFeatureProcessors active can result in shadow + // flickering [ATOM-13568] + // as well as continually rebuilding MeshDrawPackets [ATOM-13633]. Lets just disable the directional light FP for now. + // Possibly re-enable with [GFX TODO][ATOM-13639] + // "AZ::Render::DirectionalLightFeatureProcessor", + "AZ::Render::DiskLightFeatureProcessor", + "AZ::Render::CapsuleLightFeatureProcessor", + "AZ::Render::QuadLightFeatureProcessor", + "AZ::Render::DecalTextureArrayFeatureProcessor", + "AZ::Render::ImageBasedLightFeatureProcessor", + "AZ::Render::PostProcessFeatureProcessor", + "AZ::Render::SkyBoxFeatureProcessor" + }; } CommonThumbnailRenderer::~CommonThumbnailRenderer() @@ -50,6 +72,7 @@ namespace AZ } AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusDisconnect(); SystemTickBus::Handler::BusDisconnect(); + ThumbnailFeatureProcessorProviderBus::Handler::BusDisconnect(); } void CommonThumbnailRenderer::SetStep(Step step) @@ -77,6 +100,11 @@ namespace AZ AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::ExecuteQueuedEvents(); } + const AZStd::vector& CommonThumbnailRenderer::GetCustomFeatureProcessors() const + { + return m_minimalFeatureProcessors; + } + AZStd::shared_ptr CommonThumbnailRenderer::GetData() const { return m_data; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.h index 50e73f4391..249a1f1343 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.h @@ -17,6 +17,8 @@ #include #include +#include + // Disables warning messages triggered by the Qt library // 4251: class needs to have dll-interface to be used by clients of class // 4800: forcing value to bool 'true' or 'false' (performance warning) @@ -34,9 +36,10 @@ namespace AZ //! Provides custom rendering of material and model thumbnails class CommonThumbnailRenderer - : private AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler + : public ThumbnailRendererContext + , private AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler , private SystemTickBus::Handler - , public ThumbnailRendererContext + , private ThumbnailFeatureProcessorProviderBus::Handler { public: AZ_CLASS_ALLOCATOR(CommonThumbnailRenderer, AZ::SystemAllocator, 0) @@ -57,9 +60,13 @@ namespace AZ //! SystemTickBus::Handler interface overrides... void OnSystemTick() override; + //! Render::ThumbnailFeatureProcessorProviderBus::Handler interface overrides... + const AZStd::vector& GetCustomFeatureProcessors() const override; + AZStd::unordered_map> m_steps; Step m_currentStep = Step::None; AZStd::shared_ptr m_data; + AZStd::vector m_minimalFeatureProcessors; }; } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp index 322c765f1b..c35c33017a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp @@ -11,10 +11,16 @@ */ +#include +#include + +#include + #include #include #include #include + #include #include #include @@ -23,10 +29,11 @@ #include #include #include + #include #include -#include -#include +#include + #include #include #include @@ -37,7 +44,6 @@ namespace AZ { namespace Thumbnails { - InitializeStep::InitializeStep(ThumbnailRendererContext* context) : ThumbnailRendererStep(context) { @@ -50,24 +56,23 @@ namespace AZ data->m_entityContext = AZStd::make_unique(); data->m_entityContext->InitContext(); - // Create and register a scene with minimum required feature processors + // Create and register a scene with all required feature processors RPI::SceneDescriptor sceneDesc; - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::TransformServiceFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::MeshFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::SimplePointLightFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::SimpleSpotLightFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::PointLightFeatureProcessor"); - // There is currently a bug where having multiple DirectionalLightFeatureProcessors active can result in shadow flickering [ATOM-13568] - // as well as continually rebuilding MeshDrawPackets [ATOM-13633]. Lets just disable the directional light FP for now. - // Possibly re-enable with [GFX TODO][ATOM-13639] - // sceneDesc.m_featureProcessorNames.push_back("AZ::Render::DirectionalLightFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::DiskLightFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::CapsuleLightFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::QuadLightFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::DecalTextureArrayFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::ImageBasedLightFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::PostProcessFeatureProcessor"); - sceneDesc.m_featureProcessorNames.push_back("AZ::Render::SkyBoxFeatureProcessor"); + + AZ::EBusAggregateResults> results; + ThumbnailFeatureProcessorProviderBus::BroadcastResult(results, &ThumbnailFeatureProcessorProviderBus::Handler::GetCustomFeatureProcessors); + + AZStd::set featureProcessorNames; + for (auto& resultCollection : results.values) + { + for (auto& featureProcessorName : resultCollection) + { + if (featureProcessorNames.emplace(featureProcessorName).second) + { + sceneDesc.m_featureProcessorNames.push_back(featureProcessorName); + } + } + } data->m_scene = RPI::Scene::CreateScene(sceneDesc); From d7ae88c17b1ce1c5c59f293a0575cee9f4ea0937 Mon Sep 17 00:00:00 2001 From: mnaumov Date: Tue, 1 Jun 2021 20:24:52 -0700 Subject: [PATCH 387/811] Adding cmake change --- .../Code/atomlyintegration_commonfeatures_editor_files.cmake | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index e58f72a121..9072cd54f2 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -10,11 +10,12 @@ # set(FILES + Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h + Include/AtomLyIntegration/CommonFeatures/ReflectionProbe/EditorReflectionProbeBus.h + Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h Source/Module.cpp Source/Animation/EditorAttachmentComponent.h Source/Animation/EditorAttachmentComponent.cpp - Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h - Include/AtomLyIntegration/CommonFeatures/ReflectionProbe/EditorReflectionProbeBus.h Source/EditorCommonFeaturesSystemComponent.h Source/EditorCommonFeaturesSystemComponent.cpp Source/CoreLights/EditorAreaLightComponent.h From 553318ed17f5e5673a2b4d73a46a96d804e21e36 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Tue, 1 Jun 2021 14:01:52 +0200 Subject: [PATCH 388/811] [LYN-2514] Extending gem model * Added was previously added state for gems. * Added helpers to add/remove gems from the model. * Helpers for extracting the gem model indices to be added/removed. --- .../Source/GemCatalog/GemModel.cpp | 65 +++++++++++++++++-- .../Source/GemCatalog/GemModel.h | 15 ++++- 2 files changed, 73 insertions(+), 7 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp index df11c4c7a6..6c09c95572 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp @@ -38,6 +38,7 @@ namespace O3DE::ProjectManager item->setData(aznumeric_cast(gemInfo.m_platforms), RolePlatforms); item->setData(aznumeric_cast(gemInfo.m_types), RoleTypes); item->setData(gemInfo.m_summary, RoleSummary); + item->setData(false, RoleWasPreviouslyAdded); item->setData(gemInfo.m_isAdded, RoleIsAdded); item->setData(gemInfo.m_directoryLink, RoleDirectoryLink); item->setData(gemInfo.m_documentationLink, RoleDocLink); @@ -47,6 +48,7 @@ namespace O3DE::ProjectManager item->setData(gemInfo.m_lastUpdatedDate, RoleLastUpdated); item->setData(gemInfo.m_binarySizeInKB, RoleBinarySize); item->setData(gemInfo.m_features, RoleFeatures); + item->setData(gemInfo.m_path, RolePath); appendRow(item); @@ -89,11 +91,6 @@ namespace O3DE::ProjectManager return modelIndex.data(RoleSummary).toString(); } - bool GemModel::IsAdded(const QModelIndex& modelIndex) - { - return modelIndex.data(RoleIsAdded).toBool(); - } - QString GemModel::GetDirectoryLink(const QModelIndex& modelIndex) { return modelIndex.data(RoleDirectoryLink).toString(); @@ -180,4 +177,62 @@ namespace O3DE::ProjectManager { return modelIndex.data(RoleFeatures).toStringList(); } + + QString GemModel::GetPath(const QModelIndex& modelIndex) + { + return modelIndex.data(RolePath).toString(); + } + + bool GemModel::IsAdded(const QModelIndex& modelIndex) + { + return modelIndex.data(RoleIsAdded).toBool(); + } + + void GemModel::SetIsAdded(QAbstractItemModel& model, const QModelIndex& modelIndex, bool isAdded) + { + model.setData(modelIndex, isAdded, RoleIsAdded); + } + + void GemModel::SetWasPreviouslyAdded(QAbstractItemModel& model, const QModelIndex& modelIndex, bool wasAdded) + { + model.setData(modelIndex, wasAdded, RoleWasPreviouslyAdded); + } + + bool GemModel::NeedsToBeAdded(const QModelIndex& modelIndex) + { + return (!modelIndex.data(RoleWasPreviouslyAdded).toBool() && modelIndex.data(RoleIsAdded).toBool()); + } + + bool GemModel::NeedsToBeRemoved(const QModelIndex& modelIndex) + { + return (modelIndex.data(RoleWasPreviouslyAdded).toBool() && !modelIndex.data(RoleIsAdded).toBool()); + } + + QVector GemModel::GatherGemsToBeAdded() const + { + QVector result; + for (int row = 0; row < rowCount(); ++row) + { + const QModelIndex modelIndex = index(row, 0); + if (NeedsToBeAdded(modelIndex)) + { + result.push_back(modelIndex); + } + } + return result; + } + + QVector GemModel::GatherGemsToBeRemoved() const + { + QVector result; + for (int row = 0; row < rowCount(); ++row) + { + const QModelIndex modelIndex = index(row, 0); + if (NeedsToBeRemoved(modelIndex)) + { + result.push_back(modelIndex); + } + } + return result; + } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h index 0caa399b58..77f973a91c 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h @@ -46,13 +46,22 @@ namespace O3DE::ProjectManager static GemInfo::Platforms GetPlatforms(const QModelIndex& modelIndex); static GemInfo::Types GetTypes(const QModelIndex& modelIndex); static QString GetSummary(const QModelIndex& modelIndex); - static bool IsAdded(const QModelIndex& modelIndex); static QString GetDirectoryLink(const QModelIndex& modelIndex); static QString GetDocLink(const QModelIndex& modelIndex); static QString GetVersion(const QModelIndex& modelIndex); static QString GetLastUpdated(const QModelIndex& modelIndex); static int GetBinarySizeInKB(const QModelIndex& modelIndex); static QStringList GetFeatures(const QModelIndex& modelIndex); + static QString GetPath(const QModelIndex& modelIndex); + + static bool IsAdded(const QModelIndex& modelIndex); + static void SetIsAdded(QAbstractItemModel& model, const QModelIndex& modelIndex, bool isAdded); + static void SetWasPreviouslyAdded(QAbstractItemModel& model, const QModelIndex& modelIndex, bool wasAdded); + static bool NeedsToBeAdded(const QModelIndex& modelIndex); + static bool NeedsToBeRemoved(const QModelIndex& modelIndex); + + QVector GatherGemsToBeAdded() const; + QVector GatherGemsToBeRemoved() const; private: enum UserRole @@ -62,6 +71,7 @@ namespace O3DE::ProjectManager RoleGemOrigin, RolePlatforms, RoleSummary, + RoleWasPreviouslyAdded, RoleIsAdded, RoleDirectoryLink, RoleDocLink, @@ -71,7 +81,8 @@ namespace O3DE::ProjectManager RoleLastUpdated, RoleBinarySize, RoleFeatures, - RoleTypes + RoleTypes, + RolePath }; QHash m_nameToIndexMap; From 7b6226a8aa5f7d7f504c1c6a975abfeff00c4d96 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Tue, 1 Jun 2021 14:03:11 +0200 Subject: [PATCH 389/811] [LYN-2514] GemCatalog: Item delegate changes enabled/disabled state in the gem model When clicking the button on the right side of the gem item delegate, it changes the enabled/disabled state of the gem in the model. --- .../Source/GemCatalog/GemItemDelegate.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp index 57200e3b36..0fc0d89fcb 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp @@ -131,6 +131,22 @@ namespace O3DE::ProjectManager return false; } + if (event->type() == QEvent::MouseButtonPress) + { + QMouseEvent* mouseEvent = static_cast(event); + + QRect fullRect, itemRect, contentRect; + CalcRects(option, fullRect, itemRect, contentRect); + const QRect buttonRect = CalcButtonRect(contentRect); + + if (buttonRect.contains(mouseEvent->pos())) + { + const bool isAdded = GemModel::IsAdded(modelIndex); + GemModel::SetIsAdded(*model, modelIndex, !isAdded); + return true; + } + } + return QStyledItemDelegate::editorEvent(event, model, option, modelIndex); } From 0f699cfd470701f21dc6c2e498e9cde9dfa5361d Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Wed, 2 Jun 2021 08:35:59 +0200 Subject: [PATCH 390/811] [LYN-4157] EMotionFX: Adding/removing colliders to/from ragdoll and saving the actor crashes the Editor (#1055) The actor dirty flag was set to true even after saving the asset info which resulted in the save dirty files dialog to appear providing the user to save the actor another time, just after saving it which is confusing. This might have led to rendering an already deleted actor and the crash. Though, I was not able to stably reproduce the issue and can't reproduce it anymore after this fix. --- .../Tools/EMotionStudio/EMStudioSDK/Source/Commands.cpp | 4 ++++ 1 file changed, 4 insertions(+) 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 294f4c7c99..46760af8f0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Commands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Commands.cpp @@ -218,6 +218,10 @@ namespace EMStudio } const bool saveResult = manifest.SaveToFile(manifestFilename.c_str()); + if (saveResult) + { + actor->SetDirtyFlag(false); + } // Source Control: Add file in case it did not exist before (when saving it the first time). if (saveResult && !fileExisted) From 982c30eefdbe3364c55265e690bcec576b6a2dc6 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Tue, 1 Jun 2021 23:43:27 -0700 Subject: [PATCH 391/811] Added a visibility result flag to RPI::Cullable, set to true if the object passed all culling tests. --- .../Code/Include/Atom/RPI.Public/Culling.h | 3 +++ .../RPI/Code/Source/RPI.Public/Culling.cpp | 25 ++++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h index 3f03fb9dcb..295797d2dd 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h @@ -96,6 +96,9 @@ namespace AZ }; LodData m_lodData; + //! Flag indicating if the object is visible, i.e., was not culled out in the last frame + bool m_isVisible = true; + void SetDebugName([[maybe_unused]] const AZ::Name& debugName) { #ifdef AZ_CULL_DEBUG_ENABLED diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index 79d152f661..85b6bf07b8 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -315,21 +315,29 @@ namespace AZ //Add all objects within this node to the view, without any extra culling for (AzFramework::VisibilityEntry* visibleEntry : nodeData.m_entries) { -#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED - if (TestOcclusionCulling(visibleEntry) == MaskedOcclusionCulling::CullingResult::VISIBLE) -#endif { if (visibleEntry->m_typeFlags & AzFramework::VisibilityEntry::TYPE_RPI_Cullable) { Cullable* c = static_cast(visibleEntry->m_userData); + + // reset visibility flag to false, update to true if all culling checks pass + c->m_isVisible = false; + if ((c->m_cullData.m_drawListMask & drawListMask).none() || c->m_cullData.m_hideFlags & viewFlags || c->m_cullData.m_scene != m_jobData->m_scene) //[GFX_TODO][ATOM-13796] once the IVisibilitySystem supports multiple octree scenes, remove this { continue; } - numDrawPackets += AddLodDataToView(c->m_cullData.m_boundingSphere.GetCenter(), c->m_lodData, *m_jobData->m_view); - ++numVisibleCullables; + +#if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED + if (TestOcclusionCulling(visibleEntry) == MaskedOcclusionCulling::CullingResult::VISIBLE) +#endif + { + numDrawPackets += AddLodDataToView(c->m_cullData.m_boundingSphere.GetCenter(), c->m_lodData, *m_jobData->m_view); + ++numVisibleCullables; + c->m_isVisible = true; + } } } } @@ -342,6 +350,10 @@ namespace AZ if (visibleEntry->m_typeFlags & AzFramework::VisibilityEntry::TYPE_RPI_Cullable) { Cullable* c = static_cast(visibleEntry->m_userData); + + // reset visibility flag to false, update to true if all culling checks pass + c->m_isVisible = false; + if ((c->m_cullData.m_drawListMask & drawListMask).none() || c->m_cullData.m_hideFlags & viewFlags || c->m_cullData.m_scene != m_jobData->m_scene) //[GFX_TODO][ATOM-13796] once the IVisibilitySystem supports multiple octree scenes, remove this @@ -362,6 +374,7 @@ namespace AZ { numDrawPackets += AddLodDataToView(c->m_cullData.m_boundingSphere.GetCenter(), c->m_lodData, *m_jobData->m_view); ++numVisibleCullables; + c->m_isVisible = true; } } } @@ -461,11 +474,11 @@ namespace AZ corners[7] = m_jobData->m_view->GetWorldToClipMatrix() * Vector4(maxBound.GetX(), maxBound.GetY(), minBound.GetZ(), 1.0f); // find min clip-space depth and NDC min/max + float minDepth = FLT_MAX; float ndcMinX = FLT_MAX; float ndcMinY = FLT_MAX; float ndcMaxX = -FLT_MAX; float ndcMaxY = -FLT_MAX; - float minDepth = FLT_MAX; for (uint32_t index = 0; index < 8; ++index) { minDepth = AZStd::min(minDepth, corners[index].GetW()); From 4a5b7edbfe864c6a5bbb38824302ac22644394ca Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Wed, 2 Jun 2021 09:20:45 +0100 Subject: [PATCH 392/811] Updates to kd-tree ray intersection - ATOM-15673 (#1026) * updates to kd-tree ray intersection * update tests for kd-tree * add one more test for kd-tree intersection * updates to ModelKdTree following review feedback * improve api doc comment for RayIntersection in ModelKdTree * updates following review feedback * update .clang-format to stack parameters if they do not all fit on one line --- .clang-format | 1 + .../Atom/RPI.Reflect/Model/ModelKdTree.h | 20 +++++- .../Code/Source/RPI.Public/Model/Model.cpp | 9 ++- .../Source/RPI.Reflect/Model/ModelKdTree.cpp | 71 ++++++++++++------- Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp | 69 ++++++++++++++++-- .../Code/Source/Mesh/EditorMeshComponent.cpp | 9 ++- .../Source/Mesh/MeshComponentController.cpp | 8 +-- 7 files changed, 143 insertions(+), 44 deletions(-) diff --git a/.clang-format b/.clang-format index 04e0284f97..ef3ce64192 100644 --- a/.clang-format +++ b/.clang-format @@ -13,6 +13,7 @@ AllowShortFunctionsOnASingleLine: None AllowShortLambdasOnASingleLine: None AlwaysBreakAfterReturnType: None AlwaysBreakTemplateDeclarations: true +BinPackParameters: false BreakBeforeBraces: Custom BraceWrapping: AfterClass: true diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelKdTree.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelKdTree.h index 9cd33eda6c..832681d7f1 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelKdTree.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelKdTree.h @@ -35,7 +35,15 @@ namespace AZ ModelKdTree() = default; bool Build(const ModelAsset* model); - bool RayIntersection(const AZ::Vector3& raySrc, const AZ::Vector3& rayDir, float& distance, AZ::Vector3& normal) const; + //! Return if a ray intersected the model. + //! @param raySrc The starting point of the ray. + //! @param rayDir The direction and length of the ray (magnitude is encoded in the direction). + //! @param[out] The normalized distance of the intersection (in the range 0.0-1.0) - to calculate the actual + //! distance, multiply distanceNormalized by the magnitude of rayDir. + //! @param[out] The surface normal of the intersection with the model. + //! @return Return true if there was an intersection with the model, false otherwise. + bool RayIntersection( + const AZ::Vector3& raySrc, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const; void GetPenetratedBoxes(const AZ::Vector3& raySrc, const AZ::Vector3& rayDir, AZStd::vector& outBoxes); enum ESplitAxis @@ -53,8 +61,14 @@ namespace AZ private: void BuildRecursively(ModelKdTreeNode* pNode, const AZ::Aabb& boundbox, AZStd::vector& indices); - bool RayIntersectionRecursively(ModelKdTreeNode* pNode, const AZ::Vector3& raySrc, const AZ::Vector3& rayDir, float& distance, AZ::Vector3& normal) const; - void GetPenetratedBoxesRecursively(ModelKdTreeNode* pNode, const AZ::Vector3& raySrc, const AZ::Vector3& rayDir, AZStd::vector& outBoxes); + bool RayIntersectionRecursively( + ModelKdTreeNode* pNode, + const AZ::Vector3& raySrc, + const AZ::Vector3& rayDir, + float& distanceNormalized, + AZ::Vector3& normal) const; + void GetPenetratedBoxesRecursively( + ModelKdTreeNode* pNode, const AZ::Vector3& raySrc, const AZ::Vector3& rayDir, AZStd::vector& outBoxes); void ConstructMeshList(const ModelAsset* model, const AZ::Transform& matParent); static const int s_MinimumVertexSizeInLeafNode = 3 * 10; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp index 15c8aaf528..86477bf785 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp @@ -140,8 +140,9 @@ namespace AZ bool Model::LocalRayIntersection(const AZ::Vector3& rayStart, const AZ::Vector3& dir, float& distance, AZ::Vector3& normal) const { AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); - float firstHit; - const int result = Intersect::IntersectRayAABB2(rayStart, dir.GetReciprocal(), m_aabb, firstHit, distance); + float start; + float end; + const int result = Intersect::IntersectRayAABB2(rayStart, dir.GetReciprocal(), m_aabb, start, end); if (Intersect::ISECT_RAY_AABB_NONE != result) { if (ModelAsset* modelAssetPtr = m_modelAsset.Get()) @@ -164,7 +165,9 @@ namespace AZ return false; } - bool Model::RayIntersection(const AZ::Transform& modelTransform, const AZ::Vector3& nonUniformScale, const AZ::Vector3& rayStart, const AZ::Vector3& dir, float& distanceFactor, AZ::Vector3& normal) const + bool Model::RayIntersection( + const AZ::Transform& modelTransform, const AZ::Vector3& nonUniformScale, const AZ::Vector3& rayStart, const AZ::Vector3& dir, + float& distanceFactor, AZ::Vector3& normal) const { AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); const AZ::Vector3 clampedScale = nonUniformScale.GetMax(AZ::Vector3(AZ::MinTransformScale)); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelKdTree.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelKdTree.cpp index 6a1897815f..bee489c2fd 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelKdTree.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelKdTree.cpp @@ -11,6 +11,7 @@ */ #include +#include #include #include @@ -191,10 +192,10 @@ namespace AZ if (ModelLodAsset* lodAssetPtr = model->GetLodAssets()[0].Get()) { - AZ_Warning("ModelKdTree", lodAssetPtr->GetMeshes().size() <= std::numeric_limits::max() + 1, + AZ_Warning("ModelKdTree", lodAssetPtr->GetMeshes().size() <= AZStd::numeric_limits::max() + 1, "KdTree generation doesn't support models with greater than 256 meshes. RayIntersection results will be incorrect " "unless the meshes are merged or broken up into multiple models"); - const size_t size = AZStd::min(lodAssetPtr->GetMeshes().size(), std::numeric_limits::max() + 1); + const size_t size = AZStd::min(lodAssetPtr->GetMeshes().size(), AZStd::numeric_limits::max() + 1); m_meshes.reserve(size); AZStd::transform( lodAssetPtr->GetMeshes().begin(), AZStd::next(lodAssetPtr->GetMeshes().begin(), size), @@ -204,20 +205,42 @@ namespace AZ } } - bool ModelKdTree::RayIntersection(const AZ::Vector3& raySrc, const AZ::Vector3& rayDir, float& distance, AZ::Vector3& normal) const + bool ModelKdTree::RayIntersection( + const AZ::Vector3& raySrc, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const { - return RayIntersectionRecursively(m_pRootNode.get(), raySrc, rayDir, distance, normal); + float closestDistanceNormalized = AZStd::numeric_limits::max(); + if (RayIntersectionRecursively(m_pRootNode.get(), raySrc, rayDir, closestDistanceNormalized, normal)) + { + distanceNormalized = closestDistanceNormalized; + return true; + } + + return false; } - bool ModelKdTree::RayIntersectionRecursively(ModelKdTreeNode* pNode, const AZ::Vector3& raySrc, const AZ::Vector3& rayDir, float& distance, AZ::Vector3& normal) const + bool ModelKdTree::RayIntersectionRecursively( + ModelKdTreeNode* pNode, + const AZ::Vector3& raySrc, + const AZ::Vector3& rayDir, + float& distanceNormalized, + AZ::Vector3& normal) const { + using Intersect::IntersectRayAABB2; + using Intersect::IntersectSegmentTriangleCCW; + using Intersect::ISECT_RAY_AABB_NONE; + if (!pNode) { return false; } float start, end; - if (AZ::Intersect::IntersectRayAABB2(raySrc, rayDir.GetReciprocal(), pNode->GetBoundBox(), start, end) == Intersect::ISECT_RAY_AABB_NONE) + if (IntersectRayAABB2(raySrc, rayDir.GetReciprocal(), pNode->GetBoundBox(), start, end) == ISECT_RAY_AABB_NONE) + { + return false; + } + + if (start > distanceNormalized) { return false; } @@ -235,17 +258,13 @@ namespace AZ return false; } - AZ::Vector3 intersectionNormal; - float hitDistanceNormalized; - const float maxDist(FLT_MAX); - float nearestDist = maxDist; - + float nearestDistanceNormalized = distanceNormalized; for (AZ::u32 i = 0; i < nVBuffSize; ++i) { const auto& [first, second, third] = pNode->GetVertexIndex(i); const AZ::u32 nObjIndex = pNode->GetObjIndex(i); - AZStd::array_view positionBuffer = m_meshes[nObjIndex].m_vertexData; + const AZStd::array_view positionBuffer = m_meshes[nObjIndex].m_vertexData; if (positionBuffer.empty()) { @@ -258,25 +277,23 @@ namespace AZ AZ::Vector3{positionBuffer[third * 3 + 0], positionBuffer[third * 3 + 1], positionBuffer[third * 3 + 2]}, }; - const AZ::Vector3 rayEnd = raySrc + rayDir * distance; - - if (AZ::Intersect::IntersectSegmentTriangleCCW(raySrc, rayEnd, trianglePoints[0], trianglePoints[1], trianglePoints[2], - intersectionNormal, hitDistanceNormalized) != Intersect::ISECT_RAY_AABB_NONE) + float hitDistanceNormalized; + AZ::Vector3 intersectionNormal; + const AZ::Vector3 rayEnd = raySrc + rayDir; + if (IntersectSegmentTriangleCCW(raySrc, rayEnd, trianglePoints[0], trianglePoints[1], trianglePoints[2], + intersectionNormal, hitDistanceNormalized) != ISECT_RAY_AABB_NONE) { - float hitDistance = hitDistanceNormalized * distance; - - if (nearestDist > hitDistance) + if (nearestDistanceNormalized > hitDistanceNormalized) { normal = intersectionNormal; + nearestDistanceNormalized = hitDistanceNormalized; } - - nearestDist = AZStd::GetMin(nearestDist, hitDistance); } } - if (nearestDist < maxDist) + if (nearestDistanceNormalized < distanceNormalized) { - distance = AZStd::GetMin(distance, nearestDist); + distanceNormalized = nearestDistanceNormalized; return true; } @@ -284,8 +301,8 @@ namespace AZ } // running both sides to find the closest intersection - const bool bFoundChild0 = RayIntersectionRecursively(pNode->GetChild(0), raySrc, rayDir, distance, normal); - const bool bFoundChild1 = RayIntersectionRecursively(pNode->GetChild(1), raySrc, rayDir, distance, normal); + const bool bFoundChild0 = RayIntersectionRecursively(pNode->GetChild(0), raySrc, rayDir, distanceNormalized, normal); + const bool bFoundChild1 = RayIntersectionRecursively(pNode->GetChild(1), raySrc, rayDir, distanceNormalized, normal); return bFoundChild0 || bFoundChild1; } @@ -311,5 +328,5 @@ namespace AZ GetPenetratedBoxesRecursively(pNode->GetChild(0), raySrc, rayDir, outBoxes); GetPenetratedBoxesRecursively(pNode->GetChild(1), raySrc, rayDir, outBoxes); } - } -} + } // namespace RPI +} // namespace AZ diff --git a/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp b/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp index 1ec14c6169..3ce17bee8b 100644 --- a/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp @@ -1074,13 +1074,13 @@ namespace UnitTest } }; - class KdTreeIntersectsFixture + class KdTreeIntersectsParameterizedFixture : public ModelTests , public ::testing::WithParamInterface { }; - TEST_P(KdTreeIntersectsFixture, KdTreeIntersects) + TEST_P(KdTreeIntersectsParameterizedFixture, KdTreeIntersects) { TwoSeparatedPlanesMesh mesh; @@ -1090,7 +1090,10 @@ namespace UnitTest float distance = AZStd::numeric_limits::max(); AZ::Vector3 normal; - EXPECT_THAT(kdTree.RayIntersection(AZ::Vector3(GetParam().xpos, GetParam().ypos, GetParam().zpos), AZ::Vector3::CreateAxisZ(-1.0f), distance, normal), testing::Eq(GetParam().expectedShouldIntersect)); + EXPECT_THAT( + kdTree.RayIntersection( + AZ::Vector3(GetParam().xpos, GetParam().ypos, GetParam().zpos), AZ::Vector3::CreateAxisZ(-1.0f), distance, normal), + testing::Eq(GetParam().expectedShouldIntersect)); EXPECT_THAT(distance, testing::FloatEq(GetParam().expectedDistance)); } @@ -1119,5 +1122,63 @@ namespace UnitTest KdTreeIntersectParams{0.778f, 0.111f, 1.0f, 0.5f, true}, KdTreeIntersectParams{0.778f, 0.778f, 1.0f, 0.5f, true}, }; - INSTANTIATE_TEST_CASE_P(KdTreeIntersectsPlane, KdTreeIntersectsFixture, ::testing::ValuesIn(intersectTestData)); + + INSTANTIATE_TEST_CASE_P(KdTreeIntersectsPlane, KdTreeIntersectsParameterizedFixture, ::testing::ValuesIn(intersectTestData)); + + class KdTreeIntersectsFixture + : public ModelTests + { + public: + void SetUp() override + { + ModelTests::SetUp(); + + m_mesh = AZStd::make_unique(); + m_kdTree = AZStd::make_unique(); + ASSERT_TRUE(m_kdTree->Build(m_mesh->GetModel().Get())); + } + + void TearDown() override + { + m_kdTree.reset(); + m_mesh.reset(); + + ModelTests::TearDown(); + } + + AZStd::unique_ptr m_mesh; + AZStd::unique_ptr m_kdTree; + }; + + TEST_F(KdTreeIntersectsFixture, KdTreeIntersectionReturnsNormalizedDistance) + { + float t = AZStd::numeric_limits::max(); + AZ::Vector3 normal; + + constexpr float rayLength = 100.0f; + EXPECT_THAT( + m_kdTree->RayIntersection( + AZ::Vector3::CreateZero(), AZ::Vector3::CreateAxisZ(-rayLength), t, normal), testing::Eq(true)); + EXPECT_THAT(t, testing::FloatEq(0.005f)); + } + + TEST_F(KdTreeIntersectsFixture, KdTreeIntersectionHandlesInvalidStartingNormalizedDistance) + { + float t = -0.5f; // invalid starting distance + AZ::Vector3 normal; + + constexpr float rayLength = 10.0f; + EXPECT_THAT( + m_kdTree->RayIntersection(AZ::Vector3::CreateAxisZ(0.75f), AZ::Vector3::CreateAxisZ(-rayLength), t, normal), testing::Eq(true)); + EXPECT_THAT(t, testing::FloatEq(0.025f)); + } + + TEST_F(KdTreeIntersectsFixture, KdTreeIntersectionDoesNotScaleRayByStartingDistance) + { + float t = 10.0f; // starting distance (used to check it is not read from initially by RayIntersection) + AZ::Vector3 normal; + + EXPECT_THAT( + m_kdTree->RayIntersection(AZ::Vector3::CreateAxisZ(5.0f), -AZ::Vector3::CreateAxisZ(), t, normal), testing::Eq(false)); + } } // namespace UnitTest diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.cpp index f2ad9a13e6..e1c9026c74 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.cpp @@ -140,9 +140,16 @@ namespace AZ AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); AZ::NonUniformScaleRequestBus::EventResult(nonUniformScale, GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); + float t; AZ::Vector3 ignoreNormal; + constexpr float rayLength = 1000.0f; + if (m_controller.GetModel()->RayIntersection(transform, nonUniformScale, src, dir * rayLength, t, ignoreNormal)) + { + distance = rayLength * t; + return true; + } - return m_controller.GetModel()->RayIntersection(transform, nonUniformScale, src, dir, distance, ignoreNormal); + return false; } bool EditorMeshComponent::SupportsEditorRayIntersect() diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp index c089dd01f9..e7eecd3c7f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp @@ -485,16 +485,12 @@ namespace AZ m_transformInterface->GetWorldTM(), m_cachedNonUniformScale, ray.m_startWorldPosition, ray.m_endWorldPosition - ray.m_startWorldPosition, t, normal)) { - // note: this is a temporary workaround to handle cases where model->RayIntersection - // returns negative distances, follow-up ATOM-15673 - const auto absT = AZStd::abs(t); - // fill in ray result structure after successful intersection const auto intersectionLine = (ray.m_endWorldPosition - ray.m_startWorldPosition); result.m_uv = AZ::Vector2::CreateZero(); - result.m_worldPosition = ray.m_startWorldPosition + intersectionLine * absT; + result.m_worldPosition = ray.m_startWorldPosition + intersectionLine * t; result.m_worldNormal = normal; - result.m_distance = intersectionLine.GetLength() * absT; + result.m_distance = intersectionLine.GetLength() * t; result.m_entityAndComponent = m_entityComponentIdPair; } } From d02ba51d03644b4b60ccac16b4f4ca2020661c36 Mon Sep 17 00:00:00 2001 From: jjjoness <82226755+jjjoness@users.noreply.github.com> Date: Wed, 2 Jun 2021 10:34:08 +0100 Subject: [PATCH 393/811] Changed svg and layout of the new logo. (#1059) --- Code/Sandbox/Editor/StartupLogoDialog.ui | 8 ++-- Code/Sandbox/Editor/o3de_logo.svg | 51 +++++++++++++++--------- 2 files changed, 36 insertions(+), 23 deletions(-) diff --git a/Code/Sandbox/Editor/StartupLogoDialog.ui b/Code/Sandbox/Editor/StartupLogoDialog.ui index 6e01808a84..0815fa8b18 100644 --- a/Code/Sandbox/Editor/StartupLogoDialog.ui +++ b/Code/Sandbox/Editor/StartupLogoDialog.ui @@ -42,14 +42,14 @@ - 161 - 49 + 175 + 66 - 161 - 50 + 175 + 66 diff --git a/Code/Sandbox/Editor/o3de_logo.svg b/Code/Sandbox/Editor/o3de_logo.svg index ba44566ce8..35a880c5c8 100644 --- a/Code/Sandbox/Editor/o3de_logo.svg +++ b/Code/Sandbox/Editor/o3de_logo.svg @@ -1,22 +1,35 @@ - - Group 12 - - - - - - - - - - - - - - - - + + Artboard + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + \ No newline at end of file From ede8daaece0f8348f73d2f3f5c4989f1a8a4c142 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 2 Jun 2021 13:27:55 +0200 Subject: [PATCH 394/811] [LYN-2514] Extending pythin bindings to adapt CLI changes for the gem catalog * Added ExecuteWithLockErrorHandling() which returns an outcome with the actual error we get from python so that we can expose that to the UI. * Added cmake pybind. * Get gems now calling get_all_gems and alphabetically sorting the result. * Added get enabled gems function which first gets the cmake enabled gems file path from the project path and then the list of gem names that are enabled. * Some changes to the enable and disable gem functions. --- .../ProjectManager/Source/PythonBindings.cpp | 125 +++++++++++------- .../ProjectManager/Source/PythonBindings.h | 11 +- .../Source/PythonBindingsInterface.h | 24 ++-- 3 files changed, 101 insertions(+), 59 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index c0481d6c87..e6ebfbefca 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -283,6 +283,7 @@ namespace O3DE::ProjectManager AZ_Warning("ProjectManagerWindow", result != -1, "Append to sys path failed"); // import required modules + m_cmake = pybind11::module::import("o3de.cmake"); m_register = pybind11::module::import("o3de.register"); m_manifest = pybind11::module::import("o3de.manifest"); m_engineTemplate = pybind11::module::import("o3de.engine_template"); @@ -311,7 +312,7 @@ namespace O3DE::ProjectManager return !PyErr_Occurred(); } - bool PythonBindings::ExecuteWithLock(AZStd::function executionCallback) + AZ::Outcome PythonBindings::ExecuteWithLockErrorHandling(AZStd::function executionCallback) { AZStd::lock_guard lock(m_lock); pybind11::gil_scoped_release release; @@ -320,15 +321,20 @@ namespace O3DE::ProjectManager try { executionCallback(); - return true; + return AZ::Success(); } catch ([[maybe_unused]] const std::exception& e) { AZ_Warning("PythonBindings", false, "Python exception %s", e.what()); - return false; + return AZ::Failure(e.what()); } } + bool PythonBindings::ExecuteWithLock(AZStd::function executionCallback) + { + return ExecuteWithLockErrorHandling(executionCallback).IsSuccess(); + } + AZ::Outcome PythonBindings::GetEngineInfo() { EngineInfo engineInfo; @@ -419,7 +425,7 @@ namespace O3DE::ProjectManager return result; } - AZ::Outcome PythonBindings::GetGem(const QString& path) + AZ::Outcome PythonBindings::GetGemInfo(const QString& path) { GemInfo gemInfo = GemInfoFromPath(pybind11::str(path.toStdString())); if (gemInfo.IsValid()) @@ -432,32 +438,59 @@ namespace O3DE::ProjectManager } } - AZ::Outcome> PythonBindings::GetGems() + AZ::Outcome, AZStd::string> PythonBindings::GetAllGemInfos(const QString& projectPath) { QVector gems; - bool result = ExecuteWithLock([&] { - // external gems - for (auto path : m_manifest.attr("get_gems")()) + auto result = ExecuteWithLockErrorHandling([&] { - gems.push_back(GemInfoFromPath(path)); - } + pybind11::str pyProjectPath = projectPath.toStdString(); + for (auto path : m_manifest.attr("get_all_gems")(pyProjectPath)) + { + gems.push_back(GemInfoFromPath(path)); + } + }); + if (!result.IsSuccess()) + { + return AZ::Failure(result.GetError().c_str()); + } - // gems from the engine - for (auto path : m_manifest.attr("get_engine_gems")()) + std::sort(gems.begin(), gems.end()); + return AZ::Success(AZStd::move(gems)); + } + + AZ::Outcome, AZStd::string> PythonBindings::GetEnabledGemNames(const QString& projectPath) + { + // Retrieve the path to the cmake file that lists the enabled gems. + pybind11::str enabledGemsFilename; + auto result = ExecuteWithLockErrorHandling([&] { - gems.push_back(GemInfoFromPath(path)); - } - }); + const pybind11::str pyProjectPath = projectPath.toStdString(); + enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")( + pybind11::none(), // project_name + pyProjectPath); // project_path + }); + if (!result.IsSuccess()) + { + return AZ::Failure(result.GetError().c_str()); + } - if (!result) + // Retrieve the actual list of names from the cmake file. + QVector gemNames; + result = ExecuteWithLockErrorHandling([&] + { + const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename); + for (auto gemName : pyGemNames) + { + gemNames.push_back(Py_To_String(gemName)); + } + }); + if (!result.IsSuccess()) { - return AZ::Failure(); - } - else - { - return AZ::Success(AZStd::move(gems)); + return AZ::Failure(result.GetError().c_str()); } + + return AZ::Success(AZStd::move(gemNames)); } bool PythonBindings::AddProject(const QString& path) @@ -637,38 +670,36 @@ namespace O3DE::ProjectManager } } - bool PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath) + AZ::Outcome PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath) { - bool result = ExecuteWithLock([&] { - pybind11::str pyGemPath = gemPath.toStdString(); - pybind11::str pyProjectPath = projectPath.toStdString(); + return ExecuteWithLockErrorHandling([&] + { + pybind11::str pyGemPath = gemPath.toStdString(); + pybind11::str pyProjectPath = projectPath.toStdString(); - m_enableGemProject.attr("enable_gem_in_project")( - pybind11::none(), // gem_name - pyGemPath, - pybind11::none(), // project_name - pyProjectPath - ); - }); - - return result; + m_enableGemProject.attr("enable_gem_in_project")( + pybind11::none(), // gem name not needed as path is provided + pyGemPath, + pybind11::none(), // project name not needed as path is provided + pyProjectPath + ); + }); } - bool PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath) + AZ::Outcome PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath) { - bool result = ExecuteWithLock([&] { - pybind11::str pyGemPath = gemPath.toStdString(); - pybind11::str pyProjectPath = projectPath.toStdString(); + return ExecuteWithLockErrorHandling([&] + { + pybind11::str pyGemPath = gemPath.toStdString(); + pybind11::str pyProjectPath = projectPath.toStdString(); - m_disableGemProject.attr("disable_gem_in_project")( - pybind11::none(), // gem_name - pyGemPath, - pybind11::none(), // project_name - pyProjectPath - ); - }); - - return result; + m_disableGemProject.attr("disable_gem_in_project")( + pybind11::none(), // gem name not needed as path is provided + pyGemPath, + pybind11::none(), // project name not needed as path is provided + pyProjectPath + ); + }); } bool PythonBindings::UpdateProject([[maybe_unused]] const ProjectInfo& projectInfo) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h index 18122f484b..44958b0b0f 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.h +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -39,8 +39,9 @@ namespace O3DE::ProjectManager bool SetEngineInfo(const EngineInfo& engineInfo) override; // Gem - AZ::Outcome GetGem(const QString& path) override; - AZ::Outcome> GetGems() override; + AZ::Outcome GetGemInfo(const QString& path) override; + AZ::Outcome, AZStd::string> GetAllGemInfos(const QString& projectPath) override; + AZ::Outcome, AZStd::string> GetEnabledGemNames(const QString& projectPath) override; // Project AZ::Outcome CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo) override; @@ -49,8 +50,8 @@ namespace O3DE::ProjectManager bool AddProject(const QString& path) override; bool RemoveProject(const QString& path) override; bool UpdateProject(const ProjectInfo& projectInfo) override; - bool AddGemToProject(const QString& gemPath, const QString& projectPath) override; - bool RemoveGemFromProject(const QString& gemPath, const QString& projectPath) override; + AZ::Outcome AddGemToProject(const QString& gemPath, const QString& projectPath) override; + AZ::Outcome RemoveGemFromProject(const QString& gemPath, const QString& projectPath) override; // ProjectTemplate AZ::Outcome> GetProjectTemplates() override; @@ -58,6 +59,7 @@ namespace O3DE::ProjectManager private: AZ_DISABLE_COPY_MOVE(PythonBindings); + AZ::Outcome ExecuteWithLockErrorHandling(AZStd::function executionCallback); bool ExecuteWithLock(AZStd::function executionCallback); GemInfo GemInfoFromPath(pybind11::handle path); ProjectInfo ProjectInfoFromPath(pybind11::handle path); @@ -68,6 +70,7 @@ namespace O3DE::ProjectManager AZ::IO::FixedMaxPath m_enginePath; pybind11::handle m_engineTemplate; AZStd::recursive_mutex m_lock; + pybind11::handle m_cmake; pybind11::handle m_register; pybind11::handle m_manifest; pybind11::handle m_enableGemProject; diff --git a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h index a58eea0fe6..2e8347f488 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h +++ b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h @@ -57,13 +57,21 @@ namespace O3DE::ProjectManager * @param path the absolute path to the Gem * @return an outcome with GemInfo on success */ - virtual AZ::Outcome GetGem(const QString& path) = 0; + virtual AZ::Outcome GetGemInfo(const QString& path) = 0; /** - * Get info about all known Gems - * @return an outcome with GemInfos on success + * Get all available gem infos. This concatenates gems registered by the engine and the project. + * @param path The absolute path to the project. + * @return A list of gem infos. */ - virtual AZ::Outcome> GetGems() = 0; + virtual AZ::Outcome, AZStd::string> GetAllGemInfos(const QString& projectPath) = 0; + + /** + * Get a list of all enabled gem names for a given project. + * @param[in] projectPath Absolute file path to the project. + * @return A list of gem names of all the enabled gems for a given project or a error message on failure. + */ + virtual AZ::Outcome, AZStd::string> GetEnabledGemNames(const QString& projectPath) = 0; // Projects @@ -114,17 +122,17 @@ namespace O3DE::ProjectManager * Add a gem to a project * @param gemPath the absolute path to the gem * @param projectPath the absolute path to the project - * @return true on success, false on failure + * @return An outcome with the success flag as well as an error message in case of a failure. */ - virtual bool AddGemToProject(const QString& gemPath, const QString& projectPath) = 0; + virtual AZ::Outcome AddGemToProject(const QString& gemPath, const QString& projectPath) = 0; /** * Remove gem to a project * @param gemPath the absolute path to the gem * @param projectPath the absolute path to the project - * @return true on success, false on failure + * @return An outcome with the success flag as well as an error message in case of a failure. */ - virtual bool RemoveGemFromProject(const QString& gemPath, const QString& projectPath) = 0; + virtual AZ::Outcome RemoveGemFromProject(const QString& gemPath, const QString& projectPath) = 0; // Project Templates From bcdb541b7c9ec6488d6e26b69896bff67c1d1327 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 2 Jun 2021 13:29:10 +0200 Subject: [PATCH 395/811] [LYN-2514] Sorting gems in the gem catalog after retrieving all gem infos Added Date: Wed, 2 Jun 2021 14:46:08 +0100 Subject: [PATCH 396/811] Changed logo and repositioned. (#1061) --- Code/Sandbox/Editor/AboutDialog.ui | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Sandbox/Editor/AboutDialog.ui b/Code/Sandbox/Editor/AboutDialog.ui index 67767c0de1..0b86f15542 100644 --- a/Code/Sandbox/Editor/AboutDialog.ui +++ b/Code/Sandbox/Editor/AboutDialog.ui @@ -75,14 +75,14 @@ - 161 - 49 + 175 + 66 - 161 - 49 + 175 + 66 From 485a45d3c2a12bd7194210939ca75a58f9640bd2 Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 2 Jun 2021 15:32:03 +0100 Subject: [PATCH 397/811] Made some corrections --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 11 +-- .../AssetBrowser/AssetBrowserTableModel.cpp | 10 ++- .../Views/AssetBrowserTableView.cpp | 9 +- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 83 ++++++++++--------- 4 files changed, 60 insertions(+), 53 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 2660b660e4..adb4ae66c4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -26,7 +26,6 @@ AZ_POP_DISABLE_WARNING AZ_CVAR( bool, ed_useNewAssetBrowserTableView, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Use the new AssetBrowser TableView for searching assets."); -#pragma optimize("", off) namespace AzToolsFramework { namespace AssetBrowser @@ -139,7 +138,7 @@ namespace AzToolsFramework { const auto& subFilters = compFilter->GetSubFilters(); - const auto compositeFilterIterator = AZStd::find_if(subFilters.begin(), subFilters.end(), [subFilters](FilterConstType filter) -> bool + const auto compositeFilterIterator = AZStd::find_if(subFilters.cbegin(), subFilters.cend(), [subFilters](FilterConstType filter) -> bool { const auto assetTypeFilter = qobject_cast >(filter); return !assetTypeFilter.isNull(); @@ -150,7 +149,7 @@ namespace AzToolsFramework m_assetTypeFilter = qobject_cast >(*compositeFilterIterator); } - const auto compStringFilterIter = AZStd::find_if(subFilters.begin(), subFilters.end(), [](FilterConstType filter) -> bool + const auto compStringFilterIter = AZStd::find_if(subFilters.cbegin(), subFilters.cend(), [](FilterConstType filter) -> bool { //The real StringFilter is really a CompositeFilter with just one StringFilter in its subfilter list //To know if it is actually a StringFilter we have to get that subfilter and check if it is a Stringfilter. @@ -164,7 +163,7 @@ namespace AzToolsFramework auto strFilter = qobject_cast>(filt); return !strFilter.isNull(); }; - const auto stringSubfliterConstIter = AZStd::find_if(stringSubfilters.begin(), stringSubfilters.end(), canBeCasted); + const auto stringSubfliterConstIter = AZStd::find_if(stringSubfilters.cbegin(), stringSubfilters.cend(), canBeCasted); //A Composite StringFilter will only have just one subfilter and nothing more. if (stringSubfliterConstIter != stringSubfilters.end() && stringSubfilters.size() == 1) @@ -188,8 +187,7 @@ namespace AzToolsFramework } invalidateFilter(); Q_EMIT filterChanged(); - bool isNullAB = m_stringFilter.isNull(); - emit stringFilterPopulated(!isNullAB); + emit stringFilterPopulated(!m_stringFilter.isNull()); } void AssetBrowserFilterModel::filterUpdatedSlot() @@ -209,6 +207,5 @@ namespace AzToolsFramework } // namespace AssetBrowser } // namespace AzToolsFramework// namespace AssetBrowser -#pragma optimize("", on) #include "AssetBrowser/moc_AssetBrowserFilterModel.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 40f8318a2d..70d66f4e1f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -9,8 +9,8 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ -#include #include +#include #include namespace AzToolsFramework @@ -26,7 +26,9 @@ namespace AzToolsFramework void AssetBrowserTableModel::setSourceModel(QAbstractItemModel* sourceModel) { m_filterModel = qobject_cast(sourceModel); - AZ_Assert(m_filterModel, "Error in AssetBrowserTableModel initialization, class expects source model to be an AssetBrowserFilterModel."); + AZ_Assert( + m_filterModel, + "Error in AssetBrowserTableModel initialization, class expects source model to be an AssetBrowserFilterModel."); QSortFilterProxyModel::setSourceModel(sourceModel); } @@ -86,7 +88,8 @@ namespace AzToolsFramework return !parent.isValid() ? m_indexMap.size() : 0; } - int AssetBrowserTableModel::BuildTableModelMap(const QAbstractItemModel* model, const QModelIndex& parent /*= QModelIndex()*/, int row /*= 0*/) + int AssetBrowserTableModel::BuildTableModelMap( + const QAbstractItemModel* model, const QModelIndex& parent /*= QModelIndex()*/, int row /*= 0*/) { int rows = model ? model->rowCount(parent) : 0; for (int i = 0; i < rows; ++i) @@ -134,7 +137,6 @@ namespace AzToolsFramework } BuildTableModelMap(sourceModel()); emit layoutChanged(); - } } // namespace AssetBrowser } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index f7128cb504..894bbd8700 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -37,7 +37,6 @@ AZ_PUSH_DISABLE_WARNING( #include #include AZ_POP_DISABLE_WARNING -#pragma optimize("", off) namespace AzToolsFramework { namespace AssetBrowser @@ -128,7 +127,8 @@ namespace AzToolsFramework QTableView::rowsAboutToBeRemoved(parent, start, end); } - void AssetBrowserTableView::layoutChangedSlot([[maybe_unused]] const QList& parents,[[maybe_unused]] QAbstractItemModel::LayoutChangeHint hint) + void AssetBrowserTableView::layoutChangedSlot( + [[maybe_unused]] const QList& parents, [[maybe_unused]] QAbstractItemModel::LayoutChangeHint hint) { scrollToTop(); } @@ -159,7 +159,6 @@ namespace AzToolsFramework void AssetBrowserTableView::OnContextMenu([[maybe_unused]] const QPoint& point) { - const auto& selectedAssets = GetSelectedAssets(); if (selectedAssets.size() != 1) { @@ -167,7 +166,8 @@ namespace AzToolsFramework } QMenu menu(this); - AssetBrowserInteractionNotificationBus::Broadcast(&AssetBrowserInteractionNotificationBus::Events::AddContextMenuActions, this, &menu, selectedAssets); + AssetBrowserInteractionNotificationBus::Broadcast( + &AssetBrowserInteractionNotificationBus::Events::AddContextMenuActions, this, &menu, selectedAssets); if (!menu.isEmpty()) { menu.exec(QCursor::pos()); @@ -175,5 +175,4 @@ namespace AzToolsFramework } } // namespace AssetBrowser } // namespace AzToolsFramework -#pragma optimize("", on) #include "AssetBrowser/Views/moc_AssetBrowserTableView.cpp" diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index e722d6d03e..90b597e273 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -1,26 +1,26 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "EditorDefs.h" #include "AzAssetBrowserWindow.h" // AzToolsFramework +#include #include #include +#include #include #include -#include -#include // AzQtComponents #include @@ -35,7 +35,6 @@ AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING AZ_CVAR_EXTERNED(bool, ed_useNewAssetBrowserTableView); - class ListenerForShowAssetEditorEvent : public QObject , private AzToolsFramework::EditorEvents::Bus::Handler @@ -113,22 +112,29 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); - connect(m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, - m_filterModel.data(), &AssetBrowserFilterModel::filterUpdatedSlot); - connect(m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, this, [this]() - { - const bool hasFilter = !m_ui->m_searchWidget->GetFilterString().isEmpty(); - const bool selectFirstFilteredIndex = false; - m_ui->m_assetBrowserTreeViewWidget->UpdateAfterFilter(hasFilter, selectFirstFilteredIndex); - }); + connect( + m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), + &AssetBrowserFilterModel::filterUpdatedSlot); + connect( + m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, this, + [this]() + { + const bool hasFilter = !m_ui->m_searchWidget->GetFilterString().isEmpty(); + const bool selectFirstFilteredIndex = false; + m_ui->m_assetBrowserTreeViewWidget->UpdateAfterFilter(hasFilter, selectFirstFilteredIndex); + }); - connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::selectionChangedSignal, - this, &AzAssetBrowserWindow::SelectionChangedSlot); + connect( + m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::selectionChangedSignal, this, + &AzAssetBrowserWindow::SelectionChangedSlot); connect(m_ui->m_assetBrowserTreeViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); - connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, &SearchWidget::ClearStringFilter); - connect(m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, &SearchWidget::ClearTypeFilter); + connect( + m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, + &SearchWidget::ClearStringFilter); + connect( + m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, &SearchWidget::ClearTypeFilter); m_ui->m_assetBrowserTreeViewWidget->SetName("AssetBrowserTreeView_main"); } @@ -199,18 +205,21 @@ void AzAssetBrowserWindow::SelectAsset(const QString& assetPath) // interferes with the update from the select and expand, and if you don't // queue it, the tree doesn't expand reliably. - QTimer::singleShot(0, this, [this, filteredIndex = index] { - // the treeview has a filter model so we have to backwards go from that - QModelIndex index = m_filterModel->mapFromSource(filteredIndex); + QTimer::singleShot( + 0, this, + [this, filteredIndex = index] + { + // the treeview has a filter model so we have to backwards go from that + QModelIndex index = m_filterModel->mapFromSource(filteredIndex); - QTreeView* treeView = m_ui->m_assetBrowserTreeViewWidget; - ExpandTreeToIndex(treeView, index); + QTreeView* treeView = m_ui->m_assetBrowserTreeViewWidget; + ExpandTreeToIndex(treeView, index); - treeView->scrollTo(index); - treeView->setCurrentIndex(index); + treeView->scrollTo(index); + treeView->setCurrentIndex(index); - treeView->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect); - }); + treeView->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect); + }); } } @@ -243,11 +252,12 @@ void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& assetIdToOpen = AZ::Data::AssetId(sourceEntry->GetSourceUuid(), 0); fullFilePath = entry->GetFullPath(); } - + bool handledBySomeone = false; if (assetIdToOpen.IsValid()) { - AssetBrowserInteractionNotificationBus::Broadcast(&AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); + AssetBrowserInteractionNotificationBus::Broadcast( + &AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); } if (!handledBySomeone && !fullFilePath.empty()) @@ -255,7 +265,6 @@ void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& AzAssetBrowserRequestHandler::OpenWithOS(fullFilePath); } } - } void AzAssetBrowserWindow::DoubleClickedItemTableModel([[maybe_unused]] const QModelIndex& element) From 01f69acc5f086824223ed3e4785f5423fa13eb81 Mon Sep 17 00:00:00 2001 From: Nicholas Lawson <70027408+lawsonamzn@users.noreply.github.com> Date: Wed, 2 Jun 2021 07:38:39 -0700 Subject: [PATCH 398/811] Cleans up remaining 3p package todos (#1080) Removes Clang Adds a required LICENSE.TXT to the folder of glad in atom. --- .../glad/2.0.0-beta/include/glad/license.txt | 209 ++++++++++++++++++ cmake/3rdParty/FindClang.cmake | 15 -- cmake/3rdParty/cmake_files.cmake | 1 - 3 files changed, 209 insertions(+), 16 deletions(-) create mode 100644 Gems/Atom/RHI/Vulkan/External/glad/2.0.0-beta/include/glad/license.txt delete mode 100644 cmake/3rdParty/FindClang.cmake diff --git a/Gems/Atom/RHI/Vulkan/External/glad/2.0.0-beta/include/glad/license.txt b/Gems/Atom/RHI/Vulkan/External/glad/2.0.0-beta/include/glad/license.txt new file mode 100644 index 0000000000..158138973a --- /dev/null +++ b/Gems/Atom/RHI/Vulkan/External/glad/2.0.0-beta/include/glad/license.txt @@ -0,0 +1,209 @@ +vulkan.h was generated using a code generator from https://github.com/Dav1dde/glad + +/* +** Copyright (c) 2014-2020 The Khronos Group Inc. +** +** SPDX-License-Identifier: Apache-2.0 +*/ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/cmake/3rdParty/FindClang.cmake b/cmake/3rdParty/FindClang.cmake deleted file mode 100644 index 8062e6ebb2..0000000000 --- a/cmake/3rdParty/FindClang.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -ly_add_external_target( - NAME Clang - VERSION 6.0.1-az -) diff --git a/cmake/3rdParty/cmake_files.cmake b/cmake/3rdParty/cmake_files.cmake index ebbad6e156..f7a315686f 100644 --- a/cmake/3rdParty/cmake_files.cmake +++ b/cmake/3rdParty/cmake_files.cmake @@ -11,7 +11,6 @@ set(FILES BuiltInPackages.cmake - FindClang.cmake FindOpenGLInterface.cmake FindRadTelemetry.cmake FindVkValidation.cmake From 274e1972f3574fc70fc41a58e0de3c5db5a9d8d2 Mon Sep 17 00:00:00 2001 From: Hasareej <82398396+Hasareej@users.noreply.github.com> Date: Wed, 2 Jun 2021 15:54:30 +0100 Subject: [PATCH 399/811] Adding a shortcut to hide clusters. (#1071) Adding the shortcut "U" to hide the TransformModeSelection & SpaceSelection clusters from the viewport. --- .../EditorTransformComponentSelection.cpp | 12 +++++++++++- .../EditorTransformComponentSelection.h | 1 + Code/Sandbox/Editor/Resource.h | 1 + 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index 3507f532b5..91ac495e0e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -2471,7 +2471,17 @@ namespace AzToolsFramework break; } }); - + + AddAction( + m_actions, { QKeySequence(Qt::Key_U) }, + /*ID_VIEWPORTUI_VISIBLE=*/50040, "Toggle ViewportUI", "Hide/Unhide Viewport UI", + [this]() + { + SetViewportUiClusterVisible(m_transformModeClusterId, !m_viewportUiVisible); + SetViewportUiClusterVisible(m_spaceCluster.m_spaceClusterId, !m_viewportUiVisible); + m_viewportUiVisible = !m_viewportUiVisible; + }); + EditorMenuRequestBus::Broadcast(&EditorMenuRequests::RestoreEditMenuToDefault); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h index 2bc4d7cbf6..2ec7fa2489 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h @@ -306,6 +306,7 @@ namespace AzToolsFramework AzFramework::ClickDetector m_clickDetector; //!< Detect different types of mouse click. AzFramework::CursorState m_cursorState; //!< Track the mouse position and delta movement each frame. SpaceCluster m_spaceCluster; //!< Related viewport ui state for controlling the current reference space. + bool m_viewportUiVisible = true; //!< Used to hide/show the viewport ui elements. }; //! The ETCS (EntityTransformComponentSelection) namespace contains functions and data used exclusively by diff --git a/Code/Sandbox/Editor/Resource.h b/Code/Sandbox/Editor/Resource.h index 9c50045367..98a6e56d14 100644 --- a/Code/Sandbox/Editor/Resource.h +++ b/Code/Sandbox/Editor/Resource.h @@ -369,3 +369,4 @@ #define ID_TOOLBAR_WIDGET_SPACER_RIGHT 50013 #define ID_TOOLBAR_WIDGET_PLAYCONSOLE_LABEL 50014 #define ID_TOOLBAR_WIDGET_LAST 50020 +#define ID_VIEWPORTUI_VISIBLE 50040 From 39d1f2702192090408d59746b78d59870495f38f Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 08:39:57 -0700 Subject: [PATCH 400/811] [ftue_auto_register] post merge and linux build fixes --- Code/Tools/ProjectManager/Source/PythonBindings.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index ab13e67591..ca8e571de5 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -324,10 +324,10 @@ namespace O3DE::ProjectManager // check current engine path against all other registered engines // to see if we are already registered - auto allEngines = m_registration.attr("get_engines")(); + auto allEngines = m_manifest.attr("get_engines")(); if (pybind11::isinstance(allEngines)) { - for (const auto& engine : allEngines) + for (auto engine : allEngines) { AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"])); if (enginePath.Compare(m_enginePath) == 0) @@ -340,7 +340,7 @@ namespace O3DE::ProjectManager if (registerThis) { - auto result = m_registration.attr("register")(m_enginePath.c_str()); + auto result = m_register.attr("register")(m_enginePath.c_str()); registrationResult = (result.cast() == 0); } }); From 5554bdf329d69ba7f7180fa6c2eb0cacd55697f3 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 08:46:57 -0700 Subject: [PATCH 401/811] [ftue_auto_register] use early return in registered engines loop instead of break --- Code/Tools/ProjectManager/Source/PythonBindings.cpp | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index ca8e571de5..2859a8fc9d 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -320,8 +320,6 @@ namespace O3DE::ProjectManager bool pythonResult = ExecuteWithLock( [&] { - bool registerThis = true; - // check current engine path against all other registered engines // to see if we are already registered auto allEngines = m_manifest.attr("get_engines")(); @@ -332,17 +330,13 @@ namespace O3DE::ProjectManager AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"])); if (enginePath.Compare(m_enginePath) == 0) { - registerThis = false; - break; + return; } } } - if (registerThis) - { - auto result = m_register.attr("register")(m_enginePath.c_str()); - registrationResult = (result.cast() == 0); - } + auto result = m_register.attr("register")(m_enginePath.c_str()); + registrationResult = (result.cast() == 0); }); bool finalResult = (registrationResult && pythonResult); From 53615230c1c7ebd905c37629898f35dc8b04160d Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 2 Jun 2021 17:49:40 +0200 Subject: [PATCH 402/811] [LYN-2514] Adding get engine gem infos to the python bindings --- .../ProjectManager/Source/PythonBindings.cpp | 20 +++++++++++++++++++ .../ProjectManager/Source/PythonBindings.h | 1 + .../Source/PythonBindingsInterface.h | 6 ++++++ 3 files changed, 27 insertions(+) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index e6ebfbefca..72db92ff20 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -438,6 +438,26 @@ namespace O3DE::ProjectManager } } + AZ::Outcome, AZStd::string> PythonBindings::GetEngineGemInfos() + { + QVector gems; + + auto result = ExecuteWithLockErrorHandling([&] + { + for (auto path : m_manifest.attr("get_engine_gems")()) + { + gems.push_back(GemInfoFromPath(path)); + } + }); + if (!result.IsSuccess()) + { + return AZ::Failure(result.GetError().c_str()); + } + + std::sort(gems.begin(), gems.end()); + return AZ::Success(AZStd::move(gems)); + } + AZ::Outcome, AZStd::string> PythonBindings::GetAllGemInfos(const QString& projectPath) { QVector gems; diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h index 44958b0b0f..d508f15b95 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.h +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -40,6 +40,7 @@ namespace O3DE::ProjectManager // Gem AZ::Outcome GetGemInfo(const QString& path) override; + AZ::Outcome, AZStd::string> GetEngineGemInfos() override; AZ::Outcome, AZStd::string> GetAllGemInfos(const QString& projectPath) override; AZ::Outcome, AZStd::string> GetEnabledGemNames(const QString& projectPath) override; diff --git a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h index 2e8347f488..09d9187dbd 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h +++ b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h @@ -66,6 +66,12 @@ namespace O3DE::ProjectManager */ virtual AZ::Outcome, AZStd::string> GetAllGemInfos(const QString& projectPath) = 0; + /** + * Get engine gem infos. + * @return A list of all registered gem infos. + */ + virtual AZ::Outcome, AZStd::string> GetEngineGemInfos() = 0; + /** * Get a list of all enabled gem names for a given project. * @param[in] projectPath Absolute file path to the project. From f10627366726495bb1d13f2474bb856a96a0e15c Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 2 Jun 2021 17:52:17 +0200 Subject: [PATCH 403/811] [LYN-2514] Adding functionality to reinit the gem catalog for a given project and enable/disable the changed gems * Removed test data from gem catalog screen as we can now extract the real data. * Reiniting the catalog to a project updates the filters, and clears and fills the gem model. * Added functionality to enable/disable gems based on the user adjustments on the gem catalog. --- .../Source/GemCatalog/GemCatalogScreen.cpp | 213 +++++++++--------- .../Source/GemCatalog/GemCatalogScreen.h | 10 +- 2 files changed, 114 insertions(+), 109 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp index 2d243e7f8b..670cbbc5a3 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp @@ -15,13 +15,12 @@ #include #include #include -#include #include #include #include #include - -//#define USE_TESTGEMDATA +#include +#include namespace O3DE::ProjectManager { @@ -29,47 +28,32 @@ namespace O3DE::ProjectManager : ScreenWidget(parent) { m_gemModel = new GemModel(this); - GemSortFilterProxyModel* proxyModel = new GemSortFilterProxyModel(m_gemModel, this); + m_proxModel = new GemSortFilterProxyModel(m_gemModel, this); QVBoxLayout* vLayout = new QVBoxLayout(); vLayout->setMargin(0); vLayout->setSpacing(0); setLayout(vLayout); - GemCatalogHeaderWidget* headerWidget = new GemCatalogHeaderWidget(proxyModel); + GemCatalogHeaderWidget* headerWidget = new GemCatalogHeaderWidget(m_proxModel); vLayout->addWidget(headerWidget); QHBoxLayout* hLayout = new QHBoxLayout(); hLayout->setMargin(0); vLayout->addLayout(hLayout); - m_gemListView = new GemListView(proxyModel, proxyModel->GetSelectionModel(), this); + m_gemListView = new GemListView(m_proxModel, m_proxModel->GetSelectionModel(), this); m_gemInspector = new GemInspector(m_gemModel, this); - m_gemInspector->setFixedWidth(320); + m_gemInspector->setFixedWidth(240); - // Start: Temporary gem test data -#ifdef USE_TESTGEMDATA - QVector testGemData = GenerateTestData(); - for (const GemInfo& gemInfo : testGemData) - { - m_gemModel->AddGem(gemInfo); - } -#else - // End: Temporary gem test data - auto result = PythonBindingsInterface::Get()->GetGems(); - if (result.IsSuccess()) - { - for (auto gemInfo : result.GetValue()) - { - m_gemModel->AddGem(gemInfo); - } - } -#endif + QWidget* filterWidget = new QWidget(this); + filterWidget->setFixedWidth(240); + m_filterWidgetLayout = new QVBoxLayout(); + m_filterWidgetLayout->setMargin(0); + m_filterWidgetLayout->setSpacing(0); + filterWidget->setLayout(m_filterWidgetLayout); - GemFilterWidget* filterWidget = new GemFilterWidget(proxyModel); - filterWidget->setFixedWidth(250); - - GemListHeaderWidget* listHeaderWidget = new GemListHeaderWidget(proxyModel); + GemListHeaderWidget* listHeaderWidget = new GemListHeaderWidget(m_proxModel); QVBoxLayout* middleVLayout = new QVBoxLayout(); middleVLayout->setMargin(0); @@ -80,98 +64,111 @@ namespace O3DE::ProjectManager hLayout->addWidget(filterWidget); hLayout->addLayout(middleVLayout); hLayout->addWidget(m_gemInspector); - - proxyModel->InvalidateFilter(); } - QVector GemCatalogScreen::GenerateTestData() + void GemCatalogScreen::ReinitForProject(const QString& projectPath, bool isNewProject) { - QVector result; + m_gemModel->clear(); + FillModel(projectPath, isNewProject); - GemInfo gem("EMotion FX", - "O3DE Foundation", - "EMFX is a real-time character animation system. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", - (GemInfo::Android | GemInfo::iOS | GemInfo::macOS | GemInfo::Windows | GemInfo::Linux), - true); - gem.m_directoryLink = "C:/"; - gem.m_documentationLink = "http://www.amazon.com"; - gem.m_dependingGemUuids = QStringList({"EMotionFX", "Atom"}); - gem.m_conflictingGemUuids = QStringList({"Vegetation", "Camera", "ScriptCanvas", "CloudCanvas", "Networking"}); - gem.m_types = (GemInfo::Code | GemInfo::Asset); - gem.m_version = "v1.01"; - gem.m_lastUpdatedDate = "24th April 2021"; - gem.m_binarySizeInKB = 40; - gem.m_features = QStringList({"Animation", "Assets", "Physics"}); - gem.m_gemOrigin = GemInfo::O3DEFoundation; - result.push_back(gem); + if (m_filterWidget) + { + m_filterWidget->hide(); + m_filterWidget->deleteLater(); + } - gem.m_name = "Atom"; - gem.m_creator = "O3DE Seattle"; - gem.m_summary = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; - gem.m_platforms = (GemInfo::Android | GemInfo::Windows | GemInfo::Linux | GemInfo::macOS); - gem.m_isAdded = true; - gem.m_directoryLink = "C:/"; - gem.m_documentationLink = "https://aws.amazon.com/gametech/"; - gem.m_dependingGemUuids = QStringList({"EMotionFX", "Core", "AudioSystem", "Camera", "Particles"}); - gem.m_conflictingGemUuids = QStringList({"CloudCanvas", "NovaNet"}); - gem.m_version = "v2.31"; - gem.m_lastUpdatedDate = "24th November 2020"; - gem.m_features = QStringList({"Assets", "Rendering", "UI", "VR", "Debug", "Environment"}); - gem.m_binarySizeInKB = 2087; - result.push_back(gem); + m_filterWidget = new GemFilterWidget(m_proxModel); + m_filterWidgetLayout->addWidget(m_filterWidget); - gem.m_name = "Physics"; - gem.m_creator = "O3DE London"; - gem.m_summary = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; - gem.m_platforms = (GemInfo::Android | GemInfo::Linux | GemInfo::macOS); - gem.m_isAdded = true; - gem.m_directoryLink = "C:/"; - gem.m_documentationLink = "https://aws.amazon.com/gametech/"; - gem.m_dependingGemUuids = QStringList({"GraphCanvas", "ExpressionEvaluation", "UI Lib", "Multiplayer", "GameStateSamples"}); - gem.m_conflictingGemUuids = QStringList({"Cloud Canvas", "EMotion FX", "Streaming", "MessagePopup", "Cloth", "Graph Canvas", "Twitch Integration"}); - gem.m_version = "v1.5.102145"; - gem.m_lastUpdatedDate = "1st January 2021"; - gem.m_binarySizeInKB = 2000000; - gem.m_features = QStringList({"Physics", "Gameplay", "Debug", "Assets"}); - result.push_back(gem); + m_proxModel->InvalidateFilter(); - result.push_back(O3DE::ProjectManager::GemInfo("Certificate Manager", - "O3DE Irvine", - "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", - GemInfo::Windows, - false)); + // Select the first entry after everything got correctly sized + QTimer::singleShot(200, [=]{ + QModelIndex firstModelIndex = m_gemListView->model()->index(0,0); + m_gemListView->selectionModel()->select(firstModelIndex, QItemSelectionModel::ClearAndSelect); + }); + } - result.push_back(O3DE::ProjectManager::GemInfo("Cloud Gem Framework", - "O3DE Seattle", - "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", - GemInfo::iOS | GemInfo::Linux, - false)); + void GemCatalogScreen::FillModel(const QString& projectPath, [[maybe_unused]] bool isNewProject) + { + AZ::Outcome, AZStd::string> allGemInfosResult; + if (isNewProject) + { + allGemInfosResult = PythonBindingsInterface::Get()->GetEngineGemInfos(); + } + else + { + allGemInfosResult = PythonBindingsInterface::Get()->GetAllGemInfos(projectPath); + } - result.push_back(O3DE::ProjectManager::GemInfo("Cloud Gem Core", - "O3DE Foundation", - "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - GemInfo::Android | GemInfo::Windows | GemInfo::Linux, - true)); + if (allGemInfosResult.IsSuccess()) + { + // Add all available gems to the model. + const QVector allGemInfos = allGemInfosResult.GetValue(); + for (const GemInfo& gemInfo : allGemInfos) + { + m_gemModel->AddGem(gemInfo); + } - result.push_back(O3DE::ProjectManager::GemInfo("Gestures", - "O3DE Foundation", - "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - GemInfo::Android | GemInfo::Windows | GemInfo::Linux, - false)); + // Gather enabled gems for the given project. + auto enabledGemNamesResult = PythonBindingsInterface::Get()->GetEnabledGemNames(projectPath); + if (enabledGemNamesResult.IsSuccess()) + { + const QVector enabledGemNames = enabledGemNamesResult.GetValue(); + for (const AZStd::string& enabledGemName : enabledGemNames) + { + const QModelIndex modelIndex = m_gemModel->FindIndexByNameString(enabledGemName.c_str()); + if (modelIndex.isValid()) + { + GemModel::SetWasPreviouslyAdded(*m_gemModel, modelIndex, true); + GemModel::SetIsAdded(*m_gemModel, modelIndex, true); + } + else + { + AZ_Warning("ProjectManager::GemCatalog", false, + "Cannot find entry for gem with name '%s'. The CMake target name probably does not match the specified name in the gem.json.", + enabledGemName.c_str()); + } + } + } + else + { + QMessageBox::critical(nullptr, "Operation failed", QString("Cannot retrieve enabled gems for project %1.\n\nError:\n%2").arg(projectPath, enabledGemNamesResult.GetError().c_str())); + } + } + else + { + QMessageBox::critical(nullptr, "Operation failed", QString("Cannot retrieve gems for %1.\n\nError:\n%2").arg(projectPath, allGemInfosResult.GetError().c_str())); + } + } - result.push_back(O3DE::ProjectManager::GemInfo("Effects System", - "O3DE Foundation", - "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - GemInfo::Android | GemInfo::Windows | GemInfo::Linux, - true)); + void GemCatalogScreen::EnableDisableGemsForProject(const QString& projectPath) + { + IPythonBindings* pythonBindings = PythonBindingsInterface::Get(); + QVector toBeAdded = m_gemModel->GatherGemsToBeAdded(); + QVector toBeRemoved = m_gemModel->GatherGemsToBeRemoved(); - result.push_back(O3DE::ProjectManager::GemInfo("Microphone", - "O3DE Foundation", - "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus euismod ligula vitae dui dictum, a sodales dolor luctus. Sed id elit dapibus, finibus neque sed, efficitur mi. Nam facilisis ligula at eleifend pellentesque. Praesent non ex consectetur, blandit tellus in, venenatis lacus. Duis nec neque in urna ullamcorper euismod id eu leo. Nam efficitur dolor sed odio vehicula venenatis. Suspendisse nec est non velit commodo cursus in sit amet dui. Ut bibendum nisl et libero hendrerit dapibus. Vestibulum ultrices ullamcorper urna, placerat porttitor est lobortis in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer a magna ac tellus sollicitudin porttitor. Phasellus lobortis viverra justo id bibendum. Etiam ac pharetra risus. Nulla vitae justo nibh. Nulla viverra leo et molestie interdum. Duis sit amet bibendum nulla, sit amet vehicula augue.", - GemInfo::Android | GemInfo::Windows | GemInfo::Linux, - false)); + for (const QModelIndex& modelIndex : toBeAdded) + { + const QString gemPath = GemModel::GetPath(modelIndex); + const AZ::Outcome result = pythonBindings->AddGemToProject(gemPath, projectPath); + if (!result.IsSuccess()) + { + QMessageBox::critical(nullptr, "Operation failed", + QString("Cannot add gem %1 to project.\n\nError:\n%2").arg(GemModel::GetName(modelIndex), result.GetError().c_str())); + } + } - return result; + for (const QModelIndex& modelIndex : toBeRemoved) + { + const QString gemPath = GemModel::GetPath(modelIndex); + const AZ::Outcome result = pythonBindings->RemoveGemFromProject(gemPath, projectPath); + if (!result.IsSuccess()) + { + QMessageBox::critical(nullptr, "Operation failed", + QString("Cannot remove gem %1 from project.\n\nError:\n%2").arg(GemModel::GetName(modelIndex), result.GetError().c_str())); + } + } } ProjectManagerScreen GemCatalogScreen::GetScreenEnum() diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h index 44e0727c7e..0847d9b74e 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h @@ -14,9 +14,11 @@ #if !defined(Q_MOC_RUN) #include +#include #include #include #include +#include #endif namespace O3DE::ProjectManager @@ -29,11 +31,17 @@ namespace O3DE::ProjectManager ~GemCatalogScreen() = default; ProjectManagerScreen GetScreenEnum() override; + void ReinitForProject(const QString& projectPath, bool isNewProject); + void EnableDisableGemsForProject(const QString& projectPath); + private: - QVector GenerateTestData(); + void FillModel(const QString& projectPath, bool isNewProject); GemListView* m_gemListView = nullptr; GemInspector* m_gemInspector = nullptr; GemModel* m_gemModel = nullptr; + GemSortFilterProxyModel* m_proxModel = nullptr; + QVBoxLayout* m_filterWidgetLayout = nullptr; + GemFilterWidget* m_filterWidget = nullptr; }; } // namespace O3DE::ProjectManager From b0ef89edf967b9d78ddc948382e45a5ad27d99b5 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 2 Jun 2021 17:53:02 +0200 Subject: [PATCH 404/811] [LYN-2514] Update project control now reinits for the selected project and enabled/disables gems based on the user selection in the gem catalog --- .../Source/UpdateProjectCtrl.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp index b3180966ce..bfa62dcae8 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -26,6 +27,7 @@ namespace O3DE::ProjectManager : ScreenWidget(parent) { QVBoxLayout* vLayout = new QVBoxLayout(); + vLayout->setMargin(0); setLayout(vLayout); m_screensCtrl = new ScreensCtrl(); @@ -95,6 +97,17 @@ namespace O3DE::ProjectManager } m_projectInfo = projectScreen->GetProjectInfo(); + + // The next page is the gem catalog. Gather the available gems that will be shown in the gem catalog. + auto* gemCatalogScreen = reinterpret_cast(m_screensCtrl->FindScreen(ProjectManagerScreen::GemCatalog)); + if (gemCatalogScreen) + { + gemCatalogScreen->ReinitForProject(m_projectInfo.m_path, /*isNewProject=*/false); + } + else + { + QMessageBox::critical(this, tr("Operation failed"), tr("Cannot find gem catalog screen.")); + } } } @@ -114,6 +127,17 @@ namespace O3DE::ProjectManager { QMessageBox::critical(this, tr("Project update failed"), tr("Failed to update project.")); } + + // Enable or disable the gems that got adjusted in the gem catalog and apply them to the given project. + auto* gemCatalogScreen = reinterpret_cast(m_screensCtrl->FindScreen(ProjectManagerScreen::GemCatalog)); + if (gemCatalogScreen) + { + gemCatalogScreen->EnableDisableGemsForProject(m_projectInfo.m_path); + } + else + { + QMessageBox::critical(this, tr("Operation failed"), tr("Cannot find gem catalog screen.")); + } } } From 39bb0bf2fc4cce33aa4404a5ac183604611a26db Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 2 Jun 2021 17:53:49 +0200 Subject: [PATCH 405/811] [LYN-2514] Create a new project control now reinits the gem catalog and enables gems based on the user selection --- .../ProjectManager/Source/CreateProjectCtrl.cpp | 14 +++++++++++--- .../ProjectManager/Source/CreateProjectCtrl.h | 3 +++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp index 60e351cdb4..559141bc82 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp @@ -15,7 +15,6 @@ #include #include #include -#include #include #include @@ -42,9 +41,10 @@ namespace O3DE::ProjectManager m_stack = new QStackedWidget(this); m_stack->setObjectName("body"); - m_stack->setSizePolicy(QSizePolicy(QSizePolicy::Preferred,QSizePolicy::Expanding)); + m_stack->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding)); m_stack->addWidget(new NewProjectSettingsScreen()); - m_stack->addWidget(new GemCatalogScreen()); + m_gemCatalog = new GemCatalogScreen(); + m_stack->addWidget(m_gemCatalog); vLayout->addWidget(m_stack); QDialogButtonBox* backNextButtons = new QDialogButtonBox(); @@ -88,9 +88,11 @@ namespace O3DE::ProjectManager emit GotoPreviousScreenRequest(); } } + void CreateProjectCtrl::HandleNextButton() { ScreenWidget* currentScreen = reinterpret_cast(m_stack->currentWidget()); + const int currentScreenIndex = m_stack->currentIndex(); ProjectManagerScreen screenEnum = currentScreen->GetScreenEnum(); if (screenEnum == ProjectManagerScreen::NewProjectSettings) @@ -106,6 +108,9 @@ namespace O3DE::ProjectManager m_projectInfo = newProjectScreen->GetProjectInfo(); m_projectTemplatePath = newProjectScreen->GetProjectTemplatePath(); + + // The next page is the gem catalog. Gather the available gems that will be shown in the gem catalog. + m_gemCatalog->ReinitForProject(m_projectInfo.m_path, /*isNewProject=*/true); } } @@ -129,6 +134,9 @@ namespace O3DE::ProjectManager { QMessageBox::critical(this, tr("Project creation failed"), tr("Failed to create project.")); } + + // Enable/disable gems for the newly created project. + m_gemCatalog->EnableDisableGemsForProject(m_projectInfo.m_path); } } diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h index 355ba3941d..89d18a9ebc 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h @@ -14,6 +14,7 @@ #if !defined(Q_MOC_RUN) #include #include +#include #endif QT_FORWARD_DECLARE_CLASS(QStackedWidget) @@ -48,6 +49,8 @@ namespace O3DE::ProjectManager QString m_projectTemplatePath; ProjectInfo m_projectInfo; + + GemCatalogScreen* m_gemCatalog = nullptr; }; } // namespace O3DE::ProjectManager From 1f65c3ba3a8560d20895d1cf51460a3dbb2096bd Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Wed, 2 Jun 2021 09:13:04 -0700 Subject: [PATCH 406/811] LYN-4134 Automatically add `--project-path=` to debugging parameters in Editor/AP for engine-centric (#1081) --- Code/Sandbox/Editor/CMakeLists.txt | 16 +++++++--------- Code/Tools/AssetProcessor/CMakeLists.txt | 4 ++++ cmake/Projects.cmake | 3 +++ 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/Code/Sandbox/Editor/CMakeLists.txt b/Code/Sandbox/Editor/CMakeLists.txt index 7be9947e99..01b58e3f77 100644 --- a/Code/Sandbox/Editor/CMakeLists.txt +++ b/Code/Sandbox/Editor/CMakeLists.txt @@ -177,6 +177,11 @@ ly_add_target( Legacy::EditorLib ProjectManager ) +set_property(SOURCE + CryEdit.cpp + APPEND PROPERTY + COMPILE_DEFINITIONS LY_CMAKE_TARGET="Editor" +) ly_add_translations( TARGETS Editor PREFIX Translations @@ -186,15 +191,8 @@ ly_add_translations( ) ly_add_dependencies(Editor AssetProcessor) -if(TARGET Editor) - set_property(SOURCE - CryEdit.cpp - APPEND PROPERTY - COMPILE_DEFINITIONS LY_CMAKE_TARGET="Editor" - ) -else() - message(FATAL_ERROR "Cannot set LY_CMAKE_TARGET define to Editor as the target doesn't exist anymore." - " Perhaps it has been renamed") +if(LY_FIRST_PROJECT_PATH) + set_property(TARGET Editor APPEND PROPERTY VS_DEBUGGER_COMMAND_ARGUMENTS "--project-path=\"${LY_FIRST_PROJECT_PATH}\"") endif() ################################################################################ diff --git a/Code/Tools/AssetProcessor/CMakeLists.txt b/Code/Tools/AssetProcessor/CMakeLists.txt index 5d4980eed4..6c12ab6024 100644 --- a/Code/Tools/AssetProcessor/CMakeLists.txt +++ b/Code/Tools/AssetProcessor/CMakeLists.txt @@ -125,6 +125,10 @@ ly_add_target( AZ::AssetProcessorBatch.Static ) +if(LY_FIRST_PROJECT_PATH) + set_property(TARGET AssetProcessor AssetProcessorBatch APPEND PROPERTY VS_DEBUGGER_COMMAND_ARGUMENTS "--project-path=\"${LY_FIRST_PROJECT_PATH}\"") +endif() + # Adds the AssetProcessorBatch target as a C preprocessor define so that it can be used as a Settings Registry # specialization in order to look up the generated .setreg which contains the dependencies # specified for the target. diff --git a/cmake/Projects.cmake b/cmake/Projects.cmake index 297dad4ddf..adaf7ee15f 100644 --- a/cmake/Projects.cmake +++ b/cmake/Projects.cmake @@ -167,6 +167,9 @@ endfunction() # Add the projects here so the above function is found foreach(project ${LY_PROJECTS}) file(REAL_PATH ${project} full_directory_path BASE_DIRECTORY ${CMAKE_SOURCE_DIR}) + if(NOT LY_FIRST_PROJECT) + ly_set(LY_FIRST_PROJECT_PATH ${full_directory_path}) + endif() string(SHA256 full_directory_hash ${full_directory_path}) # Truncate the full_directory_hash down to 8 characters to avoid hitting the Windows 260 character path limit From 25a114d32447282f1d19a71da621fd8626b3ab15 Mon Sep 17 00:00:00 2001 From: guthadam Date: Wed, 2 Jun 2021 11:35:40 -0500 Subject: [PATCH 407/811] updating includes --- .../Feature/Common/Code/Source/Material/MaterialAssignment.cpp | 3 +-- .../Code/Source/Material/MaterialAssignmentSerializer.cpp | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp index b4d8200dbc..029a81ec49 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp @@ -14,8 +14,7 @@ #include #include #include - -#include "MaterialAssignmentSerializer.h" +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.cpp index bb68a05a3e..a895c04b95 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentSerializer.cpp @@ -10,7 +10,7 @@ * */ -#include "MaterialAssignmentSerializer.h" +#include #include namespace AZ From fc0de9e0e309a6172457af7c913f44b369e8e7d2 Mon Sep 17 00:00:00 2001 From: AMZN-stankowi Date: Wed, 2 Jun 2021 09:36:34 -0700 Subject: [PATCH 408/811] Added [[maybe unused]] to fix release build compile issue (#1090) --- Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp index 791af4bf68..336cc1b172 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp @@ -42,7 +42,7 @@ namespace AZ } #if AZ_TRAIT_COMPILER_SUPPORT_CSIGNAL - void signal_handler(int signal) + void signal_handler([[maybe_unused]] int signal) { AZ_TracePrintf( SceneAPI::Utilities::ErrorWindow, From e7e85f91d6ca30dd6e3fb872b27a693e6e8f0816 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 2 Jun 2021 19:08:10 +0200 Subject: [PATCH 409/811] Addressing PR feedback --- Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp | 1 - .../ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp | 6 +++--- Code/Tools/ProjectManager/Source/PythonBindings.cpp | 3 ++- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp index 559141bc82..85e34aeced 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp @@ -92,7 +92,6 @@ namespace O3DE::ProjectManager void CreateProjectCtrl::HandleNextButton() { ScreenWidget* currentScreen = reinterpret_cast(m_stack->currentWidget()); - const int currentScreenIndex = m_stack->currentIndex(); ProjectManagerScreen screenEnum = currentScreen->GetScreenEnum(); if (screenEnum == ProjectManagerScreen::NewProjectSettings) diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp index 670cbbc5a3..aa36c1b0ab 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp @@ -89,7 +89,7 @@ namespace O3DE::ProjectManager }); } - void GemCatalogScreen::FillModel(const QString& projectPath, [[maybe_unused]] bool isNewProject) + void GemCatalogScreen::FillModel(const QString& projectPath, bool isNewProject) { AZ::Outcome, AZStd::string> allGemInfosResult; if (isNewProject) @@ -133,12 +133,12 @@ namespace O3DE::ProjectManager } else { - QMessageBox::critical(nullptr, "Operation failed", QString("Cannot retrieve enabled gems for project %1.\n\nError:\n%2").arg(projectPath, enabledGemNamesResult.GetError().c_str())); + QMessageBox::critical(nullptr, tr("Operation failed"), QString("Cannot retrieve enabled gems for project %1.\n\nError:\n%2").arg(projectPath, enabledGemNamesResult.GetError().c_str())); } } else { - QMessageBox::critical(nullptr, "Operation failed", QString("Cannot retrieve gems for %1.\n\nError:\n%2").arg(projectPath, allGemInfosResult.GetError().c_str())); + QMessageBox::critical(nullptr, tr("Operation failed"), QString("Cannot retrieve gems for %1.\n\nError:\n%2").arg(projectPath, allGemInfosResult.GetError().c_str())); } } diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 72db92ff20..07edb1722f 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -321,13 +321,14 @@ namespace O3DE::ProjectManager try { executionCallback(); - return AZ::Success(); } catch ([[maybe_unused]] const std::exception& e) { AZ_Warning("PythonBindings", false, "Python exception %s", e.what()); return AZ::Failure(e.what()); } + + return AZ::Success(); } bool PythonBindings::ExecuteWithLock(AZStd::function executionCallback) From 8a281072996706b469e94795718d74843b4b6f2d Mon Sep 17 00:00:00 2001 From: AMZN-nggieber <52797929+AMZN-nggieber@users.noreply.github.com> Date: Wed, 2 Jun 2021 10:23:58 -0700 Subject: [PATCH 410/811] Project Manager Setup Update Project Settings Screen and Flow * Filled out and connected up UpdateProjectCtrl and UpdateProjectsSettingsScreen --- Code/Tools/ProjectManager/CMakeLists.txt | 1 - .../Resources/ProjectManager.qss | 12 ++ .../Source/NewProjectSettingsScreen.cpp | 154 ++++------------ .../Source/NewProjectSettingsScreen.h | 17 +- .../Source/ProjectButtonWidget.cpp | 10 - .../Source/ProjectButtonWidget.h | 2 - .../ProjectManager/Source/ProjectInfo.cpp | 13 ++ .../Tools/ProjectManager/Source/ProjectInfo.h | 2 + .../Source/ProjectSettingsScreen.cpp | 120 ++++++++++-- .../Source/ProjectSettingsScreen.h | 24 ++- .../Source/ProjectSettingsScreen.ui | 113 ------------ .../ProjectManager/Source/ProjectsScreen.cpp | 10 - .../ProjectManager/Source/ProjectsScreen.h | 1 - Code/Tools/ProjectManager/Source/ScreenDefs.h | 4 +- .../ProjectManager/Source/ScreenFactory.cpp | 6 +- .../ProjectManager/Source/ScreensCtrl.cpp | 1 + .../Source/UpdateProjectCtrl.cpp | 174 +++++++++++------- .../ProjectManager/Source/UpdateProjectCtrl.h | 39 ++-- .../Source/UpdateProjectSettingsScreen.cpp | 51 +++++ .../Source/UpdateProjectSettingsScreen.h | 34 ++++ .../project_manager_files.cmake | 3 +- 21 files changed, 416 insertions(+), 375 deletions(-) delete mode 100644 Code/Tools/ProjectManager/Source/ProjectSettingsScreen.ui create mode 100644 Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp create mode 100644 Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.h diff --git a/Code/Tools/ProjectManager/CMakeLists.txt b/Code/Tools/ProjectManager/CMakeLists.txt index a655600325..aeb7be9793 100644 --- a/Code/Tools/ProjectManager/CMakeLists.txt +++ b/Code/Tools/ProjectManager/CMakeLists.txt @@ -25,7 +25,6 @@ ly_add_target( OUTPUT_NAME o3de NAMESPACE AZ AUTOMOC - AUTOUIC AUTORCC FILES_CMAKE project_manager_files.cmake diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qss b/Code/Tools/ProjectManager/Resources/ProjectManager.qss index a85b911c15..224574f522 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qss +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qss @@ -232,6 +232,18 @@ QTabBar::tab:pressed margin-left:30px; } +#projectSettingsTab::tab-bar { + left: 60px; +} + +#projectSettingsTabBar::tab { + height:50px; +} + +#projectSettingsTopFrame { + background-color:#1E252F; +} + /************** Projects **************/ #firstTimeContent > #titleLabel { font-size:60px; diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp index 53400b3193..c8dc8451ae 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp @@ -34,83 +34,57 @@ namespace O3DE::ProjectManager constexpr const char* k_pathProperty = "Path"; NewProjectSettingsScreen::NewProjectSettingsScreen(QWidget* parent) - : ScreenWidget(parent) + : ProjectSettingsScreen(parent) { - QHBoxLayout* hLayout = new QHBoxLayout(this); - hLayout->setAlignment(Qt::AlignLeft); - hLayout->setContentsMargins(0,0,0,0); + const QString defaultName{ "NewProject" }; + const QString defaultPath = QDir::toNativeSeparators(GetDefaultProjectPath() + "/" + defaultName); - // if we don't provide a parent for this box layout the stylesheet doesn't take - // if we don't set this in a frame (just use a sub-layout) all the content will align incorrectly horizontally - QFrame* projectSettingsFrame = new QFrame(this); - projectSettingsFrame->setObjectName("projectSettings"); - QVBoxLayout* vLayout = new QVBoxLayout(this); + m_projectName->lineEdit()->setText(defaultName); + m_projectPath->lineEdit()->setText(defaultPath); - // you cannot remove content margins in qss - vLayout->setContentsMargins(0,0,0,0); - vLayout->setAlignment(Qt::AlignTop); + // if we don't use a QFrame we cannot "contain" the widgets inside and move them around + // as a group + QFrame* projectTemplateWidget = new QFrame(this); + projectTemplateWidget->setObjectName("projectTemplate"); + QVBoxLayout* containerLayout = new QVBoxLayout(); + containerLayout->setAlignment(Qt::AlignTop); { - const QString defaultName{ "NewProject" }; - const QString defaultPath = QDir::toNativeSeparators(GetDefaultProjectPath() + "/" + defaultName); + QLabel* projectTemplateLabel = new QLabel(tr("Select a Project Template")); + projectTemplateLabel->setObjectName("projectTemplateLabel"); + containerLayout->addWidget(projectTemplateLabel); - m_projectName = new FormLineEditWidget(tr("Project name"), defaultName, this); - connect(m_projectName->lineEdit(), &QLineEdit::textChanged, this, &NewProjectSettingsScreen::ValidateProjectPath); - vLayout->addWidget(m_projectName); + QLabel* projectTemplateDetailsLabel = new QLabel(tr("Project templates are pre-configured with relevant Gems that provide " + "additional functionality and content to the project.")); + projectTemplateDetailsLabel->setWordWrap(true); + projectTemplateDetailsLabel->setObjectName("projectTemplateDetailsLabel"); + containerLayout->addWidget(projectTemplateDetailsLabel); - m_projectPath = new FormBrowseEditWidget(tr("Project Location"), defaultPath, this); - m_projectPath->lineEdit()->setReadOnly(true); - connect(m_projectPath->lineEdit(), &QLineEdit::textChanged, this, &NewProjectSettingsScreen::ValidateProjectPath); - vLayout->addWidget(m_projectPath); + QHBoxLayout* templateLayout = new QHBoxLayout(this); + containerLayout->addItem(templateLayout); - // if we don't use a QFrame we cannot "contain" the widgets inside and move them around - // as a group - QFrame* projectTemplateWidget = new QFrame(this); - projectTemplateWidget->setObjectName("projectTemplate"); - QVBoxLayout* containerLayout = new QVBoxLayout(); - containerLayout->setAlignment(Qt::AlignTop); + m_projectTemplateButtonGroup = new QButtonGroup(this); + m_projectTemplateButtonGroup->setObjectName("templateButtonGroup"); + auto templatesResult = PythonBindingsInterface::Get()->GetProjectTemplates(); + if (templatesResult.IsSuccess() && !templatesResult.GetValue().isEmpty()) { - QLabel* projectTemplateLabel = new QLabel(tr("Select a Project Template")); - projectTemplateLabel->setObjectName("projectTemplateLabel"); - containerLayout->addWidget(projectTemplateLabel); - - QLabel* projectTemplateDetailsLabel = new QLabel(tr("Project templates are pre-configured with relevant Gems that provide " - "additional functionality and content to the project.")); - projectTemplateDetailsLabel->setWordWrap(true); - projectTemplateDetailsLabel->setObjectName("projectTemplateDetailsLabel"); - containerLayout->addWidget(projectTemplateDetailsLabel); - - QHBoxLayout* templateLayout = new QHBoxLayout(this); - containerLayout->addItem(templateLayout); - - m_projectTemplateButtonGroup = new QButtonGroup(this); - m_projectTemplateButtonGroup->setObjectName("templateButtonGroup"); - auto templatesResult = PythonBindingsInterface::Get()->GetProjectTemplates(); - if (templatesResult.IsSuccess() && !templatesResult.GetValue().isEmpty()) + for (const ProjectTemplateInfo& projectTemplate : templatesResult.GetValue()) { - for (auto projectTemplate : templatesResult.GetValue()) - { - QRadioButton* radioButton = new QRadioButton(projectTemplate.m_name, this); - radioButton->setProperty(k_pathProperty, projectTemplate.m_path); - m_projectTemplateButtonGroup->addButton(radioButton); + QRadioButton* radioButton = new QRadioButton(projectTemplate.m_name, this); + radioButton->setProperty(k_pathProperty, projectTemplate.m_path); + m_projectTemplateButtonGroup->addButton(radioButton); - containerLayout->addWidget(radioButton); - } - - m_projectTemplateButtonGroup->buttons().first()->setChecked(true); + containerLayout->addWidget(radioButton); } - } - projectTemplateWidget->setLayout(containerLayout); - vLayout->addWidget(projectTemplateWidget); - } - projectSettingsFrame->setLayout(vLayout); - hLayout->addWidget(projectSettingsFrame); + m_projectTemplateButtonGroup->buttons().first()->setChecked(true); + } + } + projectTemplateWidget->setLayout(containerLayout); + m_verticalLayout->addWidget(projectTemplateWidget); QWidget* projectTemplateDetails = new QWidget(this); projectTemplateDetails->setObjectName("projectTemplateDetails"); - hLayout->addWidget(projectTemplateDetails); - - this->setLayout(hLayout); + m_horizontalLayout->addWidget(projectTemplateDetails); } QString NewProjectSettingsScreen::GetDefaultProjectPath() @@ -133,69 +107,13 @@ namespace O3DE::ProjectManager return ProjectManagerScreen::NewProjectSettings; } - void NewProjectSettingsScreen::ValidateProjectPath() - { - Validate(); - } - void NewProjectSettingsScreen::NotifyCurrentScreen() { Validate(); } - ProjectInfo NewProjectSettingsScreen::GetProjectInfo() - { - ProjectInfo projectInfo; - projectInfo.m_projectName = m_projectName->lineEdit()->text(); - projectInfo.m_path = m_projectPath->lineEdit()->text(); - return projectInfo; - } - QString NewProjectSettingsScreen::GetProjectTemplatePath() { return m_projectTemplateButtonGroup->checkedButton()->property(k_pathProperty).toString(); } - - bool NewProjectSettingsScreen::Validate() - { - bool projectPathIsValid = true; - if (m_projectPath->lineEdit()->text().isEmpty()) - { - projectPathIsValid = false; - m_projectPath->setErrorLabelText(tr("Please provide a valid location.")); - } - else - { - QDir path(m_projectPath->lineEdit()->text()); - if (path.exists() && !path.isEmpty()) - { - projectPathIsValid = false; - m_projectPath->setErrorLabelText(tr("This folder exists and isn't empty. Please choose a different location.")); - } - } - - bool projectNameIsValid = true; - if (m_projectName->lineEdit()->text().isEmpty()) - { - projectNameIsValid = false; - m_projectName->setErrorLabelText(tr("Please provide a project name.")); - } - else - { - // this validation should roughly match the utils.validate_identifier which the cli - // uses to validate project names - QRegExp validProjectNameRegex("[A-Za-z][A-Za-z0-9_-]{0,63}"); - const bool result = validProjectNameRegex.exactMatch(m_projectName->lineEdit()->text()); - if (!result) - { - projectNameIsValid = false; - m_projectName->setErrorLabelText(tr("Project names must start with a letter and consist of up to 64 letter, number, '_' or '-' characters")); - } - - } - - m_projectName->setErrorLabelVisible(!projectNameIsValid); - m_projectPath->setErrorLabelVisible(!projectPathIsValid); - return projectNameIsValid && projectPathIsValid; - } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h index 0560f8728d..6a4b6ec57d 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h +++ b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h @@ -12,41 +12,28 @@ #pragma once #if !defined(Q_MOC_RUN) -#include -#include +#include #endif QT_FORWARD_DECLARE_CLASS(QButtonGroup) namespace O3DE::ProjectManager { - QT_FORWARD_DECLARE_CLASS(FormLineEditWidget) - QT_FORWARD_DECLARE_CLASS(FormBrowseEditWidget) - class NewProjectSettingsScreen - : public ScreenWidget + : public ProjectSettingsScreen { public: explicit NewProjectSettingsScreen(QWidget* parent = nullptr); ~NewProjectSettingsScreen() = default; ProjectManagerScreen GetScreenEnum() override; - ProjectInfo GetProjectInfo(); QString GetProjectTemplatePath(); - bool Validate(); - void NotifyCurrentScreen() override; - protected slots: - void HandleBrowseButton(); - void ValidateProjectPath(); - private: QString GetDefaultProjectPath(); - FormLineEditWidget* m_projectName; - FormBrowseEditWidget* m_projectPath; QButtonGroup* m_projectTemplateButtonGroup; }; diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp index 72ffa686c1..b1dbd984fb 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp @@ -22,8 +22,6 @@ #include #include -//#define SHOW_ALL_PROJECT_ACTIONS - namespace O3DE::ProjectManager { inline constexpr static int s_projectImageWidth = 210; @@ -96,10 +94,6 @@ namespace O3DE::ProjectManager m_removeProjectAction = newProjectMenu->addAction(tr("Remove from O3DE")); m_deleteProjectAction = newProjectMenu->addAction(tr("Delete this Project")); -#ifdef SHOW_ALL_PROJECT_ACTIONS - m_editProjectGemsAction = newProjectMenu->addAction(tr("Cutomize Gems...")); -#endif - QFrame* footer = new QFrame(this); QHBoxLayout* hLayout = new QHBoxLayout(); hLayout->setContentsMargins(0, 0, 0, 0); @@ -121,10 +115,6 @@ namespace O3DE::ProjectManager connect(m_copyProjectAction, &QAction::triggered, [this]() { emit CopyProject(m_projectInfo.m_path); }); connect(m_removeProjectAction, &QAction::triggered, [this]() { emit RemoveProject(m_projectInfo.m_path); }); connect(m_deleteProjectAction, &QAction::triggered, [this]() { emit DeleteProject(m_projectInfo.m_path); }); - -#ifdef SHOW_ALL_PROJECT_ACTIONS - connect(m_editProjectGemsAction, &QAction::triggered, [this]() { emit EditProjectGems(m_projectInfo.m_path); }); -#endif } void ProjectButton::SetButtonEnabled(bool enabled) diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h index e82b56b3fa..3ac69b7603 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h @@ -62,7 +62,6 @@ namespace O3DE::ProjectManager signals: void OpenProject(const QString& projectName); void EditProject(const QString& projectName); - void EditProjectGems(const QString& projectName); void CopyProject(const QString& projectName); void RemoveProject(const QString& projectName); void DeleteProject(const QString& projectName); @@ -73,7 +72,6 @@ namespace O3DE::ProjectManager ProjectInfo m_projectInfo; LabelButton* m_projectImageLabel; QAction* m_editProjectAction; - QAction* m_editProjectGemsAction; QAction* m_copyProjectAction; QAction* m_removeProjectAction; QAction* m_deleteProjectAction; diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp index b0b740fad9..f0dc05cc62 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp @@ -25,6 +25,19 @@ namespace O3DE::ProjectManager { } + bool ProjectInfo::operator==(const ProjectInfo& rhs) + { + return m_path == rhs.m_path + && m_projectName == rhs.m_projectName + && m_imagePath == rhs.m_imagePath + && m_backgroundImagePath == rhs.m_backgroundImagePath; + } + + bool ProjectInfo::operator!=(const ProjectInfo& rhs) + { + return !operator==(rhs); + } + bool ProjectInfo::IsValid() const { return !m_path.isEmpty() && !m_projectName.isEmpty(); diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.h b/Code/Tools/ProjectManager/Source/ProjectInfo.h index 92a7459d78..71fa12b344 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.h +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.h @@ -25,6 +25,8 @@ namespace O3DE::ProjectManager ProjectInfo() = default; ProjectInfo(const QString& path, const QString& projectName, const QString& displayName, const QString& imagePath, const QString& backgroundImagePath, bool isNew); + bool operator==(const ProjectInfo& rhs); + bool operator!=(const ProjectInfo& rhs); bool IsValid() const; diff --git a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp index 76aa1d2897..26711753d4 100644 --- a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp @@ -11,45 +11,131 @@ */ #include +#include +#include +#include +#include -#include +#include +#include +#include +#include +#include +#include +#include namespace O3DE::ProjectManager { ProjectSettingsScreen::ProjectSettingsScreen(QWidget* parent) : ScreenWidget(parent) - , m_ui(new Ui::ProjectSettingsClass()) { - m_ui->setupUi(this); + m_horizontalLayout = new QHBoxLayout(this); + m_horizontalLayout->setAlignment(Qt::AlignLeft); + m_horizontalLayout->setContentsMargins(0, 0, 0, 0); - connect(m_ui->gemsButton, &QPushButton::pressed, this, &ProjectSettingsScreen::HandleGemsButton); + // if we don't provide a parent for this box layout the stylesheet doesn't take + // if we don't set this in a frame (just use a sub-layout) all the content will align incorrectly horizontally + QFrame* projectSettingsFrame = new QFrame(this); + projectSettingsFrame->setObjectName("projectSettings"); + m_verticalLayout = new QVBoxLayout(this); + + // you cannot remove content margins in qss + m_verticalLayout->setContentsMargins(0, 0, 0, 0); + m_verticalLayout->setAlignment(Qt::AlignTop); + + m_projectName = new FormLineEditWidget(tr("Project name"), "", this); + connect(m_projectName->lineEdit(), &QLineEdit::textChanged, this, &ProjectSettingsScreen::ValidateProjectName); + m_verticalLayout->addWidget(m_projectName); + + m_projectPath = new FormBrowseEditWidget(tr("Project Location"), "", this); + m_projectPath->lineEdit()->setReadOnly(true); + connect(m_projectPath->lineEdit(), &QLineEdit::textChanged, this, &ProjectSettingsScreen::Validate); + m_verticalLayout->addWidget(m_projectPath); + + projectSettingsFrame->setLayout(m_verticalLayout); + + m_horizontalLayout->addWidget(projectSettingsFrame); + + setLayout(m_horizontalLayout); } ProjectManagerScreen ProjectSettingsScreen::GetScreenEnum() { - return ProjectManagerScreen::ProjectSettings; + return ProjectManagerScreen::Invalid; + } + + QString ProjectSettingsScreen::GetDefaultProjectPath() + { + QString defaultPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); + AZ::Outcome engineInfoResult = PythonBindingsInterface::Get()->GetEngineInfo(); + if (engineInfoResult.IsSuccess()) + { + QDir path(QDir::toNativeSeparators(engineInfoResult.GetValue().m_defaultProjectsFolder)); + if (path.exists()) + { + defaultPath = path.absolutePath(); + } + } + return defaultPath; } ProjectInfo ProjectSettingsScreen::GetProjectInfo() { - // Impl pending next PR - return ProjectInfo(); + ProjectInfo projectInfo; + projectInfo.m_projectName = m_projectName->lineEdit()->text(); + projectInfo.m_path = m_projectPath->lineEdit()->text(); + return projectInfo; } - void ProjectSettingsScreen::SetProjectInfo() + bool ProjectSettingsScreen::ValidateProjectName() { - // Impl pending next PR + bool projectNameIsValid = true; + if (m_projectName->lineEdit()->text().isEmpty()) + { + projectNameIsValid = false; + m_projectName->setErrorLabelText(tr("Please provide a project name.")); + } + else + { + // this validation should roughly match the utils.validate_identifier which the cli + // uses to validate project names + QRegExp validProjectNameRegex("[A-Za-z][A-Za-z0-9_-]{0,63}"); + const bool result = validProjectNameRegex.exactMatch(m_projectName->lineEdit()->text()); + if (!result) + { + projectNameIsValid = false; + m_projectName->setErrorLabelText( + tr("Project names must start with a letter and consist of up to 64 letter, number, '_' or '-' characters")); + } + } + + m_projectName->setErrorLabelVisible(!projectNameIsValid); + return projectNameIsValid; + } + bool ProjectSettingsScreen::ValidateProjectPath() + { + bool projectPathIsValid = true; + if (m_projectPath->lineEdit()->text().isEmpty()) + { + projectPathIsValid = false; + m_projectPath->setErrorLabelText(tr("Please provide a valid location.")); + } + else + { + QDir path(m_projectPath->lineEdit()->text()); + if (path.exists() && !path.isEmpty()) + { + projectPathIsValid = false; + m_projectPath->setErrorLabelText(tr("This folder exists and isn't empty. Please choose a different location.")); + } + } + + m_projectPath->setErrorLabelVisible(!projectPathIsValid); + return projectPathIsValid; } bool ProjectSettingsScreen::Validate() { - // Impl pending next PR - return true; + return ValidateProjectName() && ValidateProjectPath(); } - - void ProjectSettingsScreen::HandleGemsButton() - { - emit ChangeScreenRequest(ProjectManagerScreen::GemCatalog); - } - } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.h b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.h index a4cafcd93a..0d75bbbc64 100644 --- a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.h +++ b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.h @@ -12,17 +12,18 @@ #pragma once #if !defined(Q_MOC_RUN) -#include #include +#include #endif -namespace Ui -{ - class ProjectSettingsClass; -} +QT_FORWARD_DECLARE_CLASS(QHBoxLayout) +QT_FORWARD_DECLARE_CLASS(QVBoxLayout) namespace O3DE::ProjectManager { + QT_FORWARD_DECLARE_CLASS(FormLineEditWidget) + QT_FORWARD_DECLARE_CLASS(FormBrowseEditWidget) + class ProjectSettingsScreen : public ScreenWidget { @@ -32,15 +33,20 @@ namespace O3DE::ProjectManager ProjectManagerScreen GetScreenEnum() override; ProjectInfo GetProjectInfo(); - void SetProjectInfo(); bool Validate(); protected slots: - void HandleGemsButton(); + virtual bool ValidateProjectName(); + virtual bool ValidateProjectPath(); - private: - QScopedPointer m_ui; + protected: + QString GetDefaultProjectPath(); + + QHBoxLayout* m_horizontalLayout; + QVBoxLayout* m_verticalLayout; + FormLineEditWidget* m_projectName; + FormBrowseEditWidget* m_projectPath; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.ui b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.ui deleted file mode 100644 index 934238a257..0000000000 --- a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.ui +++ /dev/null @@ -1,113 +0,0 @@ - - - ProjectSettingsClass - - - - 0 - 0 - 782 - 579 - - - - Form - - - - - - - - Project Settings - - - - - - - Gems - - - - - - - Qt::Horizontal - - - - 761 - 20 - - - - - - - - - - - - - - Project Name - - - - - - - - - - Project Location - - - - - - - - - - Project Image Location - - - - - - - - - - Project Background Image Location - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp index 7b9e3ecb9d..425aa8514d 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp @@ -182,10 +182,6 @@ namespace O3DE::ProjectManager connect(projectButton, &ProjectButton::CopyProject, this, &ProjectsScreen::HandleCopyProject); connect(projectButton, &ProjectButton::RemoveProject, this, &ProjectsScreen::HandleRemoveProject); connect(projectButton, &ProjectButton::DeleteProject, this, &ProjectsScreen::HandleDeleteProject); - -#ifdef SHOW_ALL_PROJECT_ACTIONS - connect(projectButton, &ProjectButton::EditProjectGems, this, &ProjectsScreen::HandleEditProjectGems); -#endif } layout->addWidget(projectsScrollArea); @@ -293,14 +289,8 @@ namespace O3DE::ProjectManager void ProjectsScreen::HandleEditProject(const QString& projectPath) { emit NotifyCurrentProject(projectPath); - emit ResetScreenRequest(ProjectManagerScreen::UpdateProject); emit ChangeScreenRequest(ProjectManagerScreen::UpdateProject); } - void ProjectsScreen::HandleEditProjectGems(const QString& projectPath) - { - emit NotifyCurrentProject(projectPath); - emit ChangeScreenRequest(ProjectManagerScreen::GemCatalog); - } void ProjectsScreen::HandleCopyProject(const QString& projectPath) { // Open file dialog and choose location for copied project then register copy with O3DE diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.h b/Code/Tools/ProjectManager/Source/ProjectsScreen.h index d88ba8398d..e02b34525b 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsScreen.h +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.h @@ -41,7 +41,6 @@ namespace O3DE::ProjectManager void HandleAddProjectButton(); void HandleOpenProject(const QString& projectPath); void HandleEditProject(const QString& projectPath); - void HandleEditProjectGems(const QString& projectPath); void HandleCopyProject(const QString& projectPath); void HandleRemoveProject(const QString& projectPath); void HandleDeleteProject(const QString& projectPath); diff --git a/Code/Tools/ProjectManager/Source/ScreenDefs.h b/Code/Tools/ProjectManager/Source/ScreenDefs.h index 43ed303461..198f1b5d03 100644 --- a/Code/Tools/ProjectManager/Source/ScreenDefs.h +++ b/Code/Tools/ProjectManager/Source/ScreenDefs.h @@ -26,7 +26,7 @@ namespace O3DE::ProjectManager GemCatalog, Projects, UpdateProject, - ProjectSettings, + UpdateProjectSettings, EngineSettings }; @@ -37,7 +37,7 @@ namespace O3DE::ProjectManager { "GemCatalog", ProjectManagerScreen::GemCatalog}, { "Projects", ProjectManagerScreen::Projects}, { "UpdateProject", ProjectManagerScreen::UpdateProject}, - { "ProjectSettings", ProjectManagerScreen::ProjectSettings}, + { "UpdateProjectSettings", ProjectManagerScreen::UpdateProjectSettings}, { "EngineSettings", ProjectManagerScreen::EngineSettings} }; diff --git a/Code/Tools/ProjectManager/Source/ScreenFactory.cpp b/Code/Tools/ProjectManager/Source/ScreenFactory.cpp index b2b4376e14..a85f44080d 100644 --- a/Code/Tools/ProjectManager/Source/ScreenFactory.cpp +++ b/Code/Tools/ProjectManager/Source/ScreenFactory.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include namespace O3DE::ProjectManager @@ -42,8 +42,8 @@ namespace O3DE::ProjectManager case (ProjectManagerScreen::UpdateProject): newScreen = new UpdateProjectCtrl(parent); break; - case (ProjectManagerScreen::ProjectSettings): - newScreen = new ProjectSettingsScreen(parent); + case (ProjectManagerScreen::UpdateProjectSettings): + newScreen = new UpdateProjectSettingsScreen(parent); break; case (ProjectManagerScreen::EngineSettings): newScreen = new EngineSettingsScreen(parent); diff --git a/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp b/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp index 6206d4cee9..52fcbf354a 100644 --- a/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp index b3180966ce..dd130d804d 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp @@ -10,15 +10,20 @@ * */ -#include -#include +#include #include -#include +#include +#include +#include +#include +#include #include -#include -#include #include +#include +#include +#include +#include namespace O3DE::ProjectManager { @@ -26,31 +31,57 @@ namespace O3DE::ProjectManager : ScreenWidget(parent) { QVBoxLayout* vLayout = new QVBoxLayout(); - setLayout(vLayout); + vLayout->setContentsMargins(0, 0, 0, 0); - m_screensCtrl = new ScreensCtrl(); - vLayout->addWidget(m_screensCtrl); + m_header = new ScreenHeader(this); + m_header->setTitle(tr("")); + m_header->setSubTitle(tr("Edit Project Settings:")); + connect(m_header->backButton(), &QPushButton::clicked, this, &UpdateProjectCtrl::HandleBackButton); + vLayout->addWidget(m_header); + + m_updateSettingsScreen = new UpdateProjectSettingsScreen(); + m_gemCatalogScreen = new GemCatalogScreen(); + + m_stack = new QStackedWidget(this); + m_stack->setObjectName("body"); + m_stack->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding)); + vLayout->addWidget(m_stack); + + QFrame* topBarFrameWidget = new QFrame(this); + topBarFrameWidget->setObjectName("projectSettingsTopFrame"); + QHBoxLayout* topBarHLayout = new QHBoxLayout(); + topBarHLayout->setContentsMargins(0, 0, 0, 0); + topBarFrameWidget->setLayout(topBarHLayout); + + QTabWidget* tabWidget = new QTabWidget(); + tabWidget->setObjectName("projectSettingsTab"); + tabWidget->tabBar()->setObjectName("projectSettingsTabBar"); + tabWidget->addTab(m_updateSettingsScreen, tr("General")); + + QPushButton* gemsButton = new QPushButton(tr("Add More Gems"), this); + topBarHLayout->addWidget(gemsButton); + tabWidget->setCornerWidget(gemsButton); + + topBarHLayout->addWidget(tabWidget); + + m_stack->addWidget(topBarFrameWidget); + m_stack->addWidget(m_gemCatalogScreen); QDialogButtonBox* backNextButtons = new QDialogButtonBox(); + backNextButtons->setObjectName("footer"); vLayout->addWidget(backNextButtons); m_backButton = backNextButtons->addButton(tr("Back"), QDialogButtonBox::RejectRole); + m_backButton->setProperty("secondary", true); m_nextButton = backNextButtons->addButton(tr("Next"), QDialogButtonBox::ApplyRole); - connect(m_backButton, &QPushButton::pressed, this, &UpdateProjectCtrl::HandleBackButton); - connect(m_nextButton, &QPushButton::pressed, this, &UpdateProjectCtrl::HandleNextButton); + connect(gemsButton, &QPushButton::clicked, this, &UpdateProjectCtrl::HandleGemsButton); + connect(m_backButton, &QPushButton::clicked, this, &UpdateProjectCtrl::HandleBackButton); + connect(m_nextButton, &QPushButton::clicked, this, &UpdateProjectCtrl::HandleNextButton); connect(reinterpret_cast(parent), &ScreensCtrl::NotifyCurrentProject, this, &UpdateProjectCtrl::UpdateCurrentProject); - m_screensOrder = - { - ProjectManagerScreen::ProjectSettings, - ProjectManagerScreen::GemCatalog - }; - m_screensCtrl->BuildScreens(m_screensOrder); - m_screensCtrl->ForceChangeToScreen(ProjectManagerScreen::ProjectSettings, false); - - UpdateNextButtonText(); - + Update(); + setLayout(vLayout); } ProjectManagerScreen UpdateProjectCtrl::GetScreenEnum() @@ -58,63 +89,70 @@ namespace O3DE::ProjectManager return ProjectManagerScreen::UpdateProject; } + void UpdateProjectCtrl::NotifyCurrentScreen() + { + m_stack->setCurrentIndex(ScreenOrder::Settings); + Update(); + } + + void UpdateProjectCtrl::HandleGemsButton() + { + m_stack->setCurrentWidget(m_gemCatalogScreen); + Update(); + } + void UpdateProjectCtrl::HandleBackButton() { - if (!m_screensCtrl->GotoPreviousScreen()) + if (m_stack->currentIndex() > 0) { - emit GotoPreviousScreenRequest(); + m_stack->setCurrentIndex(m_stack->currentIndex() - 1); + Update(); } else { - UpdateNextButtonText(); + emit GotoPreviousScreenRequest(); } } void UpdateProjectCtrl::HandleNextButton() { - ScreenWidget* currentScreen = m_screensCtrl->GetCurrentScreen(); - ProjectManagerScreen screenEnum = currentScreen->GetScreenEnum(); - auto screenOrderIter = m_screensOrder.begin(); - for (; screenOrderIter != m_screensOrder.end(); ++screenOrderIter) + if (m_stack->currentIndex() == ScreenOrder::Settings) { - if (*screenOrderIter == screenEnum) + if (m_updateSettingsScreen) { - ++screenOrderIter; - break; - } - } - - if (screenEnum == ProjectManagerScreen::ProjectSettings) - { - auto projectScreen = reinterpret_cast(currentScreen); - if (projectScreen) - { - if (!projectScreen->Validate()) + if (!m_updateSettingsScreen->Validate()) { QMessageBox::critical(this, tr("Invalid project settings"), tr("Invalid project settings")); return; } - m_projectInfo = projectScreen->GetProjectInfo(); + ProjectInfo newProjectSettings = m_updateSettingsScreen->GetProjectInfo(); + + // Update project if settings changed + if (m_projectInfo != newProjectSettings) + { + bool result = PythonBindingsInterface::Get()->UpdateProject(newProjectSettings); + if (!result) + { + QMessageBox::critical(this, tr("Project update failed"), tr("Failed to update project.")); + return; + } + } + + // Check if project path has changed and move it + if (newProjectSettings.m_path != m_projectInfo.m_path) + { + if (!ProjectUtils::MoveProject(m_projectInfo.m_path, newProjectSettings.m_path)) + { + QMessageBox::critical(this, tr("Project move failed"), tr("Failed to move project.")); + return; + } + } + + m_projectInfo = newProjectSettings; } } - if (screenOrderIter != m_screensOrder.end()) - { - m_screensCtrl->ChangeToScreen(*screenOrderIter); - UpdateNextButtonText(); - } - else - { - auto result = PythonBindingsInterface::Get()->UpdateProject(m_projectInfo); - if (result) - { - emit ChangeScreenRequest(ProjectManagerScreen::Projects); - } - else - { - QMessageBox::critical(this, tr("Project update failed"), tr("Failed to update project.")); - } - } + emit ChangeScreenRequest(ProjectManagerScreen::Projects); } void UpdateProjectCtrl::UpdateCurrentProject(const QString& projectPath) @@ -124,16 +162,28 @@ namespace O3DE::ProjectManager { m_projectInfo = projectResult.GetValue(); } + + Update(); + UpdateSettingsScreen(); } - void UpdateProjectCtrl::UpdateNextButtonText() + void UpdateProjectCtrl::Update() { - QString nextButtonText = tr("Continue"); - if (m_screensCtrl->GetCurrentScreen()->GetScreenEnum() == ProjectManagerScreen::GemCatalog) + if (m_stack->currentIndex() == ScreenOrder::Gems) { - nextButtonText = tr("Update Project"); + m_header->setSubTitle(QString(tr("Add More Gems to \"%1\"")).arg(m_projectInfo.m_projectName)); + m_nextButton->setText(tr("Confirm")); } - m_nextButton->setText(nextButtonText); + else + { + m_header->setSubTitle(QString(tr("Edit Project Settings: \"%1\"")).arg(m_projectInfo.m_projectName)); + m_nextButton->setText(tr("Save")); + } + } + + void UpdateProjectCtrl::UpdateSettingsScreen() + { + m_updateSettingsScreen->SetProjectInfo(m_projectInfo); } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.h b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.h index ee871e7bb2..231bfb8f19 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.h +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.h @@ -12,40 +12,57 @@ #pragma once #if !defined(Q_MOC_RUN) -#include "ProjectInfo.h" +#include #include -#include -#include #endif +QT_FORWARD_DECLARE_CLASS(QStackedWidget) +QT_FORWARD_DECLARE_CLASS(QTabWidget) +QT_FORWARD_DECLARE_CLASS(QPushButton) +QT_FORWARD_DECLARE_CLASS(QFrame) namespace O3DE::ProjectManager { - class UpdateProjectCtrl - : public ScreenWidget + QT_FORWARD_DECLARE_CLASS(ScreenHeader) + QT_FORWARD_DECLARE_CLASS(UpdateProjectSettingsScreen) + QT_FORWARD_DECLARE_CLASS(GemCatalogScreen) + + class UpdateProjectCtrl : public ScreenWidget { public: explicit UpdateProjectCtrl(QWidget* parent = nullptr); ~UpdateProjectCtrl() = default; ProjectManagerScreen GetScreenEnum() override; + protected: + void NotifyCurrentScreen() override; protected slots: void HandleBackButton(); void HandleNextButton(); + void HandleGemsButton(); void UpdateCurrentProject(const QString& projectPath); private: - void UpdateNextButtonText(); + void Update(); + void UpdateSettingsScreen(); - ScreensCtrl* m_screensCtrl; - QPushButton* m_backButton; - QPushButton* m_nextButton; + enum ScreenOrder + { + Settings, + Gems + }; + + ScreenHeader* m_header = nullptr; + QStackedWidget* m_stack = nullptr; + UpdateProjectSettingsScreen* m_updateSettingsScreen = nullptr; + GemCatalogScreen* m_gemCatalogScreen = nullptr; + + QPushButton* m_backButton = nullptr; + QPushButton* m_nextButton = nullptr; QVector m_screensOrder; ProjectInfo m_projectInfo; - - ProjectManagerScreen m_screenEnum; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp new file mode 100644 index 0000000000..c29be3c7fd --- /dev/null +++ b/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp @@ -0,0 +1,51 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include +#include +#include + +#include +#include + +namespace O3DE::ProjectManager +{ + UpdateProjectSettingsScreen::UpdateProjectSettingsScreen(QWidget* parent) + : ProjectSettingsScreen(parent) + { + } + + ProjectManagerScreen UpdateProjectSettingsScreen::GetScreenEnum() + { + return ProjectManagerScreen::UpdateProjectSettings; + } + + void UpdateProjectSettingsScreen::SetProjectInfo(const ProjectInfo& projectInfo) + { + m_projectName->lineEdit()->setText(projectInfo.m_projectName); + m_projectPath->lineEdit()->setText(projectInfo.m_path); + } + + bool UpdateProjectSettingsScreen::ValidateProjectPath() + { + bool projectPathIsValid = true; + if (m_projectPath->lineEdit()->text().isEmpty()) + { + projectPathIsValid = false; + m_projectPath->setErrorLabelText(tr("Please provide a valid location.")); + } + + m_projectPath->setErrorLabelVisible(!projectPathIsValid); + return projectPathIsValid; + } + +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.h b/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.h new file mode 100644 index 0000000000..95bbceb9c6 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.h @@ -0,0 +1,34 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#endif + +namespace O3DE::ProjectManager +{ + class UpdateProjectSettingsScreen + : public ProjectSettingsScreen + { + public: + explicit UpdateProjectSettingsScreen(QWidget* parent = nullptr); + ~UpdateProjectSettingsScreen() = default; + ProjectManagerScreen GetScreenEnum() override; + + void SetProjectInfo(const ProjectInfo& projectInfo); + + protected: + bool ValidateProjectPath() override; + }; + +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index feaea4c172..a7a36f26ab 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -38,6 +38,8 @@ set(FILES Source/ProjectInfo.cpp Source/ProjectUtils.h Source/ProjectUtils.cpp + Source/UpdateProjectSettingsScreen.h + Source/UpdateProjectSettingsScreen.cpp Source/NewProjectSettingsScreen.h Source/NewProjectSettingsScreen.cpp Source/CreateProjectCtrl.h @@ -48,7 +50,6 @@ set(FILES Source/ProjectsScreen.cpp Source/ProjectSettingsScreen.h Source/ProjectSettingsScreen.cpp - Source/ProjectSettingsScreen.ui Source/EngineSettingsScreen.h Source/EngineSettingsScreen.cpp Source/ProjectButtonWidget.h From 5dff21239894201c1257968a45e85ee7376b4643 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 2 Jun 2021 19:49:07 +0200 Subject: [PATCH 411/811] Fixing non-unity build --- Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp index 2c94c621bb..a383a0f93b 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include From a1b8d1233cb75a330adfd260ad85c827f163f84d Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 11:28:22 -0700 Subject: [PATCH 412/811] [cpack_installer] initial work for installer Jenkins jobs --- .../build/Platform/Windows/build_config.json | 15 ++++++++ .../Windows/build_installer_windows.cmd | 22 +++++++++++ .../build/Platform/Windows/build_windows.cmd | 9 +++++ .../Platform/Windows/installer_windows.cmd | 38 +++++++++++++++++++ .../Platform/Windows/install_utiltools.ps1 | 3 ++ 5 files changed, 87 insertions(+) create mode 100644 scripts/build/Platform/Windows/build_installer_windows.cmd create mode 100644 scripts/build/Platform/Windows/installer_windows.cmd diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index 38cd7d6ad8..b0d16f1fb6 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -306,6 +306,21 @@ "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" } }, + "windows_installer": { + "TAGS": [ + "package" + ], + "COMMAND": "build_installer_windows.cmd", + "PARAMETERS": { + "CONFIGURATION": "profile", + "OUTPUT_DIRECTORY": "build\\windows_vs2019", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_DISABLE_TEST_MODULES=TRUE", + "CMAKE_INCLUDE_WIX": "True", + "CMAKE_LY_PROJECTS": "", + "CMAKE_TARGET": "ALL_BUILD", + "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" + } + }, "project_enginesource_profile_vs2019": { "TAGS": [ "project" diff --git a/scripts/build/Platform/Windows/build_installer_windows.cmd b/scripts/build/Platform/Windows/build_installer_windows.cmd new file mode 100644 index 0000000000..0d50f4b57a --- /dev/null +++ b/scripts/build/Platform/Windows/build_installer_windows.cmd @@ -0,0 +1,22 @@ +@ECHO OFF +REM +REM All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +REM its licensors. +REM +REM For complete copyright and license terms please see the LICENSE at the root of this +REM distribution (the "License"). All use of this software is governed by the License, +REM or, if provided, by the license below or the license accompanying this file. Do not +REM remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM + +CALL "%~dp0build_windows.cmd" +IF NOT %ERRORLEVEL%==0 GOTO :error + +CALL "%~dp0installer_windows.cmd" +IF NOT %ERRORLEVEL%==0 GOTO :error + +EXIT /b 0 + +:error +EXIT /b 1 \ No newline at end of file diff --git a/scripts/build/Platform/Windows/build_windows.cmd b/scripts/build/Platform/Windows/build_windows.cmd index 3e995e1905..109db3438e 100644 --- a/scripts/build/Platform/Windows/build_windows.cmd +++ b/scripts/build/Platform/Windows/build_windows.cmd @@ -38,6 +38,15 @@ IF NOT EXIST %TMP% ( REM Compute half the amount of processors so some jobs can run SET /a HALF_PROCESSORS = NUMBER_OF_PROCESSORS / 2 +IF %CMAKE_INCLUDE_WIX%=="True" ( + REM Explicitly enable wix via command line arg for forensic logging + SET EXTRA_CMAKE_OPTIONS=%EXTRA_CMAKE_OPTIONS% -DLY_WIX_PATH="%WIX%" +) +ELSE ( + REM Disable implicit enabling of windows packing by clearing out the wix variable + SET WIX= +) + SET LAST_CONFIGURE_CMD_FILE=ci_last_configure_cmd.txt SET CONFIGURE_CMD=cmake %SOURCE_DIRECTORY% %CMAKE_OPTIONS% %EXTRA_CMAKE_OPTIONS% -DLY_3RDPARTY_PATH="%LY_3RDPARTY_PATH%" -DLY_PROJECTS=%CMAKE_LY_PROJECTS% IF NOT EXIST CMakeCache.txt ( diff --git a/scripts/build/Platform/Windows/installer_windows.cmd b/scripts/build/Platform/Windows/installer_windows.cmd new file mode 100644 index 0000000000..c613f0a1e3 --- /dev/null +++ b/scripts/build/Platform/Windows/installer_windows.cmd @@ -0,0 +1,38 @@ +@ECHO OFF +REM +REM All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +REM its licensors. +REM +REM For complete copyright and license terms please see the LICENSE at the root of this +REM distribution (the "License"). All use of this software is governed by the License, +REM or, if provided, by the license below or the license accompanying this file. Do not +REM remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM + +SETLOCAL EnableDelayedExpansion + +CALL %~dp0env_windows.cmd + +IF NOT EXIST %OUTPUT_DIRECTORY% ( + ECHO [ci_build] Error: $OUTPUT_DIRECTORY was not found + GOTO :error +) +PUSHD %OUTPUT_DIRECTORY% + +REM Override the temporary directory used by wix to the EBS volume +SET "WIX_TEMP=!WORKSPACE!/temp/wix" + +REM Run cpack +ECHO [ci_build] cpack -C %CONFIGURATION% +cpack -C %CONFIGURATION% +IF NOT %ERRORLEVEL%==0 GOTO :popd_error + +POPD +EXIT /b 0 + +:popd_error +POPD + +:error +EXIT /b 1 \ No newline at end of file diff --git a/scripts/build/build_node/Platform/Windows/install_utiltools.ps1 b/scripts/build/build_node/Platform/Windows/install_utiltools.ps1 index 4e3695d35d..35ae04cc09 100644 --- a/scripts/build/build_node/Platform/Windows/install_utiltools.ps1 +++ b/scripts/build/build_node/Platform/Windows/install_utiltools.ps1 @@ -29,3 +29,6 @@ choco install corretto8jdk -y --ia INSTALLDIR="c:\jdk8" # Custom directory to ha # Install CMake choco install cmake -y --installargs 'ADD_CMAKE_TO_PATH=System' + +# Install WIX +choco install wixtoolset -y From 3549db295e3732fa0e70652973881f0e801d96ab Mon Sep 17 00:00:00 2001 From: Junbo Liang <68558268+junbo75@users.noreply.github.com> Date: Wed, 2 Jun 2021 11:36:20 -0700 Subject: [PATCH 413/811] [LYN-4184] AWSClientAuth, AWSCore and AWSMetrics don't have the expected target or alias defined (#1089) [LYN-4184] AWSClientAuth, AWSCore and AWSMetrics don't have the expected target or alias defined --- Gems/AWSClientAuth/Code/CMakeLists.txt | 6 +++++- Gems/AWSCore/Code/CMakeLists.txt | 6 ++---- Gems/AWSCore/Code/Include/Private/AWSCoreEditorModule.h | 6 +++--- Gems/AWSCore/Code/Source/AWSCoreEditorModule.cpp | 8 +++----- Gems/AWSCore/Code/Source/AWSCoreModule.cpp | 2 -- Gems/AWSCore/Code/awscore_editor_shared_files.cmake | 2 -- Gems/AWSMetrics/Code/CMakeLists.txt | 6 +++++- 7 files changed, 18 insertions(+), 18 deletions(-) diff --git a/Gems/AWSClientAuth/Code/CMakeLists.txt b/Gems/AWSClientAuth/Code/CMakeLists.txt index 40f6e0fe36..3f85b6453e 100644 --- a/Gems/AWSClientAuth/Code/CMakeLists.txt +++ b/Gems/AWSClientAuth/Code/CMakeLists.txt @@ -56,9 +56,13 @@ ly_add_target( Gem::HttpRequestor ) -# servers and clients use the above module. +# Load the "Gem::AWSClientAuth" module in all types of applications. ly_create_alias(NAME AWSClientAuth.Servers NAMESPACE Gem TARGETS Gem::AWSClientAuth) ly_create_alias(NAME AWSClientAuth.Clients NAMESPACE Gem TARGETS Gem::AWSClientAuth) +if (PAL_TRAIT_BUILD_HOST_TOOLS) + ly_create_alias(NAME AWSClientAuth.Tools NAMESPACE Gem TARGETS Gem::AWSClientAuth) + ly_create_alias(NAME AWSClientAuth.Builders NAMESPACE Gem TARGETS Gem::AWSClientAuth) +endif() ################################################################################ # Tests diff --git a/Gems/AWSCore/Code/CMakeLists.txt b/Gems/AWSCore/Code/CMakeLists.txt index 46046c0791..7edb22124f 100644 --- a/Gems/AWSCore/Code/CMakeLists.txt +++ b/Gems/AWSCore/Code/CMakeLists.txt @@ -79,14 +79,12 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) INCLUDE_DIRECTORIES PRIVATE Include/Private - COMPILE_DEFINITIONS - PRIVATE - AWSCORE_EDITOR BUILD_DEPENDENCIES PRIVATE AZ::AzCore - Gem::AWSCore.Static Gem::AWSCore.Editor.Static + RUNTIME_DEPENDENCIES + Gem::AWSCore ) ly_add_target( diff --git a/Gems/AWSCore/Code/Include/Private/AWSCoreEditorModule.h b/Gems/AWSCore/Code/Include/Private/AWSCoreEditorModule.h index 91a1af00d9..45a2c1f9f7 100644 --- a/Gems/AWSCore/Code/Include/Private/AWSCoreEditorModule.h +++ b/Gems/AWSCore/Code/Include/Private/AWSCoreEditorModule.h @@ -11,15 +11,15 @@ #pragma once -#include +#include namespace AWSCore { class AWSCoreEditorModule - : public AWSCoreModule + :public AZ::Module { public: - AZ_RTTI(AWSCoreEditorModule, "{C1C9B898-848B-4C2F-A7AA-69642D12BCB5}", AWSCoreModule); + AZ_RTTI(AWSCoreEditorModule, "{C1C9B898-848B-4C2F-A7AA-69642D12BCB5}", AZ::Module); AZ_CLASS_ALLOCATOR(AWSCoreEditorModule, AZ::SystemAllocator, 0); AWSCoreEditorModule(); diff --git a/Gems/AWSCore/Code/Source/AWSCoreEditorModule.cpp b/Gems/AWSCore/Code/Source/AWSCoreEditorModule.cpp index d8df1695c2..69e45bfd68 100644 --- a/Gems/AWSCore/Code/Source/AWSCoreEditorModule.cpp +++ b/Gems/AWSCore/Code/Source/AWSCoreEditorModule.cpp @@ -15,7 +15,6 @@ namespace AWSCore { AWSCoreEditorModule::AWSCoreEditorModule() - : AWSCoreModule() { // Push results of [MyComponent]::CreateDescriptor() into m_descriptors here. m_descriptors.insert(m_descriptors.end(), { @@ -28,10 +27,9 @@ namespace AWSCore */ AZ::ComponentTypeList AWSCoreEditorModule::GetRequiredSystemComponents() const { - AZ::ComponentTypeList requiredComponents = AWSCoreModule::GetRequiredSystemComponents(); - requiredComponents.push_back(azrtti_typeid()); - - return requiredComponents; + return AZ::ComponentTypeList{ + azrtti_typeid() + }; } } diff --git a/Gems/AWSCore/Code/Source/AWSCoreModule.cpp b/Gems/AWSCore/Code/Source/AWSCoreModule.cpp index 19a3ad4383..a80ca62b89 100644 --- a/Gems/AWSCore/Code/Source/AWSCoreModule.cpp +++ b/Gems/AWSCore/Code/Source/AWSCoreModule.cpp @@ -40,9 +40,7 @@ namespace AWSCore } -#if !defined(AWSCORE_EDITOR) // DO NOT MODIFY THIS LINE UNLESS YOU RENAME THE GEM // The first parameter should be GemName_GemIdLower // The second should be the fully qualified name of the class above AZ_DECLARE_MODULE_CLASS(Gem_AWSCore, AWSCore::AWSCoreModule) -#endif diff --git a/Gems/AWSCore/Code/awscore_editor_shared_files.cmake b/Gems/AWSCore/Code/awscore_editor_shared_files.cmake index 61ff9c3bf2..42cebe8dc4 100644 --- a/Gems/AWSCore/Code/awscore_editor_shared_files.cmake +++ b/Gems/AWSCore/Code/awscore_editor_shared_files.cmake @@ -11,7 +11,5 @@ set(FILES Include/Private/AWSCoreEditorModule.h - Include/Private/AWSCoreModule.h Source/AWSCoreEditorModule.cpp - Source/AWSCoreModule.cpp ) diff --git a/Gems/AWSMetrics/Code/CMakeLists.txt b/Gems/AWSMetrics/Code/CMakeLists.txt index aa790371d2..3e7118cb58 100644 --- a/Gems/AWSMetrics/Code/CMakeLists.txt +++ b/Gems/AWSMetrics/Code/CMakeLists.txt @@ -46,9 +46,13 @@ ly_add_target( Gem::AWSCore ) -# Servers and Clients use the above metrics module +# Load the "Gem::AWSMetrics" module in all types of applications. ly_create_alias(NAME AWSMetrics.Servers NAMESPACE Gem TARGETS Gem::AWSMetrics) ly_create_alias(NAME AWSMetrics.Clients NAMESPACE Gem TARGETS Gem::AWSMetrics) +if (PAL_TRAIT_BUILD_HOST_TOOLS) + ly_create_alias(NAME AWSMetrics.Tools NAMESPACE Gem TARGETS Gem::AWSMetrics) + ly_create_alias(NAME AWSMetrics.Builders NAMESPACE Gem TARGETS Gem::AWSMetrics) +endif() ################################################################################ # Tests From ee0ecc2fa03b73cb95e3987d56a63441cfc8fe0a Mon Sep 17 00:00:00 2001 From: mnaumov Date: Wed, 2 Jun 2021 11:49:08 -0700 Subject: [PATCH 414/811] [ATOM-15711] Changing thumbmail sphere to polar sphere --- Gems/Atom/Feature/Common/Assets/Models/sphere.fbx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Models/sphere.fbx b/Gems/Atom/Feature/Common/Assets/Models/sphere.fbx index 5c8f550c8c..eb02c68394 100644 --- a/Gems/Atom/Feature/Common/Assets/Models/sphere.fbx +++ b/Gems/Atom/Feature/Common/Assets/Models/sphere.fbx @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a476e99b55cf2a76fef6775c5a57dad29f8ffcb942c625bab04c89051a72a560 -size 62626 +oid sha256:838830c99f344f5b68e5e85c9bc52751350caf48e662c9c2b767ab77039bbd8f +size 103472 From cfd06f2e4a46869052dd5d6e5baee03d21860d35 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 13:10:11 -0700 Subject: [PATCH 415/811] [cpack_installer] added check for desired cmake version to be at least greater than minimum required plus minor cleanup --- cmake/Packaging.cmake | 10 ++++++++-- cmake/Platform/Windows/Packaging_windows.cmake | 4 ++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index 84bad13687..e7136eab12 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -51,6 +51,12 @@ if(NOT CPACK_GENERATOR) return() endif() +if(${CPACK_DESIRED_CMAKE_VERSION} VERSION_LESS ${CMAKE_MINIMUM_REQUIRED_VERSION}) + message(FATAL_ERROR + "The desired version of CMake to be included in the package is " + "is below the minium required version of CMake to run") +endif() + # pull down the desired copy of CMake so it can be included in the package if(NOT (CPACK_CMAKE_PACKAGE_FILE AND CPACK_CMAKE_PACKAGE_HASH)) message(FATAL_ERROR @@ -67,7 +73,7 @@ list(GET _version_componets 1 _minor_version) set(_url_version_tag "v${_major_version}.${_minor_version}") set(_package_url "https://cmake.org/files/${_url_version_tag}/${CPACK_CMAKE_PACKAGE_FILE}") -message(STATUS "Ensuring CMake ${CPACK_DESIRED_CMAKE_VERSION} is available for packaging...") +message(STATUS "Downloading CMake ${CPACK_DESIRED_CMAKE_VERSION} for packaging...") download_file( URL ${_package_url} TARGET_FILE ${_cmake_package_dest} @@ -77,7 +83,7 @@ download_file( list(GET _results 0 _status_code) if (${_status_code} EQUAL 0 AND EXISTS ${_cmake_package_dest}) - message(STATUS "-> Package found and verified!") + message(STATUS "Package found and verified!") else() file(REMOVE ${_cmake_package_dest}) list(REMOVE_AT _results 0) diff --git a/cmake/Platform/Windows/Packaging_windows.cmake b/cmake/Platform/Windows/Packaging_windows.cmake index db9c7fc906..5210c24e7b 100644 --- a/cmake/Platform/Windows/Packaging_windows.cmake +++ b/cmake/Platform/Windows/Packaging_windows.cmake @@ -12,7 +12,7 @@ set(LY_WIX_PATH "" CACHE PATH "Path to the WiX install path") if(LY_WIX_PATH) - file(TO_CMAKE_PATH ${LY_QTIFW_PATH} CPACK_WIX_ROOT) + file(TO_CMAKE_PATH ${LY_WIX_PATH} CPACK_WIX_ROOT) elseif(DEFINED ENV{WIX}) file(TO_CMAKE_PATH $ENV{WIX} CPACK_WIX_ROOT) endif() @@ -26,7 +26,7 @@ else() return() endif() -set(CPACK_GENERATOR "WIX") +set(CPACK_GENERATOR WIX) set(_cmake_package_name "cmake-${CPACK_DESIRED_CMAKE_VERSION}-windows-x86_64") set(CPACK_CMAKE_PACKAGE_FILE "${_cmake_package_name}.zip") From 12cdaed03e0c968630c4b27d25d86cdeede3c389 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 13:58:37 -0700 Subject: [PATCH 416/811] [cpack_installer] updated installer icon/logo --- cmake/Platform/Windows/Packaging/product_icon.ico | 4 ++-- cmake/Platform/Windows/Packaging/product_logo.png | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmake/Platform/Windows/Packaging/product_icon.ico b/cmake/Platform/Windows/Packaging/product_icon.ico index 0680ceea19..e7b77c35bf 100644 --- a/cmake/Platform/Windows/Packaging/product_icon.ico +++ b/cmake/Platform/Windows/Packaging/product_icon.ico @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c042fce57915fc749abc7b37de765fd697c3c4d7de045a3d44805aa0ce29901a -size 107016 +oid sha256:d717f77fe01f45df934a61bbc215e5322447d21e16f3cebcf2a02f148178f266 +size 106449 diff --git a/cmake/Platform/Windows/Packaging/product_logo.png b/cmake/Platform/Windows/Packaging/product_logo.png index d5fd60ffb8..ac9c06f8f1 100644 --- a/cmake/Platform/Windows/Packaging/product_logo.png +++ b/cmake/Platform/Windows/Packaging/product_logo.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ac0348c906c91de864cba91c0231b4794d8a00fafa630d13f2232351b90aa59b +oid sha256:8c804a6be619b9f35cad46eab30b94def7a4ac7142a92cb3f7c78a659381d834 size 11074 From 7631cdc11e6e0b23dba10c16b774bb0dc6825757 Mon Sep 17 00:00:00 2001 From: Qing Tao <55564570+VickyAtAZ@users.noreply.github.com> Date: Wed, 2 Jun 2021 14:06:04 -0700 Subject: [PATCH 417/811] ATOM-15659 Add changing StencilState support to DynamicDrawContext (#1009) --- .../DynamicDraw/DynamicDrawContext.h | 8 +-- .../DynamicDraw/DynamicDrawContext.cpp | 54 ++++++++----------- 2 files changed, 27 insertions(+), 35 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawContext.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawContext.h index 2dd0865688..81b23068a1 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawContext.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawContext.h @@ -43,7 +43,7 @@ namespace AZ { PrimitiveType = AZ_BIT(0), DepthState = AZ_BIT(1), - EnableStencil = AZ_BIT(2), + StencilState = AZ_BIT(2), FaceCullMode = AZ_BIT(3), BlendMode = AZ_BIT(4) }; @@ -110,8 +110,8 @@ namespace AZ //! Set DepthState if DrawStateOptions::DepthState option is enabled void SetDepthState(RHI::DepthState depthState); - //! Enable/disable stencil if DrawStateOptions::EnableStencil option is enabled - void SetEnableStencil(bool enable); + //! Set StencilState if DrawStateOptions::StencilState option is enabled + void SetStencilState(RHI::StencilState stencilState); //! Set CullMode if DrawStateOptions::FaceCullMode option is enabled void SetCullMode(RHI::CullMode cullMode); //! Set TargetBlendState for target 0 if DrawStateOptions::BlendMode option is enabled @@ -188,7 +188,7 @@ namespace AZ // states available for change RHI::CullMode m_cullMode; RHI::DepthState m_depthState; - bool m_enableStencil; + RHI::StencilState m_stencilState; RHI::PrimitiveTopology m_topology; RHI::TargetBlendState m_blendState0; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp index 4e4a7a5e71..00c2122825 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp @@ -30,25 +30,7 @@ namespace AZ constexpr const char* PerContextSrgName = "PerContextSrg"; constexpr const char* PerDrawSrgName = "PerDrawSrg"; }; - - bool CompareTargetBlendState(const RHI::TargetBlendState& firstState, const RHI::TargetBlendState& secondState) - { - return !(firstState.m_enable != secondState.m_enable - || firstState.m_blendOp != secondState.m_blendOp - || firstState.m_blendDest != secondState.m_blendDest - || firstState.m_blendSource != secondState.m_blendSource - || firstState.m_blendAlphaDest != secondState.m_blendAlphaDest - || firstState.m_blendAlphaOp != secondState.m_blendAlphaOp - || firstState.m_blendAlphaSource != secondState.m_blendAlphaSource); - } - - bool CompareDepthState(const RHI::DepthState& firstState, const RHI::DepthState& secondState) - { - return !(firstState.m_enable != secondState.m_enable - || firstState.m_func != secondState.m_func - || firstState.m_writeMask != secondState.m_writeMask); - } - + void DynamicDrawContext::MultiStates::UpdateHash(const DrawStateOptions& drawStateOptions) { if (!m_isDirty) @@ -70,9 +52,19 @@ namespace AZ seed = TypeHash64(m_depthState.m_writeMask, seed); } - if (RHI::CheckBitsAny(drawStateOptions, DrawStateOptions::EnableStencil)) + if (RHI::CheckBitsAny(drawStateOptions, DrawStateOptions::StencilState)) { - seed = TypeHash64(m_enableStencil, seed); + seed = TypeHash64(m_stencilState.m_enable, seed); + seed = TypeHash64(m_stencilState.m_readMask, seed); + seed = TypeHash64(m_stencilState.m_writeMask, seed); + seed = TypeHash64(m_stencilState.m_frontFace.m_failOp, seed); + seed = TypeHash64(m_stencilState.m_frontFace.m_depthFailOp, seed); + seed = TypeHash64(m_stencilState.m_frontFace.m_passOp, seed); + seed = TypeHash64(m_stencilState.m_frontFace.m_func, seed); + seed = TypeHash64(m_stencilState.m_backFace.m_failOp, seed); + seed = TypeHash64(m_stencilState.m_backFace.m_depthFailOp, seed); + seed = TypeHash64(m_stencilState.m_backFace.m_passOp, seed); + seed = TypeHash64(m_stencilState.m_backFace.m_func, seed); } if (RHI::CheckBitsAny(drawStateOptions, DrawStateOptions::FaceCullMode)) @@ -203,7 +195,7 @@ namespace AZ m_currentStates.m_cullMode = m_pipelineState->ConstDescriptor().m_renderStates.m_rasterState.m_cullMode; m_currentStates.m_topology = m_pipelineState->ConstDescriptor().m_inputStreamLayout.GetTopology(); m_currentStates.m_depthState = m_pipelineState->ConstDescriptor().m_renderStates.m_depthStencilState.m_depth; - m_currentStates.m_enableStencil = m_pipelineState->ConstDescriptor().m_renderStates.m_depthStencilState.m_stencil.m_enable; + m_currentStates.m_stencilState = m_pipelineState->ConstDescriptor().m_renderStates.m_depthStencilState.m_stencil; m_currentStates.m_blendState0 = m_pipelineState->ConstDescriptor().m_renderStates.m_blendState.m_targets[0]; m_currentStates.UpdateHash(m_drawStateOptions); @@ -291,7 +283,7 @@ namespace AZ { if (RHI::CheckBitsAny(m_drawStateOptions, DrawStateOptions::DepthState)) { - if (!CompareDepthState(m_currentStates.m_depthState, depthState)) + if (!(m_currentStates.m_depthState == depthState)) { m_currentStates.m_depthState = depthState; m_currentStates.m_isDirty = true; @@ -303,19 +295,19 @@ namespace AZ } } - void DynamicDrawContext::SetEnableStencil(bool enable) + void DynamicDrawContext::SetStencilState(RHI::StencilState stencilState) { - if (RHI::CheckBitsAny(m_drawStateOptions, DrawStateOptions::EnableStencil)) + if (RHI::CheckBitsAny(m_drawStateOptions, DrawStateOptions::StencilState)) { - if (m_currentStates.m_enableStencil != enable) + if (!(m_currentStates.m_stencilState == stencilState)) { - m_currentStates.m_enableStencil = enable; + m_currentStates.m_stencilState = stencilState; m_currentStates.m_isDirty = true; } } else { - AZ_Warning("RHI", false, "Can't set SetEnableStencil if DrawVariation::EnableStencil wasn't enabled"); + AZ_Warning("RHI", false, "Can't set SetStencilState if DrawVariation::StencilState wasn't enabled"); } } @@ -340,7 +332,7 @@ namespace AZ { if (RHI::CheckBitsAny(m_drawStateOptions, DrawStateOptions::BlendMode)) { - if (!CompareTargetBlendState(m_currentStates.m_blendState0, blendState)) + if (!(m_currentStates.m_blendState0 == blendState)) { m_currentStates.m_blendState0 = blendState; m_currentStates.m_isDirty = true; @@ -695,9 +687,9 @@ namespace AZ { m_pipelineState->RenderStatesOverlay().m_depthStencilState.m_depth = m_currentStates.m_depthState; } - if (RHI::CheckBitsAny(m_drawStateOptions, DrawStateOptions::EnableStencil)) + if (RHI::CheckBitsAny(m_drawStateOptions, DrawStateOptions::StencilState)) { - m_pipelineState->RenderStatesOverlay().m_depthStencilState.m_stencil.m_enable = m_currentStates.m_enableStencil; + m_pipelineState->RenderStatesOverlay().m_depthStencilState.m_stencil = m_currentStates.m_stencilState; } if (RHI::CheckBitsAny(m_drawStateOptions, DrawStateOptions::FaceCullMode)) { From 4b40f23d0b63cdf5b75188000c843e08c168c139 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 14:06:27 -0700 Subject: [PATCH 418/811] [cpack_installer] couple small fixes to installer Jenkins scripts --- scripts/build/Platform/Windows/build_windows.cmd | 5 ++--- scripts/build/Platform/Windows/installer_windows.cmd | 3 +++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/scripts/build/Platform/Windows/build_windows.cmd b/scripts/build/Platform/Windows/build_windows.cmd index 109db3438e..a2f42b75cf 100644 --- a/scripts/build/Platform/Windows/build_windows.cmd +++ b/scripts/build/Platform/Windows/build_windows.cmd @@ -38,11 +38,10 @@ IF NOT EXIST %TMP% ( REM Compute half the amount of processors so some jobs can run SET /a HALF_PROCESSORS = NUMBER_OF_PROCESSORS / 2 -IF %CMAKE_INCLUDE_WIX%=="True" ( +IF "%CMAKE_INCLUDE_WIX%"=="True" ( REM Explicitly enable wix via command line arg for forensic logging SET EXTRA_CMAKE_OPTIONS=%EXTRA_CMAKE_OPTIONS% -DLY_WIX_PATH="%WIX%" -) -ELSE ( +) ELSE ( REM Disable implicit enabling of windows packing by clearing out the wix variable SET WIX= ) diff --git a/scripts/build/Platform/Windows/installer_windows.cmd b/scripts/build/Platform/Windows/installer_windows.cmd index c613f0a1e3..e8ce10ff14 100644 --- a/scripts/build/Platform/Windows/installer_windows.cmd +++ b/scripts/build/Platform/Windows/installer_windows.cmd @@ -22,6 +22,9 @@ PUSHD %OUTPUT_DIRECTORY% REM Override the temporary directory used by wix to the EBS volume SET "WIX_TEMP=!WORKSPACE!/temp/wix" +IF NOT EXIST "%WIX_TEMP%" ( + MKDIR %WIX_TEMP% +) REM Run cpack ECHO [ci_build] cpack -C %CONFIGURATION% From a69db3bf7681e2e6cef653919544ec3828b195c4 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 2 Jun 2021 14:44:02 -0700 Subject: [PATCH 419/811] Converts physx console commands from cry console to az console, fixes some bugs in the multiplayer gem --- .../Components/NetworkTransformComponent.cpp | 12 +++ .../Source/MultiplayerSystemComponent.cpp | 79 +++++++++++-------- .../Code/Source/SystemComponent.cpp | 49 ++++-------- Gems/PhysXDebug/Code/Source/SystemComponent.h | 3 - 4 files changed, 75 insertions(+), 68 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp index 9a49724fb8..d4abf6e789 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp @@ -81,6 +81,9 @@ namespace Multiplayer void NetworkTransformComponent::OnResetCountChangedEvent() { + m_targetTransform.SetRotation(GetRotation()); + m_targetTransform.SetTranslation(GetTranslation()); + m_targetTransform.SetUniformScale(GetScale()); m_previousTransform = m_targetTransform; } @@ -93,6 +96,15 @@ namespace Multiplayer blendTransform.SetTranslation(m_previousTransform.GetTranslation().Lerp(m_targetTransform.GetTranslation(), blendFactor)); blendTransform.SetScale(m_previousTransform.GetScale().Lerp(m_targetTransform.GetScale(), blendFactor)); GetTransformComponent()->SetWorldTM(blendTransform); + + //AZLOG + //( + // NET_Movement, + // "Blending entity to position %f x %f x %f", + // blendTransform.GetTranslation().GetX(), + // blendTransform.GetTranslation().GetY(), + // blendTransform.GetTranslation().GetZ() + //); } } diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 485a3719ad..38f0fda94e 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -634,45 +634,62 @@ namespace Multiplayer const float adjustedBlendFactor = 1.0f - (std::powf(0.2f, m_renderBlendFactor)); AZLOG(NET_Blending, "Computed blend factor of %f", adjustedBlendFactor); - AZ::Transform activeCameraTransform; - Camera::Configuration activeCameraConfiguration; - Camera::ActiveCameraRequestBus::BroadcastResult(activeCameraTransform, &Camera::ActiveCameraRequestBus::Events::GetActiveCameraTransform); - Camera::ActiveCameraRequestBus::BroadcastResult(activeCameraConfiguration, &Camera::ActiveCameraRequestBus::Events::GetActiveCameraConfiguration); - - const AZ::ViewFrustumAttributes frustumAttributes - ( - activeCameraTransform, - activeCameraConfiguration.m_frustumHeight / activeCameraConfiguration.m_frustumWidth, - activeCameraConfiguration.m_fovRadians, - activeCameraConfiguration.m_nearClipDistance, - activeCameraConfiguration.m_farClipDistance - ); - const AZ::Frustum viewFrustum = AZ::Frustum(frustumAttributes); - - // Unfortunately necessary, as NotifyPreRender can update transforms and thus cause a deadlock inside the vis system - AZStd::vector gatheredEntities; - AzFramework::IEntityBoundsUnion* entityBoundsUnion = AZ::Interface::Get(); - AZ::Interface::Get()->GetDefaultVisibilityScene()->Enumerate(viewFrustum, - [&gatheredEntities, entityBoundsUnion](const AzFramework::IVisibilityScene::NodeData& nodeData) + if (Camera::ActiveCameraRequestBus::HasHandlers()) { - gatheredEntities.reserve(gatheredEntities.size() + nodeData.m_entries.size()); - for (AzFramework::VisibilityEntry* visEntry : nodeData.m_entries) + // If there's a camera, update only what's visible + AZ::Transform activeCameraTransform; + Camera::Configuration activeCameraConfiguration; + Camera::ActiveCameraRequestBus::BroadcastResult(activeCameraTransform, &Camera::ActiveCameraRequestBus::Events::GetActiveCameraTransform); + Camera::ActiveCameraRequestBus::BroadcastResult(activeCameraConfiguration, &Camera::ActiveCameraRequestBus::Events::GetActiveCameraConfiguration); + + const AZ::ViewFrustumAttributes frustumAttributes + ( + activeCameraTransform, + activeCameraConfiguration.m_frustumHeight / activeCameraConfiguration.m_frustumWidth, + activeCameraConfiguration.m_fovRadians, + activeCameraConfiguration.m_nearClipDistance, + activeCameraConfiguration.m_farClipDistance + ); + const AZ::Frustum viewFrustum = AZ::Frustum(frustumAttributes); + + // Unfortunately necessary, as NotifyPreRender can update transforms and thus cause a deadlock inside the vis system + AZStd::vector gatheredEntities; + AzFramework::IEntityBoundsUnion* entityBoundsUnion = AZ::Interface::Get(); + AZ::Interface::Get()->GetDefaultVisibilityScene()->Enumerate(viewFrustum, + [&gatheredEntities, entityBoundsUnion](const AzFramework::IVisibilityScene::NodeData& nodeData) { - if (visEntry->m_typeFlags & AzFramework::VisibilityEntry::TypeFlags::TYPE_Entity) + gatheredEntities.reserve(gatheredEntities.size() + nodeData.m_entries.size()); + for (AzFramework::VisibilityEntry* visEntry : nodeData.m_entries) { - AZ::Entity* entity = static_cast(visEntry->m_userData); - NetBindComponent* netBindComponent = entity->template FindComponent(); - if (netBindComponent != nullptr) + if (visEntry->m_typeFlags & AzFramework::VisibilityEntry::TypeFlags::TYPE_Entity) { - gatheredEntities.push_back(netBindComponent); + AZ::Entity* entity = static_cast(visEntry->m_userData); + NetBindComponent* netBindComponent = entity->FindComponent(); + if (netBindComponent != nullptr) + { + gatheredEntities.push_back(netBindComponent); + } } } - } - }); + }); - for (NetBindComponent* netBindComponent : gatheredEntities) + for (NetBindComponent* netBindComponent : gatheredEntities) + { + netBindComponent->NotifyPreRender(deltaTime, adjustedBlendFactor); + } + } + else { - netBindComponent->NotifyPreRender(deltaTime, adjustedBlendFactor); + // If there's no camera, fall back to updating all net entities + for (auto& iter : *(m_networkEntityManager.GetNetworkEntityTracker())) + { + AZ::Entity* entity = iter.second; + NetBindComponent* netBindComponent = entity->FindComponent(); + if (netBindComponent != nullptr) + { + netBindComponent->NotifyPreRender(deltaTime, adjustedBlendFactor); + } + } } } diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 08bf71753d..24a28b8f43 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -183,9 +184,7 @@ namespace PhysXDebug void SystemComponent::OnCrySystemInitialized([[maybe_unused]] ISystem& system, const SSystemInitParams&) { InitPhysXColorMappings(); - RegisterCommands(); ConfigurePhysXVisualizationParameters(); - } void SystemComponent::Reflect(AZ::ReflectContext* context) @@ -537,12 +536,13 @@ namespace PhysXDebug } } - static void CmdEnableWireFrame([[maybe_unused]] IConsoleCmdArgs* args) + static void physx_EnableWireFrame([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { PhysXDebug::PhysXDebugRequestBus::Broadcast(&PhysXDebug::PhysXDebugRequestBus::Events::ToggleCullingWireFrame); } + AZ_CONSOLEFREEFUNC(physx_EnableWireFrame, AZ::ConsoleFunctorFlags::DontReplicate, "Enables physx wireframe view"); - static void CmdConnectToPvd([[maybe_unused]] IConsoleCmdArgs* args) + static void physx_ConnectToPvd([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { auto* debug = AZ::Interface::Get(); if (debug) @@ -550,8 +550,9 @@ namespace PhysXDebug debug->ConnectToPvd(); } } + AZ_CONSOLEFREEFUNC(physx_ConnectToPvd, AZ::ConsoleFunctorFlags::DontReplicate, "Connects to the physx visual debugger"); - static void CmdDisconnectFromPvd([[maybe_unused]] IConsoleCmdArgs* args) + static void physx_DisconnectFromPvd([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { auto* debug = AZ::Interface::Get(); if (debug) @@ -559,13 +560,14 @@ namespace PhysXDebug debug->DisconnectFromPvd(); } } + AZ_CONSOLEFREEFUNC(physx_DisconnectFromPvd, AZ::ConsoleFunctorFlags::DontReplicate, "Disconnects from the physx visual debugger"); - static void CmdSetPhysXDebugCullingBoxSize(IConsoleCmdArgs* args) + static void physx_SetPhysXDebugCullingBoxSize([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { - const int argumentCount = args->GetArgCount(); + const int argumentCount = arguments.size(); if (argumentCount == 2) { - float newCullingBoxSize = (float)strtol(args->GetArg(1), nullptr, 10); + float newCullingBoxSize = (float)strtol(AZ::CVarFixedString(arguments[1]).c_str(), nullptr, 10); PhysXDebug::PhysXDebugRequestBus::Broadcast(&PhysXDebug::PhysXDebugRequestBus::Events::SetCullingBoxSize, newCullingBoxSize); } else @@ -574,16 +576,17 @@ namespace PhysXDebug "Please use physx_SetDebugCullingBoxSize e.g. physx_SetDebugCullingBoxSize 100."); } } + AZ_CONSOLEFREEFUNC(physx_SetPhysXDebugCullingBoxSize, AZ::ConsoleFunctorFlags::DontReplicate, "Sets physx debug culling box size"); - static void CmdTogglePhysXDebugVisualization(IConsoleCmdArgs* args) + static void physx_TogglePhysXDebugVisualization([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { using namespace CryStringUtils; - const int argumentCount = args->GetArgCount(); + const int argumentCount = arguments.size(); if (argumentCount == 2) { - const auto userPreference = static_cast(strtol(args->GetArg(1), nullptr, 10)); + const auto userPreference = static_cast(strtol(AZ::CVarFixedString(arguments[1]).c_str(), nullptr, 10)); switch (userPreference) { @@ -609,29 +612,7 @@ namespace PhysXDebug AZ_Warning("PhysXDebug", false, "Invalid physx_Debug Arguments. Please use physx_Debug 1 to enable, physx_Debug 0 to disable or physx_Debug 2 to enable all configuration settings."); } } - - void SystemComponent::RegisterCommands() - { - if (m_registered) - { - return; - } - - if (gEnv) - { - IConsole* console = gEnv->pSystem->GetIConsole(); - if (console) - { - console->AddCommand("physx_Debug", CmdTogglePhysXDebugVisualization); - console->AddCommand("physx_CullingBox", CmdEnableWireFrame); - console->AddCommand("physx_CullingBoxSize", CmdSetPhysXDebugCullingBoxSize); - console->AddCommand("physx_PvdConnect", CmdConnectToPvd); - console->AddCommand("physx_PvdDisconnect", CmdDisconnectFromPvd); - } - - m_registered = true; - } - } + AZ_CONSOLEFREEFUNC(physx_TogglePhysXDebugVisualization, AZ::ConsoleFunctorFlags::DontReplicate, "Toggles physx debug visualization"); void SystemComponent::ConfigurePhysXVisualizationParameters() { diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.h b/Gems/PhysXDebug/Code/Source/SystemComponent.h index 631354c034..f4d033fd4c 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.h +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.h @@ -161,9 +161,6 @@ namespace PhysXDebug /// Initialise the PhysX debug draw colors based on defaults. void InitPhysXColorMappings(); - /// Register debug drawing PhysX commands with Open 3D Engine console during game mode. - void RegisterCommands(); - /// Draw the culling box being used by the viewport. /// @param cullingBoxAabb culling box Aabb to debug draw. void DrawDebugCullingBox(const AZ::Aabb& cullingBoxAabb); From 8a7f156e2c66235546589744d07622da69483d1a Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Wed, 2 Jun 2021 14:45:43 -0700 Subject: [PATCH 420/811] LYN-4133 | Prefab Container Transform stores non-default values to template on Create Prefab (#1038) * Show container transforms, reset container transform to zero before saving a prefab after create. * Fix order of operations to prevent patching issues * Reset the entity to the Identity Transform instead of the default constructor to correctly set the scale to 1.0 --- .../Prefab/PrefabPublicHandler.cpp | 26 +++++++++++++++++-- .../PropertyEditor/EntityPropertyEditor.cpp | 3 ++- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index fadcc1b81f..6501986231 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -243,11 +243,33 @@ namespace AzToolsFramework instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(), AZStd::move(patch)); + // Reset the transform of the container entity so that the new values aren't saved in the new prefab's dom. + // The new values were saved in the link, so propagation will apply them correctly. + { + AZ::Entity* containerEntity = GetEntityById(containerEntityId); + + PrefabDom containerBeforeReset; + m_instanceToTemplateInterface->GenerateDomForEntity(containerBeforeReset, *containerEntity); + + AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetParent, AZ::EntityId()); + AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetLocalTM, AZ::Transform::CreateIdentity()); + + PrefabDom containerAfterReset; + m_instanceToTemplateInterface->GenerateDomForEntity(containerAfterReset, *containerEntity); + + // Update the state of the entity + PrefabUndoEntityUpdate* state = aznew PrefabUndoEntityUpdate(AZStd::to_string(static_cast(containerEntityId))); + state->SetParent(undoBatch.GetUndoBatch()); + state->Capture(containerBeforeReset, containerAfterReset, containerEntityId); + + state->Redo(); + } + // This clears any entities marked as dirty due to reparenting of entities during the process of creating a prefab. - // We are doing this so that the changes in those enities are not queued up twice for propagation. + // We are doing this so that the changes in those entities are not queued up twice for propagation. AzToolsFramework::ToolsApplicationRequestBus::Broadcast( &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); - + // Select Container Entity { auto selectionUndo = aznew SelectionCommand({containerEntityId}, "Select Prefab Container Entity"); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp index d0f3fa452a..60a53aca42 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp @@ -969,7 +969,8 @@ namespace AzToolsFramework { // Build up components to display SharedComponentArray sharedComponentArray; - BuildSharedComponentArray(sharedComponentArray, selectionEntityTypeInfo != SelectionEntityTypeInfo::OnlyStandardEntities); + BuildSharedComponentArray(sharedComponentArray, + !(selectionEntityTypeInfo == SelectionEntityTypeInfo::OnlyStandardEntities || selectionEntityTypeInfo == SelectionEntityTypeInfo::OnlyPrefabEntities)); if (sharedComponentArray.size() == 0) { From 8ef2bd751821c56ed841bb15d6b9765a05d75b8a Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 2 Jun 2021 14:47:05 -0700 Subject: [PATCH 421/811] Turn off desync debug by default, as this explodes network input sizes --- .../Source/Components/LocalPredictionPlayerInputComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp index 99e19a89fd..97e194dccb 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp @@ -25,7 +25,7 @@ namespace Multiplayer AZ_CVAR(AZ::TimeMs, cl_MaxRewindHistoryMs, AZ::TimeMs{ 2000 }, nullptr, AZ::ConsoleFunctorFlags::Null, "Maximum number of milliseconds to keep for server correction rewind and replay"); #ifndef AZ_RELEASE_BUILD AZ_CVAR(float, cl_DebugHackTimeMultiplier, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "Scalar value used to simulate clock hacking cheats for validating bank time system and anticheat"); - AZ_CVAR(bool, cl_EnableDesyncDebugging, true, nullptr, AZ::ConsoleFunctorFlags::Null, "If enabled, debug logs will contain verbose information on detected state desyncs"); + AZ_CVAR(bool, cl_EnableDesyncDebugging, false, nullptr, AZ::ConsoleFunctorFlags::Null, "If enabled, debug logs will contain verbose information on detected state desyncs"); #endif AZ_CVAR(bool, sv_EnableCorrections, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Enables server corrections on autonomous proxy desyncs"); From b013d7ac6780c61607792bb291627da4a08154e0 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 2 Jun 2021 14:53:33 -0700 Subject: [PATCH 422/811] Minor cleanup --- .../Components/NetworkTransformComponent.cpp | 9 --------- .../Code/Source/SystemComponent.cpp | 20 +++++++++---------- 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp index d4abf6e789..2de838df93 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp @@ -96,15 +96,6 @@ namespace Multiplayer blendTransform.SetTranslation(m_previousTransform.GetTranslation().Lerp(m_targetTransform.GetTranslation(), blendFactor)); blendTransform.SetScale(m_previousTransform.GetScale().Lerp(m_targetTransform.GetScale(), blendFactor)); GetTransformComponent()->SetWorldTM(blendTransform); - - //AZLOG - //( - // NET_Movement, - // "Blending entity to position %f x %f x %f", - // blendTransform.GetTranslation().GetX(), - // blendTransform.GetTranslation().GetY(), - // blendTransform.GetTranslation().GetZ() - //); } } diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 24a28b8f43..34315eb11e 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -536,13 +536,13 @@ namespace PhysXDebug } } - static void physx_EnableWireFrame([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) + static void physx_CullingBox([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { PhysXDebug::PhysXDebugRequestBus::Broadcast(&PhysXDebug::PhysXDebugRequestBus::Events::ToggleCullingWireFrame); } - AZ_CONSOLEFREEFUNC(physx_EnableWireFrame, AZ::ConsoleFunctorFlags::DontReplicate, "Enables physx wireframe view"); + AZ_CONSOLEFREEFUNC(physx_CullingBox, AZ::ConsoleFunctorFlags::DontReplicate, "Enables physx wireframe view"); - static void physx_ConnectToPvd([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) + static void physx_PvdConnect([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { auto* debug = AZ::Interface::Get(); if (debug) @@ -550,9 +550,9 @@ namespace PhysXDebug debug->ConnectToPvd(); } } - AZ_CONSOLEFREEFUNC(physx_ConnectToPvd, AZ::ConsoleFunctorFlags::DontReplicate, "Connects to the physx visual debugger"); + AZ_CONSOLEFREEFUNC(physx_PvdConnect, AZ::ConsoleFunctorFlags::DontReplicate, "Connects to the physx visual debugger"); - static void physx_DisconnectFromPvd([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) + static void physx_PvdDisconnect([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { auto* debug = AZ::Interface::Get(); if (debug) @@ -560,9 +560,9 @@ namespace PhysXDebug debug->DisconnectFromPvd(); } } - AZ_CONSOLEFREEFUNC(physx_DisconnectFromPvd, AZ::ConsoleFunctorFlags::DontReplicate, "Disconnects from the physx visual debugger"); + AZ_CONSOLEFREEFUNC(physx_PvdDisconnect, AZ::ConsoleFunctorFlags::DontReplicate, "Disconnects from the physx visual debugger"); - static void physx_SetPhysXDebugCullingBoxSize([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) + static void physx_CullingBoxSize([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { const int argumentCount = arguments.size(); if (argumentCount == 2) @@ -576,9 +576,9 @@ namespace PhysXDebug "Please use physx_SetDebugCullingBoxSize e.g. physx_SetDebugCullingBoxSize 100."); } } - AZ_CONSOLEFREEFUNC(physx_SetPhysXDebugCullingBoxSize, AZ::ConsoleFunctorFlags::DontReplicate, "Sets physx debug culling box size"); + AZ_CONSOLEFREEFUNC(physx_CullingBoxSize, AZ::ConsoleFunctorFlags::DontReplicate, "Sets physx debug culling box size"); - static void physx_TogglePhysXDebugVisualization([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) + static void physx_Debug([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { using namespace CryStringUtils; @@ -612,7 +612,7 @@ namespace PhysXDebug AZ_Warning("PhysXDebug", false, "Invalid physx_Debug Arguments. Please use physx_Debug 1 to enable, physx_Debug 0 to disable or physx_Debug 2 to enable all configuration settings."); } } - AZ_CONSOLEFREEFUNC(physx_TogglePhysXDebugVisualization, AZ::ConsoleFunctorFlags::DontReplicate, "Toggles physx debug visualization"); + AZ_CONSOLEFREEFUNC(physx_Debug, AZ::ConsoleFunctorFlags::DontReplicate, "Toggles physx debug visualization"); void SystemComponent::ConfigurePhysXVisualizationParameters() { From c6e4e3ed1fd549d88e27a0aac254ec3ab267bc98 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 14:57:18 -0700 Subject: [PATCH 423/811] [cpack_installer] few more small fixes to installer Jenkins scripts --- scripts/build/Platform/Windows/build_windows.cmd | 2 +- scripts/build/build_node/Platform/Windows/install_utiltools.ps1 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/build/Platform/Windows/build_windows.cmd b/scripts/build/Platform/Windows/build_windows.cmd index a2f42b75cf..799e6828b2 100644 --- a/scripts/build/Platform/Windows/build_windows.cmd +++ b/scripts/build/Platform/Windows/build_windows.cmd @@ -40,7 +40,7 @@ SET /a HALF_PROCESSORS = NUMBER_OF_PROCESSORS / 2 IF "%CMAKE_INCLUDE_WIX%"=="True" ( REM Explicitly enable wix via command line arg for forensic logging - SET EXTRA_CMAKE_OPTIONS=%EXTRA_CMAKE_OPTIONS% -DLY_WIX_PATH="%WIX%" + SET CMAKE_OPTIONS=%CMAKE_OPTIONS% -DLY_WIX_PATH="%WIX%" ) ELSE ( REM Disable implicit enabling of windows packing by clearing out the wix variable SET WIX= diff --git a/scripts/build/build_node/Platform/Windows/install_utiltools.ps1 b/scripts/build/build_node/Platform/Windows/install_utiltools.ps1 index 35ae04cc09..050e446f52 100644 --- a/scripts/build/build_node/Platform/Windows/install_utiltools.ps1 +++ b/scripts/build/build_node/Platform/Windows/install_utiltools.ps1 @@ -30,5 +30,5 @@ choco install corretto8jdk -y --ia INSTALLDIR="c:\jdk8" # Custom directory to ha # Install CMake choco install cmake -y --installargs 'ADD_CMAKE_TO_PATH=System' -# Install WIX +# Install Windows Installer XML toolkit (WiX) choco install wixtoolset -y From 134258c18acff77588b7f57d8200d069144ecc2a Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 15:03:26 -0700 Subject: [PATCH 424/811] [cpack_installer] add trailing newline to some new files --- scripts/build/Platform/Windows/build_installer_windows.cmd | 2 +- scripts/build/Platform/Windows/installer_windows.cmd | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/build/Platform/Windows/build_installer_windows.cmd b/scripts/build/Platform/Windows/build_installer_windows.cmd index 0d50f4b57a..4f31fee085 100644 --- a/scripts/build/Platform/Windows/build_installer_windows.cmd +++ b/scripts/build/Platform/Windows/build_installer_windows.cmd @@ -19,4 +19,4 @@ IF NOT %ERRORLEVEL%==0 GOTO :error EXIT /b 0 :error -EXIT /b 1 \ No newline at end of file +EXIT /b 1 diff --git a/scripts/build/Platform/Windows/installer_windows.cmd b/scripts/build/Platform/Windows/installer_windows.cmd index e8ce10ff14..e3a60fee1c 100644 --- a/scripts/build/Platform/Windows/installer_windows.cmd +++ b/scripts/build/Platform/Windows/installer_windows.cmd @@ -38,4 +38,4 @@ EXIT /b 0 POPD :error -EXIT /b 1 \ No newline at end of file +EXIT /b 1 From 82f9d08cfd7539482dd137e5c66d181f1ce11013 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 2 Jun 2021 15:21:43 -0700 Subject: [PATCH 425/811] Build fix for uniform scale changes --- .../Code/Source/Components/NetworkTransformComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp index 2de838df93..bb256701ff 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp @@ -94,7 +94,7 @@ namespace Multiplayer AZ::Transform blendTransform; blendTransform.SetRotation(m_previousTransform.GetRotation().Slerp(m_targetTransform.GetRotation(), blendFactor)); blendTransform.SetTranslation(m_previousTransform.GetTranslation().Lerp(m_targetTransform.GetTranslation(), blendFactor)); - blendTransform.SetScale(m_previousTransform.GetScale().Lerp(m_targetTransform.GetScale(), blendFactor)); + blendTransform.SetUniformScale(AZ::Lerp(m_previousTransform.GetUniformScale(), m_targetTransform.GetUniformScale(), blendFactor)); GetTransformComponent()->SetWorldTM(blendTransform); } } From 38853eb2c2426dfed99be3384b2923fce5d0116e Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 2 Jun 2021 15:34:35 -0700 Subject: [PATCH 426/811] Linux build fix --- Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 074e9af86c..f30c8912de 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -38,6 +38,8 @@ #include +#include // for std::powf on linux + namespace AZ::ConsoleTypeHelpers { template <> From 197241f16d4a7f0ec6bfc33af715d43aff93e6e8 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 15:40:41 -0700 Subject: [PATCH 427/811] [cpack_installer] fixed issue with cpack selection --- scripts/build/Platform/Windows/installer_windows.cmd | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/scripts/build/Platform/Windows/installer_windows.cmd b/scripts/build/Platform/Windows/installer_windows.cmd index e3a60fee1c..824a461a4b 100644 --- a/scripts/build/Platform/Windows/installer_windows.cmd +++ b/scripts/build/Platform/Windows/installer_windows.cmd @@ -26,9 +26,17 @@ IF NOT EXIST "%WIX_TEMP%" ( MKDIR %WIX_TEMP% ) +REM Make sure we are using the CMake version of CPack and not the one that comes with chocolaty +IF "%LY_CMAKE_PATH%"=="" ( + for /f %%i in ('where cmake') do SET "CMAKE_EXE_PATH=%%i" + for %%F in ("%CMAKE_EXE_PATH%") do SET "CMAKE_INSTALL_PATH=%%~dpF" +) ELSE ( + SET "CMAKE_INSTALL_PATH=%LY_CMAKE_PATH%\" +) + REM Run cpack -ECHO [ci_build] cpack -C %CONFIGURATION% -cpack -C %CONFIGURATION% +ECHO [ci_build] "%CMAKE_INSTALL_PATH%cpack" -C %CONFIGURATION% +"%CMAKE_INSTALL_PATH%cpack" -C %CONFIGURATION% IF NOT %ERRORLEVEL%==0 GOTO :popd_error POPD From fd8cff6aecb2c93b93e6e09f9927feac563392c7 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 16:10:41 -0700 Subject: [PATCH 428/811] [cpack_installer] second attempt to fix cpack selection --- scripts/build/Platform/Windows/installer_windows.cmd | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/scripts/build/Platform/Windows/installer_windows.cmd b/scripts/build/Platform/Windows/installer_windows.cmd index 824a461a4b..b1fecaa2cb 100644 --- a/scripts/build/Platform/Windows/installer_windows.cmd +++ b/scripts/build/Platform/Windows/installer_windows.cmd @@ -23,10 +23,11 @@ PUSHD %OUTPUT_DIRECTORY% REM Override the temporary directory used by wix to the EBS volume SET "WIX_TEMP=!WORKSPACE!/temp/wix" IF NOT EXIST "%WIX_TEMP%" ( - MKDIR %WIX_TEMP% + MKDIR "WIX_TEMP%" ) REM Make sure we are using the CMake version of CPack and not the one that comes with chocolaty +SET CMAKE_INSTALL_PATH= IF "%LY_CMAKE_PATH%"=="" ( for /f %%i in ('where cmake') do SET "CMAKE_EXE_PATH=%%i" for %%F in ("%CMAKE_EXE_PATH%") do SET "CMAKE_INSTALL_PATH=%%~dpF" @@ -34,6 +35,11 @@ IF "%LY_CMAKE_PATH%"=="" ( SET "CMAKE_INSTALL_PATH=%LY_CMAKE_PATH%\" ) +IF "%CMAKE_INSTALL_PATH%"=="" ( + ECHO [ci_build] CPack path not found + GOTO :popd_error +) + REM Run cpack ECHO [ci_build] "%CMAKE_INSTALL_PATH%cpack" -C %CONFIGURATION% "%CMAKE_INSTALL_PATH%cpack" -C %CONFIGURATION% From f1dbeb584af8e2671a056baee74e645bab5382f0 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Wed, 2 Jun 2021 16:50:18 -0700 Subject: [PATCH 429/811] LYN-4206 CMake bakes install prefix during configure (#1100) --- cmake/Platform/Common/Install_common.cmake | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index b18aed6fb4..710a8b266f 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -15,7 +15,11 @@ ly_set(LY_DEFAULT_INSTALL_COMPONENT Core) file(RELATIVE_PATH runtime_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) -set(install_output_folder "${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$") +# Anywhere CMAKE_INSTALL_PREFIX is used, it has to be escaped so it is baked into the cmake_install.cmake script instead +# of baking the path. This is needed so `cmake --install --prefix ` works regardless of the CMAKE_INSTALL_PREFIX +# used to generate the solution. +# CMAKE_INSTALL_PREFIX is still used when building the INSTALL target +set(install_output_folder "\${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$") #! ly_setup_target: Setup the data needed to re-create the cmake target commands for a single target From c752b9d0fc19ca1f5f5cbc713184b0aeaedd1d9a Mon Sep 17 00:00:00 2001 From: pereslav Date: Thu, 3 Jun 2021 01:04:01 +0100 Subject: [PATCH 430/811] Fixed ctrl+g port number. Enabled server spawn for levels with no network entities since we can spawn net entities from the scripts --- .../Editor/MultiplayerEditorConnection.cpp | 41 +++++++++++-------- .../Editor/MultiplayerEditorConnection.h | 4 +- .../MultiplayerEditorSystemComponent.cpp | 2 +- 3 files changed, 29 insertions(+), 18 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp index f684e1f12f..710a051cd9 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp @@ -109,11 +109,7 @@ namespace Multiplayer AZ::Interface::Get()->InitializeMultiplayer(MultiplayerAgentType::DedicatedServer); INetworkInterface* networkInterface = AZ::Interface::Get()->RetrieveNetworkInterface(AZ::Name(MPNetworkInterfaceName)); - uint16_t serverPort = DefaultServerPort; - if (auto console = AZ::Interface::Get(); console) - { - console->GetCvarValue("sv_port", serverPort); - } + uint16_t serverPort = GetGameServerPort(); networkInterface->Listen(serverPort); AZLOG_INFO("Editor Server completed asset receive, responding to Editor..."); @@ -138,18 +134,20 @@ namespace Multiplayer if (auto console = AZ::Interface::Get(); console) { AZ::CVarFixedString remoteAddress; - uint16_t remotePort; - if (console->GetCvarValue("editorsv_serveraddr", remoteAddress) != AZ::GetValueResult::ConsoleVarNotFound && - console->GetCvarValue("editorsv_port", remotePort) != AZ::GetValueResult::ConsoleVarNotFound) - { - // Connect the Editor to the editor server for Multiplayer simulation - AZ::Interface::Get()->InitializeMultiplayer(MultiplayerAgentType::Client); - INetworkInterface* networkInterface = - AZ::Interface::Get()->RetrieveNetworkInterface(AZ::Name(MPNetworkInterfaceName)); + uint16_t remotePort = GetGameServerPort(); + if (console->GetCvarValue("editorsv_serveraddr", remoteAddress) != AZ::GetValueResult::ConsoleVarNotFound) + { + // Connect the Editor to the editor server for Multiplayer simulation + AZ::Interface::Get()->InitializeMultiplayer(MultiplayerAgentType::Client); + INetworkInterface* networkInterface = + AZ::Interface::Get()->RetrieveNetworkInterface(AZ::Name(MPNetworkInterfaceName)); - const IpAddress ipAddress(remoteAddress.c_str(), remotePort, networkInterface->GetType()); - networkInterface->Connect(ipAddress); - } + // Connecting to DefaultServerPort here + const IpAddress ipAddress(remoteAddress.c_str(), remotePort, networkInterface->GetType()); + networkInterface->Connect(ipAddress); + + AZ::Interface::Get()->SendReadyForEntityUpdates(true); + } } } return true; @@ -184,4 +182,15 @@ namespace Multiplayer { ; } + + uint16_t MultiplayerEditorConnection::GetGameServerPort() + { + uint16_t serverPort = DefaultServerPort; + if (auto console = AZ::Interface::Get(); console) + { + console->GetCvarValue("sv_port", serverPort); + } + return serverPort; + } + } diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h index d803a60744..aeafc09861 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h @@ -39,7 +39,8 @@ namespace Multiplayer bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerEditorPackets::EditorServerInit& packet); bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerEditorPackets::EditorServerReady& packet); - + + //! IConnectionListener interface //! @{ AzNetworking::ConnectResult ValidateConnect(const AzNetworking::IpAddress& remoteAddress, const AzNetworking::IPacketHeader& packetHeader, AzNetworking::ISerializer& serializer) override; @@ -50,6 +51,7 @@ namespace Multiplayer //! @} private: + uint16_t GetGameServerPort(); AzNetworking::INetworkInterface* m_networkEditorInterface = nullptr; AZStd::vector m_buffer; diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp index 523ffd90de..3ac4e98d42 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp @@ -165,7 +165,7 @@ namespace Multiplayer // BeginGameMode and Prefab Processing have completed at this point IMultiplayerTools* mpTools = AZ::Interface::Get(); - if (editorsv_enabled && mpTools != nullptr && mpTools->DidProcessNetworkPrefabs()) + if (editorsv_enabled && mpTools != nullptr) { const AZStd::vector>& assetData = prefabEditorEntityOwnershipInterface->GetPlayInEditorAssetData(); From 3b519c64756df01777dc89b134308338794a4e72 Mon Sep 17 00:00:00 2001 From: pereslav Date: Thu, 3 Jun 2021 01:06:15 +0100 Subject: [PATCH 431/811] removed whitespace --- .../Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h | 1 - 1 file changed, 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h index aeafc09861..40eb38af1d 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h @@ -40,7 +40,6 @@ namespace Multiplayer bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerEditorPackets::EditorServerInit& packet); bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerEditorPackets::EditorServerReady& packet); - //! IConnectionListener interface //! @{ AzNetworking::ConnectResult ValidateConnect(const AzNetworking::IpAddress& remoteAddress, const AzNetworking::IPacketHeader& packetHeader, AzNetworking::ISerializer& serializer) override; From bffb7d1b2876633780c728969906c656f813105e Mon Sep 17 00:00:00 2001 From: pereslav Date: Thu, 3 Jun 2021 01:20:22 +0100 Subject: [PATCH 432/811] Simplified the change to rely on sv_port cvar --- .../Editor/MultiplayerEditorConnection.cpp | 41 ++++++++----------- .../Editor/MultiplayerEditorConnection.h | 3 +- 2 files changed, 18 insertions(+), 26 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp index 710a051cd9..847d1caadf 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp @@ -109,7 +109,11 @@ namespace Multiplayer AZ::Interface::Get()->InitializeMultiplayer(MultiplayerAgentType::DedicatedServer); INetworkInterface* networkInterface = AZ::Interface::Get()->RetrieveNetworkInterface(AZ::Name(MPNetworkInterfaceName)); - uint16_t serverPort = GetGameServerPort(); + uint16_t serverPort = DefaultServerPort; + if (auto console = AZ::Interface::Get(); console) + { + console->GetCvarValue("sv_port", serverPort); + } networkInterface->Listen(serverPort); AZLOG_INFO("Editor Server completed asset receive, responding to Editor..."); @@ -134,20 +138,20 @@ namespace Multiplayer if (auto console = AZ::Interface::Get(); console) { AZ::CVarFixedString remoteAddress; - uint16_t remotePort = GetGameServerPort(); - if (console->GetCvarValue("editorsv_serveraddr", remoteAddress) != AZ::GetValueResult::ConsoleVarNotFound) - { - // Connect the Editor to the editor server for Multiplayer simulation - AZ::Interface::Get()->InitializeMultiplayer(MultiplayerAgentType::Client); - INetworkInterface* networkInterface = - AZ::Interface::Get()->RetrieveNetworkInterface(AZ::Name(MPNetworkInterfaceName)); + uint16_t remotePort; + if (console->GetCvarValue("editorsv_serveraddr", remoteAddress) != AZ::GetValueResult::ConsoleVarNotFound && + console->GetCvarValue("sv_port", remotePort) != AZ::GetValueResult::ConsoleVarNotFound) + { + // Connect the Editor to the editor server for Multiplayer simulation + AZ::Interface::Get()->InitializeMultiplayer(MultiplayerAgentType::Client); + INetworkInterface* networkInterface = + AZ::Interface::Get()->RetrieveNetworkInterface(AZ::Name(MPNetworkInterfaceName)); - // Connecting to DefaultServerPort here - const IpAddress ipAddress(remoteAddress.c_str(), remotePort, networkInterface->GetType()); - networkInterface->Connect(ipAddress); + const IpAddress ipAddress(remoteAddress.c_str(), remotePort, networkInterface->GetType()); + networkInterface->Connect(ipAddress); - AZ::Interface::Get()->SendReadyForEntityUpdates(true); - } + AZ::Interface::Get()->SendReadyForEntityUpdates(true); + } } } return true; @@ -182,15 +186,4 @@ namespace Multiplayer { ; } - - uint16_t MultiplayerEditorConnection::GetGameServerPort() - { - uint16_t serverPort = DefaultServerPort; - if (auto console = AZ::Interface::Get(); console) - { - console->GetCvarValue("sv_port", serverPort); - } - return serverPort; - } - } diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h index 40eb38af1d..d803a60744 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.h @@ -39,7 +39,7 @@ namespace Multiplayer bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerEditorPackets::EditorServerInit& packet); bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerEditorPackets::EditorServerReady& packet); - + //! IConnectionListener interface //! @{ AzNetworking::ConnectResult ValidateConnect(const AzNetworking::IpAddress& remoteAddress, const AzNetworking::IPacketHeader& packetHeader, AzNetworking::ISerializer& serializer) override; @@ -50,7 +50,6 @@ namespace Multiplayer //! @} private: - uint16_t GetGameServerPort(); AzNetworking::INetworkInterface* m_networkEditorInterface = nullptr; AZStd::vector m_buffer; From e445c643211322d9c4193669200ebc1965bc777e Mon Sep 17 00:00:00 2001 From: pereslav Date: Thu, 3 Jun 2021 01:21:27 +0100 Subject: [PATCH 433/811] Fixed TimedThread bled %d ms logging to not spam the console --- .../AzNetworking/AzNetworking/Utilities/TimedThread.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzNetworking/AzNetworking/Utilities/TimedThread.cpp b/Code/Framework/AzNetworking/AzNetworking/Utilities/TimedThread.cpp index d078149996..7e1f41f745 100644 --- a/Code/Framework/AzNetworking/AzNetworking/Utilities/TimedThread.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/Utilities/TimedThread.cpp @@ -46,7 +46,7 @@ namespace AzNetworking } else if (m_updateRate < updateTimeMs) { - AZLOG_INFO("TimedThread bled %d ms", aznumeric_cast(updateTimeMs - m_updateRate)); + AZLOG(NET_TimedThread, "TimedThread bled %d ms", aznumeric_cast(updateTimeMs - m_updateRate)); } } OnStop(); From 201d6b1b72ec579c980c5e38d58fc354bfcc9a29 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 17:29:50 -0700 Subject: [PATCH 434/811] [cpack_installer] third attempt to fix cpack selection --- .../Platform/Windows/installer_windows.cmd | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/scripts/build/Platform/Windows/installer_windows.cmd b/scripts/build/Platform/Windows/installer_windows.cmd index b1fecaa2cb..41cc21b35b 100644 --- a/scripts/build/Platform/Windows/installer_windows.cmd +++ b/scripts/build/Platform/Windows/installer_windows.cmd @@ -26,23 +26,29 @@ IF NOT EXIST "%WIX_TEMP%" ( MKDIR "WIX_TEMP%" ) -REM Make sure we are using the CMake version of CPack and not the one that comes with chocolaty -SET CMAKE_INSTALL_PATH= +REM Make sure we are using the CMake version of CPack and not the one that comes with chocolatey +SET CPACK_PATH= IF "%LY_CMAKE_PATH%"=="" ( - for /f %%i in ('where cmake') do SET "CMAKE_EXE_PATH=%%i" - for %%F in ("%CMAKE_EXE_PATH%") do SET "CMAKE_INSTALL_PATH=%%~dpF" + FOR /F %%i in ('where cpack') DO ( + REM The cpack in chocolatey expects a number supplied with --version so it will error + %%i --version > NUL + IF !ERRORLEVEL!==0 ( + SET "CPACK_PATH=%%i" + ) + ) ) ELSE ( - SET "CMAKE_INSTALL_PATH=%LY_CMAKE_PATH%\" + SET "CPACK_PATH=%LY_CMAKE_PATH%\cpack.exe" ) -IF "%CMAKE_INSTALL_PATH%"=="" ( - ECHO [ci_build] CPack path not found - GOTO :popd_error +ECHO [ci_build] "%CPACK_PATH%" --version +"%CPACK_PATH%" --version +IF ERRORLEVEL 1 ( + ECHO [ci_build] CPack not found! + exit /b 1 ) - REM Run cpack -ECHO [ci_build] "%CMAKE_INSTALL_PATH%cpack" -C %CONFIGURATION% -"%CMAKE_INSTALL_PATH%cpack" -C %CONFIGURATION% +ECHO [ci_build] "%CPACK_PATH%" -C %CONFIGURATION% +"%CPACK_PATH%" -C %CONFIGURATION% IF NOT %ERRORLEVEL%==0 GOTO :popd_error POPD From 312c704ba65d2b2d447ba332fc948e301e5a34c5 Mon Sep 17 00:00:00 2001 From: Qing Tao <55564570+VickyAtAZ@users.noreply.github.com> Date: Wed, 2 Jun 2021 17:39:50 -0700 Subject: [PATCH 435/811] ATOM-15352 Find a solution to modify a render pipeline when enable a feature gem (#960) * Added atom_rpi_tools python module in Atom_RPI gem. The tool includes functions to modify pass template data and some utility functions. * Added pytest tests for atom_rpi_tools --- Gems/Atom/RPI/CMakeLists.txt | 2 + Gems/Atom/RPI/Tools/CMakeLists.txt | 23 ++ Gems/Atom/RPI/Tools/README.txt | 39 +++ Gems/Atom/RPI/Tools/__init__.py | 10 + .../RPI/Tools/atom_rpi_tools/pass_data.py | 210 ++++++++++++ .../Tools/atom_rpi_tools/tests/__init__.py | 10 + .../tests/test_pass_template.py | 303 ++++++++++++++++++ .../Tools/atom_rpi_tools/tests/test_utils.py | 53 +++ .../tests/testdata/pass_requests.json | 116 +++++++ .../tests/testdata/pass_slots.json | 21 ++ .../tests/testdata/pass_test_bad.json | 6 + Gems/Atom/RPI/Tools/atom_rpi_tools/utils.py | 31 ++ Gems/Atom/RPI/Tools/setup.py | 33 ++ 13 files changed, 857 insertions(+) create mode 100644 Gems/Atom/RPI/Tools/CMakeLists.txt create mode 100644 Gems/Atom/RPI/Tools/README.txt create mode 100644 Gems/Atom/RPI/Tools/__init__.py create mode 100644 Gems/Atom/RPI/Tools/atom_rpi_tools/pass_data.py create mode 100644 Gems/Atom/RPI/Tools/atom_rpi_tools/tests/__init__.py create mode 100644 Gems/Atom/RPI/Tools/atom_rpi_tools/tests/test_pass_template.py create mode 100644 Gems/Atom/RPI/Tools/atom_rpi_tools/tests/test_utils.py create mode 100644 Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_requests.json create mode 100644 Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_slots.json create mode 100644 Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_test_bad.json create mode 100644 Gems/Atom/RPI/Tools/atom_rpi_tools/utils.py create mode 100644 Gems/Atom/RPI/Tools/setup.py diff --git a/Gems/Atom/RPI/CMakeLists.txt b/Gems/Atom/RPI/CMakeLists.txt index 20a680bce9..8cea783633 100644 --- a/Gems/Atom/RPI/CMakeLists.txt +++ b/Gems/Atom/RPI/CMakeLists.txt @@ -10,3 +10,5 @@ # add_subdirectory(Code) +add_subdirectory(Tools) + diff --git a/Gems/Atom/RPI/Tools/CMakeLists.txt b/Gems/Atom/RPI/Tools/CMakeLists.txt new file mode 100644 index 0000000000..35df664ab2 --- /dev/null +++ b/Gems/Atom/RPI/Tools/CMakeLists.txt @@ -0,0 +1,23 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +if (PAL_TRAIT_BUILD_HOST_TOOLS) + ly_pip_install_local_package_editable(${CMAKE_CURRENT_LIST_DIR} atom_rpi_tools) + + if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) + ly_add_pytest( + NAME RPI::atom_rpi_tools_tests + PATH ${CMAKE_CURRENT_LIST_DIR}/atom_rpi_tools/tests/ + TIMEOUT 30 + ) + endif() +endif() + diff --git a/Gems/Atom/RPI/Tools/README.txt b/Gems/Atom/RPI/Tools/README.txt new file mode 100644 index 0000000000..ee2e9264da --- /dev/null +++ b/Gems/Atom/RPI/Tools/README.txt @@ -0,0 +1,39 @@ +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +INTRODUCTION +------------ + +atom_rpi_tools is a Python project that contains a collection of tools +developed by the Atom team. The project contains the following tools: + + * Render pipeline merge tool: + A library to manipulate .pass asset files and help gems create scripts to update render pipeline + + +REQUIREMENTS +------------ + + * Python 3.7.5 (64-bit) + +It is recommended that you completely remove any other versions of Python +installed on your system. + + +INSTALL +----------- +It is recommended to set up these these tools with Lumberyard's CMake build commands. + + +UNINSTALLATION +-------------- + +The preferred way to uninstall the project is: +(engine install root)/python/python -m pip uninstall atom_rpi_tools diff --git a/Gems/Atom/RPI/Tools/__init__.py b/Gems/Atom/RPI/Tools/__init__.py new file mode 100644 index 0000000000..79f8fa4422 --- /dev/null +++ b/Gems/Atom/RPI/Tools/__init__.py @@ -0,0 +1,10 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" diff --git a/Gems/Atom/RPI/Tools/atom_rpi_tools/pass_data.py b/Gems/Atom/RPI/Tools/atom_rpi_tools/pass_data.py new file mode 100644 index 0000000000..e5e7a839bd --- /dev/null +++ b/Gems/Atom/RPI/Tools/atom_rpi_tools/pass_data.py @@ -0,0 +1,210 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +""" + +import sys, os +import json +import shutil + +class PassTemplate: + # This class provide necessary functions for insert pass requests and update connections + # which are common functions required for adding features. + # It doesn't include the remove/delete furnctions since that's not common case for merging render pipeline + def __init__(self, filePath: str): + self.initialized = False + self.file_path: str = filePath + #load the json file + json_data = open(filePath, "r") + self.file_data = json.load(json_data) + + if 'ClassName' not in self.file_data or 'ClassData' not in self.file_data or self.file_data['ClassName']!='PassAsset' or 'PassTemplate' not in self.file_data['ClassData']: + raise KeyError('the json file is not a PassAsset file') + return + + if 'PassRequests' in self.file_data['ClassData']['PassTemplate']: + self.passRequests = self.file_data['ClassData']['PassTemplate']['PassRequests'] + + if 'Slots' in self.file_data['ClassData']['PassTemplate']: + self.slots = self.file_data['ClassData']['PassTemplate']['Slots'] + + self.initialized = True + print('PassTemplate is loaded from ', filePath) + + def find_pass(self, passName): + # return pass's index in PassRequests if a PassRequest with input passName exists + if not hasattr(self, 'passRequests'): + return -1 + index = 0 + for passRequest in self.passRequests: + if passRequest['Name'] == passName: + return index + index += 1 + return -1 + + def get_pass_count(self): + if not hasattr(self, 'passRequests'): + return 0 + return len(self.passRequests) + + def __validate_pass_request_data(self, passRequest): + if ('Name' not in passRequest or 'TemplateName' not in passRequest): + raise KeyError('invalid pass request data') + + def __ensure_pass_requests_key(self): + if not hasattr(self, 'passRequests'): + self.file_data['ClassData']['PassTemplate']['PassRequests'] = [] + self.passRequests = self.file_data['ClassData']['PassTemplate']['PassRequests'] + + def __ensure_pass_slots_key(self): + if not hasattr(self, 'slots'): + self.file_data['ClassData']['PassTemplate']['Slots'] = [] + self.slots = self.file_data['ClassData']['PassTemplate']['Slots'] + + def insert_pass_request(self, location, passRequest): + self.__validate_pass_request_data(passRequest) + + if (self.find_pass(passRequest['Name']) >= 0): + raise ValueError('pass request ', passRequest['Name'], ' is already exist') + # insert a passRequest before the specified location + self.__ensure_pass_requests_key() + self.passRequests.insert(location, passRequest) + + def replace_references_after(self, startPassRequest, oldPass, oldSlot, newPass, newSlot): + if not hasattr(self, 'passRequests'): + return 0 + # from all pass requests after startPassRequest + # replace all attachment references which uses oldPass and oldSlot + # with newPass and newSlot + started = False + replaced_count = 0 + for request in self.passRequests: + if started: + if ('Connections' in request): + for connection in request['Connections']: + if connection['AttachmentRef']['Pass'] == oldPass and connection['AttachmentRef']['Attachment'] == oldSlot: + connection['AttachmentRef']['Pass'] = newPass + connection['AttachmentRef']['Attachment'] = newSlot + replaced_count += 1 + if request['Name'] == startPassRequest and not started: + started = True + return replaced_count + + def replace_references_for(self, passRequest, oldPass, oldSlot, newPass, newSlot): + if not hasattr(self, 'passRequests'): + return 0 + #replace pass reference for the specified passRequest + replaced_count = 0 + for request in self.passRequests: + if request['Name'] == passRequest: + if ('Connections' in request): + for connection in request['Connections']: + if connection['AttachmentRef']['Pass'] == oldPass and connection['AttachmentRef']['Attachment'] == oldSlot: + connection['AttachmentRef']['Pass'] = newPass + connection['AttachmentRef']['Attachment'] = newSlot + replaced_count += 1 + return replaced_count #return when the specified pass request is updated. + return replaced_count + + def __validate_slot_data(self, slotData): + if ('Name' not in slotData or 'SlotType' not in slotData): + raise KeyError('invalid slot data') + + def get_slot_count(self): + if not hasattr(self, 'slots'): + return 0 + return len(self.slots) + + def find_slot(self, slotName): + # return slot's index in Slots if a PassRequest with input passName exists + if not hasattr(self, 'slots'): + return -1 + index = 0 + for slot in self.slots: + if slot['Name'] == slotName: + return index + index += 1 + return -1 + + def insert_slot(self, location, newSlotData): + # insert a new slot at specified location + self.__validate_slot_data(newSlotData) + # check if the slot already exist + if (self.find_slot(newSlotData['Name']) >= 0): + raise ValueError('Slot ', newSlotData['Name'], ' is already exist') + + self.__ensure_pass_slots_key() + self.slots.insert(location, newSlotData) + + def add_slot(self, newSlotData): + # append a new slot to slots + self.__validate_slot_data(newSlotData) + # check if the slot already exist + if (self.find_slot(newSlotData['Name']) >= 0): + raise ValueError('Slot ', newSlotData['Name'], ' is already exist') + + self.__ensure_pass_slots_key() + self.slots.append(newSlotData) + + def get_pass_request(self, passName): + if not hasattr(self, 'passRequests'): + return + # Get the pass request from PassRequests with matching pass name + for passRequest in self.passRequests: + if passRequest['Name'] == passName: + return passRequest + + def save(self): + # backup the original file + backupFilePath = self.file_path +'.backup' + shutil.copyfile(self.file_path, backupFilePath) + # save and overwrite file + with open(self.file_path, 'w') as json_file: + json.dump(self.file_data, json_file, indent = 4) + print('File [', self.file_path, '] is updated. Old version is saved in [', backupFilePath, ']') + + +class PassRequest: + + def __init__(self, passRequest: object): + self.pass_request = passRequest + if 'Connections' in passRequest: + self.connections = passRequest['Connections'] + + def __validate_connection(self, connection): + if ('LocalSlot' not in connection or 'AttachmentRef' not in connection): + raise KeyError('invalid connection data') + + def __ensure_connections_key(self): + if not hasattr(self, 'connections'): + self.pass_request['Connections'] = [] + self.connections = self.pass_request['Connections'] + + def get_connection_count(self): + if not hasattr(self, 'connections'): + return 0 + return len(self.connections) + + def find_connection(self, localSlotName): + if not hasattr(self, 'connections'): + return -1 + index = 0 + for connection in self.connections: + if connection['LocalSlot'] == localSlotName: + return index + index += 1 + return -1 + + def add_connection(self, newConnection): + self.__validate_connection(newConnection) + if self.find_connection(newConnection['LocalSlot']) >= 0: + raise ValueError('connection ', newConnection['LocalSlot'], ' already exists') + self.__ensure_connections_key() + self.connections.append(newConnection) \ No newline at end of file diff --git a/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/__init__.py b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/__init__.py new file mode 100644 index 0000000000..79f8fa4422 --- /dev/null +++ b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/__init__.py @@ -0,0 +1,10 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" diff --git a/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/test_pass_template.py b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/test_pass_template.py new file mode 100644 index 0000000000..d8cfc4840a --- /dev/null +++ b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/test_pass_template.py @@ -0,0 +1,303 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Unit tests for pass_data.py +""" +import os +import pytest +import shutil +import json +from atom_rpi_tools.pass_data import PassTemplate +from atom_rpi_tools.pass_data import PassRequest + +good_pass_requests_file = os.path.join(os.path.dirname(__file__), 'testdata/pass_requests.json') +good_pass_slots_file = os.path.join(os.path.dirname(__file__), 'testdata/pass_slots.json') +bad_test_data_file = os.path.join(os.path.dirname(__file__), 'testdata/pass_test_bad.json') + +@pytest.fixture +def pass_requests_template(tmpdir): + filename = 'pass_requests.json' + source_path = os.path.join(os.path.dirname(__file__), 'testdata/', filename) + destFilePath = os.path.join(tmpdir, 'pass_requests.json') + shutil.copyfile(source_path, destFilePath) + return PassTemplate(destFilePath) + +@pytest.fixture +def pass_slots_template(tmpdir): + filename = 'pass_slots.json' + source_path = os.path.join(os.path.dirname(__file__), 'testdata/', filename) + destFilePath = os.path.join(tmpdir, 'pass_requests.json') + shutil.copyfile(source_path, destFilePath) + return PassTemplate(destFilePath) + +@pytest.fixture +def new_pass_request(): + pass_request = json.loads('{\"Name\": \"InsertPass\",\"TemplateName\": \"InsertPassTemplate\"}') + return pass_request + +@pytest.fixture +def new_slot(): + slot = json.loads('{\"Name\": \"NewSlot\",\"SlotType\": \"Input\"}') + return slot + +@pytest.fixture +def new_connection(): + connection = json.loads('{\"LocalSlot\": \"color\", \"AttachmentRef\": { \"Pass\": \"Parent\", \"Attachment\": \"DepthStencil\"}}') + return connection + +def test_PassTemplate_Initialize_BadPassTemplateData_ExceptionThrown(): + with pytest.raises(KeyError): + PassTemplate(bad_test_data_file) + +def test_PassTemplate_FindPass_Success(pass_requests_template): + assert pass_requests_template.find_pass('OpaquePass') == 0 + assert pass_requests_template.find_pass('ImGuiPass') == 4 + assert pass_requests_template.find_pass('NotExistPass') == -1 + +def test_PassTemplate_InsertPassRequest_AtBegining_Success(pass_requests_template, new_pass_request): + template = pass_requests_template + pass_count = template.get_pass_count() + template.insert_pass_request(0, new_pass_request) + assert template.find_pass(new_pass_request['Name']) == 0 + assert template.get_pass_count() == pass_count+1 + + # verify the change is saved + template.save() + saved_tamplate = PassTemplate(template.file_path) + assert saved_tamplate.find_pass(new_pass_request['Name'])== 0 + assert saved_tamplate.get_pass_count() == pass_count+1 + +def test_PassTemplate_InsertPassRequest_AtEnd_Success(pass_requests_template, new_pass_request): + template = pass_requests_template + pass_count = template.get_pass_count() + template.insert_pass_request(pass_count, new_pass_request) + assert template.find_pass(new_pass_request['Name']) == pass_count + assert template.get_pass_count() == pass_count+1 + + # verify the change is saved + template.save() + saved_tamplate = PassTemplate(template.file_path) + assert saved_tamplate.find_pass(new_pass_request['Name']) == pass_count + assert saved_tamplate.get_pass_count() == pass_count+1 + +def test_PassTemplate_InsertPassRequest_WithDuplicatedName_ExceptionThrown(pass_requests_template, new_pass_request): + template = pass_requests_template + # insert new pass request + template.insert_pass_request(0, new_pass_request) + pass_count = template.get_pass_count() + # exception when insert the same pass again + with pytest.raises(ValueError): + template.insert_pass_request(2, new_pass_request) + # pass count doesn't change + assert template.get_pass_count() == pass_count + +def test_PassTemplate_InsertPassRequest_WithBadData_ExceptionThrown(pass_requests_template): + template = pass_requests_template + pass_count = template.get_pass_count() + bad_pass_request = json.loads('{\"name\":\"value\"}') + with pytest.raises(KeyError): + template.insert_pass_request(2, bad_pass_request) + assert template.get_pass_count() == pass_count + +def test_PassTemplate_InsertPassRequest_AtOutOfRange_AppendSuccess(pass_requests_template, new_pass_request): + template = pass_requests_template + pass_count = template.get_pass_count() + template.insert_pass_request(pass_count+2, new_pass_request) + assert template.find_pass(new_pass_request['Name']) == pass_count + assert template.get_pass_count() == pass_count+1 + +def test_PassTemplate_ReplaceReferencesAfter_Success(pass_requests_template): + # replace OpaquePass.DepthStencil with Parent.DepthStencil' + refPass = 'OpaquePass' + # there are 2 passes after OpaquePass which use OpaquePass.DepthStencil as attachment reference + assert pass_requests_template.replace_references_after(refPass, 'OpaquePass', 'DepthStencil', 'Parent', 'DepthStencil') == 2 + # after the previous replacement, there it no OpaquePass.DepthStencil reference + refPass = 'TransparentPass' + assert pass_requests_template.replace_references_after(refPass, 'OpaquePass', 'DepthStencil', 'Parent', 'DepthStencil') == 0 + + # verify changes are saved + pass_requests_template.save() + saved_tamplate = PassTemplate(pass_requests_template.file_path) + assert saved_tamplate.replace_references_after('OpaquePass', 'OpaquePass', 'DepthStencil', 'Parent', 'DepthStencil') == 0 + +def test_PassTemplate_ReplaceReferencesFor_Success(pass_requests_template): + refPass = 'TransparentPass' + assert pass_requests_template.replace_references_for(refPass, 'OpaquePass', 'DepthStencil', 'Parent', 'DepthStencil') == 1 + refPass = '2DPass' + assert pass_requests_template.replace_references_for(refPass, 'OpaquePass', 'DepthStencil', 'Parent', 'DepthStencil') == 0 + + # verify changes are saved + pass_requests_template.save() + saved_tamplate = PassTemplate(pass_requests_template.file_path) + # no reference of OpaquePass.DepthStencil in TransparentPass + assert saved_tamplate.replace_references_for('TransparentPass', 'OpaquePass', 'DepthStencil', 'Parent', 'DepthStencil') == 0 + +def test_PassTemplate_FindSlot_Success(pass_slots_template): + assert pass_slots_template.find_slot('Color') == -1 + assert pass_slots_template.find_slot('DepthStencil') == 0 + assert pass_slots_template.find_slot('ColorInputOutput') == 1 + +def test_PassTemplate_InsertSlot_AtBegining_Success(pass_slots_template, new_slot): + template = pass_slots_template + slot_count = template.get_slot_count() + depth_stencil_slot = template.find_slot('DepthStencil') + template.insert_slot(0, new_slot) + assert template.find_slot(new_slot['Name']) == 0 + assert template.find_slot('DepthStencil') == depth_stencil_slot+1 # DepthStencil moved back by 1 + assert template.get_slot_count() == slot_count+1 + + # verify the change is saved + template.save() + saved_tamplate = PassTemplate(template.file_path) + assert saved_tamplate.find_slot(new_slot['Name']) == 0 + assert saved_tamplate.get_slot_count() == slot_count+1 + +def test_PassTemplate_InsertSlot_AtEnd_Success(pass_slots_template, new_slot): + template = pass_slots_template + slot_count = template.get_slot_count() + depth_stencil_slot = template.find_slot('DepthStencil') + template.insert_slot(slot_count, new_slot) + assert template.find_slot(new_slot['Name']) == slot_count + assert template.find_slot('DepthStencil') == depth_stencil_slot + assert template.get_slot_count() == slot_count+1 + + # verify the change is saved + template.save() + saved_tamplate = PassTemplate(template.file_path) + assert saved_tamplate.find_slot(new_slot['Name']) == slot_count + assert saved_tamplate.get_slot_count() == slot_count+1 + +def test_PassTemplate_AddSlot_GoodSlotData_Success(pass_slots_template, new_slot): + template = pass_slots_template + slot_count = template.get_slot_count() + depth_stencil_slot = template.find_slot('DepthStencil') + template.add_slot(new_slot) + assert template.find_slot(new_slot['Name']) == slot_count + assert template.find_slot('DepthStencil') == depth_stencil_slot + assert template.get_slot_count() == slot_count+1 + + # verify the change is saved + template.save() + saved_tamplate = PassTemplate(template.file_path) + assert saved_tamplate.find_slot(new_slot['Name']) == slot_count + assert saved_tamplate.get_slot_count() == slot_count+1 + +def test_PassTemplate_InsertSlot_OutOfRange_AppendSuccess(pass_slots_template, new_slot): + template = pass_slots_template + slot_count = template.get_slot_count() + template.insert_slot(slot_count+3, new_slot) + assert template.find_slot(new_slot['Name']) == slot_count + assert template.get_slot_count() == slot_count+1 + +def test_PassTemplate_AddDuplicateSlot_ExceptionThrown(pass_slots_template, new_slot): + template = pass_slots_template + slot_count = template.get_slot_count() + template.add_slot(new_slot) + + with pytest.raises(ValueError): + template.insert_slot(0, new_slot) + with pytest.raises(ValueError): + template.add_slot(new_slot) + +def test_PassTemplate_InsertOrAddSlot_WithBadSlotData_ExceptionThrown(pass_slots_template): + template = pass_slots_template + slot_count = template.get_slot_count() + bad_slot = json.loads('{\"slot\": \"xxx\"}') + + with pytest.raises(KeyError): + template.insert_slot(0, bad_slot) + with pytest.raises(KeyError): + template.add_slot(bad_slot) + +def test_PassReqeuest_Initialize_WithExistPassReqeuestFromPassTemplate_Success(pass_requests_template): + template = pass_requests_template + request = PassRequest(template.get_pass_request('OpaquePass')) + connection_count = request.get_connection_count() + assert connection_count == 2 + +def test_PassTemplate_GetPassRequest_NotExist_ReturnNull(pass_requests_template): + assert not pass_requests_template.get_pass_request('NotExistPass') + +def test_PassReqeuest_AddConnection_WithExistingConnections_Success(pass_requests_template, new_connection): + template = pass_requests_template + request = PassRequest(template.get_pass_request('OpaquePass')) + connection_count = request.get_connection_count() + request.add_connection(new_connection) + connection_count += 1 + assert request.get_connection_count() == connection_count + + # verify changes are saved + template.save() + saved_tamplate = PassTemplate(template.file_path) + saved_request = PassRequest(saved_tamplate.get_pass_request('OpaquePass')) + assert saved_request.get_connection_count() == connection_count + +def test_PassReqeuest_AddConnection_WithNoExistingConnections_Success(pass_requests_template, new_connection): + template = pass_requests_template + request = PassRequest(template.get_pass_request('ImGuiPass')) + assert request.get_connection_count() == 0 + request.add_connection(new_connection) + assert request.get_connection_count() == 1 + + # verify changes are saved + template.save() + saved_tamplate = PassTemplate(template.file_path) + saved_request = PassRequest(saved_tamplate.get_pass_request('ImGuiPass')) + assert saved_request.get_connection_count() == 1 + +def test_PassReqeuest_AddConnection_WithDuplicatedName_ExceptionThrown(pass_requests_template, new_connection): + template = pass_requests_template + request = PassRequest(template.get_pass_request('OpaquePass')) + request.add_connection(new_connection) + with pytest.raises(ValueError): + request.add_connection(new_connection) + +def test_PassReqeuest_AddConnect_BadConnectionData_ExceptionThrown(pass_requests_template, new_connection): + template = pass_requests_template + request = PassRequest(template.get_pass_request('OpaquePass')) + bad_connection = json.loads('{\"xxx\": \"xxx\"}') + with pytest.raises(KeyError): + request.add_connection(bad_connection) + +def test_PassTemplate_InsertSlot_ToEmptyList_Success(pass_requests_template, new_slot): + template = pass_requests_template + # test insert slot function to pass template which doesn't have any slots + slot_count = template.get_slot_count() + assert slot_count == 0 + + assert template.find_slot(new_slot['Name'])==-1 + pass_requests_template.insert_slot(0, new_slot) + assert template.find_slot(new_slot['Name']) == 0 + assert template.get_slot_count() == 1 + + # verify changes are saved + template.save() + saved_tamplate = PassTemplate(template.file_path) + assert saved_tamplate.get_slot_count() == 1 + +def test_PassTempalte_InsertPassRequest_ToEmptyList_Success(pass_slots_template, new_pass_request): + template = pass_slots_template + # test insert pass function to pass template which doesn't have any pass requests + pass_count = template.get_pass_count() + assert pass_count == 0 + template.insert_pass_request(0, new_pass_request) + assert template.find_pass(new_pass_request['Name']) == 0 + assert template.get_pass_count() == 1 + + # verify changes are saved + template.save() + saved_tamplate = PassTemplate(template.file_path) + assert saved_tamplate.get_pass_count() == 1 + +def test_PassTemplate_Save_Success(pass_requests_template): + pass_requests_template.save() + saved_tamplate = PassTemplate(pass_requests_template.file_path) + assert os.path.exists(pass_requests_template.file_path) + assert os.path.exists(pass_requests_template.file_path +'.backup') diff --git a/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/test_utils.py b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/test_utils.py new file mode 100644 index 0000000000..ac1bb6edf9 --- /dev/null +++ b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/test_utils.py @@ -0,0 +1,53 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Unit tests for utils.py +""" +import pytest +import os +import atom_rpi_tools.utils as utils + + +def test_FindOrCopyFile_DestFileNotExist_CopySuccess(tmpdir): + # created dir and copied + filename = 'pass_requests.json' + source_path = os.path.join(os.path.dirname(__file__), 'testdata/', filename) + dest_path = os.path.join(tmpdir, 'testdata/', 'pass_requests.json') + assert not os.path.exists(dest_path) + utils.find_or_copy_file(dest_path, source_path) + assert os.path.exists(dest_path) + source_size = os.path.getsize(source_path) + dest_size = os.path.getsize(dest_path) + assert source_size == dest_size + +def test_FindOrCopyFile_DestFileAlreadyExists_Skip(tmpdir): + # copy %cur_dir%/testdata/pass_requests.json to tempdir/testdata/pass_requests.json + filename = 'pass_requests.json' + source_path = os.path.join(os.path.dirname(__file__), 'testdata/', filename) + dest_path = os.path.join(tmpdir, 'testdata/', 'pass_requests.json') + utils.find_or_copy_file(dest_path, source_path) + + # skip if dest_path already exists + assert os.path.exists(dest_path) + before_size = os.path.getsize(dest_path) + source_path = os.path.join(os.path.dirname(__file__), 'testdata/', 'pass_slots.json') + before_source_size = os.path.getsize(source_path) + assert before_size != source_path + utils.find_or_copy_file(dest_path, source_path) + after_size = os.path.getsize(dest_path) + assert before_size == after_size + + +def test_FindOrCopyFile_SourceFileNotExists_ExceptionThrown(tmpdir): + # report error if source doesn't exist + bad_source_path = 'notexist.dat' + dest_path = os.path.join(tmpdir, 'notexist.dat') + with pytest.raises(ValueError): + utils.find_or_copy_file(dest_path, bad_source_path) diff --git a/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_requests.json b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_requests.json new file mode 100644 index 0000000000..f3dd3f7a19 --- /dev/null +++ b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_requests.json @@ -0,0 +1,116 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "PassAsset", + "ClassData": { + "PassTemplate": { + "Name": "PipelineTemplate", + "PassClass": "ParentPass", + "PassRequests": [ + { + "Name": "OpaquePass", + "TemplateName": "OpaquePassTemplate", + "Connections": [ + { + "LocalSlot": "DepthStencil", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "DepthStencil" + } + }, + { + "LocalSlot": "ColorInputOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "ColorInputOutput" + } + } + ] + }, + { + "Name": "TransparentPass", + "TemplateName": "TransparentPassTemplate", + "Enabled": true, + "Connections": [ + { + "LocalSlot": "DepthStencil", + "AttachmentRef": { + "Pass": "OpaquePass", + "Attachment": "DepthStencil" + } + }, + { + "LocalSlot": "ColorInputOutput", + "AttachmentRef": { + "Pass": "OpaquePass", + "Attachment": "Color" + } + } + ], + "PassData": { + "$type": "RasterPassData", + "DrawListTag": "transparent", + "DrawListSortType": "KeyThenReverseDepth", + "PipelineViewTag": "MainCamera", + "PassSrgAsset": { + "FilePath": "shaderlib/atom/features/pbr/transparentpasssrg.azsli:PassSrg" + } + } + }, + { + "Name": "AuxGeomPass", + "TemplateName": "AuxGeomPassTemplate", + "Enabled": true, + "Connections": [ + { + "LocalSlot": "DepthStencil", + "AttachmentRef": { + "Pass": "OpaquePass", + "Attachment": "DepthStencil" + } + }, + { + "LocalSlot": "ColorInputOutput", + "AttachmentRef": { + "Pass": "TransparentPass", + "Attachment": "ColorInputOutput" + } + } + ], + "PassData": { + "$type": "RasterPassData", + "DrawListTag": "auxgeom", + "PipelineViewTag": "MainCamera" + } + }, + { + "Name": "2DPass", + "TemplateName": "UIPassTemplate", + "Enabled": true, + "Connections": [ + { + "LocalSlot": "ColorInputOutput", + "AttachmentRef": { + "Pass": "TransparentPass", + "Attachment": "ColorInputOutput" + } + } + ], + "PassData": { + "$type": "RasterPassData", + "DrawListTag": "2dpass", + "PipelineViewTag": "MainCamera" + } + }, + { + "Name": "ImGuiPass", + "TemplateName": "ImGuiPassTemplate", + "PassData": { + "$type": "ImGuiPassData", + "IsDefaultImGui": true + } + } + ] + } + } +} diff --git a/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_slots.json b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_slots.json new file mode 100644 index 0000000000..7274b0968a --- /dev/null +++ b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_slots.json @@ -0,0 +1,21 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "PassAsset", + "ClassData": { + "PassTemplate": { + "Name": "PipelineTemplate", + "PassClass": "ParentPass", + "Slots": [ + { + "Name": "DepthStencil", + "SlotType": "InputOutput" + }, + { + "Name": "ColorInputOutput", + "SlotType": "InputOutput" + } + ] + } + } +} diff --git a/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_test_bad.json b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_test_bad.json new file mode 100644 index 0000000000..a0e5ffcc90 --- /dev/null +++ b/Gems/Atom/RPI/Tools/atom_rpi_tools/tests/testdata/pass_test_bad.json @@ -0,0 +1,6 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassData": { + } +} \ No newline at end of file diff --git a/Gems/Atom/RPI/Tools/atom_rpi_tools/utils.py b/Gems/Atom/RPI/Tools/atom_rpi_tools/utils.py new file mode 100644 index 0000000000..90037a8287 --- /dev/null +++ b/Gems/Atom/RPI/Tools/atom_rpi_tools/utils.py @@ -0,0 +1,31 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" +import os.path +from os import path +import shutil +import json + + +def find_or_copy_file(destFilePath, sourceFilePath): + if path.exists(destFilePath): + return + if not path.exists(sourceFilePath): + raise ValueError('find_or_copy_file: source file [', sourceFilePath, '] doesn\'t exist') + return + + dstDir = path.dirname(destFilePath) + if not path.isdir(dstDir): + os.makedirs(dstDir) + shutil.copyfile(sourceFilePath, destFilePath) + +def load_json_file(filePath): + file_stream = open(filePath, "r") + return json.load(file_stream) diff --git a/Gems/Atom/RPI/Tools/setup.py b/Gems/Atom/RPI/Tools/setup.py new file mode 100644 index 0000000000..ab494ec773 --- /dev/null +++ b/Gems/Atom/RPI/Tools/setup.py @@ -0,0 +1,33 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" +import os +import platform + +from setuptools import setup, find_packages + +PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) + +PYTHON_64 = platform.architecture()[0] == '64bit' + +if __name__ == '__main__': + if not PYTHON_64: + raise RuntimeError("32-bit Python is not a supported platform.") + + with open(os.path.join(PROJECT_ROOT, 'README.txt')) as f: + long_description = f.read() + + setup( + name="atom_rpi_tools", + version="1.0.0", + description='Python interface to Atom RPI tools', + long_description=long_description, + packages=find_packages(exclude=['tests']) + ) From bb92e4c0b86963d59916bbfc844d5d998215ae1f Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Wed, 2 Jun 2021 19:49:38 -0500 Subject: [PATCH 436/811] Font update to dynamic draw per view (#1085) * Move AtomFont over to use the new per viewport dynamic draw context. Remove scene tracking and listening for bootstrap scene created. Remove build dependency on the Bootstrap gem. Add build dependency on the AtomBridge gem. FFont's are now initialized with a viewport Id. Remove previous DynamicDraw context per scene system. Verify FFont can get a dynamic draw context before attempting initialization. Ensure a render scene exists before attempting font initialization (as a proxy for rendering has begun) * Move AtomFont FFont to use ShaderInputNameIndex's This allowed removing all of the InitFont function as no longer need to query compiled shader info for constant data offsets. * cache the AZ::Name used to find the dynamic draw context rather than recreate it each use --- .../AtomFont/Code/CMakeLists.txt | 3 +- .../AtomLyIntegration/AtomFont/AtomFont.h | 15 +-- .../AtomLyIntegration/AtomFont/FFont.h | 22 +--- .../AtomFont/Code/Source/AtomFont.cpp | 74 +++--------- .../AtomFont/Code/Source/FFont.cpp | 105 ++++-------------- 5 files changed, 51 insertions(+), 168 deletions(-) diff --git a/Gems/AtomLyIntegration/AtomFont/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomFont/Code/CMakeLists.txt index d3b8c8cde7..0045b37687 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomFont/Code/CMakeLists.txt @@ -29,7 +29,8 @@ ly_add_target( Legacy::CryCommon Gem::Atom_RHI.Reflect Gem::Atom_RPI.Public - Gem::Atom_Bootstrap.Headers + PUBLIC + Gem::Atom_AtomBridge.Static ) ################################################################################ diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h index d5463fc15c..d21796cf17 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h @@ -27,11 +27,14 @@ #include #include +#include namespace AZ { class FFont; + static constexpr char AtomFontDynamicDrawContextName[] = "AtomFont"; + //! AtomFont is the font system manager. //! AtomFont manages the lifetime of FFont instances, each of which represents an individual font (e.g Courier New Italic) @@ -90,13 +93,6 @@ namespace AZ AzFramework::FontDrawInterface* GetFontDrawInterface(AzFramework::FontId fontId) const override; AzFramework::FontDrawInterface* GetDefaultFontDrawInterface() const override; - void SceneAboutToBeRemoved(AzFramework::Scene& scene); - - - // Atom DynamicDraw interface management - AZ::RHI::Ptr GetOrCreateDynamicDrawForScene(AZ::RPI::Scene* scene); - - public: void UnregisterFont(const char* fontName); @@ -108,8 +104,6 @@ namespace AZ using FontFamilyMap = AZStd::unordered_map>; using FontFamilyReverseLookupMap = AZStd::unordered_map; - using SceneToDynamicDrawMap = AZStd::unordered_map>; - private: //! Convenience method for loading fonts IFFont* LoadFont(const char* fontName); @@ -145,9 +139,6 @@ namespace AZ int r_persistFontFamilies = 1; //!< Persist fonts for application lifetime to prevent unnecessary work; enabled by default. AZStd::vector m_persistedFontFamilies; //!< Stores persisted fonts (if "persist font families" is enabled) - - SceneToDynamicDrawMap m_sceneToDynamicDrawMap; - AZStd::shared_mutex m_sceneToDynamicDrawMutex; }; } #endif diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h index 1e224d6090..78d74a784a 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h @@ -42,11 +42,9 @@ #include #include #include +#include #include -#include -#include - struct ISystem; namespace AZ @@ -68,7 +66,6 @@ namespace AZ : public IFFont , public AZStd::intrusive_refcount , public AzFramework::FontDrawInterface - , private AZ::Render::Bootstrap::NotificationBus::Handler { using ref_count = AZStd::intrusive_refcount; friend FontDeleter; @@ -168,8 +165,8 @@ namespace AZ struct FontShaderData { - AZ::RHI::ShaderInputImageIndex m_imageInputIndex; - AZ::RHI::ShaderInputConstantIndex m_viewProjInputIndex; + AZ::RHI::ShaderInputNameIndex m_imageInputIndex = "m_texture"; + AZ::RHI::ShaderInputNameIndex m_viewProjInputIndex = "m_worldToProj"; }; public: @@ -230,7 +227,6 @@ namespace AZ private: virtual ~FFont(); - bool InitFont(AZ::RPI::Scene* renderScene); bool InitTexture(); bool InitCache(); @@ -281,8 +277,6 @@ namespace AZ void ScaleCoord(const RHI::Viewport& viewport, float& x, float& y) const; - void OnBootstrapSceneReady(AZ::RPI::Scene* bootstrapScene) override; - RPI::WindowContextSharedPtr GetDefaultWindowContext() const; RPI::ViewportContextPtr GetDefaultViewportContext() const; @@ -303,6 +297,8 @@ namespace AZ string m_name; string m_curPath; + AZ::Name m_dynamicDrawContextName = AZ::Name(AZ::AtomFontDynamicDrawContextName); + FontTexture* m_fontTexture = nullptr; size_t m_fontBufferSize = 0; @@ -315,13 +311,6 @@ namespace AZ AtomFont* m_atomFont = nullptr; bool m_fontTexDirty = false; - enum class InitializationState : AZ::u8 - { - Uninitialized, - Initializing, - Initialized - }; - AZStd::atomic m_fontInitializationState = InitializationState::Uninitialized; FontEffects m_effects; @@ -356,6 +345,7 @@ namespace AZ if (font && font->m_atomFont) { font->m_atomFont->UnregisterFont(font->m_name); + font->m_atomFont = nullptr; } delete font; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp index 623a931ac9..fd8a4f26ed 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp @@ -354,17 +354,26 @@ AZ::AtomFont::AtomFont(ISystem* system) #endif AZ::Interface::Register(this); - m_sceneEventHandler = AzFramework::ISceneSystem::SceneEvent::Handler( - [this](AzFramework::ISceneSystem::EventType eventType, const AZStd::shared_ptr& scene) + // register font per viewport dynamic draw context. + static const char* shaderFilepath = "Shaders/SimpleTextured.azshader"; + AZ::AtomBridge::PerViewportDynamicDraw::Get()->RegisterDynamicDrawContext( + AZ::Name(AZ::AtomFontDynamicDrawContextName), + [](RPI::Ptr drawContext) { - if (eventType == AzFramework::ISceneSystem::EventType::ScenePendingRemoval) - { - SceneAboutToBeRemoved(*scene); - } + Data::Instance shader = AZ::RPI::LoadShader(shaderFilepath); + AZ::RPI::ShaderOptionList shaderOptions; + shaderOptions.push_back(AZ::RPI::ShaderOption(AZ::Name("o_useColorChannels"), AZ::Name("false"))); + shaderOptions.push_back(AZ::RPI::ShaderOption(AZ::Name("o_clamp"), AZ::Name("true"))); + drawContext->InitShaderWithVariant(shader, &shaderOptions); + drawContext->InitVertexFormat( + { + {"POSITION", RHI::Format::R32G32B32_FLOAT}, + {"COLOR", RHI::Format::B8G8R8A8_UNORM}, + {"TEXCOORD0", RHI::Format::R32G32_FLOAT} + }); + drawContext->EndInit(); }); - auto sceneSystem = AzFramework::SceneSystemInterface::Get(); - AZ_Assert(sceneSystem, "Font created before the scene system is available."); - sceneSystem->ConnectToEvents(m_sceneEventHandler); + } AZ::AtomFont::~AtomFont() @@ -860,52 +869,5 @@ XmlNodeRef AZ::AtomFont::LoadFontFamilyXml(const char* fontFamilyName, string& o return root; } - -void AZ::AtomFont::SceneAboutToBeRemoved(AzFramework::Scene& scene) -{ - AZ::RPI::ScenePtr* rpiScene = scene.FindSubsystem(); - if (rpiScene) - { - AZStd::lock_guard lock(m_sceneToDynamicDrawMutex); - if (auto it = m_sceneToDynamicDrawMap.find(rpiScene->get()); it != m_sceneToDynamicDrawMap.end()) - { - m_sceneToDynamicDrawMap.erase(it); - } - } -} - -AZ::RHI::Ptr AZ::AtomFont::GetOrCreateDynamicDrawForScene(AZ::RPI::Scene* scene) -{ - static const char* shaderFilepath = "Shaders/SimpleTextured.azshader"; - - { - // shared lock while reading - AZStd::shared_lock lock(m_sceneToDynamicDrawMutex); - - if (auto it = m_sceneToDynamicDrawMap.find(scene); it != m_sceneToDynamicDrawMap.end()) - { - return it->second; - } - } - - // Create and initialize DynamicDrawContext for font draw - AZ::RHI::Ptr dynamicDraw = RPI::DynamicDrawInterface::Get()->CreateDynamicDrawContext(scene); - - Data::Instance shader = AZ::RPI::LoadShader(shaderFilepath); - AZ::RPI::ShaderOptionList shaderOptions; - shaderOptions.push_back(AZ::RPI::ShaderOption(AZ::Name("o_useColorChannels"), AZ::Name("false"))); - shaderOptions.push_back(AZ::RPI::ShaderOption(AZ::Name("o_clamp"), AZ::Name("true"))); - dynamicDraw->InitShaderWithVariant(shader, &shaderOptions); - dynamicDraw->InitVertexFormat({{"POSITION", RHI::Format::R32G32B32_FLOAT}, {"COLOR", RHI::Format::B8G8R8A8_UNORM}, {"TEXCOORD0", RHI::Format::R32G32_FLOAT}}); - dynamicDraw->EndInit(); - - // exclusive lock while writing - AZStd::lock_guard lock(m_sceneToDynamicDrawMutex); - m_sceneToDynamicDrawMap.insert(AZStd::make_pair(scene, dynamicDraw)); - - return dynamicDraw; -} - - #endif diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index 31eb089803..1976c69b45 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -60,14 +60,7 @@ static const size_t MaxVerts = 8 * 1024; // 2048 quads static const size_t MaxIndices = (MaxVerts * 6) / 4; // 6 indices per quad, 6/4 * MaxVerts static const char DrawList2DPassName[] = "2dpass"; -namespace ShaderInputs -{ - static const char TextureIndexName[] = "m_texture"; - static const char WorldToProjIndexName[] = "m_worldToProj"; - static const char SamplerIndexName[] = "m_sampler"; -} - -AZ::FFont::FFont(AtomFont* atomFont, const char* fontName) +AZ::FFont::FFont(AZ::AtomFont* atomFont, const char* fontName) : m_name(fontName) , m_atomFont(atomFont) { @@ -78,9 +71,14 @@ AZ::FFont::FFont(AtomFont* atomFont, const char* fontName) FontEffect* effect = AddEffect("default"); effect->AddPass(); - AddRef(); + // Create cpu memory to cache the font draw data before submit + m_vertexBuffer = new SVF_P3F_C4B_T2F[MaxVerts]; + m_indexBuffer = new u16[MaxIndices]; - AZ::Render::Bootstrap::NotificationBus::Handler::BusConnect(); + m_vertexCount = 0; + m_indexCount = 0; + + AddRef(); } AZ::RPI::ViewportContextPtr AZ::FFont::GetDefaultViewportContext() const @@ -98,55 +96,10 @@ AZ::RPI::WindowContextSharedPtr AZ::FFont::GetDefaultWindowContext() const return {}; } -bool AZ::FFont::InitFont(AZ::RPI::Scene* renderScene) -{ - if (!renderScene) - { - return false; - } - - auto initializationState = InitializationState::Uninitialized; - // Do an atomic transition to Initializing if we're in the Uninitialized state. - // Otherwise, check the current state. - // If we're Initialized, there's no more work to be done, return true to indicate we're good to go. - // If we're Initializing (on another thread), return false to let the consumer know it's not safe for us to be used yet. - if (!m_fontInitializationState.compare_exchange_strong(initializationState, InitializationState::Initializing)) - { - return initializationState == InitializationState::Initialized; - } - - // Create and initialize DynamicDrawContext for font draw - AZ::RPI::Ptr dynamicDraw = m_atomFont->GetOrCreateDynamicDrawForScene(renderScene); - - // Save draw srg input indices for later use - Data::Instance drawSrg = dynamicDraw->NewDrawSrg(); - const RHI::ShaderResourceGroupLayout* layout = drawSrg->GetAsset()->GetLayout(); - - m_fontShaderData.m_imageInputIndex = layout->FindShaderInputImageIndex(AZ::Name(ShaderInputs::TextureIndexName)); - AZ_Error("AtomFont::FFont", m_fontShaderData.m_imageInputIndex.IsValid(), "Failed to find shader input constant %s.", - ShaderInputs::TextureIndexName); - - m_fontShaderData.m_viewProjInputIndex = layout->FindShaderInputConstantIndex(AZ::Name(ShaderInputs::WorldToProjIndexName)); - AZ_Error("AtomFont::FFont", m_fontShaderData.m_viewProjInputIndex.IsValid(), "Failed to find shader input constant %s.", - ShaderInputs::WorldToProjIndexName); - - // Create cpu memory to cache the font draw data before submit - m_vertexBuffer = new SVF_P3F_C4B_T2F[MaxVerts]; - m_indexBuffer = new u16[MaxIndices]; - - m_vertexCount = 0; - m_indexCount = 0; - - m_fontInitializationState = InitializationState::Initialized; - return true; -} - AZ::FFont::~FFont() { AZ_Assert(m_atomFont == nullptr, "The font should already be unregistered through a call to AZ::FFont::Release()"); - AZ::Render::Bootstrap::NotificationBus::Handler::BusDisconnect(); - delete[] m_vertexBuffer; delete[] m_indexBuffer; @@ -303,7 +256,8 @@ void AZ::FFont::DrawStringUInternal( const TextDrawContext& ctx) { // Lazily ensure we're initialized before attempting to render. - if (!viewportContext || !InitFont(viewportContext->GetRenderScene().get())) + // Validate that there is a render scene before attempting to init. + if (!viewportContext || !viewportContext->GetRenderScene()) { return; } @@ -323,12 +277,6 @@ void AZ::FFont::DrawStringUInternal( return; } - // if the font is about to be deleted then m_atomFont can be nullptr - if (!m_atomFont) - { - return; - } - const bool orthoMode = ctx.m_overrideViewProjMatrices; const float viewX = viewport.m_minX; @@ -406,14 +354,17 @@ void AZ::FFont::DrawStringUInternal( if (numQuads) { - auto dynamicDraw = m_atomFont->GetOrCreateDynamicDrawForScene(viewportContext->GetRenderScene().get()); - //setup per draw srg - auto drawSrg = dynamicDraw->NewDrawSrg(); - drawSrg->SetConstant(m_fontShaderData.m_viewProjInputIndex, modelViewProjMat); - drawSrg->SetImageView(m_fontShaderData.m_imageInputIndex, m_fontStreamingImage->GetImageView()); - drawSrg->Compile(); + AZ::RPI::Ptr dynamicDraw = AZ::AtomBridge::PerViewportDynamicDraw::Get()->GetDynamicDrawContextForViewport(m_dynamicDrawContextName, viewportContext->GetId()); + if (dynamicDraw) + { + //setup per draw srg + auto drawSrg = dynamicDraw->NewDrawSrg(); + drawSrg->SetConstant(m_fontShaderData.m_viewProjInputIndex, modelViewProjMat); + drawSrg->SetImageView(m_fontShaderData.m_imageInputIndex, m_fontStreamingImage->GetImageView()); + drawSrg->Compile(); - dynamicDraw->DrawIndexed(m_vertexBuffer, m_vertexCount, m_indexBuffer, m_indexCount, RHI::IndexFormat::Uint16, drawSrg); + dynamicDraw->DrawIndexed(m_vertexBuffer, m_vertexCount, m_indexBuffer, m_indexCount, RHI::IndexFormat::Uint16, drawSrg); + } m_indexCount = 0; m_vertexCount = 0; } @@ -694,12 +645,6 @@ uint32_t AZ::FFont::WriteTextQuadsToBuffers(SVF_P2F_C4B_T2F_F4B* verts, uint16_t return numQuadsWritten; } - // if the font is about to be deleted then m_atomFont can be nullptr - if (!m_atomFont) - { - return numQuadsWritten; - } - SVF_P2F_C4B_T2F_F4B* vertexData = verts; uint16_t* indexData = indices; size_t vertexOffset = 0; @@ -1523,7 +1468,7 @@ bool AZ::FFont::UpdateTexture() { using namespace AZ; - if (m_fontInitializationState != InitializationState::Initialized || !m_fontImage) + if (!m_fontImage) { return false; } @@ -1591,7 +1536,7 @@ void AZ::FFont::Prepare(const char* str, bool updateTexture, const AtomFont::Gly const bool rerenderGlyphs = m_sizeBehavior == SizeBehavior::Rerender; const AtomFont::GlyphSize usedGlyphSize = rerenderGlyphs ? glyphSize : AtomFont::defaultGlyphSize; bool texUpdateNeeded = m_fontTexture->PreCacheString(str, nullptr, m_sizeRatio, usedGlyphSize, m_fontHintParams) == 1 || m_fontTexDirty; - if (m_fontInitializationState == InitializationState::Initialized && updateTexture && texUpdateNeeded && m_fontImage) + if (updateTexture && texUpdateNeeded && m_fontImage) { UpdateTexture(); m_fontTexDirty = false; @@ -1625,12 +1570,6 @@ void AZ::FFont::ScaleCoord(const RHI::Viewport& viewport, float& x, float& y) co y *= height / WindowScaleHeight; } - -void AZ::FFont::OnBootstrapSceneReady([[maybe_unused]] AZ::RPI::Scene* bootstrapScene) -{ - InitFont(bootstrapScene); -} - static void SetCommonContextFlags(AZ::TextDrawContext& ctx, const AzFramework::TextDrawParameters& params) { if (params.m_hAlign == AzFramework::TextHorizontalAlignment::Center) From 01f3ba560819fcba0d3a5575510e597904cced4f Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 17:58:58 -0700 Subject: [PATCH 437/811] [cpack_installer] fourth attempt to fix cpack selection --- scripts/build/Platform/Windows/installer_windows.cmd | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/scripts/build/Platform/Windows/installer_windows.cmd b/scripts/build/Platform/Windows/installer_windows.cmd index 41cc21b35b..ef284290f3 100644 --- a/scripts/build/Platform/Windows/installer_windows.cmd +++ b/scripts/build/Platform/Windows/installer_windows.cmd @@ -23,7 +23,7 @@ PUSHD %OUTPUT_DIRECTORY% REM Override the temporary directory used by wix to the EBS volume SET "WIX_TEMP=!WORKSPACE!/temp/wix" IF NOT EXIST "%WIX_TEMP%" ( - MKDIR "WIX_TEMP%" + MKDIR "%WIX_TEMP%" ) REM Make sure we are using the CMake version of CPack and not the one that comes with chocolatey @@ -40,15 +40,15 @@ IF "%LY_CMAKE_PATH%"=="" ( SET "CPACK_PATH=%LY_CMAKE_PATH%\cpack.exe" ) -ECHO [ci_build] "%CPACK_PATH%" --version -"%CPACK_PATH%" --version +ECHO [ci_build] "!CPACK_PATH!" --version +"!CPACK_PATH!" --version IF ERRORLEVEL 1 ( ECHO [ci_build] CPack not found! exit /b 1 ) -REM Run cpack -ECHO [ci_build] "%CPACK_PATH%" -C %CONFIGURATION% -"%CPACK_PATH%" -C %CONFIGURATION% + +ECHO [ci_build] "!CPACK_PATH!" -C %CONFIGURATION% +"!CPACK_PATH!" -C %CONFIGURATION% IF NOT %ERRORLEVEL%==0 GOTO :popd_error POPD From 9dbe596e400bbeac8fcecc34227821fceab378b1 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Wed, 2 Jun 2021 18:39:05 -0700 Subject: [PATCH 438/811] Added reflection probe cubemap quality levels --- .../Config/IBLSpecular.preset | 15 +- .../Config/IBLSpecularHigh.preset | 135 ++++++++++++++++++ .../Config/IBLSpecularLow.preset | 135 ++++++++++++++++++ .../Config/IBLSpecularVeryHigh.preset | 135 ++++++++++++++++++ .../Config/IBLSpecularVeryLow.preset | 135 ++++++++++++++++++ .../EditorReflectionProbeComponent.cpp | 20 ++- .../EditorReflectionProbeComponent.h | 1 + .../ReflectionProbeComponentController.cpp | 1 + .../ReflectionProbeComponentController.h | 24 ++++ 9 files changed, 595 insertions(+), 6 deletions(-) create mode 100644 Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularHigh.preset create mode 100644 Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularLow.preset create mode 100644 Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryHigh.preset create mode 100644 Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryLow.preset diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset index d940f425c2..4f935c73ff 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset @@ -8,7 +8,8 @@ "Name": "IBLSpecular", "Description": "The input cubemap generates an IBL specular output cubemap.", "FileMasks": [ - "_iblspecularcm" + "_iblspecularcm", + "_iblspecularcm256" ], "SourceColor": "Linear", "DestColor": "Linear", @@ -34,7 +35,8 @@ "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", "FileMasks": [ - "_iblspecularcm" + "_iblspecularcm", + "_iblspecularcm256" ], "SourceColor": "Linear", "DestColor": "Linear", @@ -59,7 +61,8 @@ "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", "FileMasks": [ - "_iblspecularcm" + "_iblspecularcm", + "_iblspecularcm256" ], "SourceColor": "Linear", "DestColor": "Linear", @@ -84,7 +87,8 @@ "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", "FileMasks": [ - "_iblspecularcm" + "_iblspecularcm", + "_iblspecularcm256" ], "SourceColor": "Linear", "DestColor": "Linear", @@ -109,7 +113,8 @@ "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", "FileMasks": [ - "_iblspecularcm" + "_iblspecularcm", + "_iblspecularcm256" ], "SourceColor": "Linear", "DestColor": "Linear", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularHigh.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularHigh.preset new file mode 100644 index 0000000000..ff4e143326 --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularHigh.preset @@ -0,0 +1,135 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "MultiplatformPresetSettings", + "ClassData": { + "DefaultPreset": { + "UUID": "{B66395E1-8D0E-4159-989B-FC2B9F091B75}", + "Name": "IBLSpecularHigh", + "Description": "The input cubemap generates an IBL specular output cubemap.", + "FileMasks": [ + "_iblspecularcm512" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 512, + "MaxTextureSize": 512, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "PlatformsPresets": { + "android": { + "UUID": "{B66395E1-8D0E-4159-989B-FC2B9F091B75}", + "Name": "IBLSpecularHigh", + "FileMasks": [ + "_iblspecularcm512" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 512, + "MaxTextureSize": 512, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "ios": { + "UUID": "{B66395E1-8D0E-4159-989B-FC2B9F091B75}", + "Name": "IBLSpecularHigh", + "FileMasks": [ + "_iblspecularcm512" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 512, + "MaxTextureSize": 512, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "mac": { + "UUID": "{B66395E1-8D0E-4159-989B-FC2B9F091B75}", + "Name": "IBLSpecularHigh", + "FileMasks": [ + "_iblspecularcm512" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 512, + "MaxTextureSize": 512, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "provo": { + "UUID": "{B66395E1-8D0E-4159-989B-FC2B9F091B75}", + "Name": "IBLSpecularHigh", + "FileMasks": [ + "_iblspecularcm512" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 512, + "MaxTextureSize": 512, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + } + } + } +} diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularLow.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularLow.preset new file mode 100644 index 0000000000..ee9ddd6ac7 --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularLow.preset @@ -0,0 +1,135 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "MultiplatformPresetSettings", + "ClassData": { + "DefaultPreset": { + "UUID": "{7273ACAE-6E34-487C-AF71-99423A6E1CB0}", + "Name": "IBLSpecularLow", + "Description": "The input cubemap generates an IBL specular output cubemap.", + "FileMasks": [ + "_iblspecularcm128" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 128, + "MaxTextureSize": 128, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "PlatformsPresets": { + "android": { + "UUID": "{7273ACAE-6E34-487C-AF71-99423A6E1CB0}", + "Name": "IBLSpecularLow", + "FileMasks": [ + "_iblspecularcm128" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 128, + "MaxTextureSize": 128, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "ios": { + "UUID": "{7273ACAE-6E34-487C-AF71-99423A6E1CB0}", + "Name": "IBLSpecularLow", + "FileMasks": [ + "_iblspecularcm128" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 128, + "MaxTextureSize": 128, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "mac": { + "UUID": "{7273ACAE-6E34-487C-AF71-99423A6E1CB0}", + "Name": "IBLSpecularLow", + "FileMasks": [ + "_iblspecularcm128" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 128, + "MaxTextureSize": 128, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "provo": { + "UUID": "{7273ACAE-6E34-487C-AF71-99423A6E1CB0}", + "Name": "IBLSpecularLow", + "FileMasks": [ + "_iblspecularcm128" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 128, + "MaxTextureSize": 128, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + } + } + } +} diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryHigh.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryHigh.preset new file mode 100644 index 0000000000..08d9416935 --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryHigh.preset @@ -0,0 +1,135 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "MultiplatformPresetSettings", + "ClassData": { + "DefaultPreset": { + "UUID": "{5CD1AFA6-915B-4716-893C-A5B1F4074C22}", + "Name": "IBLSpecularVeryHigh", + "Description": "The input cubemap generates an IBL specular output cubemap.", + "FileMasks": [ + "_iblspecularcm1024" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 1024, + "MaxTextureSize": 1024, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "PlatformsPresets": { + "android": { + "UUID": "{5CD1AFA6-915B-4716-893C-A5B1F4074C22}", + "Name": "IBLSpecularVeryHigh", + "FileMasks": [ + "_iblspecularcm1024" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 1024, + "MaxTextureSize": 1024, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "ios": { + "UUID": "{5CD1AFA6-915B-4716-893C-A5B1F4074C22}", + "Name": "IBLSpecularVeryHigh", + "FileMasks": [ + "_iblspecularcm1024" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 1024, + "MaxTextureSize": 1024, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "mac": { + "UUID": "{5CD1AFA6-915B-4716-893C-A5B1F4074C22}", + "Name": "IBLSpecularVeryHigh", + "FileMasks": [ + "_iblspecularcm1024" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 1024, + "MaxTextureSize": 1024, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "provo": { + "UUID": "{5CD1AFA6-915B-4716-893C-A5B1F4074C22}", + "Name": "IBLSpecularVeryHigh", + "FileMasks": [ + "_iblspecularcm1024" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 1024, + "MaxTextureSize": 1024, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + } + } + } +} diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryLow.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryLow.preset new file mode 100644 index 0000000000..c5c0788848 --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryLow.preset @@ -0,0 +1,135 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "MultiplatformPresetSettings", + "ClassData": { + "DefaultPreset": { + "UUID": "{8293C236-D3E8-4352-8B18-C2E82EEE6547}", + "Name": "IBLSpecularVeryLow", + "Description": "The input cubemap generates an IBL specular output cubemap.", + "FileMasks": [ + "_iblspecularcm64" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 64, + "MaxTextureSize": 64, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "PlatformsPresets": { + "android": { + "UUID": "{8293C236-D3E8-4352-8B18-C2E82EEE6547}", + "Name": "IBLSpecularVeryLow", + "FileMasks": [ + "_iblspecularcm64" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 64, + "MaxTextureSize": 64, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "ios": { + "UUID": "{8293C236-D3E8-4352-8B18-C2E82EEE6547}", + "Name": "IBLSpecularVeryLow", + "FileMasks": [ + "_iblspecularcm64" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 64, + "MaxTextureSize": 64, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "mac": { + "UUID": "{8293C236-D3E8-4352-8B18-C2E82EEE6547}", + "Name": "IBLSpecularVeryLow", + "FileMasks": [ + "_iblspecularcm64" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 64, + "MaxTextureSize": 64, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "provo": { + "UUID": "{8293C236-D3E8-4352-8B18-C2E82EEE6547}", + "Name": "IBLSpecularVeryLow", + "FileMasks": [ + "_iblspecularcm64" + ], + "SourceColor": "Linear", + "DestColor": "Linear", + "SuppressEngineReduce": true, + "PixelFormat": "R9G9B9E5", + "DiscardAlpha": true, + "MinTextureSize": 64, + "MaxTextureSize": 64, + "IsPowerOf2": true, + "CubemapSettings": { + "Filter": "GGX", + "MipAngle": 7.0, + "MipSlope": 2.299999952316284, + "EdgeFixup": -431602080.0, + "SubId": 2000 + }, + "MipMapSetting": { + "MipGenType": "Box" + } + } + } + } +} diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp index 7880d5e88c..f3932322b1 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp @@ -39,6 +39,7 @@ namespace AZ serializeContext->Class() ->Version(2, ConvertToEditorRenderComponentAdapter<1>) ->Field("useBakedCubemap", &EditorReflectionProbeComponent::m_useBakedCubemap) + ->Field("bakedCubeMapQualityLevel", &EditorReflectionProbeComponent::m_bakedCubeMapQualityLevel) ->Field("bakedCubeMapRelativePath", &EditorReflectionProbeComponent::m_bakedCubeMapRelativePath) ->Field("authoredCubeMapAsset", &EditorReflectionProbeComponent::m_authoredCubeMapAsset) ; @@ -67,6 +68,13 @@ namespace AZ ->DataElement(AZ::Edit::UIHandlers::Default, &EditorReflectionProbeComponent::m_useBakedCubemap, "Use Baked Cubemap", "Selects between a cubemap that captures the environment at location in the scene or a preauthored cubemap") ->Attribute(AZ::Edit::Attributes::ChangeValidate, &EditorReflectionProbeComponent::OnUseBakedCubemapValidate) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorReflectionProbeComponent::OnUseBakedCubemapChanged) + ->DataElement(AZ::Edit::UIHandlers::ComboBox, &EditorReflectionProbeComponent::m_bakedCubeMapQualityLevel, "Baked Cubemap Quality", "Resolution of the baked cubemap") + ->Attribute(AZ::Edit::Attributes::Visibility, &EditorReflectionProbeComponent::GetBakedCubemapVisibilitySetting) + ->EnumAttribute(BakedCubeMapQualityLevel::VeryLow, "Very Low") + ->EnumAttribute(BakedCubeMapQualityLevel::Low, "Low") + ->EnumAttribute(BakedCubeMapQualityLevel::Medium, "Medium") + ->EnumAttribute(BakedCubeMapQualityLevel::High, "High") + ->EnumAttribute(BakedCubeMapQualityLevel::VeryHigh, "Very High") ->DataElement(AZ::Edit::UIHandlers::MultiLineEdit, &EditorReflectionProbeComponent::m_bakedCubeMapRelativePath, "Baked Cubemap Path", "Baked Cubemap Path") ->Attribute(AZ::Edit::Attributes::ReadOnly, true) ->Attribute(AZ::Edit::Attributes::Visibility, &EditorReflectionProbeComponent::GetBakedCubemapVisibilitySetting) @@ -332,6 +340,12 @@ namespace AZ // clear it to force the generation of a new filename cubeMapRelativePath.clear(); } + + // if the quality level changed we need to generate a new filename + if (m_controller.m_configuration.m_bakedCubeMapQualityLevel != m_bakedCubeMapQualityLevel) + { + cubeMapRelativePath.clear(); + } } // build a new cubemap path if necessary @@ -345,7 +359,10 @@ namespace AZ AZStd::string uuidString; uuid.ToString(uuidString); - cubeMapRelativePath = "ReflectionProbes/" + entity->GetName() + "_" + uuidString + "_iblspecularcm.dds"; + // determine the filemask suffix from the cubemap quality level setting + AZStd::string fileSuffix = BakedCubeMapFileSuffixes[aznumeric_cast(m_bakedCubeMapQualityLevel)]; + + cubeMapRelativePath = "ReflectionProbes/" + entity->GetName() + "_" + uuidString + fileSuffix; // replace any invalid filename characters auto invalidCharacters = [](char letter) @@ -384,6 +401,7 @@ namespace AZ // save the relative source path in the configuration AzToolsFramework::ScopedUndoBatch undoBatch("Cubemap path changed."); m_controller.m_configuration.m_bakedCubeMapRelativePath = cubeMapRelativePath; + m_controller.m_configuration.m_bakedCubeMapQualityLevel = m_bakedCubeMapQualityLevel; SetDirty(); // update UI cubemap path display diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h index 23fd391818..bc45eae11b 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h @@ -77,6 +77,7 @@ namespace AZ // UI settings // the user can select between a baked cubemap or an authored cubemap asset bool m_useBakedCubemap = true; + BakedCubeMapQualityLevel m_bakedCubeMapQualityLevel = BakedCubeMapQualityLevel::Medium; AZStd::string m_bakedCubeMapRelativePath; Data::Asset m_bakedCubeMapAsset; Data::Asset m_authoredCubeMapAsset; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp index 9b0ff29bb8..873810c016 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp @@ -46,6 +46,7 @@ namespace AZ ->Field("InnerLength", &ReflectionProbeComponentConfig::m_innerLength) ->Field("InnerWidth", &ReflectionProbeComponentConfig::m_innerWidth) ->Field("UseBakedCubemap", &ReflectionProbeComponentConfig::m_useBakedCubemap) + ->Field("BakedCubemapQualityLevel", &ReflectionProbeComponentConfig::m_bakedCubeMapQualityLevel) ->Field("BakedCubeMapRelativePath", &ReflectionProbeComponentConfig::m_bakedCubeMapRelativePath) ->Field("BakedCubeMapAsset", &ReflectionProbeComponentConfig::m_bakedCubeMapAsset) ->Field("AuthoredCubeMapAsset", &ReflectionProbeComponentConfig::m_authoredCubeMapAsset) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h index 0a57fde882..97a7fbebb4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h @@ -24,6 +24,29 @@ namespace AZ { namespace Render { + enum class BakedCubeMapQualityLevel : uint32_t + { + VeryLow, // 64 + Low, // 128 + Medium, // 256 + High, // 512 + VeryHigh, // 1024 + + Count + }; + + static const char* BakedCubeMapFileSuffixes[] = + { + "_iblspecularcm64.dds", + "_iblspecularcm128.dds", + "_iblspecularcm256.dds", + "_iblspecularcm512.dds", + "_iblspecularcm1024.dds" + }; + + static_assert(AZ_ARRAY_SIZE(BakedCubeMapFileSuffixes) == aznumeric_cast(BakedCubeMapQualityLevel::Count), + "BakedCubeMapFileSuffixes must have the same number of entries as BakedCubeMapQualityLevel"); + class ReflectionProbeComponentConfig final : public AZ::ComponentConfig { @@ -43,6 +66,7 @@ namespace AZ bool m_showVisualization = true; bool m_useBakedCubemap = true; + BakedCubeMapQualityLevel m_bakedCubeMapQualityLevel = BakedCubeMapQualityLevel::Medium; AZStd::string m_bakedCubeMapRelativePath; Data::Asset m_bakedCubeMapAsset; Data::Asset m_authoredCubeMapAsset; From 3f9811e498efdb07e9275a3395f201b65ce8aa0f Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 18:40:22 -0700 Subject: [PATCH 439/811] [cpack_installer] fifth attempt to fix cpack selection --- scripts/build/Platform/Windows/installer_windows.cmd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build/Platform/Windows/installer_windows.cmd b/scripts/build/Platform/Windows/installer_windows.cmd index ef284290f3..73d1a3d88c 100644 --- a/scripts/build/Platform/Windows/installer_windows.cmd +++ b/scripts/build/Platform/Windows/installer_windows.cmd @@ -31,7 +31,7 @@ SET CPACK_PATH= IF "%LY_CMAKE_PATH%"=="" ( FOR /F %%i in ('where cpack') DO ( REM The cpack in chocolatey expects a number supplied with --version so it will error - %%i --version > NUL + "%%i" --version > NUL IF !ERRORLEVEL!==0 ( SET "CPACK_PATH=%%i" ) From c3df73bed8f4b052659086e69127e90ae794bb46 Mon Sep 17 00:00:00 2001 From: mnaumov Date: Wed, 2 Jun 2021 18:48:50 -0700 Subject: [PATCH 440/811] PR feedback and fixing TrackView --- .../DisplayMapperConfigurationDescriptor.cpp | 2 +- .../DisplayMapper/DisplayMapperComponentBus.h | 5 +++++ .../DisplayMapperComponentController.cpp | 20 +++++++++++++++++++ .../EditorDisplayMapperComponent.cpp | 5 ++--- 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperConfigurationDescriptor.cpp b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperConfigurationDescriptor.cpp index 0858381fc5..a064b61a1a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperConfigurationDescriptor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperConfigurationDescriptor.cpp @@ -96,7 +96,7 @@ namespace AZ ; serializeContext->Class() - ->Version(1) + ->Version(2) ->Field("Name", &DisplayMapperConfigurationDescriptor::m_name) ->Field("OperationType", &DisplayMapperConfigurationDescriptor::m_operationType) ->Field("LdrGradingLutEnabled", &DisplayMapperConfigurationDescriptor::m_ldrGradingLutEnabled) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h index 4a01f71325..448c6cd32a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/DisplayMapper/DisplayMapperComponentBus.h @@ -26,6 +26,11 @@ namespace AZ : public ComponentBus { public: + AZ_RTTI(AZ::Render::DisplayMapperComponentRequests, "{9E2E8AF5-1176-44B4-A461-E09867753349}"); + + /// Overrides the default AZ::EBusTraits handler policy to allow one listener only. + static const EBusHandlerPolicy HandlerPolicy = EBusHandlerPolicy::Single; + //! Load preconfigured preset for specific ODT mode virtual void LoadPreset(OutputDeviceTransformType preset) = 0; //! Set display mapper type diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp index 06c549f560..30c0ac8b1d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/DisplayMapperComponentController.cpp @@ -122,10 +122,14 @@ namespace AZ void DisplayMapperComponentController::Activate(EntityId entityId) { m_entityId = entityId; + + DisplayMapperComponentRequestBus::Handler::BusConnect(m_entityId); } void DisplayMapperComponentController::Deactivate() { + DisplayMapperComponentRequestBus::Handler::BusDisconnect(m_entityId); + m_postProcessInterface = nullptr; m_entityId.SetInvalid(); } @@ -186,6 +190,10 @@ namespace AZ void DisplayMapperComponentController::SetOverrideAcesParameters(bool value) { + if (m_configuration.m_acesParameterOverrides.m_overrideDefaults == value) + { + return; // prevents flickering when set via TrackView + } m_configuration.m_acesParameterOverrides.m_overrideDefaults = value; if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) { @@ -200,6 +208,10 @@ namespace AZ void DisplayMapperComponentController::SetAlterSurround(bool value) { + if (m_configuration.m_acesParameterOverrides.m_alterSurround != value) + { + return; // prevents flickering when set via TrackView + } m_configuration.m_acesParameterOverrides.m_alterSurround = value; if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) { @@ -214,6 +226,10 @@ namespace AZ void DisplayMapperComponentController::SetApplyDesaturation(bool value) { + if (m_configuration.m_acesParameterOverrides.m_applyDesaturation != value) + { + return; // prevents flickering when set via TrackView + } m_configuration.m_acesParameterOverrides.m_applyDesaturation = value; if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) { @@ -228,6 +244,10 @@ namespace AZ void DisplayMapperComponentController::SetApplyCATD60toD65(bool value) { + if (m_configuration.m_acesParameterOverrides.m_applyCATD60toD65 != value) + { + return; // prevents flickering when set via TrackView + } m_configuration.m_acesParameterOverrides.m_applyCATD60toD65 = value; if (m_configuration.m_displayMapperOperation == DisplayMapperOperationType::Aces) { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp index 4a03c6f712..8b59cfc9ea 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp @@ -10,10 +10,9 @@ * */ -#include "Atom/Feature/ACES/AcesDisplayMapperFeatureProcessor.h" - #include #include +#include namespace AZ { @@ -180,7 +179,7 @@ namespace AZ if (auto behaviorContext = azrtti_cast(context)) { - behaviorContext->Class()->RequestBus("DisplayMapperComponentRequestBus"); + behaviorContext->Class()->RequestBus("DisplayMapperComponentRequestBus"); behaviorContext->ConstantProperty("EditorDisplayMapperComponentTypeId", BehaviorConstant(Uuid(EditorDisplayMapperComponentTypeId))) ->Attribute(AZ::Script::Attributes::Module, "render") From 35fed7722305c8a3eaadb91f45836628d5d2ba33 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Wed, 2 Jun 2021 21:56:03 -0400 Subject: [PATCH 441/811] Adding CLI script for modifying project properties (LYN-3918). Updating O3de to support it. Fixing some typo errors in manifest.py and minor optimizations --- scripts/o3de.py | 7 ++- scripts/o3de/o3de/manifest.py | 12 +--- scripts/o3de/o3de/project_properties.py | 82 +++++++++++++++++++++++++ 3 files changed, 90 insertions(+), 11 deletions(-) create mode 100644 scripts/o3de/o3de/project_properties.py diff --git a/scripts/o3de.py b/scripts/o3de.py index 8d7532878c..85d49ec268 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -32,7 +32,7 @@ def add_args(parser, subparsers) -> None: # add the scripts/o3de directory to the front of the sys.path sys.path.insert(0, str(o3de_package_dir)) from o3de import engine_template, global_project, register, print_registration, get_registration, \ - enable_gem, disable_gem, sha256 + enable_gem, disable_gem, project_properties, sha256 # Remove the temporarily added path sys.path = sys.path[1:] @@ -55,7 +55,10 @@ def add_args(parser, subparsers) -> None: # remove a gem from a project disable_gem.add_args(subparsers) - + + # modify project properties + project_properties.add_args(subparsers) + # sha256 sha256.add_args(subparsers) diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index 2a7e5bba11..edcd44c525 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -573,9 +573,7 @@ def get_registered(engine_name: str = None, return engine_path elif isinstance(project_name, str): - enging_projects = get_engine_projects() - projects = json_data['projects'].copy() - projects.extend(engine_object['projects']) + projects = get_all_projects() for project_path in projects: project_path = pathlib.Path(project_path).resolve() project_json = project_path / 'project.json' @@ -605,9 +603,7 @@ def get_registered(engine_name: str = None, return gem_path elif isinstance(template_name, str): - engine_templates = get_engine_templates() - templates = json_data['templates'].copy() - templates.extend(engine_templates) + templates = get_all_templates() for template_path in templates: template_path = pathlib.Path(template_path).resolve() template_json = template_path / 'template.json' @@ -622,9 +618,7 @@ def get_registered(engine_name: str = None, return template_path elif isinstance(restricted_name, str): - engine_restricted = get_engine_restricted() - restricted = json_data['restricted'].copy() - restricted.extend(engine_restricted) + restricted = get_all_restricted() for restricted_path in restricted: restricted_path = pathlib.Path(restricted_path).resolve() restricted_json = restricted_path / 'restricted.json' diff --git a/scripts/o3de/o3de/project_properties.py b/scripts/o3de/o3de/project_properties.py new file mode 100644 index 0000000000..10153ff833 --- /dev/null +++ b/scripts/o3de/o3de/project_properties.py @@ -0,0 +1,82 @@ +import argparse +import json +import os +import pathlib +import sys +import logging + +from o3de import manifest + +logger = logging.getLogger() +logging.basicConfig() + +def get_project_props(name: str = None, path: pathlib.Path = None) -> dict: + proj_json = manifest.get_project_json_data(project_name=name, project_path=path) + if not proj_json: + logger.error('Could not retrieve project.json file') + return None + return proj_json + +def edit_project_props(proj_path, proj_name, new_origin, new_display, + new_summary, new_icon, new_tag) -> int: + proj_json = get_project_props(proj_name, proj_path) + + try: + if new_origin and 'origin' in proj_json: + proj_json['origin'] = new_origin + if new_display and 'display_name' in proj_json: + proj_json['display_name'] = new_display + if new_summary and 'summary' in proj_json: + proj_json['summary'] = new_summary + if new_icon and 'icon_path' in proj_json: + proj_json['icon_path'] = new_icon + if new_tag and 'user_tags' in proj_json: + proj_json['user_tags'].append(new_tag) + except Exception as e: + logger.error(e) + return 1 + + manifest.save_o3de_manifest(proj_json, pathlib.Path(proj_path)/'project.json') + return 0 + +def _edit_project_props(args: argparse) -> int: + return edit_project_props(args.project_path, + args.project_name, + args.project_origin, + args.project_display, + args.project_summary, + args.project_icon, + args.project_tag) + +def add_parser_args(parser): + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument('-pp', '--project-path', type=pathlib.Path, required=False, + help='The path to the project.') + group.add_argument('-pn', '--project-name', type=str, required=False, + help='The name of the project.') + group = parser.add_argument_group('properties', 'arguments for modifying individual project properties.') + group.add_argument('-po', '--project-origin', type=str, required=False, + help='Sets description or url for project origin.') + group.add_argument('-pd', '--project-display', type=str, required=False, + help='Sets the project display name.') + group.add_argument('-ps', '--project-summary', type=str, required=False, + help='Sets the summary description of the project.') + group.add_argument('-pi', '--project-icon', type=str, required=False, + help='Sets the path to the projects icon resource.') + group.add_argument('-pt', '--project-tag', type=str, required=False, + help='Adds a tag to canonical user tags.') + parser.set_defaults(func=_edit_project_props) + +def add_args(subparsers) -> None: + enable_project_props_subparser = subparsers.add_parser('edit-project-props') + add_parser_args(enable_project_props_subparser) + +def main(): + the_parser = argparse.ArgumentParser() + add_parser_args(the_parser) + the_args = the_parser.parse_args() + ret = the_args.func(the_args) if hasattr(the_args, 'func') else 1 + sys.exit(ret) + +if __name__ == "__main__": + main() \ No newline at end of file From 86234841689b7c48de57b3d7b9c3a60f129637a0 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Wed, 2 Jun 2021 19:02:42 -0700 Subject: [PATCH 442/811] Added Masked Occlusion Culling external files --- .../CompilerSpecific.inl | 98 + .../MaskedOcclusionCulling/LICENSE.txt | 181 ++ .../MaskedOcclusionCulling.cpp | 456 ++++ .../MaskedOcclusionCulling.h | 592 +++++ .../MaskedOcclusionCullingAVX2.cpp | 243 ++ .../MaskedOcclusionCullingAVX512.cpp | 309 +++ .../MaskedOcclusionCullingCommon.inl | 2053 +++++++++++++++++ .../MaskedOcclusionCulling/PackageInfo.json | 6 + 8 files changed, 3938 insertions(+) create mode 100644 Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/CompilerSpecific.inl create mode 100644 Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/LICENSE.txt create mode 100644 Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCulling.cpp create mode 100644 Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCulling.h create mode 100644 Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX2.cpp create mode 100644 Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX512.cpp create mode 100644 Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingCommon.inl create mode 100644 Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/PackageInfo.json diff --git a/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/CompilerSpecific.inl b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/CompilerSpecific.inl new file mode 100644 index 0000000000..a6203ff939 --- /dev/null +++ b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/CompilerSpecific.inl @@ -0,0 +1,98 @@ +//////////////////////////////////////////////////////////////////////////////// +// Copyright 2017 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy +// of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +//////////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Common shared include file to hide compiler/os specific functions from the rest of the code. +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#if defined(_MSC_VER) && !defined(__INTEL_COMPILER) && !defined(__clang__) + #define __MICROSOFT_COMPILER +#endif + +#if defined(_WIN32) && (defined(_MSC_VER) || defined(__INTEL_COMPILER) || defined(__clang__)) // Windows: MSVC / Intel compiler / clang + #include + #include + + #define FORCE_INLINE __forceinline + + FORCE_INLINE unsigned long find_clear_lsb(unsigned int *mask) + { + unsigned long idx; + _BitScanForward(&idx, *mask); + *mask &= *mask - 1; + return idx; + } + + FORCE_INLINE void *aligned_alloc(size_t alignment, size_t size) + { + return _aligned_malloc(size, alignment); + } + + FORCE_INLINE void aligned_free(void *ptr) + { + _aligned_free(ptr); + } + +#elif defined(__GNUG__) || defined(__clang__) // G++ or clang + #include +#if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) + #include // memalign +#else + #include // memalign +#endif + #include + #include + #include + + #define FORCE_INLINE inline + + FORCE_INLINE unsigned long find_clear_lsb(unsigned int *mask) + { + unsigned long idx; + idx = __builtin_ctzl(*mask); + *mask &= *mask - 1; + return idx; + } + + FORCE_INLINE void *aligned_alloc(size_t alignment, size_t size) + { + return memalign(alignment, size); + } + + FORCE_INLINE void aligned_free(void *ptr) + { + free(ptr); + } + + FORCE_INLINE void __cpuidex(int* cpuinfo, int function, int subfunction) + { + __cpuid_count(function, subfunction, cpuinfo[0], cpuinfo[1], cpuinfo[2], cpuinfo[3]); + } + + FORCE_INLINE unsigned long long _xgetbv(unsigned int index) + { + unsigned int eax, edx; + __asm__ __volatile__( + "xgetbv;" + : "=a" (eax), "=d"(edx) + : "c" (index) + ); + return ((unsigned long long)edx << 32) | eax; + } + +#else + #error Unsupported compiler +#endif diff --git a/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/LICENSE.txt b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/LICENSE.txt new file mode 100644 index 0000000000..f1b08a582c --- /dev/null +++ b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/LICENSE.txt @@ -0,0 +1,181 @@ + +Apache License + Version 2.0, January 2004 + + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this +License, each Contributor hereby grants to You a perpetual, worldwide, +non-exclusive, no-charge, royalty-free, irrevocable copyright license to +reproduce, prepare Derivative Works of, publicly display, publicly perform, +sublicense, and distribute the Work and such Derivative Works in Source or +Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, +each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) patent +license to make, have made, use, offer to sell, sell, import, and otherwise +transfer the Work, where such license applies only to those patent claims +licensable by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) with the Work +to which such Contribution(s) was submitted. If You institute patent litigation +against any entity (including a cross-claim or counterclaim in a lawsuit) +alleging that the Work or a Contribution incorporated within the Work +constitutes direct or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate as of the date +such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or +Derivative Works thereof in any medium, with or without modifications, and in +Source or Object form, provided that You meet the following conditions: + You must give any other recipients of the Work or Derivative Works a copy of + this License; and + + + You must cause any modified files to carry prominent notices stating that You + changed the files; and + + + You must retain, in the Source form of any Derivative Works that You + distribute, all copyright, patent, trademark, and attribution notices from the + Source form of the Work, excluding those notices that do not pertain to any + part of the Derivative Works; and + + + If the Work includes a "NOTICE" text file as part of its distribution, then + any Derivative Works that You distribute must include a readable copy of the + attribution notices contained within such NOTICE file, excluding those notices + that do not pertain to any part of the Derivative Works, in at least one of + the following places: within a NOTICE text file distributed as part of the + Derivative Works; within the Source form or documentation, if provided along + with the Derivative Works; or, within a display generated by the Derivative + Works, if and wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and do not modify the + License. You may add Your own attribution notices within Derivative Works that + You distribute, alongside or as an addendum to the NOTICE text from the Work, + provided that such additional attribution notices cannot be construed as + modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any +Contribution intentionally submitted for inclusion in the Work by You to the +Licensor shall be under the terms and conditions of this License, without any +additional terms or conditions. Notwithstanding the above, nothing herein shall +supersede or modify the terms of any separate license agreement you may have +executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, +trademarks, service marks, or product names of the Licensor, except as required +for reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in +writing, Licensor provides the Work (and each Contributor provides its +Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied, including, without limitation, any warranties +or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any risks +associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in +tort (including negligence), contract, or otherwise, unless required by +applicable law (such as deliberate and grossly negligent acts) or agreed to in +writing, shall any Contributor be liable to You for damages, including any +direct, indirect, special, incidental, or consequential damages of any character +arising as a result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, work stoppage, +computer failure or malfunction, or any and all other commercial damages or +losses), even if such Contributor has been advised of the possibility of such +damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or +Derivative Works thereof, You may choose to offer, and charge a fee for, +acceptance of support, warranty, indemnity, or other liability obligations +and/or rights consistent with this License. However, in accepting such +obligations, You may act only on Your own behalf and on Your sole +responsibility, not on behalf of any other Contributor, and only if You agree to +indemnify, defend, and hold each Contributor harmless for any liability incurred +by, or claims asserted against, such Contributor by reason of your accepting any +such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + +Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, +Version 2.0 (the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or +agreed to in writing, software distributed under the License is distributed on +an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +or implied. See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCulling.cpp b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCulling.cpp new file mode 100644 index 0000000000..2844fbde00 --- /dev/null +++ b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCulling.cpp @@ -0,0 +1,456 @@ +//////////////////////////////////////////////////////////////////////////////// +// Copyright 2017 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy +// of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +//////////////////////////////////////////////////////////////////////////////// +#include +#include +#include +#include +#include "MaskedOcclusionCulling.h" +#include "CompilerSpecific.inl" + +#if MOC_RECORDER_ENABLE +#include "FrameRecorder.h" +#endif + +#if defined(__AVX__) || defined(__AVX2__) + // For performance reasons, the MaskedOcclusionCullingAVX2/512.cpp files should be compiled with VEX encoding for SSE instructions (to avoid + // AVX-SSE transition penalties, see https://software.intel.com/en-us/articles/avoiding-avx-sse-transition-penalties). However, this file + // _must_ be compiled without VEX encoding to allow backwards compatibility. Best practice is to use lowest supported target platform + // (/arch:SSE2) as project default, and elevate only the MaskedOcclusionCullingAVX2/512.cpp files. + #error The MaskedOcclusionCulling.cpp should be compiled with lowest supported target platform, e.g. /arch:SSE2 +#endif + +static MaskedOcclusionCulling::Implementation DetectCPUFeatures(MaskedOcclusionCulling::pfnAlignedAlloc alignedAlloc, MaskedOcclusionCulling::pfnAlignedFree alignedFree) +{ + struct CpuInfo { int regs[4]; }; + + // Get regular CPUID values + int regs[4]; + __cpuidex(regs, 0, 0); + + // MOCVectorAllocator mocalloc( alignedAlloc, alignedFree ); + // std::vector> cpuId( mocalloc ), cpuIdEx( mocalloc ); + // cpuId.resize( regs[0] ); + size_t cpuIdCount = regs[0]; + CpuInfo * cpuId = (CpuInfo*)alignedAlloc( 64, sizeof(CpuInfo) * cpuIdCount ); + + for (size_t i = 0; i < cpuIdCount; ++i) + __cpuidex(cpuId[i].regs, (int)i, 0); + + // Get extended CPUID values + __cpuidex(regs, 0x80000000, 0); + + //cpuIdEx.resize(regs[0] - 0x80000000); + size_t cpuIdExCount = regs[0] - 0x80000000; + CpuInfo * cpuIdEx = (CpuInfo*)alignedAlloc( 64, sizeof( CpuInfo ) * cpuIdExCount ); + + for (size_t i = 0; i < cpuIdExCount; ++i) + __cpuidex(cpuIdEx[i].regs, 0x80000000 + (int)i, 0); + + #define TEST_BITS(A, B) (((A) & (B)) == (B)) + #define TEST_FMA_MOVE_OXSAVE (cpuIdCount >= 1 && TEST_BITS(cpuId[1].regs[2], (1 << 12) | (1 << 22) | (1 << 27))) + #define TEST_LZCNT (cpuIdExCount >= 1 && TEST_BITS(cpuIdEx[1].regs[2], 0x20)) + #define TEST_SSE41 (cpuIdCount >= 1 && TEST_BITS(cpuId[1].regs[2], (1 << 19))) + #define TEST_XMM_YMM (cpuIdCount >= 1 && TEST_BITS(_xgetbv(0), (1 << 2) | (1 << 1))) + #define TEST_OPMASK_ZMM (cpuIdCount >= 1 && TEST_BITS(_xgetbv(0), (1 << 7) | (1 << 6) | (1 << 5))) + #define TEST_BMI1_BMI2_AVX2 (cpuIdCount >= 7 && TEST_BITS(cpuId[7].regs[1], (1 << 3) | (1 << 5) | (1 << 8))) + #define TEST_AVX512_F_BW_DQ (cpuIdCount >= 7 && TEST_BITS(cpuId[7].regs[1], (1 << 16) | (1 << 17) | (1 << 30))) + + MaskedOcclusionCulling::Implementation retVal = MaskedOcclusionCulling::SSE2; + if (TEST_FMA_MOVE_OXSAVE && TEST_LZCNT && TEST_SSE41) + { + if (TEST_XMM_YMM && TEST_OPMASK_ZMM && TEST_BMI1_BMI2_AVX2 && TEST_AVX512_F_BW_DQ) + retVal = MaskedOcclusionCulling::AVX512; + else if (TEST_XMM_YMM && TEST_BMI1_BMI2_AVX2) + retVal = MaskedOcclusionCulling::AVX2; + } + else if (TEST_SSE41) + retVal = MaskedOcclusionCulling::SSE41; + alignedFree( cpuId ); + alignedFree( cpuIdEx ); + return retVal; +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Utility functions (not directly related to the algorithm/rasterizer) +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +void MaskedOcclusionCulling::TransformVertices(const float *mtx, const float *inVtx, float *xfVtx, unsigned int nVtx, const VertexLayout &vtxLayout) +{ + // This function pretty slow, about 10-20% slower than if the vertices are stored in aligned SOA form. + if (nVtx == 0) + return; + + // Load matrix and swizzle out the z component. For post-multiplication (OGL), the matrix is assumed to be column + // major, with one column per SSE register. For pre-multiplication (DX), the matrix is assumed to be row major. + __m128 mtxCol0 = _mm_loadu_ps(mtx); + __m128 mtxCol1 = _mm_loadu_ps(mtx + 4); + __m128 mtxCol2 = _mm_loadu_ps(mtx + 8); + __m128 mtxCol3 = _mm_loadu_ps(mtx + 12); + + int stride = vtxLayout.mStride; + const char *vPtr = (const char *)inVtx; + float *outPtr = xfVtx; + + // Iterate through all vertices and transform + for (unsigned int vtx = 0; vtx < nVtx; ++vtx) + { + __m128 xVal = _mm_load1_ps((float*)(vPtr)); + __m128 yVal = _mm_load1_ps((float*)(vPtr + vtxLayout.mOffsetY)); + __m128 zVal = _mm_load1_ps((float*)(vPtr + vtxLayout.mOffsetZ)); + + __m128 xform = _mm_add_ps(_mm_mul_ps(mtxCol0, xVal), _mm_add_ps(_mm_mul_ps(mtxCol1, yVal), _mm_add_ps(_mm_mul_ps(mtxCol2, zVal), mtxCol3))); + _mm_storeu_ps(outPtr, xform); + vPtr += stride; + outPtr += 4; + } +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Typedefs +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef MaskedOcclusionCulling::pfnAlignedAlloc pfnAlignedAlloc; +typedef MaskedOcclusionCulling::pfnAlignedFree pfnAlignedFree; +typedef MaskedOcclusionCulling::VertexLayout VertexLayout; + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Common SSE2/SSE4.1 defines +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#define SIMD_LANES 4 +#define TILE_HEIGHT_SHIFT 2 + +#define SIMD_LANE_IDX _mm_setr_epi32(0, 1, 2, 3) + +#define SIMD_SUB_TILE_COL_OFFSET _mm_setr_epi32(0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3) +#define SIMD_SUB_TILE_ROW_OFFSET _mm_setzero_si128() +#define SIMD_SUB_TILE_COL_OFFSET_F _mm_setr_ps(0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3) +#define SIMD_SUB_TILE_ROW_OFFSET_F _mm_setzero_ps() + +#define SIMD_LANE_YCOORD_I _mm_setr_epi32(128, 384, 640, 896) +#define SIMD_LANE_YCOORD_F _mm_setr_ps(128.0f, 384.0f, 640.0f, 896.0f) + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Common SSE2/SSE4.1 functions +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef __m128 __mw; +typedef __m128i __mwi; + +#define _mmw_set1_ps _mm_set1_ps +#define _mmw_setzero_ps _mm_setzero_ps +#define _mmw_and_ps _mm_and_ps +#define _mmw_or_ps _mm_or_ps +#define _mmw_xor_ps _mm_xor_ps +#define _mmw_not_ps(a) _mm_xor_ps((a), _mm_castsi128_ps(_mm_set1_epi32(~0))) +#define _mmw_andnot_ps _mm_andnot_ps +#define _mmw_neg_ps(a) _mm_xor_ps((a), _mm_set1_ps(-0.0f)) +#define _mmw_abs_ps(a) _mm_and_ps((a), _mm_castsi128_ps(_mm_set1_epi32(0x7FFFFFFF))) +#define _mmw_add_ps _mm_add_ps +#define _mmw_sub_ps _mm_sub_ps +#define _mmw_mul_ps _mm_mul_ps +#define _mmw_div_ps _mm_div_ps +#define _mmw_min_ps _mm_min_ps +#define _mmw_max_ps _mm_max_ps +#define _mmw_movemask_ps _mm_movemask_ps +#define _mmw_cmpge_ps(a,b) _mm_cmpge_ps(a, b) +#define _mmw_cmpgt_ps(a,b) _mm_cmpgt_ps(a, b) +#define _mmw_cmpeq_ps(a,b) _mm_cmpeq_ps(a, b) +#define _mmw_fmadd_ps(a,b,c) _mm_add_ps(_mm_mul_ps(a,b), c) +#define _mmw_fmsub_ps(a,b,c) _mm_sub_ps(_mm_mul_ps(a,b), c) +#define _mmw_shuffle_ps _mm_shuffle_ps +#define _mmw_insertf32x4_ps(a,b,c) (b) +#define _mmw_cvtepi32_ps _mm_cvtepi32_ps +#define _mmw_blendv_epi32(a,b,c) simd_cast<__mwi>(_mmw_blendv_ps(simd_cast<__mw>(a), simd_cast<__mw>(b), simd_cast<__mw>(c))) + +#define _mmw_set1_epi32 _mm_set1_epi32 +#define _mmw_setzero_epi32 _mm_setzero_si128 +#define _mmw_and_epi32 _mm_and_si128 +#define _mmw_or_epi32 _mm_or_si128 +#define _mmw_xor_epi32 _mm_xor_si128 +#define _mmw_not_epi32(a) _mm_xor_si128((a), _mm_set1_epi32(~0)) +#define _mmw_andnot_epi32 _mm_andnot_si128 +#define _mmw_neg_epi32(a) _mm_sub_epi32(_mm_set1_epi32(0), (a)) +#define _mmw_add_epi32 _mm_add_epi32 +#define _mmw_sub_epi32 _mm_sub_epi32 +#define _mmw_subs_epu16 _mm_subs_epu16 +#define _mmw_cmpeq_epi32 _mm_cmpeq_epi32 +#define _mmw_cmpgt_epi32 _mm_cmpgt_epi32 +#define _mmw_srai_epi32 _mm_srai_epi32 +#define _mmw_srli_epi32 _mm_srli_epi32 +#define _mmw_slli_epi32 _mm_slli_epi32 +#define _mmw_cvtps_epi32 _mm_cvtps_epi32 +#define _mmw_cvttps_epi32 _mm_cvttps_epi32 + +#define _mmx_fmadd_ps _mmw_fmadd_ps +#define _mmx_max_epi32 _mmw_max_epi32 +#define _mmx_min_epi32 _mmw_min_epi32 + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// SIMD casting functions +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +template FORCE_INLINE T simd_cast(Y A); +template<> FORCE_INLINE __m128 simd_cast<__m128>(float A) { return _mm_set1_ps(A); } +template<> FORCE_INLINE __m128 simd_cast<__m128>(__m128i A) { return _mm_castsi128_ps(A); } +template<> FORCE_INLINE __m128 simd_cast<__m128>(__m128 A) { return A; } +template<> FORCE_INLINE __m128i simd_cast<__m128i>(int A) { return _mm_set1_epi32(A); } +template<> FORCE_INLINE __m128i simd_cast<__m128i>(__m128 A) { return _mm_castps_si128(A); } +template<> FORCE_INLINE __m128i simd_cast<__m128i>(__m128i A) { return A; } + +#define MAKE_ACCESSOR(name, simd_type, base_type, is_const, elements) \ + FORCE_INLINE is_const base_type * name(is_const simd_type &a) { \ + union accessor { simd_type m_native; base_type m_array[elements]; }; \ + is_const accessor *acs = reinterpret_cast(&a); \ + return acs->m_array; \ + } + +MAKE_ACCESSOR(simd_f32, __m128, float, , 4) +MAKE_ACCESSOR(simd_f32, __m128, float, const, 4) +MAKE_ACCESSOR(simd_i32, __m128i, int, , 4) +MAKE_ACCESSOR(simd_i32, __m128i, int, const, 4) + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Specialized SSE input assembly function for general vertex gather +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +FORCE_INLINE void GatherVertices(__m128 *vtxX, __m128 *vtxY, __m128 *vtxW, const float *inVtx, const unsigned int *inTrisPtr, int numLanes, const VertexLayout &vtxLayout) +{ + for (int lane = 0; lane < numLanes; lane++) + { + for (int i = 0; i < 3; i++) + { + char *vPtrX = (char *)inVtx + inTrisPtr[lane * 3 + i] * vtxLayout.mStride; + char *vPtrY = vPtrX + vtxLayout.mOffsetY; + char *vPtrW = vPtrX + vtxLayout.mOffsetW; + + simd_f32(vtxX[i])[lane] = *((float*)vPtrX); + simd_f32(vtxY[i])[lane] = *((float*)vPtrY); + simd_f32(vtxW[i])[lane] = *((float*)vPtrW); + } + } +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// SSE4.1 version +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +namespace MaskedOcclusionCullingSSE41 +{ + FORCE_INLINE __m128i _mmw_mullo_epi32(const __m128i &a, const __m128i &b) { return _mm_mullo_epi32(a, b); } + FORCE_INLINE __m128i _mmw_min_epi32(const __m128i &a, const __m128i &b) { return _mm_min_epi32(a, b); } + FORCE_INLINE __m128i _mmw_max_epi32(const __m128i &a, const __m128i &b) { return _mm_max_epi32(a, b); } + FORCE_INLINE __m128i _mmw_abs_epi32(const __m128i &a) { return _mm_abs_epi32(a); } + FORCE_INLINE __m128 _mmw_blendv_ps(const __m128 &a, const __m128 &b, const __m128 &c) { return _mm_blendv_ps(a, b, c); } + FORCE_INLINE int _mmw_testz_epi32(const __m128i &a, const __m128i &b) { return _mm_testz_si128(a, b); } + FORCE_INLINE __m128 _mmx_dp4_ps(const __m128 &a, const __m128 &b) { return _mm_dp_ps(a, b, 0xFF); } + FORCE_INLINE __m128 _mmw_floor_ps(const __m128 &a) { return _mm_round_ps(a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC); } + FORCE_INLINE __m128 _mmw_ceil_ps(const __m128 &a) { return _mm_round_ps(a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC); } + FORCE_INLINE __m128i _mmw_transpose_epi8(const __m128i &a) + { + const __m128i shuff = _mm_setr_epi8(0x0, 0x4, 0x8, 0xC, 0x1, 0x5, 0x9, 0xD, 0x2, 0x6, 0xA, 0xE, 0x3, 0x7, 0xB, 0xF); + return _mm_shuffle_epi8(a, shuff); + } + FORCE_INLINE __m128i _mmw_sllv_ones(const __m128i &ishift) + { + __m128i shift = _mm_min_epi32(ishift, _mm_set1_epi32(32)); + + // Uses lookup tables and _mm_shuffle_epi8 to perform _mm_sllv_epi32(~0, shift) + const __m128i byteShiftLUT = _mm_setr_epi8((char)0xFF, (char)0xFE, (char)0xFC, (char)0xF8, (char)0xF0, (char)0xE0, (char)0xC0, (char)0x80, 0, 0, 0, 0, 0, 0, 0, 0); + const __m128i byteShiftOffset = _mm_setr_epi8(0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24); + const __m128i byteShiftShuffle = _mm_setr_epi8(0x0, 0x0, 0x0, 0x0, 0x4, 0x4, 0x4, 0x4, 0x8, 0x8, 0x8, 0x8, 0xC, 0xC, 0xC, 0xC); + + __m128i byteShift = _mm_shuffle_epi8(shift, byteShiftShuffle); + byteShift = _mm_min_epi8(_mm_subs_epu8(byteShift, byteShiftOffset), _mm_set1_epi8(8)); + __m128i retMask = _mm_shuffle_epi8(byteShiftLUT, byteShift); + + return retMask; + } + + static MaskedOcclusionCulling::Implementation gInstructionSet = MaskedOcclusionCulling::SSE41; + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Include common algorithm implementation (general, SIMD independent code) + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + #include "MaskedOcclusionCullingCommon.inl" + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Utility function to create a new object using the allocator callbacks + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + MaskedOcclusionCulling *CreateMaskedOcclusionCulling(pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree) + { + MaskedOcclusionCullingPrivate *object = (MaskedOcclusionCullingPrivate *)alignedAlloc(64, sizeof(MaskedOcclusionCullingPrivate)); + new (object) MaskedOcclusionCullingPrivate(alignedAlloc, alignedFree); + return object; + } +}; + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// SSE2 version +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +namespace MaskedOcclusionCullingSSE2 +{ + FORCE_INLINE __m128i _mmw_mullo_epi32(const __m128i &a, const __m128i &b) + { + // Do products for even / odd lanes & merge the result + __m128i even = _mm_and_si128(_mm_mul_epu32(a, b), _mm_setr_epi32(~0, 0, ~0, 0)); + __m128i odd = _mm_slli_epi64(_mm_mul_epu32(_mm_srli_epi64(a, 32), _mm_srli_epi64(b, 32)), 32); + return _mm_or_si128(even, odd); + } + FORCE_INLINE __m128i _mmw_min_epi32(const __m128i &a, const __m128i &b) + { + __m128i cond = _mm_cmpgt_epi32(a, b); + return _mm_or_si128(_mm_andnot_si128(cond, a), _mm_and_si128(cond, b)); + } + FORCE_INLINE __m128i _mmw_max_epi32(const __m128i &a, const __m128i &b) + { + __m128i cond = _mm_cmpgt_epi32(b, a); + return _mm_or_si128(_mm_andnot_si128(cond, a), _mm_and_si128(cond, b)); + } + FORCE_INLINE __m128i _mmw_abs_epi32(const __m128i &a) + { + __m128i mask = _mm_cmplt_epi32(a, _mm_setzero_si128()); + return _mm_add_epi32(_mm_xor_si128(a, mask), _mm_srli_epi32(mask, 31)); + } + FORCE_INLINE int _mmw_testz_epi32(const __m128i &a, const __m128i &b) + { + return _mm_movemask_epi8(_mm_cmpeq_epi8(_mm_and_si128(a, b), _mm_setzero_si128())) == 0xFFFF; + } + FORCE_INLINE __m128 _mmw_blendv_ps(const __m128 &a, const __m128 &b, const __m128 &c) + { + __m128 cond = _mm_castsi128_ps(_mm_srai_epi32(_mm_castps_si128(c), 31)); + return _mm_or_ps(_mm_andnot_ps(cond, a), _mm_and_ps(cond, b)); + } + FORCE_INLINE __m128 _mmx_dp4_ps(const __m128 &a, const __m128 &b) + { + // Product and two shuffle/adds pairs (similar to hadd_ps) + __m128 prod = _mm_mul_ps(a, b); + __m128 dp = _mm_add_ps(prod, _mm_shuffle_ps(prod, prod, _MM_SHUFFLE(2, 3, 0, 1))); + dp = _mm_add_ps(dp, _mm_shuffle_ps(dp, dp, _MM_SHUFFLE(0, 1, 2, 3))); + return dp; + } + FORCE_INLINE __m128 _mmw_floor_ps(const __m128 &a) + { + int originalMode = _MM_GET_ROUNDING_MODE(); + _MM_SET_ROUNDING_MODE(_MM_ROUND_DOWN); + __m128 rounded = _mm_cvtepi32_ps(_mm_cvtps_epi32(a)); + _MM_SET_ROUNDING_MODE(originalMode); + return rounded; + } + FORCE_INLINE __m128 _mmw_ceil_ps(const __m128 &a) + { + int originalMode = _MM_GET_ROUNDING_MODE(); + _MM_SET_ROUNDING_MODE(_MM_ROUND_UP); + __m128 rounded = _mm_cvtepi32_ps(_mm_cvtps_epi32(a)); + _MM_SET_ROUNDING_MODE(originalMode); + return rounded; + } + FORCE_INLINE __m128i _mmw_transpose_epi8(const __m128i &a) + { + // Perform transpose through two 16->8 bit pack and byte shifts + __m128i res = a; + const __m128i mask = _mm_setr_epi8(~0, 0, ~0, 0, ~0, 0, ~0, 0, ~0, 0, ~0, 0, ~0, 0, ~0, 0); + res = _mm_packus_epi16(_mm_and_si128(res, mask), _mm_srli_epi16(res, 8)); + res = _mm_packus_epi16(_mm_and_si128(res, mask), _mm_srli_epi16(res, 8)); + return res; + } + FORCE_INLINE __m128i _mmw_sllv_ones(const __m128i &ishift) + { + __m128i shift = _mmw_min_epi32(ishift, _mm_set1_epi32(32)); + + // Uses scalar approach to perform _mm_sllv_epi32(~0, shift) + static const unsigned int maskLUT[33] = { + ~0U << 0, ~0U << 1, ~0U << 2 , ~0U << 3, ~0U << 4, ~0U << 5, ~0U << 6 , ~0U << 7, ~0U << 8, ~0U << 9, ~0U << 10 , ~0U << 11, ~0U << 12, ~0U << 13, ~0U << 14 , ~0U << 15, + ~0U << 16, ~0U << 17, ~0U << 18 , ~0U << 19, ~0U << 20, ~0U << 21, ~0U << 22 , ~0U << 23, ~0U << 24, ~0U << 25, ~0U << 26 , ~0U << 27, ~0U << 28, ~0U << 29, ~0U << 30 , ~0U << 31, + 0U }; + + __m128i retMask; + simd_i32(retMask)[0] = (int)maskLUT[simd_i32(shift)[0]]; + simd_i32(retMask)[1] = (int)maskLUT[simd_i32(shift)[1]]; + simd_i32(retMask)[2] = (int)maskLUT[simd_i32(shift)[2]]; + simd_i32(retMask)[3] = (int)maskLUT[simd_i32(shift)[3]]; + return retMask; + } + + static MaskedOcclusionCulling::Implementation gInstructionSet = MaskedOcclusionCulling::SSE2; + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Include common algorithm implementation (general, SIMD independent code) + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + #include "MaskedOcclusionCullingCommon.inl" + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Utility function to create a new object using the allocator callbacks + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + MaskedOcclusionCulling *CreateMaskedOcclusionCulling(pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree) + { + MaskedOcclusionCullingPrivate *object = (MaskedOcclusionCullingPrivate *)alignedAlloc(64, sizeof(MaskedOcclusionCullingPrivate)); + new (object) MaskedOcclusionCullingPrivate(alignedAlloc, alignedFree); + return object; + } +}; + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Object construction and allocation +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +namespace MaskedOcclusionCullingAVX512 +{ + extern MaskedOcclusionCulling *CreateMaskedOcclusionCulling(pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree); +} + +namespace MaskedOcclusionCullingAVX2 +{ + extern MaskedOcclusionCulling *CreateMaskedOcclusionCulling(pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree); +} + +MaskedOcclusionCulling *MaskedOcclusionCulling::Create(Implementation RequestedSIMD) +{ + return Create(RequestedSIMD, aligned_alloc, aligned_free); +} + +MaskedOcclusionCulling *MaskedOcclusionCulling::Create(Implementation RequestedSIMD, pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree) +{ + MaskedOcclusionCulling *object = nullptr; + + MaskedOcclusionCulling::Implementation impl = DetectCPUFeatures(alignedAlloc, alignedFree); + + if (RequestedSIMD < impl) + impl = RequestedSIMD; + + // Return best supported version + if (object == nullptr && impl >= AVX512) + object = MaskedOcclusionCullingAVX512::CreateMaskedOcclusionCulling(alignedAlloc, alignedFree); // Use AVX512 version + if (object == nullptr && impl >= AVX2) + object = MaskedOcclusionCullingAVX2::CreateMaskedOcclusionCulling(alignedAlloc, alignedFree); // Use AVX2 version + if (object == nullptr && impl >= SSE41) + object = MaskedOcclusionCullingSSE41::CreateMaskedOcclusionCulling(alignedAlloc, alignedFree); // Use SSE4.1 version + if (object == nullptr) + object = MaskedOcclusionCullingSSE2::CreateMaskedOcclusionCulling(alignedAlloc, alignedFree); // Use SSE2 (slow) version + + return object; +} + +void MaskedOcclusionCulling::Destroy(MaskedOcclusionCulling *moc) +{ + pfnAlignedFree alignedFreeCallback = moc->mAlignedFreeCallback; + moc->~MaskedOcclusionCulling(); + alignedFreeCallback(moc); +} diff --git a/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCulling.h b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCulling.h new file mode 100644 index 0000000000..4ace525887 --- /dev/null +++ b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCulling.h @@ -0,0 +1,592 @@ +//////////////////////////////////////////////////////////////////////////////// +// Copyright 2017 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy +// of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +//////////////////////////////////////////////////////////////////////////////// +#pragma once + +/*! + * \file MaskedOcclusionCulling.h + * \brief Masked Occlusion Culling + * + * General information + * - Input to all API functions are (x,y,w) clip-space coordinates (x positive left, y positive up, w positive away from camera). + * We entirely skip the z component and instead compute it as 1 / w, see next bullet. For TestRect the input is NDC (x/w, y/w). + * - We use a simple z = 1 / w transform, which is a bit faster than OGL/DX depth transforms. Thus, depth is REVERSED and z = 0 at + * the far plane and z = inf at w = 0. We also have to use a GREATER depth function, which explains why all the conservative + * tests will be reversed compared to what you might be used to (for example zMaxTri >= zMinBuffer is a visibility test) + * - We support different layouts for vertex data (basic AoS and SoA), but note that it's beneficial to store the position data + * as tightly in memory as possible to reduce cache misses. Big strides are bad, so it's beneficial to keep position as a separate + * stream (rather than bundled with attributes) or to keep a copy of the position data for the occlusion culling system. + * - The resolution width must be a multiple of 8 and height a multiple of 4. + * - The hierarchical Z buffer is stored OpenGL-style with the y axis pointing up. This includes the scissor box. + * - This code is only tested with Visual Studio 2015, but should hopefully be easy to port to other compilers. + */ + + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Defines used to configure the implementation +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef QUICK_MASK +/*! + * Configure the algorithm used for updating and merging hierarchical z buffer entries. If QUICK_MASK + * is defined to 1, use the algorithm from the paper "Masked Software Occlusion Culling", which has good + * balance between performance and low leakage. If QUICK_MASK is defined to 0, use the algorithm from + * "Masked Depth Culling for Graphics Hardware" which has less leakage, but also lower performance. + */ +#define QUICK_MASK 1 + +#endif + +#ifndef USE_D3D +/*! + * Configures the library for use with Direct3D (default) or OpenGL rendering. This changes whether the + * screen space Y axis points downwards (D3D) or upwards (OGL), and is primarily important in combination + * with the PRECISE_COVERAGE define, where this is important to ensure correct rounding and tie-breaker + * behaviour. It also affects the ScissorRect screen space coordinates. + */ +#define USE_D3D 1 + +#endif + +#ifndef PRECISE_COVERAGE +/*! + * Define PRECISE_COVERAGE to 1 to more closely match GPU rasterization rules. The increased precision comes + * at a cost of slightly lower performance. + */ +#define PRECISE_COVERAGE 1 + +#endif + +#ifndef USE_AVX512 +/*! + * Define USE_AVX512 to 1 to enable experimental AVX-512 support. It's currently mostly untested and only + * validated on simple examples using Intel SDE. Older compilers may not support AVX-512 intrinsics. + */ +#define USE_AVX512 0 + +#endif + +#ifndef CLIPPING_PRESERVES_ORDER +/*! + * Define CLIPPING_PRESERVES_ORDER to 1 to prevent clipping from reordering triangle rasterization + * order; This comes at a cost (approx 3-4%) but removes one source of temporal frame-to-frame instability. + */ +#define CLIPPING_PRESERVES_ORDER 1 + +#endif + +#ifndef ENABLE_STATS +/*! + * Define ENABLE_STATS to 1 to gather various statistics during occlusion culling. Can be used for profiling + * and debugging. Note that enabling this function will reduce performance significantly. + */ +#define ENABLE_STATS 0 + +#endif + +#ifndef MOC_RECORDER_ENABLE +/*! + * Define MOC_RECORDER_ENABLE to 1 to enable frame recorder (see FrameRecorder.h/cpp for details) + */ +#define MOC_RECORDER_ENABLE 0 + +#endif + +#if MOC_RECORDER_ENABLE +#ifndef MOC_RECORDER_ENABLE_PLAYBACK +/*! + * Define MOC_RECORDER_ENABLE_PLAYBACK to 1 to enable compilation of the playback code (not needed + for recording) + */ +#define MOC_RECORDER_ENABLE_PLAYBACK 0 +#endif +#endif + + +#if MOC_RECORDER_ENABLE + +#include + +class FrameRecorder; + +#endif // #if MOC_RECORDER_ENABLE + + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Masked occlusion culling class +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class MaskedOcclusionCulling +{ +public: + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Memory management callback functions + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + typedef void *(*pfnAlignedAlloc)(size_t alignment, size_t size); + typedef void (*pfnAlignedFree) (void *ptr); + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Enums + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + enum Implementation + { + SSE2 = 0, + SSE41 = 1, + AVX2 = 2, + AVX512 = 3 + }; + + enum BackfaceWinding + { + BACKFACE_NONE = 0, + BACKFACE_CW = 1, + BACKFACE_CCW = 2, + }; + + enum CullingResult + { + VISIBLE = 0x0, + OCCLUDED = 0x1, + VIEW_CULLED = 0x3 + }; + + enum ClipPlanes + { + CLIP_PLANE_NONE = 0x00, + CLIP_PLANE_NEAR = 0x01, + CLIP_PLANE_LEFT = 0x02, + CLIP_PLANE_RIGHT = 0x04, + CLIP_PLANE_BOTTOM = 0x08, + CLIP_PLANE_TOP = 0x10, + CLIP_PLANE_SIDES = (CLIP_PLANE_LEFT | CLIP_PLANE_RIGHT | CLIP_PLANE_BOTTOM | CLIP_PLANE_TOP), + CLIP_PLANE_ALL = (CLIP_PLANE_LEFT | CLIP_PLANE_RIGHT | CLIP_PLANE_BOTTOM | CLIP_PLANE_TOP | CLIP_PLANE_NEAR) + }; + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Structs + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /*! + * Used to specify custom vertex layout. Memory offsets to y and z coordinates are set through + * mOffsetY and mOffsetW, and vertex stride is given by mStride. It's possible to configure both + * AoS and SoA layouts. Note that large strides may cause more cache misses and decrease + * performance. It is advisable to store position data as compactly in memory as possible. + */ + struct VertexLayout + { + VertexLayout() {} + VertexLayout(int stride, int offsetY, int offsetZW) : + mStride(stride), mOffsetY(offsetY), mOffsetW(offsetZW) {} + + int mStride; //!< byte stride between vertices + int mOffsetY; //!< byte offset from X to Y coordinate + union { + int mOffsetZ; //!< byte offset from X to Z coordinate + int mOffsetW; //!< byte offset from X to W coordinate + }; + }; + + /*! + * Used to control scissoring during rasterization. Note that we only provide coarse scissor support. + * The scissor box x coordinates must be a multiple of 32, and the y coordinates a multiple of 8. + * Scissoring is mainly meant as a means of enabling binning (sort middle) rasterizers in case + * application developers want to use that approach for multithreading. + */ + struct ScissorRect + { + ScissorRect() {} + ScissorRect(int minX, int minY, int maxX, int maxY) : + mMinX(minX), mMinY(minY), mMaxX(maxX), mMaxY(maxY) {} + + int mMinX; //!< Screen space X coordinate for left side of scissor rect, inclusive and must be a multiple of 32 + int mMinY; //!< Screen space Y coordinate for bottom side of scissor rect, inclusive and must be a multiple of 8 + int mMaxX; //!< Screen space X coordinate for right side of scissor rect, non inclusive and must be a multiple of 32 + int mMaxY; //!< Screen space Y coordinate for top side of scissor rect, non inclusive and must be a multiple of 8 + }; + + /*! + * Used to specify storage area for a binlist, containing triangles. This struct is used for binning + * and multithreading. The host application is responsible for allocating memory for the binlists. + */ + struct TriList + { + unsigned int mNumTriangles; //!< Maximum number of triangles that may be stored in mPtr + unsigned int mTriIdx; //!< Index of next triangle to be written, clear before calling BinTriangles to start from the beginning of the list + float *mPtr; //!< Scratchpad buffer allocated by the host application + }; + + /*! + * Statistics that can be gathered during occluder rendering and visibility to aid debugging + * and profiling. Must be enabled by changing the ENABLE_STATS define. + */ + struct OcclusionCullingStatistics + { + struct + { + long long mNumProcessedTriangles; //!< Number of occluder triangles processed in total + long long mNumRasterizedTriangles; //!< Number of occluder triangles passing view frustum and backface culling + long long mNumTilesTraversed; //!< Number of tiles traversed by the rasterizer + long long mNumTilesUpdated; //!< Number of tiles where the hierarchical z buffer was updated + long long mNumTilesMerged; //!< Number of tiles where the hierarchical z buffer was updated + } mOccluders; + + struct + { + long long mNumProcessedRectangles; //!< Number of rects processed (TestRect()) + long long mNumProcessedTriangles; //!< Number of ocludee triangles processed (TestTriangles()) + long long mNumRasterizedTriangles; //!< Number of ocludee triangle passing view frustum and backface culling + long long mNumTilesTraversed; //!< Number of tiles traversed by triangle & rect rasterizers + } mOccludees; + }; + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Functions + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /*! + * \brief Creates a new object with default state, no z buffer attached/allocated. + */ + static MaskedOcclusionCulling *Create(Implementation RequestedSIMD = AVX512); + + /*! + * \brief Creates a new object with default state, no z buffer attached/allocated. + * \param alignedAlloc Pointer to a callback function used when allocating memory + * \param alignedFree Pointer to a callback function used when freeing memory + */ + static MaskedOcclusionCulling *Create(Implementation RequestedSIMD, pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree); + + /*! + * \brief Destroys an object and frees the z buffer memory. Note that you cannot + * use the delete operator, and should rather use this function to free up memory. + */ + static void Destroy(MaskedOcclusionCulling *moc); + + /*! + * \brief Sets the resolution of the hierarchical depth buffer. This function will + * re-allocate the current depth buffer (if present). The contents of the + * buffer is undefined until ClearBuffer() is called. + * + * \param witdh The width of the buffer in pixels, must be a multiple of 8 + * \param height The height of the buffer in pixels, must be a multiple of 4 + */ + virtual void SetResolution(unsigned int width, unsigned int height) = 0; + + /*! + * \brief Gets the resolution of the hierarchical depth buffer. + * + * \param witdh Output: The width of the buffer in pixels + * \param height Output: The height of the buffer in pixels + */ + virtual void GetResolution(unsigned int &width, unsigned int &height) const = 0; + + /*! + * \brief Returns the tile size for the current implementation. + * + * \param nBinsW Number of vertical bins, the screen is divided into nBinsW x nBinsH + * rectangular bins. + * \param nBinsH Number of horizontal bins, the screen is divided into nBinsW x nBinsH + * rectangular bins. + * \param outBinWidth Output: The width of the single bin in pixels (except for the + * rightmost bin width, which is extended to resolution width) + * \param outBinHeight Output: The height of the single bin in pixels (except for the + * bottommost bin height, which is extended to resolution height) + */ + virtual void ComputeBinWidthHeight(unsigned int nBinsW, unsigned int nBinsH, unsigned int & outBinWidth, unsigned int & outBinHeight) = 0; + + /*! + * \brief Sets the distance for the near clipping plane. Default is nearDist = 0. + * + * \param nearDist The distance to the near clipping plane, given as clip space w + */ + virtual void SetNearClipPlane(float nearDist) = 0; + + /*! + * \brief Gets the distance for the near clipping plane. + */ + virtual float GetNearClipPlane() const = 0; + + /*! + * \brief Clears the hierarchical depth buffer. + */ + virtual void ClearBuffer() = 0; + + /*! + * \brief Merge a second hierarchical depth buffer into the main buffer. + */ + virtual void MergeBuffer(MaskedOcclusionCulling* BufferB) = 0; + + /*! + * \brief Renders a mesh of occluder triangles and updates the hierarchical z buffer + * with conservative depth values. + * + * This function is optimized for vertex layouts with stride 16 and y and w + * offsets of 4 and 12 bytes, respectively. + * + * \param inVtx Pointer to an array of input vertices, should point to the x component + * of the first vertex. The input vertices are given as (x,y,w) coordinates + * in clip space. The memory layout can be changed using vtxLayout. + * \param inTris Pointer to an array of vertex indices. Each triangle is created + * from three indices consecutively fetched from the array. + * \param nTris The number of triangles to render (inTris must contain atleast 3*nTris + * entries) + * \param modelToClipMatrix all vertices will be transformed by this matrix before + * performing projection. If nullptr is passed the transform step will be skipped + * \param bfWinding Sets triangle winding order to consider backfacing, must be one one + * of (BACKFACE_NONE, BACKFACE_CW and BACKFACE_CCW). Back-facing triangles are culled + * and will not be rasterized. You may use BACKFACE_NONE to disable culling for + * double sided geometry + * \param clipPlaneMask A mask indicating which clip planes should be considered by the + * triangle clipper. Can be used as an optimization if your application can + * determine (for example during culling) that a group of triangles does not + * intersect a certain frustum plane. However, setting an incorrect mask may + * cause out of bounds memory accesses. + * \param vtxLayout A struct specifying the vertex layout (see struct for detailed + * description). For best performance, it is advisable to store position data + * as compactly in memory as possible. + * \return Will return VIEW_CULLED if all triangles are either outside the frustum or + * backface culled, returns VISIBLE otherwise. + */ + virtual CullingResult RenderTriangles(const float *inVtx, const unsigned int *inTris, int nTris, const float *modelToClipMatrix = nullptr, BackfaceWinding bfWinding = BACKFACE_CW, ClipPlanes clipPlaneMask = CLIP_PLANE_ALL, const VertexLayout &vtxLayout = VertexLayout(16, 4, 12)) = 0; + + /*! + * \brief Occlusion query for a rectangle with a given depth. The rectangle is given + * in normalized device coordinates where (x,y) coordinates between [-1,1] map + * to the visible screen area. The query uses a GREATER_EQUAL (reversed) depth + * test meaning that depth values equal to the contents of the depth buffer are + * counted as visible. + * + * \param xmin NDC coordinate of the left side of the rectangle. + * \param ymin NDC coordinate of the bottom side of the rectangle. + * \param xmax NDC coordinate of the right side of the rectangle. + * \param ymax NDC coordinate of the top side of the rectangle. + * \param ymax NDC coordinate of the top side of the rectangle. + * \param wmin Clip space W coordinate for the rectangle. + * \return The query will return VISIBLE if the rectangle may be visible, OCCLUDED + * if the rectangle is occluded by a previously rendered object, or VIEW_CULLED + * if the rectangle is outside the view frustum. + */ + virtual CullingResult TestRect(float xmin, float ymin, float xmax, float ymax, float wmin) const = 0; + + /*! + * \brief This function is similar to RenderTriangles(), but performs an occlusion + * query instead and does not update the hierarchical z buffer. The query uses + * a GREATER_EQUAL (reversed) depth test meaning that depth values equal to the + * contents of the depth buffer are counted as visible. + * + * This function is optimized for vertex layouts with stride 16 and y and w + * offsets of 4 and 12 bytes, respectively. + * + * \param inVtx Pointer to an array of input vertices, should point to the x component + * of the first vertex. The input vertices are given as (x,y,w) coordinates + * in clip space. The memory layout can be changed using vtxLayout. + * \param inTris Pointer to an array of triangle indices. Each triangle is created + * from three indices consecutively fetched from the array. + * \param nTris The number of triangles to render (inTris must contain atleast 3*nTris + * entries) + * \param modelToClipMatrix all vertices will be transformed by this matrix before + * performing projection. If nullptr is passed the transform step will be skipped + * \param bfWinding Sets triangle winding order to consider backfacing, must be one one + * of (BACKFACE_NONE, BACKFACE_CW and BACKFACE_CCW). Back-facing triangles are culled + * and will not be occlusion tested. You may use BACKFACE_NONE to disable culling + * for double sided geometry + * \param clipPlaneMask A mask indicating which clip planes should be considered by the + * triangle clipper. Can be used as an optimization if your application can + * determine (for example during culling) that a group of triangles does not + * intersect a certain frustum plane. However, setting an incorrect mask may + * cause out of bounds memory accesses. + * \param vtxLayout A struct specifying the vertex layout (see struct for detailed + * description). For best performance, it is advisable to store position data + * as compactly in memory as possible. + * \return The query will return VISIBLE if the triangle mesh may be visible, OCCLUDED + * if the mesh is occluded by a previously rendered object, or VIEW_CULLED if all + * triangles are entirely outside the view frustum or backface culled. + */ + virtual CullingResult TestTriangles(const float *inVtx, const unsigned int *inTris, int nTris, const float *modelToClipMatrix = nullptr, BackfaceWinding bfWinding = BACKFACE_CW, ClipPlanes clipPlaneMask = CLIP_PLANE_ALL, const VertexLayout &vtxLayout = VertexLayout(16, 4, 12)) = 0; + + /*! + * \brief Perform input assembly, clipping , projection, triangle setup, and write + * triangles to the screen space bins they overlap. This function can be used to + * distribute work for threading (See the CullingThreadpool class for an example) + * + * \param inVtx Pointer to an array of input vertices, should point to the x component + * of the first vertex. The input vertices are given as (x,y,w) coordinates + * in clip space. The memory layout can be changed using vtxLayout. + * \param inTris Pointer to an array of vertex indices. Each triangle is created + * from three indices consecutively fetched from the array. + * \param nTris The number of triangles to render (inTris must contain atleast 3*nTris + * entries) + * \param triLists Pointer to an array of TriList objects with one TriList object per + * bin. If a triangle overlaps a bin, it will be written to the corresponding + * trilist. Note that this method appends the triangles to the current list, to + * start writing from the beginning of the list, set triList.mTriIdx = 0 + * \param nBinsW Number of vertical bins, the screen is divided into nBinsW x nBinsH + * rectangular bins. + * \param nBinsH Number of horizontal bins, the screen is divided into nBinsW x nBinsH + * rectangular bins. + * \param modelToClipMatrix all vertices will be transformed by this matrix before + * performing projection. If nullptr is passed the transform step will be skipped + * \param clipPlaneMask A mask indicating which clip planes should be considered by the + * triangle clipper. Can be used as an optimization if your application can + * determine (for example during culling) that a group of triangles does not + * intersect a certain frustum plane. However, setting an incorrect mask may + * cause out of bounds memory accesses. + * \param vtxLayout A struct specifying the vertex layout (see struct for detailed + * description). For best performance, it is advisable to store position data + * as compactly in memory as possible. + * \param bfWinding Sets triangle winding order to consider backfacing, must be one one + * of (BACKFACE_NONE, BACKFACE_CW and BACKFACE_CCW). Back-facing triangles are culled + * and will not be binned / rasterized. You may use BACKFACE_NONE to disable culling + * for double sided geometry + */ + virtual void BinTriangles(const float *inVtx, const unsigned int *inTris, int nTris, TriList *triLists, unsigned int nBinsW, unsigned int nBinsH, const float *modelToClipMatrix = nullptr, BackfaceWinding bfWinding = BACKFACE_CW, ClipPlanes clipPlaneMask = CLIP_PLANE_ALL, const VertexLayout &vtxLayout = VertexLayout(16, 4, 12)) = 0; + + /*! + * \brief Renders all occluder triangles in a trilist. This function can be used in + * combination with BinTriangles() to create a threded (binning) rasterizer. The + * bins can be processed independently by different threads without risking writing + * to overlapping memory regions. + * + * \param triLists A triangle list, filled using the BinTriangles() function that is to + * be rendered. + * \param scissor A scissor box limiting the rendering region to the bin. The size of each + * bin must be a multiple of 32x8 pixels due to implementation constraints. For a + * render target with (width, height) resolution and (nBinsW, nBinsH) bins, the + * size of a bin is: + * binWidth = (width / nBinsW) - (width / nBinsW) % 32; + * binHeight = (height / nBinsH) - (height / nBinsH) % 8; + * The last row and column of tiles have a different size: + * lastColBinWidth = width - (nBinsW-1)*binWidth; + * lastRowBinHeight = height - (nBinsH-1)*binHeight; + */ + virtual void RenderTrilist(const TriList &triList, const ScissorRect *scissor) = 0; + + /*! + * \brief Creates a per-pixel depth buffer from the hierarchical z buffer representation. + * Intended for visualizing the hierarchical depth buffer for debugging. The + * buffer is written in scanline order, from the top to bottom (D3D) or bottom to + * top (OGL) of the surface. See the USE_D3D define. + * + * \param depthData Pointer to memory where the per-pixel depth data is written. Must + * hold storage for atleast width*height elements as set by setResolution. + */ + virtual void ComputePixelDepthBuffer(float *depthData, bool flipY) = 0; + + /*! + * \brief Fetch occlusion culling statistics, returns zeroes if ENABLE_STATS define is + * not defined. The statistics can be used for profiling or debugging. + */ + virtual OcclusionCullingStatistics GetStatistics() = 0; + + /*! + * \brief Returns the implementation (CPU instruction set) version of this object. + */ + virtual Implementation GetImplementation() = 0; + + /*! + * \brief Utility function for transforming vertices and outputting them to an (x,y,z,w) + * format suitable for the occluder rasterization and occludee testing functions. + * + * \param mtx Pointer to matrix data. The matrix should column major for post + * multiplication (OGL) and row major for pre-multiplication (DX). This is + * consistent with OpenGL / DirectX behavior. + * \param inVtx Pointer to an array of input vertices. The input vertices are given as + * (x,y,z) coordinates. The memory layout can be changed using vtxLayout. + * \param xfVtx Pointer to an array to store transformed vertices. The transformed + * vertices are always stored as array of structs (AoS) (x,y,z,w) packed in memory. + * \param nVtx Number of vertices to transform. + * \param vtxLayout A struct specifying the vertex layout (see struct for detailed + * description). For best performance, it is advisable to store position data + * as compactly in memory as possible. Note that for this function, the + * w-component is assumed to be 1.0. + */ + static void TransformVertices(const float *mtx, const float *inVtx, float *xfVtx, unsigned int nVtx, const VertexLayout &vtxLayout = VertexLayout(12, 4, 8)); + + /*! + * \brief Get used memory alloc/free callbacks. + */ + void GetAllocFreeCallback( pfnAlignedAlloc & allocCallback, pfnAlignedFree & freeCallback ) { allocCallback = mAlignedAllocCallback, freeCallback = mAlignedFreeCallback; } + +#if MOC_RECORDER_ENABLE + /*! + * \brief Start recording subsequent rasterization and testing calls using the FrameRecorder. + * The function calls that are recorded are: + * - ClearBuffer + * - RenderTriangles + * - TestTriangles + * - TestRect + * All inputs and outputs are recorded, which can be used for correctness validation + * and performance testing. + * + * \param outputFilePath Pointer to name of the output file. + * \return 'true' if recording was started successfully, 'false' otherwise (file access error). + */ + bool RecorderStart( const char * outputFilePath ) const; + + /*! + * \brief Stop recording, flush output and release used memory. + */ + void RecorderStop( ) const; + + /*! + * \brief Manually record triangles. This is called automatically from MaskedOcclusionCulling::RenderTriangles + * if the recording is started, but not from BinTriangles/RenderTrilist (used in multithreaded codepath), in + * which case it has to be called manually. + * + * \param inVtx Pointer to an array of input vertices, should point to the x component + * of the first vertex. The input vertices are given as (x,y,w) coordinates + * in clip space. The memory layout can be changed using vtxLayout. + * \param inTris Pointer to an array of triangle indices. Each triangle is created + * from three indices consecutively fetched from the array. + * \param nTris The number of triangles to render (inTris must contain atleast 3*nTris + * entries) + * \param modelToClipMatrix all vertices will be transformed by this matrix before + * performing projection. If nullptr is passed the transform step will be skipped + * \param bfWinding Sets triangle winding order to consider backfacing, must be one one + * of (BACKFACE_NONE, BACKFACE_CW and BACKFACE_CCW). Back-facing triangles are culled + * and will not be occlusion tested. You may use BACKFACE_NONE to disable culling + * for double sided geometry + * \param clipPlaneMask A mask indicating which clip planes should be considered by the + * triangle clipper. Can be used as an optimization if your application can + * determine (for example during culling) that a group of triangles does not + * intersect a certain frustum plane. However, setting an incorrect mask may + * cause out of bounds memory accesses. + * \param vtxLayout A struct specifying the vertex layout (see struct for detailed + * description). For best performance, it is advisable to store position data + * as compactly in memory as possible. + * \param cullingResult cull result value expected to be returned by executing the + * RenderTriangles call with recorded parameters. + */ + // + // merge the binned data back into original layout; in this case, call it manually from your Threadpool implementation (already added to CullingThreadpool). + // If recording is not enabled, calling this function will do nothing. + void RecordRenderTriangles( const float *inVtx, const unsigned int *inTris, int nTris, const float *modelToClipMatrix = nullptr, ClipPlanes clipPlaneMask = CLIP_PLANE_ALL, BackfaceWinding bfWinding = BACKFACE_CW, const VertexLayout &vtxLayout = VertexLayout( 16, 4, 12 ), CullingResult cullingResult = (CullingResult)-1 ); +#endif // #if MOC_RECORDER_ENABLE + +protected: + pfnAlignedAlloc mAlignedAllocCallback; + pfnAlignedFree mAlignedFreeCallback; + + mutable OcclusionCullingStatistics mStats; + +#if MOC_RECORDER_ENABLE + mutable FrameRecorder * mRecorder; + mutable std::mutex mRecorderMutex; +#endif // #if MOC_RECORDER_ENABLE + + virtual ~MaskedOcclusionCulling() {} +}; diff --git a/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX2.cpp b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX2.cpp new file mode 100644 index 0000000000..b129f12943 --- /dev/null +++ b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX2.cpp @@ -0,0 +1,243 @@ +//////////////////////////////////////////////////////////////////////////////// +// Copyright 2017 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy +// of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +//////////////////////////////////////////////////////////////////////////////// +#include +#include +#include +#include "MaskedOcclusionCulling.h" +#include "CompilerSpecific.inl" + +#if MOC_RECORDER_ENABLE +#include "FrameRecorder.h" +#endif + +#if defined(__MICROSOFT_COMPILER) && _MSC_VER < 1900 + // If you remove/comment this error, the code will compile & use the SSE41 version instead. + #error Older versions than visual studio 2015 not supported due to compiler bug(s) +#endif + +#if !defined(__MICROSOFT_COMPILER) || _MSC_VER >= 1900 + +// For performance reasons, the MaskedOcclusionCullingAVX2.cpp file should be compiled with VEX encoding for SSE instructions (to avoid +// AVX-SSE transition penalties, see https://software.intel.com/en-us/articles/avoiding-avx-sse-transition-penalties). However, the SSE +// version in MaskedOcclusionCulling.cpp _must_ be compiled without VEX encoding to allow backwards compatibility. Best practice is to +// use lowest supported target platform (e.g. /arch:SSE2) as project default, and elevate only the MaskedOcclusionCullingAVX2/512.cpp files. +#ifndef __AVX2__ + #error For best performance, MaskedOcclusionCullingAVX2.cpp should be compiled with /arch:AVX2 +#endif + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// AVX specific defines and constants +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#define SIMD_LANES 8 +#define TILE_HEIGHT_SHIFT 3 + +#define SIMD_LANE_IDX _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7) + +#define SIMD_SUB_TILE_COL_OFFSET _mm256_setr_epi32(0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3, 0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3) +#define SIMD_SUB_TILE_ROW_OFFSET _mm256_setr_epi32(0, 0, 0, 0, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT) +#define SIMD_SUB_TILE_COL_OFFSET_F _mm256_setr_ps(0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3, 0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3) +#define SIMD_SUB_TILE_ROW_OFFSET_F _mm256_setr_ps(0, 0, 0, 0, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT) + +#define SIMD_SHUFFLE_SCANLINE_TO_SUBTILES _mm256_setr_epi8(0x0, 0x4, 0x8, 0xC, 0x1, 0x5, 0x9, 0xD, 0x2, 0x6, 0xA, 0xE, 0x3, 0x7, 0xB, 0xF, 0x0, 0x4, 0x8, 0xC, 0x1, 0x5, 0x9, 0xD, 0x2, 0x6, 0xA, 0xE, 0x3, 0x7, 0xB, 0xF) + +#define SIMD_LANE_YCOORD_I _mm256_setr_epi32(128, 384, 640, 896, 1152, 1408, 1664, 1920) +#define SIMD_LANE_YCOORD_F _mm256_setr_ps(128.0f, 384.0f, 640.0f, 896.0f, 1152.0f, 1408.0f, 1664.0f, 1920.0f) + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// AVX specific typedefs and functions +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef __m256 __mw; +typedef __m256i __mwi; + +#define _mmw_set1_ps _mm256_set1_ps +#define _mmw_setzero_ps _mm256_setzero_ps +#define _mmw_and_ps _mm256_and_ps +#define _mmw_or_ps _mm256_or_ps +#define _mmw_xor_ps _mm256_xor_ps +#define _mmw_not_ps(a) _mm256_xor_ps((a), _mm256_castsi256_ps(_mm256_set1_epi32(~0))) +#define _mmw_andnot_ps _mm256_andnot_ps +#define _mmw_neg_ps(a) _mm256_xor_ps((a), _mm256_set1_ps(-0.0f)) +#define _mmw_abs_ps(a) _mm256_and_ps((a), _mm256_castsi256_ps(_mm256_set1_epi32(0x7FFFFFFF))) +#define _mmw_add_ps _mm256_add_ps +#define _mmw_sub_ps _mm256_sub_ps +#define _mmw_mul_ps _mm256_mul_ps +#define _mmw_div_ps _mm256_div_ps +#define _mmw_min_ps _mm256_min_ps +#define _mmw_max_ps _mm256_max_ps +#define _mmw_fmadd_ps _mm256_fmadd_ps +#define _mmw_fmsub_ps _mm256_fmsub_ps +#define _mmw_movemask_ps _mm256_movemask_ps +#define _mmw_blendv_ps _mm256_blendv_ps +#define _mmw_cmpge_ps(a,b) _mm256_cmp_ps(a, b, _CMP_GE_OQ) +#define _mmw_cmpgt_ps(a,b) _mm256_cmp_ps(a, b, _CMP_GT_OQ) +#define _mmw_cmpeq_ps(a,b) _mm256_cmp_ps(a, b, _CMP_EQ_OQ) +#define _mmw_floor_ps(x) _mm256_round_ps(x, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) +#define _mmw_ceil_ps(x) _mm256_round_ps(x, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) +#define _mmw_shuffle_ps _mm256_shuffle_ps +#define _mmw_insertf32x4_ps _mm256_insertf128_ps +#define _mmw_cvtepi32_ps _mm256_cvtepi32_ps +#define _mmw_blendv_epi32(a,b,c) simd_cast<__mwi>(_mmw_blendv_ps(simd_cast<__mw>(a), simd_cast<__mw>(b), simd_cast<__mw>(c))) + +#define _mmw_set1_epi32 _mm256_set1_epi32 +#define _mmw_setzero_epi32 _mm256_setzero_si256 +#define _mmw_and_epi32 _mm256_and_si256 +#define _mmw_or_epi32 _mm256_or_si256 +#define _mmw_xor_epi32 _mm256_xor_si256 +#define _mmw_not_epi32(a) _mm256_xor_si256((a), _mm256_set1_epi32(~0)) +#define _mmw_andnot_epi32 _mm256_andnot_si256 +#define _mmw_neg_epi32(a) _mm256_sub_epi32(_mm256_set1_epi32(0), (a)) +#define _mmw_add_epi32 _mm256_add_epi32 +#define _mmw_sub_epi32 _mm256_sub_epi32 +#define _mmw_min_epi32 _mm256_min_epi32 +#define _mmw_max_epi32 _mm256_max_epi32 +#define _mmw_subs_epu16 _mm256_subs_epu16 +#define _mmw_mullo_epi32 _mm256_mullo_epi32 +#define _mmw_cmpeq_epi32 _mm256_cmpeq_epi32 +#define _mmw_testz_epi32 _mm256_testz_si256 +#define _mmw_cmpgt_epi32 _mm256_cmpgt_epi32 +#define _mmw_srai_epi32 _mm256_srai_epi32 +#define _mmw_srli_epi32 _mm256_srli_epi32 +#define _mmw_slli_epi32 _mm256_slli_epi32 +#define _mmw_sllv_ones(x) _mm256_sllv_epi32(SIMD_BITS_ONE, x) +#define _mmw_transpose_epi8(x) _mm256_shuffle_epi8(x, SIMD_SHUFFLE_SCANLINE_TO_SUBTILES) +#define _mmw_abs_epi32 _mm256_abs_epi32 +#define _mmw_cvtps_epi32 _mm256_cvtps_epi32 +#define _mmw_cvttps_epi32 _mm256_cvttps_epi32 + +#define _mmx_dp4_ps(a, b) _mm_dp_ps(a, b, 0xFF) +#define _mmx_fmadd_ps _mm_fmadd_ps +#define _mmx_max_epi32 _mm_max_epi32 +#define _mmx_min_epi32 _mm_min_epi32 + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// SIMD casting functions +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +template FORCE_INLINE T simd_cast(Y A); +template<> FORCE_INLINE __m128 simd_cast<__m128>(float A) { return _mm_set1_ps(A); } +template<> FORCE_INLINE __m128 simd_cast<__m128>(__m128i A) { return _mm_castsi128_ps(A); } +template<> FORCE_INLINE __m128 simd_cast<__m128>(__m128 A) { return A; } +template<> FORCE_INLINE __m128i simd_cast<__m128i>(int A) { return _mm_set1_epi32(A); } +template<> FORCE_INLINE __m128i simd_cast<__m128i>(__m128 A) { return _mm_castps_si128(A); } +template<> FORCE_INLINE __m128i simd_cast<__m128i>(__m128i A) { return A; } +template<> FORCE_INLINE __m256 simd_cast<__m256>(float A) { return _mm256_set1_ps(A); } +template<> FORCE_INLINE __m256 simd_cast<__m256>(__m256i A) { return _mm256_castsi256_ps(A); } +template<> FORCE_INLINE __m256 simd_cast<__m256>(__m256 A) { return A; } +template<> FORCE_INLINE __m256i simd_cast<__m256i>(int A) { return _mm256_set1_epi32(A); } +template<> FORCE_INLINE __m256i simd_cast<__m256i>(__m256 A) { return _mm256_castps_si256(A); } +template<> FORCE_INLINE __m256i simd_cast<__m256i>(__m256i A) { return A; } + +#define MAKE_ACCESSOR(name, simd_type, base_type, is_const, elements) \ + FORCE_INLINE is_const base_type * name(is_const simd_type &a) { \ + union accessor { simd_type m_native; base_type m_array[elements]; }; \ + is_const accessor *acs = reinterpret_cast(&a); \ + return acs->m_array; \ + } + +MAKE_ACCESSOR(simd_f32, __m128, float, , 4) +MAKE_ACCESSOR(simd_f32, __m128, float, const, 4) +MAKE_ACCESSOR(simd_i32, __m128i, int, , 4) +MAKE_ACCESSOR(simd_i32, __m128i, int, const, 4) + +MAKE_ACCESSOR(simd_f32, __m256, float, , 8) +MAKE_ACCESSOR(simd_f32, __m256, float, const, 8) +MAKE_ACCESSOR(simd_i32, __m256i, int, , 8) +MAKE_ACCESSOR(simd_i32, __m256i, int, const, 8) + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Specialized AVX input assembly function for general vertex gather +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef MaskedOcclusionCulling::VertexLayout VertexLayout; + +FORCE_INLINE void GatherVertices(__m256 *vtxX, __m256 *vtxY, __m256 *vtxW, const float *inVtx, const unsigned int *inTrisPtr, int numLanes, const VertexLayout &vtxLayout) +{ + assert(numLanes >= 1); + + const __m256i SIMD_TRI_IDX_OFFSET = _mm256_setr_epi32(0, 3, 6, 9, 12, 15, 18, 21); + static const __m256i SIMD_LANE_MASK[9] = { + _mm256_setr_epi32( 0, 0, 0, 0, 0, 0, 0, 0), + _mm256_setr_epi32(~0, 0, 0, 0, 0, 0, 0, 0), + _mm256_setr_epi32(~0, ~0, 0, 0, 0, 0, 0, 0), + _mm256_setr_epi32(~0, ~0, ~0, 0, 0, 0, 0, 0), + _mm256_setr_epi32(~0, ~0, ~0, ~0, 0, 0, 0, 0), + _mm256_setr_epi32(~0, ~0, ~0, ~0, ~0, 0, 0, 0), + _mm256_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, 0, 0), + _mm256_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, 0), + _mm256_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0) + }; + + // Compute per-lane index list offset that guards against out of bounds memory accesses + __m256i safeTriIdxOffset = _mm256_and_si256(SIMD_TRI_IDX_OFFSET, SIMD_LANE_MASK[numLanes]); + + // Fetch triangle indices. + __m256i vtxIdx[3]; + vtxIdx[0] = _mmw_mullo_epi32(_mm256_i32gather_epi32((const int*)inTrisPtr + 0, safeTriIdxOffset, 4), _mmw_set1_epi32(vtxLayout.mStride)); + vtxIdx[1] = _mmw_mullo_epi32(_mm256_i32gather_epi32((const int*)inTrisPtr + 1, safeTriIdxOffset, 4), _mmw_set1_epi32(vtxLayout.mStride)); + vtxIdx[2] = _mmw_mullo_epi32(_mm256_i32gather_epi32((const int*)inTrisPtr + 2, safeTriIdxOffset, 4), _mmw_set1_epi32(vtxLayout.mStride)); + + char *vPtr = (char *)inVtx; + + // Fetch triangle vertices + for (int i = 0; i < 3; i++) + { + vtxX[i] = _mm256_i32gather_ps((float *)vPtr, vtxIdx[i], 1); + vtxY[i] = _mm256_i32gather_ps((float *)(vPtr + vtxLayout.mOffsetY), vtxIdx[i], 1); + vtxW[i] = _mm256_i32gather_ps((float *)(vPtr + vtxLayout.mOffsetW), vtxIdx[i], 1); + } +} + +namespace MaskedOcclusionCullingAVX2 +{ + static MaskedOcclusionCulling::Implementation gInstructionSet = MaskedOcclusionCulling::AVX2; + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Include common algorithm implementation (general, SIMD independent code) + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + #include "MaskedOcclusionCullingCommon.inl" + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Utility function to create a new object using the allocator callbacks + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + typedef MaskedOcclusionCulling::pfnAlignedAlloc pfnAlignedAlloc; + typedef MaskedOcclusionCulling::pfnAlignedFree pfnAlignedFree; + + MaskedOcclusionCulling *CreateMaskedOcclusionCulling(pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree) + { + MaskedOcclusionCullingPrivate *object = (MaskedOcclusionCullingPrivate *)alignedAlloc(64, sizeof(MaskedOcclusionCullingPrivate)); + new (object) MaskedOcclusionCullingPrivate(alignedAlloc, alignedFree); + return object; + } +}; + +#else + +namespace MaskedOcclusionCullingAVX2 +{ + typedef MaskedOcclusionCulling::pfnAlignedAlloc pfnAlignedAlloc; + typedef MaskedOcclusionCulling::pfnAlignedFree pfnAlignedFree; + + MaskedOcclusionCulling *CreateMaskedOcclusionCulling(pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree) + { + return nullptr; + } +}; + +#endif diff --git a/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX512.cpp b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX512.cpp new file mode 100644 index 0000000000..1dccccd83e --- /dev/null +++ b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingAVX512.cpp @@ -0,0 +1,309 @@ +//////////////////////////////////////////////////////////////////////////////// +// Copyright 2017 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy +// of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +//////////////////////////////////////////////////////////////////////////////// +#include +#include +#include +#include "MaskedOcclusionCulling.h" +#include "CompilerSpecific.inl" + +#if MOC_RECORDER_ENABLE +#include "FrameRecorder.h" +#endif + +// Make sure compiler supports AVX-512 intrinsics: Visual Studio 2017 (Update 3) || Intel C++ Compiler 16.0 || Clang 4.0 || GCC 5.0 +#if USE_AVX512 != 0 && ((defined(_MSC_VER) && _MSC_VER >= 1911) || (defined(__INTEL_COMPILER) && __INTEL_COMPILER >= 1600) || (defined(__clang__) && __clang_major__ >= 4) || (defined(__GNUC__) && __GNUC__ >= 5)) + +// The MaskedOcclusionCullingAVX512.cpp file should be compiled avx2/avx512 architecture options turned on in the compiler. However, the SSE +// version in MaskedOcclusionCulling.cpp _must_ be compiled with SSE2 architecture allow backwards compatibility. Best practice is to +// use lowest supported target platform (e.g. /arch:SSE2) as project default, and elevate only the MaskedOcclusionCullingAVX2/512.cpp files. +#ifndef __AVX2__ + #error For best performance, MaskedOcclusionCullingAVX512.cpp should be compiled with /arch:AVX2 +#endif + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// AVX specific defines and constants +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#define SIMD_LANES 16 +#define TILE_HEIGHT_SHIFT 4 + +#define SIMD_LANE_IDX _mm512_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) + +#define SIMD_SUB_TILE_COL_OFFSET _mm512_setr_epi32(0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3, 0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3, 0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3, 0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3) +#define SIMD_SUB_TILE_ROW_OFFSET _mm512_setr_epi32(0, 0, 0, 0, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT * 2, SUB_TILE_HEIGHT * 2, SUB_TILE_HEIGHT * 2, SUB_TILE_HEIGHT * 2, SUB_TILE_HEIGHT * 3, SUB_TILE_HEIGHT * 3, SUB_TILE_HEIGHT * 3, SUB_TILE_HEIGHT * 3) +#define SIMD_SUB_TILE_COL_OFFSET_F _mm512_setr_ps(0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3, 0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3, 0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3, 0, SUB_TILE_WIDTH, SUB_TILE_WIDTH * 2, SUB_TILE_WIDTH * 3) +#define SIMD_SUB_TILE_ROW_OFFSET_F _mm512_setr_ps(0, 0, 0, 0, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT, SUB_TILE_HEIGHT * 2, SUB_TILE_HEIGHT * 2, SUB_TILE_HEIGHT * 2, SUB_TILE_HEIGHT * 2, SUB_TILE_HEIGHT * 3, SUB_TILE_HEIGHT * 3, SUB_TILE_HEIGHT * 3, SUB_TILE_HEIGHT * 3) + +#define SIMD_SHUFFLE_SCANLINE_TO_SUBTILES _mm512_set_epi32(0x0F0B0703, 0x0E0A0602, 0x0D090501, 0x0C080400, 0x0F0B0703, 0x0E0A0602, 0x0D090501, 0x0C080400, 0x0F0B0703, 0x0E0A0602, 0x0D090501, 0x0C080400, 0x0F0B0703, 0x0E0A0602, 0x0D090501, 0x0C080400) + +#define SIMD_LANE_YCOORD_I _mm512_setr_epi32(128, 384, 640, 896, 1152, 1408, 1664, 1920, 2176, 2432, 2688, 2944, 3200, 3456, 3712, 3968) +#define SIMD_LANE_YCOORD_F _mm512_setr_ps(128.0f, 384.0f, 640.0f, 896.0f, 1152.0f, 1408.0f, 1664.0f, 1920.0f, 2176.0f, 2432.0f, 2688.0f, 2944.0f, 3200.0f, 3456.0f, 3712.0f, 3968.0f) + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// AVX specific typedefs and functions +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef __m512 __mw; +typedef __m512i __mwi; + +#define _mmw_set1_ps _mm512_set1_ps +#define _mmw_setzero_ps _mm512_setzero_ps +#define _mmw_and_ps _mm512_and_ps +#define _mmw_or_ps _mm512_or_ps +#define _mmw_xor_ps _mm512_xor_ps +#define _mmw_not_ps(a) _mm512_xor_ps((a), _mm512_castsi512_ps(_mm512_set1_epi32(~0))) +#define _mmw_andnot_ps _mm512_andnot_ps +#define _mmw_neg_ps(a) _mm512_xor_ps((a), _mm512_set1_ps(-0.0f)) +#define _mmw_abs_ps(a) _mm512_and_ps((a), _mm512_castsi512_ps(_mm512_set1_epi32(0x7FFFFFFF))) +#define _mmw_add_ps _mm512_add_ps +#define _mmw_sub_ps _mm512_sub_ps +#define _mmw_mul_ps _mm512_mul_ps +#define _mmw_div_ps _mm512_div_ps +#define _mmw_min_ps _mm512_min_ps +#define _mmw_max_ps _mm512_max_ps +#define _mmw_fmadd_ps _mm512_fmadd_ps +#define _mmw_fmsub_ps _mm512_fmsub_ps +#define _mmw_shuffle_ps _mm512_shuffle_ps +#define _mmw_insertf32x4_ps _mm512_insertf32x4 +#define _mmw_cvtepi32_ps _mm512_cvtepi32_ps +#define _mmw_blendv_epi32(a,b,c) simd_cast<__mwi>(_mmw_blendv_ps(simd_cast<__mw>(a), simd_cast<__mw>(b), simd_cast<__mw>(c))) + +#define _mmw_set1_epi32 _mm512_set1_epi32 +#define _mmw_setzero_epi32 _mm512_setzero_si512 +#define _mmw_and_epi32 _mm512_and_si512 +#define _mmw_or_epi32 _mm512_or_si512 +#define _mmw_xor_epi32 _mm512_xor_si512 +#define _mmw_not_epi32(a) _mm512_xor_si512((a), _mm512_set1_epi32(~0)) +#define _mmw_andnot_epi32 _mm512_andnot_si512 +#define _mmw_neg_epi32(a) _mm512_sub_epi32(_mm512_set1_epi32(0), (a)) +#define _mmw_add_epi32 _mm512_add_epi32 +#define _mmw_sub_epi32 _mm512_sub_epi32 +#define _mmw_min_epi32 _mm512_min_epi32 +#define _mmw_max_epi32 _mm512_max_epi32 +#define _mmw_subs_epu16 _mm512_subs_epu16 +#define _mmw_mullo_epi32 _mm512_mullo_epi32 +#define _mmw_srai_epi32 _mm512_srai_epi32 +#define _mmw_srli_epi32 _mm512_srli_epi32 +#define _mmw_slli_epi32 _mm512_slli_epi32 +#define _mmw_sllv_ones(x) _mm512_sllv_epi32(SIMD_BITS_ONE, x) +#define _mmw_transpose_epi8(x) _mm512_shuffle_epi8(x, SIMD_SHUFFLE_SCANLINE_TO_SUBTILES) +#define _mmw_abs_epi32 _mm512_abs_epi32 +#define _mmw_cvtps_epi32 _mm512_cvtps_epi32 +#define _mmw_cvttps_epi32 _mm512_cvttps_epi32 + +#define _mmx_dp4_ps(a, b) _mm_dp_ps(a, b, 0xFF) +#define _mmx_fmadd_ps _mm_fmadd_ps +#define _mmx_max_epi32 _mm_max_epi32 +#define _mmx_min_epi32 _mm_min_epi32 + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// SIMD casting functions +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +template FORCE_INLINE T simd_cast(Y A); +template<> FORCE_INLINE __m128 simd_cast<__m128>(float A) { return _mm_set1_ps(A); } +template<> FORCE_INLINE __m128 simd_cast<__m128>(__m128i A) { return _mm_castsi128_ps(A); } +template<> FORCE_INLINE __m128 simd_cast<__m128>(__m128 A) { return A; } +template<> FORCE_INLINE __m128i simd_cast<__m128i>(int A) { return _mm_set1_epi32(A); } +template<> FORCE_INLINE __m128i simd_cast<__m128i>(__m128 A) { return _mm_castps_si128(A); } +template<> FORCE_INLINE __m128i simd_cast<__m128i>(__m128i A) { return A; } +template<> FORCE_INLINE __m256 simd_cast<__m256>(float A) { return _mm256_set1_ps(A); } +template<> FORCE_INLINE __m256 simd_cast<__m256>(__m256i A) { return _mm256_castsi256_ps(A); } +template<> FORCE_INLINE __m256 simd_cast<__m256>(__m256 A) { return A; } +template<> FORCE_INLINE __m256i simd_cast<__m256i>(int A) { return _mm256_set1_epi32(A); } +template<> FORCE_INLINE __m256i simd_cast<__m256i>(__m256 A) { return _mm256_castps_si256(A); } +template<> FORCE_INLINE __m256i simd_cast<__m256i>(__m256i A) { return A; } +template<> FORCE_INLINE __m512 simd_cast<__m512>(float A) { return _mm512_set1_ps(A); } +template<> FORCE_INLINE __m512 simd_cast<__m512>(__m512i A) { return _mm512_castsi512_ps(A); } +template<> FORCE_INLINE __m512 simd_cast<__m512>(__m512 A) { return A; } +template<> FORCE_INLINE __m512i simd_cast<__m512i>(int A) { return _mm512_set1_epi32(A); } +template<> FORCE_INLINE __m512i simd_cast<__m512i>(__m512 A) { return _mm512_castps_si512(A); } +template<> FORCE_INLINE __m512i simd_cast<__m512i>(__m512i A) { return A; } + +#define MAKE_ACCESSOR(name, simd_type, base_type, is_const, elements) \ + FORCE_INLINE is_const base_type * name(is_const simd_type &a) { \ + union accessor { simd_type m_native; base_type m_array[elements]; }; \ + is_const accessor *acs = reinterpret_cast(&a); \ + return acs->m_array; \ + } + +MAKE_ACCESSOR(simd_f32, __m128, float, , 4) +MAKE_ACCESSOR(simd_f32, __m128, float, const, 4) +MAKE_ACCESSOR(simd_i32, __m128i, int, , 4) +MAKE_ACCESSOR(simd_i32, __m128i, int, const, 4) + +MAKE_ACCESSOR(simd_f32, __m256, float, , 8) +MAKE_ACCESSOR(simd_f32, __m256, float, const, 8) +MAKE_ACCESSOR(simd_i32, __m256i, int, , 8) +MAKE_ACCESSOR(simd_i32, __m256i, int, const, 8) + +MAKE_ACCESSOR(simd_f32, __m512, float, , 16) +MAKE_ACCESSOR(simd_f32, __m512, float, const, 16) +MAKE_ACCESSOR(simd_i32, __m512i, int, , 16) +MAKE_ACCESSOR(simd_i32, __m512i, int, const, 16) + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Specialized AVX input assembly function for general vertex gather +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef MaskedOcclusionCulling::VertexLayout VertexLayout; + +FORCE_INLINE void GatherVertices(__m512 *vtxX, __m512 *vtxY, __m512 *vtxW, const float *inVtx, const unsigned int *inTrisPtr, int numLanes, const VertexLayout &vtxLayout) +{ + assert(numLanes >= 1); + + const __m512i SIMD_TRI_IDX_OFFSET = _mm512_setr_epi32(0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45); + static const __m512i SIMD_LANE_MASK[17] = { + _mm512_setr_epi32( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, 0, 0, 0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 0, 0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 0), + _mm512_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0) + }; + + // Compute per-lane index list offset that guards against out of bounds memory accesses + __m512i safeTriIdxOffset = _mm512_and_si512(SIMD_TRI_IDX_OFFSET, SIMD_LANE_MASK[numLanes]); + + // Fetch triangle indices. + __m512i vtxIdx[3]; + vtxIdx[0] = _mmw_mullo_epi32(_mm512_i32gather_epi32(safeTriIdxOffset, (const int*)inTrisPtr + 0, 4), _mmw_set1_epi32(vtxLayout.mStride)); + vtxIdx[1] = _mmw_mullo_epi32(_mm512_i32gather_epi32(safeTriIdxOffset, (const int*)inTrisPtr + 1, 4), _mmw_set1_epi32(vtxLayout.mStride)); + vtxIdx[2] = _mmw_mullo_epi32(_mm512_i32gather_epi32(safeTriIdxOffset, (const int*)inTrisPtr + 2, 4), _mmw_set1_epi32(vtxLayout.mStride)); + + char *vPtr = (char *)inVtx; + + // Fetch triangle vertices + for (int i = 0; i < 3; i++) + { + vtxX[i] = _mm512_i32gather_ps(vtxIdx[i], (float *)vPtr, 1); + vtxY[i] = _mm512_i32gather_ps(vtxIdx[i], (float *)(vPtr + vtxLayout.mOffsetY), 1); + vtxW[i] = _mm512_i32gather_ps(vtxIdx[i], (float *)(vPtr + vtxLayout.mOffsetW), 1); + } +} + +namespace MaskedOcclusionCullingAVX512 +{ + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Poorly implemented functions. TODO: fix common (maskedOcclusionCullingCommon.inl) code to improve perf + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + FORCE_INLINE __m512 _mmw_floor_ps(__m512 x) + { + return _mm512_roundscale_ps(x, 1); // 1 = floor + } + + FORCE_INLINE __m512 _mmw_ceil_ps(__m512 x) + { + return _mm512_roundscale_ps(x, 2); // 2 = ceil + } + + FORCE_INLINE __m512i _mmw_cmpeq_epi32(__m512i a, __m512i b) + { + __mmask16 mask = _mm512_cmpeq_epi32_mask(a, b); + return _mm512_mask_mov_epi32(_mm512_set1_epi32(0), mask, _mm512_set1_epi32(~0)); + } + + FORCE_INLINE __m512i _mmw_cmpgt_epi32(__m512i a, __m512i b) + { + __mmask16 mask = _mm512_cmpgt_epi32_mask(a, b); + return _mm512_mask_mov_epi32(_mm512_set1_epi32(0), mask, _mm512_set1_epi32(~0)); + } + + FORCE_INLINE bool _mmw_testz_epi32(__m512i a, __m512i b) + { + __mmask16 mask = _mm512_cmpeq_epi32_mask(_mm512_and_si512(a, b), _mm512_set1_epi32(0)); + return mask == 0xFFFF; + } + + FORCE_INLINE __m512 _mmw_cmpge_ps(__m512 a, __m512 b) + { + __mmask16 mask = _mm512_cmp_ps_mask(a, b, _CMP_GE_OQ); + return _mm512_castsi512_ps(_mm512_mask_mov_epi32(_mm512_set1_epi32(0), mask, _mm512_set1_epi32(~0))); + } + + FORCE_INLINE __m512 _mmw_cmpgt_ps(__m512 a, __m512 b) + { + __mmask16 mask = _mm512_cmp_ps_mask(a, b, _CMP_GT_OQ); + return _mm512_castsi512_ps(_mm512_mask_mov_epi32(_mm512_set1_epi32(0), mask, _mm512_set1_epi32(~0))); + } + + FORCE_INLINE __m512 _mmw_cmpeq_ps(__m512 a, __m512 b) + { + __mmask16 mask = _mm512_cmp_ps_mask(a, b, _CMP_EQ_OQ); + return _mm512_castsi512_ps(_mm512_mask_mov_epi32(_mm512_set1_epi32(0), mask, _mm512_set1_epi32(~0))); + } + + FORCE_INLINE __mmask16 _mmw_movemask_ps(const __m512 &a) + { + __mmask16 mask = _mm512_cmp_epi32_mask(_mm512_and_si512(_mm512_castps_si512(a), _mm512_set1_epi32(0x80000000)), _mm512_set1_epi32(0), 4); // a & 0x8000000 != 0 + return mask; + } + + FORCE_INLINE __m512 _mmw_blendv_ps(const __m512 &a, const __m512 &b, const __m512 &c) + { + __mmask16 mask = _mmw_movemask_ps(c); + return _mm512_mask_mov_ps(a, mask, b); + } + + static MaskedOcclusionCulling::Implementation gInstructionSet = MaskedOcclusionCulling::AVX512; + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Include common algorithm implementation (general, SIMD independent code) + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + #include "MaskedOcclusionCullingCommon.inl" + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Utility function to create a new object using the allocator callbacks + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + typedef MaskedOcclusionCulling::pfnAlignedAlloc pfnAlignedAlloc; + typedef MaskedOcclusionCulling::pfnAlignedFree pfnAlignedFree; + + MaskedOcclusionCulling *CreateMaskedOcclusionCulling(pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree) + { + MaskedOcclusionCullingPrivate *object = (MaskedOcclusionCullingPrivate *)alignedAlloc(64, sizeof(MaskedOcclusionCullingPrivate)); + new (object) MaskedOcclusionCullingPrivate(alignedAlloc, alignedFree); + return object; + } +}; + +#else + +namespace MaskedOcclusionCullingAVX512 +{ + typedef MaskedOcclusionCulling::pfnAlignedAlloc pfnAlignedAlloc; + typedef MaskedOcclusionCulling::pfnAlignedFree pfnAlignedFree; + + MaskedOcclusionCulling *CreateMaskedOcclusionCulling(pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree) + { + return nullptr; + } +}; + +#endif diff --git a/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingCommon.inl b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingCommon.inl new file mode 100644 index 0000000000..331ca69964 --- /dev/null +++ b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/MaskedOcclusionCullingCommon.inl @@ -0,0 +1,2053 @@ +//////////////////////////////////////////////////////////////////////////////// +// Copyright 2017 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy +// of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +//////////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Common SIMD math utility functions +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +template FORCE_INLINE T max(const T &a, const T &b) { return a > b ? a : b; } +template FORCE_INLINE T min(const T &a, const T &b) { return a < b ? a : b; } + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Common defines and constants +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#define SIMD_ALL_LANES_MASK ((1 << SIMD_LANES) - 1) + +// Tile dimensions are 32xN pixels. These values are not tweakable and the code must also be modified +// to support different tile sizes as it is tightly coupled with the SSE/AVX register size +#define TILE_WIDTH_SHIFT 5 +#define TILE_WIDTH (1 << TILE_WIDTH_SHIFT) +#define TILE_HEIGHT (1 << TILE_HEIGHT_SHIFT) + +// Sub-tiles (used for updating the masked HiZ buffer) are 8x4 tiles, so there are 4x2 sub-tiles in a tile +#define SUB_TILE_WIDTH 8 +#define SUB_TILE_HEIGHT 4 + +// The number of fixed point bits used to represent vertex coordinates / edge slopes. +#if PRECISE_COVERAGE != 0 + #define FP_BITS 8 + #define FP_HALF_PIXEL (1 << (FP_BITS - 1)) + #define FP_INV (1.0f / (float)(1 << FP_BITS)) +#else + // Note that too low precision, without precise coverage, may cause overshoots / false coverage during rasterization. + // This is configured for 14 bits for AVX512 and 16 bits for SSE. Max tile slope delta is roughly + // (screenWidth + 2*(GUARD_BAND_PIXEL_SIZE + 1)) * (2^FP_BITS * (TILE_HEIGHT + GUARD_BAND_PIXEL_SIZE + 1)) + // and must fit in 31 bits. With this config, max image resolution (width) is ~3272, so stay well clear of this limit. + #define FP_BITS (19 - TILE_HEIGHT_SHIFT) +#endif + +// Tile dimensions in fixed point coordinates +#define FP_TILE_HEIGHT_SHIFT (FP_BITS + TILE_HEIGHT_SHIFT) +#define FP_TILE_HEIGHT (1 << FP_TILE_HEIGHT_SHIFT) + +// Maximum number of triangles that may be generated during clipping. We process SIMD_LANES triangles at a time and +// clip against 5 planes, so the max should be 5*8 = 40 (we immediately draw the first clipped triangle). +// This number must be a power of two. +#define MAX_CLIPPED (8*SIMD_LANES) +#define MAX_CLIPPED_WRAP (MAX_CLIPPED - 1) + +// Size of guard band in pixels. Clipping doesn't seem to be very expensive so we use a small guard band +// to improve rasterization performance. It's not recommended to set the guard band to zero, as this may +// cause leakage along the screen border due to precision/rounding. +#define GUARD_BAND_PIXEL_SIZE 1.0f + +// We classify triangles as big if the bounding box is wider than this given threshold and use a tighter +// but slightly more expensive traversal algorithm. This improves performance greatly for sliver triangles +#define BIG_TRIANGLE 3 + +// Only gather statistics if enabled. +#if ENABLE_STATS != 0 + #define STATS_ADD(var, val) _InterlockedExchangeAdd64( &var, val ) +#else + #define STATS_ADD(var, val) +#endif + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// SIMD common defines (constant values) +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#define SIMD_BITS_ONE _mmw_set1_epi32(~0) +#define SIMD_BITS_ZERO _mmw_setzero_epi32() +#define SIMD_TILE_WIDTH _mmw_set1_epi32(TILE_WIDTH) + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Vertex fetch utility function, need to be in global namespace due to template specialization +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +template FORCE_INLINE void VtxFetch4(__mw *v, const unsigned int *inTrisPtr, int triVtx, const float *inVtx, int numLanes) +{ + // Fetch 4 vectors (matching 1 sse part of the SIMD register), and continue to the next + const int ssePart = (SIMD_LANES / 4) - N; + for (int k = 0; k < 4; k++) + { + int lane = 4 * ssePart + k; + if (numLanes > lane) + v[k] = _mmw_insertf32x4_ps(v[k], _mm_loadu_ps(&inVtx[inTrisPtr[lane * 3 + triVtx] << 2]), ssePart); + } + VtxFetch4(v, inTrisPtr, triVtx, inVtx, numLanes); +} + +template<> FORCE_INLINE void VtxFetch4<0>(__mw *v, const unsigned int *inTrisPtr, int triVtx, const float *inVtx, int numLanes) +{ + // Workaround for unused parameter warning + (void)v; (void)inTrisPtr; (void)triVtx; (void)inVtx; (void)numLanes; +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Private class containing the implementation +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class MaskedOcclusionCullingPrivate : public MaskedOcclusionCulling +{ +public: + struct ZTile + { + __mw mZMin[2]; + __mwi mMask; + }; + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Member variables + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + __mw mHalfWidth; + __mw mHalfHeight; + __mw mCenterX; + __mw mCenterY; + __m128 mCSFrustumPlanes[5]; + __m128 mIHalfSize; + __m128 mICenter; + __m128i mIScreenSize; + + float mNearDist; + int mWidth; + int mHeight; + int mTilesWidth; + int mTilesHeight; + + ZTile *mMaskedHiZBuffer; + ScissorRect mFullscreenScissor; + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Constructors and state handling + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + MaskedOcclusionCullingPrivate(pfnAlignedAlloc alignedAlloc, pfnAlignedFree alignedFree) : mFullscreenScissor(0, 0, 0, 0) + { + mMaskedHiZBuffer = nullptr; + mAlignedAllocCallback = alignedAlloc; + mAlignedFreeCallback = alignedFree; +#if MOC_RECORDER_ENABLE + mRecorder = nullptr; +#endif + + SetNearClipPlane(0.0f); + mCSFrustumPlanes[0] = _mm_setr_ps(0.0f, 0.0f, 1.0f, 0.0f); + mCSFrustumPlanes[1] = _mm_setr_ps(1.0f, 0.0f, 1.0f, 0.0f); + mCSFrustumPlanes[2] = _mm_setr_ps(-1.0f, 0.0f, 1.0f, 0.0f); + mCSFrustumPlanes[3] = _mm_setr_ps(0.0f, 1.0f, 1.0f, 0.0f); + mCSFrustumPlanes[4] = _mm_setr_ps(0.0f, -1.0f, 1.0f, 0.0f); + + memset(&mStats, 0, sizeof(OcclusionCullingStatistics)); + + SetResolution(0, 0); + } + + ~MaskedOcclusionCullingPrivate() override + { + if (mMaskedHiZBuffer != nullptr) + mAlignedFreeCallback(mMaskedHiZBuffer); + mMaskedHiZBuffer = nullptr; + +#if MOC_RECORDER_ENABLE + assert( mRecorder == nullptr ); // forgot to call StopRecording()? +#endif + } + + void SetResolution(unsigned int width, unsigned int height) override + { + // Resolution must be a multiple of the subtile size + assert(width % SUB_TILE_WIDTH == 0 && height % SUB_TILE_HEIGHT == 0); +#if PRECISE_COVERAGE == 0 + // Test if combination of resolution & SLOPE_FP_BITS bits may cause 32-bit overflow. Note that the maximum resolution estimate + // is only an estimate (not conservative). It's advicable to stay well below the limit. + assert(width < ((1U << 31) - 1U) / ((1U << FP_BITS) * (TILE_HEIGHT + (unsigned int)(GUARD_BAND_PIXEL_SIZE + 1.0f))) - (2U * (unsigned int)(GUARD_BAND_PIXEL_SIZE + 1.0f))); +#endif + + // Delete current masked hierarchical Z buffer + if (mMaskedHiZBuffer != nullptr) + mAlignedFreeCallback(mMaskedHiZBuffer); + mMaskedHiZBuffer = nullptr; + + // Setup various resolution dependent constant values + mWidth = (int)width; + mHeight = (int)height; + mTilesWidth = (int)(width + TILE_WIDTH - 1) >> TILE_WIDTH_SHIFT; + mTilesHeight = (int)(height + TILE_HEIGHT - 1) >> TILE_HEIGHT_SHIFT; + mCenterX = _mmw_set1_ps((float)mWidth * 0.5f); + mCenterY = _mmw_set1_ps((float)mHeight * 0.5f); + mICenter = _mm_setr_ps((float)mWidth * 0.5f, (float)mWidth * 0.5f, (float)mHeight * 0.5f, (float)mHeight * 0.5f); + mHalfWidth = _mmw_set1_ps((float)mWidth * 0.5f); +#if USE_D3D != 0 + mHalfHeight = _mmw_set1_ps((float)-mHeight * 0.5f); + mIHalfSize = _mm_setr_ps((float)mWidth * 0.5f, (float)mWidth * 0.5f, (float)-mHeight * 0.5f, (float)-mHeight * 0.5f); +#else + mHalfHeight = _mmw_set1_ps((float)mHeight * 0.5f); + mIHalfSize = _mm_setr_ps((float)mWidth * 0.5f, (float)mWidth * 0.5f, (float)mHeight * 0.5f, (float)mHeight * 0.5f); +#endif + mIScreenSize = _mm_setr_epi32(mWidth - 1, mWidth - 1, mHeight - 1, mHeight - 1); + + // Setup a full screen scissor rectangle + mFullscreenScissor.mMinX = 0; + mFullscreenScissor.mMinY = 0; + mFullscreenScissor.mMaxX = mTilesWidth << TILE_WIDTH_SHIFT; + mFullscreenScissor.mMaxY = mTilesHeight << TILE_HEIGHT_SHIFT; + + // Adjust clip planes to include a small guard band to avoid clipping leaks + if (mWidth > 0.0f && mHeight > 0.0f) + { + float guardBandWidth = (2.0f / (float)mWidth) * GUARD_BAND_PIXEL_SIZE; + float guardBandHeight = (2.0f / (float)mHeight) * GUARD_BAND_PIXEL_SIZE; + mCSFrustumPlanes[1] = _mm_setr_ps(1.0f - guardBandWidth, 0.0f, 1.0f, 0.0f); + mCSFrustumPlanes[2] = _mm_setr_ps(-1.0f + guardBandWidth, 0.0f, 1.0f, 0.0f); + mCSFrustumPlanes[3] = _mm_setr_ps(0.0f, 1.0f - guardBandHeight, 1.0f, 0.0f); + mCSFrustumPlanes[4] = _mm_setr_ps(0.0f, -1.0f + guardBandHeight, 1.0f, 0.0f); + } + + // Allocate masked hierarchical Z buffer (if zero size leave at nullptr) + if(mTilesWidth * mTilesHeight > 0) + mMaskedHiZBuffer = (ZTile *)mAlignedAllocCallback(64, sizeof(ZTile) * mTilesWidth * mTilesHeight); + } + + void GetResolution(unsigned int &width, unsigned int &height) const override + { + width = mWidth; + height = mHeight; + } + + void ComputeBinWidthHeight(unsigned int nBinsW, unsigned int nBinsH, unsigned int & outBinWidth, unsigned int & outBinHeight) override + { + outBinWidth = (mWidth / nBinsW) - ((mWidth / nBinsW) % TILE_WIDTH); + outBinHeight = (mHeight / nBinsH) - ((mHeight / nBinsH) % TILE_HEIGHT); + } + + void SetNearClipPlane(float nearDist) override + { + // Setup the near frustum plane + mNearDist = nearDist; + mCSFrustumPlanes[0] = _mm_setr_ps(0.0f, 0.0f, 1.0f, -nearDist); + } + + float GetNearClipPlane() const override + { + return mNearDist; + } + + void ClearBuffer() override + { + assert(mMaskedHiZBuffer != nullptr); + + // Iterate through all depth tiles and clear to default values + for (int i = 0; i < mTilesWidth * mTilesHeight; i++) + { + mMaskedHiZBuffer[i].mMask = _mmw_setzero_epi32(); + + // Clear z0 to beyond infinity to ensure we never merge with clear data + mMaskedHiZBuffer[i].mZMin[0] = _mmw_set1_ps(-1.0f); +#if QUICK_MASK != 0 + // Clear z1 to nearest depth value as it is pushed back on each update + mMaskedHiZBuffer[i].mZMin[1] = _mmw_set1_ps(FLT_MAX); +#else + mMaskedHiZBuffer[i].mZMin[1] = _mmw_setzero_ps(); +#endif + } + +#if ENABLE_STATS != 0 + memset(&mStats, 0, sizeof(OcclusionCullingStatistics)); +#endif + +#if MOC_RECORDER_ENABLE != 0 + { + std::lock_guard lock( mRecorderMutex ); + if( mRecorder != nullptr ) mRecorder->RecordClearBuffer(); + } +#endif + } + + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // MergeBuffer + // Utility Function merges another MOC buffer into the existing one + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + void MergeBuffer(MaskedOcclusionCulling* BufferB) override + { + assert(mMaskedHiZBuffer != nullptr); + + //// Iterate through all depth tiles and merge the 2 tiles + for (int i = 0; i < mTilesWidth * mTilesHeight; i++) + { + __mw *zMinB = ((MaskedOcclusionCullingPrivate*)BufferB)->mMaskedHiZBuffer[i].mZMin; + __mw *zMinA = mMaskedHiZBuffer[i].mZMin; + __mwi RastMaskB = ((MaskedOcclusionCullingPrivate*)BufferB)->mMaskedHiZBuffer[i].mMask; + +#if QUICK_MASK != 0 + // Clear z0 to beyond infinity to ensure we never merge with clear data + __mwi sign0 = _mmw_srai_epi32(simd_cast<__mwi>(zMinB[0]), 31); + // Only merge tiles that have data in zMinB[0], use the sign bit to determine if they are still in a clear state + sign0 = _mmw_cmpeq_epi32(sign0, SIMD_BITS_ZERO); + if (!_mmw_testz_epi32(sign0, sign0)) + { + STATS_ADD(mStats.mOccluders.mNumTilesMerged, 1); + zMinA[0] = _mmw_max_ps(zMinA[0], zMinB[0]); + + __mwi rastMask = mMaskedHiZBuffer[i].mMask; + __mwi deadLane = _mmw_cmpeq_epi32(rastMask, SIMD_BITS_ZERO); + // Mask out all subtiles failing the depth test (don't update these subtiles) + deadLane = _mmw_or_epi32(deadLane, _mmw_srai_epi32(simd_cast<__mwi>(_mmw_sub_ps(zMinA[1], zMinA[0])), 31)); + mMaskedHiZBuffer[i].mMask = _mmw_andnot_epi32(deadLane, rastMask); + } + + // Set 32bit value to -1 if any pixels are set incide the coverage mask for a subtile + __mwi LiveTile = _mmw_cmpeq_epi32(RastMaskB, SIMD_BITS_ZERO); + // invert to have bits set for clear subtiles + __mwi t0inv = _mmw_not_epi32(LiveTile); + // VPTEST sets the ZF flag if all the resulting bits are 0 (ie if all tiles are clear) + if (!_mmw_testz_epi32(t0inv, t0inv)) + { + STATS_ADD(mStats.mOccluders.mNumTilesMerged, 1); + UpdateTileQuick(i, RastMaskB, zMinB[1]); + } +#else + // Clear z0 to beyond infinity to ensure we never merge with clear data + __mwi sign1 = _mmw_srai_epi32(simd_cast<__mwi>(mMaskedHiZBuffer[i].mZMin[0]), 31); + // Only merge tiles that have data in zMinB[0], use the sign bit to determine if they are still in a clear state + sign1 = _mmw_cmpeq_epi32(sign1, SIMD_BITS_ZERO); + + // Set 32bit value to -1 if any pixels are set incide the coverage mask for a subtile + __mwi LiveTile1 = _mmw_cmpeq_epi32(mMaskedHiZBuffer[i].mMask, SIMD_BITS_ZERO); + // invert to have bits set for clear subtiles + __mwi t1inv = _mmw_not_epi32(LiveTile1); + // VPTEST sets the ZF flag if all the resulting bits are 0 (ie if all tiles are clear) + if (_mmw_testz_epi32(sign1, sign1) && _mmw_testz_epi32(t1inv, t1inv)) + { + mMaskedHiZBuffer[i].mMask = ((MaskedOcclusionCullingPrivate*)BufferB)->mMaskedHiZBuffer[i].mMask; + mMaskedHiZBuffer[i].mZMin[0] = zMinB[0]; + mMaskedHiZBuffer[i].mZMin[1] = zMinB[1]; + } + else + { + // Clear z0 to beyond infinity to ensure we never merge with clear data + __mwi sign0 = _mmw_srai_epi32(simd_cast<__mwi>(zMinB[0]), 31); + sign0 = _mmw_cmpeq_epi32(sign0, SIMD_BITS_ZERO); + // Only merge tiles that have data in zMinB[0], use the sign bit to determine if they are still in a clear state + if (!_mmw_testz_epi32(sign0, sign0)) + { + // build a mask for Zmin[0], full if the layer has been completed, or partial if tile is still partly filled. + // cant just use the completement of the mask, as tiles might not get updated by merge + __mwi sign1 = _mmw_srai_epi32(simd_cast<__mwi>(zMinB[1]), 31); + __mwi LayerMask0 = _mmw_not_epi32(sign1); + __mwi LayerMask1 = _mmw_not_epi32(((MaskedOcclusionCullingPrivate*)BufferB)->mMaskedHiZBuffer[i].mMask); + __mwi rastMask = _mmw_or_epi32(LayerMask0, LayerMask1); + + UpdateTileAccurate(i, rastMask, zMinB[0]); + } + + // Set 32bit value to -1 if any pixels are set incide the coverage mask for a subtile + __mwi LiveTile = _mmw_cmpeq_epi32(((MaskedOcclusionCullingPrivate*)BufferB)->mMaskedHiZBuffer[i].mMask, SIMD_BITS_ZERO); + // invert to have bits set for clear subtiles + __mwi t0inv = _mmw_not_epi32(LiveTile); + // VPTEST sets the ZF flag if all the resulting bits are 0 (ie if all tiles are clear) + if (!_mmw_testz_epi32(t0inv, t0inv)) + { + UpdateTileAccurate(i, ((MaskedOcclusionCullingPrivate*)BufferB)->mMaskedHiZBuffer[i].mMask, zMinB[1]); + } + + //if (_mmw_testz_epi32(sign0, sign0) && _mmw_testz_epi32(t0inv, t0inv)) + // STATS_ADD(mStats.mOccluders.mNumTilesMerged, 1); + + } + +#endif + } + } + + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Polygon clipping functions + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + FORCE_INLINE int ClipPolygon(__m128 *outVtx, __m128 *inVtx, const __m128 &plane, int n) const + { + __m128 p0 = inVtx[n - 1]; + __m128 dist0 = _mmx_dp4_ps(p0, plane); + + // Loop over all polygon edges and compute intersection with clip plane (if any) + int nout = 0; + for (int k = 0; k < n; k++) + { + __m128 p1 = inVtx[k]; + __m128 dist1 = _mmx_dp4_ps(p1, plane); + int dist0Neg = _mm_movemask_ps(dist0); + if (!dist0Neg) // dist0 > 0.0f + outVtx[nout++] = p0; + + // Edge intersects the clip plane if dist0 and dist1 have opposing signs + if (_mm_movemask_ps(_mm_xor_ps(dist0, dist1))) + { + // Always clip from the positive side to avoid T-junctions + if (!dist0Neg) + { + __m128 t = _mm_div_ps(dist0, _mm_sub_ps(dist0, dist1)); + outVtx[nout++] = _mmx_fmadd_ps(_mm_sub_ps(p1, p0), t, p0); + } + else + { + __m128 t = _mm_div_ps(dist1, _mm_sub_ps(dist1, dist0)); + outVtx[nout++] = _mmx_fmadd_ps(_mm_sub_ps(p0, p1), t, p1); + } + } + + dist0 = dist1; + p0 = p1; + } + return nout; + } + + template void TestClipPlane(__mw *vtxX, __mw *vtxY, __mw *vtxW, unsigned int &straddleMask, unsigned int &triMask, ClipPlanes clipPlaneMask) + { + straddleMask = 0; + // Skip masked clip planes + if (!(clipPlaneMask & CLIP_PLANE)) + return; + + // Evaluate all 3 vertices against the frustum plane + __mw planeDp[3]; + for (int i = 0; i < 3; ++i) + { + switch (CLIP_PLANE) + { + case ClipPlanes::CLIP_PLANE_LEFT: planeDp[i] = _mmw_add_ps(vtxW[i], vtxX[i]); break; + case ClipPlanes::CLIP_PLANE_RIGHT: planeDp[i] = _mmw_sub_ps(vtxW[i], vtxX[i]); break; + case ClipPlanes::CLIP_PLANE_BOTTOM: planeDp[i] = _mmw_add_ps(vtxW[i], vtxY[i]); break; + case ClipPlanes::CLIP_PLANE_TOP: planeDp[i] = _mmw_sub_ps(vtxW[i], vtxY[i]); break; + case ClipPlanes::CLIP_PLANE_NEAR: planeDp[i] = _mmw_sub_ps(vtxW[i], _mmw_set1_ps(mNearDist)); break; + } + } + + // Look at FP sign and determine if tri is inside, outside or straddles the frustum plane + __mw inside = _mmw_andnot_ps(planeDp[0], _mmw_andnot_ps(planeDp[1], _mmw_not_ps(planeDp[2]))); + __mw outside = _mmw_and_ps(planeDp[0], _mmw_and_ps(planeDp[1], planeDp[2])); + unsigned int inMask = (unsigned int)_mmw_movemask_ps(inside); + unsigned int outMask = (unsigned int)_mmw_movemask_ps(outside); + straddleMask = (~outMask) & (~inMask); + triMask &= ~outMask; + } + + FORCE_INLINE void ClipTriangleAndAddToBuffer(__mw *vtxX, __mw *vtxY, __mw *vtxW, __m128 *clippedTrisBuffer, int &clipWriteIdx, unsigned int &triMask, unsigned int triClipMask, ClipPlanes clipPlaneMask) + { + if (!triClipMask) + return; + + // Inside test all 3 triangle vertices against all active frustum planes + unsigned int straddleMask[5]; + TestClipPlane(vtxX, vtxY, vtxW, straddleMask[0], triMask, clipPlaneMask); + TestClipPlane(vtxX, vtxY, vtxW, straddleMask[1], triMask, clipPlaneMask); + TestClipPlane(vtxX, vtxY, vtxW, straddleMask[2], triMask, clipPlaneMask); + TestClipPlane(vtxX, vtxY, vtxW, straddleMask[3], triMask, clipPlaneMask); + TestClipPlane(vtxX, vtxY, vtxW, straddleMask[4], triMask, clipPlaneMask); + + // Clip triangle against straddling planes and add to the clipped triangle buffer + __m128 vtxBuf[2][8]; + +#if CLIPPING_PRESERVES_ORDER != 0 + unsigned int clipMask = triClipMask & triMask; + unsigned int clipAndStraddleMask = (straddleMask[0] | straddleMask[1] | straddleMask[2] | straddleMask[3] | straddleMask[4]) & clipMask; + // no clipping needed after all - early out + if (clipAndStraddleMask == 0) + return; + while( clipMask ) + { + // Find and setup next triangle to clip + unsigned int triIdx = find_clear_lsb(&clipMask); + unsigned int triBit = (1U << triIdx); + assert(triIdx < SIMD_LANES); + + int bufIdx = 0; + int nClippedVerts = 3; + for (int i = 0; i < 3; i++) + vtxBuf[0][i] = _mm_setr_ps(simd_f32(vtxX[i])[triIdx], simd_f32(vtxY[i])[triIdx], simd_f32(vtxW[i])[triIdx], 1.0f); + + // Clip triangle with straddling planes. + for (int i = 0; i < 5; ++i) + { + if ((straddleMask[i] & triBit) && (clipPlaneMask & (1 << i))) // <- second part maybe not needed? + { + nClippedVerts = ClipPolygon(vtxBuf[bufIdx ^ 1], vtxBuf[bufIdx], mCSFrustumPlanes[i], nClippedVerts); + bufIdx ^= 1; + } + } + + if (nClippedVerts >= 3) + { + // Write all triangles into the clip buffer and process them next loop iteration + clippedTrisBuffer[clipWriteIdx * 3 + 0] = vtxBuf[bufIdx][0]; + clippedTrisBuffer[clipWriteIdx * 3 + 1] = vtxBuf[bufIdx][1]; + clippedTrisBuffer[clipWriteIdx * 3 + 2] = vtxBuf[bufIdx][2]; + clipWriteIdx = (clipWriteIdx + 1) & (MAX_CLIPPED - 1); + for (int i = 2; i < nClippedVerts - 1; i++) + { + clippedTrisBuffer[clipWriteIdx * 3 + 0] = vtxBuf[bufIdx][0]; + clippedTrisBuffer[clipWriteIdx * 3 + 1] = vtxBuf[bufIdx][i]; + clippedTrisBuffer[clipWriteIdx * 3 + 2] = vtxBuf[bufIdx][i + 1]; + clipWriteIdx = (clipWriteIdx + 1) & (MAX_CLIPPED - 1); + } + } + } + // since all triangles were copied to clip buffer for next iteration, skip further processing + triMask = 0; +#else + unsigned int clipMask = (straddleMask[0] | straddleMask[1] | straddleMask[2] | straddleMask[3] | straddleMask[4]) & (triClipMask & triMask); + while (clipMask) + { + // Find and setup next triangle to clip + unsigned int triIdx = find_clear_lsb(&clipMask); + unsigned int triBit = (1U << triIdx); + assert(triIdx < SIMD_LANES); + + int bufIdx = 0; + int nClippedVerts = 3; + for (int i = 0; i < 3; i++) + vtxBuf[0][i] = _mm_setr_ps(simd_f32(vtxX[i])[triIdx], simd_f32(vtxY[i])[triIdx], simd_f32(vtxW[i])[triIdx], 1.0f); + + // Clip triangle with straddling planes. + for (int i = 0; i < 5; ++i) + { + if ((straddleMask[i] & triBit) && (clipPlaneMask & (1 << i))) + { + nClippedVerts = ClipPolygon(vtxBuf[bufIdx ^ 1], vtxBuf[bufIdx], mCSFrustumPlanes[i], nClippedVerts); + bufIdx ^= 1; + } + } + + if (nClippedVerts >= 3) + { + // Write the first triangle back into the list of currently processed triangles + for (int i = 0; i < 3; i++) + { + simd_f32(vtxX[i])[triIdx] = simd_f32(vtxBuf[bufIdx][i])[0]; + simd_f32(vtxY[i])[triIdx] = simd_f32(vtxBuf[bufIdx][i])[1]; + simd_f32(vtxW[i])[triIdx] = simd_f32(vtxBuf[bufIdx][i])[2]; + } + // Write the remaining triangles into the clip buffer and process them next loop iteration + for (int i = 2; i < nClippedVerts - 1; i++) + { + clippedTrisBuffer[clipWriteIdx * 3 + 0] = vtxBuf[bufIdx][0]; + clippedTrisBuffer[clipWriteIdx * 3 + 1] = vtxBuf[bufIdx][i]; + clippedTrisBuffer[clipWriteIdx * 3 + 2] = vtxBuf[bufIdx][i + 1]; + clipWriteIdx = (clipWriteIdx + 1) & (MAX_CLIPPED - 1); + } + } + else // Kill triangles that was removed by clipping + triMask &= ~triBit; + } +#endif + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Vertex transform & projection + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + FORCE_INLINE void TransformVerts(__mw *vtxX, __mw *vtxY, __mw *vtxW, const float *modelToClipMatrix) + { + if (modelToClipMatrix != nullptr) + { + for (int i = 0; i < 3; ++i) + { + __mw tmpX, tmpY, tmpW; + tmpX = _mmw_fmadd_ps(vtxX[i], _mmw_set1_ps(modelToClipMatrix[0]), _mmw_fmadd_ps(vtxY[i], _mmw_set1_ps(modelToClipMatrix[4]), _mmw_fmadd_ps(vtxW[i], _mmw_set1_ps(modelToClipMatrix[8]), _mmw_set1_ps(modelToClipMatrix[12])))); + tmpY = _mmw_fmadd_ps(vtxX[i], _mmw_set1_ps(modelToClipMatrix[1]), _mmw_fmadd_ps(vtxY[i], _mmw_set1_ps(modelToClipMatrix[5]), _mmw_fmadd_ps(vtxW[i], _mmw_set1_ps(modelToClipMatrix[9]), _mmw_set1_ps(modelToClipMatrix[13])))); + tmpW = _mmw_fmadd_ps(vtxX[i], _mmw_set1_ps(modelToClipMatrix[3]), _mmw_fmadd_ps(vtxY[i], _mmw_set1_ps(modelToClipMatrix[7]), _mmw_fmadd_ps(vtxW[i], _mmw_set1_ps(modelToClipMatrix[11]), _mmw_set1_ps(modelToClipMatrix[15])))); + vtxX[i] = tmpX; vtxY[i] = tmpY; vtxW[i] = tmpW; + } + } + } + +#if PRECISE_COVERAGE != 0 + FORCE_INLINE void ProjectVertices(__mwi *ipVtxX, __mwi *ipVtxY, __mw *pVtxX, __mw *pVtxY, __mw *pVtxZ, const __mw *vtxX, const __mw *vtxY, const __mw *vtxW) + { +#if USE_D3D != 0 + static const int vertexOrder[] = {2, 1, 0}; +#else + static const int vertexOrder[] = {0, 1, 2}; +#endif + + // Project vertices and transform to screen space. Snap to sub-pixel coordinates with FP_BITS precision. + for (int i = 0; i < 3; i++) + { + int idx = vertexOrder[i]; + __mw rcpW = _mmw_div_ps(_mmw_set1_ps(1.0f), vtxW[i]); + __mw screenX = _mmw_fmadd_ps(_mmw_mul_ps(vtxX[i], mHalfWidth), rcpW, mCenterX); + __mw screenY = _mmw_fmadd_ps(_mmw_mul_ps(vtxY[i], mHalfHeight), rcpW, mCenterY); + ipVtxX[idx] = _mmw_cvtps_epi32(_mmw_mul_ps(screenX, _mmw_set1_ps(float(1 << FP_BITS)))); + ipVtxY[idx] = _mmw_cvtps_epi32(_mmw_mul_ps(screenY, _mmw_set1_ps(float(1 << FP_BITS)))); + pVtxX[idx] = _mmw_mul_ps(_mmw_cvtepi32_ps(ipVtxX[idx]), _mmw_set1_ps(FP_INV)); + pVtxY[idx] = _mmw_mul_ps(_mmw_cvtepi32_ps(ipVtxY[idx]), _mmw_set1_ps(FP_INV)); + pVtxZ[idx] = rcpW; + } + } +#else + FORCE_INLINE void ProjectVertices(__mw *pVtxX, __mw *pVtxY, __mw *pVtxZ, const __mw *vtxX, const __mw *vtxY, const __mw *vtxW) + { +#if USE_D3D != 0 + static const int vertexOrder[] = {2, 1, 0}; +#else + static const int vertexOrder[] = {0, 1, 2}; +#endif + // Project vertices and transform to screen space. Round to nearest integer pixel coordinate + for (int i = 0; i < 3; i++) + { + int idx = vertexOrder[i]; + __mw rcpW = _mmw_div_ps(_mmw_set1_ps(1.0f), vtxW[i]); + + // The rounding modes are set to match HW rasterization with OpenGL. In practice our samples are placed + // in the (1,0) corner of each pixel, while HW rasterizer uses (0.5, 0.5). We get (1,0) because of the + // floor used when interpolating along triangle edges. The rounding modes match an offset of (0.5, -0.5) + pVtxX[idx] = _mmw_ceil_ps(_mmw_fmadd_ps(_mmw_mul_ps(vtxX[i], mHalfWidth), rcpW, mCenterX)); + pVtxY[idx] = _mmw_floor_ps(_mmw_fmadd_ps(_mmw_mul_ps(vtxY[i], mHalfHeight), rcpW, mCenterY)); + pVtxZ[idx] = rcpW; + } + } +#endif + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Common SSE/AVX input assembly functions, note that there are specialized gathers for the general case in the SSE/AVX specific files + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + FORCE_INLINE void GatherVerticesFast(__mw *vtxX, __mw *vtxY, __mw *vtxW, const float *inVtx, const unsigned int *inTrisPtr, int numLanes) + { + // This function assumes that the vertex layout is four packed x, y, z, w-values. + // Since the layout is known we can get some additional performance by using a + // more optimized gather strategy. + assert(numLanes >= 1); + + // Gather vertices + __mw v[4], swz[4]; + for (int i = 0; i < 3; i++) + { + // Load 4 (x,y,z,w) vectors per SSE part of the SIMD register (so 4 vectors for SSE, 8 vectors for AVX) + // this fetch uses templates to unroll the loop + VtxFetch4(v, inTrisPtr, i, inVtx, numLanes); + + // Transpose each individual SSE part of the SSE/AVX register (similar to _MM_TRANSPOSE4_PS) + swz[0] = _mmw_shuffle_ps(v[0], v[1], 0x44); + swz[2] = _mmw_shuffle_ps(v[0], v[1], 0xEE); + swz[1] = _mmw_shuffle_ps(v[2], v[3], 0x44); + swz[3] = _mmw_shuffle_ps(v[2], v[3], 0xEE); + + vtxX[i] = _mmw_shuffle_ps(swz[0], swz[1], 0x88); + vtxY[i] = _mmw_shuffle_ps(swz[0], swz[1], 0xDD); + vtxW[i] = _mmw_shuffle_ps(swz[2], swz[3], 0xDD); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Rasterization functions + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + FORCE_INLINE void ComputeBoundingBox(__mwi &bbminX, __mwi &bbminY, __mwi &bbmaxX, __mwi &bbmaxY, const __mw *vX, const __mw *vY, const ScissorRect *scissor) + { + static const __mwi SIMD_PAD_W_MASK = _mmw_set1_epi32(~(TILE_WIDTH - 1)); + static const __mwi SIMD_PAD_H_MASK = _mmw_set1_epi32(~(TILE_HEIGHT - 1)); + + // Find Min/Max vertices + bbminX = _mmw_cvttps_epi32(_mmw_min_ps(vX[0], _mmw_min_ps(vX[1], vX[2]))); + bbminY = _mmw_cvttps_epi32(_mmw_min_ps(vY[0], _mmw_min_ps(vY[1], vY[2]))); + bbmaxX = _mmw_cvttps_epi32(_mmw_max_ps(vX[0], _mmw_max_ps(vX[1], vX[2]))); + bbmaxY = _mmw_cvttps_epi32(_mmw_max_ps(vY[0], _mmw_max_ps(vY[1], vY[2]))); + + // Clamp to tile boundaries + bbminX = _mmw_and_epi32(bbminX, SIMD_PAD_W_MASK); + bbmaxX = _mmw_and_epi32(_mmw_add_epi32(bbmaxX, _mmw_set1_epi32(TILE_WIDTH)), SIMD_PAD_W_MASK); + bbminY = _mmw_and_epi32(bbminY, SIMD_PAD_H_MASK); + bbmaxY = _mmw_and_epi32(_mmw_add_epi32(bbmaxY, _mmw_set1_epi32(TILE_HEIGHT)), SIMD_PAD_H_MASK); + + // Clip to scissor + bbminX = _mmw_max_epi32(bbminX, _mmw_set1_epi32(scissor->mMinX)); + bbmaxX = _mmw_min_epi32(bbmaxX, _mmw_set1_epi32(scissor->mMaxX)); + bbminY = _mmw_max_epi32(bbminY, _mmw_set1_epi32(scissor->mMinY)); + bbmaxY = _mmw_min_epi32(bbmaxY, _mmw_set1_epi32(scissor->mMaxY)); + } + +#if PRECISE_COVERAGE != 0 + FORCE_INLINE void SortVertices(__mwi *vX, __mwi *vY) + { + // Rotate the triangle in the winding order until v0 is the vertex with lowest Y value + for (int i = 0; i < 2; i++) + { + __mwi ey1 = _mmw_sub_epi32(vY[1], vY[0]); + __mwi ey2 = _mmw_sub_epi32(vY[2], vY[0]); + __mwi swapMask = _mmw_or_epi32(_mmw_or_epi32(ey1, ey2), _mmw_cmpeq_epi32(simd_cast<__mwi>(ey2), SIMD_BITS_ZERO)); + __mwi sX, sY; + sX = _mmw_blendv_epi32(vX[2], vX[0], swapMask); + vX[0] = _mmw_blendv_epi32(vX[0], vX[1], swapMask); + vX[1] = _mmw_blendv_epi32(vX[1], vX[2], swapMask); + vX[2] = sX; + sY = _mmw_blendv_epi32(vY[2], vY[0], swapMask); + vY[0] = _mmw_blendv_epi32(vY[0], vY[1], swapMask); + vY[1] = _mmw_blendv_epi32(vY[1], vY[2], swapMask); + vY[2] = sY; + } + } + + FORCE_INLINE int CullBackfaces(__mwi *ipVtxX, __mwi *ipVtxY, __mw *pVtxX, __mw *pVtxY, __mw *pVtxZ, const __mw &ccwMask, BackfaceWinding bfWinding) + { + // Reverse vertex order if non cw faces are considered front facing (rasterizer code requires CCW order) + if (!(bfWinding & BACKFACE_CW)) + { + __mw tmpX, tmpY, tmpZ; + __mwi itmpX, itmpY; + itmpX = _mmw_blendv_epi32(ipVtxX[2], ipVtxX[0], simd_cast<__mwi>(ccwMask)); + itmpY = _mmw_blendv_epi32(ipVtxY[2], ipVtxY[0], simd_cast<__mwi>(ccwMask)); + tmpX = _mmw_blendv_ps(pVtxX[2], pVtxX[0], ccwMask); + tmpY = _mmw_blendv_ps(pVtxY[2], pVtxY[0], ccwMask); + tmpZ = _mmw_blendv_ps(pVtxZ[2], pVtxZ[0], ccwMask); + ipVtxX[2] = _mmw_blendv_epi32(ipVtxX[0], ipVtxX[2], simd_cast<__mwi>(ccwMask)); + ipVtxY[2] = _mmw_blendv_epi32(ipVtxY[0], ipVtxY[2], simd_cast<__mwi>(ccwMask)); + pVtxX[2] = _mmw_blendv_ps(pVtxX[0], pVtxX[2], ccwMask); + pVtxY[2] = _mmw_blendv_ps(pVtxY[0], pVtxY[2], ccwMask); + pVtxZ[2] = _mmw_blendv_ps(pVtxZ[0], pVtxZ[2], ccwMask); + ipVtxX[0] = itmpX; + ipVtxY[0] = itmpY; + pVtxX[0] = tmpX; + pVtxY[0] = tmpY; + pVtxZ[0] = tmpZ; + } + + // Return a lane mask with all front faces set + return ((bfWinding & BACKFACE_CCW) ? 0 : _mmw_movemask_ps(ccwMask)) | ((bfWinding & BACKFACE_CW) ? 0 : ~_mmw_movemask_ps(ccwMask)); + } +#else + FORCE_INLINE void SortVertices(__mw *vX, __mw *vY) + { + // Rotate the triangle in the winding order until v0 is the vertex with lowest Y value + for (int i = 0; i < 2; i++) + { + __mw ey1 = _mmw_sub_ps(vY[1], vY[0]); + __mw ey2 = _mmw_sub_ps(vY[2], vY[0]); + __mw swapMask = _mmw_or_ps(_mmw_or_ps(ey1, ey2), simd_cast<__mw>(_mmw_cmpeq_epi32(simd_cast<__mwi>(ey2), SIMD_BITS_ZERO))); + __mw sX, sY; + sX = _mmw_blendv_ps(vX[2], vX[0], swapMask); + vX[0] = _mmw_blendv_ps(vX[0], vX[1], swapMask); + vX[1] = _mmw_blendv_ps(vX[1], vX[2], swapMask); + vX[2] = sX; + sY = _mmw_blendv_ps(vY[2], vY[0], swapMask); + vY[0] = _mmw_blendv_ps(vY[0], vY[1], swapMask); + vY[1] = _mmw_blendv_ps(vY[1], vY[2], swapMask); + vY[2] = sY; + } + } + + FORCE_INLINE int CullBackfaces(__mw *pVtxX, __mw *pVtxY, __mw *pVtxZ, const __mw &ccwMask, BackfaceWinding bfWinding) + { + // Reverse vertex order if non cw faces are considered front facing (rasterizer code requires CCW order) + if (!(bfWinding & BACKFACE_CW)) + { + __mw tmpX, tmpY, tmpZ; + tmpX = _mmw_blendv_ps(pVtxX[2], pVtxX[0], ccwMask); + tmpY = _mmw_blendv_ps(pVtxY[2], pVtxY[0], ccwMask); + tmpZ = _mmw_blendv_ps(pVtxZ[2], pVtxZ[0], ccwMask); + pVtxX[2] = _mmw_blendv_ps(pVtxX[0], pVtxX[2], ccwMask); + pVtxY[2] = _mmw_blendv_ps(pVtxY[0], pVtxY[2], ccwMask); + pVtxZ[2] = _mmw_blendv_ps(pVtxZ[0], pVtxZ[2], ccwMask); + pVtxX[0] = tmpX; + pVtxY[0] = tmpY; + pVtxZ[0] = tmpZ; + } + + // Return a lane mask with all front faces set + return ((bfWinding & BACKFACE_CCW) ? 0 : _mmw_movemask_ps(ccwMask)) | ((bfWinding & BACKFACE_CW) ? 0 : ~_mmw_movemask_ps(ccwMask)); + } +#endif + + FORCE_INLINE void ComputeDepthPlane(const __mw *pVtxX, const __mw *pVtxY, const __mw *pVtxZ, __mw &zPixelDx, __mw &zPixelDy) const + { + // Setup z(x,y) = z0 + dx*x + dy*y screen space depth plane equation + __mw x2 = _mmw_sub_ps(pVtxX[2], pVtxX[0]); + __mw x1 = _mmw_sub_ps(pVtxX[1], pVtxX[0]); + __mw y1 = _mmw_sub_ps(pVtxY[1], pVtxY[0]); + __mw y2 = _mmw_sub_ps(pVtxY[2], pVtxY[0]); + __mw z1 = _mmw_sub_ps(pVtxZ[1], pVtxZ[0]); + __mw z2 = _mmw_sub_ps(pVtxZ[2], pVtxZ[0]); + __mw d = _mmw_div_ps(_mmw_set1_ps(1.0f), _mmw_fmsub_ps(x1, y2, _mmw_mul_ps(y1, x2))); + zPixelDx = _mmw_mul_ps(_mmw_fmsub_ps(z1, y2, _mmw_mul_ps(y1, z2)), d); + zPixelDy = _mmw_mul_ps(_mmw_fmsub_ps(x1, z2, _mmw_mul_ps(z1, x2)), d); + } + + FORCE_INLINE void UpdateTileQuick(int tileIdx, const __mwi &coverage, const __mw &zTriv) + { + // Update heuristic used in the paper "Masked Software Occlusion Culling", + // good balance between performance and accuracy + STATS_ADD(mStats.mOccluders.mNumTilesUpdated, 1); + assert(tileIdx >= 0 && tileIdx < mTilesWidth*mTilesHeight); + + __mwi mask = mMaskedHiZBuffer[tileIdx].mMask; + __mw *zMin = mMaskedHiZBuffer[tileIdx].mZMin; + + // Swizzle coverage mask to 8x4 subtiles and test if any subtiles are not covered at all + __mwi rastMask = coverage; + __mwi deadLane = _mmw_cmpeq_epi32(rastMask, SIMD_BITS_ZERO); + + // Mask out all subtiles failing the depth test (don't update these subtiles) + deadLane = _mmw_or_epi32(deadLane, _mmw_srai_epi32(simd_cast<__mwi>(_mmw_sub_ps(zTriv, zMin[0])), 31)); + rastMask = _mmw_andnot_epi32(deadLane, rastMask); + + // Use distance heuristic to discard layer 1 if incoming triangle is significantly nearer to observer + // than the buffer contents. See Section 3.2 in "Masked Software Occlusion Culling" + __mwi coveredLane = _mmw_cmpeq_epi32(rastMask, SIMD_BITS_ONE); + __mw diff = _mmw_fmsub_ps(zMin[1], _mmw_set1_ps(2.0f), _mmw_add_ps(zTriv, zMin[0])); + __mwi discardLayerMask = _mmw_andnot_epi32(deadLane, _mmw_or_epi32(_mmw_srai_epi32(simd_cast<__mwi>(diff), 31), coveredLane)); + + // Update the mask with incoming triangle coverage + mask = _mmw_or_epi32(_mmw_andnot_epi32(discardLayerMask, mask), rastMask); + + __mwi maskFull = _mmw_cmpeq_epi32(mask, SIMD_BITS_ONE); + + // Compute new value for zMin[1]. This has one of four outcomes: zMin[1] = min(zMin[1], zTriv), zMin[1] = zTriv, + // zMin[1] = FLT_MAX or unchanged, depending on if the layer is updated, discarded, fully covered, or not updated + __mw opA = _mmw_blendv_ps(zTriv, zMin[1], simd_cast<__mw>(deadLane)); + __mw opB = _mmw_blendv_ps(zMin[1], zTriv, simd_cast<__mw>(discardLayerMask)); + __mw z1min = _mmw_min_ps(opA, opB); + zMin[1] = _mmw_blendv_ps(z1min, _mmw_set1_ps(FLT_MAX), simd_cast<__mw>(maskFull)); + + // Propagate zMin[1] back to zMin[0] if tile was fully covered, and update the mask + zMin[0] = _mmw_blendv_ps(zMin[0], z1min, simd_cast<__mw>(maskFull)); + mMaskedHiZBuffer[tileIdx].mMask = _mmw_andnot_epi32(maskFull, mask); + } + + FORCE_INLINE void UpdateTileAccurate(int tileIdx, const __mwi &coverage, const __mw &zTriv) + { + assert(tileIdx >= 0 && tileIdx < mTilesWidth*mTilesHeight); + + __mw *zMin = mMaskedHiZBuffer[tileIdx].mZMin; + __mwi &mask = mMaskedHiZBuffer[tileIdx].mMask; + + // Swizzle coverage mask to 8x4 subtiles + __mwi rastMask = coverage; + + // Perform individual depth tests with layer 0 & 1 and mask out all failing pixels + __mw sdist0 = _mmw_sub_ps(zMin[0], zTriv); + __mw sdist1 = _mmw_sub_ps(zMin[1], zTriv); + __mwi sign0 = _mmw_srai_epi32(simd_cast<__mwi>(sdist0), 31); + __mwi sign1 = _mmw_srai_epi32(simd_cast<__mwi>(sdist1), 31); + __mwi triMask = _mmw_and_epi32(rastMask, _mmw_or_epi32(_mmw_andnot_epi32(mask, sign0), _mmw_and_epi32(mask, sign1))); + + // Early out if no pixels survived the depth test (this test is more accurate than + // the early culling test in TraverseScanline()) + __mwi t0 = _mmw_cmpeq_epi32(triMask, SIMD_BITS_ZERO); + __mwi t0inv = _mmw_not_epi32(t0); + if (_mmw_testz_epi32(t0inv, t0inv)) + return; + + STATS_ADD(mStats.mOccluders.mNumTilesUpdated, 1); + + __mw zTri = _mmw_blendv_ps(zTriv, zMin[0], simd_cast<__mw>(t0)); + + // Test if incoming triangle completely overwrites layer 0 or 1 + __mwi layerMask0 = _mmw_andnot_epi32(triMask, _mmw_not_epi32(mask)); + __mwi layerMask1 = _mmw_andnot_epi32(triMask, mask); + __mwi lm0 = _mmw_cmpeq_epi32(layerMask0, SIMD_BITS_ZERO); + __mwi lm1 = _mmw_cmpeq_epi32(layerMask1, SIMD_BITS_ZERO); + __mw z0 = _mmw_blendv_ps(zMin[0], zTri, simd_cast<__mw>(lm0)); + __mw z1 = _mmw_blendv_ps(zMin[1], zTri, simd_cast<__mw>(lm1)); + + // Compute distances used for merging heuristic + __mw d0 = _mmw_abs_ps(sdist0); + __mw d1 = _mmw_abs_ps(sdist1); + __mw d2 = _mmw_abs_ps(_mmw_sub_ps(z0, z1)); + + // Find minimum distance + __mwi c01 = simd_cast<__mwi>(_mmw_sub_ps(d0, d1)); + __mwi c02 = simd_cast<__mwi>(_mmw_sub_ps(d0, d2)); + __mwi c12 = simd_cast<__mwi>(_mmw_sub_ps(d1, d2)); + // Two tests indicating which layer the incoming triangle will merge with or + // overwrite. d0min indicates that the triangle will overwrite layer 0, and + // d1min flags that the triangle will overwrite layer 1. + __mwi d0min = _mmw_or_epi32(_mmw_and_epi32(c01, c02), _mmw_or_epi32(lm0, t0)); + __mwi d1min = _mmw_andnot_epi32(d0min, _mmw_or_epi32(c12, lm1)); + + /////////////////////////////////////////////////////////////////////////////// + // Update depth buffer entry. NOTE: we always merge into layer 0, so if the + // triangle should be merged with layer 1, we first swap layer 0 & 1 and then + // merge into layer 0. + /////////////////////////////////////////////////////////////////////////////// + + // Update mask based on which layer the triangle overwrites or was merged into + __mw inner = _mmw_blendv_ps(simd_cast<__mw>(triMask), simd_cast<__mw>(layerMask1), simd_cast<__mw>(d0min)); + mask = simd_cast<__mwi>(_mmw_blendv_ps(inner, simd_cast<__mw>(layerMask0), simd_cast<__mw>(d1min))); + + // Update the zMin[0] value. There are four outcomes: overwrite with layer 1, + // merge with layer 1, merge with zTri or overwrite with layer 1 and then merge + // with zTri. + __mw e0 = _mmw_blendv_ps(z0, z1, simd_cast<__mw>(d1min)); + __mw e1 = _mmw_blendv_ps(z1, zTri, simd_cast<__mw>(_mmw_or_epi32(d1min, d0min))); + zMin[0] = _mmw_min_ps(e0, e1); + + // Update the zMin[1] value. There are three outcomes: keep current value, + // overwrite with zTri, or overwrite with z1 + __mw z1t = _mmw_blendv_ps(zTri, z1, simd_cast<__mw>(d0min)); + zMin[1] = _mmw_blendv_ps(z1t, z0, simd_cast<__mw>(d1min)); + } + + template + FORCE_INLINE int TraverseScanline(int leftOffset, int rightOffset, int tileIdx, int rightEvent, int leftEvent, const __mwi *events, const __mw &zTriMin, const __mw &zTriMax, const __mw &iz0, float zx) + { + // Floor edge events to integer pixel coordinates (shift out fixed point bits) + int eventOffset = leftOffset << TILE_WIDTH_SHIFT; + __mwi right[NRIGHT], left[NLEFT]; + for (int i = 0; i < NRIGHT; ++i) + right[i] = _mmw_max_epi32(_mmw_sub_epi32(_mmw_srai_epi32(events[rightEvent + i], FP_BITS), _mmw_set1_epi32(eventOffset)), SIMD_BITS_ZERO); + for (int i = 0; i < NLEFT; ++i) + left[i] = _mmw_max_epi32(_mmw_sub_epi32(_mmw_srai_epi32(events[leftEvent - i], FP_BITS), _mmw_set1_epi32(eventOffset)), SIMD_BITS_ZERO); + + __mw z0 = _mmw_add_ps(iz0, _mmw_set1_ps(zx*leftOffset)); + int tileIdxEnd = tileIdx + rightOffset; + tileIdx += leftOffset; + for (;;) + { + if (TEST_Z) + STATS_ADD(mStats.mOccludees.mNumTilesTraversed, 1); + else + STATS_ADD(mStats.mOccluders.mNumTilesTraversed, 1); + + // Perform a coarse test to quickly discard occluded tiles +#if QUICK_MASK != 0 + // Only use the reference layer (layer 0) to cull as it is always conservative + __mw zMinBuf = mMaskedHiZBuffer[tileIdx].mZMin[0]; +#else + // Compute zMin for the overlapped layers + __mwi mask = mMaskedHiZBuffer[tileIdx].mMask; + __mw zMin0 = _mmw_blendv_ps(mMaskedHiZBuffer[tileIdx].mZMin[0], mMaskedHiZBuffer[tileIdx].mZMin[1], simd_cast<__mw>(_mmw_cmpeq_epi32(mask, _mmw_set1_epi32(~0)))); + __mw zMin1 = _mmw_blendv_ps(mMaskedHiZBuffer[tileIdx].mZMin[1], mMaskedHiZBuffer[tileIdx].mZMin[0], simd_cast<__mw>(_mmw_cmpeq_epi32(mask, _mmw_setzero_epi32()))); + __mw zMinBuf = _mmw_min_ps(zMin0, zMin1); +#endif + __mw dist0 = _mmw_sub_ps(zTriMax, zMinBuf); + if (_mmw_movemask_ps(dist0) != SIMD_ALL_LANES_MASK) + { + // Compute coverage mask for entire 32xN using shift operations + __mwi accumulatedMask = _mmw_sllv_ones(left[0]); + for (int i = 1; i < NLEFT; ++i) + accumulatedMask = _mmw_and_epi32(accumulatedMask, _mmw_sllv_ones(left[i])); + for (int i = 0; i < NRIGHT; ++i) + accumulatedMask = _mmw_andnot_epi32(_mmw_sllv_ones(right[i]), accumulatedMask); + + if (TEST_Z) + { + // Perform a conservative visibility test (test zMax against buffer for each covered 8x4 subtile) + __mw zSubTileMax = _mmw_min_ps(z0, zTriMax); + __mwi zPass = simd_cast<__mwi>(_mmw_cmpge_ps(zSubTileMax, zMinBuf)); + + __mwi rastMask = _mmw_transpose_epi8(accumulatedMask); + __mwi deadLane = _mmw_cmpeq_epi32(rastMask, SIMD_BITS_ZERO); + zPass = _mmw_andnot_epi32(deadLane, zPass); + + if (!_mmw_testz_epi32(zPass, zPass)) + return CullingResult::VISIBLE; + } + else + { + // Compute interpolated min for each 8x4 subtile and update the masked hierarchical z buffer entry + __mw zSubTileMin = _mmw_max_ps(z0, zTriMin); +#if QUICK_MASK != 0 + UpdateTileQuick(tileIdx, _mmw_transpose_epi8(accumulatedMask), zSubTileMin); +#else + UpdateTileAccurate(tileIdx, _mmw_transpose_epi8(accumulatedMask), zSubTileMin); +#endif + } + } + + // Update buffer address, interpolate z and edge events + tileIdx++; + if (tileIdx >= tileIdxEnd) + break; + z0 = _mmw_add_ps(z0, _mmw_set1_ps(zx)); + for (int i = 0; i < NRIGHT; ++i) + right[i] = _mmw_subs_epu16(right[i], SIMD_TILE_WIDTH); // Trick, use sub saturated to avoid checking against < 0 for shift (values should fit in 16 bits) + for (int i = 0; i < NLEFT; ++i) + left[i] = _mmw_subs_epu16(left[i], SIMD_TILE_WIDTH); + } + + return TEST_Z ? CullingResult::OCCLUDED : CullingResult::VISIBLE; + } + + + template +#if PRECISE_COVERAGE != 0 + FORCE_INLINE int RasterizeTriangle(unsigned int triIdx, int bbWidth, int tileRowIdx, int tileMidRowIdx, int tileEndRowIdx, const __mwi *eventStart, const __mw *slope, const __mwi *slopeTileDelta, const __mw &zTriMin, const __mw &zTriMax, __mw &z0, float zx, float zy, const __mwi *edgeY, const __mwi *absEdgeX, const __mwi *slopeSign, const __mwi *eventStartRemainder, const __mwi *slopeTileRemainder) +#else + FORCE_INLINE int RasterizeTriangle(unsigned int triIdx, int bbWidth, int tileRowIdx, int tileMidRowIdx, int tileEndRowIdx, const __mwi *eventStart, const __mwi *slope, const __mwi *slopeTileDelta, const __mw &zTriMin, const __mw &zTriMax, __mw &z0, float zx, float zy) +#endif + { + if (TEST_Z) + STATS_ADD(mStats.mOccludees.mNumRasterizedTriangles, 1); + else + STATS_ADD(mStats.mOccluders.mNumRasterizedTriangles, 1); + + int cullResult; + +#if PRECISE_COVERAGE != 0 + #define LEFT_EDGE_BIAS -1 + #define RIGHT_EDGE_BIAS 1 + #define UPDATE_TILE_EVENTS_Y(i) \ + triEventRemainder[i] = _mmw_sub_epi32(triEventRemainder[i], triSlopeTileRemainder[i]); \ + __mwi overflow##i = _mmw_srai_epi32(triEventRemainder[i], 31); \ + triEventRemainder[i] = _mmw_add_epi32(triEventRemainder[i], _mmw_and_epi32(overflow##i, triEdgeY[i])); \ + triEvent[i] = _mmw_add_epi32(triEvent[i], _mmw_add_epi32(triSlopeTileDelta[i], _mmw_and_epi32(overflow##i, triSlopeSign[i]))) + + __mwi triEvent[3], triSlopeSign[3], triSlopeTileDelta[3], triEdgeY[3], triSlopeTileRemainder[3], triEventRemainder[3]; + for (int i = 0; i < 3; ++i) + { + triSlopeSign[i] = _mmw_set1_epi32(simd_i32(slopeSign[i])[triIdx]); + triSlopeTileDelta[i] = _mmw_set1_epi32(simd_i32(slopeTileDelta[i])[triIdx]); + triEdgeY[i] = _mmw_set1_epi32(simd_i32(edgeY[i])[triIdx]); + triSlopeTileRemainder[i] = _mmw_set1_epi32(simd_i32(slopeTileRemainder[i])[triIdx]); + + __mw triSlope = _mmw_set1_ps(simd_f32(slope[i])[triIdx]); + __mwi triAbsEdgeX = _mmw_set1_epi32(simd_i32(absEdgeX[i])[triIdx]); + __mwi triStartRemainder = _mmw_set1_epi32(simd_i32(eventStartRemainder[i])[triIdx]); + __mwi triEventStart = _mmw_set1_epi32(simd_i32(eventStart[i])[triIdx]); + + __mwi scanlineDelta = _mmw_cvttps_epi32(_mmw_mul_ps(triSlope, SIMD_LANE_YCOORD_F)); + __mwi scanlineSlopeRemainder = _mmw_sub_epi32(_mmw_mullo_epi32(triAbsEdgeX, SIMD_LANE_YCOORD_I), _mmw_mullo_epi32(_mmw_abs_epi32(scanlineDelta), triEdgeY[i])); + + triEventRemainder[i] = _mmw_sub_epi32(triStartRemainder, scanlineSlopeRemainder); + __mwi overflow = _mmw_srai_epi32(triEventRemainder[i], 31); + triEventRemainder[i] = _mmw_add_epi32(triEventRemainder[i], _mmw_and_epi32(overflow, triEdgeY[i])); + triEvent[i] = _mmw_add_epi32(_mmw_add_epi32(triEventStart, scanlineDelta), _mmw_and_epi32(overflow, triSlopeSign[i])); + } + +#else + #define LEFT_EDGE_BIAS 0 + #define RIGHT_EDGE_BIAS 0 + #define UPDATE_TILE_EVENTS_Y(i) triEvent[i] = _mmw_add_epi32(triEvent[i], triSlopeTileDelta[i]); + + // Get deltas used to increment edge events each time we traverse one scanline of tiles + __mwi triSlopeTileDelta[3]; + triSlopeTileDelta[0] = _mmw_set1_epi32(simd_i32(slopeTileDelta[0])[triIdx]); + triSlopeTileDelta[1] = _mmw_set1_epi32(simd_i32(slopeTileDelta[1])[triIdx]); + triSlopeTileDelta[2] = _mmw_set1_epi32(simd_i32(slopeTileDelta[2])[triIdx]); + + // Setup edge events for first batch of SIMD_LANES scanlines + __mwi triEvent[3]; + triEvent[0] = _mmw_add_epi32(_mmw_set1_epi32(simd_i32(eventStart[0])[triIdx]), _mmw_mullo_epi32(SIMD_LANE_IDX, _mmw_set1_epi32(simd_i32(slope[0])[triIdx]))); + triEvent[1] = _mmw_add_epi32(_mmw_set1_epi32(simd_i32(eventStart[1])[triIdx]), _mmw_mullo_epi32(SIMD_LANE_IDX, _mmw_set1_epi32(simd_i32(slope[1])[triIdx]))); + triEvent[2] = _mmw_add_epi32(_mmw_set1_epi32(simd_i32(eventStart[2])[triIdx]), _mmw_mullo_epi32(SIMD_LANE_IDX, _mmw_set1_epi32(simd_i32(slope[2])[triIdx]))); +#endif + + // For big triangles track start & end tile for each scanline and only traverse the valid region + int startDelta, endDelta, topDelta, startEvent, endEvent, topEvent; + if (TIGHT_TRAVERSAL) + { + startDelta = simd_i32(slopeTileDelta[2])[triIdx] + LEFT_EDGE_BIAS; + endDelta = simd_i32(slopeTileDelta[0])[triIdx] + RIGHT_EDGE_BIAS; + topDelta = simd_i32(slopeTileDelta[1])[triIdx] + (MID_VTX_RIGHT ? RIGHT_EDGE_BIAS : LEFT_EDGE_BIAS); + + // Compute conservative bounds for the edge events over a 32xN tile + startEvent = simd_i32(eventStart[2])[triIdx] + min(0, startDelta); + endEvent = simd_i32(eventStart[0])[triIdx] + max(0, endDelta) + (TILE_WIDTH << FP_BITS); + if (MID_VTX_RIGHT) + topEvent = simd_i32(eventStart[1])[triIdx] + max(0, topDelta) + (TILE_WIDTH << FP_BITS); + else + topEvent = simd_i32(eventStart[1])[triIdx] + min(0, topDelta); + } + + if (tileRowIdx <= tileMidRowIdx) + { + int tileStopIdx = min(tileEndRowIdx, tileMidRowIdx); + // Traverse the bottom half of the triangle + while (tileRowIdx < tileStopIdx) + { + int start = 0, end = bbWidth; + if (TIGHT_TRAVERSAL) + { + // Compute tighter start and endpoints to avoid traversing empty space + start = max(0, min(bbWidth - 1, startEvent >> (TILE_WIDTH_SHIFT + FP_BITS))); + end = min(bbWidth, ((int)endEvent >> (TILE_WIDTH_SHIFT + FP_BITS))); + startEvent += startDelta; + endEvent += endDelta; + } + + // Traverse the scanline and update the masked hierarchical z buffer + cullResult = TraverseScanline(start, end, tileRowIdx, 0, 2, triEvent, zTriMin, zTriMax, z0, zx); + + if (TEST_Z && cullResult == CullingResult::VISIBLE) // Early out if performing occlusion query + return CullingResult::VISIBLE; + + // move to the next scanline of tiles, update edge events and interpolate z + tileRowIdx += mTilesWidth; + z0 = _mmw_add_ps(z0, _mmw_set1_ps(zy)); + UPDATE_TILE_EVENTS_Y(0); + UPDATE_TILE_EVENTS_Y(2); + } + + // Traverse the middle scanline of tiles. We must consider all three edges only in this region + if (tileRowIdx < tileEndRowIdx) + { + int start = 0, end = bbWidth; + if (TIGHT_TRAVERSAL) + { + // Compute tighter start and endpoints to avoid traversing lots of empty space + start = max(0, min(bbWidth - 1, startEvent >> (TILE_WIDTH_SHIFT + FP_BITS))); + end = min(bbWidth, ((int)endEvent >> (TILE_WIDTH_SHIFT + FP_BITS))); + + // Switch the traversal start / end to account for the upper side edge + endEvent = MID_VTX_RIGHT ? topEvent : endEvent; + endDelta = MID_VTX_RIGHT ? topDelta : endDelta; + startEvent = MID_VTX_RIGHT ? startEvent : topEvent; + startDelta = MID_VTX_RIGHT ? startDelta : topDelta; + startEvent += startDelta; + endEvent += endDelta; + } + + // Traverse the scanline and update the masked hierarchical z buffer. + if (MID_VTX_RIGHT) + cullResult = TraverseScanline(start, end, tileRowIdx, 0, 2, triEvent, zTriMin, zTriMax, z0, zx); + else + cullResult = TraverseScanline(start, end, tileRowIdx, 0, 2, triEvent, zTriMin, zTriMax, z0, zx); + + if (TEST_Z && cullResult == CullingResult::VISIBLE) // Early out if performing occlusion query + return CullingResult::VISIBLE; + + tileRowIdx += mTilesWidth; + } + + // Traverse the top half of the triangle + if (tileRowIdx < tileEndRowIdx) + { + // move to the next scanline of tiles, update edge events and interpolate z + z0 = _mmw_add_ps(z0, _mmw_set1_ps(zy)); + int i0 = MID_VTX_RIGHT + 0; + int i1 = MID_VTX_RIGHT + 1; + UPDATE_TILE_EVENTS_Y(i0); + UPDATE_TILE_EVENTS_Y(i1); + for (;;) + { + int start = 0, end = bbWidth; + if (TIGHT_TRAVERSAL) + { + // Compute tighter start and endpoints to avoid traversing lots of empty space + start = max(0, min(bbWidth - 1, startEvent >> (TILE_WIDTH_SHIFT + FP_BITS))); + end = min(bbWidth, ((int)endEvent >> (TILE_WIDTH_SHIFT + FP_BITS))); + startEvent += startDelta; + endEvent += endDelta; + } + + // Traverse the scanline and update the masked hierarchical z buffer + cullResult = TraverseScanline(start, end, tileRowIdx, MID_VTX_RIGHT + 0, MID_VTX_RIGHT + 1, triEvent, zTriMin, zTriMax, z0, zx); + + if (TEST_Z && cullResult == CullingResult::VISIBLE) // Early out if performing occlusion query + return CullingResult::VISIBLE; + + // move to the next scanline of tiles, update edge events and interpolate z + tileRowIdx += mTilesWidth; + if (tileRowIdx >= tileEndRowIdx) + break; + z0 = _mmw_add_ps(z0, _mmw_set1_ps(zy)); + UPDATE_TILE_EVENTS_Y(i0); + UPDATE_TILE_EVENTS_Y(i1); + } + } + } + else + { + if (TIGHT_TRAVERSAL) + { + // For large triangles, switch the traversal start / end to account for the upper side edge + endEvent = MID_VTX_RIGHT ? topEvent : endEvent; + endDelta = MID_VTX_RIGHT ? topDelta : endDelta; + startEvent = MID_VTX_RIGHT ? startEvent : topEvent; + startDelta = MID_VTX_RIGHT ? startDelta : topDelta; + } + + // Traverse the top half of the triangle + if (tileRowIdx < tileEndRowIdx) + { + int i0 = MID_VTX_RIGHT + 0; + int i1 = MID_VTX_RIGHT + 1; + for (;;) + { + int start = 0, end = bbWidth; + if (TIGHT_TRAVERSAL) + { + // Compute tighter start and endpoints to avoid traversing lots of empty space + start = max(0, min(bbWidth - 1, startEvent >> (TILE_WIDTH_SHIFT + FP_BITS))); + end = min(bbWidth, ((int)endEvent >> (TILE_WIDTH_SHIFT + FP_BITS))); + startEvent += startDelta; + endEvent += endDelta; + } + + // Traverse the scanline and update the masked hierarchical z buffer + cullResult = TraverseScanline(start, end, tileRowIdx, MID_VTX_RIGHT + 0, MID_VTX_RIGHT + 1, triEvent, zTriMin, zTriMax, z0, zx); + + if (TEST_Z && cullResult == CullingResult::VISIBLE) // Early out if performing occlusion query + return CullingResult::VISIBLE; + + // move to the next scanline of tiles, update edge events and interpolate z + tileRowIdx += mTilesWidth; + if (tileRowIdx >= tileEndRowIdx) + break; + z0 = _mmw_add_ps(z0, _mmw_set1_ps(zy)); + UPDATE_TILE_EVENTS_Y(i0); + UPDATE_TILE_EVENTS_Y(i1); + } + } + } + + return TEST_Z ? CullingResult::OCCLUDED : CullingResult::VISIBLE; + } + + template +#if PRECISE_COVERAGE != 0 + FORCE_INLINE int RasterizeTriangleBatch(__mwi ipVtxX[3], __mwi ipVtxY[3], __mw pVtxX[3], __mw pVtxY[3], __mw pVtxZ[3], unsigned int triMask, const ScissorRect *scissor) +#else + FORCE_INLINE int RasterizeTriangleBatch(__mw pVtxX[3], __mw pVtxY[3], __mw pVtxZ[3], unsigned int triMask, const ScissorRect *scissor) +#endif + { + int cullResult = CullingResult::VIEW_CULLED; + + ////////////////////////////////////////////////////////////////////////////// + // Compute bounding box and clamp to tile coordinates + ////////////////////////////////////////////////////////////////////////////// + + __mwi bbPixelMinX, bbPixelMinY, bbPixelMaxX, bbPixelMaxY; + ComputeBoundingBox(bbPixelMinX, bbPixelMinY, bbPixelMaxX, bbPixelMaxY, pVtxX, pVtxY, scissor); + + // Clamp bounding box to tiles (it's already padded in computeBoundingBox) + __mwi bbTileMinX = _mmw_srai_epi32(bbPixelMinX, TILE_WIDTH_SHIFT); + __mwi bbTileMinY = _mmw_srai_epi32(bbPixelMinY, TILE_HEIGHT_SHIFT); + __mwi bbTileMaxX = _mmw_srai_epi32(bbPixelMaxX, TILE_WIDTH_SHIFT); + __mwi bbTileMaxY = _mmw_srai_epi32(bbPixelMaxY, TILE_HEIGHT_SHIFT); + __mwi bbTileSizeX = _mmw_sub_epi32(bbTileMaxX, bbTileMinX); + __mwi bbTileSizeY = _mmw_sub_epi32(bbTileMaxY, bbTileMinY); + + // Cull triangles with zero bounding box + __mwi bboxSign = _mmw_or_epi32(_mmw_sub_epi32(bbTileSizeX, _mmw_set1_epi32(1)), _mmw_sub_epi32(bbTileSizeY, _mmw_set1_epi32(1))); + triMask &= ~_mmw_movemask_ps(simd_cast<__mw>(bboxSign)) & SIMD_ALL_LANES_MASK; + if (triMask == 0x0) + return cullResult; + + if (!TEST_Z) + cullResult = CullingResult::VISIBLE; + + ////////////////////////////////////////////////////////////////////////////// + // Set up screen space depth plane + ////////////////////////////////////////////////////////////////////////////// + + __mw zPixelDx, zPixelDy; + ComputeDepthPlane(pVtxX, pVtxY, pVtxZ, zPixelDx, zPixelDy); + + // Compute z value at min corner of bounding box. Offset to make sure z is conservative for all 8x4 subtiles + __mw bbMinXV0 = _mmw_sub_ps(_mmw_cvtepi32_ps(bbPixelMinX), pVtxX[0]); + __mw bbMinYV0 = _mmw_sub_ps(_mmw_cvtepi32_ps(bbPixelMinY), pVtxY[0]); + __mw zPlaneOffset = _mmw_fmadd_ps(zPixelDx, bbMinXV0, _mmw_fmadd_ps(zPixelDy, bbMinYV0, pVtxZ[0])); + __mw zTileDx = _mmw_mul_ps(zPixelDx, _mmw_set1_ps((float)TILE_WIDTH)); + __mw zTileDy = _mmw_mul_ps(zPixelDy, _mmw_set1_ps((float)TILE_HEIGHT)); + if (TEST_Z) + { + zPlaneOffset = _mmw_add_ps(zPlaneOffset, _mmw_max_ps(_mmw_setzero_ps(), _mmw_mul_ps(zPixelDx, _mmw_set1_ps(SUB_TILE_WIDTH)))); + zPlaneOffset = _mmw_add_ps(zPlaneOffset, _mmw_max_ps(_mmw_setzero_ps(), _mmw_mul_ps(zPixelDy, _mmw_set1_ps(SUB_TILE_HEIGHT)))); + } + else + { + zPlaneOffset = _mmw_add_ps(zPlaneOffset, _mmw_min_ps(_mmw_setzero_ps(), _mmw_mul_ps(zPixelDx, _mmw_set1_ps(SUB_TILE_WIDTH)))); + zPlaneOffset = _mmw_add_ps(zPlaneOffset, _mmw_min_ps(_mmw_setzero_ps(), _mmw_mul_ps(zPixelDy, _mmw_set1_ps(SUB_TILE_HEIGHT)))); + } + + // Compute Zmin and Zmax for the triangle (used to narrow the range for difficult tiles) + __mw zMin = _mmw_min_ps(pVtxZ[0], _mmw_min_ps(pVtxZ[1], pVtxZ[2])); + __mw zMax = _mmw_max_ps(pVtxZ[0], _mmw_max_ps(pVtxZ[1], pVtxZ[2])); + + ////////////////////////////////////////////////////////////////////////////// + // Sort vertices (v0 has lowest Y, and the rest is in winding order) and + // compute edges. Also find the middle vertex and compute tile + ////////////////////////////////////////////////////////////////////////////// + +#if PRECISE_COVERAGE != 0 + + // Rotate the triangle in the winding order until v0 is the vertex with lowest Y value + SortVertices(ipVtxX, ipVtxY); + + // Compute edges + __mwi edgeX[3] = { _mmw_sub_epi32(ipVtxX[1], ipVtxX[0]), _mmw_sub_epi32(ipVtxX[2], ipVtxX[1]), _mmw_sub_epi32(ipVtxX[2], ipVtxX[0]) }; + __mwi edgeY[3] = { _mmw_sub_epi32(ipVtxY[1], ipVtxY[0]), _mmw_sub_epi32(ipVtxY[2], ipVtxY[1]), _mmw_sub_epi32(ipVtxY[2], ipVtxY[0]) }; + + // Classify if the middle vertex is on the left or right and compute its position + int midVtxRight = ~_mmw_movemask_ps(simd_cast<__mw>(edgeY[1])); + __mwi midPixelX = _mmw_blendv_epi32(ipVtxX[1], ipVtxX[2], edgeY[1]); + __mwi midPixelY = _mmw_blendv_epi32(ipVtxY[1], ipVtxY[2], edgeY[1]); + __mwi midTileY = _mmw_srai_epi32(_mmw_max_epi32(midPixelY, SIMD_BITS_ZERO), TILE_HEIGHT_SHIFT + FP_BITS); + __mwi bbMidTileY = _mmw_max_epi32(bbTileMinY, _mmw_min_epi32(bbTileMaxY, midTileY)); + + // Compute edge events for the bottom of the bounding box, or for the middle tile in case of + // the edge originating from the middle vertex. + __mwi xDiffi[2], yDiffi[2]; + xDiffi[0] = _mmw_sub_epi32(ipVtxX[0], _mmw_slli_epi32(bbPixelMinX, FP_BITS)); + xDiffi[1] = _mmw_sub_epi32(midPixelX, _mmw_slli_epi32(bbPixelMinX, FP_BITS)); + yDiffi[0] = _mmw_sub_epi32(ipVtxY[0], _mmw_slli_epi32(bbPixelMinY, FP_BITS)); + yDiffi[1] = _mmw_sub_epi32(midPixelY, _mmw_slli_epi32(bbMidTileY, FP_BITS + TILE_HEIGHT_SHIFT)); + + ////////////////////////////////////////////////////////////////////////////// + // Edge slope setup - Note we do not conform to DX/GL rasterization rules + ////////////////////////////////////////////////////////////////////////////// + + // Potentially flip edge to ensure that all edges have positive Y slope. + edgeX[1] = _mmw_blendv_epi32(edgeX[1], _mmw_neg_epi32(edgeX[1]), edgeY[1]); + edgeY[1] = _mmw_abs_epi32(edgeY[1]); + + // Compute floating point slopes + __mw slope[3]; + slope[0] = _mmw_div_ps(_mmw_cvtepi32_ps(edgeX[0]), _mmw_cvtepi32_ps(edgeY[0])); + slope[1] = _mmw_div_ps(_mmw_cvtepi32_ps(edgeX[1]), _mmw_cvtepi32_ps(edgeY[1])); + slope[2] = _mmw_div_ps(_mmw_cvtepi32_ps(edgeX[2]), _mmw_cvtepi32_ps(edgeY[2])); + + // Modify slope of horizontal edges to make sure they mask out pixels above/below the edge. The slope is set to screen + // width to mask out all pixels above or below the horizontal edge. We must also add a small bias to acount for that + // vertices may end up off screen due to clipping. We're assuming that the round off error is no bigger than 1.0 + __mw horizontalSlopeDelta = _mmw_set1_ps(2.0f * ((float)mWidth + 2.0f*(GUARD_BAND_PIXEL_SIZE + 1.0f))); + __mwi horizontalSlope0 = _mmw_cmpeq_epi32(edgeY[0], _mmw_setzero_epi32()); + __mwi horizontalSlope1 = _mmw_cmpeq_epi32(edgeY[1], _mmw_setzero_epi32()); + slope[0] = _mmw_blendv_ps(slope[0], horizontalSlopeDelta, simd_cast<__mw>(horizontalSlope0)); + slope[1] = _mmw_blendv_ps(slope[1], _mmw_neg_ps(horizontalSlopeDelta), simd_cast<__mw>(horizontalSlope1)); + + __mwi vy[3] = { yDiffi[0], yDiffi[1], yDiffi[0] }; + __mwi offset0 = _mmw_and_epi32(_mmw_add_epi32(yDiffi[0], _mmw_set1_epi32(FP_HALF_PIXEL - 1)), _mmw_set1_epi32((int)((~0u) << FP_BITS))); + __mwi offset1 = _mmw_and_epi32(_mmw_add_epi32(yDiffi[1], _mmw_set1_epi32(FP_HALF_PIXEL - 1)), _mmw_set1_epi32((int)((~0u) << FP_BITS))); + vy[0] = _mmw_blendv_epi32(yDiffi[0], offset0, horizontalSlope0); + vy[1] = _mmw_blendv_epi32(yDiffi[1], offset1, horizontalSlope1); + + // Compute edge events for the bottom of the bounding box, or for the middle tile in case of + // the edge originating from the middle vertex. + __mwi slopeSign[3], absEdgeX[3]; + __mwi slopeTileDelta[3], eventStartRemainder[3], slopeTileRemainder[3], eventStart[3]; + for (int i = 0; i < 3; i++) + { + // Common, compute slope sign (used to propagate the remainder term when overflowing) is postive or negative x-direction + slopeSign[i] = _mmw_blendv_epi32(_mmw_set1_epi32(1), _mmw_set1_epi32(-1), edgeX[i]); + absEdgeX[i] = _mmw_abs_epi32(edgeX[i]); + + // Delta and error term for one vertical tile step. The exact delta is exactDelta = edgeX / edgeY, due to limited precision we + // repersent the delta as delta = qoutient + remainder / edgeY, where quotient = int(edgeX / edgeY). In this case, since we step + // one tile of scanlines at a time, the slope is computed for a tile-sized step. + slopeTileDelta[i] = _mmw_cvttps_epi32(_mmw_mul_ps(slope[i], _mmw_set1_ps(FP_TILE_HEIGHT))); + slopeTileRemainder[i] = _mmw_sub_epi32(_mmw_slli_epi32(absEdgeX[i], FP_TILE_HEIGHT_SHIFT), _mmw_mullo_epi32(_mmw_abs_epi32(slopeTileDelta[i]), edgeY[i])); + + // Jump to bottom scanline of tile row, this is the bottom of the bounding box, or the middle vertex of the triangle. + // The jump can be in both positive and negative y-direction due to clipping / offscreen vertices. + __mwi tileStartDir = _mmw_blendv_epi32(slopeSign[i], _mmw_neg_epi32(slopeSign[i]), vy[i]); + __mwi tieBreaker = _mmw_blendv_epi32(_mmw_set1_epi32(0), _mmw_set1_epi32(1), tileStartDir); + __mwi tileStartSlope = _mmw_cvttps_epi32(_mmw_mul_ps(slope[i], _mmw_cvtepi32_ps(_mmw_neg_epi32(vy[i])))); + __mwi tileStartRemainder = _mmw_sub_epi32(_mmw_mullo_epi32(absEdgeX[i], _mmw_abs_epi32(vy[i])), _mmw_mullo_epi32(_mmw_abs_epi32(tileStartSlope), edgeY[i])); + + eventStartRemainder[i] = _mmw_sub_epi32(tileStartRemainder, tieBreaker); + __mwi overflow = _mmw_srai_epi32(eventStartRemainder[i], 31); + eventStartRemainder[i] = _mmw_add_epi32(eventStartRemainder[i], _mmw_and_epi32(overflow, edgeY[i])); + eventStartRemainder[i] = _mmw_blendv_epi32(eventStartRemainder[i], _mmw_sub_epi32(_mmw_sub_epi32(edgeY[i], eventStartRemainder[i]), _mmw_set1_epi32(1)), vy[i]); + + //eventStart[i] = xDiffi[i & 1] + tileStartSlope + (overflow & tileStartDir) + _mmw_set1_epi32(FP_HALF_PIXEL - 1) + tieBreaker; + eventStart[i] = _mmw_add_epi32(_mmw_add_epi32(xDiffi[i & 1], tileStartSlope), _mmw_and_epi32(overflow, tileStartDir)); + eventStart[i] = _mmw_add_epi32(_mmw_add_epi32(eventStart[i], _mmw_set1_epi32(FP_HALF_PIXEL - 1)), tieBreaker); + } + +#else // PRECISE_COVERAGE + + SortVertices(pVtxX, pVtxY); + + // Compute edges + __mw edgeX[3] = { _mmw_sub_ps(pVtxX[1], pVtxX[0]), _mmw_sub_ps(pVtxX[2], pVtxX[1]), _mmw_sub_ps(pVtxX[2], pVtxX[0]) }; + __mw edgeY[3] = { _mmw_sub_ps(pVtxY[1], pVtxY[0]), _mmw_sub_ps(pVtxY[2], pVtxY[1]), _mmw_sub_ps(pVtxY[2], pVtxY[0]) }; + + // Classify if the middle vertex is on the left or right and compute its position + int midVtxRight = ~_mmw_movemask_ps(edgeY[1]); + __mw midPixelX = _mmw_blendv_ps(pVtxX[1], pVtxX[2], edgeY[1]); + __mw midPixelY = _mmw_blendv_ps(pVtxY[1], pVtxY[2], edgeY[1]); + __mwi midTileY = _mmw_srai_epi32(_mmw_max_epi32(_mmw_cvttps_epi32(midPixelY), SIMD_BITS_ZERO), TILE_HEIGHT_SHIFT); + __mwi bbMidTileY = _mmw_max_epi32(bbTileMinY, _mmw_min_epi32(bbTileMaxY, midTileY)); + + ////////////////////////////////////////////////////////////////////////////// + // Edge slope setup - Note we do not conform to DX/GL rasterization rules + ////////////////////////////////////////////////////////////////////////////// + + // Compute floating point slopes + __mw slope[3]; + slope[0] = _mmw_div_ps(edgeX[0], edgeY[0]); + slope[1] = _mmw_div_ps(edgeX[1], edgeY[1]); + slope[2] = _mmw_div_ps(edgeX[2], edgeY[2]); + + // Modify slope of horizontal edges to make sure they mask out pixels above/below the edge. The slope is set to screen + // width to mask out all pixels above or below the horizontal edge. We must also add a small bias to acount for that + // vertices may end up off screen due to clipping. We're assuming that the round off error is no bigger than 1.0 + __mw horizontalSlopeDelta = _mmw_set1_ps((float)mWidth + 2.0f*(GUARD_BAND_PIXEL_SIZE + 1.0f)); + slope[0] = _mmw_blendv_ps(slope[0], horizontalSlopeDelta, _mmw_cmpeq_ps(edgeY[0], _mmw_setzero_ps())); + slope[1] = _mmw_blendv_ps(slope[1], _mmw_neg_ps(horizontalSlopeDelta), _mmw_cmpeq_ps(edgeY[1], _mmw_setzero_ps())); + + // Convert floaing point slopes to fixed point + __mwi slopeFP[3]; + slopeFP[0] = _mmw_cvttps_epi32(_mmw_mul_ps(slope[0], _mmw_set1_ps(1 << FP_BITS))); + slopeFP[1] = _mmw_cvttps_epi32(_mmw_mul_ps(slope[1], _mmw_set1_ps(1 << FP_BITS))); + slopeFP[2] = _mmw_cvttps_epi32(_mmw_mul_ps(slope[2], _mmw_set1_ps(1 << FP_BITS))); + + // Fan out edge slopes to avoid (rare) cracks at vertices. We increase right facing slopes + // by 1 LSB, which results in overshooting vertices slightly, increasing triangle coverage. + // e0 is always right facing, e1 depends on if the middle vertex is on the left or right + slopeFP[0] = _mmw_add_epi32(slopeFP[0], _mmw_set1_epi32(1)); + slopeFP[1] = _mmw_add_epi32(slopeFP[1], _mmw_srli_epi32(_mmw_not_epi32(simd_cast<__mwi>(edgeY[1])), 31)); + + // Compute slope deltas for an SIMD_LANES scanline step (tile height) + __mwi slopeTileDelta[3]; + slopeTileDelta[0] = _mmw_slli_epi32(slopeFP[0], TILE_HEIGHT_SHIFT); + slopeTileDelta[1] = _mmw_slli_epi32(slopeFP[1], TILE_HEIGHT_SHIFT); + slopeTileDelta[2] = _mmw_slli_epi32(slopeFP[2], TILE_HEIGHT_SHIFT); + + // Compute edge events for the bottom of the bounding box, or for the middle tile in case of + // the edge originating from the middle vertex. + __mwi xDiffi[2], yDiffi[2]; + xDiffi[0] = _mmw_slli_epi32(_mmw_sub_epi32(_mmw_cvttps_epi32(pVtxX[0]), bbPixelMinX), FP_BITS); + xDiffi[1] = _mmw_slli_epi32(_mmw_sub_epi32(_mmw_cvttps_epi32(midPixelX), bbPixelMinX), FP_BITS); + yDiffi[0] = _mmw_sub_epi32(_mmw_cvttps_epi32(pVtxY[0]), bbPixelMinY); + yDiffi[1] = _mmw_sub_epi32(_mmw_cvttps_epi32(midPixelY), _mmw_slli_epi32(bbMidTileY, TILE_HEIGHT_SHIFT)); + + __mwi eventStart[3]; + eventStart[0] = _mmw_sub_epi32(xDiffi[0], _mmw_mullo_epi32(slopeFP[0], yDiffi[0])); + eventStart[1] = _mmw_sub_epi32(xDiffi[1], _mmw_mullo_epi32(slopeFP[1], yDiffi[1])); + eventStart[2] = _mmw_sub_epi32(xDiffi[0], _mmw_mullo_epi32(slopeFP[2], yDiffi[0])); +#endif + + ////////////////////////////////////////////////////////////////////////////// + // Split bounding box into bottom - middle - top region. + ////////////////////////////////////////////////////////////////////////////// + + __mwi bbBottomIdx = _mmw_add_epi32(bbTileMinX, _mmw_mullo_epi32(bbTileMinY, _mmw_set1_epi32(mTilesWidth))); + __mwi bbTopIdx = _mmw_add_epi32(bbTileMinX, _mmw_mullo_epi32(_mmw_add_epi32(bbTileMinY, bbTileSizeY), _mmw_set1_epi32(mTilesWidth))); + __mwi bbMidIdx = _mmw_add_epi32(bbTileMinX, _mmw_mullo_epi32(midTileY, _mmw_set1_epi32(mTilesWidth))); + + ////////////////////////////////////////////////////////////////////////////// + // Loop over non-culled triangle and change SIMD axis to per-pixel + ////////////////////////////////////////////////////////////////////////////// + while (triMask) + { + unsigned int triIdx = find_clear_lsb(&triMask); + int triMidVtxRight = (midVtxRight >> triIdx) & 1; + + // Get Triangle Zmin zMax + __mw zTriMax = _mmw_set1_ps(simd_f32(zMax)[triIdx]); + __mw zTriMin = _mmw_set1_ps(simd_f32(zMin)[triIdx]); + + // Setup Zmin value for first set of 8x4 subtiles + __mw z0 = _mmw_fmadd_ps(_mmw_set1_ps(simd_f32(zPixelDx)[triIdx]), SIMD_SUB_TILE_COL_OFFSET_F, + _mmw_fmadd_ps(_mmw_set1_ps(simd_f32(zPixelDy)[triIdx]), SIMD_SUB_TILE_ROW_OFFSET_F, _mmw_set1_ps(simd_f32(zPlaneOffset)[triIdx]))); + float zx = simd_f32(zTileDx)[triIdx]; + float zy = simd_f32(zTileDy)[triIdx]; + + // Get dimension of bounding box bottom, mid & top segments + int bbWidth = simd_i32(bbTileSizeX)[triIdx]; + int bbHeight = simd_i32(bbTileSizeY)[triIdx]; + int tileRowIdx = simd_i32(bbBottomIdx)[triIdx]; + int tileMidRowIdx = simd_i32(bbMidIdx)[triIdx]; + int tileEndRowIdx = simd_i32(bbTopIdx)[triIdx]; + + if (bbWidth > BIG_TRIANGLE && bbHeight > BIG_TRIANGLE) // For big triangles we use a more expensive but tighter traversal algorithm + { +#if PRECISE_COVERAGE != 0 + if (triMidVtxRight) + cullResult &= RasterizeTriangle(triIdx, bbWidth, tileRowIdx, tileMidRowIdx, tileEndRowIdx, eventStart, slope, slopeTileDelta, zTriMin, zTriMax, z0, zx, zy, edgeY, absEdgeX, slopeSign, eventStartRemainder, slopeTileRemainder); + else + cullResult &= RasterizeTriangle(triIdx, bbWidth, tileRowIdx, tileMidRowIdx, tileEndRowIdx, eventStart, slope, slopeTileDelta, zTriMin, zTriMax, z0, zx, zy, edgeY, absEdgeX, slopeSign, eventStartRemainder, slopeTileRemainder); +#else + if (triMidVtxRight) + cullResult &= RasterizeTriangle(triIdx, bbWidth, tileRowIdx, tileMidRowIdx, tileEndRowIdx, eventStart, slopeFP, slopeTileDelta, zTriMin, zTriMax, z0, zx, zy); + else + cullResult &= RasterizeTriangle(triIdx, bbWidth, tileRowIdx, tileMidRowIdx, tileEndRowIdx, eventStart, slopeFP, slopeTileDelta, zTriMin, zTriMax, z0, zx, zy); +#endif + } + else + { +#if PRECISE_COVERAGE != 0 + if (triMidVtxRight) + cullResult &= RasterizeTriangle(triIdx, bbWidth, tileRowIdx, tileMidRowIdx, tileEndRowIdx, eventStart, slope, slopeTileDelta, zTriMin, zTriMax, z0, zx, zy, edgeY, absEdgeX, slopeSign, eventStartRemainder, slopeTileRemainder); + else + cullResult &= RasterizeTriangle(triIdx, bbWidth, tileRowIdx, tileMidRowIdx, tileEndRowIdx, eventStart, slope, slopeTileDelta, zTriMin, zTriMax, z0, zx, zy, edgeY, absEdgeX, slopeSign, eventStartRemainder, slopeTileRemainder); +#else + if (triMidVtxRight) + cullResult &= RasterizeTriangle(triIdx, bbWidth, tileRowIdx, tileMidRowIdx, tileEndRowIdx, eventStart, slopeFP, slopeTileDelta, zTriMin, zTriMax, z0, zx, zy); + else + cullResult &= RasterizeTriangle(triIdx, bbWidth, tileRowIdx, tileMidRowIdx, tileEndRowIdx, eventStart, slopeFP, slopeTileDelta, zTriMin, zTriMax, z0, zx, zy); +#endif + } + + if (TEST_Z && cullResult == CullingResult::VISIBLE) + return CullingResult::VISIBLE; + } + + return cullResult; + } + + template + FORCE_INLINE CullingResult RenderTriangles(const float *inVtx, const unsigned int *inTris, int nTris, const float *modelToClipMatrix, BackfaceWinding bfWinding, ClipPlanes clipPlaneMask, const VertexLayout &vtxLayout) + { + assert(mMaskedHiZBuffer != nullptr); + + if (TEST_Z) + STATS_ADD(mStats.mOccludees.mNumProcessedTriangles, nTris); + else + STATS_ADD(mStats.mOccluders.mNumProcessedTriangles, nTris); + +#if PRECISE_COVERAGE != 0 + int originalRoundingMode = _MM_GET_ROUNDING_MODE(); + _MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST); +#endif + + int clipHead = 0; + int clipTail = 0; + __m128 clipTriBuffer[MAX_CLIPPED * 3]; + int cullResult = CullingResult::VIEW_CULLED; + + const unsigned int *inTrisPtr = inTris; + int numLanes = SIMD_LANES; + int triIndex = 0; + while (triIndex < nTris || clipHead != clipTail) + { + __mw vtxX[3], vtxY[3], vtxW[3]; + unsigned int triMask = SIMD_ALL_LANES_MASK; + + GatherTransformClip( clipHead, clipTail, numLanes, nTris, triIndex, vtxX, vtxY, vtxW, inVtx, inTrisPtr, vtxLayout, modelToClipMatrix, clipTriBuffer, triMask, clipPlaneMask ); + + if (triMask == 0x0) + continue; + + ////////////////////////////////////////////////////////////////////////////// + // Project, transform to screen space and perform backface culling. Note + // that we use z = 1.0 / vtx.w for depth, which means that z = 0 is far and + // z = 1 is near. We must also use a greater than depth test, and in effect + // everything is reversed compared to regular z implementations. + ////////////////////////////////////////////////////////////////////////////// + + __mw pVtxX[3], pVtxY[3], pVtxZ[3]; + +#if PRECISE_COVERAGE != 0 + __mwi ipVtxX[3], ipVtxY[3]; + ProjectVertices(ipVtxX, ipVtxY, pVtxX, pVtxY, pVtxZ, vtxX, vtxY, vtxW); +#else + ProjectVertices(pVtxX, pVtxY, pVtxZ, vtxX, vtxY, vtxW); +#endif + + // Perform backface test. + __mw triArea1 = _mmw_mul_ps(_mmw_sub_ps(pVtxX[1], pVtxX[0]), _mmw_sub_ps(pVtxY[2], pVtxY[0])); + __mw triArea2 = _mmw_mul_ps(_mmw_sub_ps(pVtxX[0], pVtxX[2]), _mmw_sub_ps(pVtxY[0], pVtxY[1])); + __mw triArea = _mmw_sub_ps(triArea1, triArea2); + __mw ccwMask = _mmw_cmpgt_ps(triArea, _mmw_setzero_ps()); + +#if PRECISE_COVERAGE != 0 + triMask &= CullBackfaces(ipVtxX, ipVtxY, pVtxX, pVtxY, pVtxZ, ccwMask, bfWinding); +#else + triMask &= CullBackfaces(pVtxX, pVtxY, pVtxZ, ccwMask, bfWinding); +#endif + + if (triMask == 0x0) + continue; + + ////////////////////////////////////////////////////////////////////////////// + // Setup and rasterize a SIMD batch of triangles + ////////////////////////////////////////////////////////////////////////////// +#if PRECISE_COVERAGE != 0 + cullResult &= RasterizeTriangleBatch(ipVtxX, ipVtxY, pVtxX, pVtxY, pVtxZ, triMask, &mFullscreenScissor); +#else + cullResult &= RasterizeTriangleBatch(pVtxX, pVtxY, pVtxZ, triMask, &mFullscreenScissor); +#endif + + if (TEST_Z && cullResult == CullingResult::VISIBLE) { +#if PRECISE_COVERAGE != 0 + _MM_SET_ROUNDING_MODE(originalRoundingMode); +#endif + return CullingResult::VISIBLE; + } + } + +#if PRECISE_COVERAGE != 0 + _MM_SET_ROUNDING_MODE(originalRoundingMode); +#endif + return (CullingResult)cullResult; + } + + CullingResult RenderTriangles(const float *inVtx, const unsigned int *inTris, int nTris, const float *modelToClipMatrix, BackfaceWinding bfWinding, ClipPlanes clipPlaneMask, const VertexLayout &vtxLayout) override + { + CullingResult retVal; + + if (vtxLayout.mStride == 16 && vtxLayout.mOffsetY == 4 && vtxLayout.mOffsetW == 12) + retVal = (CullingResult)RenderTriangles<0, 1>(inVtx, inTris, nTris, modelToClipMatrix, bfWinding, clipPlaneMask, vtxLayout); + else + retVal = (CullingResult)RenderTriangles<0, 0>(inVtx, inTris, nTris, modelToClipMatrix, bfWinding, clipPlaneMask, vtxLayout); + +#if MOC_RECORDER_ENABLE + RecordRenderTriangles( inVtx, inTris, nTris, modelToClipMatrix, clipPlaneMask, bfWinding, vtxLayout, retVal ); +#endif + return retVal; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Occlusion query functions + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + CullingResult TestTriangles(const float *inVtx, const unsigned int *inTris, int nTris, const float *modelToClipMatrix, BackfaceWinding bfWinding, ClipPlanes clipPlaneMask, const VertexLayout &vtxLayout) override + { + CullingResult retVal; + + if (vtxLayout.mStride == 16 && vtxLayout.mOffsetY == 4 && vtxLayout.mOffsetW == 12) + retVal = (CullingResult)RenderTriangles<1, 1>(inVtx, inTris, nTris, modelToClipMatrix, bfWinding, clipPlaneMask, vtxLayout); + else + retVal = (CullingResult)RenderTriangles<1, 0>(inVtx, inTris, nTris, modelToClipMatrix, bfWinding, clipPlaneMask, vtxLayout); + +#if MOC_RECORDER_ENABLE + { + std::lock_guard lock( mRecorderMutex ); + if( mRecorder != nullptr ) mRecorder->RecordTestTriangles( retVal, inVtx, inTris, nTris, modelToClipMatrix, clipPlaneMask, bfWinding, vtxLayout ); + } +#endif + return retVal; + } + + CullingResult TestRect( float xmin, float ymin, float xmax, float ymax, float wmin ) const override + { + STATS_ADD(mStats.mOccludees.mNumProcessedRectangles, 1); + assert(mMaskedHiZBuffer != nullptr); + + static const __m128i SIMD_TILE_PAD = _mm_setr_epi32(0, TILE_WIDTH, 0, TILE_HEIGHT); + static const __m128i SIMD_TILE_PAD_MASK = _mm_setr_epi32(~(TILE_WIDTH - 1), ~(TILE_WIDTH - 1), ~(TILE_HEIGHT - 1), ~(TILE_HEIGHT - 1)); + static const __m128i SIMD_SUB_TILE_PAD = _mm_setr_epi32(0, SUB_TILE_WIDTH, 0, SUB_TILE_HEIGHT); + static const __m128i SIMD_SUB_TILE_PAD_MASK = _mm_setr_epi32(~(SUB_TILE_WIDTH - 1), ~(SUB_TILE_WIDTH - 1), ~(SUB_TILE_HEIGHT - 1), ~(SUB_TILE_HEIGHT - 1)); + + ////////////////////////////////////////////////////////////////////////////// + // Compute screen space bounding box and guard for out of bounds + ////////////////////////////////////////////////////////////////////////////// +#if USE_D3D != 0 + __m128 pixelBBox = _mmx_fmadd_ps(_mm_setr_ps(xmin, xmax, ymax, ymin), mIHalfSize, mICenter); +#else + __m128 pixelBBox = _mmx_fmadd_ps(_mm_setr_ps(xmin, xmax, ymin, ymax), mIHalfSize, mICenter); +#endif + __m128i pixelBBoxi = _mm_cvttps_epi32(pixelBBox); + pixelBBoxi = _mmx_max_epi32(_mm_setzero_si128(), _mmx_min_epi32(mIScreenSize, pixelBBoxi)); + + ////////////////////////////////////////////////////////////////////////////// + // Pad bounding box to (32xN) tiles. Tile BB is used for looping / traversal + ////////////////////////////////////////////////////////////////////////////// + __m128i tileBBoxi = _mm_and_si128(_mm_add_epi32(pixelBBoxi, SIMD_TILE_PAD), SIMD_TILE_PAD_MASK); + int txMin = simd_i32(tileBBoxi)[0] >> TILE_WIDTH_SHIFT; + int txMax = simd_i32(tileBBoxi)[1] >> TILE_WIDTH_SHIFT; + int tileRowIdx = (simd_i32(tileBBoxi)[2] >> TILE_HEIGHT_SHIFT)*mTilesWidth; + int tileRowIdxEnd = (simd_i32(tileBBoxi)[3] >> TILE_HEIGHT_SHIFT)*mTilesWidth; + + if (simd_i32(tileBBoxi)[0] == simd_i32(tileBBoxi)[1] || simd_i32(tileBBoxi)[2] == simd_i32(tileBBoxi)[3]) + { +#if MOC_RECORDER_ENABLE + { + std::lock_guard lock( mRecorderMutex ); + if( mRecorder != nullptr ) mRecorder->RecordTestRect( CullingResult::VIEW_CULLED, xmin, ymin, xmax, ymax, wmin ); + } +#endif + return CullingResult::VIEW_CULLED; + } + + /////////////////////////////////////////////////////////////////////////////// + // Pad bounding box to (8x4) subtiles. Skip SIMD lanes outside the subtile BB + /////////////////////////////////////////////////////////////////////////////// + __m128i subTileBBoxi = _mm_and_si128(_mm_add_epi32(pixelBBoxi, SIMD_SUB_TILE_PAD), SIMD_SUB_TILE_PAD_MASK); + __mwi stxmin = _mmw_set1_epi32(simd_i32(subTileBBoxi)[0] - 1); // - 1 to be able to use GT test + __mwi stymin = _mmw_set1_epi32(simd_i32(subTileBBoxi)[2] - 1); // - 1 to be able to use GT test + __mwi stxmax = _mmw_set1_epi32(simd_i32(subTileBBoxi)[1]); + __mwi stymax = _mmw_set1_epi32(simd_i32(subTileBBoxi)[3]); + + // Setup pixel coordinates used to discard lanes outside subtile BB + __mwi startPixelX = _mmw_add_epi32(SIMD_SUB_TILE_COL_OFFSET, _mmw_set1_epi32(simd_i32(tileBBoxi)[0])); + __mwi pixelY = _mmw_add_epi32(SIMD_SUB_TILE_ROW_OFFSET, _mmw_set1_epi32(simd_i32(tileBBoxi)[2])); + + ////////////////////////////////////////////////////////////////////////////// + // Compute z from w. Note that z is reversed order, 0 = far, 1 = near, which + // means we use a greater than test, so zMax is used to test for visibility. + ////////////////////////////////////////////////////////////////////////////// + __mw zMax = _mmw_div_ps(_mmw_set1_ps(1.0f), _mmw_set1_ps(wmin)); + + for (;;) + { + __mwi pixelX = startPixelX; + for (int tx = txMin;;) + { + STATS_ADD(mStats.mOccludees.mNumTilesTraversed, 1); + + int tileIdx = tileRowIdx + tx; + assert(tileIdx >= 0 && tileIdx < mTilesWidth*mTilesHeight); + + // Fetch zMin from masked hierarchical Z buffer +#if QUICK_MASK != 0 + __mw zBuf = mMaskedHiZBuffer[tileIdx].mZMin[0]; +#else + __mwi mask = mMaskedHiZBuffer[tileIdx].mMask; + __mw zMin0 = _mmw_blendv_ps(mMaskedHiZBuffer[tileIdx].mZMin[0], mMaskedHiZBuffer[tileIdx].mZMin[1], simd_cast<__mw>(_mmw_cmpeq_epi32(mask, _mmw_set1_epi32(~0)))); + __mw zMin1 = _mmw_blendv_ps(mMaskedHiZBuffer[tileIdx].mZMin[1], mMaskedHiZBuffer[tileIdx].mZMin[0], simd_cast<__mw>(_mmw_cmpeq_epi32(mask, _mmw_setzero_epi32()))); + __mw zBuf = _mmw_min_ps(zMin0, zMin1); +#endif + // Perform conservative greater than test against hierarchical Z buffer (zMax >= zBuf means the subtile is visible) + __mwi zPass = simd_cast<__mwi>(_mmw_cmpge_ps(zMax, zBuf)); //zPass = zMax >= zBuf ? ~0 : 0 + + // Mask out lanes corresponding to subtiles outside the bounding box + __mwi bboxTestMin = _mmw_and_epi32(_mmw_cmpgt_epi32(pixelX, stxmin), _mmw_cmpgt_epi32(pixelY, stymin)); + __mwi bboxTestMax = _mmw_and_epi32(_mmw_cmpgt_epi32(stxmax, pixelX), _mmw_cmpgt_epi32(stymax, pixelY)); + __mwi boxMask = _mmw_and_epi32(bboxTestMin, bboxTestMax); + zPass = _mmw_and_epi32(zPass, boxMask); + + // If not all tiles failed the conservative z test we can immediately terminate the test + if (!_mmw_testz_epi32(zPass, zPass)) + { +#if MOC_RECORDER_ENABLE + { + std::lock_guard lock( mRecorderMutex ); + if( mRecorder != nullptr ) mRecorder->RecordTestRect( CullingResult::VISIBLE, xmin, ymin, xmax, ymax, wmin ); + } +#endif + return CullingResult::VISIBLE; + } + + if (++tx >= txMax) + break; + pixelX = _mmw_add_epi32(pixelX, _mmw_set1_epi32(TILE_WIDTH)); + } + + tileRowIdx += mTilesWidth; + if (tileRowIdx >= tileRowIdxEnd) + break; + pixelY = _mmw_add_epi32(pixelY, _mmw_set1_epi32(TILE_HEIGHT)); + } +#if MOC_RECORDER_ENABLE + { + std::lock_guard lock( mRecorderMutex ); + if( mRecorder != nullptr ) mRecorder->RecordTestRect( CullingResult::OCCLUDED, xmin, ymin, xmax, ymax, wmin ); + } +#endif + return CullingResult::OCCLUDED; + } + + template + FORCE_INLINE void BinTriangles(const float *inVtx, const unsigned int *inTris, int nTris, TriList *triLists, unsigned int nBinsW, unsigned int nBinsH, const float *modelToClipMatrix, BackfaceWinding bfWinding, ClipPlanes clipPlaneMask, const VertexLayout &vtxLayout) + { + assert(mMaskedHiZBuffer != nullptr); + +#if PRECISE_COVERAGE != 0 + int originalRoundingMode = _MM_GET_ROUNDING_MODE(); + _MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST); +#endif + + STATS_ADD(mStats.mOccluders.mNumProcessedTriangles, nTris); + + int clipHead = 0; + int clipTail = 0; + __m128 clipTriBuffer[MAX_CLIPPED * 3]; + + const unsigned int *inTrisPtr = inTris; + int numLanes = SIMD_LANES; + int triIndex = 0; + while (triIndex < nTris || clipHead != clipTail) + { + unsigned int triMask = SIMD_ALL_LANES_MASK; + __mw vtxX[3], vtxY[3], vtxW[3]; + + GatherTransformClip( clipHead, clipTail, numLanes, nTris, triIndex, vtxX, vtxY, vtxW, inVtx, inTrisPtr, vtxLayout, modelToClipMatrix, clipTriBuffer, triMask, clipPlaneMask ); + + if (triMask == 0x0) + continue; + + ////////////////////////////////////////////////////////////////////////////// + // Project, transform to screen space and perform backface culling. Note + // that we use z = 1.0 / vtx.w for depth, which means that z = 0 is far and + // z = 1 is near. We must also use a greater than depth test, and in effect + // everything is reversed compared to regular z implementations. + ////////////////////////////////////////////////////////////////////////////// + + __mw pVtxX[3], pVtxY[3], pVtxZ[3]; + +#if PRECISE_COVERAGE != 0 + __mwi ipVtxX[3], ipVtxY[3]; + ProjectVertices(ipVtxX, ipVtxY, pVtxX, pVtxY, pVtxZ, vtxX, vtxY, vtxW); +#else + ProjectVertices(pVtxX, pVtxY, pVtxZ, vtxX, vtxY, vtxW); +#endif + + // Perform backface test. + __mw triArea1 = _mmw_mul_ps(_mmw_sub_ps(pVtxX[1], pVtxX[0]), _mmw_sub_ps(pVtxY[2], pVtxY[0])); + __mw triArea2 = _mmw_mul_ps(_mmw_sub_ps(pVtxX[0], pVtxX[2]), _mmw_sub_ps(pVtxY[0], pVtxY[1])); + __mw triArea = _mmw_sub_ps(triArea1, triArea2); + __mw ccwMask = _mmw_cmpgt_ps(triArea, _mmw_setzero_ps()); + +#if PRECISE_COVERAGE != 0 + triMask &= CullBackfaces(ipVtxX, ipVtxY, pVtxX, pVtxY, pVtxZ, ccwMask, bfWinding); +#else + triMask &= CullBackfaces(pVtxX, pVtxY, pVtxZ, ccwMask, bfWinding); +#endif + + if (triMask == 0x0) + continue; + + ////////////////////////////////////////////////////////////////////////////// + // Bin triangles + ////////////////////////////////////////////////////////////////////////////// + + unsigned int binWidth; + unsigned int binHeight; + ComputeBinWidthHeight(nBinsW, nBinsH, binWidth, binHeight); + + // Compute pixel bounding box + __mwi bbPixelMinX, bbPixelMinY, bbPixelMaxX, bbPixelMaxY; + ComputeBoundingBox(bbPixelMinX, bbPixelMinY, bbPixelMaxX, bbPixelMaxY, pVtxX, pVtxY, &mFullscreenScissor); + + while (triMask) + { + unsigned int triIdx = find_clear_lsb(&triMask); + + // Clamp bounding box to bins + int startX = min(nBinsW-1, simd_i32(bbPixelMinX)[triIdx] / binWidth); + int startY = min(nBinsH-1, simd_i32(bbPixelMinY)[triIdx] / binHeight); + int endX = min(nBinsW, (simd_i32(bbPixelMaxX)[triIdx] + binWidth - 1) / binWidth); + int endY = min(nBinsH, (simd_i32(bbPixelMaxY)[triIdx] + binHeight - 1) / binHeight); + + for (int y = startY; y < endY; ++y) + { + for (int x = startX; x < endX; ++x) + { + int binIdx = x + y * nBinsW; + unsigned int writeTriIdx = triLists[binIdx].mTriIdx; + for (int i = 0; i < 3; ++i) + { +#if PRECISE_COVERAGE != 0 + ((int*)triLists[binIdx].mPtr)[i * 3 + writeTriIdx * 9 + 0] = simd_i32(ipVtxX[i])[triIdx]; + ((int*)triLists[binIdx].mPtr)[i * 3 + writeTriIdx * 9 + 1] = simd_i32(ipVtxY[i])[triIdx]; +#else + triLists[binIdx].mPtr[i * 3 + writeTriIdx * 9 + 0] = simd_f32(pVtxX[i])[triIdx]; + triLists[binIdx].mPtr[i * 3 + writeTriIdx * 9 + 1] = simd_f32(pVtxY[i])[triIdx]; +#endif + triLists[binIdx].mPtr[i * 3 + writeTriIdx * 9 + 2] = simd_f32(pVtxZ[i])[triIdx]; + } + triLists[binIdx].mTriIdx++; + } + } + } + } +#if PRECISE_COVERAGE != 0 + _MM_SET_ROUNDING_MODE(originalRoundingMode); +#endif + } + + void BinTriangles(const float *inVtx, const unsigned int *inTris, int nTris, TriList *triLists, unsigned int nBinsW, unsigned int nBinsH, const float *modelToClipMatrix, BackfaceWinding bfWinding, ClipPlanes clipPlaneMask, const VertexLayout &vtxLayout) override + { + if (vtxLayout.mStride == 16 && vtxLayout.mOffsetY == 4 && vtxLayout.mOffsetW == 12) + BinTriangles(inVtx, inTris, nTris, triLists, nBinsW, nBinsH, modelToClipMatrix, bfWinding, clipPlaneMask, vtxLayout); + else + BinTriangles(inVtx, inTris, nTris, triLists, nBinsW, nBinsH, modelToClipMatrix, bfWinding, clipPlaneMask, vtxLayout); + } + + template + void GatherTransformClip( int & clipHead, int & clipTail, int & numLanes, int nTris, int & triIndex, __mw * vtxX, __mw * vtxY, __mw * vtxW, const float * inVtx, const unsigned int * &inTrisPtr, const VertexLayout & vtxLayout, const float * modelToClipMatrix, __m128 * clipTriBuffer, unsigned int &triMask, ClipPlanes clipPlaneMask ) + { + ////////////////////////////////////////////////////////////////////////////// + // Assemble triangles from the index list + ////////////////////////////////////////////////////////////////////////////// + unsigned int triClipMask = SIMD_ALL_LANES_MASK; + + if( clipHead != clipTail ) + { + int clippedTris = clipHead > clipTail ? clipHead - clipTail : MAX_CLIPPED + clipHead - clipTail; + clippedTris = min( clippedTris, SIMD_LANES ); + +#if CLIPPING_PRESERVES_ORDER != 0 + // if preserving order, don't mix clipped and new triangles, handle the clip buffer fully + // and then continue gathering; this is not as efficient - ideally we want to gather + // at the end (if clip buffer has less than SIMD_LANES triangles) but that requires + // more modifications below - something to do in the future. + numLanes = 0; +#else + // Fill out SIMD registers by fetching more triangles. + numLanes = max( 0, min( SIMD_LANES - clippedTris, nTris - triIndex ) ); +#endif + + if( numLanes > 0 ) { + if( FAST_GATHER ) + GatherVerticesFast( vtxX, vtxY, vtxW, inVtx, inTrisPtr, numLanes ); + else + GatherVertices( vtxX, vtxY, vtxW, inVtx, inTrisPtr, numLanes, vtxLayout ); + + TransformVerts( vtxX, vtxY, vtxW, modelToClipMatrix ); + } + + for( int clipTri = numLanes; clipTri < numLanes + clippedTris; clipTri++ ) + { + int triIdx = clipTail * 3; + for( int i = 0; i < 3; i++ ) + { + simd_f32( vtxX[i] )[clipTri] = simd_f32( clipTriBuffer[triIdx + i] )[0]; + simd_f32( vtxY[i] )[clipTri] = simd_f32( clipTriBuffer[triIdx + i] )[1]; + simd_f32( vtxW[i] )[clipTri] = simd_f32( clipTriBuffer[triIdx + i] )[2]; + } + clipTail = ( clipTail + 1 ) & ( MAX_CLIPPED - 1 ); + } + + triIndex += numLanes; + inTrisPtr += numLanes * 3; + + triMask = ( 1U << ( clippedTris + numLanes ) ) - 1; + triClipMask = ( 1U << numLanes ) - 1; // Don't re-clip already clipped triangles + } + else + { + numLanes = min( SIMD_LANES, nTris - triIndex ); + triMask = ( 1U << numLanes ) - 1; + triClipMask = triMask; + + if( FAST_GATHER ) + GatherVerticesFast( vtxX, vtxY, vtxW, inVtx, inTrisPtr, numLanes ); + else + GatherVertices( vtxX, vtxY, vtxW, inVtx, inTrisPtr, numLanes, vtxLayout ); + + TransformVerts( vtxX, vtxY, vtxW, modelToClipMatrix ); + + triIndex += SIMD_LANES; + inTrisPtr += SIMD_LANES * 3; + } + + ////////////////////////////////////////////////////////////////////////////// + // Clip transformed triangles + ////////////////////////////////////////////////////////////////////////////// + + if( clipPlaneMask != ClipPlanes::CLIP_PLANE_NONE ) + ClipTriangleAndAddToBuffer( vtxX, vtxY, vtxW, clipTriBuffer, clipHead, triMask, triClipMask, clipPlaneMask ); + } + + void RenderTrilist(const TriList &triList, const ScissorRect *scissor) override + { + assert(mMaskedHiZBuffer != nullptr); + + // Setup fullscreen scissor rect as default + scissor = scissor == nullptr ? &mFullscreenScissor : scissor; + + for (unsigned int i = 0; i < triList.mTriIdx; i += SIMD_LANES) + { + ////////////////////////////////////////////////////////////////////////////// + // Fetch triangle vertices + ////////////////////////////////////////////////////////////////////////////// + + unsigned int numLanes = min((unsigned int)SIMD_LANES, triList.mTriIdx - i); + unsigned int triMask = (1U << numLanes) - 1; + + __mw pVtxX[3], pVtxY[3], pVtxZ[3]; +#if PRECISE_COVERAGE != 0 + __mwi ipVtxX[3], ipVtxY[3]; + for (unsigned int l = 0; l < numLanes; ++l) + { + unsigned int triIdx = i + l; + for (int v = 0; v < 3; ++v) + { + simd_i32(ipVtxX[v])[l] = ((int*)triList.mPtr)[v * 3 + triIdx * 9 + 0]; + simd_i32(ipVtxY[v])[l] = ((int*)triList.mPtr)[v * 3 + triIdx * 9 + 1]; + simd_f32(pVtxZ[v])[l] = triList.mPtr[v * 3 + triIdx * 9 + 2]; + } + } + + for (int v = 0; v < 3; ++v) + { + pVtxX[v] = _mmw_mul_ps(_mmw_cvtepi32_ps(ipVtxX[v]), _mmw_set1_ps(FP_INV)); + pVtxY[v] = _mmw_mul_ps(_mmw_cvtepi32_ps(ipVtxY[v]), _mmw_set1_ps(FP_INV)); + } + + ////////////////////////////////////////////////////////////////////////////// + // Setup and rasterize a SIMD batch of triangles + ////////////////////////////////////////////////////////////////////////////// + + RasterizeTriangleBatch(ipVtxX, ipVtxY, pVtxX, pVtxY, pVtxZ, triMask, scissor); +#else + for (unsigned int l = 0; l < numLanes; ++l) + { + unsigned int triIdx = i + l; + for (int v = 0; v < 3; ++v) + { + simd_f32(pVtxX[v])[l] = triList.mPtr[v * 3 + triIdx * 9 + 0]; + simd_f32(pVtxY[v])[l] = triList.mPtr[v * 3 + triIdx * 9 + 1]; + simd_f32(pVtxZ[v])[l] = triList.mPtr[v * 3 + triIdx * 9 + 2]; + } + } + + ////////////////////////////////////////////////////////////////////////////// + // Setup and rasterize a SIMD batch of triangles + ////////////////////////////////////////////////////////////////////////////// + + RasterizeTriangleBatch(pVtxX, pVtxY, pVtxZ, triMask, scissor); +#endif + + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Debugging and statistics + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + MaskedOcclusionCulling::Implementation GetImplementation() override + { + return gInstructionSet; + } + + void ComputePixelDepthBuffer(float *depthData, bool flipY) override + { + assert(mMaskedHiZBuffer != nullptr); + for (int y = 0; y < mHeight; y++) + { + for (int x = 0; x < mWidth; x++) + { + // Compute 32xN tile index (SIMD value offset) + int tx = x / TILE_WIDTH; + int ty = y / TILE_HEIGHT; + int tileIdx = ty * mTilesWidth + tx; + + // Compute 8x4 subtile index (SIMD lane offset) + int stx = (x % TILE_WIDTH) / SUB_TILE_WIDTH; + int sty = (y % TILE_HEIGHT) / SUB_TILE_HEIGHT; + int subTileIdx = sty * 4 + stx; + + // Compute pixel index in subtile (bit index in 32-bit word) + int px = (x % SUB_TILE_WIDTH); + int py = (y % SUB_TILE_HEIGHT); + int bitIdx = py * 8 + px; + + int pixelLayer = (simd_i32(mMaskedHiZBuffer[tileIdx].mMask)[subTileIdx] >> bitIdx) & 1; + float pixelDepth = simd_f32(mMaskedHiZBuffer[tileIdx].mZMin[pixelLayer])[subTileIdx]; + + if( flipY ) + depthData[( mHeight - y - 1 ) * mWidth + x] = pixelDepth; + else + depthData[y * mWidth + x] = pixelDepth; + } + } + } + + OcclusionCullingStatistics GetStatistics() override + { + return mStats; + } + +}; diff --git a/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/PackageInfo.json b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/PackageInfo.json new file mode 100644 index 0000000000..08b29fd566 --- /dev/null +++ b/Gems/Atom/RPI/Code/External/MaskedOcclusionCulling/PackageInfo.json @@ -0,0 +1,6 @@ +{ + "PackageName": "Masked Occlusion Culling", + "URL": "https://software.intel.com/content/www/us/en/develop/articles/masked-software-occlusion-culling.html", + "License": "Apache 2.0", + "LicenseFile": "LICENSE.txt" +} From afeea878627b29f465eb0da648f06f4e9dbc69b0 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 2 Jun 2021 19:21:39 -0700 Subject: [PATCH 443/811] Fix for linux being a banned keyword --- Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index f30c8912de..069ac49d96 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -38,7 +38,7 @@ #include -#include // for std::powf on linux +#include namespace AZ::ConsoleTypeHelpers { @@ -641,7 +641,7 @@ namespace Multiplayer m_renderBlendFactor += targetAdjustBlend; // Linear close to the origin, but asymptote at y = 1 - const float adjustedBlendFactor = 1.0f - (std::powf(0.2f, m_renderBlendFactor)); + const float adjustedBlendFactor = 1.0f - (std::pow(0.2f, m_renderBlendFactor)); AZLOG(NET_Blending, "Computed blend factor of %f", adjustedBlendFactor); if (Camera::ActiveCameraRequestBus::HasHandlers()) From 89b1afc50e00e7dd78488feb9ba6770544412d9d Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Wed, 2 Jun 2021 19:37:35 -0700 Subject: [PATCH 444/811] Adding Multiplayer:: namespace to RpcIndex so components outside the Multiplayer gem can compile --- Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 5cfd0bfc4d..917b1058a7 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -311,7 +311,7 @@ void {{ ClassName }}::Set{{ UpperFirst(Property.attrib['Name']) }}(const {{ Prop {{ AutoComponentMacros.ParseRpcParams(Property, paramNames, paramTypes, paramDefines) }} void {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.join(paramDefines) }}) { - constexpr RpcIndex rpcId = static_cast({{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure::{{ UpperFirst(Property.attrib['Name']) }}); + constexpr Multiplayer::RpcIndex rpcId = static_cast({{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure::{{ UpperFirst(Property.attrib['Name']) }}); {% if Property.attrib['IsReliable']|booleanTrue %} constexpr AzNetworking::ReliabilityType isReliable = Multiplayer::ReliabilityType::Reliable; {% else %} From 69e2d6bba1022f9e439a8c55edf1bbabf89887da Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Wed, 2 Jun 2021 19:44:55 -0700 Subject: [PATCH 445/811] Minor comment update --- Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h index 7d192ea62a..e611ecf0d6 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h @@ -202,7 +202,7 @@ namespace AZ MatrixChangedEvent m_onWorldToClipMatrixChange; MatrixChangedEvent m_onWorldToViewMatrixChange; - // Software occlusion culling + // Masked Occlusion Culling interface MaskedOcclusionCulling* m_maskedOcclusionCulling = nullptr; }; From d737fcd3d3acd03edd184086e0e4b3754f2c6ed2 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Wed, 2 Jun 2021 19:52:28 -0700 Subject: [PATCH 446/811] Removed extra newline --- Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index 85b6bf07b8..e97805ceb2 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -617,7 +617,6 @@ namespace AZ jobData->m_maskedOcclusionCulling = maskedOcclusionCulling; #endif - auto nodeVisitorLambda = [this, jobData, &parentJob, &frustum, &worklist](const AzFramework::IVisibilityScene::NodeData& nodeData) -> void { AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "nodeVisitorLambda()"); From 113073ca31fcf10b9d2d1ff8e02962c5264c9ff9 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Wed, 2 Jun 2021 19:54:22 -0700 Subject: [PATCH 447/811] Removed unnecessary include --- Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp index c02ac0713c..7e33750eb5 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp @@ -23,7 +23,6 @@ #include #include #include -#include #include #include From b09f73378f3efc08f7fa775e1f49bd38b30f63f3 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 20:49:39 -0700 Subject: [PATCH 448/811] [cpack_installer] replaced LY_DEFAULT_INSTALL_COMPONENT with built-in CMAKE_INSTALL_DEFAULT_COMPONENT_NAME. updated stale references to ly_install_target_COMPONENT with a get_prop call --- cmake/3rdParty.cmake | 2 - cmake/Packaging.cmake | 4 +- cmake/Platform/Common/Install_common.cmake | 46 ++++++++-------------- 3 files changed, 19 insertions(+), 33 deletions(-) diff --git a/cmake/3rdParty.cmake b/cmake/3rdParty.cmake index eb11404237..ebf640af23 100644 --- a/cmake/3rdParty.cmake +++ b/cmake/3rdParty.cmake @@ -291,7 +291,6 @@ function(ly_install_external_target 3RDPARTY_ROOT_DIRECTORY) # Install the Find file to our /cmake directory install(FILES ${CMAKE_CURRENT_LIST_FILE} DESTINATION cmake - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) # We only want to install external targets that are part of our source tree @@ -302,7 +301,6 @@ function(ly_install_external_target 3RDPARTY_ROOT_DIRECTORY) get_filename_component(rel_path ${rel_path} DIRECTORY) install(DIRECTORY ${3RDPARTY_ROOT_DIRECTORY} DESTINATION ${rel_path} - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) endif() diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index e7136eab12..1bcb251271 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -101,7 +101,7 @@ endif() install(FILES ${_cmake_package_dest} DESTINATION ./Tools/Redistributables/CMake - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} ) # IMPORTANT: required to be included AFTER setting all property overrides @@ -141,7 +141,7 @@ endfunction() # configure ALL components here ly_configure_cpack_component( - ${LY_DEFAULT_INSTALL_COMPONENT} REQUIRED + ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} REQUIRED DISPLAY_NAME "${PROJECT_NAME} Core" DESCRIPTION "${PROJECT_NAME} Headers, Libraries and Tools" ) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 710a8b266f..e0301bb914 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -11,7 +11,7 @@ set(CMAKE_INSTALL_MESSAGE NEVER) # Simplify messages to reduce output noise -ly_set(LY_DEFAULT_INSTALL_COMPONENT Core) +ly_set(CMAKE_INSTALL_DEFAULT_COMPONENT_NAME Core) file(RELATIVE_PATH runtime_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) file(RELATIVE_PATH library_output_directory ${CMAKE_BINARY_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) @@ -27,6 +27,12 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME) # De-alias target name ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) + # get the component ID. if the property isn't set for the target, fallback to use CMAKE_INSTALL_DEFAULT_COMPONENT_NAME + get_target_property(install_componet ${TARGET_NAME} INSTALL_COMPONENT) + if("${install_componet}" STREQUAL "install_componet-NOTFOUND") + unset(install_componet) + endif() + # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. @@ -41,7 +47,7 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME) unset(current_public_headers) install(DIRECTORY ${include_directory} DESTINATION ${include_location}/${target_source_dir} - COMPONENT ${ly_install_target_COMPONENT} + COMPONENT ${install_componet} FILES_MATCHING PATTERN *.h PATTERN *.hpp @@ -68,13 +74,13 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME) TARGETS ${TARGET_NAME} ARCHIVE DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ - COMPONENT ${ly_install_target_COMPONENT} + COMPONENT ${install_componet} LIBRARY DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} - COMPONENT ${ly_install_target_COMPONENT} + COMPONENT ${install_componet} RUNTIME DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} - COMPONENT ${ly_install_target_COMPONENT} + COMPONENT ${install_componet} ) # CMakeLists.txt file @@ -182,7 +188,7 @@ set_property(TARGET ${TARGET_NAME} file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" DESTINATION ${target_source_dir} - COMPONENT ${ly_install_target_COMPONENT} + COMPONENT ${install_componet} ) # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target @@ -239,9 +245,13 @@ function(ly_setup_subdirectory absolute_target_source_dir) "\n" "${CREATE_ALIASES_PLACEHOLDER}" ) + + # get the component ID. if the property isn't set for the directory, it will auto fallback to use CMAKE_INSTALL_DEFAULT_COMPONENT_NAME + get_property(install_componet DIRECTORY ${absolute_target_source_dir} PROPERTY INSTALL_COMPONENT) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/CMakeLists.txt" DESTINATION ${target_source_dir} - COMPONENT ${ly_install_target_COMPONENT} + COMPONENT ${install_componet} ) endfunction() @@ -262,7 +272,6 @@ function(ly_setup_cmake_install) install(DIRECTORY "${LY_ROOT_FOLDER}/cmake" DESTINATION . - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} PATTERN "__pycache__" EXCLUDE REGEX "Findo3de.cmake" EXCLUDE REGEX "Platform\/.*\/BuiltInPackages_.*\.cmake" EXCLUDE @@ -290,7 +299,6 @@ function(ly_setup_cmake_install) "${LY_ROOT_FOLDER}/CMakeLists.txt" "${CMAKE_CURRENT_BINARY_DIR}/cmake/engine.json" DESTINATION . - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) # Collect all Find files that were added with ly_add_external_target_path @@ -303,7 +311,6 @@ function(ly_setup_cmake_install) endforeach() install(FILES ${additional_find_files} DESTINATION cmake/3rdParty - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) # Findo3de.cmake file: we generate a different Findo3de.camke file than the one we have in cmake. This one is going to expose all @@ -320,7 +327,6 @@ function(ly_setup_cmake_install) configure_file(${LY_ROOT_FOLDER}/cmake/install/Findo3de.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/Findo3de.cmake @ONLY) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/cmake/Findo3de.cmake" DESTINATION cmake - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) # BuiltInPackage_.cmake: since associations could happen in any cmake file across the engine. We collect @@ -340,7 +346,6 @@ function(ly_setup_cmake_install) ) install(FILES "${pal_builtin_file}" DESTINATION cmake/3rdParty/Platform/${PAL_PLATFORM_NAME} - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) endfunction() @@ -362,7 +367,6 @@ endfunction() function(ly_copy source_file target_directory) file(COPY \"\${source_file}\" DESTINATION \"\${target_directory}\" FILE_PERMISSIONS ${LY_COPY_PERMISSIONS}) endfunction()" - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) unset(runtime_commands) @@ -408,7 +412,6 @@ endfunction()" list(REMOVE_DUPLICATES runtime_commands) list(JOIN runtime_commands " " runtime_commands_str) # the spaces are just to see the right identation in the cmake_install.cmake file install(CODE "${runtime_commands_str}" - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) endfunction() @@ -427,7 +430,6 @@ function(ly_setup_others) install(DIRECTORY "${LY_ROOT_FOLDER}/${dir}" DESTINATION ${install_path} - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} PATTERN "__pycache__" EXCLUDE ) @@ -438,7 +440,6 @@ function(ly_setup_others) install(FILES ${o3de_scripts} DESTINATION ./scripts - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) install(DIRECTORY @@ -446,7 +447,6 @@ function(ly_setup_others) ${LY_ROOT_FOLDER}/scripts/project_manager ${LY_ROOT_FOLDER}/scripts/o3de DESTINATION ./scripts - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} PATTERN "__pycache__" EXCLUDE PATTERN "CMakeLists.txt" EXCLUDE PATTERN "tests" EXCLUDE @@ -454,7 +454,6 @@ function(ly_setup_others) install(DIRECTORY "${LY_ROOT_FOLDER}/python" DESTINATION . - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} REGEX "downloaded_packages" EXCLUDE REGEX "runtime" EXCLUDE ) @@ -463,19 +462,16 @@ function(ly_setup_others) install(DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/$/Registry DESTINATION ./${runtime_output_directory}/${PAL_PLATFORM_NAME}/$ - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) install(DIRECTORY ${LY_ROOT_FOLDER}/Registry DESTINATION . - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) # Engine Source Assets install(DIRECTORY ${LY_ROOT_FOLDER}/Assets DESTINATION . - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) # Gem Source Assets and Registry @@ -495,7 +491,6 @@ function(ly_setup_others) # the "Assets" folder from being copied underneath the /Assets folder install(DIRECTORY ${gem_abs_assets_path} DESTINATION ${gem_assets_path} - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) endif() endforeach() @@ -511,7 +506,6 @@ function(ly_setup_others) get_filename_component(gem_relative_path ${gem_json_path} DIRECTORY) install(FILES ${gem_json_path} DESTINATION ${gem_relative_path} - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) endforeach() @@ -519,14 +513,12 @@ function(ly_setup_others) install(DIRECTORY ${LY_ROOT_FOLDER}/Gems/Atom/Asset/ImageProcessingAtom/Config DESTINATION Gems/Atom/Asset/ImageProcessingAtom - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) # Templates install(DIRECTORY ${LY_ROOT_FOLDER}/Templates DESTINATION . - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) # Misc @@ -535,7 +527,6 @@ function(ly_setup_others) ${LY_ROOT_FOLDER}/LICENSE.txt ${LY_ROOT_FOLDER}/README.md DESTINATION . - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) endfunction() @@ -549,15 +540,12 @@ function(ly_setup_target_generator) ${LY_ROOT_FOLDER}/Code/LauncherUnified/LauncherProject.cpp ${LY_ROOT_FOLDER}/Code/LauncherUnified/StaticModules.in DESTINATION LauncherGenerator - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) install(DIRECTORY ${LY_ROOT_FOLDER}/Code/LauncherUnified/Platform DESTINATION LauncherGenerator - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) install(FILES ${LY_ROOT_FOLDER}/Code/LauncherUnified/FindLauncherGenerator.cmake DESTINATION cmake - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) endfunction() From 99497672f4188479a92f45411ee66a09012c23ec Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Wed, 2 Jun 2021 20:51:07 -0700 Subject: [PATCH 449/811] Fixed cmake platform files for non-Windows platforms --- .../Code/Source/Platform/Android/platform_android_files.cmake | 4 ++-- .../RPI/Code/Source/Platform/Linux/platform_linux_files.cmake | 4 ++-- .../RPI/Code/Source/Platform/Mac/platform_mac_files.cmake | 4 ++-- .../RPI/Code/Source/Platform/iOS/platform_ios_files.cmake | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/Platform/Android/platform_android_files.cmake b/Gems/Atom/RPI/Code/Source/Platform/Android/platform_android_files.cmake index 357d8f0381..83ddc410d6 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Android/platform_android_files.cmake +++ b/Gems/Atom/RPI/Code/Source/Platform/Android/platform_android_files.cmake @@ -10,6 +10,6 @@ # set(FILES - Atom_Feature_Traits_Platform.h - Atom_Feature_Traits_Android.h + Atom_RPI_Traits_Platform.h + Atom_RPI_Traits_Android.h ) diff --git a/Gems/Atom/RPI/Code/Source/Platform/Linux/platform_linux_files.cmake b/Gems/Atom/RPI/Code/Source/Platform/Linux/platform_linux_files.cmake index 19be7951f6..99df861f9c 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Linux/platform_linux_files.cmake +++ b/Gems/Atom/RPI/Code/Source/Platform/Linux/platform_linux_files.cmake @@ -10,6 +10,6 @@ # set(FILES - Atom_Feature_Traits_Platform.h - Atom_Feature_Traits_Linux.h + Atom_RPI_Traits_Platform.h + Atom_RPI_Traits_Linux.h ) diff --git a/Gems/Atom/RPI/Code/Source/Platform/Mac/platform_mac_files.cmake b/Gems/Atom/RPI/Code/Source/Platform/Mac/platform_mac_files.cmake index bde67ff340..b1baca036e 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Mac/platform_mac_files.cmake +++ b/Gems/Atom/RPI/Code/Source/Platform/Mac/platform_mac_files.cmake @@ -10,6 +10,6 @@ # set(FILES - Atom_Feature_Traits_Platform.h - Atom_Feature_Traits_Mac.h + Atom_RPI_Traits_Platform.h + Atom_RPI_Traits_Mac.h ) diff --git a/Gems/Atom/RPI/Code/Source/Platform/iOS/platform_ios_files.cmake b/Gems/Atom/RPI/Code/Source/Platform/iOS/platform_ios_files.cmake index 7f603e4bfd..3eae72e612 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/iOS/platform_ios_files.cmake +++ b/Gems/Atom/RPI/Code/Source/Platform/iOS/platform_ios_files.cmake @@ -10,6 +10,6 @@ # set(FILES - Atom_Feature_Traits_Platform.h - Atom_Feature_Traits_iOS.h + Atom_RPI_Traits_Platform.h + Atom_RPI_Traits_iOS.h ) From 9afd9b0992befcd19390cea11ec74bdb0080103a Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Wed, 2 Jun 2021 20:58:22 -0700 Subject: [PATCH 450/811] Fixed PAL cmake files for non-Windows builds --- .../Code/Source/Platform/Android/PAL_android.cmake | 13 +++++++++++++ .../RPI/Code/Source/Platform/Linux/PAL_linux.cmake | 1 + .../Atom/RPI/Code/Source/Platform/Mac/PAL_mac.cmake | 1 + .../Atom/RPI/Code/Source/Platform/iOS/PAL_ios.cmake | 13 +++++++++++++ 4 files changed, 28 insertions(+) create mode 100644 Gems/Atom/RPI/Code/Source/Platform/Android/PAL_android.cmake create mode 100644 Gems/Atom/RPI/Code/Source/Platform/iOS/PAL_ios.cmake diff --git a/Gems/Atom/RPI/Code/Source/Platform/Android/PAL_android.cmake b/Gems/Atom/RPI/Code/Source/Platform/Android/PAL_android.cmake new file mode 100644 index 0000000000..4542e7c707 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Android/PAL_android.cmake @@ -0,0 +1,13 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set (PAL_TRAIT_BUILD_ATOM_RPI_ASSETS_SUPPORTED FALSE) +set (PAL_TRAIT_BUILD_ATOM_RPI_MASKED_OCCLUSION_CULLING_SUPPORTED FALSE) diff --git a/Gems/Atom/RPI/Code/Source/Platform/Linux/PAL_linux.cmake b/Gems/Atom/RPI/Code/Source/Platform/Linux/PAL_linux.cmake index e9a14ba928..4542e7c707 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Linux/PAL_linux.cmake +++ b/Gems/Atom/RPI/Code/Source/Platform/Linux/PAL_linux.cmake @@ -10,3 +10,4 @@ # set (PAL_TRAIT_BUILD_ATOM_RPI_ASSETS_SUPPORTED FALSE) +set (PAL_TRAIT_BUILD_ATOM_RPI_MASKED_OCCLUSION_CULLING_SUPPORTED FALSE) diff --git a/Gems/Atom/RPI/Code/Source/Platform/Mac/PAL_mac.cmake b/Gems/Atom/RPI/Code/Source/Platform/Mac/PAL_mac.cmake index c060b8bbaa..f177b9dfb9 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Mac/PAL_mac.cmake +++ b/Gems/Atom/RPI/Code/Source/Platform/Mac/PAL_mac.cmake @@ -10,3 +10,4 @@ # set (PAL_TRAIT_BUILD_ATOM_RPI_ASSETS_SUPPORTED TRUE) +set (PAL_TRAIT_BUILD_ATOM_RPI_MASKED_OCCLUSION_CULLING_SUPPORTED FALSE) diff --git a/Gems/Atom/RPI/Code/Source/Platform/iOS/PAL_ios.cmake b/Gems/Atom/RPI/Code/Source/Platform/iOS/PAL_ios.cmake new file mode 100644 index 0000000000..4542e7c707 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/iOS/PAL_ios.cmake @@ -0,0 +1,13 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set (PAL_TRAIT_BUILD_ATOM_RPI_ASSETS_SUPPORTED FALSE) +set (PAL_TRAIT_BUILD_ATOM_RPI_MASKED_OCCLUSION_CULLING_SUPPORTED FALSE) From 5695681ed3518d3e7c4ab7ed3aad92c4bb01d422 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 21:03:41 -0700 Subject: [PATCH 451/811] [cpack_installer] fifth attempt to fix cpack selection --- scripts/build/Platform/Windows/installer_windows.cmd | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/scripts/build/Platform/Windows/installer_windows.cmd b/scripts/build/Platform/Windows/installer_windows.cmd index 73d1a3d88c..c71b091de9 100644 --- a/scripts/build/Platform/Windows/installer_windows.cmd +++ b/scripts/build/Platform/Windows/installer_windows.cmd @@ -29,22 +29,25 @@ IF NOT EXIST "%WIX_TEMP%" ( REM Make sure we are using the CMake version of CPack and not the one that comes with chocolatey SET CPACK_PATH= IF "%LY_CMAKE_PATH%"=="" ( - FOR /F %%i in ('where cpack') DO ( + REM quote the paths from 'where' so we can properly tokenize ones in the list with spaces + FOR /F delims^=^"^ tokens^=1 %%i in ('where /F cpack') DO ( REM The cpack in chocolatey expects a number supplied with --version so it will error "%%i" --version > NUL IF !ERRORLEVEL!==0 ( SET "CPACK_PATH=%%i" + GOTO :run_cpack ) ) ) ELSE ( SET "CPACK_PATH=%LY_CMAKE_PATH%\cpack.exe" ) +:run_cpack ECHO [ci_build] "!CPACK_PATH!" --version "!CPACK_PATH!" --version IF ERRORLEVEL 1 ( ECHO [ci_build] CPack not found! - exit /b 1 + GOTO :popd_error ) ECHO [ci_build] "!CPACK_PATH!" -C %CONFIGURATION% From 091d6894cb928d51d61a6d026b6854ca304da47b Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Wed, 2 Jun 2021 22:02:10 -0700 Subject: [PATCH 452/811] Fixed non-Windows platform include --- .../RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Platform.h | 2 +- .../RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Platform.h | 2 +- .../RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Platform.h | 2 +- .../RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_Platform.h | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Platform.h b/Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Platform.h index 27e0af7f35..60835c7025 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Platform.h +++ b/Gems/Atom/RPI/Code/Source/Platform/Android/Atom_RPI_Traits_Platform.h @@ -11,4 +11,4 @@ */ #pragma once -#include "Atom_Feature_Traits_Android.h" +#include "Atom_RPI_Traits_Android.h" diff --git a/Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Platform.h b/Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Platform.h index 39c6a3e572..f7a51ddbf7 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Platform.h +++ b/Gems/Atom/RPI/Code/Source/Platform/Linux/Atom_RPI_Traits_Platform.h @@ -11,4 +11,4 @@ */ #pragma once -#include "Atom_Feature_Traits_Linux.h" +#include "Atom_RPI_Traits_Linux.h" diff --git a/Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Platform.h b/Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Platform.h index 19816f2bd1..87bc2190f3 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Platform.h +++ b/Gems/Atom/RPI/Code/Source/Platform/Mac/Atom_RPI_Traits_Platform.h @@ -11,4 +11,4 @@ */ #pragma once -#include "Atom_Feature_Traits_Mac.h" +#include "Atom_RPI_Traits_Mac.h" diff --git a/Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_Platform.h b/Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_Platform.h index 4403d741dc..48fe26cc61 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_Platform.h +++ b/Gems/Atom/RPI/Code/Source/Platform/iOS/Atom_RPI_Traits_Platform.h @@ -11,4 +11,4 @@ */ #pragma once -#include "Atom_Feature_Traits_iOS.h" +#include "Atom_RPI_Traits_iOS.h" From 602dd01434848ad04e32123e1dbd6d0aeb717824 Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 22:02:11 -0700 Subject: [PATCH 453/811] [cpack_installer] fixed typo in error message --- cmake/Packaging.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index 1bcb251271..e2aa0f9348 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -54,7 +54,7 @@ endif() if(${CPACK_DESIRED_CMAKE_VERSION} VERSION_LESS ${CMAKE_MINIMUM_REQUIRED_VERSION}) message(FATAL_ERROR "The desired version of CMake to be included in the package is " - "is below the minium required version of CMake to run") + "is below the minimum required version of CMake to run") endif() # pull down the desired copy of CMake so it can be included in the package From 881c51dc9c9ff3caa1f4b404c91e9cbaf74bd6ab Mon Sep 17 00:00:00 2001 From: scottr Date: Wed, 2 Jun 2021 22:05:20 -0700 Subject: [PATCH 454/811] [cpack_installer] removed unnecessary explicit use of CMAKE_INSTALL_DEFAULT_COMPONENT_NAME --- cmake/Packaging.cmake | 1 - 1 file changed, 1 deletion(-) diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index e2aa0f9348..e5799c8ff1 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -101,7 +101,6 @@ endif() install(FILES ${_cmake_package_dest} DESTINATION ./Tools/Redistributables/CMake - COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} ) # IMPORTANT: required to be included AFTER setting all property overrides From eb67b6b452a768c10e2a905711e2ab1710bcbc4a Mon Sep 17 00:00:00 2001 From: igarri Date: Thu, 3 Jun 2021 13:36:47 +0100 Subject: [PATCH 455/811] Adding namespace aliases and API comments --- .../Views/AssetBrowserTableView.h | 2 +- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 71 +++++++++---------- 2 files changed, 36 insertions(+), 37 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h index 65f97d1a6d..15bc95f13c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -32,7 +32,7 @@ namespace AzToolsFramework class AssetBrowserFilterModel; class EntryDelegate; - class AssetBrowserTableView + class AssetBrowserTableView //! Table view that displays the asset browser entries in a list. : public QTableView , public AssetBrowserViewRequestBus::Handler , public AssetBrowserComponentNotificationBus::Handler diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 90b597e273..481cc35635 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -74,8 +74,9 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->setupUi(this); m_ui->m_searchWidget->Setup(true, true); - using namespace AzToolsFramework::AssetBrowser; - AssetBrowserComponentRequestBus::BroadcastResult(m_assetBrowserModel, &AssetBrowserComponentRequests::GetAssetBrowserModel); + namespace AB = AzToolsFramework::AssetBrowser; + + AB::AssetBrowserComponentRequestBus::BroadcastResult(m_assetBrowserModel, &AB::AssetBrowserComponentRequests::GetAssetBrowserModel); AZ_Assert(m_assetBrowserModel, "Failed to get filebrowser model"); m_filterModel->setSourceModel(m_assetBrowserModel); m_filterModel->SetFilter(m_ui->m_searchWidget->GetFilter()); @@ -89,34 +90,34 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_tableModel->setSourceModel(m_filterModel.data()); m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); connect( - m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, m_tableModel.data(), - &AssetBrowserTableModel::UpdateTableModelMaps); + m_filterModel.data(), &AB::AssetBrowserFilterModel::filterChanged, m_tableModel.data(), + &AB::AssetBrowserTableModel::UpdateTableModelMaps); connect( - m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::selectionChangedSignal, this, + m_ui->m_assetBrowserTableViewWidget, &AB::AssetBrowserTableView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); connect( m_ui->m_assetBrowserTableViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItemTableModel); connect( - m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::ClearStringFilter, m_ui->m_searchWidget, - &SearchWidget::ClearStringFilter); + m_ui->m_assetBrowserTableViewWidget, &AB::AssetBrowserTableView::ClearStringFilter, m_ui->m_searchWidget, + &AB::SearchWidget::ClearStringFilter); connect( - m_ui->m_assetBrowserTableViewWidget, &AssetBrowserTableView::ClearTypeFilter, m_ui->m_searchWidget, - &SearchWidget::ClearTypeFilter); + m_ui->m_assetBrowserTableViewWidget, &AB::AssetBrowserTableView::ClearTypeFilter, m_ui->m_searchWidget, + &AB::SearchWidget::ClearTypeFilter); m_ui->m_assetBrowserTableViewWidget->SetName("AssetBrowserTableView_main"); - connect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); + connect(m_filterModel.data(), &AB::AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); connect(m_ui->m_viewSwitcherCheckBox, &QCheckBox::stateChanged, this, &AzAssetBrowserWindow::LockToDefaultView); } m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); connect( - m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), - &AssetBrowserFilterModel::filterUpdatedSlot); + m_ui->m_searchWidget->GetFilter().data(), &AB::AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), + &AB::AssetBrowserFilterModel::filterUpdatedSlot); connect( - m_filterModel.data(), &AssetBrowserFilterModel::filterChanged, this, + m_filterModel.data(), &AB::AssetBrowserFilterModel::filterChanged, this, [this]() { const bool hasFilter = !m_ui->m_searchWidget->GetFilterString().isEmpty(); @@ -125,16 +126,17 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) }); connect( - m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::selectionChangedSignal, this, + m_ui->m_assetBrowserTreeViewWidget, &AB::AssetBrowserTreeView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); connect(m_ui->m_assetBrowserTreeViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); connect( - m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, - &SearchWidget::ClearStringFilter); + m_ui->m_assetBrowserTreeViewWidget, &AB::AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, + &AB::SearchWidget::ClearStringFilter); connect( - m_ui->m_assetBrowserTreeViewWidget, &AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, &SearchWidget::ClearTypeFilter); + m_ui->m_assetBrowserTreeViewWidget, &AB::AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, + &AB::SearchWidget::ClearTypeFilter); m_ui->m_assetBrowserTreeViewWidget->SetName("AssetBrowserTreeView_main"); } @@ -192,8 +194,6 @@ static void ExpandTreeToIndex(QTreeView* treeView, const QModelIndex& index) void AzAssetBrowserWindow::SelectAsset(const QString& assetPath) { - using namespace AzToolsFramework::AssetBrowser; - QModelIndex index = m_assetBrowserModel->findIndex(assetPath); if (index.isValid()) { @@ -232,21 +232,21 @@ void AzAssetBrowserWindow::SelectionChangedSlot(const QItemSelection& /*selected // just becuase on some OS clicking once is activation. void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& element) { - using namespace AzToolsFramework; - using namespace AzToolsFramework::AssetBrowser; + namespace AB = AzToolsFramework::AssetBrowser; + // assumption: Double clicking an item selects it before telling us we double clicked it. const auto& selectedAssets = m_ui->m_assetBrowserTreeViewWidget->GetSelectedAssets(); - for (const AssetBrowserEntry* entry : selectedAssets) + for (const AB::AssetBrowserEntry* entry : selectedAssets) { AZ::Data::AssetId assetIdToOpen; AZStd::string fullFilePath; - if (const ProductAssetBrowserEntry* productEntry = azrtti_cast(entry)) + if (const AB::ProductAssetBrowserEntry* productEntry = azrtti_cast(entry)) { assetIdToOpen = productEntry->GetAssetId(); fullFilePath = entry->GetFullPath(); } - else if (const SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry)) + else if (const AB::SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry)) { // manufacture an empty AssetID with the source's UUID assetIdToOpen = AZ::Data::AssetId(sourceEntry->GetSourceUuid(), 0); @@ -256,8 +256,8 @@ void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& bool handledBySomeone = false; if (assetIdToOpen.IsValid()) { - AssetBrowserInteractionNotificationBus::Broadcast( - &AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); + AB::AssetBrowserInteractionNotificationBus::Broadcast( + &AB::AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); } if (!handledBySomeone && !fullFilePath.empty()) @@ -269,21 +269,20 @@ void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& void AzAssetBrowserWindow::DoubleClickedItemTableModel([[maybe_unused]] const QModelIndex& element) { - using namespace AzToolsFramework; - using namespace AzToolsFramework::AssetBrowser; + namespace AB = AzToolsFramework::AssetBrowser; // assumption: Double clicking an item selects it before telling us we double clicked it. const auto& selectedAssets = m_ui->m_assetBrowserTableViewWidget->GetSelectedAssets(); - for (const AssetBrowserEntry* entry : selectedAssets) + for (const AB::AssetBrowserEntry* entry : selectedAssets) { AZ::Data::AssetId assetIdToOpen; AZStd::string fullFilePath; - if (const ProductAssetBrowserEntry* productEntry = azrtti_cast(entry)) + if (const AB::ProductAssetBrowserEntry* productEntry = azrtti_cast(entry)) { assetIdToOpen = productEntry->GetAssetId(); fullFilePath = entry->GetFullPath(); } - else if (const SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry)) + else if (const AB::SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry)) { // manufacture an empty AssetID with the source's UUID assetIdToOpen = AZ::Data::AssetId(sourceEntry->GetSourceUuid(), 0); @@ -293,8 +292,8 @@ void AzAssetBrowserWindow::DoubleClickedItemTableModel([[maybe_unused]] const QM bool handledBySomeone = false; if (assetIdToOpen.IsValid()) { - AssetBrowserInteractionNotificationBus::Broadcast( - &AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); + AB::AssetBrowserInteractionNotificationBus::Broadcast( + &AB::AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); } if (!handledBySomeone && !fullFilePath.empty()) @@ -312,12 +311,12 @@ void AzAssetBrowserWindow::SwitchDisplayView(bool state) void AzAssetBrowserWindow::LockToDefaultView(bool state) { - using namespace AzToolsFramework; - using namespace AzToolsFramework::AssetBrowser; + using AzToolsFramework::AssetBrowser::AssetBrowserFilterModel; SwitchDisplayView(!state); if (state == true) { - disconnect(m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); + disconnect( + m_filterModel.data(), &AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); } else { From f2a7cd9a2da207c118ae56f58dd8077f3d1960dd Mon Sep 17 00:00:00 2001 From: Terry Michaels Date: Thu, 3 Jun 2021 08:29:24 -0500 Subject: [PATCH 456/811] Fixed monolithic build warning/error (#1116) --- Gems/LyShine/Code/Source/LyShineSystemComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp b/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp index 0eab7705f6..1290683145 100644 --- a/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp +++ b/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp @@ -375,7 +375,7 @@ namespace LyShine } /////////////////////////////////////////////////////////////////////////////////////////////// - void LyShineSystemComponent::OnCrySystemInitialized(ISystem& system, [[maybe_unused]] const SSystemInitParams& startupParams) + void LyShineSystemComponent::OnCrySystemInitialized([[maybe_unused]] ISystem& system, [[maybe_unused]] const SSystemInitParams& startupParams) { #if !defined(AZ_MONOLITHIC_BUILD) // When module is linked dynamically, we must set our gEnv pointer. From 328ced0059f90f66d740d97e2f50721c9724995f Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 3 Jun 2021 07:24:30 -0700 Subject: [PATCH 457/811] [cpack_installer] replaced missing get_target_property hack and fixed a typo --- cmake/Platform/Common/Install_common.cmake | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index e0301bb914..7e6917287f 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -27,11 +27,8 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME) # De-alias target name ly_de_alias_target(${ALIAS_TARGET_NAME} TARGET_NAME) - # get the component ID. if the property isn't set for the target, fallback to use CMAKE_INSTALL_DEFAULT_COMPONENT_NAME - get_target_property(install_componet ${TARGET_NAME} INSTALL_COMPONENT) - if("${install_componet}" STREQUAL "install_componet-NOTFOUND") - unset(install_componet) - endif() + # get the component ID. if the property isn't set for the target, it will auto fallback to use CMAKE_INSTALL_DEFAULT_COMPONENT_NAME + get_property(install_component TARGET ${TARGET_NAME} PROPERTY INSTALL_COMPONENT) # All include directories marked PUBLIC or INTERFACE will be installed. We dont use PUBLIC_HEADER because in order to do that # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the @@ -47,7 +44,7 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME) unset(current_public_headers) install(DIRECTORY ${include_directory} DESTINATION ${include_location}/${target_source_dir} - COMPONENT ${install_componet} + COMPONENT ${install_component} FILES_MATCHING PATTERN *.h PATTERN *.hpp @@ -74,13 +71,13 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME) TARGETS ${TARGET_NAME} ARCHIVE DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ - COMPONENT ${install_componet} + COMPONENT ${install_component} LIBRARY DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} - COMPONENT ${install_componet} + COMPONENT ${install_component} RUNTIME DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} - COMPONENT ${install_componet} + COMPONENT ${install_component} ) # CMakeLists.txt file @@ -188,7 +185,7 @@ set_property(TARGET ${TARGET_NAME} file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" DESTINATION ${target_source_dir} - COMPONENT ${install_componet} + COMPONENT ${install_component} ) # Since a CMakeLists.txt could contain multiple targets, we generate it in a folder per target @@ -247,11 +244,11 @@ function(ly_setup_subdirectory absolute_target_source_dir) ) # get the component ID. if the property isn't set for the directory, it will auto fallback to use CMAKE_INSTALL_DEFAULT_COMPONENT_NAME - get_property(install_componet DIRECTORY ${absolute_target_source_dir} PROPERTY INSTALL_COMPONENT) + get_property(install_component DIRECTORY ${absolute_target_source_dir} PROPERTY INSTALL_COMPONENT) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/CMakeLists.txt" DESTINATION ${target_source_dir} - COMPONENT ${install_componet} + COMPONENT ${install_component} ) endfunction() From cf08f4dab1e7206a8b69e7d79b5f1f0a4b51e398 Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Thu, 3 Jun 2021 15:48:44 +0100 Subject: [PATCH 458/811] Improve camera orbit behavior (#1060) --- Code/Sandbox/Editor/EditorViewportWidget.cpp | 18 +++++++-------- .../SandboxIntegration.cpp | 7 +++--- .../ModularViewportCameraController.h | 5 ++++- ...odularViewportCameraControllerRequestBus.h | 7 +++++- .../ModularViewportCameraController.cpp | 22 +++++++++++++++++-- 5 files changed, 43 insertions(+), 16 deletions(-) diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 24d1590808..667179e3cd 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -1233,7 +1233,7 @@ void EditorViewportWidget::SetViewportId(int id) auto controller = AZStd::make_shared(); controller->SetCameraListBuilderCallback( - [](AzFramework::Cameras& cameras) + [id](AzFramework::Cameras& cameras) { auto firstPersonRotateCamera = AZStd::make_shared(AzFramework::CameraFreeLookButton); auto firstPersonPanCamera = @@ -1243,17 +1243,17 @@ void EditorViewportWidget::SetViewportId(int id) auto orbitCamera = AZStd::make_shared(); orbitCamera->SetLookAtFn( - [](const AZ::Vector3& position, const AZ::Vector3& direction) -> AZStd::optional + [id](const AZ::Vector3& position, const AZ::Vector3& direction) -> AZStd::optional { - AZStd::optional manipulatorTransform; - AzToolsFramework::EditorTransformComponentSelectionRequestBus::EventResult( - manipulatorTransform, AzToolsFramework::GetEntityContextId(), - &AzToolsFramework::EditorTransformComponentSelectionRequestBus::Events::GetManipulatorTransform); + AZStd::optional lookAtAfterInterpolation; + AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( + lookAtAfterInterpolation, id, + &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::LookAtAfterInterpolation); - // initially attempt to use manipulator transform if one exists (there is a selection) - if (manipulatorTransform) + // initially attempt to use the last set look at point after an interpolation has finished + if (lookAtAfterInterpolation.has_value()) { - return manipulatorTransform->GetTranslation(); + return *lookAtAfterInterpolation; } const float RayDistance = 1000.0f; diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 5ff2debe3d..8161d07547 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -1732,13 +1732,14 @@ void SandboxIntegrationManager::GoToEntitiesInViewports(const AzToolsFramework:: // compute new camera transform const float fov = AzFramework::RetrieveFov(viewportContext->GetCameraProjectionMatrix()); const float fovScale = (1.0f / AZStd::tan(fov * 0.5f)); - const float distanceToTarget = selectionSize * fovScale * centerScale; + const float distanceToLookAt = selectionSize * fovScale * centerScale; const AZ::Transform nextCameraTransform = - AZ::Transform::CreateLookAt(aabb.GetCenter() - (forward * distanceToTarget), aabb.GetCenter()); + AZ::Transform::CreateLookAt(aabb.GetCenter() - (forward * distanceToLookAt), aabb.GetCenter()); AtomToolsFramework::ModularViewportCameraControllerRequestBus::Event( viewportContext->GetId(), - &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::InterpolateToTransform, nextCameraTransform); + &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::InterpolateToTransform, nextCameraTransform, + distanceToLookAt); } } } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h index 1318deb355..b88b340926 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h @@ -51,7 +51,8 @@ namespace AtomToolsFramework void UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) override; // ModularViewportCameraControllerRequestBus overrides ... - void InterpolateToTransform(const AZ::Transform& worldFromLocal) override; + void InterpolateToTransform(const AZ::Transform& worldFromLocal, float lookAtDistance) override; + AZStd::optional LookAtAfterInterpolation() const override; private: // AzFramework::ViewportDebugDisplayEventBus overrides ... @@ -71,6 +72,8 @@ namespace AtomToolsFramework AZ::Transform m_transformEnd = AZ::Transform::CreateIdentity(); float m_animationT = 0.0f; CameraMode m_cameraMode = CameraMode::Control; + AZStd::optional m_lookAtAfterInterpolation; //!< The look at point after an interpolation has finished. + //!< Will be cleared when the view changes (camera looks away). bool m_updatingTransform = false; AZ::RPI::ViewportContext::MatrixChangedEvent::Handler m_cameraViewMatrixChangeHandler; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h index 5b90119372..a7f067cdf4 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h @@ -32,7 +32,12 @@ namespace AtomToolsFramework static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; //! Begin a smooth transition of the camera to the requested transform. - virtual void InterpolateToTransform(const AZ::Transform& worldFromLocal) = 0; + //! @param worldFromLocal The transform of where the camera should end up. + //! @param lookAtDistance The distance between the camera transform and the imagined look at point. + virtual void InterpolateToTransform(const AZ::Transform& worldFromLocal, float lookAtDistance) = 0; + + //! Look at point after an interpolation has finished and no translation has occurred. + virtual AZStd::optional LookAtAfterInterpolation() const = 0; protected: ~ModularViewportCameraControllerRequests() = default; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp index 896d9f8043..082dc8f272 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp @@ -140,6 +140,18 @@ namespace AtomToolsFramework m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, event.m_deltaTime.count()); + // if there has been an interpolation, only clear the look at point if it is no longer + // centered in the view (the camera has looked away from it) + if (m_lookAtAfterInterpolation.has_value()) + { + if (const float lookDirection = + (*m_lookAtAfterInterpolation - m_camera.Translation()).GetNormalized().Dot(m_camera.Transform().GetBasisY()); + !AZ::IsCloseMag(lookDirection, 1.0f, 0.001f)) + { + m_lookAtAfterInterpolation = {}; + } + } + viewportContext->SetCameraTransform(m_camera.Transform()); } else if (m_cameraMode == CameraMode::Animation) @@ -148,8 +160,8 @@ namespace AtomToolsFramework { return t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f); }; - const float transitionT = smootherStepFn(m_animationT); + const float transitionT = smootherStepFn(m_animationT); const AZ::Transform current = AZ::Transform::CreateFromQuaternionAndTranslation( m_transformStart.GetRotation().Slerp(m_transformEnd.GetRotation(), transitionT), m_transformStart.GetTranslation().Lerp(m_transformEnd.GetTranslation(), transitionT)); @@ -185,11 +197,17 @@ namespace AtomToolsFramework } } - void ModernViewportCameraControllerInstance::InterpolateToTransform(const AZ::Transform& worldFromLocal) + void ModernViewportCameraControllerInstance::InterpolateToTransform(const AZ::Transform& worldFromLocal, const float lookAtDistance) { m_animationT = 0.0f; m_cameraMode = CameraMode::Animation; m_transformStart = m_camera.Transform(); m_transformEnd = worldFromLocal; + m_lookAtAfterInterpolation = m_transformEnd.GetTranslation() + m_transformEnd.GetBasisY() * lookAtDistance; + } + + AZStd::optional ModernViewportCameraControllerInstance::LookAtAfterInterpolation() const + { + return m_lookAtAfterInterpolation; } } // namespace AtomToolsFramework From 8214706ff9ab2c49cfafc7164bb6dbe0d296112c Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 3 Jun 2021 08:24:01 -0700 Subject: [PATCH 459/811] [cpack_installer] reworked how packaging is enabled for windows --- cmake/Platform/Windows/Packaging_windows.cmake | 10 ++-------- scripts/build/Platform/Windows/build_config.json | 3 +-- scripts/build/Platform/Windows/build_windows.cmd | 8 -------- 3 files changed, 3 insertions(+), 18 deletions(-) diff --git a/cmake/Platform/Windows/Packaging_windows.cmake b/cmake/Platform/Windows/Packaging_windows.cmake index 5210c24e7b..2fd281ad51 100644 --- a/cmake/Platform/Windows/Packaging_windows.cmake +++ b/cmake/Platform/Windows/Packaging_windows.cmake @@ -9,17 +9,11 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(LY_WIX_PATH "" CACHE PATH "Path to the WiX install path") - -if(LY_WIX_PATH) - file(TO_CMAKE_PATH ${LY_WIX_PATH} CPACK_WIX_ROOT) -elseif(DEFINED ENV{WIX}) - file(TO_CMAKE_PATH $ENV{WIX} CPACK_WIX_ROOT) -endif() +set(CPACK_WIX_ROOT "" CACHE PATH "Path to the WiX install path") if(CPACK_WIX_ROOT) if(NOT EXISTS ${CPACK_WIX_ROOT}) - message(FATAL_ERROR "Invalid path supplied for LY_WIX_PATH argument or WIX environment variable") + message(FATAL_ERROR "Invalid path supplied for CPACK_WIX_ROOT argument") endif() else() # early out as no path to WiX has been supplied effectively disabling support diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index b0d16f1fb6..fc4668de0a 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -314,8 +314,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_DISABLE_TEST_MODULES=TRUE", - "CMAKE_INCLUDE_WIX": "True", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_DISABLE_TEST_MODULES=TRUE -DCPACK_WIX_ROOT=\"!WIX!\"", "CMAKE_LY_PROJECTS": "", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" diff --git a/scripts/build/Platform/Windows/build_windows.cmd b/scripts/build/Platform/Windows/build_windows.cmd index 799e6828b2..3e995e1905 100644 --- a/scripts/build/Platform/Windows/build_windows.cmd +++ b/scripts/build/Platform/Windows/build_windows.cmd @@ -38,14 +38,6 @@ IF NOT EXIST %TMP% ( REM Compute half the amount of processors so some jobs can run SET /a HALF_PROCESSORS = NUMBER_OF_PROCESSORS / 2 -IF "%CMAKE_INCLUDE_WIX%"=="True" ( - REM Explicitly enable wix via command line arg for forensic logging - SET CMAKE_OPTIONS=%CMAKE_OPTIONS% -DLY_WIX_PATH="%WIX%" -) ELSE ( - REM Disable implicit enabling of windows packing by clearing out the wix variable - SET WIX= -) - SET LAST_CONFIGURE_CMD_FILE=ci_last_configure_cmd.txt SET CONFIGURE_CMD=cmake %SOURCE_DIRECTORY% %CMAKE_OPTIONS% %EXTRA_CMAKE_OPTIONS% -DLY_3RDPARTY_PATH="%LY_3RDPARTY_PATH%" -DLY_PROJECTS=%CMAKE_LY_PROJECTS% IF NOT EXIST CMakeCache.txt ( From cd619e14dc9b74f845cb4897780ea8aa6004f10b Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Thu, 3 Jun 2021 08:31:38 -0700 Subject: [PATCH 460/811] Allow script canvas users to send RPCs via entityId --- .../Source/AutoGen/AutoComponent_Common.jinja | 2 +- .../Source/AutoGen/AutoComponent_Source.jinja | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja index 61dcacaa94..05403a00ef 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja @@ -175,7 +175,7 @@ void Handle{{ PropertyName }}(AzNetworking::IConnection* invokingConnection, {{ //! {{ PropertyName }} Handler //! {{ Property.attrib['Description'] }} //! HandleOn {{ HandleOn }} -virtual void Handle{{ PropertyName }}(AzNetworking::IConnection* invokingConnection, {{ ', '.join(paramDefines) }}) = 0; +virtual void Handle{{ PropertyName }}([[maybe_unused]] AzNetworking::IConnection* invokingConnection, [[maybe_unused]] {{ ', [[maybe_unused]] '.join(paramDefines) }}) {} {% endif %} {% endmacro %} {# diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 917b1058a7..259f469020 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -368,6 +368,31 @@ void {{ ClassName }}::Signal{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.jo ->Method("{{ UpperFirst(Property.attrib['Name']) }}", [](const {{ ClassName }}* self, {{ ', '.join(paramDefines) }}) { self->m_controller->{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.join(paramNames) }}); }) + ->Method("{{ UpperFirst(Property.attrib['Name']) }}ByEntity", [](AZ::EntityId id, {{ ', '.join(paramDefines) }}) { + + AZ::Entity* entity = AZ::Interface::Get()->FindEntity(id); + if (!entity) + { + AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }} failed. The entity with id %s doesn't exist, please provide a valid entity id.", id.ToString().c_str()) + return; + } + + {{ ClassName }}* networkComponent = entity->FindComponent<{{ ClassName }}>(); + if (!networkComponent) + { + AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }} failed. Entity '%s' (id: %s) is missing {{ ClassName }}, be sure to add {{ ClassName }} to this entity.", entity->GetName().c_str(), id.ToString().c_str()) + return; + } + + {{ ClassName }}Controller* controller = static_cast<{{ ClassName }}Controller*>(networkComponent->GetController()); + if (!controller) + { + AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }} method failed. Entity '%s' (id: %s) {{ ClassName }} is missing the network controller. This RemoteProcedure can only be invoked from {{InvokeFrom}} network entities, because this entity doesn't have a controller, it must not be a {{InvokeFrom}} entity. Please check your network context before attempting to call {{ UpperFirst(Property.attrib['Name']) }}.", entity->GetName().c_str(), id.ToString().c_str()) + return; + } + + controller->{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.join(paramNames) }}); + }) {% endif %} {% endcall %} {% endmacro %} From 5fbf587b9e34a88a7b26d8ccbde77f6ae9fa15a4 Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Thu, 3 Jun 2021 10:50:27 -0500 Subject: [PATCH 461/811] Updating File Menu actions in test_Menus_FileMenuOptions_Work. Temporarily marking test as xfail due to LYN-4208 --- .../EditorScripts/Menus_FileMenuOptions.py | 10 ++++----- .../Gem/PythonTests/editor/test_Menus.py | 21 ++++++++++--------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_FileMenuOptions.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_FileMenuOptions.py index 3e174af2bd..734226a9d1 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_FileMenuOptions.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_FileMenuOptions.py @@ -9,11 +9,6 @@ remove or modify any license notices. This file is distributed on an "AS IS" BAS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ -""" -C24064528: The File menu options function normally -C16780778: The File menu options function normally-New view interaction Model enabled -""" - import os import sys @@ -54,7 +49,10 @@ class TestFileMenuOptions(EditorTestHelper): ("Save",), ("Save As",), ("Save Level Statistics",), - ("Project Settings", "Project Settings Tool"), + ("Edit Project Settings",), + ("Edit Platform Settings",), + ("New Project",), + ("Open Project",), ("Show Log File",), ("Resave All Slices",), ("Exit",), diff --git a/AutomatedTesting/Gem/PythonTests/editor/test_Menus.py b/AutomatedTesting/Gem/PythonTests/editor/test_Menus.py index c2da1343de..2b3fdcbdf3 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/test_Menus.py +++ b/AutomatedTesting/Gem/PythonTests/editor/test_Menus.py @@ -7,8 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -C16780783: Base Edit Menu Options (New Viewport Interaction Model) """ import os @@ -17,6 +15,7 @@ import pytest # Bail on the test if ly_test_tools doesn't exist. pytest.importorskip('ly_test_tools') import ly_test_tools.environment.file_system as file_system +import ly_test_tools.environment.process_utils as process_utils import editor_python_test_tools.hydra_test_utils as hydra test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") @@ -33,6 +32,7 @@ class TestMenus(object): def setup_teardown(self, request, workspace, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) + process_utils.kill_processes_named("o3de", ignore_extensions=True) # Kill ProjectManager windows request.addfinalizer(teardown) @@ -80,8 +80,7 @@ class TestMenus(object): expected_lines, cfg_args=[level], run_python="--runpython", - auto_test_mode=True, - timeout=log_monitor_timeout, + timeout=log_monitor_timeout ) @pytest.mark.test_case_id("C16780807") @@ -107,13 +106,13 @@ class TestMenus(object): "Menus_ViewMenuOptions.py", expected_lines, cfg_args=[level], - auto_test_mode=True, run_python="--runpython", - timeout=log_monitor_timeout, + timeout=log_monitor_timeout ) @pytest.mark.test_case_id("C16780778") @pytest.mark.SUITE_sandbox + @pytest.mark.xfail # LYN-4208 def test_Menus_FileMenuOptions_Work(self, request, editor, level, launcher_platform): expected_lines = [ "New Level Action triggered", @@ -122,7 +121,10 @@ class TestMenus(object): "Save Action triggered", "Save As Action triggered", "Save Level Statistics Action triggered", - "Project Settings Tool Action triggered", + "Edit Project Settings Action triggered", + "Edit Platform Settings Action triggered", + "New Project Action triggered", + "Open Project Action triggered", "Show Log File Action triggered", "Resave All Slices Action triggered", "Exit Action triggered", @@ -135,7 +137,6 @@ class TestMenus(object): "Menus_FileMenuOptions.py", expected_lines, cfg_args=[level], - auto_test_mode=True, run_python="--runpython", - timeout=log_monitor_timeout, - ) \ No newline at end of file + timeout=log_monitor_timeout + ) From 29c71b4e530861d07426521a574f168d781a2ca3 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 3 Jun 2021 09:30:33 -0700 Subject: [PATCH 462/811] SPEC-2513 Fixes to enable w4701 (#1105) * Some fixes * more fixes * fixes for debug --- Code/CryEngine/CrySystem/DebugCallStack.cpp | 2 +- Code/CryEngine/CrySystem/System.cpp | 2 +- Code/CryEngine/CrySystem/SystemInit.cpp | 2 +- Code/Framework/AzCore/Tests/Jobs.cpp | 3 ++- .../Windowing/NativeWindow_Windows.cpp | 1 + Code/Sandbox/Editor/LogFile.cpp | 2 +- Code/Sandbox/Editor/Util/AffineParts.cpp | 4 ++-- Code/Sandbox/Editor/Util/FileUtil.cpp | 3 ++- Code/Sandbox/Editor/Util/ImageBT.cpp | 1 + Code/Sandbox/Editor/Util/StringHelpers.cpp | 2 +- .../Code/Source/Converters/FIR-Weights.cpp | 2 +- .../External/CubeMapGen/CCubeMapProcessor.cpp | 2 +- .../Code/Source/RHI/FrameGraphCompiler.cpp | 1 + .../Code/Tests/BoolLogicNodeTests.cpp | 4 ++-- .../Code/External/FastNoise/FastNoise.cpp | 21 +++++++++++++------ .../GraphCanvas/Utils/GraphUtils.cpp | 2 +- .../Code/Source/Animation/AzEntityNode.cpp | 2 +- .../Code/Source/UiLayoutGridComponent.cpp | 6 ++++-- .../Code/Source/UiNavigationHelpers.cpp | 2 ++ .../Source/Optimization/LineSearch.cpp | 2 +- .../Common/MSVC/Configurations_msvc.cmake | 1 - 21 files changed, 42 insertions(+), 25 deletions(-) diff --git a/Code/CryEngine/CrySystem/DebugCallStack.cpp b/Code/CryEngine/CrySystem/DebugCallStack.cpp index 2a219ce674..eea4725639 100644 --- a/Code/CryEngine/CrySystem/DebugCallStack.cpp +++ b/Code/CryEngine/CrySystem/DebugCallStack.cpp @@ -561,7 +561,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) if (pex) { - MINIDUMP_TYPE mdumpValue; + MINIDUMP_TYPE mdumpValue = MiniDumpNormal; bool bDump = true; switch (g_cvars.sys_dump_type) { diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index 6fcbc32b72..bf34700c39 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -66,7 +66,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) } if (pSystem && !pSystem->IsQuitting()) { - LRESULT result; + LRESULT result = 0; bool bAny = false; for (std::vector::const_iterator it = pSystem->m_windowMessageHandlers.begin(); it != pSystem->m_windowMessageHandlers.end(); ++it) { diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 52744519bb..4a4296bbb5 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -634,7 +634,7 @@ ICVar* CSystem::attachVariable (const char* szVarName, int* pContainer, const ch IConsole* pConsole = GetIConsole(); ICVar* pOldVar = pConsole->GetCVar (szVarName); - int nDefault; + int nDefault = 0; if (pOldVar) { nDefault = pOldVar->GetIVal(); diff --git a/Code/Framework/AzCore/Tests/Jobs.cpp b/Code/Framework/AzCore/Tests/Jobs.cpp index 553123496e..664b163417 100644 --- a/Code/Framework/AzCore/Tests/Jobs.cpp +++ b/Code/Framework/AzCore/Tests/Jobs.cpp @@ -395,7 +395,8 @@ namespace UnitTest } else { - int result1, result2; + int result1 = 0; + int result2 = 0; Job* job1 = aznew FibonacciJob2(m_n - 1, &result1, m_context); Job* job2 = aznew FibonacciJob2(m_n - 2, &result2, m_context); StartAsChild(job1); diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp index fd49f37dc8..b96ec81b5f 100644 --- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp +++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp @@ -353,6 +353,7 @@ namespace AzFramework // Get the dimensions of the display device on which the window is currently displayed. MONITORINFO monitorInfo; + memset(&monitorInfo, 0, sizeof(MONITORINFO)); // C4701 potentially uninitialized local variable 'monitorInfo' used monitorInfo.cbSize = sizeof(MONITORINFO); const BOOL success = monitor ? GetMonitorInfo(monitor, &monitorInfo) : FALSE; if (!success) diff --git a/Code/Sandbox/Editor/LogFile.cpp b/Code/Sandbox/Editor/LogFile.cpp index 0841a6b288..0bbfd09a21 100644 --- a/Code/Sandbox/Editor/LogFile.cpp +++ b/Code/Sandbox/Editor/LogFile.cpp @@ -553,7 +553,7 @@ void CLogFile::OnWriteToConsole(const char* sText, bool bNewLine) // remember selection and the top row int len = m_hWndEditBox->document()->toPlainText().length(); - int top; + int top = 0; int from = m_hWndEditBox->textCursor().selectionStart(); int to = from + m_hWndEditBox->textCursor().selectionEnd(); bool keepPos = false; diff --git a/Code/Sandbox/Editor/Util/AffineParts.cpp b/Code/Sandbox/Editor/Util/AffineParts.cpp index e294f93089..139519c078 100644 --- a/Code/Sandbox/Editor/Util/AffineParts.cpp +++ b/Code/Sandbox/Editor/Util/AffineParts.cpp @@ -157,7 +157,7 @@ static Quatern Qt_FromMatrix(HMatrix mat) * |w| is greater than 1/2, which is as small as a largest component can be. * Otherwise, the largest diagonal entry corresponds to the largest of |x|, * |y|, or |z|, one of which must be larger than |w|, and at least 1/2. */ - Quatern qu; + Quatern qu = { 0.0f, 0.0f, 0.0f, 1.0f }; double tr, s; tr = mat[X][X] + mat[Y][Y] + mat[Z][Z]; @@ -531,7 +531,7 @@ Quatern snuggle(Quatern q, HVect* k) #define swap(a, i, j) {a[3] = a[i]; a[i] = a[j]; a[j] = a[3]; } #define cycle(a, p) if (p) {a[3] = a[0]; a[0] = a[1]; a[1] = a[2]; a[2] = a[3]; } \ else {a[3] = a[2]; a[2] = a[1]; a[1] = a[0]; a[0] = a[3]; } - Quatern p; + Quatern p = { 0.0f, 0.0f, 0.0f, 1.0f }; float ka[4]; int i, turn = -1; ka[X] = k->x; diff --git a/Code/Sandbox/Editor/Util/FileUtil.cpp b/Code/Sandbox/Editor/Util/FileUtil.cpp index 8dd379f096..ece516659e 100644 --- a/Code/Sandbox/Editor/Util/FileUtil.cpp +++ b/Code/Sandbox/Editor/Util/FileUtil.cpp @@ -2239,7 +2239,8 @@ uint32 CFileUtil::GetAttributes(const char* filename, bool bUseSourceControl /*= bool CFileUtil::CompareFiles(const QString& strFilePath1, const QString& strFilePath2) { // Get the size of both files. If either fails we say they are different (most likely one doesn't exist) - uint64 size1, size2; + uint64 size1 = 0; + uint64 size2 = 0; if (!GetDiskFileSize(strFilePath1.toUtf8().data(), size1) || !GetDiskFileSize(strFilePath2.toUtf8().data(), size2)) { return false; diff --git a/Code/Sandbox/Editor/Util/ImageBT.cpp b/Code/Sandbox/Editor/Util/ImageBT.cpp index 30c4911cb8..79ce4bba35 100644 --- a/Code/Sandbox/Editor/Util/ImageBT.cpp +++ b/Code/Sandbox/Editor/Util/ImageBT.cpp @@ -116,6 +116,7 @@ bool CImageBT::Load(const QString& fileName, CFloatImage& image) // Get the BT header data BtHeader header; + memset(&header, 0, sizeof(BtHeader)); // C4701 potentially uninitialized local variable 'header' used bool validData = true; validData = validData && (fread(&header, sizeof(BtHeader), 1, file) != 0); diff --git a/Code/Sandbox/Editor/Util/StringHelpers.cpp b/Code/Sandbox/Editor/Util/StringHelpers.cpp index 5e44c3b0bd..12865dfe73 100644 --- a/Code/Sandbox/Editor/Util/StringHelpers.cpp +++ b/Code/Sandbox/Editor/Util/StringHelpers.cpp @@ -419,7 +419,7 @@ static inline bool MatchesWildcardsIgnoreCaseExt_Tpl(const TS& str, const TS& wi const typename TS::value_type* savedStrBegin = 0; const typename TS::value_type* savedStrEnd = 0; const typename TS::value_type* savedWild = 0; - size_t savedWildCount; + size_t savedWildCount = 0; const typename TS::value_type* pStr = str.c_str(); const typename TS::value_type* pWild = wildcards.c_str(); diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/FIR-Weights.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/FIR-Weights.cpp index 192c82c165..b1d0cfbda0 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/FIR-Weights.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/FIR-Weights.cpp @@ -88,7 +88,7 @@ namespace ImageProcessingAtom int dstPosition; signed short int n; bool trimZeros = true, stillzero; - int lastnonzero, hWeight, highest; + int lastnonzero = 0, hWeight, highest = 0; signed int sumiWeights, iWeight; signed short int* weightsPtr; signed short int* weightsMem; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/CCubeMapProcessor.cpp b/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/CCubeMapProcessor.cpp index 26768f8f2e..df31067af0 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/CCubeMapProcessor.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/CCubeMapProcessor.cpp @@ -1106,7 +1106,7 @@ namespace ImageProcessingAtom //fractional amount to apply change in tap intensity along edge to taps // in a perpendicular direction to edge CP_ITYPE fixupFrac = (CP_ITYPE)(fixupDist - iFixup) / (CP_ITYPE)(fixupDist); - CP_ITYPE fixupWeight; + CP_ITYPE fixupWeight = 0.0f; switch(a_FixupType ) { diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp index 7fc1db179a..e4fff11d32 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp @@ -484,6 +484,7 @@ namespace AZ } D3D12_RESOURCE_TRANSITION_BARRIER transition; + memset(&transition, 0, sizeof(D3D12_RESOURCE_TRANSITION_BARRIER)); // C4701 potentially unitialized local variable 'transition' used transition.pResource = image.GetMemoryView().GetMemory(); Scope& firstScope = static_cast(scopeAttachment->GetScope()); diff --git a/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp index 30950790d9..218bea2169 100644 --- a/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp @@ -165,8 +165,8 @@ namespace EMotionFX const AZ::Outcome boolYParamIndexOutcome = m_animGraphInstance->FindParameterIndex(nameBoolY); success = boolXParamIndexOutcome.IsSuccess() && boolYParamIndexOutcome.IsSuccess(); - uint32 boolXOutputPortIndex; - uint32 boolYOutputPortIndex; + uint32 boolXOutputPortIndex = InvalidIndex32; + uint32 boolYOutputPortIndex = InvalidIndex32; const int portIndicesTosetCount = 2; int portIndicesFound = 0; const AZStd::vector& parameterNodeOutputPorts = parameterNode->GetOutputPorts(); diff --git a/Gems/FastNoise/Code/External/FastNoise/FastNoise.cpp b/Gems/FastNoise/Code/External/FastNoise/FastNoise.cpp index fce7d6498a..3fe7bf45fe 100644 --- a/Gems/FastNoise/Code/External/FastNoise/FastNoise.cpp +++ b/Gems/FastNoise/Code/External/FastNoise/FastNoise.cpp @@ -612,7 +612,9 @@ FN_DECIMAL FastNoise::SingleValue(unsigned char offset, FN_DECIMAL x, FN_DECIMAL int y1 = y0 + 1; int z1 = z0 + 1; - FN_DECIMAL xs, ys, zs; + FN_DECIMAL xs = 0.0f; + FN_DECIMAL ys = 0.0f; + FN_DECIMAL zs = 0.0f; switch (m_interp) { case Linear: @@ -726,7 +728,8 @@ FN_DECIMAL FastNoise::SingleValue(unsigned char offset, FN_DECIMAL x, FN_DECIMAL int x1 = x0 + 1; int y1 = y0 + 1; - FN_DECIMAL xs, ys; + FN_DECIMAL xs = 0.0f; + FN_DECIMAL ys = 0.0f; switch (m_interp) { case Linear: @@ -840,7 +843,9 @@ FN_DECIMAL FastNoise::SinglePerlin(unsigned char offset, FN_DECIMAL x, FN_DECIMA int y1 = y0 + 1; int z1 = z0 + 1; - FN_DECIMAL xs, ys, zs; + FN_DECIMAL xs = 0.0f; + FN_DECIMAL ys = 0.0f; + FN_DECIMAL zs = 0.0f; switch (m_interp) { case Linear: @@ -962,7 +967,8 @@ FN_DECIMAL FastNoise::SinglePerlin(unsigned char offset, FN_DECIMAL x, FN_DECIMA int x1 = x0 + 1; int y1 = y0 + 1; - FN_DECIMAL xs, ys; + FN_DECIMAL xs = 0.0f; + FN_DECIMAL ys = 0.0f; switch (m_interp) { case Linear: @@ -1699,7 +1705,9 @@ FN_DECIMAL FastNoise::SingleCellular(FN_DECIMAL x, FN_DECIMAL y, FN_DECIMAL z) c int zr = FastRound(z); FN_DECIMAL distance = 999999; - int xc, yc, zc; + int xc = 0; + int yc = 0; + int zc = 0; switch (m_cellularDistanceFunction) { @@ -1923,7 +1931,8 @@ FN_DECIMAL FastNoise::SingleCellular(FN_DECIMAL x, FN_DECIMAL y) const int yr = FastRound(y); FN_DECIMAL distance = 999999; - int xc, yc; + int xc = 0; + int yc = 0; switch (m_cellularDistanceFunction) { diff --git a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Utils/GraphUtils.cpp b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Utils/GraphUtils.cpp index 28fb760c20..c2574a69f6 100644 --- a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Utils/GraphUtils.cpp +++ b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Utils/GraphUtils.cpp @@ -1239,7 +1239,7 @@ namespace GraphCanvas bool GraphUtils::IsValidModelConnection(const GraphId& graphId, const Endpoint& sourceEndpoint, const Endpoint& targetEndpoint) { - bool validConnection; + bool validConnection = false; AZStd::unordered_set< Endpoint > finalSourceEndpoints = RemapEndpointForModel(sourceEndpoint); AZStd::unordered_set< Endpoint > finalTargetEndpoints = RemapEndpointForModel(targetEndpoint); diff --git a/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp b/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp index 7ff46f285f..2d24a84c71 100644 --- a/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp +++ b/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp @@ -691,7 +691,7 @@ IUiAnimTrack* CUiAnimAzEntityNode::CreateTrackForAzField(const UiAnimParamData& return nullptr; } - EUiAnimValue valueType; + EUiAnimValue valueType = eUiAnimValue_Unknown; switch (numElements) { case 2: diff --git a/Gems/LyShine/Code/Source/UiLayoutGridComponent.cpp b/Gems/LyShine/Code/Source/UiLayoutGridComponent.cpp index e39b9cc684..4c5d48911f 100644 --- a/Gems/LyShine/Code/Source/UiLayoutGridComponent.cpp +++ b/Gems/LyShine/Code/Source/UiLayoutGridComponent.cpp @@ -107,7 +107,8 @@ void UiLayoutGridComponent::ApplyLayoutHeight() AZStd::vector childEntityIds; EBUS_EVENT_ID_RESULT(childEntityIds, GetEntityId(), UiElementBus, GetChildEntityIds); int childIndex = 0; - int columnIndex, rowIndex; + int columnIndex = 0; + int rowIndex = 0; for (auto child : childEntityIds) { // Set the anchors @@ -627,7 +628,8 @@ AZ::Vector2 UiLayoutGridComponent::GetChildrenBoundingRectSize(const AZ::Vector2 UiLayoutHelpers::GetSizeInsidePadding(GetEntityId(), m_padding, layoutRectSize); // Calculate number of rows and columns - int numColumns, numRows; + int numColumns = 0; + int numRows = 0; switch (m_startingDirection) { case StartingDirection::HorizontalOrder: diff --git a/Gems/LyShine/Code/Source/UiNavigationHelpers.cpp b/Gems/LyShine/Code/Source/UiNavigationHelpers.cpp index 0c1b6765ce..79084c8bbe 100644 --- a/Gems/LyShine/Code/Source/UiNavigationHelpers.cpp +++ b/Gems/LyShine/Code/Source/UiNavigationHelpers.cpp @@ -151,6 +151,8 @@ namespace UiNavigationHelpers } UiTransformInterface::Rect parentRect; + parentRect.Set(0.0f, 0.0f, 0.0f, 0.0f); + AZ::Matrix4x4 parentTransformFromViewport; if (parentElement.IsValid() && !isCurElementDescendantOfParentElement) { diff --git a/Gems/PhysX/Code/NumericalMethods/Source/Optimization/LineSearch.cpp b/Gems/PhysX/Code/NumericalMethods/Source/Optimization/LineSearch.cpp index abc2154228..1325638dd2 100644 --- a/Gems/PhysX/Code/NumericalMethods/Source/Optimization/LineSearch.cpp +++ b/Gems/PhysX/Code/NumericalMethods/Source/Optimization/LineSearch.cpp @@ -72,7 +72,7 @@ namespace NumericalMethods::Optimization for (AZ::u32 iteration = 0; iteration < lineSearchIterations; iteration++) { - ScalarVariable alphaNew; + ScalarVariable alphaNew = 0.0; if (iteration > 0) { // first try selecting a new alpha value based on cubic interpolation through the most recent points diff --git a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake index 25b6e63ab9..24dffe56a6 100644 --- a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake +++ b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake @@ -75,7 +75,6 @@ ly_append_configurations_options( /wd4450 # declaration hides global declaration /wd4457 # declaration hides function parameter /wd4459 # declaration hides global declaration - /wd4701 # potentially unintialized local variable # Enabling warnings that are disabled by default from /W4 # https://docs.microsoft.com/en-us/cpp/preprocessor/compiler-warnings-that-are-off-by-default?view=vs-2019 From d56688e6cd9e620e384f8233431fa8180294da5a Mon Sep 17 00:00:00 2001 From: Tommy Walton <82672795+amzn-tommy@users.noreply.github.com> Date: Thu, 3 Jun 2021 09:41:31 -0700 Subject: [PATCH 463/811] Adding a file that was missed when merging PR 481 from 1.0->main. Also, updated the comment a bit (#912) --- .../RPI/Code/Source/RPI.Public/Culling.cpp | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index c64f08e4f8..c5e9d949aa 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -239,16 +239,26 @@ namespace AZ void CullingScene::RegisterOrUpdateCullable(Cullable& cullable) { - m_cullDataConcurrencyCheck.soft_lock(); + // Multiple threads can call RegisterOrUpdateCullable at the same time + // since the underlying visScene is thread safe, but if you're inserting or + // updating between BeginCulling and EndCulling, you'll get non-deterministic + // results depending on a race condition if you happen to update before or after + // the culling system starts Enumerating, so use soft_lock_shared here + m_cullDataConcurrencyCheck.soft_lock_shared(); m_visScene->InsertOrUpdateEntry(cullable.m_cullData.m_visibilityEntry); - m_cullDataConcurrencyCheck.soft_unlock(); + m_cullDataConcurrencyCheck.soft_unlock_shared(); } void CullingScene::UnregisterCullable(Cullable& cullable) { - m_cullDataConcurrencyCheck.soft_lock(); + // Multiple threads can call RegisterOrUpdateCullable at the same time + // since the underlying visScene is thread safe, but if you're inserting or + // updating between BeginCulling and EndCulling, you'll get non-deterministic + // results depending on a race condition if you happen to update before or after + // the culling system starts Enumerating, so use soft_lock_shared here + m_cullDataConcurrencyCheck.soft_lock_shared(); m_visScene->RemoveEntry(cullable.m_cullData.m_visibilityEntry); - m_cullDataConcurrencyCheck.soft_unlock(); + m_cullDataConcurrencyCheck.soft_unlock_shared(); } uint32_t CullingScene::GetNumCullables() const From eef5122ce54dc44f97d852b4bf11b9a6a6cfc51b Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 3 Jun 2021 11:56:20 -0500 Subject: [PATCH 464/811] [LYN-3008] Only register the Slice Relationship View when prefabs are disabled. --- .../ComponentEntityEditorPlugin.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp index 54ac71db16..ed21b5b6e9 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp @@ -179,11 +179,11 @@ ComponentEntityEditorPlugin::ComponentEntityEditorPlugin([[maybe_unused]] IEdito LyViewPane::EntityOutliner, LyViewPane::CategoryTools, outlinerOptions); - } - AzToolsFramework::ViewPaneOptions options; - options.preferedDockingArea = Qt::NoDockWidgetArea; - RegisterViewPane(LyViewPane::SliceRelationships, LyViewPane::CategoryTools, options); + AzToolsFramework::ViewPaneOptions options; + options.preferedDockingArea = Qt::NoDockWidgetArea; + RegisterViewPane(LyViewPane::SliceRelationships, LyViewPane::CategoryTools, options); + } RegisterModuleResourceSelectors(GetIEditor()->GetResourceSelectorHost()); From 5838975d626fc632d74f6069bfa329b5092ab062 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Thu, 3 Jun 2021 13:29:51 -0400 Subject: [PATCH 465/811] Incorporating review comments. Minor formatting changes and changes to parameter descriptions. Removed try-catch for property modification and added creation of user_tags element if it does not exist but is modified through CLI --- scripts/o3de/o3de/project_properties.py | 37 +++++++++++++------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/scripts/o3de/o3de/project_properties.py b/scripts/o3de/o3de/project_properties.py index 10153ff833..d8453a2c4f 100644 --- a/scripts/o3de/o3de/project_properties.py +++ b/scripts/o3de/o3de/project_properties.py @@ -21,22 +21,23 @@ def edit_project_props(proj_path, proj_name, new_origin, new_display, new_summary, new_icon, new_tag) -> int: proj_json = get_project_props(proj_name, proj_path) - try: - if new_origin and 'origin' in proj_json: - proj_json['origin'] = new_origin - if new_display and 'display_name' in proj_json: - proj_json['display_name'] = new_display - if new_summary and 'summary' in proj_json: - proj_json['summary'] = new_summary - if new_icon and 'icon_path' in proj_json: - proj_json['icon_path'] = new_icon - if new_tag and 'user_tags' in proj_json: - proj_json['user_tags'].append(new_tag) - except Exception as e: - logger.error(e) + if not proj_json: return 1 - manifest.save_o3de_manifest(proj_json, pathlib.Path(proj_path)/'project.json') + if new_origin: + proj_json['origin'] = new_origin + if new_display: + proj_json['display_name'] = new_display + if new_summary: + proj_json['summary'] = new_summary + if new_icon: + proj_json['icon_path'] = new_icon + if new_tag: + if 'user_tags' not in proj_json: + proj_json['user_tags'] = [] + proj_json['user_tags'].append(new_tag) + + manifest.save_o3de_manifest(proj_json, pathlib.Path(proj_path) / 'project.json') return 0 def _edit_project_props(args: argparse) -> int: @@ -56,7 +57,7 @@ def add_parser_args(parser): help='The name of the project.') group = parser.add_argument_group('properties', 'arguments for modifying individual project properties.') group.add_argument('-po', '--project-origin', type=str, required=False, - help='Sets description or url for project origin.') + help='Sets description or url for project origin (such as project host, repository, owner...etc).') group.add_argument('-pd', '--project-display', type=str, required=False, help='Sets the project display name.') group.add_argument('-ps', '--project-summary', type=str, required=False, @@ -64,11 +65,11 @@ def add_parser_args(parser): group.add_argument('-pi', '--project-icon', type=str, required=False, help='Sets the path to the projects icon resource.') group.add_argument('-pt', '--project-tag', type=str, required=False, - help='Adds a tag to canonical user tags.') + help='Adds a tag to canonical user tags. These tags are intended for documentation and filtering.') parser.set_defaults(func=_edit_project_props) def add_args(subparsers) -> None: - enable_project_props_subparser = subparsers.add_parser('edit-project-props') + enable_project_props_subparser = subparsers.add_parser('edit-project-properties') add_parser_args(enable_project_props_subparser) def main(): @@ -79,4 +80,4 @@ def main(): sys.exit(ret) if __name__ == "__main__": - main() \ No newline at end of file + main() From c009e7d50bc47daa1a3a19c775d66c031c5b8a5f Mon Sep 17 00:00:00 2001 From: Qing Tao <55564570+VickyAtAZ@users.noreply.github.com> Date: Thu, 3 Jun 2021 10:42:20 -0700 Subject: [PATCH 466/811] ATOM-4782 [Material] Transparent pass is using StandardPBR_Forwardpass shader with incorrect SRG (#1103) Removed TransparentPassSrg until we have pbr shaders TransparentPassSrg --- .../Materials/Special/ShadowCatcher.azsl | 2 +- .../Assets/Passes/TransparentParent.pass | 2 +- .../Atom/Features/PBR/ForwardPassSrg.azsli | 1 + .../Features/PBR/TransparentPassSrg.azsli | 39 ------------------- .../atom_feature_common_asset_files.cmake | 1 - 5 files changed, 3 insertions(+), 42 deletions(-) delete mode 100644 Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/TransparentPassSrg.azsli diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Special/ShadowCatcher.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Special/ShadowCatcher.azsl index 942db3ed5f..4a228f076c 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Special/ShadowCatcher.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Special/ShadowCatcher.azsl @@ -37,7 +37,7 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial } #include -#include +#include #include #include diff --git a/Gems/Atom/Feature/Common/Assets/Passes/TransparentParent.pass b/Gems/Atom/Feature/Common/Assets/Passes/TransparentParent.pass index b278f2bcb4..a9db59c646 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/TransparentParent.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/TransparentParent.pass @@ -124,7 +124,7 @@ "DrawListSortType": "KeyThenReverseDepth", "PipelineViewTag": "MainCamera", "PassSrgAsset": { - "FilePath": "shaderlib/atom/features/pbr/transparentpasssrg.azsli:PassSrg" + "FilePath": "shaderlib/atom/features/pbr/forwardpasssrg.azsli:PassSrg" } } } diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/ForwardPassSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/ForwardPassSrg.azsli index 14cff21739..d9367f9d03 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/ForwardPassSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/ForwardPassSrg.azsli @@ -35,4 +35,5 @@ ShaderResourceGroup PassSrg : SRG_PerPass Texture2D m_tileLightData; StructuredBuffer m_lightListRemapped; + Texture2D m_linearDepthTexture; } diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/TransparentPassSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/TransparentPassSrg.azsli deleted file mode 100644 index d9367f9d03..0000000000 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/TransparentPassSrg.azsli +++ /dev/null @@ -1,39 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include - -ShaderResourceGroup PassSrg : SRG_PerPass -{ - // [GFX TODO][ATOM-2012] adapt to multiple shadowmaps - Texture2DArray m_directionalLightShadowmap; - Texture2DArray m_directionalLightExponentialShadowmap; - Texture2DArray m_projectedShadowmaps; - Texture2DArray m_projectedExponentialShadowmap; - Texture2D m_brdfMap; - - Sampler LinearSampler - { - MinFilter = Linear; - MagFilter = Linear; - MipFilter = Linear; - AddressU = Clamp; - AddressV = Clamp; - AddressW = Clamp; - }; - - Texture2D m_tileLightData; - StructuredBuffer m_lightListRemapped; - Texture2D m_linearDepthTexture; -} diff --git a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake index 359c0b9b20..a9ba765329 100644 --- a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake +++ b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake @@ -246,7 +246,6 @@ set(FILES ShaderLib/Atom/Features/PBR/Hammersley.azsli ShaderLib/Atom/Features/PBR/LightingOptions.azsli ShaderLib/Atom/Features/PBR/LightingUtils.azsli - ShaderLib/Atom/Features/PBR/TransparentPassSrg.azsli ShaderLib/Atom/Features/PBR/Lighting/DualSpecularLighting.azsli ShaderLib/Atom/Features/PBR/Lighting/EnhancedLighting.azsli ShaderLib/Atom/Features/PBR/Lighting/LightingData.azsli From bcef8856ff2143fa137078525d98d47ddc6fe348 Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 3 Jun 2021 10:51:13 -0700 Subject: [PATCH 467/811] [cpack_installer] minor wording fixes --- cmake/Packaging.cmake | 2 +- scripts/build/Platform/Windows/installer_windows.cmd | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index e5799c8ff1..3e23511fa1 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -54,7 +54,7 @@ endif() if(${CPACK_DESIRED_CMAKE_VERSION} VERSION_LESS ${CMAKE_MINIMUM_REQUIRED_VERSION}) message(FATAL_ERROR "The desired version of CMake to be included in the package is " - "is below the minimum required version of CMake to run") + "below the minimum required version of CMake to run") endif() # pull down the desired copy of CMake so it can be included in the package diff --git a/scripts/build/Platform/Windows/installer_windows.cmd b/scripts/build/Platform/Windows/installer_windows.cmd index c71b091de9..a6ce15d59e 100644 --- a/scripts/build/Platform/Windows/installer_windows.cmd +++ b/scripts/build/Platform/Windows/installer_windows.cmd @@ -20,7 +20,7 @@ IF NOT EXIST %OUTPUT_DIRECTORY% ( ) PUSHD %OUTPUT_DIRECTORY% -REM Override the temporary directory used by wix to the EBS volume +REM Override the temporary directory used by wix to the workspace SET "WIX_TEMP=!WORKSPACE!/temp/wix" IF NOT EXIST "%WIX_TEMP%" ( MKDIR "%WIX_TEMP%" From 8704b9233a699af223cfd0964bedd5271b79db45 Mon Sep 17 00:00:00 2001 From: mnaumov Date: Thu, 3 Jun 2021 10:53:00 -0700 Subject: [PATCH 468/811] build fix --- .../Rendering/ThumbnailRendererSteps/InitializeStep.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp index c35c33017a..8bf157e5f3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp @@ -12,7 +12,7 @@ #include -#include +#include #include From 54fdca353b9d3a1108e4a5dd2f63a23b171cdb3a Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Thu, 3 Jun 2021 12:54:14 -0500 Subject: [PATCH 469/811] Fix editor axis gizmo text rendering above gizmo Add AzToolsFramework utility function to query the display scale for a viewport. Use new function to fix the text location on the axis gizmo. --- .../ViewportSelection/EditorSelectionUtil.cpp | 11 +++++++++++ .../ViewportSelection/EditorSelectionUtil.h | 3 +++ .../EditorTransformComponentSelection.cpp | 7 ++++--- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp index 88b92e8c41..d0143c5517 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp @@ -124,4 +124,15 @@ namespace AzToolsFramework return cameraState; } + + float GetScreenDisplayScaling(const int viewportId) + { + float scaling = 1.0f; + ViewportInteraction::ViewportInteractionRequestBus::EventResult( + scaling, viewportId, + &ViewportInteraction::ViewportInteractionRequestBus::Events::DeviceScalingFactor); + + return scaling; + } + } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h index 9936fb9afd..e904277078 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h @@ -60,6 +60,9 @@ namespace AzToolsFramework /// Wrapper for EBus call to return the CameraState for a given viewport. AzFramework::CameraState GetCameraState(int viewportId); + /// Wrapper for EBus call to return the DPI scaling for a given viewport. + float GetScreenDisplayScaling(const int viewportId); + /// A utility to return the center of several points. /// Take several positions and store the min and max of each in /// turn - when all points have been added return the center/midpoint. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index 91ac495e0e..5acfa5df59 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -3573,9 +3573,10 @@ namespace AzToolsFramework debugDisplay.SetLineWidth(1.0f); const float labelOffset = cl_viewportGizmoAxisLabelOffset; - const auto labelXScreenPosition = (gizmoStart + (gizmoAxisX * labelOffset)) * editorCameraState.m_viewportSize; - const auto labelYScreenPosition = (gizmoStart + (gizmoAxisY * labelOffset)) * editorCameraState.m_viewportSize; - const auto labelZScreenPosition = (gizmoStart + (gizmoAxisZ * labelOffset)) * editorCameraState.m_viewportSize; + const float screenScale = GetScreenDisplayScaling(viewportId); + const auto labelXScreenPosition = (gizmoStart + (gizmoAxisX * labelOffset)) * editorCameraState.m_viewportSize * screenScale; + const auto labelYScreenPosition = (gizmoStart + (gizmoAxisY * labelOffset)) * editorCameraState.m_viewportSize * screenScale; + const auto labelZScreenPosition = (gizmoStart + (gizmoAxisZ * labelOffset)) * editorCameraState.m_viewportSize * screenScale; // draw the label of of each axis for the gizmo const float labelSize = cl_viewportGizmoAxisLabelSize; From 1bf8c599e3789999e2c33da5a2f82d77e48ea9df Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Thu, 27 May 2021 09:56:11 -0700 Subject: [PATCH 470/811] External Serialize Context for spawning This change makes it possible to provide a Serialize Context for spawning entities from spawnables. This also removes the need for the Serialize Context to be retrieved multiple times per frame. --- .../Spawnable/SpawnableEntitiesInterface.h | 54 +++++--- .../Spawnable/SpawnableEntitiesManager.cpp | 126 +++++++++--------- .../Spawnable/SpawnableEntitiesManager.h | 33 ++--- .../SpawnableEntitiesManagerTests.cpp | 24 +++- 4 files changed, 139 insertions(+), 98 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index 27f45064b6..cfa1f3b464 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -21,6 +21,7 @@ namespace AZ { class Entity; + class SerializeContext; } namespace AzFramework @@ -171,6 +172,34 @@ namespace AzFramework using ClaimEntitiesCallback = AZStd::function; using BarrierCallback = AZStd::function; + struct SpawnEntitiesOptionalArgs + { + //! Callback that's called after instances of entities have been created, but before they're spawned into the world. This + //! gives the opportunity to modify the entities if needed such as injecting additional components or modifying components. + EntityPreInsertionCallback m_preInsertionCallback; + //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that + //! made the function call. The returned list of entities contains all the newly created entities. + EntitySpawnCallback m_completionCallback; + //! The Serialize Context used to clone entities with. If this is not provided the global Serialize Contetx will be used. + AZ::SerializeContext* m_serializeContext { nullptr }; + }; + + struct DespawnAllEntitiesOptionalArgs + { + //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that + //! made the function call. The returned list of entities contains all the newly created entities. + EntityDespawnCallback m_completionCallback; + }; + + struct ReloadSpawnableOptionalArgs + { + //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that + //! made the function call. The returned list of entities contains all the newly created entities. + ReloadSpawnableCallback m_completionCallback; + //! The Serialize Context used to clone entities with. If this is not provided the global Serialize Contetx will be used. + AZ::SerializeContext* m_serializeContext { nullptr }; + }; + //! Interface definition to (de)spawn entities from a spawnable into the game world. //! //! While the callbacks of the individual calls are being processed they will block processing any other request. Callbacks can be @@ -197,40 +226,31 @@ namespace AzFramework //! Spawn instances of all entities in the spawnable. //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. //! @param priority The priority at which this call will be executed. - //! @param completionCallback Optional callback that's called when spawning entities has completed. This can be called from - //! a different thread than the one that made the function call. The returned list of entities contains all the newly - //! created entities. + //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs virtual void SpawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, EntityPreInsertionCallback preInsertionCallback = {}, - EntitySpawnCallback completionCallback = {}) = 0; + EntitySpawnTicket& ticket, SpawnablePriority priority, SpawnEntitiesOptionalArgs optionalArgs = {}) = 0; //! Spawn instances of some entities in the spawnable. //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. //! @param priority The priority at which this call will be executed. //! @param entityIndices The indices into the template entities stored in the spawnable that will be used to spawn entities from. - //! @param completionCallback Optional callback that's called when spawning entities has completed. This can be called from - //! a different thread than the one that made this function call. The returned list of entities contains all the newly - //! created entities. + //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs virtual void SpawnEntities( EntitySpawnTicket& ticket, SpawnablePriority priority, AZStd::vector entityIndices, - EntityPreInsertionCallback preInsertionCallback = {}, EntitySpawnCallback completionCallback = {}) = 0; + SpawnEntitiesOptionalArgs optionalArgs = {}) = 0; //! Removes all entities in the provided list from the environment. //! @param ticket The ticket previously used to spawn entities with. //! @param priority The priority at which this call will be executed. - //! @param completionCallback Optional callback that's called when despawning entities has completed. This can be called from - //! a different thread than the one that made this function call. + //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs virtual void DespawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, EntityDespawnCallback completionCallback = {}) = 0; - + EntitySpawnTicket& ticket, SpawnablePriority priority, DespawnAllEntitiesOptionalArgs optionalArgs = {}) = 0; //! Removes all entities in the provided list from the environment and reconstructs the entities from the provided spawnable. //! @param ticket Holds the information on the entities to reload. //! @param priority The priority at which this call will be executed. //! @param spawnable The spawnable that will replace the existing spawnable. Both need to have the same asset id. - //! @param completionCallback Optional callback that's called when the entities have been reloaded. This can be called from - //! a different thread than the one that made this function call. The returned list of entities contains all the replacement - //! entities. + //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs virtual void ReloadSpawnable( EntitySpawnTicket& ticket, SpawnablePriority priority, AZ::Data::Asset spawnable, - ReloadSpawnableCallback completionCallback = {}) = 0; + ReloadSpawnableOptionalArgs optionalArgs = {}) = 0; //! List all entities that are spawned using this ticket. //! @param ticket Only the entities associated with this ticket will be listed. diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp index 7b767d2a72..77106172f6 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp @@ -38,6 +38,10 @@ namespace AzFramework SpawnableEntitiesManager::SpawnableEntitiesManager() { + AZ::ComponentApplicationBus::BroadcastResult(m_defaultSerializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); + AZ_Assert( + m_defaultSerializeContext, "Failed to retrieve serialization context during construction of the Spawnable Entities Manager."); + if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { AZ::u64 value = aznumeric_caster(m_highPriorityThreshold); @@ -47,53 +51,57 @@ namespace AzFramework } void SpawnableEntitiesManager::SpawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, EntityPreInsertionCallback preInsertionCallback, - EntitySpawnCallback completionCallback) + EntitySpawnTicket& ticket, SpawnablePriority priority, SpawnEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnAllEntities hasn't been initialized."); SpawnAllEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); - queueEntry.m_completionCallback = AZStd::move(completionCallback); - queueEntry.m_preInsertionCallback = AZStd::move(preInsertionCallback); + queueEntry.m_serializeContext = + optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; + queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); + queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::SpawnEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, AZStd::vector entityIndices, - EntityPreInsertionCallback preInsertionCallback, EntitySpawnCallback completionCallback) + EntitySpawnTicket& ticket, SpawnablePriority priority, AZStd::vector entityIndices, SpawnEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnEntities hasn't been initialized."); SpawnEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_entityIndices = AZStd::move(entityIndices); - queueEntry.m_completionCallback = AZStd::move(completionCallback); - queueEntry.m_preInsertionCallback = AZStd::move(preInsertionCallback); + queueEntry.m_serializeContext = + optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; + queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); + queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::DespawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, EntityDespawnCallback completionCallback) + EntitySpawnTicket& ticket, SpawnablePriority priority, DespawnAllEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to DespawnAllEntities hasn't been initialized."); DespawnAllEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); - queueEntry.m_completionCallback = AZStd::move(completionCallback); + queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::ReloadSpawnable( EntitySpawnTicket& ticket, SpawnablePriority priority, AZ::Data::Asset spawnable, - ReloadSpawnableCallback completionCallback) + ReloadSpawnableOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to ReloadSpawnable hasn't been initialized."); ReloadSpawnableCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_spawnable = AZStd::move(spawnable); - queueEntry.m_completionCallback = AZStd::move(completionCallback); + queueEntry.m_serializeContext = + optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; + queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); QueueRequest(ticket, priority, AZStd::move(queueEntry)); } @@ -174,58 +182,57 @@ namespace AzFramework auto SpawnableEntitiesManager::ProcessQueue(Queue& queue) -> CommandQueueStatus { - AZStd::queue pendingRequestQueue; + // Process delayed requests first. + // Only process the requests that are currently in this queue, not the ones that could be re-added if they still can't complete. + size_t delayedSize = queue.m_delayed.size(); + for (size_t i = 0; i < delayedSize; ++i) { - AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); - queue.m_pendingRequest.swap(pendingRequestQueue); + Requests& request = queue.m_delayed.front(); + bool result = AZStd::visit( + [this](auto&& args) -> bool + { + return ProcessRequest(args); + }, + request); + if (!result) + { + queue.m_delayed.emplace_back(AZStd::move(request)); + } + queue.m_delayed.pop_front(); } - if (!pendingRequestQueue.empty() || !queue.m_delayed.empty()) + // Process newly added requests. + while (true) { - AZ::SerializeContext* serializeContext = nullptr; - AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); - AZ_Assert(serializeContext, "Failed to retrieve serialization context."); - - // Only process the requests that are currently in this queue, not the ones that could be re-added if they still can't complete. - size_t delayedSize = queue.m_delayed.size(); - for (size_t i = 0; i < delayedSize; ++i) + AZStd::queue pendingRequestQueue; { - Requests& request = queue.m_delayed.front(); - bool result = AZStd::visit([this, serializeContext](auto&& args) -> bool - { - return ProcessRequest(args, *serializeContext); - }, request); - if (!result) - { - queue.m_delayed.emplace_back(AZStd::move(request)); - } - queue.m_delayed.pop_front(); + AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); + queue.m_pendingRequest.swap(pendingRequestQueue); } - do + if (!pendingRequestQueue.empty()) { while (!pendingRequestQueue.empty()) { Requests& request = pendingRequestQueue.front(); - bool result = AZStd::visit([this, serializeContext](auto&& args) -> bool + bool result = AZStd::visit( + [this](auto&& args) -> bool { - return ProcessRequest(args, *serializeContext); - }, request); + return ProcessRequest(args); + }, + request); if (!result) { queue.m_delayed.emplace_back(AZStd::move(request)); } pendingRequestQueue.pop(); } - - // Spawning entities can result in more entities being queued to spawn. Repeat spawning until the queue is - // empty to avoid a chain of entity spawning getting dragged out over multiple frames. - { - AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); - queue.m_pendingRequest.swap(pendingRequestQueue); - } - } while (!pendingRequestQueue.empty()); - } + } + else + { + break; + } + }; return queue.m_delayed.empty() ? CommandQueueStatus::NoCommandsLeft : CommandQueueStatus::HasCommandsLeft; } @@ -267,7 +274,7 @@ namespace AzFramework &entityTemplate, templateToCloneEntityIdMap, &serializeContext); } - bool SpawnableEntitiesManager::ProcessRequest(SpawnAllEntitiesCommand& request, AZ::SerializeContext& serializeContext) + bool SpawnableEntitiesManager::ProcessRequest(SpawnAllEntitiesCommand& request) { Ticket& ticket = *request.m_ticket; if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) @@ -296,7 +303,7 @@ namespace AzFramework { const AZ::Entity& entityTemplate = *entitiesToSpawn[i]; - AZ::Entity* clone = CloneSingleEntity(entityTemplate, templateToCloneEntityIdMap, serializeContext); + AZ::Entity* clone = CloneSingleEntity(entityTemplate, templateToCloneEntityIdMap, *request.m_serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); @@ -347,7 +354,7 @@ namespace AzFramework } } - bool SpawnableEntitiesManager::ProcessRequest(SpawnEntitiesCommand& request, AZ::SerializeContext& serializeContext) + bool SpawnableEntitiesManager::ProcessRequest(SpawnEntitiesCommand& request) { Ticket& ticket = *request.m_ticket; if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) @@ -371,7 +378,7 @@ namespace AzFramework { const AZ::Entity& entityTemplate = *entitiesToSpawn[index]; - AZ::Entity* clone = serializeContext.CloneObject(&entityTemplate); + AZ::Entity* clone = request.m_serializeContext->CloneObject(&entityTemplate); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); clone->SetId(AZ::Entity::MakeId()); @@ -413,8 +420,7 @@ namespace AzFramework } } - bool SpawnableEntitiesManager::ProcessRequest(DespawnAllEntitiesCommand& request, - [[maybe_unused]] AZ::SerializeContext& serializeContext) + bool SpawnableEntitiesManager::ProcessRequest(DespawnAllEntitiesCommand& request) { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) @@ -447,7 +453,7 @@ namespace AzFramework } } - bool SpawnableEntitiesManager::ProcessRequest(ReloadSpawnableCommand& request, AZ::SerializeContext& serializeContext) + bool SpawnableEntitiesManager::ProcessRequest(ReloadSpawnableCommand& request) { Ticket& ticket = *request.m_ticket; AZ_Assert(ticket.m_spawnable.GetId() == request.m_spawnable.GetId(), @@ -488,7 +494,7 @@ namespace AzFramework { const AZ::Entity& entityTemplate = *entities[i]; - AZ::Entity* clone = CloneSingleEntity(entityTemplate, templateToCloneEntityIdMap, serializeContext); + AZ::Entity* clone = CloneSingleEntity(entityTemplate, templateToCloneEntityIdMap, *request.m_serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); @@ -502,7 +508,7 @@ namespace AzFramework for (size_t index : ticket.m_spawnedEntityIndices) { ticket.m_spawnedEntities.push_back( - index < entitiesSize ? SpawnSingleEntity(*entities[index], serializeContext) : nullptr); + index < entitiesSize ? SpawnSingleEntity(*entities[index], *request.m_serializeContext) : nullptr); } } ticket.m_spawnable = AZStd::move(request.m_spawnable); @@ -525,7 +531,7 @@ namespace AzFramework } } - bool SpawnableEntitiesManager::ProcessRequest(ListEntitiesCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) + bool SpawnableEntitiesManager::ProcessRequest(ListEntitiesCommand& request) { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) @@ -541,7 +547,7 @@ namespace AzFramework } } - bool SpawnableEntitiesManager::ProcessRequest(ListIndicesEntitiesCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) + bool SpawnableEntitiesManager::ProcessRequest(ListIndicesEntitiesCommand& request) { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) @@ -560,7 +566,7 @@ namespace AzFramework } } - bool SpawnableEntitiesManager::ProcessRequest(ClaimEntitiesCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) + bool SpawnableEntitiesManager::ProcessRequest(ClaimEntitiesCommand& request) { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) @@ -580,7 +586,7 @@ namespace AzFramework } } - bool SpawnableEntitiesManager::ProcessRequest(BarrierCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) + bool SpawnableEntitiesManager::ProcessRequest(BarrierCommand& request) { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) @@ -599,7 +605,7 @@ namespace AzFramework } } - bool SpawnableEntitiesManager::ProcessRequest(DestroyTicketCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext) + bool SpawnableEntitiesManager::ProcessRequest(DestroyTicketCommand& request) { if (request.m_requestId == request.m_ticket->m_currentRequestId) { diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h index afffdab8b5..b40ec20aa3 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h @@ -57,19 +57,16 @@ namespace AzFramework // The following functions are thread safe // - void SpawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, EntityPreInsertionCallback preInsertionCallback = {}, - EntitySpawnCallback completionCallback = {}) override; + void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, SpawnEntitiesOptionalArgs optionalArgs = {}) override; void SpawnEntities( EntitySpawnTicket& ticket, SpawnablePriority priority, AZStd::vector entityIndices, - EntityPreInsertionCallback preInsertionCallback = {}, - EntitySpawnCallback completionCallback = {}) override; + SpawnEntitiesOptionalArgs optionalArgs = {}) override; void DespawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, EntityDespawnCallback completionCallback = {}) override; + EntitySpawnTicket& ticket, SpawnablePriority priority, DespawnAllEntitiesOptionalArgs optionalArgs = {}) override; void ReloadSpawnable( EntitySpawnTicket& ticket, SpawnablePriority priority, AZ::Data::Asset spawnable, - ReloadSpawnableCallback completionCallback = {}) override; + ReloadSpawnableOptionalArgs optionalArgs = {}) override; void ListEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ListEntitiesCallback listCallback) override; void ListIndicesAndEntities( @@ -105,6 +102,7 @@ namespace AzFramework { EntitySpawnCallback m_completionCallback; EntityPreInsertionCallback m_preInsertionCallback; + AZ::SerializeContext* m_serializeContext; Ticket* m_ticket; EntitySpawnTicket::Id m_ticketId; uint32_t m_requestId; @@ -114,6 +112,7 @@ namespace AzFramework AZStd::vector m_entityIndices; EntitySpawnCallback m_completionCallback; EntityPreInsertionCallback m_preInsertionCallback; + AZ::SerializeContext* m_serializeContext; Ticket* m_ticket; EntitySpawnTicket::Id m_ticketId; uint32_t m_requestId; @@ -129,6 +128,7 @@ namespace AzFramework { AZ::Data::Asset m_spawnable; ReloadSpawnableCallback m_completionCallback; + AZ::SerializeContext* m_serializeContext; Ticket* m_ticket; EntitySpawnTicket::Id m_ticketId; uint32_t m_requestId; @@ -191,15 +191,15 @@ namespace AzFramework AZ::Entity* CloneSingleEntity(const AZ::Entity& entityTemplate, EntityIdMap& templateToCloneEntityIdMap, AZ::SerializeContext& serializeContext); - bool ProcessRequest(SpawnAllEntitiesCommand& request, AZ::SerializeContext& serializeContext); - bool ProcessRequest(SpawnEntitiesCommand& request, AZ::SerializeContext& serializeContext); - bool ProcessRequest(DespawnAllEntitiesCommand& request, AZ::SerializeContext& serializeContext); - bool ProcessRequest(ReloadSpawnableCommand& request, AZ::SerializeContext& serializeContext); - bool ProcessRequest(ListEntitiesCommand& request, AZ::SerializeContext& serializeContext); - bool ProcessRequest(ListIndicesEntitiesCommand& request, AZ::SerializeContext& serializeContext); - bool ProcessRequest(ClaimEntitiesCommand& request, AZ::SerializeContext& serializeContext); - bool ProcessRequest(BarrierCommand& request, AZ::SerializeContext& serializeContext); - bool ProcessRequest(DestroyTicketCommand& request, AZ::SerializeContext& serializeContext); + bool ProcessRequest(SpawnAllEntitiesCommand& request); + bool ProcessRequest(SpawnEntitiesCommand& request); + bool ProcessRequest(DespawnAllEntitiesCommand& request); + bool ProcessRequest(ReloadSpawnableCommand& request); + bool ProcessRequest(ListEntitiesCommand& request); + bool ProcessRequest(ListIndicesEntitiesCommand& request); + bool ProcessRequest(ClaimEntitiesCommand& request); + bool ProcessRequest(BarrierCommand& request); + bool ProcessRequest(DestroyTicketCommand& request); Queue m_highPriorityQueue; Queue m_regularPriorityQueue; @@ -207,6 +207,7 @@ namespace AzFramework AZ::Event> m_onSpawnedEvent; AZ::Event> m_onDespawnedEvent; + AZ::SerializeContext* m_defaultSerializeContext { nullptr }; //! The threshold used to determine if a request goes in the regular (if bigger than the value) or high priority queue (if smaller //! or equal to this value). The starting value of 64 is chosen as it's between default values SpawnablePriority_High and //! SpawnablePriority_Default which gives users a bit of room to fine tune the priorities as this value can be configured diff --git a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp index 484b7f46d7..7a2e7f614b 100644 --- a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp +++ b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp @@ -104,7 +104,9 @@ namespace UnitTest { spawnedEntitiesCount += entities.size(); }; - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, {}, AZStd::move(callback)); + AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + optionalArgs.m_completionCallback = AZStd::move(callback); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(optionalArgs)); m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); EXPECT_EQ(NumEntities, spawnedEntitiesCount); @@ -305,8 +307,14 @@ namespace UnitTest defaultPriorityCallId = callCounter++; }; - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, {}, AZStd::move(defaultCallback)); - m_manager->SpawnAllEntities(highPriorityTicket, AzFramework::SpawnablePriority_High, {}, AZStd::move(highCallback)); + AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + optionalArgs.m_completionCallback = AZStd::move(defaultCallback); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(optionalArgs)); + + AzFramework::SpawnEntitiesOptionalArgs highPriortyOptionalArgs; + highPriortyOptionalArgs.m_completionCallback = AZStd::move(highCallback); + m_manager->SpawnAllEntities(highPriorityTicket, AzFramework::SpawnablePriority_High, AZStd::move(highPriortyOptionalArgs)); + m_manager->ProcessQueue( AzFramework::SpawnableEntitiesManager::CommandQueuePriority::High | AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); @@ -333,8 +341,14 @@ namespace UnitTest defaultPriorityCallId = callCounter++; }; - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, {}, AZStd::move(defaultCallback)); - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_High, {}, AZStd::move(highCallback)); + AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + optionalArgs.m_completionCallback = AZStd::move(defaultCallback); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(optionalArgs)); + + AzFramework::SpawnEntitiesOptionalArgs highPriortyOptionalArgs; + highPriortyOptionalArgs.m_completionCallback = AZStd::move(highCallback); + m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_High, AZStd::move(highPriortyOptionalArgs)); + m_manager->ProcessQueue( AzFramework::SpawnableEntitiesManager::CommandQueuePriority::High | AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); From 8c541b5205dd7605965e9719df6bfcfc1470f52a Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Tue, 1 Jun 2021 16:11:55 -0700 Subject: [PATCH 471/811] Moved default values to object in the Spawnable Entities Interface --- .../Spawnable/SpawnableEntitiesContainer.cpp | 11 ++-- .../Spawnable/SpawnableEntitiesInterface.h | 53 +++++++++++++------ .../Spawnable/SpawnableEntitiesManager.cpp | 37 +++++++------ .../Spawnable/SpawnableEntitiesManager.h | 22 ++++---- .../SpawnableEntitiesManagerTests.cpp | 26 +++++---- .../Libraries/Spawning/SpawnNodeable.cpp | 6 ++- 6 files changed, 88 insertions(+), 67 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp index 808de74e71..a945ea4edc 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesContainer.cpp @@ -38,20 +38,20 @@ namespace AzFramework void SpawnableEntitiesContainer::SpawnAllEntities() { AZ_Assert(m_threadData, "Calling SpawnAllEntities on a Spawnable container that's not set."); - SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_threadData->m_spawnedEntitiesTicket, SpawnablePriority_Default); + SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_threadData->m_spawnedEntitiesTicket); } void SpawnableEntitiesContainer::SpawnEntities(AZStd::vector entityIndices) { AZ_Assert(m_threadData, "Calling SpawnEntities on a Spawnable container that's not set."); SpawnableEntitiesInterface::Get()->SpawnEntities( - m_threadData->m_spawnedEntitiesTicket, SpawnablePriority_Default, AZStd::move(entityIndices)); + m_threadData->m_spawnedEntitiesTicket, AZStd::move(entityIndices)); } void SpawnableEntitiesContainer::DespawnAllEntities() { AZ_Assert(m_threadData, "Calling DespawnEntities on a Spawnable container that's not set."); - SpawnableEntitiesInterface::Get()->DespawnAllEntities(m_threadData->m_spawnedEntitiesTicket, SpawnablePriority_Default); + SpawnableEntitiesInterface::Get()->DespawnAllEntities(m_threadData->m_spawnedEntitiesTicket); } void SpawnableEntitiesContainer::Reset(AZ::Data::Asset spawnable) @@ -69,7 +69,6 @@ namespace AzFramework SpawnableEntitiesInterface::Get()->Barrier( m_threadData->m_spawnedEntitiesTicket, - SpawnablePriority_Default, [threadData = m_threadData](EntitySpawnTicket::Id) mutable { threadData.reset(); @@ -88,7 +87,6 @@ namespace AzFramework AZ_Assert(m_threadData, "Calling DespawnEntities on a Spawnable container that's not set."); SpawnableEntitiesInterface::Get()->Barrier( m_threadData->m_spawnedEntitiesTicket, - SpawnablePriority_Default, [generation = m_threadData->m_generation, callback = AZStd::move(callback)](EntitySpawnTicket::Id) { callback(generation); @@ -115,7 +113,6 @@ namespace AzFramework AZ_Assert(m_threadData, "SpawnableEntitiesContainer is monitoring a spawnable, but doesn't have the associated data."); AZ_TracePrintf("Spawnables", "Reloading spawnable '%s'.\n", replacementAsset.GetHint().c_str()); - SpawnableEntitiesInterface::Get()->ReloadSpawnable( - m_threadData->m_spawnedEntitiesTicket, SpawnablePriority_Default, AZStd::move(replacementAsset)); + SpawnableEntitiesInterface::Get()->ReloadSpawnable(m_threadData->m_spawnedEntitiesTicket, AZStd::move(replacementAsset)); } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index cfa1f3b464..5d7ce79641 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -172,7 +172,7 @@ namespace AzFramework using ClaimEntitiesCallback = AZStd::function; using BarrierCallback = AZStd::function; - struct SpawnEntitiesOptionalArgs + struct SpawnEntitiesOptionalArgs final { //! Callback that's called after instances of entities have been created, but before they're spawned into the world. This //! gives the opportunity to modify the entities if needed such as injecting additional components or modifying components. @@ -182,22 +182,46 @@ namespace AzFramework EntitySpawnCallback m_completionCallback; //! The Serialize Context used to clone entities with. If this is not provided the global Serialize Contetx will be used. AZ::SerializeContext* m_serializeContext { nullptr }; + //! The priority at which this call will be executed. + SpawnablePriority m_priority { SpawnablePriority_Default }; }; - struct DespawnAllEntitiesOptionalArgs + struct DespawnAllEntitiesOptionalArgs final { //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that //! made the function call. The returned list of entities contains all the newly created entities. EntityDespawnCallback m_completionCallback; + //! The priority at which this call will be executed. + SpawnablePriority m_priority { SpawnablePriority_Default }; }; - struct ReloadSpawnableOptionalArgs + struct ReloadSpawnableOptionalArgs final { //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that //! made the function call. The returned list of entities contains all the newly created entities. ReloadSpawnableCallback m_completionCallback; //! The Serialize Context used to clone entities with. If this is not provided the global Serialize Contetx will be used. AZ::SerializeContext* m_serializeContext { nullptr }; + //! The priority at which this call will be executed. + SpawnablePriority m_priority { SpawnablePriority_Default }; + }; + + struct ListEntitiesOptionalArgs final + { + //! The priority at which this call will be executed. + SpawnablePriority m_priority{ SpawnablePriority_Default }; + }; + + struct ClaimEntitiesOptionalArgs final + { + //! The priority at which this call will be executed. + SpawnablePriority m_priority{ SpawnablePriority_Default }; + }; + + struct BarrierOptionalArgs final + { + //! The priority at which this call will be executed. + SpawnablePriority m_priority{ SpawnablePriority_Default }; }; //! Interface definition to (de)spawn entities from a spawnable into the game world. @@ -225,38 +249,34 @@ namespace AzFramework //! Spawn instances of all entities in the spawnable. //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. - //! @param priority The priority at which this call will be executed. //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs - virtual void SpawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, SpawnEntitiesOptionalArgs optionalArgs = {}) = 0; + virtual void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnEntitiesOptionalArgs optionalArgs = {}) = 0; //! Spawn instances of some entities in the spawnable. //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. //! @param priority The priority at which this call will be executed. //! @param entityIndices The indices into the template entities stored in the spawnable that will be used to spawn entities from. //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs virtual void SpawnEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, AZStd::vector entityIndices, - SpawnEntitiesOptionalArgs optionalArgs = {}) = 0; + EntitySpawnTicket& ticket, AZStd::vector entityIndices, SpawnEntitiesOptionalArgs optionalArgs = {}) = 0; //! Removes all entities in the provided list from the environment. //! @param ticket The ticket previously used to spawn entities with. //! @param priority The priority at which this call will be executed. //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs - virtual void DespawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, DespawnAllEntitiesOptionalArgs optionalArgs = {}) = 0; + virtual void DespawnAllEntities(EntitySpawnTicket& ticket, DespawnAllEntitiesOptionalArgs optionalArgs = {}) = 0; //! Removes all entities in the provided list from the environment and reconstructs the entities from the provided spawnable. //! @param ticket Holds the information on the entities to reload. //! @param priority The priority at which this call will be executed. //! @param spawnable The spawnable that will replace the existing spawnable. Both need to have the same asset id. //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs virtual void ReloadSpawnable( - EntitySpawnTicket& ticket, SpawnablePriority priority, AZ::Data::Asset spawnable, - ReloadSpawnableOptionalArgs optionalArgs = {}) = 0; + EntitySpawnTicket& ticket, AZ::Data::Asset spawnable, ReloadSpawnableOptionalArgs optionalArgs = {}) = 0; //! List all entities that are spawned using this ticket. //! @param ticket Only the entities associated with this ticket will be listed. //! @param priority The priority at which this call will be executed. //! @param listCallback Required callback that will be called to list the entities on. - virtual void ListEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ListEntitiesCallback listCallback) = 0; + virtual void ListEntities( + EntitySpawnTicket& ticket, ListEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs = {}) = 0; //! List all entities that are spawned using this ticket with their spawnable index. //! Spawnables contain a flat list of entities, which are used as templates to spawn entities from. For every spawned entity //! the index of the entity in the spawnable that was used as a template is stored. This version of ListEntities will return @@ -267,20 +287,21 @@ namespace AzFramework //! @param priority The priority at which this call will be executed. //! @param listCallback Required callback that will be called to list the entities and indices on. virtual void ListIndicesAndEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, ListIndicesEntitiesCallback listCallback) = 0; + EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs = {}) = 0; //! Claim all entities that are spawned using this ticket. Ownership of the entities is transferred from the ticket to the //! caller through the callback. After this call the ticket will have no entities associated with it. The caller of //! this function will need to manage the entities after this call. //! @param ticket Only the entities associated with this ticket will be released. //! @param priority The priority at which this call will be executed. //! @param listCallback Required callback that will be called to transfer the entities through. - virtual void ClaimEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ClaimEntitiesCallback listCallback) = 0; + virtual void ClaimEntities( + EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback, ClaimEntitiesOptionalArgs optionalArgs = {}) = 0; //! Blocks until all operations made on the provided ticket before the barrier call have completed. //! @param ticket The ticket to monitor. //! @param priority The priority at which this call will be executed. //! @param completionCallback Required callback that will be called as soon as the barrier has been reached. - virtual void Barrier(EntitySpawnTicket& ticket, SpawnablePriority priority, BarrierCallback completionCallback) = 0; + virtual void Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback, BarrierOptionalArgs optionalArgs = {}) = 0; //! Register a handler for OnSpawned events. virtual void AddOnSpawnedHandler(AZ::Event>::Handler& handler) = 0; diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp index 77106172f6..c11ce94bb2 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp @@ -50,8 +50,7 @@ namespace AzFramework } } - void SpawnableEntitiesManager::SpawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, SpawnEntitiesOptionalArgs optionalArgs) + void SpawnableEntitiesManager::SpawnAllEntities(EntitySpawnTicket& ticket, SpawnEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnAllEntities hasn't been initialized."); @@ -61,11 +60,11 @@ namespace AzFramework optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback); - QueueRequest(ticket, priority, AZStd::move(queueEntry)); + QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::SpawnEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, AZStd::vector entityIndices, SpawnEntitiesOptionalArgs optionalArgs) + EntitySpawnTicket& ticket, AZStd::vector entityIndices, SpawnEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnEntities hasn't been initialized."); @@ -76,23 +75,21 @@ namespace AzFramework optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback); - QueueRequest(ticket, priority, AZStd::move(queueEntry)); + QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } - void SpawnableEntitiesManager::DespawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, DespawnAllEntitiesOptionalArgs optionalArgs) + void SpawnableEntitiesManager::DespawnAllEntities(EntitySpawnTicket& ticket, DespawnAllEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to DespawnAllEntities hasn't been initialized."); DespawnAllEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); - QueueRequest(ticket, priority, AZStd::move(queueEntry)); + QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::ReloadSpawnable( - EntitySpawnTicket& ticket, SpawnablePriority priority, AZ::Data::Asset spawnable, - ReloadSpawnableOptionalArgs optionalArgs) + EntitySpawnTicket& ticket, AZ::Data::Asset spawnable, ReloadSpawnableOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to ReloadSpawnable hasn't been initialized."); @@ -102,10 +99,11 @@ namespace AzFramework queueEntry.m_serializeContext = optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); - QueueRequest(ticket, priority, AZStd::move(queueEntry)); + QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } - void SpawnableEntitiesManager::ListEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ListEntitiesCallback listCallback) + void SpawnableEntitiesManager::ListEntities( + EntitySpawnTicket& ticket, ListEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs) { AZ_Assert(listCallback, "ListEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized."); @@ -113,11 +111,11 @@ namespace AzFramework ListEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); - QueueRequest(ticket, priority, AZStd::move(queueEntry)); + QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::ListIndicesAndEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, ListIndicesEntitiesCallback listCallback) + EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs) { AZ_Assert(listCallback, "ListEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized."); @@ -125,10 +123,11 @@ namespace AzFramework ListIndicesEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); - QueueRequest(ticket, priority, AZStd::move(queueEntry)); + QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } - void SpawnableEntitiesManager::ClaimEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ClaimEntitiesCallback listCallback) + void SpawnableEntitiesManager::ClaimEntities( + EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback, ClaimEntitiesOptionalArgs optionalArgs) { AZ_Assert(listCallback, "ClaimEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ClaimEntities hasn't been initialized."); @@ -136,10 +135,10 @@ namespace AzFramework ClaimEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); - QueueRequest(ticket, priority, AZStd::move(queueEntry)); + QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } - void SpawnableEntitiesManager::Barrier(EntitySpawnTicket& ticket, SpawnablePriority priority, BarrierCallback completionCallback) + void SpawnableEntitiesManager::Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback, BarrierOptionalArgs optionalArgs) { AZ_Assert(completionCallback, "Barrier on spawnable entities called without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to Barrier hasn't been initialized."); @@ -147,7 +146,7 @@ namespace AzFramework BarrierCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(completionCallback); - QueueRequest(ticket, priority, AZStd::move(queueEntry)); + QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::AddOnSpawnedHandler(AZ::Event>::Handler& handler) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h index b40ec20aa3..e6db19557f 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h @@ -57,23 +57,21 @@ namespace AzFramework // The following functions are thread safe // - void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, SpawnEntitiesOptionalArgs optionalArgs = {}) override; + void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnEntitiesOptionalArgs optionalArgs = {}) override; void SpawnEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, AZStd::vector entityIndices, - SpawnEntitiesOptionalArgs optionalArgs = {}) override; - void DespawnAllEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, DespawnAllEntitiesOptionalArgs optionalArgs = {}) override; - + EntitySpawnTicket& ticket, AZStd::vector entityIndices, SpawnEntitiesOptionalArgs optionalArgs = {}) override; + void DespawnAllEntities(EntitySpawnTicket& ticket, DespawnAllEntitiesOptionalArgs optionalArgs = {}) override; void ReloadSpawnable( - EntitySpawnTicket& ticket, SpawnablePriority priority, AZ::Data::Asset spawnable, - ReloadSpawnableOptionalArgs optionalArgs = {}) override; + EntitySpawnTicket& ticket, AZ::Data::Asset spawnable, ReloadSpawnableOptionalArgs optionalArgs = {}) override; - void ListEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ListEntitiesCallback listCallback) override; + void ListEntities( + EntitySpawnTicket& ticket, ListEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs = {}) override; void ListIndicesAndEntities( - EntitySpawnTicket& ticket, SpawnablePriority priority, ListIndicesEntitiesCallback listCallback) override; - void ClaimEntities(EntitySpawnTicket& ticket, SpawnablePriority priority, ClaimEntitiesCallback listCallback) override; + EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs = {}) override; + void ClaimEntities( + EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback, ClaimEntitiesOptionalArgs optionalArgs = {}) override; - void Barrier(EntitySpawnTicket& spawnInfo, SpawnablePriority priority, BarrierCallback completionCallback) override; + void Barrier(EntitySpawnTicket& spawnInfo, BarrierCallback completionCallback, BarrierOptionalArgs optionalArgs = {}) override; void AddOnSpawnedHandler(AZ::Event>::Handler& handler) override; void AddOnDespawnedHandler(AZ::Event>::Handler& handler) override; diff --git a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp index 7a2e7f614b..8637684b3c 100644 --- a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp +++ b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp @@ -106,7 +106,7 @@ namespace UnitTest }; AzFramework::SpawnEntitiesOptionalArgs optionalArgs; optionalArgs.m_completionCallback = AZStd::move(callback); - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(optionalArgs)); + m_manager->SpawnAllEntities(*m_ticket, AZStd::move(optionalArgs)); m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); EXPECT_EQ(NumEntities, spawnedEntitiesCount); @@ -116,7 +116,7 @@ namespace UnitTest { { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->SpawnAllEntities(ticket, AzFramework::SpawnablePriority_Default); + m_manager->SpawnAllEntities(ticket); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -130,7 +130,7 @@ namespace UnitTest { { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->SpawnEntities(ticket, AzFramework::SpawnablePriority_Default, {}); + m_manager->SpawnEntities(ticket, {/* Deliberate empty list of indices. */}); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -144,7 +144,7 @@ namespace UnitTest { { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->DespawnAllEntities(ticket, AzFramework::SpawnablePriority_Default); + m_manager->DespawnAllEntities(ticket); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -158,7 +158,7 @@ namespace UnitTest { { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->ReloadSpawnable(ticket, AzFramework::SpawnablePriority_Default, *m_spawnableAsset); + m_manager->ReloadSpawnable(ticket, *m_spawnableAsset); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -185,7 +185,7 @@ namespace UnitTest spawnedEntitiesCount += entities.size(); }; - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default); + m_manager->SpawnAllEntities(*m_ticket); m_manager->ListEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); @@ -230,7 +230,7 @@ namespace UnitTest } }; - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default); + m_manager->SpawnAllEntities(*m_ticket); m_manager->ListIndicesAndEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); @@ -309,11 +309,13 @@ namespace UnitTest AzFramework::SpawnEntitiesOptionalArgs optionalArgs; optionalArgs.m_completionCallback = AZStd::move(defaultCallback); - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(optionalArgs)); + optionalArgs.m_priority = AzFramework::SpawnablePriority_Default; + m_manager->SpawnAllEntities(*m_ticket, AZStd::move(optionalArgs)); AzFramework::SpawnEntitiesOptionalArgs highPriortyOptionalArgs; highPriortyOptionalArgs.m_completionCallback = AZStd::move(highCallback); - m_manager->SpawnAllEntities(highPriorityTicket, AzFramework::SpawnablePriority_High, AZStd::move(highPriortyOptionalArgs)); + highPriortyOptionalArgs.m_priority = AzFramework::SpawnablePriority_High; + m_manager->SpawnAllEntities(highPriorityTicket, AZStd::move(highPriortyOptionalArgs)); m_manager->ProcessQueue( AzFramework::SpawnableEntitiesManager::CommandQueuePriority::High | @@ -343,11 +345,13 @@ namespace UnitTest AzFramework::SpawnEntitiesOptionalArgs optionalArgs; optionalArgs.m_completionCallback = AZStd::move(defaultCallback); - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(optionalArgs)); + optionalArgs.m_priority = AzFramework::SpawnablePriority_Default; + m_manager->SpawnAllEntities(*m_ticket, AZStd::move(optionalArgs)); AzFramework::SpawnEntitiesOptionalArgs highPriortyOptionalArgs; highPriortyOptionalArgs.m_completionCallback = AZStd::move(highCallback); - m_manager->SpawnAllEntities(*m_ticket, AzFramework::SpawnablePriority_High, AZStd::move(highPriortyOptionalArgs)); + highPriortyOptionalArgs.m_priority = AzFramework::SpawnablePriority_High; + m_manager->SpawnAllEntities(*m_ticket, AZStd::move(highPriortyOptionalArgs)); m_manager->ProcessQueue( AzFramework::SpawnableEntitiesManager::CommandQueuePriority::High | diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index ad53236108..39afa46a19 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -134,7 +134,9 @@ namespace ScriptCanvas::Nodeables::Spawning m_spawnBatchSizes.push_back(view.size()); }; - AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities( - m_spawnTicket, AzFramework::SpawnablePriority_Default, preSpawnCB, spawnCompleteCB); + AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + optionalArgs.m_preInsertionCallback = AZStd::move(preSpawnCB); + optionalArgs.m_completionCallback = AZStd::move(spawnCompleteCB); + AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_spawnTicket, AZStd::move(optionalArgs)); } } From 1e7ac6094982b78a262da2989507fcbf0ab0d566 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Thu, 3 Jun 2021 10:49:25 -0700 Subject: [PATCH 472/811] Reintroduced spawning multiple instances of the same entity The following was changed: - The remapper in AZ::IdUtils now has an additional argument to tell it what to do when it encounters the same source entity id. The original behavior of ignoring the new entity id and returning the first occurrence is the default. The alternative behavior is to store the last known entity id and return that instead. - Split the optional arguments for SpawnAllEntities and SpawnEntities. - SpawnEntities now has an option to continue with the entity mapping from a previous spawn call or to start with a fresh mapping. The latter is the default as the former will come at a performance cost since the mapping table has to be reconstructed. - Entities spawned using SpawnEntities and ReloadEntities now also get the correct entity mapping applied. - Added several new unit tests to cover most of the new functionality. - Fixed some places where the older API version was still called. --- .../AzCore/AzCore/Serialization/IdUtils.h | 28 +- .../AzCore/AzCore/Serialization/IdUtils.inl | 16 +- .../Spawnable/SpawnableEntitiesInterface.h | 23 +- .../Spawnable/SpawnableEntitiesManager.cpp | 111 ++++---- .../Spawnable/SpawnableEntitiesManager.h | 14 +- .../SpawnableEntitiesManagerTests.cpp | 254 +++++++++++++++++- .../Pipeline/NetBindMarkerComponent.cpp | 6 +- .../Libraries/Spawning/SpawnNodeable.cpp | 2 +- 8 files changed, 362 insertions(+), 92 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/IdUtils.h b/Code/Framework/AzCore/AzCore/Serialization/IdUtils.h index a571379883..98959fe4bd 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/IdUtils.h +++ b/Code/Framework/AzCore/AzCore/Serialization/IdUtils.h @@ -28,7 +28,13 @@ namespace AZ { namespace IdUtils { - template + /** + * \param AllowDuplicates - If true allows the same id to be registered multiple time, + with the newer value overwriting the stored value. If false, duplicates are not allowed and + the first stored value is kept.The default is false. + */ + + template struct Remapper { /** @@ -138,14 +144,18 @@ namespace AZ * \param context - The serialize context for enumerating the @classPtr elements */ template - static void GenerateNewIdsAndFixRefs(T* object, MapType& newIdMap, AZ::SerializeContext* context = nullptr) + static void GenerateNewIdsAndFixRefs( + T* object, MapType& newIdMap, AZ::SerializeContext* context = nullptr) { if (!context) { AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationRequests::GetSerializeContext); if (!context) { - AZ_Error("Serialization", false, "No serialize context provided! Failed to get component application default serialize context! ComponentApp is not started or input serialize context should not be null!"); + AZ_Error( + "Serialization", false, + "No serialize context provided! Failed to get component application default serialize context! ComponentApp is " + "not started or input serialize context should not be null!"); return; } } @@ -156,8 +166,16 @@ namespace AZ { if (idGenerator) { - auto it = newIdMap.emplace(originalId, idGenerator()); - return it.first->second; + if constexpr(AllowDuplicates) + { + auto it = newIdMap.insert_or_assign(originalId, idGenerator()); + return it.first->second; + } + else + { + auto it = newIdMap.emplace(originalId, idGenerator()); + return it.first->second; + } } return originalId; } diff --git a/Code/Framework/AzCore/AzCore/Serialization/IdUtils.inl b/Code/Framework/AzCore/AzCore/Serialization/IdUtils.inl index 01617cf5aa..0dc87dfe18 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/IdUtils.inl +++ b/Code/Framework/AzCore/AzCore/Serialization/IdUtils.inl @@ -30,8 +30,10 @@ namespace AZ bool m_isModifiedContainer; }; - template - unsigned int Remapper::RemapIds(void* classPtr, const AZ::Uuid& classUuid, const typename Remapper::IdMapper& mapper, AZ::SerializeContext* context, bool replaceId) + template + unsigned int Remapper::RemapIds( + void* classPtr, const AZ::Uuid& classUuid, const typename Remapper::IdMapper& mapper, + AZ::SerializeContext* context, bool replaceId) { if (!context) { @@ -152,16 +154,18 @@ namespace AZ return replaced; } - template - unsigned int Remapper::ReplaceIdsAndIdRefs(void* classPtr, const AZ::Uuid& classUuid, const IdMapper& mapper, AZ::SerializeContext* context /*= nullptr*/) + template + unsigned int Remapper::ReplaceIdsAndIdRefs(void* classPtr, const AZ::Uuid& classUuid, const IdMapper& mapper, AZ::SerializeContext* context /*= nullptr*/) { unsigned int replaced = RemapIds(classPtr, classUuid, mapper, context, true); replaced += RemapIds(classPtr, classUuid, mapper, context, false); return replaced; } - template - unsigned int Remapper::RemapIdsAndIdRefs(void* classPtr, const AZ::Uuid& classUuid, const typename Remapper::IdReplacer& mapper, AZ::SerializeContext* context) + template + unsigned int Remapper::RemapIdsAndIdRefs( + void* classPtr, const AZ::Uuid& classUuid, const typename Remapper::IdReplacer& mapper, + AZ::SerializeContext* context) { if (!context) { diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index 5d7ce79641..2ad1db60a4 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -172,7 +172,7 @@ namespace AzFramework using ClaimEntitiesCallback = AZStd::function; using BarrierCallback = AZStd::function; - struct SpawnEntitiesOptionalArgs final + struct SpawnAllEntitiesOptionalArgs final { //! Callback that's called after instances of entities have been created, but before they're spawned into the world. This //! gives the opportunity to modify the entities if needed such as injecting additional components or modifying components. @@ -186,6 +186,25 @@ namespace AzFramework SpawnablePriority m_priority { SpawnablePriority_Default }; }; + struct SpawnEntitiesOptionalArgs final + { + //! Callback that's called after instances of entities have been created, but before they're spawned into the world. This + //! gives the opportunity to modify the entities if needed such as injecting additional components or modifying components. + EntityPreInsertionCallback m_preInsertionCallback; + //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that + //! made the function call. The returned list of entities contains all the newly created entities. + EntitySpawnCallback m_completionCallback; + //! The Serialize Context used to clone entities with. If this is not provided the global Serialize Contetx will be used. + AZ::SerializeContext* m_serializeContext{ nullptr }; + //! The priority at which this call will be executed. + SpawnablePriority m_priority{ SpawnablePriority_Default }; + //! Entity references are resolved by referring to the last entity spawned from a template entity in the spawnable. If this + //! is set to false entities from previous spawn calls are not taken into account. If set to true entity references may be + //! resolved to a previously spawned entity. A lookup table has to be constructed when true, which may negatively impact + //! performance, especially if a large number of entities are present on a ticket. + bool m_referencePreviouslySpawnedEntities{ false }; + }; + struct DespawnAllEntitiesOptionalArgs final { //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that @@ -250,7 +269,7 @@ namespace AzFramework //! Spawn instances of all entities in the spawnable. //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs - virtual void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnEntitiesOptionalArgs optionalArgs = {}) = 0; + virtual void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnAllEntitiesOptionalArgs optionalArgs = {}) = 0; //! Spawn instances of some entities in the spawnable. //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. //! @param priority The priority at which this call will be executed. diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp index c11ce94bb2..a482c1d4f9 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp @@ -50,7 +50,7 @@ namespace AzFramework } } - void SpawnableEntitiesManager::SpawnAllEntities(EntitySpawnTicket& ticket, SpawnEntitiesOptionalArgs optionalArgs) + void SpawnableEntitiesManager::SpawnAllEntities(EntitySpawnTicket& ticket, SpawnAllEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnAllEntities hasn't been initialized."); @@ -75,6 +75,7 @@ namespace AzFramework optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback); + queueEntry.m_referencePreviouslySpawnedEntities = optionalArgs.m_referencePreviouslySpawnedEntities; QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } @@ -256,21 +257,11 @@ namespace AzFramework } } - AZ::Entity* SpawnableEntitiesManager::SpawnSingleEntity(const AZ::Entity& entityTemplate, AZ::SerializeContext& serializeContext) - { - AZ::Entity* clone = serializeContext.CloneObject(&entityTemplate); - AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); - clone->SetId(AZ::Entity::MakeId()); - - GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, clone); - return clone; - } - AZ::Entity* SpawnableEntitiesManager::CloneSingleEntity(const AZ::Entity& entityTemplate, - EntityIdMap& templateToCloneEntityIdMap, AZ::SerializeContext& serializeContext) + EntityIdMap& templateToCloneMap, AZ::SerializeContext& serializeContext) { - return AZ::IdUtils::Remapper::CloneObjectAndGenerateNewIdsAndFixRefs( - &entityTemplate, templateToCloneEntityIdMap, &serializeContext); + return AZ::IdUtils::Remapper::CloneObjectAndGenerateNewIdsAndFixRefs( + &entityTemplate, templateToCloneMap, &serializeContext); } bool SpawnableEntitiesManager::ProcessRequest(SpawnAllEntitiesCommand& request) @@ -297,13 +288,9 @@ namespace AzFramework spawnedEntityIndices.reserve(spawnedEntityIndices.size() + entitiesToSpawnSize); templateToCloneEntityIdMap.reserve(entitiesToSpawnSize); - // Mark all indices as spawned for (size_t i = 0; i < entitiesToSpawnSize; ++i) { - const AZ::Entity& entityTemplate = *entitiesToSpawn[i]; - - AZ::Entity* clone = CloneSingleEntity(entityTemplate, templateToCloneEntityIdMap, *request.m_serializeContext); - + AZ::Entity* clone = CloneSingleEntity(*entitiesToSpawn[i], templateToCloneEntityIdMap, *request.m_serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); spawnedEntities.emplace_back(clone); @@ -311,16 +298,8 @@ namespace AzFramework } // loadAll is true if every entity has been spawned only once - if (spawnedEntities.size() == entitiesToSpawnSize) - { - ticket.m_loadAll = true; - } - else - { - // Case where there were already spawns from a previous request - ticket.m_loadAll = false; - } - + ticket.m_loadAll = (spawnedEntities.size() == entitiesToSpawnSize); + // Let other systems know about newly spawned entities for any pre-processing before adding to the scene/game context. if (request.m_preInsertionCallback) { @@ -329,11 +308,10 @@ namespace AzFramework } // Add to the game context, now the entities are active - AZStd::for_each(ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end(), - [](AZ::Entity* entity) + for (auto it = ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount; it != ticket.m_spawnedEntities.end(); ++it) { - GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, entity); - }); + GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, *it); + } // Let other systems know about newly spawned entities for any post-processing after adding to the scene/game context. if (request.m_completionCallback) @@ -360,14 +338,34 @@ namespace AzFramework { AZStd::vector& spawnedEntities = ticket.m_spawnedEntities; AZStd::vector& spawnedEntityIndices = ticket.m_spawnedEntityIndices; + AZ_Assert( + spawnedEntities.size() == spawnedEntityIndices.size(), + "The indices for the spawned entities has gone out of sync with the entities."); - // Keep track how many entities there were in the array initially + // Keep track of how many entities there were in the array initially size_t spawnedEntitiesInitialCount = spawnedEntities.size(); // These are 'template' entities we'll be cloning from const Spawnable::EntityList& entitiesToSpawn = ticket.m_spawnable->GetEntities(); size_t entitiesToSpawnSize = request.m_entityIndices.size(); + // Reconstruct the template to entity mapping. + EntityIdMap templateToCloneEntityIdMap; + if (!request.m_referencePreviouslySpawnedEntities) + { + templateToCloneEntityIdMap.reserve(entitiesToSpawnSize); + } + else + { + templateToCloneEntityIdMap.reserve(spawnedEntitiesInitialCount + entitiesToSpawnSize); + SpawnableConstIndexEntityContainerView indexEntityView( + spawnedEntities.begin(), spawnedEntityIndices.begin(), spawnedEntities.size()); + for (auto& entry : indexEntityView) + { + templateToCloneEntityIdMap.insert_or_assign(entitiesToSpawn[entry.GetIndex()]->GetId(), entry.GetEntity()->GetId()); + } + } + spawnedEntities.reserve(spawnedEntities.size() + entitiesToSpawnSize); spawnedEntityIndices.reserve(spawnedEntityIndices.size() + entitiesToSpawnSize); @@ -375,15 +373,11 @@ namespace AzFramework { if (index < entitiesToSpawn.size()) { - const AZ::Entity& entityTemplate = *entitiesToSpawn[index]; - - AZ::Entity* clone = request.m_serializeContext->CloneObject(&entityTemplate); + AZ::Entity* clone = CloneSingleEntity(*entitiesToSpawn[index], templateToCloneEntityIdMap, *request.m_serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); - clone->SetId(AZ::Entity::MakeId()); spawnedEntities.push_back(clone); spawnedEntityIndices.push_back(index); - } } ticket.m_loadAll = false; @@ -396,11 +390,10 @@ namespace AzFramework } // Add to the game context, now the entities are active - AZStd::for_each(ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end(), - [](AZ::Entity* entity) + for (auto it = ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount; it != ticket.m_spawnedEntities.end(); ++it) { - GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, entity); - }); + GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, *it); + } if (request.m_completionCallback) { @@ -475,39 +468,43 @@ namespace AzFramework // Rebuild the list of entities. ticket.m_spawnedEntities.clear(); const Spawnable::EntityList& entities = request.m_spawnable->GetEntities(); + + // Map keeps track of ids from template (spawnable) to clone (instance) + // Allowing patch ups of fields referring to entityIds outside of a given entity + EntityIdMap templateToCloneEntityIdMap; + if (ticket.m_loadAll) { // The new spawnable may have a different number of entities and since the intent of the user was - // to load every, simply start over. + // to spawn every entity, simply start over. ticket.m_spawnedEntityIndices.clear(); - size_t entitiesToSpawnSize = entities.size(); - - // Map keeps track of ids from template (spawnable) to clone (instance) - // Allowing patch ups of fields referring to entityIds outside of a given entity - EntityIdMap templateToCloneEntityIdMap; templateToCloneEntityIdMap.reserve(entitiesToSpawnSize); - // Mark all indices as spawned for (size_t i = 0; i < entitiesToSpawnSize; ++i) { - const AZ::Entity& entityTemplate = *entities[i]; - - AZ::Entity* clone = CloneSingleEntity(entityTemplate, templateToCloneEntityIdMap, *request.m_serializeContext); - + AZ::Entity* clone = CloneSingleEntity(*entities[i], templateToCloneEntityIdMap, *request.m_serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); - ticket.m_spawnedEntities.emplace_back(clone); + ticket.m_spawnedEntities.push_back(clone); ticket.m_spawnedEntityIndices.push_back(i); } } else { size_t entitiesSize = entities.size(); + templateToCloneEntityIdMap.reserve(entitiesSize); for (size_t index : ticket.m_spawnedEntityIndices) { - ticket.m_spawnedEntities.push_back( - index < entitiesSize ? SpawnSingleEntity(*entities[index], *request.m_serializeContext) : nullptr); + // It's possible for the new spawnable to have a different number of entities, so guard against this. + // It's also possible that the entities have moved within the spawnable to a new index. This can't be + // detected and will result in the incorrect entities being spawned. + if (index < entitiesSize) + { + AZ::Entity* clone = CloneSingleEntity(*entities[index], templateToCloneEntityIdMap, *request.m_serializeContext); + AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); + ticket.m_spawnedEntities.push_back(clone); + } } } ticket.m_spawnable = AZStd::move(request.m_spawnable); diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h index e6db19557f..638559f3f1 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h @@ -37,7 +37,7 @@ namespace AzFramework AZ_CLASS_ALLOCATOR(SpawnableEntitiesManager, AZ::SystemAllocator, 0); using EntityIdMap = AZStd::unordered_map; - + enum class CommandQueueStatus : bool { HasCommandsLeft, @@ -57,7 +57,7 @@ namespace AzFramework // The following functions are thread safe // - void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnEntitiesOptionalArgs optionalArgs = {}) override; + void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnAllEntitiesOptionalArgs optionalArgs = {}) override; void SpawnEntities( EntitySpawnTicket& ticket, AZStd::vector entityIndices, SpawnEntitiesOptionalArgs optionalArgs = {}) override; void DespawnAllEntities(EntitySpawnTicket& ticket, DespawnAllEntitiesOptionalArgs optionalArgs = {}) override; @@ -114,6 +114,7 @@ namespace AzFramework Ticket* m_ticket; EntitySpawnTicket::Id m_ticketId; uint32_t m_requestId; + bool m_referencePreviouslySpawnedEntities; }; struct DespawnAllEntitiesCommand { @@ -183,12 +184,9 @@ namespace AzFramework CommandQueueStatus ProcessQueue(Queue& queue); - AZ::Entity* SpawnSingleEntity(const AZ::Entity& entityTemplate, - AZ::SerializeContext& serializeContext); - - AZ::Entity* CloneSingleEntity(const AZ::Entity& entityTemplate, - EntityIdMap& templateToCloneEntityIdMap, AZ::SerializeContext& serializeContext); - + AZ::Entity* CloneSingleEntity( + const AZ::Entity& entityTemplate, EntityIdMap& templateToCloneMap, AZ::SerializeContext& serializeContext); + bool ProcessRequest(SpawnAllEntitiesCommand& request); bool ProcessRequest(SpawnEntitiesCommand& request); bool ProcessRequest(DespawnAllEntitiesCommand& request); diff --git a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp index 8637684b3c..32ad7d8ea9 100644 --- a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp +++ b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include namespace UnitTest @@ -81,6 +82,42 @@ namespace UnitTest } } + void CreateRecursiveHierarchy() + { + AzFramework::Spawnable::EntityList& entities = m_spawnable->GetEntities(); + size_t numElements = entities.size(); + AZ::EntityId parent; + for (size_t i=0; i& entity = entities[i]; + auto component = entity->CreateComponent(); + if (i > 0) + { + component->SetParent(parent); + } + parent = entity->GetId(); + } + } + + void CreateSingleParent() + { + AzFramework::Spawnable::EntityList& entities = m_spawnable->GetEntities(); + size_t numElements = entities.size(); + if (numElements > 0) + { + AZ::EntityId parent = entities[0]->GetId(); + for (size_t i = 0; i < numElements; ++i) + { + AZStd::unique_ptr& entity = entities[i]; + auto component = entity->CreateComponent(); + if (i > 0) + { + component->SetParent(parent); + } + } + } + } + protected: AZ::Data::Asset* m_spawnableAsset { nullptr }; AzFramework::SpawnableEntitiesManager* m_manager { nullptr }; @@ -104,7 +141,7 @@ namespace UnitTest { spawnedEntitiesCount += entities.size(); }; - AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + AzFramework::SpawnAllEntitiesOptionalArgs optionalArgs; optionalArgs.m_completionCallback = AZStd::move(callback); m_manager->SpawnAllEntities(*m_ticket, AZStd::move(optionalArgs)); m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); @@ -112,6 +149,37 @@ namespace UnitTest EXPECT_EQ(NumEntities, spawnedEntitiesCount); } + TEST_F(SpawnableEntitiesManagerTest, SpawnAllEntities_SetParentOnSpawnedEntities_LineageIsPreserved) + { + static constexpr size_t NumEntities = 4; + FillSpawnable(NumEntities); + CreateRecursiveHierarchy(); + + auto callback = [](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + { + AZ::EntityId parentId; + bool isFirst = true; + for (const AZ::Entity* entity : entities) + { + if (!isFirst) + { + auto transform = entity->GetTransform(); + ASSERT_NE(nullptr, transform); + EXPECT_EQ(parentId, transform->GetParentId()); + } + else + { + isFirst = false; + } + parentId = entity->GetId(); + } + }; + AzFramework::SpawnAllEntitiesOptionalArgs optionalArgs; + optionalArgs.m_completionCallback = AZStd::move(callback); + m_manager->SpawnAllEntities(*m_ticket, AZStd::move(optionalArgs)); + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + TEST_F(SpawnableEntitiesManagerTest, SpawnAllEntities_DeleteTicketBeforeCall_NoCrash) { { @@ -126,6 +194,170 @@ namespace UnitTest // SpawnEntities // + TEST_F(SpawnableEntitiesManagerTest, SpawnEntities_Call_AllEntitiesSpawned) + { + static constexpr size_t NumEntities = 4; + FillSpawnable(NumEntities); + + AZStd::vector indices = { 0, 2, 3, 1 }; + + size_t spawnedEntitiesCount = 0; + auto callback = [&spawnedEntitiesCount](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + { + spawnedEntitiesCount += entities.size(); + }; + AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + optionalArgs.m_completionCallback = AZStd::move(callback); + m_manager->SpawnEntities(*m_ticket, AZStd::move(indices), AZStd::move(optionalArgs)); + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + + EXPECT_EQ(NumEntities, spawnedEntitiesCount); + } + + TEST_F(SpawnableEntitiesManagerTest, SpawnEntities_SpawnTheSameEntity_AllEntitiesSpawned) + { + static constexpr size_t NumEntities = 1; + FillSpawnable(NumEntities); + + AZStd::vector indices = { 0, 0 }; + + size_t spawnedEntitiesCount = 0; + auto callback = + [&spawnedEntitiesCount](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + { + spawnedEntitiesCount += entities.size(); + }; + AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + optionalArgs.m_completionCallback = AZStd::move(callback); + m_manager->SpawnEntities(*m_ticket, AZStd::move(indices), AZStd::move(optionalArgs)); + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + + EXPECT_EQ(NumEntities * 2, spawnedEntitiesCount); + } + + TEST_F(SpawnableEntitiesManagerTest, SpawnEntities_MultipleSpawns_AllEntitiesSpawned) + { + static constexpr size_t NumEntities = 4; + FillSpawnable(NumEntities); + + AZStd::vector indices = { 0, 2, 3, 1 }; + + size_t spawnedEntitiesCount = 0; + auto callback = + [&spawnedEntitiesCount](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + { + spawnedEntitiesCount += entities.size(); + }; + AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + optionalArgs.m_completionCallback = AZStd::move(callback); + m_manager->SpawnEntities(*m_ticket, indices, optionalArgs); + m_manager->SpawnEntities(*m_ticket, AZStd::move(indices), AZStd::move(optionalArgs)); + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + + EXPECT_EQ(NumEntities * 2, spawnedEntitiesCount); + } + + TEST_F(SpawnableEntitiesManagerTest, SpawnEntities_ReferencesAreRemappedForNewBatch_AllPointToLatestParent) + { + static constexpr size_t NumEntities = 4; + FillSpawnable(NumEntities); + CreateSingleParent(); + + AZStd::vector indices = { 0, 1, 2, 3 }; + AZStd::vector parents; + + auto callback = [&parents](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + { + AZ::EntityId parent = (*entities.begin())->GetId(); + parents.push_back(parent); + auto it = entities.begin(); + ++it; // Skip the first as that is the parent. + for (; it != entities.end(); ++it) + { + AZ::TransformInterface* transform = (*it)->GetTransform(); + ASSERT_NE(nullptr, transform); + ASSERT_EQ(parent, transform->GetParentId()); + } + }; + AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + optionalArgs.m_completionCallback = AZStd::move(callback); + optionalArgs.m_referencePreviouslySpawnedEntities = false; + m_manager->SpawnEntities(*m_ticket, indices, optionalArgs); + m_manager->SpawnEntities(*m_ticket, AZStd::move(indices), AZStd::move(optionalArgs)); + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + + EXPECT_NE(parents[0], parents[1]); + } + + TEST_F(SpawnableEntitiesManagerTest, SpawnEntities_ReferencesAreRemappedForContinuedBatch_AllPointToLatestParent) + { + static constexpr size_t NumEntities = 4; + FillSpawnable(NumEntities); + CreateSingleParent(); + + AZStd::vector indices = { 0, 1, 2, 3 }; + AZStd::vector parents; + + auto callback = + [&parents](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + { + AZ::EntityId parent = (*entities.begin())->GetId(); + parents.push_back(parent); + auto it = entities.begin(); + ++it; // Skip the first as that is the parent. + for (; it!=entities.end(); ++it) + { + AZ::TransformInterface* transform = (*it)->GetTransform(); + ASSERT_NE(nullptr, transform); + ASSERT_EQ(parent, transform->GetParentId()); + } + }; + AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + optionalArgs.m_completionCallback = AZStd::move(callback); + optionalArgs.m_referencePreviouslySpawnedEntities = true; + m_manager->SpawnEntities(*m_ticket, indices, optionalArgs); + m_manager->SpawnEntities(*m_ticket, AZStd::move(indices), AZStd::move(optionalArgs)); + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + + EXPECT_NE(parents[0], parents[1]); + } + + TEST_F(SpawnableEntitiesManagerTest, SpawnEntities_ReferencesAreRemappedAcrossBatches_AllPointToLatestParent) + { + FillSpawnable(4); + CreateSingleParent(); + + // Spawn a regular batch but with two parents and store the id of the last entity. This will the parent for the next batch. + AZ::EntityId parent; + auto getParent = [&parent](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + { + ASSERT_NE(entities.begin(), entities.end()); + parent = (*AZStd::prev(entities.end()))->GetId(); + }; + + AzFramework::SpawnEntitiesOptionalArgs optionalArgsFirstBatch; + optionalArgsFirstBatch.m_completionCallback = AZStd::move(getParent); + optionalArgsFirstBatch.m_referencePreviouslySpawnedEntities = true; + m_manager->SpawnEntities(*m_ticket, {0, 1, 2, 3, 0}, AZStd::move(optionalArgsFirstBatch)); + + // Next, spawn all the entities that have a reference to the parent that was just stored. + auto parentCheck = [&parent](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + { + for (auto& it : entities) + { + AZ::TransformInterface* transform = it->GetTransform(); + ASSERT_NE(nullptr, transform); + ASSERT_EQ(parent, transform->GetParentId()); + } + }; + AzFramework::SpawnEntitiesOptionalArgs optionalArgsSecondBatch; + optionalArgsSecondBatch.m_completionCallback = AZStd::move(parentCheck); + optionalArgsSecondBatch.m_referencePreviouslySpawnedEntities = true; + m_manager->SpawnEntities(*m_ticket, {1, 2, 3}, AZStd::move(optionalArgsSecondBatch)); + + m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + TEST_F(SpawnableEntitiesManagerTest, SpawnEntities_DeleteTicketBeforeCall_NoCrash) { { @@ -186,7 +418,7 @@ namespace UnitTest }; m_manager->SpawnAllEntities(*m_ticket); - m_manager->ListEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); + m_manager->ListEntities(*m_ticket, AZStd::move(callback)); m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); EXPECT_TRUE(allValidEntityIds); @@ -199,7 +431,7 @@ namespace UnitTest { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->ListEntities(ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); + m_manager->ListEntities(ticket, AZStd::move(callback)); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -231,7 +463,7 @@ namespace UnitTest }; m_manager->SpawnAllEntities(*m_ticket); - m_manager->ListIndicesAndEntities(*m_ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); + m_manager->ListIndicesAndEntities(*m_ticket, AZStd::move(callback)); m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); EXPECT_TRUE(allValidEntityIds); @@ -244,7 +476,7 @@ namespace UnitTest { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->ListIndicesAndEntities(ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); + m_manager->ListIndicesAndEntities(ticket, AZStd::move(callback)); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -260,7 +492,7 @@ namespace UnitTest { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->ClaimEntities(ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); + m_manager->ClaimEntities(ticket, AZStd::move(callback)); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -276,7 +508,7 @@ namespace UnitTest { AzFramework::EntitySpawnTicket ticket(*m_spawnableAsset); - m_manager->Barrier(ticket, AzFramework::SpawnablePriority_Default, AZStd::move(callback)); + m_manager->Barrier(ticket, AZStd::move(callback)); } m_manager->ProcessQueue(AzFramework::SpawnableEntitiesManager::CommandQueuePriority::Regular); } @@ -307,12 +539,12 @@ namespace UnitTest defaultPriorityCallId = callCounter++; }; - AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + AzFramework::SpawnAllEntitiesOptionalArgs optionalArgs; optionalArgs.m_completionCallback = AZStd::move(defaultCallback); optionalArgs.m_priority = AzFramework::SpawnablePriority_Default; m_manager->SpawnAllEntities(*m_ticket, AZStd::move(optionalArgs)); - AzFramework::SpawnEntitiesOptionalArgs highPriortyOptionalArgs; + AzFramework::SpawnAllEntitiesOptionalArgs highPriortyOptionalArgs; highPriortyOptionalArgs.m_completionCallback = AZStd::move(highCallback); highPriortyOptionalArgs.m_priority = AzFramework::SpawnablePriority_High; m_manager->SpawnAllEntities(highPriorityTicket, AZStd::move(highPriortyOptionalArgs)); @@ -343,12 +575,12 @@ namespace UnitTest defaultPriorityCallId = callCounter++; }; - AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + AzFramework::SpawnAllEntitiesOptionalArgs optionalArgs; optionalArgs.m_completionCallback = AZStd::move(defaultCallback); optionalArgs.m_priority = AzFramework::SpawnablePriority_Default; m_manager->SpawnAllEntities(*m_ticket, AZStd::move(optionalArgs)); - AzFramework::SpawnEntitiesOptionalArgs highPriortyOptionalArgs; + AzFramework::SpawnAllEntitiesOptionalArgs highPriortyOptionalArgs; highPriortyOptionalArgs.m_completionCallback = AZStd::move(highCallback); highPriortyOptionalArgs.m_priority = AzFramework::SpawnablePriority_High; m_manager->SpawnAllEntities(*m_ticket, AZStd::move(highPriortyOptionalArgs)); diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetBindMarkerComponent.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetBindMarkerComponent.cpp index c93c09cfbc..bd1cf40da8 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetBindMarkerComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetBindMarkerComponent.cpp @@ -81,8 +81,10 @@ namespace Multiplayer }; m_netSpawnTicket = AzFramework::EntitySpawnTicket(m_networkSpawnableAsset); + AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + optionalArgs.m_preInsertionCallback = AZStd::move(preInsertionCallback); AzFramework::SpawnableEntitiesInterface::Get()->SpawnEntities( - m_netSpawnTicket, AzFramework::SpawnablePriority_Default, { m_netEntityIndex }, preInsertionCallback); + m_netSpawnTicket, { m_netEntityIndex }, AZStd::move(optionalArgs)); } } @@ -90,7 +92,7 @@ namespace Multiplayer { if(m_netSpawnTicket.IsValid()) { - AzFramework::SpawnableEntitiesInterface::Get()->DespawnAllEntities(m_netSpawnTicket, AzFramework::SpawnablePriority_Default); + AzFramework::SpawnableEntitiesInterface::Get()->DespawnAllEntities(m_netSpawnTicket); } } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index 39afa46a19..a7875c2615 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -134,7 +134,7 @@ namespace ScriptCanvas::Nodeables::Spawning m_spawnBatchSizes.push_back(view.size()); }; - AzFramework::SpawnEntitiesOptionalArgs optionalArgs; + AzFramework::SpawnAllEntitiesOptionalArgs optionalArgs; optionalArgs.m_preInsertionCallback = AZStd::move(preSpawnCB); optionalArgs.m_completionCallback = AZStd::move(spawnCompleteCB); AzFramework::SpawnableEntitiesInterface::Get()->SpawnAllEntities(m_spawnTicket, AZStd::move(optionalArgs)); From ba02652e6377a022b7588a1c2f59d38063a0646a Mon Sep 17 00:00:00 2001 From: Vincent Liu <5900509+onecent1101@users.noreply.github.com> Date: Thu, 3 Jun 2021 10:59:11 -0700 Subject: [PATCH 473/811] [LYN-4200] Fail and log error if required aws config file is not found (#1099) --- .../manager/configuration_manager.py | 7 +- .../resource_mapping_tool.py | 11 +- .../style/editormainwindow_resources.py | 2362 +++++++++-------- .../ResourceMappingTool/utils/aws_utils.py | 13 +- 4 files changed, 1261 insertions(+), 1132 deletions(-) diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/manager/configuration_manager.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/manager/configuration_manager.py index b679921196..fc188582c7 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/manager/configuration_manager.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/manager/configuration_manager.py @@ -48,7 +48,8 @@ class ConfigurationManager(object): def configuration(self, new_configuration: ConfigurationManager) -> None: self._configuration = new_configuration - def setup(self, config_path: str) -> None: + def setup(self, config_path: str) -> bool: + result: bool = True logger.info("Setting up default configuration ...") try: normalized_config_path: str = file_utils.normalize_file_path(config_path); @@ -63,5 +64,7 @@ class ConfigurationManager(object): self._configuration.account_id = aws_utils.get_default_account_id() self._configuration.region = aws_utils.get_default_region() except (RuntimeError, FileNotFoundError) as e: - logger.exception(e) + logger.error(e) + result = False logger.debug(self._configuration) + return result diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py index e99bf5d441..6a56491b24 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py @@ -74,11 +74,18 @@ if __name__ == "__main__": logger.warning("Failed to load style sheet for resource mapping tool") logger.info("Initializing boto3 default session ...") - aws_utils.setup_default_session(arguments.profile) + try: + aws_utils.setup_default_session(arguments.profile) + except RuntimeError as error: + logger.error(error) + environment_utils.cleanup_qt_environment() + exit(-1) logger.info("Initializing configuration manager ...") configuration_manager: ConfigurationManager = ConfigurationManager() - configuration_manager.setup(arguments.config_path) + if not configuration_manager.setup(arguments.config_path): + environment_utils.cleanup_qt_environment() + exit(-1) logger.info("Initializing thread manager ...") thread_manager: ThreadManager = ThreadManager() diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/style/editormainwindow_resources.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/style/editormainwindow_resources.py index fb819cac34..67181fa36d 100644 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/style/editormainwindow_resources.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/style/editormainwindow_resources.py @@ -3649,968 +3649,1082 @@ PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\ Z\x80d\xdf%\x00\x7f\x12T\x1b\x97qJ\x10\x92\xa7\ \x22:BG\x84z\xfa\x9d{\x88\xac\x1d\xf5-\x8f\xc3\ r\xe1\x95\x00\x00\x00\x00IEND\xaeB`\x82\ -\x00\x00;\xfb\ +\x00\x00C\x13\ \x00\ -\x01\xa2\x08x\x9c\xed]\x09\x5cL\xdf\x17\x7f-\xb4 \ -\xc9\xde\xa2\xc5RD%\x7f\x89HB\x96(;E\x14\ -\xd1\x0fQ\xb4\x92(B\xd6V*d/E*[Q\ -hAE\x08\xadZ\x94\x92\xd4\xb4\xafS\xcd\xf4\xfe\xf7\ -\xbey\xed\x13M\xcd\xd4\xc4\xdc\xcf\xe7+\xaff\xde;\ -\xf7\x9e\xfb\xce=\xf7l\x17A\xd8\x90\xfe\x08ll\x88\ -\x18rI\x18Av\x80\xff\xdb\xd8P\xae\xa5\xb8\xd9\x10\ -D\x04ATT\xf0kU\x04\x91\x1a\xcf\x86\xc8\xc9Q\ -\xae}\xc6#\xc8\x0a\x03\xf0?1\xfc\x9a\x1fA\x88g\ -\xd9\x10~~\xca\xf5\x7f\x9c\x08r\xdd\x93\x0d9\xb5B\ -c\xd1 ^A^p\xebAK\x16/X\x05\xff\x0a\ -\xc1\x0d\x1f\xbdi\xbf\x0fx\xa6\xb0\xde\x92\x05\xf3\xd6X\ -\xa6\x16e\x1c\xb8\xe2\x9a\xe8YR\xa69E\xe7E\xc0\ -\x0a[\xb5\xc9*Zk9\xfb\xb1\x9f\x97\xf2\xd9\xf6\xfa\ -\xbf\xb3[\xcfN\x10/\x1eU5)w\x94\xe4\x0c\x0f\ -\xb9%\x13.]~\x9b%\xad]p\xc1naN\x22\ -\xff\xca[Q*\xe3.}\x9e\xa72o\xdeW\xd7\xbd\ -*\xb6\xec;\x9f\x5c\xcf\xb7\xf6\xf5\xcfmX\x99\xb8A\ -\xc5(qm\xdeL\xcd\xc4\x0a\xab\xb0\xcd\xa4\xb1\xab\xcc\ -\xae\xde)8D0\x8c\x9b\xa90\xf9u\xce\xa0\x1f\x1c\ -96\xabm\x87\x84\x1bg\xe9\xeb\xaaD\x8a\x8e\x5c\xe1\ -\x17\xea\xa7zJM\x8c[X\x83\xf8H4e@!\ -\x9br\x7fs\xa2u\xf1\xba\x8c~\xd3O/\xb7`[\ -Sf\xc9\xf1,|\x9c\xee,\xb9\xd1\xee\xc8Y\xce\xc2\ -\x90\xd8\x09\xcb\xa6\xb0\x17\xf6\x0fB\x84l\x9f\x84O\x08\ -\x8b\xcb\xf0\x0f\xd5\x9d\xa4\xbf\x1c\xb1|\xce&\xf4`\xe9\ -\xe1\x89r\x03\xdcy\x7f\x14\xc8\xb8\xc5\xf0\x16\x85\xf7\xd7\ -\x1d^:)\xf0M\x89\xc9\x22\xb3\x91\x93D\xe4g!\ -\xb3\xbf\xd9\x88(\x8e|:\xc2}\xd0\x9a\x02\x19\x97@\ -;\xc1\xac\x85\xba3\x03?\x82\x0f\x98\x8e\xf4\x09\x93\x97\ -\x07\x1f\x08\xff/k\x9d.\xdf\xaa\xfc\xe3\x9b\xa7\x87O\ -\x0b\x17\x08\x8b{\xb1\xdaB\xcf\xf9\xc2T\xb6\xac\xb2\xfe\ -W\xc2\x13\xc3E\xc2\x07f\xe4\x0e\xb99\xe0\x9e\xed\xf1\ -\xf0kde\x8b\xc5\x16zu\x91\x95\xf0\xaf\xa7m\x9e\ -\xd9\x8c\x1c\xe5\x1d:[\xb52B9\x9ckru}\ -\xfa\xf2\x90\x01\xf1C\xe3\xfb\xab<\xcf\xce\xecG\x92^\ -q\x03\xfem\xfe\x94@\xc4\xf2\xbd\xdf<\xdd\x10\xa4\xd4\ -\x92Cf\xeb\x07Rm\xb8\x0a\xb8\xa5\xc4 >\xb6\xc1\ -\xc8\x00p\xcb\x15\x16z\x02\x1e\x93 -\xb9\xe1F\xb6\ -+Cb%\xec\xd8Cm\xac\xc8\xca5\xbc\x19\xfd\xf2\ -\xf5O\xc3\xef\x8d\xb5\x89>\xf5!s\x80S\xd1:6\ -\x8b:\xeb\xe29!\x03nN\x87\xdd\xe3p_\xe4w\ -`\xcd\xf5\xfa\x1d\xdcz\xd7Gl\xcdH_DR\xb6\ -\xd8\xb0^\xfcq?\x9bh!\xc5\x0b)\xa4\xfc\xff\xe9\ -l\xe7\x8f\xe4L\xe20!)\xd7D\xcf\xfa\xb6)6\ -\xc4\xd2a\x86\xf1\xd8\xc0\xd1\xbe$\xd5e\x1c\x0a\xd1\x04\ -\xbb\xef\x03\xf7\xb0Y>\xb7U\xd5\x1dR\xaa#2R\ -\xda\xee\xed\x14\x8e\xbd\x15\xf5\xe9\x1f\xd4^\xdc\xd0\x83\xfd\ -T\x13\xd88w\xce7\x9f\x9aa\x12\x1c{8v\xd4\ -[\x17g\xa8=\xf7\x10\xd7A\xc0m\xa6\x96\x8eYU\ -{\xfc\xd7\x07\xcb\xac\x17\x96\x9e+5\x0e\x00\xae\xd8^\ -\xb6\xbd\xa0\xe21d\xe4\xb8\x05#\xa48\xd6E\x11\xce\ -\xafZ\xca\x11\x9e3\x88\xc4\x158,f\xa5\xb5\xb8\xaa\ -\xbe\x87\xb0\xaeo\xb4\x10\xd1\xeb\xdd\x8c\x95\xf2\xfd\xf93\ -\xaf\xe4\xe8m5!\xa9\xda'\xccfO\xbf\xb5u\xa8\ -\xf3c.\x95C\xfb\xe2J\xec\xe7\x04\xc8\xda-v\x18\ -\x1f^\x94\xbf\xf9\x7f\xaeI\x88=Z.\xab:)\x8c\ -\x7f\xd2dq\x85\xe5\xeeA\x17UB\xa2\x911j\xe0\ -\x17w\xd3\x97\xfa\x9d\xf7Z\x9e\xca.\xa6\xbcA\xdc\xfa\ -\xb0x\xc2%\xb7\x8f\xb6\x11\x8fM\xd9\xb2\xe3\x87\xab?\ -\xc9\x10\x10\xf7\xcb\x1b\x11\x16G^pW\xd6y?\xf2\ -z\xe4d\xbf\x05\xdeuvr\xab\xb8\x8c=2\xf3\x0e\ -\xcf\xb90r\xc9D$;\xd6*s\xfe\x88Z\xee\x1b\ -\xf3E\xe4\xc6_\xd8\xfe\x8a<\x86\xc3~nJ\x85\x04\ -\xe8\xda'\xaf\x81\x96S7\x8f\xac\x1f\x7fa^\xf8\xc2\ -\x98\xd4\xc3\xe2\xa6B\x9a~2\xd5\xeaa\xecb\x0d\x85\ -\x0fg\x7f\x91\xb6\x9by(8\xac\x9eg\xdc\x1c\xd0\x95\ -\xb7\x06\xd3V\xdc\xae\xbf{\x9c\x7f\xd1t\xb6\xa1.\x19\ -ZR\xbe#T\x0ey\x94L[\x9c;2\xd2\xf0\xb4\ -\x8dA\xb6\xd9\xe38\xe7\x22\xf6\xf7\xf3\x83\xca\x04\x22\xfd\ -\xbc\x9d~l}\xael\xc1\x96\xbd\xd1\xc2h\x91y\xc9\ -\xf0\xc8\xf7\xda6\xd3\xeaBr-\xe5\xa7\xd8D;\xbd\ -\x93\xb5\xfb:\x9c\xff\xde=\xeb/w\x10\xfbk)c\ -O\x9as;\x8d\xde\xf1\x86`\x18p\xb0\x88\xfdu\x5c\ -A\xday\xe1\xe4\xf1\x0b&|]\xe8'\xfd)G\xcb\ -\xcez'[\xba\xed\x9a\xc3\xe2\xf2\x1f\xa4\xb6\x9a\x05/\ -\x9a\x13\x84d/2-\x99\xa7\x91?\x5cb\xa8\x08\xbb\ -Z\xa5\xe9\xff\x0e\x18M\xb1\x09u|'\xbb\xc0[p\ -\xb1\x1f\x9f\xc5\xbd\xb4\x11*\xa4\xe4#\xa2+n\xd4O\ -\xb2\xe3'\x9bs\x96\x9a&\xf3\xfe\xf2\xed'7\x12\xcc\ -\x0b\xfd\x90\xfd[\xcd\x9e\xa9\xeb\x04\xc1\x196\x948\xaa\ -\xf4\x97\xcc\x0b~\x89\xed\x87\xb3\xd6\x84\xc5\x89\xccj\x90\ -\x0d\xd9\xcd\xb6\xe9\x1cx\xda\xc3\xe3'7x*\xcf\xb3\ -`\xfbD\xa8\xb4\xe5\x97\xb8e\xaauG\xf3\x17;\x98\ -\x03SU.\x14\x7f\xe1\x15\xff\xb2\xd7/3\xcf_\x83\ -4X\xe7\x09\xb2\xf7\xb3\xceRq;\x01\xc9\x84\xa2m\ -\xda\xc8\x18\xa3p>ad\x92\x99\xdb\x1an'\xf3\xe9\ -\xe1+\xc0m\xf3I\x83\xa3\x83\x91\x8f\x0b\x01K\xbf\xde\ -u\xde 2\xb7\x80\x88<\xd5\xb0\xe09\xce\xbfTd\ -u\xb4\x839[6\x97\xd5\xe1\xd3\x8f\x11\xbb\x98\x1d\xd3\ -\xc3\x97xr\x9d\x9d\x10\x84L\x10\xbb\xb0\xc5\xdep\xfd\ -\x12?\x7f\x8e\xace\xc43\xeafn~\xd2^\xfd\x14\ -\x9e\xbb\x8d\x0b\x1b\xf2\xd9h\xdd\xe3O\xdf\x9c\x82V\xbb\ -\x1e\x8f\x99\xe0&\x90\xf6\xb5\xde\x1d\x91\xcb=?w\xe1\ -\x01\x85\xbd\x1eN\xd7*\xc3\xac~%\x8eHU2u\ -\xdb\xcc\xbd\xfaR?\x92`6\x9c\xd0\x8e\x03\x96%\xea\ -L\x12\xb7\x13\xf7\x8e\x22\x90>O\xb5Y\xa2\xe2_\xbc\ -\x8aG|\xa0\x93\xba\xdfG\xd1A6\xf9!\xea\xe3\xec\ -\xe4\x12L\x89\xf2\xc8\x04\x82\xcc9\xfe\xc8\x15.\xdfc\ -\x11w\xc7\xc8\x01<\xe2\xf2q\x9cHh\xb4\x90\x14\xa2\ -V\x80\xfde\xec\x9co*\xb6\x22\xa3\xd4\xe7:\xf0\x8c\ -T\xd5\x9f\xac$\x97t\x8aT\xb71\xcaq\xbf\x92\xe4\ -\x05%\x9f\xc9\x8f\xa6=}\xff1k\x95\xd2\xb1\xa5\x85\ -?\x14\xf7\x0c\xcb\xfbj\x9crCQ6h\xd6la\ -\xdb\x9f\xd5R\xdf\xb9\x85w\x9e_\x91&\xec\xe5?3\ -\xd2\xa0j\x08\xe9\xe4+a\x9fs\x81a\x0a\xcb\xa4\xfc\ -\xea\xef.\xe0U\x9be\xfb=D]\xfc\x8b\x91\xa1\x97\ -\xcb\xa3E\x8a\xa3g\xbc~\x9b\x22\xce\x17\xb5n\xd6\xc4\ -\xb7%\x15Z\x81\xd6\x02\xbc\xaf\xa2\xb7\xd8\xf9\xce\x1a\x95\ -}\xeb\x98\xb8B\x11\xcf\x837\xa2\x12\xa3\x9c\x87\xbb\x8f\ -\xde\xfat\xe8\xa8\x1b\xa1\xc3$\xcc8\xce\x14\x1d\xb2>\ -z\xc6D-W\xae*A\xb8\xff0\xdf\x92\xc4\x99\x22\ -r\xde_\x22\xdc\x97re^\x19\xb6Q\xed\xcb\x90\x13\ -{\xea\xe7\xfb\xf9\xf2\x95\xff\xf6{\ -\x83\xd1\xf0|\x99\xfe3\xf9\x14\xad\x9e\xba<:\xa9T\ -\xb6yU\xb8\xd3O\xa9\x80=\xbb\x0dr\x7f\x8a\x11\xcc\ -\xfb\xf3,\x5cud\xb0\x93\xc2|\xcfp$\xc3\xeb\xd7\ -\x12u+\xd7\xbc\xcc=\xeau\x99f\x95\xb7\x8cBH\ -\xfe\xab\xbc\xcf\xbd\xffl~\xdf\xc4M\xa145H\xb7\ -@V_\x22\xf7\xb8\x82\xbf\xe7\xc5\xe8'\xf1\xe5>\xbb\ -O\x95\x97G)\x5c|\x11\xaffvn\xe0\x18\xf7p\ -$\x9e\x0b\xde\xbcf\xca\xee\xa5\xe4\xe3v\xe6\xdb\xfb)\ -\xec\x9d=\xf7\x9aP\x5c\x9c\xc1\xa3\xb9\xaf]\xeem\xd4\ -*\x9b\x17\xfa\x98\xb7r\xb4n\xf4\x0f6\xb1\x87\xf1\x0b\ -\x1c\x86f\xd6\x9c\xd1\xaax\xc4\xbb7T\xee\x1a\xfb\xfa\ -\x83\x5cR\x0b\xaf\x0d\x0c\xe4\x90\xc9\xf0\xe2O\x9a~\xfb\ -\xfdG\xcd\x00)\xfd\x8c\xb8\xd8\xda\x88\xe3\xb5?~.\ -\xe6\x1f\x15\xb3\x9d\xeb\xb4\x99\x9b\xaa\xfdiU%\xd4|\ -\xa1\xf8n\xf4\xc5\x95\xddwr\xf5\x5c\x84\xe5T\x1f\xf8\ -!\xc3\xbc\xcb/\x08(\xa1f:C\xa4\x0fo\x88\xfa\ -1\xa4\xae\xbf\xfe}Uv\x15\xf7/\xa3\xe7{>\x97\ -\x0bpE\x9f\x07\xfd\xfaU\xb0\xc0\xe9\xb0\x00\x12\xf9\xd8\ -P\x81\xf8q\xe6\x01R\x8ed.\xa9\x22_~\x8d\xd7\ -QN\x1b\xb9\x17\x11^\xe6\x17?N\xf9\xbe>y\x98\ -\x93\xe41\xbb\x9d\xe3\xd9\xc4\xe4\xa3\xae\x98Tl8\xb0\ -e\xf4\xb6I\x22!g\x9c\xa7\x8fC\x16\xa8\x8d\x9e\x19\ -\x13\x11\x8b\xae\x8a\xca5x;\xe2b\xbe\x18\xf8\x90\x86\ -ml\xd4\xb6\xe4\x91\x15\xf1\xd2\xbc\x0f\xd4\x1d\xc4\xc6\x0b\ - \x12c\xbf\x1a\x1a\xa7\x1d\xaf\x9d\xfc\xdcwAT\xbf\ -U\xf0C\xa9~\xd3t&\x87>\xb2;\xadZ;\xa9\ -\xe6d\xfat\xa7\xb2\x09\xe7b\xbekZ\x5c\x90\xf3Y\ -\xf3\xf2\xe3[g\xa5\x09\x0f#S\x96J\xc6e\xe8\xbc\ -\xd3\xe5\xb1\xbd\x1d\x93!\xa0\xb5\x8d\xa8\xc2\x15;\x9e\xd3\ -Y\xc2b\xa9\xfe\x85\xef\x1c\x22\xb3\xad\x17\xf9\x9e\xe5\xa9\ -tJ\x1f\xefd\xa66\xd8\xbc\xf4\xa4\xa8k\xcc\x18\x0e\ -\xeb\xace\xe4\xf1\xabf\xecw<&lP\xa7\xec\xb7\ -x\xdc\xa4\x8d\x1aU\xd7\x83fF\x16\xc7\xbd*\x1cd\ -W[\xb9\xd8Ne\xbe\xdd\xab\xe5CR\xe7\x7f\x12<\ -[\x94\xb5\xf3\xd1\x9b n\xd9\xb7\xc1+W\xea\x1b,\ -\xf6\xf0\xbc1\x9cOm\x90y\xd6\xe8,92\xa9\x9e\ -\xd3\xc1%z\xaf\xd4\xcf\xa4\xf1\x83\x1eN\xdc9x\xd9\ -\x10D\x93|\xdd\xee\xc6\xf0\xfc\x8d\xdf\xbe~\x12\xdcN\ -\xd2\xe4#\xbc\x9c\x1c\xef\xe3\xcf\xf3h\xaf\x81\xe3 Q\ -\x8b\xc0D\xd1l]\x9d]V\xc6\xb9\xa1\x86gE\x0b\ -\xf4\xbfpK\xe6\x9d7/K\x5c}\xc5;=&\xe7\ -f\xbc\xce\xfb\xb0\x87\x8e[^&\xf8\x85Jyo?\ -\x8d\xf0\xe7\x07\xef\xd4\xe4\x92V\xe0\xd2z\xe25'\x97\ -\xf7\xc8\xf3$]W\x8b\xb9\xf9Y\x19\x9a\xb36\x103\ -\xef\xff\xf8\x99\xf2Tw\x13\x9f\xdb\xf2\xf7\xb9\xd9\xd36\ -\xfd\xb8\xec\x93o\x1d{\xf6\xd0]\xbe\x13\x07\xf6\xce/\ -\x17\x8a\xd5\xb6\xe5T\x19\xe1kt\xaa\xbc\xb0N\xa1\xa1\ -RC\xc8\x8a=\xca\xcc6U\xe9\xa6_\xaa\xa0~b\ -\x92\xd8\xf1g\x0a\xfeW\x5cc\x07\xe5\xe5^\xfey\xc3\ -\xb3>lmL\x10\x87\xb8\xf9!\xc1/:\xc3\xe2\x9d\ -\x90\x18\x81\xddw\x95\xdc\xeb\xce\xa4\xde\xb2\xb6\xd4\xb9\x94\ -v\x8bTV\xa4\xd0@4\x17\x9a\x16\x15R\xba\xd99\ -n\xdc\x07\xa5\xfa\x1f\xb9)D\xf2\xf27\x87\xc8\x11\xb3\ -.\xa5\xea\xab\x889\xbdg\xd7?\x15G\x18\x9b*\x8d\ -\x96\xad[\xdf\xcf\xa3\xe8^\x9e\x95C\xf2\xa3\x9c\xeb\xdf\ -\xb6d\xeaq\x88\xa4\x1fy\xd2pl\xf5{5v\x15\ -\xa9`s\x03.7\x19\x9f\x9c;q3>\x7f\xba+\ -{{\x87\xe6\xdb\xdc\x87\xa7\xcaG\xed\x93\xe0A\xf4\xec\ -\xff\x1bvU+9\xaa\x1f\x9ag\x9f\x14\xefp\xd8l\ -\xb9\x93x\xde\x84\x1d\xbc\xcf\x86F\xae8)8\xf6\xbd\ -Nj\xb8\xc3\xd5=_\xbel\x9f(\xfb\xb8\xac\xe2\x1e\ -\xafYf\xffxG\x84_{\xf2\x96\xcc\xa8\x19\xa2w\ -\xa7\x99\x06\xdd\x8c\x9f!\x99+o\xfd\xd8p&\x9f\x00\ -\xa2z\xab\xe0\x92\xdczR\xd0\xf9`\x0b\xb3Q\x0d\xdf\ -j\xb6\xac\xb6[\xfd\x92\x0c~\x1fp\x22I*\x13\xd5\ -\x99#k\xb4kF\xa5\xb5\xe6>%\xf7is\xb6\xd4\ -\xe4\xee\x96d\x13{<\xe0xD\xbd\xe9X\xcd\x80i\ -\xe6O\xbe\xcdq\x1b\xb6\xa1\xe1\xd3\x10-n\xd7,\xef\ -\x85\x83\x14\xff\xa7v\xf3\xeb\xcf\xb2s\x0ahm\xca\xd4\ -\xd2\xcc\xb93\xe2\x1ck\xa4\x01!\xc7\x06T\x1c(5\ -\x9a\x12\x22\xab#\xc4c\xc39eD\x80\xcd\x0e9\xb4\ -v\xc2\xe9\x8a\xad\xb1\xa7\xce\x19\xbf:PKj8\xb7\ -NpJ\x88\xea\x8a\x10$\xd2\xf4\xf0S\xbf\xcf\x81\xb6\ -\x11\xce\x87\x84\x82\xdf?.\xde`\x03\xde%\xcf\x15\xa3\ -\xf6\x1ey\xc8\x86\xeam\xf3\xe66\x9a-\x9b\xf9p\xe3\ -\x19u\x84{\xf5]\xa3S\xf2\x16Kn\x89\xe7`b\ -\xe4\x92\xe1\x87\xf1\x91\xf0m\xbc\xbbK5\x1d}8\xf5\ -\xf2\x81\xf4\xd9\xaf.e `\xd4v\x1d9\x14\xfa\xc1\ -\xd1\x80\x0bLs9\xad\x8am\xb1\xb3\x16#\xdc\xf1\x97\ -\xd1\xa3S5\x87l\x9e\x96x0\x03Y\xbd\x8cC&\ -\xf3\x93\x86\xd6\xbc\xba\xfez\xa9g\xb7hM\x1aV\xf7\ -\x5c9\xf2\xc8\xfd\xff~\xda\xeeNP\x8eC\xcf=\xda\ -_\xfb\xe6\xcc\x87\x8b\xda\x0ez\x15\x96\x1cI\xcf\xb4\x9d\ -\x1e\x08\x9b\xc379\xe7\x84\x0f\xf9CH\xc5\xe0s~\ -\xe9\x86\x85\x0f\xf5=o\x0f\x10\x93WUd\x0f;\xbc\ -\x90|\xfa\x85\x96A\x88\xe9\x96\xbb7\xc0k\x1e\xb5A\ -g\xf8\x8f\x0c\xcd\x84\xea\x12\x99Y\x19\x0b\xcf\xcf\xac\x96\ -\x9fn\xc7i\x13#\xe5\xf0\x22\xe9ne\xd5\x00\x93=\ -\xcb\x84vz~\x05\xa4:\xad\x04\x93\xe3\x82\x91\xdc\xc1\ -\x86Q\x04S\x0e\xf8\xcd\x03\xbb\xce\xa5F\x9f\xb8\xe3\xf0\ -@c@\xf8\xb0x\x9b\x1d\xe5\xaf\xd3\x05xM\x12\xfd\ -\x068\xa8}\x0f\x92\x14|\x5c|\xf6\xf2\xa0\xcd\x07\xc2\ -<\x8f\x84=\x5c\xf15\xef\x7f{\xed]\x9c\x0f]\x1e\ -\xaf,\x09Fz\xfe\xbb\xa2M\xa6!!?3\xa3\xe6\ -\x88\x5c$\xae\xf2MJ\x1f\x93[\xb2\xf1\xd8\xfb\xab7\ -w|?\xff\xa1\xbf\xc1\xa0X=\xb3\x0b/3\xce\x9c\ -\x93\xd0\xb1\xe1\x1c:g\xd7\xe5\xc3\x01\xcf\x8d\xde\xe6f\xa2\x16;\ -_\xa6\xefX\xfb\x8e7\xb1\x9f\xcdps#g\xa3\x1d\ -\x9b\xceD\x0e\xda\xf1n\xb8\x8c\xfc\xc3\x10[\xded\xa3\ -\xffI\x93V\xca\x0d\xe0\xb1yz\xf0\xb8I\xd5\xfc\xd8\ -\xed\xa7\xe7]\x10\xcf}h#=\x5c\x00\xd9w-Q\ -z 2`\xf6\xba\xbbg\x0clB\x8c\xef\xef\xb98\ -\xc2f{\x82T\xba\xff\xeeJ\xdd\xdd\x85\xb2w^\xf9\ -D\x14\xb0\xab\xe4:\x1c\xd5\x02\x14\xf8\x92\x02\xd5\x07\x18\ -\xae\xd1\xce\xfa\xbc\xeaV\xae\xa2\xee\x0f1\xb3\xef\x07\xc3\ -\xd95\xf7\xbd\x0b\x96\xd7\xc8\xdd\xe6\x85\x18h\xeb\xbbi\ -\x8d\xf5<\xec\xbc:\x7f\xde\xd5\xc3<\x08\xe1?\xc33\ -\x93\xf6\xf4[6Z\xcf3\xc7\xfb\xac|\xed0\xb3\x9a\ -\xff\x09\x83\xd71\x9f}\xc3;\x99\xe3J5\xa4x)\ -\x1e\x1b\xd3\xcb\xca\xda\x19s2,\x14\xfdL\xf7\xb9\x83\ -\xa7\x8c\xf3\xf1_\x19\x1c\x96\xbeSr\xe6\x85\xbdJ;\ -\xa6?\x9b\xb9\xcb\xa1\xcc\x7f\xd5!\xf6\x07Z13\xe4\ -#N^\xbb[\xffi\x8f\xc2S\xfd\xe7f\xe7=\xd7\ -\x15=\xff\xcb\xc9\xb1\x13\xee\xce|\xff\xe5\xb4\xcc\ -\x5c\xf5\xa2\x17\xe9O\xd7gxp\xec\x90`s\xd4\xcd\ -\xbc!g\xdb\xdf\x8ccn\xbc\xda\xcf\x18S]\xc1a\ -?S\xdd\xcd\xbcC\x92\xd6H\xb1_\xaeY22\xdc\ -\xf9\xdbZ\xcb\xd4\xb3\xaf\xf82\xebv]-V\x7fo\ -\xb9^\xe3\xdd\xdaT\x12Z\xaa\x12#\xefpR\x1d\x11\ -6 \xef}\xb2<\xac\x84\xbcz\x8c\xc6\x81\xff\x89\x8d\ -\x9f\xe1y-\xa0\xb2*\xf3n\xd0\xc7\x99\xe7\x05\x90\xe8\ -\xda\x12\x87\x84\xc3\xc4\x0b\xdb\xcde\xdc\x1e\xd8\x1c\xbe<\ -\xf3\xa3\x97i\xadl\xf8F%\xbf\xcf(\x17\x8f\xcd\xd0\ -C\xdaBz'\xb3'^\x0f\x95\x91Yq\x90OO\ -!4\xcf\x99\xdd+ \x13,g.\x0b\xfb#\xf3\xd8\ -\xaf\xab\xa3\xc4\x15{\xa4u\x13t\xb9\xd6_\x99r\xdf\ -F_\xc7\xf8\xd2\x99G'\xee\xe9\xac\x22;\x14\xcd\x8b\ -\xfc\x1a\x86\x94\x82\xa1\x92y\x1e\xb4\xd6Z\xb4t\x91\xdb\ -p\xc7\xdd\xb6\x15y\xf1o\xf4N\x1e\x09\xbd\xb9\xa2\xb6\ -\xde/\xc5\xcf\xd8`\xd4Pg\xe4Wd\x12Y\xdc+\ -\xf6(\xdb\x89u\x8aO\x8b\xd8\x9f\x1c\xd3\xfa\xfa\xa3.\ -\xbf\xf6\xec\xba\xf4\x1a#\xc33\xe5\xeb.\x98aO\xdb\ -(\xfb<\xd9\x9b4\xa7\xf8\xa5\xe2\xb5\xd5\xe9\xf2\xe3?\ -]~'\xafTc\xad\xb3'S4\xcb\xeb\x5c\x91\xe9\ -\x86mlY+\x05\x90\x0c\xcb\x9d\xdbB\xcb_\xea\xee\ -=\x7f.\xf3\xd0\x1d\xee\xd0J\xce\x83\x95\xd7\x92G\xac\ -\xbcm\x5c\x93\xa9\x11\xe7\xbf^\xb4n\xc7X\xb6O\xe7\ -\xc0\xeaD\x8a\xe3\xab\xfa\x10\x11p\xd5\xf9\x95\xc8\xc8%\ -\xeb\xaf+%k\xc6m\xfb\xa9X\x15\xb7\xc20M4\ -\xfb\x15G\xd2\x06\xb2\xdbb\xf6\xeb\x5c\xea\xeb\x83\x05\xcb\ -\x95k6k\xc7\xe8\x7f\x95\xcd\xe2\xbc3\xd8L\x1e\xbd\ -\x5c\xc0\xd5\x804\x04F\xb9\xc7\xa5\x1a\x8eC\x0e\x06\xee\ -5\xe0\x12\x9dxH5\xd0%\x9e-,\xd4\xd7}\x9e\ -W\xf9>\xd3I\xb2\x8f\x1f\xfc\xfa\xb9u\xfe\x8e\xa5\xca\ -\x01\x0e\xa5\xe5\x13v\x9fk\xb0p6\xda$;\xe2\xc5\ -\xce\xf7\xb2\xc7B_\x7f\x1cj\xa2.\xe58\x8d\xf7\xed\ -\xbe\xf0\xec\x8dKGi\xeb\xbdG\xf2W\xef\xd6\xe6\xd1\ -2,\x0dp\xe1T\x91m\xa8\x9b\xa7\xc4\xb5\xeb\x5c\xad\ -\xf9\x95\xa9\x09o#/\x9f\x9eB\xf6\xb3\xc9\xe8?\xf8\ -\xc3\xc4\x1d\xa7#\x8b^\x0a$*,\xb2\xdcu\xbf\xaa\ -?:k\x09R)1\xecD\xe6\xcb\xd4\xad)\xf5\x1f\ -\x84\xf3\xb2\xcb\x84\x96NV\x9aVz\x99p\x9ax\x22\ -\xdb\x80}\x9a\ -\xb4\xc5\xcaq\x84\xca\x17\xa0\x13\xa5W,\xbb\x15\xb4|\ -,\xd40K\xe6N\xca\xb9\xaa\xe5\xf1\xe4\x9a\xcd+\xbe\ -\x19q1y\xa2se\x92\xd7\xd5\x8a'\x9dsy\x87\ -\x8e_\x94\xffX\x94\xacj!.\xbf|\xb9\x0eg\xe8\ -\xa0=\xe4\xfd'3\xa2f\x8e5yzp\xe9\x98\x93\ -\x97%\xd6\x08).\xfc*:-\xfa\xd9\x86\xfd\xbby\ -\x1eI\xe6e\xef/\x18p\x7f\xbbQp\x99\xd5\xb1u\ -\xe6;x\xf3\xd9+]^\xf1\xc9\xbe\x97\xce1|\xb3\ -qM\xd5\x1b\xff\xb8\xc8\xd9u\xda\x03\xa4\x15\xee\x1d\xb1\ -\x9b9z\xe4\xd5\x9f[\xbf%\xf3\xba\x1a\xe5$\x8e\xbc\ -\xc6\x19\xb9)\xe8\xfa\xc7\xf2\xf8\xc3\xd1`\xad\x89x\xcb\ -!\xecG\xd2\x1b\xed\xd5\xef\xe7\x7f\xa7\x93\x13\x16Z\x1e\ -\xdc#\x1d\xf7\x22\xcd\xbf\xd2\xc6\xe5*\xd8b\xb9\xcf\x19\ -\xef&\xe4\x9dgR f\xe2\xa7\xbf\x8bG\xedY\xc1\ -\x8d\x83w\x87]%\xbb\xfb\x8eCV\xfd\xcf\xe4\xca\x19\ -I\xa3i\xc9_2Vp~\xbb\xcb[\x1e\xfca\xde\ -\xe6\xb4o\x1a\xd6gR\x1d\x143\xb7o\x8bJ\x11\x96\ -\xb9\xec\x1e;>G\xc7[\xe8\xb2{\x0d*X\x1b[\ -\x9ft(5`\x86\x00\xb2\xd38za-\x89(\x14\ -5;\xf8\xaa\x9f1\xa7B\x09A\xb7\xe8#\x9fBq\ -~\xd6\xb1\x17\xe2\x82\xab7\xd5_-y8\xf5\xb0\x8f\ -\xcb\xdb;\x8a\x1e\xca\xa9o\x5cW_\xd1\xae\xaf\x9e\xa3\ -E\xda!=\x98\xf4&e\xed\x15\x8f\x05\xecb\xcb\xcf\ -n\x8e\xbezZs\xf7\xd8B\xd2d;\xd4\xd8N\xd3\ -\xc1\xae\xf6\xa6\xb8\xaa\x8e\xba+Pe\x17s\xaa:I\ -\xc9\xdc9\xb7\xe9\xce\xb9\x87\xaaB\xc5[\x95\xc0j>\ -\xf0\xbe\xb1\xdc\xc1\xc0c@_\xf4\xdeUf\x9a\x07\xd6\ -\xf2\xf4\x06\xfdc\x93\x89\xf9\xb6\x0d\x9f=&\x97\xb9\xe4\ -]\x22.=\x95\xe1Xto\x95\xd9\xaa\xe3\x9e.\x93\ -\xdeo\xf9\xb8\xe6P\xa0\xec\xeb\xe7w\x84\xbc\xcakT\ -\x93\xd8n/\x91\x1a\x18<\xf7k\x0c\xd7\x88\x99k\x93\ -\xdeCE\xe9\xb9\x8fm\x10\x9f/\xf9\x85\x13\xb2\xf8\x16\ -x\xea\xcc\x01\x84\xaf{#>\x8c\xff\xb0\xb5\xe4\x86\x9c\ -\xc9\x08\x85\x15i\x867kW\x0c\x05\xc3\xfc\xc8;H\ -*\xd3\xfa\xf9fmv\xc1\xc29@\xe6.\x22\ -f\xb7\x0b\xbc\x94q\xf8Z\xa8\x97I\xf1\x7fg\x8a\xbf\ -p\x8b\x0f|\xd2\xefe:\xbf\xfe-\xca\xff\x87\xbc\x1c\ -h\xf3$D}\xac\x9d\x5c\x826Q\x1eQ`{\xf8\ -\xf6\x12\x7f\xd2'\x0d\xbf\x8f\xd1\xec\xe1%&\xc1\x1cB\ -\xa6nK\xb9\xf5\xec\x07\x95\xcd:\xf2\xde\xfb\xfa=\xca\ -\xd5-\xb39S\x91\xcd\x14#\xd5\xf9\xa4\xaa\xd7H\x0a\ -{\xc2/\x19\x0f~U_A\x01o\xb2C\x7f\x9b\xcc\ -\xbc\xf3\xec\xb2\xf92\x9e\xe07n\xd9f\x22\x8ae\xba\ -\x8e\x06fn\x1a\xdc7\x12\xa6\x9a\x91\x88\xc8\x86\x93\xa6\ -\x1cv1\xeb\xa6\xbf. \xae\x8c\xe6\x84\x9fF\xe2~\ -\xc9x\xf1\xab\x9e2\xc86#\xf9\xf8W;i\xdf\x0d\ -uU\xe5\x1e\xaf\xe1\x93&\x09\xff\xee\xdf\x7f\x1dA\xc6\ -\x97_\xe2\xfe\xbahB\xf5\xd4\x90\xb4%\xfbo`\xa6\ -\xbd\xbb\xb1\xb32t\x10\xd2\xe8R\x82\xcc\x03~\x89)\ -\xa4\xd7\x05\x95\x8c\xb38\xd1z\xba\xaa\xfd\ -\xedt\xa1\x80\xd09\x05\x15z\xfb\xc0\xbc\x5c\xab{\xb1\ -\xf8\x9e\x80j\xe5\xae\x0b\x99y/\x1f\xcb\xa2\xdb\xe4\x0d\ -\x96f\xf2<\xfe\xf5R^|\x81\x83\xb6}b\xa2r\ -\xbe\x09B\xb4.\x9e\x13~(c\xbd\xa4\xdd\xaf\xcf$\ -K\x9d\x22\x17}m\x04q@\x08f[n\xf0\xdfT\ -'\x9cJ\xfc\xac\xac^\x17\x0em\xe5\x93\x02GK}\ -\xb1~\xa2j\x7f\xeb\x92\xcd\xa9\xc3\xd7\xeas\xf4\x1bV\ ->\x9c\x82d\x1b\x19\x07\x17\xdf\x1b\xae*\x9cS\xac/\ -=\xb7\xf2V\xbfOos\x06\x91\x86\x10\xfd\x8b\xef\x8d\ -P\x0d|_br$`.*\x97?B\xe5h\x9a\ -\xcd\x9e\x90\x80M\xdcg\xd2\xd40\xd3\xf1F\x04\x19c\ -\xa4;\xaet\xcc\x0a\xefz\x19n\xbdyf\xe1\xc3\xc2\ -\xe2^\x84\x86\xc9:.\x1d`C\x14:\x22\xf4\xeb\x93\ -\xb5\xa4]\xa0;_V\x9a\xef\x9a\xc3\x8b\xa7\x22\x08I\ -\xb9\x86\x10^\x14Rr\x82\x7f\x84\x89\xd5\xf3b\xafq\ -\xb9\x08\x1cDM$,\xc1z\x91]\xa0}}\x8e\x99\ -\xcc\xf6\x89\xe7\xd8\x84\xe3r\x06\x11m\x0eh\xef=\xc5\ -\x9fTj\x9f\x99W\xedMx\xf3\xe5\x0b\xfbb\xe3\xc1\ -\x81\xaf?\xa5\x89\xdb\x99M\x16_\x17\xfde\xc2}6\ -\xfe\xb9\xa6\xa5\xe6\xe38\xed\x16\x07\x8f\x7f]G\xfe\xec\ -\xbae\xe2\xbc\x90\x8dpH\xe4\x1e\x1cx{;i\xdc\ -\x00\xf1\x90*n\xe3\x8d\xcf\xf7z\xad\xd5\x8eF\xce\xe7\ -\x95\xf5o\xe0 z\xbc\xab\xe1\x97\x88%\x7f)1A\ -7%\x9e\x91\x1e\x84@\x0f\xc0\xb4R%\xb1EUV\ -;r^F\xe8\xf0\x90QF\ -\x09V\xbcN\xb6Al\x8fV\xeb|O^\xbfS\x94\ -\xb3P\x83t\xf4#\xdb\xc5\xd1UWU\xf5\xdd\xb7\x87\ -\xcfT[{X.\xb0\x9fcL\xce\xa0t\xee\xd9\xa7\ -\x0d'Ip\xbeV\xa8x\x9a\x06\x1e\x1c\xf1kF\x92\ -\x00bljp\xc3\xc0fg\xc8;1;\x1e?\xae\ -\x9f\x95\x06\xd3\x1cL\xe5\xfc\x06\x18?'\xf6\xd3\x944\ -\xffiS\xa80\xd9\xcf\xfbx\x8a\xc5\x91\x10\xffw\x83\ -\x057\x22\xa7\x80\xac\xe4\xce\xda\xf7#\x9dMo\xd0=\ -\x1b%\x97\xaf/\xd6\x0f_\xcd\xa9\x22\x09\xe8\x9fY\xba\ -Q\xd7\xb5\xf8!\xf7\x8dp\x99\xad\x92\xd5~\x9ft\x1c\ -5RC\x10\x9dS\x99\xee\xd3\xec\xe7\x94\x8a\xdd\x118\ -c\xb8\xcf>\xc5\xa2n\xe04@\x93\xd6\x001\xa7h\ -!)\xf6b\xf6\x86\xe1>\x9ft\xc6\x88\xd7\xdd\x18\xb1\ -\x01\x99\x9d\x946\xf1E\x88\xbb\x022\xeb\xcd1]\x99\ -\xac~'\xf2e\x1c\xf8\xad\x03\x07\x97\xb2\x9d\xf9\xa0]\ -\xa6\xe4\xa1\x8c\xcc:\xf0\x9cM\xd2x\xba1\x97\xdc|\ -\x8b\x03v\xbf\x22wm]\xb4\x1f\xfdZbr\xd2t\ -\xa4\xb7\xac\xfc\x04D\xe0\xc0s\xdb\xcf\xe1\xf7\xc3\x85\xaf\ -\xaf\x02\x7f\xf7J\xe4\xdf\x18\xf7\xf0u\x89II\x82\x8e\ -\xbb\xfev}\xc4\xb4\xdc\x92\xc3$\ -\xa3_A\xc0Y>\x9b\x05c\x8c\xc2\xfb/Cd\xc6\ -\x07]\xd5\x9d\xe4x/t\x93\x84\xf4c\x0e!\xfb\x0f\ -\x99a\xbc\x86Kj>\xce\x0e\xd1_\x8e\xc0\xb9\xf1\x83\ -\xdd\xc5\xfe\xbe\xc2\x95e\x93\x85\xd5\xb6>\xf4\xd5\xd4\x9b\ -5DwF`\xbf\x14n\xbf~\x0a\xb5\xd6\xc5\xe6\x19\ -\xfdV\x8b\xef\xe6\xb8.=\xc6HLt\x14\xd7\x15\xde\ -\xb3\xc8\x09\x0eI\x0e\x0e\x81\x86\xa76[3\xb6\x0f_\ -\xfa?\xf6yY\xc6\x91\xd7\xc8\xe1\x9bu\x07\x97N\x0d\ -|\x05\x84T\x81\x8c\xcf\xca\x86\xb9b:\xff\x138\xa9\ -\xb8}3\xf4v.Y\xa8\xb1\xc0_U\xf7\xa8\x14\xf4\ -vR\xdc\x9f\x98\xc7\x12\xc1}\xa1=\xd1\x08Fc\xa8\ -a\x08\x80\x0c\xc0f\x00{\x00?\x80w\x00\xd9\x00\xe5\ -\x00$\x00\xf4\x1f\x01\x09\xefs6>\x06~\xf8\x98l\ -\xc6\xc7h\x08\xb51d\xe6\xd6\x01\xcf\x87\x01,\x008\ -\x06\x10\x0a\x90\x03P\xc9\x04\xe3\xcf\xac\xa8\xc4\xc7(\x14\ -\x1f\xb3\x05\xf8\x182\xed\x5c\xa0B\x1b'>\x87\x0f\x02\ -D\x01\x941\xc1\xb8\xf6U\x94\xe1cx\x10\x1fSN\ -f\x9a\x07T\xf8>\x03\xc0\x15\xe0;\x13\x8c\xdd\xdf\x86\ -\xef\xf8\xd8\xceh;\x0fz\x99\xef\x10\x13\x01\x1c\x00r\ -\x99`\x9c\xfev\xe4\xe2c=\xb1-\x1fz\x81\xf7|\ -\x00;\x01\x92\x99`\x5c\xfe5$\xe3c\xcf\xd7Ss\ -\xa0\x0d\xef\xa7\x00\xf8\x00\x10\x99`,\xfeU\x10q\x1e\ -La\xf4\x1chq\x7f\x0e\x80\x95\x00\xf1L\xd0\x7f\x16\ -(\x88\xc7y\xc2A\xef9@h\xfd\xces\x03\x18\x01\ -\x140A\x9fYh\x8d\x02\x9c7\xdc\x04:\xca\x82\x16\ -\xf7\x1a\x08p\x14\xa0\x8a\x09\xfa\xca\x02uT\xe1<\x1a\ -H\x0f\xfe\xb7\xe1\xfd)\x02k\xad\xef\x0b \xe2\xbc\xea\ -\xd6\x1c \xb4\x96\xf9GY\xbc\xefS\x80\xbc:Fh\ -\xb1\x16t\x91\xf7P\x9f\x80k\x0aK\xe6\xf7=T\xe1\ -\xbc\xa3I'$\xb4\xd6\xf7\xa0N\xc9\xd2\xf5\xfa.\x0a\ -p\x1evZ\x1fl\xf1Y\xb8\xa7d\xed\xf1\xfa>\xe2\ -\x09-\xec\x03\x9d\xe4=\xb4)\xf90\x01\xed,\xd0\x07\ ->\x84\x16v\xc2N\xc8}hWd\xe9{\x7f\x0f\x88\ -8O;\x5c\x07Z\xfc\x0d\xfa\x15X\xf6\xfc\xbf\x0f\xc9\ -\x84\x16>\xa3\x0ex\x0f\xfd\x8a\x0eL@+\x0b\x8c\x81\ -\x03\xa1\x85\xef\x98\x0a\xff\xa1o\x99\xe5\xc3\xfd{\x91\x8b\ -\xf3\x98\x1a\xff\xe1\xbcpe\x02\x1aY`,\x5cq^\ -\xb7}\xf7a|\x11+n\xe7\xef\xc7w\x9c\xd7mu\ -~+&\xa0\x8d\x85\x9e\x81U\x1b\xde\xc3\x18\xd3(&\ -\xa0\x8b\x85\x9eA\x14\xa1u\x5c\xf1B\x02+N\xf7_\ -B\x19\xce\xf3F\xfe\x1fc\x02\x9aX\xe8Y\x1c#4\ -\xe7\xe5\x842\x01=,\xf4,B\x09\xcd9Y9L\ -@\x0f\x0b=\x8b\x1cBs>\x1e+'\xeb\xdfC%\ -\xa19\x17\xb3\xb7i\xe9!\x88\xa0\x84\xbd\x10\xc2(a\ -\x0f\x84\x10\x0e\xc1\x16\x10j\x06\xfc\x1c\xfc<\xfc^\xaf\ -\xd3\xce\x10@\xde\xdfg\x02:\x18\x07\xc8\xbfF~\xee\ -\x97@\x0b\x0f\xc8\xa0\xc5Gg\xa3\xa5\x8e\xab\xd0\xb2+\ -\xdb\xd1\x0a/\x13\xb4\xe2\xeeA\xb4\xc2\xef0Zq\xcf\ -\x0a\xad\xf06A\xcb\xae\x1a\xa0\xa5\xcek\xd1b;e\ -\xb4\xe8\xa0,Zh2\xae\xc5\x9c\xf8\xab\xe6\x02\xe4\xfd\ -;&\xa0\x831<\x07\xff/\x04\xfc+uZ\x85V\ -\xfa\xdb\xa251\xbeh]\xe6\x07\x94\x5c\xf2\x13m\xa8\ -*E\x1bj\xabQ\x94T\x87\xa2\x0dd\x80\x06\xcaO\ -p\x0d\x7f\xdfP]\x8a\x92K\xf3\xd0\xfa\xef\x9fPb\ -\xec}\xb4\xf2\xc1q\xb4\xd4u=Zd5\x15%\x18\ -\x8b\xfe-s\xa11\xff\xbe\xb7\xe9\xa0+\xdf\x0b\xcd\xa5\ -\x00\xcfW\xa3U\xcf\x5c\xd0z\xc0\xef\x86\xaa\x12\x140\ -\x17\xednk\xa8.C\xeb\xb3\xbf\xa0\xd5/=\xd0\xd2\ -\x0bZh\xa1\x854e\x1d\xe9\xbb\xf3\xa0\xb1\xf6Bo\ -\xd3A\x07\xbe\x0bc\xb2\xbd\xfc\x86!Z\x1b\x1f\x82\x92\ -+\x8b\xbb\xcd\xef?\xcd\x85\xda\xe4\x08\xb4\x1c\xac\x1fE\ -V\xf2-t\x05&\x18\x8f\xce\xa3\xef\xd7\xdd\x00\xe3^\ -h>\x11-\xbf\xbe\x0b\xad\xfb\xfa\x1am\xa8\xaba(\ -\xdf\xdb\xcd\x83\xfaZ\xb4.\xe3\x1d\x98\x07\xfb\xd1B\xcb\ -\xc9\x94y\xd0\xdbc\xd2y\xf4]\xdec\xef\x9a(Z\ -r^\x13%~|\x04\xd6\xec\xaa\x1e\xe5{\xbbyP\ -G\x04r'\x14-uY\x07\xf4\x03\xb1\xbe(\x0b\xfa\ -\x0e\xe0;\x0f\xd6\xde\xca\x80\xa3(\xb9\xf8G\xaf\xf2\xbd\ -m#\x97\xe5\xa3UO\xce`kQ\x1f\x93\x05}\x03\ -`L\xe1\xbe\x8c\xf8>\x00E\xeb\xebz\x9b\xdd\xd4\x1b\ -\x99\x84\x12?\x07\xa3\xc5'\x17\xb0\xe6\x00]y/\x02\ -\xf6\xed+\x81N\xff\xbe\xb79\xdc\xa9V\x9f\x13\x0f\xf6\ -\x8c\x1bXk\x01] \x82\x96\xb9oFI\xf9\xe9\xbd\ -\xcdV\x9a\x1a\xa9\xf0;fg\xea\xfd\xf1\xeb\xc3\x00\xef\ -O\xd9%=\x94T\x94\xdd\xdb\xec\xecR\x83v\xa4\xb2\ -\xab\xff\xf5\xfe8\xf6E\x80\xf5\xb3\xf4\xa26\xf6\x1e\xd1\ -\xbd\x81\xbd[CM9\xdaPY\x8c\x92+\x8b\xb0\x9f\ -\xd85\xf8=\xbd\x1b\xb98\x17-\xf3\xd0e\xe9\x034\ -\xf2\xbe\xe4\xccR\xb4>7\x99.Vz\ -qS\xef\xc9R8\x07\x5c\xd7\xa3$\x02\xed6\x8a\x9a\ -W7)\xbaio\x8f}o\x03\xfauN\xcc\x03c\ -\x98E\xd3\xf8A\x1d\x91\xa2K\xf5\xb2.\x0d\x9e\x0fc\ -O`\xdc\x18-\x0d\xc6\xa2\x95\x9c^\xcc\xd2\x03@\xff\ -a\x8c\x1dM\xeb>\xf8,\x94\x17\x84\xfdc\xd1\xde\x8f\ -\xd1\x15\xc1\xde\xe3\xaaPWJ\x1c!\x0d\xad*\xf8|\ -\xef\x8f\x7f\xaf\xf2^\x04-<0\x05\xb3\x8d\xd0\xd2\xea\ -\xb3>\x82\xbd\x82\x22\xf3\xbc;\x98\xcdJ\x01\xad\xcb\x88\ -\xa5\xad\x1f`\xafStH\xbe\xf7eXo\x01\xec\xd3\ -`\xdc\x0c-\xb2\x13\xc6yA\xfb-\xd3\xf0\xbe\xa9/\ -\xc2X,\x1a-6\xe3\x06b%\xb6\x8f`\xd8~\x95\ -\xd9\x01x\x08\xed\xf1\xb4\xb4\xba\x94H\xb4\xd0r\x0a\xf3\ -\xbd3P\x96YLBk\x13_\xd0\xd4\x9f\xea\xe7n\ -\xbdO{o\x8d\x97\xf9D0^/;?X\xa4:\ -\xb4\xc2\xdb\x94y\xdf\x17@W\xf9\xcd=hC}\xe7\ -\xed\x83u\xe91x\xfc(\x93\xcdg\x86\xf3_\x18\xcb\ -\xc7\xa1\xc5\xa6\x0e\xed-L\xedC\x01<,\xb2\x9e\x8e\ -\xd6\xffH\xe8t\x9f`\xdc`\xb1\xfd?\x18/\x06\xde\ -\x15\x18\xd7\x03\xd7\xc0\xce\xb6\x9a7^\xcco73\x16\ -E\xab\xc3\xaft\xbaO\x98>sm'\xf3\xca4\x86\ -\xf1_\x10\xad\xf4;\xdc\xf9}\x1f\x90\xfd0\xd6\x9e\xe9\ -\xc7\x09\xae\x01\xd0\x87EC>B\xd5\xa3S\xcc\xdf/\ -\xbaC\x84&\x9b\x1f\xb9\xa2\x08\x8b\x09az9\x89\xd9\ -\xb3Ti\xf2\x0f\xc1\x18\x03\xc2>\xb1\xde\xa7\xbd\x07y\ -\x0fc,`~eg\x1b\x8c\xc7):4\x8d\xf9\xf5\ -$\xa8\xd7\x1e\x94\xa5\xc9\x8fY\xfb\xe5)Zh&\xc9\ -\xfc}\xa3\xe7\x18\xd1\xa8\xfbc\xfb>\xb0\xbfb\xfe1\ -\x12\xc1xY\xfb9\xb8\xf3}\xc3\xf6\x00L\xb8\xa7e\ -$\xff\xc1\x9e\x07\xf6\xbb\xb3\x8d\xf8\xf1!Zh:\x1e\ -\xed}{o'\xb0O\x02\x8b;\xebl\x83\xf9\x02E\ -Vr\xff\x16\xff\xa1\x8c\xcc\xfa\xd8\xe91\xaay{\x97\ -I\xec\xfd\x9d\x00\xd8\x03\xd4D^\xeb<\xff\xb1\xb5\xed\ -\x1f\xb2\x03cv\x7f\x19\x9a\xf2y\xfej\xfe\xffL\xf9\ -\xf7\xf8\x0f\xd6;\x96\xfc\xc7\xf9\xff/\xca\x7f\xa8\xff%\ -t\xdeVN\xd1\xff\xa4\xfb\xc0\x18uE\xff{\x8b\xf9\ -A\x99\xbfot\x1c#\x9a\xf7\x7f\xa9}l\xff\x17\xd7\ -\xe9\xbe\xd5~y\x06\xe6\x8c\x14\xf3\xf7\x8d\xce\xe3T\xfd\ -\xc2\xad\xd3c\x04\xf3\xb4`\xfcu\x9f\xb0\xff\x1c\x9fG\ -\x9b\xfd\xe7\xcdm\xe6\xb7k\xd3\x1b\x98\xfd\xd7\x9a\x06\xfb\ -o=s\xfb\xfe\x9a\xfa\xd5\x05\xfb\xef\xe3\xd3\xcc\xdf/\ -\x06\x8cS\x99\x9b\x0eM\xf1\x12\xb0\x8e\x1b\xd3\xc7LB\ -\xffO\xd8\xe5N\xf7\x09\xe6\x92\x94_\xdf\xfd\xef\xf1\x1f\ -\xfaJ\x8f(b6@X[\xad\xfe\xfb\xe7\xdf\x03|\ -\x06\xe6o\xc2\xb5\x95i\xd7I\xcc\xff\xfb?\xa0\xcf\xd3\ -\xe0\xff-/@KN\xa91\xff\xba\xc6\x08\x80w\x05\ -\xee\x03a\xad\xcd\xce\x00\xab\xad\xc3\xcc\xeb$\x94\xfd0\ -\x16\x98\x86\xfc0XC\xac\xcf\xea\xfe{E:\x07z\ -\xdc\xa33\xf7\xea\xe5\xb1\xc0\xe2\xbf\x12\x9ew\x9a\xf7\xb0\ -aq\xccF\xa2\xbdO?\xad\xd8?\x16\xeb\xef\x1fa\ -.E\xc9\xcb\xeamz\x19\x8d=x\xee*\x91\x86\xf8\ -O\xa0\xfb\x94]\xda\xda\xf7\xd6~\xa8\xbb]5@k\ -\x93\xc3\x7f\x8f\x94\x08\x94\xf8\xf6.^\x13\x8d\x89\xdf\xdd\ -\xee\xa2\xb1fA\xc6[\x9a\xde}\xa8\xd3\x14Y\xf7\x01\ -\x9bF[\x18\x0aRr6:\xd1`|\x1f\x1c\x9b\xbf\ -W\xbf\x11\xc1\xec\xbdU!.\xb4\xe7\x7f\xc8\xd4v\x8c\x9e\xe2\xbf\xef\x01\ -\xacfnW[\x8f\xc7\x84\xc0\xfa/fR\xd8y1\ -\xb0\xc6TW\x1a\xe9g\x0aZ|\x5c\xa5\xf7\xd7\xae\x7f\ -\x81\xff\xf4:\xc3\x09\xa3]\x14\xe8kK\x80\xcc\xb9\xdf\ -\xe5\xb3\x06\xe0\xf92\xf0\xdc\xa1>\xb7\xdf\xeb\x8b\xfc7\ -\x16\xc3\xce\xec\xc1b\x86\xbaT\xffM\xa4\xb9\xfe\xdb\x89\ -\xf9\xd8^\xad\xbbu\x00a\xfeR\xa1\xe9_\x10\xe7M\ -\xcb\xfe\xbf\xf8G/\xf0\x9f\x12_\x02\xd7Y\xe83\x82\ -6\xf9b[%\xbc\xf6\x9ep\x8b\xf3\xde:Q\xff\xf1\ -\xd5M\xba\xd4\xa0\x85\xb1nE\xb6\xb3\xfa\xb6\xdco\x04\ -V\xf7f\x03\x16\xe3\xf8{\x5cG\xab\x82\xceQ\x8f\xdb\ -\xea\x01\xfeC\xde\xc3\x06\xf3q\xe1\x1e\x8d\xf8)\x08\xab\ -1V\x0e\xcfzs\xdf\x8c\xd5\x94\x87{\x10\xa8\x8b\xc3\ -z\xb0\xad\xea\xbf\xfe\xfcJ\x93-\xf7w\x0d\xd6.\xc7\ -\xf4\xfd\xbf\x81\xf7-\x01\xed\xfa\x9d\x01\xb5\xef\xf6\x04\xff\ -\xe1Y\x11T\x19R\x87\xe5\x9d\xc2\xf3\xc1\xe0yQ\xf0\ -'\xc3\xea?\x97\xe4br\xa4\xcf\xcb|z\xa37\xf9\ -\xdfC\x0d\xd6\x7f/g\xd5\x7f\xff'\xf9\x8f\x9d\xff\xe0\ -\xc9:\xff\xe1_\xe4?\xf4\xeb\xb1\xce\x7f\xf9\x07\xf9O\ -\xae\xc7t\xcc\xe2\x93\xf3\xff>]\x8f\xc5\xff\xdf6\xe8\ -\xcf\x83{\x07\xd6\xf9o\xff\x16\xff)\xe7?\x86`\xe7\ -\x86\xf7\xb1\xf3\x1f\xe9|\x06(\x8d1{}\x9c\xffM\ -\xe7\xbf\xde\xde\x87\x16ZJ\xf7\xb5w\x1e\xf2\x9e\xae\xe7\ -?C;+\xcc\xe9o\x07X\xb3\xc1\x98\x8a\x8f\x96.\ -\xfe\xbf\xfb\xbf\xe1\xffx\x94\xf8!\x90N\xdcnn\x94\ -\xf3\x9f\xc3\xb1ZD\xd8\x99\xf0}\xf7\xfcg:\x9e\xff\ -.\x82\xf1\x12\xda8\xebR\xdf4#-\x0a%\xc6=\ -\xc6b\xe2\xdb\x8d\x11\xf4\xff\x9fU\xc7\xec\x83U\xc1\x0e\ -\xb4\xe3\xa9#\xa5\xe6?U\xff?\xe5\x1c\x19Zrp\ -\xff\xc4\xf3\xfa\xec\xcfX\xdd~\xa8\xd7\xff%\xe7\xbf\xbf\ -\xa3'\xff;\xcay\x81\xe7r\xc0:\x7f\xd4\xe3\x7f\x84\ -1_B\x97\xf1\xbb\xf8\x09cQ\xb4\xd8~!Z\xe1\ -g\x8d\xcd\x03(\xab\xa1/\x02\xb3\xf5\xc1\x9c#R\x1d\ -e\xed\x81\xf9g0n\x0f\xda\x04k\xab\xb1Z\xb4\xd0\ -n\x03\xeb\xf7\xc0\xfcT\xe8\xe7\x801>\xd8\xbb\x0e\xe3\ -\xb41_R\x9f\xe5{# \xef\xef\xd3\x95\xff\x1d\xd4\ -\xf2\x82zq\x87\xfcg4\x9a\xcep\x92\xc0r,\x8a\ -\x8f*av\xf8\xb2\xcb\xdb\xc0\xba\xbd\x1f\xd3?\xe0Y\ -.\x15w\xad\xb0\xdc\xc22O\x03\xa0\xc7\xadA\x8b\x8f\ -)S\xf2M\x80\x0ci\x8e5\xeb\xf3\xd2\xea\ -\xeb\xd8\x0dJ[^\x0fF\xd1\xac\x96\xd7\x5c\xadn\x8f\ -=\xa0-9m\xae\x1bZ_\x1f!\xb5\xbe\x9eKl\ -}-Z\xda\xfazp\xdb\xeb\xac\xd6\xd7\x5c\xe1\xad\xaf\ -9\xda^\xdb\xb4\xbef\xfb\xd35\xc2j\xac\xc6j\xac\ -\xc6j\x0ci6\xad/\xff(\x8f\xc3[_\xb7\x93\xef\ -Y\xad\xaf\xb9\xfe\xb4~\xb4]o\xda\xaeGm\xd7\xab\ -?\xado\xed\xd6\xc3V\x04q\xb5_O\xdb\xae\xb7m\ -\xd7\xe3\xb6\xebu\xbb\xf5\xbc\xf5z/\x05~\xa8 \x94\ -qeC\xc4(\xbfWAhj\x1d\xe8zj\xb8N\ -\x13\x86\xeb9\xd5\x00\x0d\xbd\xa0k5\xe0\xcf\xce\xc6i\ -\xb1\xc7ik\xa7c\xd1\xda\xa8\xf4[\x08\xc0\x10 \x02\ -\xa0\x94\x09\xf4\xcc\x8eP\x8a\xd3h\x88\xd3L\xf38\xb4\ -\xf9\x0e/\x80.@\x5c/\xf1\xb8;s#\x0e\xa7\x9d\ -\xb7\xb3c\xd0\xa6\xef\xe2\x007\x01j\x99\xa0?]E\ --\xde\x07\xf1?\x8dA\x9b\xbe\xcb\x13\xfe\xae\xbc\xe1(\ -\xbcOT\xc7\x80J\xdf?1\x01\xcd\xf4\xc6\xa7\x8e\xc6\ -\x80\xd0z\xce\xffM|\xa76\x0f\x9a\xde\x856}\x87\ -r\xe2&\x13\xd0\xc8h\xdc$\xb4\x91\x898\xa0\xac\xec\ -\xcb\xb2\xae\xb3\xa8\xc5\xfb\xdav}\x8fc\x02\xdaz\x0a\ -q\x84\xd6\xfa\x01\xd4\x17\xfa\xd2\xfa\xde]4\xe0}n\ -\xd4i#\x98\x80\xa6\x9eF\x04\xa1Y\x9fgf\x9d\x96\ -Q(%4\xefez\x9b\x96\xdeB\xe3>\xae\xe7\x9e\ -\xb9\xb7E}Fx\x0dkG\xc1\xb3R\xe19R-\ -\xcfn\xeb\x99\xbaB\xb0\xeft\xac\x93\xdcQ\x9f[\x9c\ -5xT\x09\xabOZ\xf9\xc8\x1e\xady}\x0b%~\ -x\x88\x12?=\xc1\xce\xba\x85\xf5\x87+|-\xd1R\ -\x87\x95X=SJ\x9dJ\x86\xd6\xd5k\xdc\xbf3\xee\ -\x19\xf0\xbc=\xf3\x89X\x9f\xb1s\xd7\x8a\xb2)\xb5y\ -\x7f\xd3\xe0Y]\xf5YqX\xed\xe8\xe2\x93\x0b\x9a\xe7\ -\x0d\xfd\xe9c\x9c\xed\x02\xf2\x1c\xcc\xed\xd2\x8b\x9b\xd0\xda\ -\xa4\xb0.\x9f)J.\xceE\xabB\x5c\xd0\xa2#3\ -\x18q\x9e4\x83\xfa.\x8c\x9d\x93\x01\xcf\xf1\x86\xf5\x96\ -\xe9\xd1`\xbdfx\x86\x1f\xe5\x19L\x5cs\x0c\xf4\xbd\ -\xc8F\x11;'\x86\xde\x0d\xd6\xda\x84u\x8c)\xf5\xf6\ -\x98p\x0c`\xdf\xc1<\x85\xf3\xbd3\x0d\xd6\xe3&W\ -\x14\x82~\x15\xa0\x0dU`\x9e\x90\xea\xff\xfc\x1d \x1b\ -*|,z\xbf\xaf\xed\xfa.\x82\xd5Cl<\x93\xb2\ -C\xfa\xabJ\xd0\xda/\xcf\xd0\xca\xfb\x87\xd1R\xd7\xf5\ -h\x89\xbd\x1aZ|B\x15-9\xbb\x0c-\xf3\xdc\x81\ -\xad\x01\xf5?\x12\x01\xb3\xc9\x1d\xdf\xa3\xb2\x18\x93\xa7\xcc\ -Vs\xb5\xf2\xe1IJ\xaduj\x0d\xc8|b\xdc#\ -\xb4\xd4iu\xeb\xba\xdbMg\xb4\xe2\xf5\x9a\xc18\xc2\ -z\xa2\xb0\xae;\xa9\xe0[\x87c\x00\xcffg\x9as\ -\xb6\x01\xed\xf0\x9cQrY~\x87<\xaf\xf4\xb7E\x0b\ -\xcd$;'\xc31}A\x18\xabo\xff\xbbw\xa9&\ -\xca\x0b%\xec\x97\xe8\xfd\xfe\x03\x1a\xe0Y-T\xfb^\ -]\x86\x9d\xa5\xd1\xd4/\x1a\xc7\x15\x9e\xd3[\x9b\x10\xda\ -\xe1\xbda\xed~\x06\xac\x8b\xb4\xf1\x1e\xbc\xbb\xe4\x8a\xa2\ -\xf6\x04\x92I\xd8\x99Q\xd8\xb9\x02]\x95\xd7\xe0\xfe\xc5\ -v\xca\x14\x99@m\x0e\xc4\xf8R\xf4\xe7\xde\xea?x\ -\xff\xaa\x82\xcfS\xa5\x0d\xd6\x0b.\xb4\x9c\xd2}]\x1e\ -\x8cA\xf9\xf5]Tu(\xa8\x1f\x15\xdb\xcd\xed%9\ - \x82\xe9\xb6\xf0\x5c\x94vs\xb3\xbe\x96r6(=\ -\xe6&\x5c[\xcc\xa4\xa8\xcb\x02 o\xcbo\x1b\xf7\xce\ -;\x00\xc6\x1c\xae]\xd4\xe4^}N\x02Zd%G\ -\xbf}\x1c\xe8\x1f\x5c\xf7\xb1\xf3<\xda\xbe\x03\x91\xd7\xd1\ -^\xd1\x87\x00Me\xee:T\xcf\x15\xaeys\x9b\xce\ -\xcf\x12FKN\xa9a\xfaR\xbb\xf7,%\x02;\x9f\ -\xa9\xe7\xfb/\x08\xf4Q\x13\xaa<\x81\xeb\x1d]\xe7$\ -\xd4\x0b\x0e\xca\xa1\xf5\xb9I\xed\xe7\xda\x8f\x04\xb4\xf0\xa0\ -l\xcf\xd7\x22\x06\xfd\xaf\xbc\x7f\x84\xfa;y\xcb\x98\xa2\ -\xcf\xd0\xedy\x14\x19@M\xd6\x90\xf23\xa8\x9f\xc1\xc4\ -\xea?\xc3\xfb\xdf\xe1\xfc\x0f\xe8\xd9\xf9_\xd4+\xf3\x1f\ -\xc8?7\x1d\xaa\xf6\x1cx&\x13E\xef\xa1\xd7\xb3\x84\ -\xb1\xbd\x12u\xf9\x17\xd9;\xf2\x0f\xae\x7f@7\xab\xcb\ -\x88\x05s0\x1d%\xfdJ\xa3\xa0 \x03;\x17\x0d;\ -G\x8c\x9e\xeb\xdf\x1ds\xea\xeb\xdf\xab\x1b\x0c\xe4q\xa3\ -M\xb6\x05Z\xeaZ\xc6b\xd8:\x0f\xf7lE\x87p\ -\xc0\xff\xc3\xf3\xb4\xe8\xa5\x97\xfeQ\xff\xd9\xcf\x18\xfd\xc7\ -X\x14\x9b\xdf\xd8\xf9Q\xf0,)\x88\xbb\x07\xd1\x923\ -K[\xf3\x95\xd1u\xf1\xa1\xfe{m'u\xfd\xb7$\ -\x97q\xfb`\xc0?h\xabh\xdb\xaa\x9e\x9ci\x1eo\ -l\xaf*\xf8\x1bt\x93/p\xffsL\x19\x93q\xd4\ -\x1a\x11\x9e\x11\xca\xa8\xfdO\x87\xfd?\xdb\xe4\xa3\x80v\ -\xce2\xf7\xcdh\xd9%=*\xd8\x8a\x96:\xae\xec:\ -}p\xff\x0b\xd65x\xfe,\xb5\x86\xed\x7f]\xd73\ -N\xf7\xff\x13\xff\x01J\x9d\xd6`t`g\xedA\xfb\ -]K\x00Y\x05\xd7k\xec\x8c\x90&\xfd\xbc\x13\xe7n\ -\xe1\xfe\x92b\xfb\x05\xe0\x9d\x7fI\xb5\xef\xb0\xd5D\xdd\ -a\xac\xfd\x03\xf6\x9f\x8a\xed\x01\xfa%\x9a\xfa\xef\xbc\x96\ -r\xde`\x07\xad\xee[l\xab\xfeC\x1bP\xa1\xe9\x84\ -\xf6\xe7\x91\xb5\xb4\x7f\x01\x19Zq\xef\x10\xa6\xd7t\xd4\ -Hy\xa9\xe0\xbd\x9f\xc7\xd8}/\xe8\x7f\xd53'\xfc\ -\xdc\xcf(\x0a\xc0\xff)\xba]'\xfb\x9f\xd1\xa2\xffP\ -_\xf0\xdc\x0e\xe6s(\xb6?(\xbd\xa0\x05\xf64\x8b\ -\xb0\xf3\xd4K\xce5\xda?\xddp\xfbg\xc7\xe7\x06c\ -\xf6Ox6h\x0f\xec\xf9\xb1sop\x9ea\x806\ -\xbc\xc69Gs\xff\x05\xb1\xf3\x84\x9b\xfa\x01\xe49\xb9\ -\xb2\x08\xb3\xebc~\x92N\xdb\xbf-\x19\xde\xef\xd6\x10\ -i\x83f\xf9D{\xff\x8d\xa9\xea0\x9diL\xe7\xff\ -\xe8\xc1\xfeC\x7f(\x83\xfc_\x9d\xf3\x01\xb6\xfa\xcc\x1ea\xccw\x00i\ -\x86\xf1\x81\xe4\x92<\xea>\x7fR\x1dJ.\xfa\x81\xe5\ -\xcb\xc2\xf83,_\xaa{\xfc\xe8>\xed\xe0\xf9%\xa7\ -\x97\xa0\xb5\x9f\x82\xd0\x86:b\xa7\xfd\xb7\x0d\xc4J\xcc\ -\xb7\xd7\xbb\xb9Z\x22\xd8\x98\x93\x08Y\x9d\xa6\xbbm\x83\ -~/,\xd6\xaa\xa7\xfb\x00\x9e\x07\xe3b`\xec\x03\xd5\ -\xf1\xad\xa9\xc0b\x81\xb0\x18\x9d\x8c\xb7X\x1cjG\xf1\ -\x080\xf7\x9a\x92/\xd5C}\x801\xbbg\xd5QR\ -av;Z`\xceHu\xd8%,\x1f\xb0\xe8\x90<\ -%\xc6\xc6L\x0a\x8bw+u\xdd\x80\xe5\xc6\xc3\xbc\xb9\ -v|\xf8\x91\x88\xc5\xdc2\x9c\x0f{)\xb9=\xd4b\ -\xef\xea\xd2\xdfb>jJ\x1f\x85Z\xf8\xc4D\x9a\xfd\ -\xbbX\xee\xf7F\xaaq\x8b5\xd1>\x98\xfcb\xec\xd8\ -\xc3\x98\xd1]\xedb3\xea\xd2\xa2\xb1\x1a\x04\x9d\xf2_\ -\xc3\xdc\xb6Sj\xedr\xcf`|\x02\xe4\x11#s\x8e\ -\x0aM\xc6\xb7\x1b{(/a\x9e%M\xcf\xc5rt\ -6\xb7\xcbC\xc7\xe2\xd3\xb18\x22F\xcc\x1da\xacn\ -\x01\xcckn\xd9\xaaC]\xbb\xe6\xd7\x07\xeb\x18\xcc\xf3\ -k\xf5.\x17|\xa3\xd4\x04`\xc4{\x00\xe3tn\xec\ -n\x95\x83\x0c\xf3\xb3i\x1e\xfb\x16\xf7+s\xdf\xd2j\ -\xdd\x80100\xfe\x8f!s\x08\xdc\x13\xe6]\xb6\x92\ -\x1b9\x09X\xecI\x97\xc6\x1f\xcb\xe9\x9f\xd9N\x8eU\ -\xf8\x98\xd39\xc7\xa5\xf9y\xd5//\xb5z\x16\x8c%\ -\xc2\xf4\x80.\xdd\x0f\xc82\xcb\xc9h}\xf6\xe7V\xf7\ -\xac|x\x821\xe3\xdf!\xfd]\xcc\xd1\xe8i\xfa\xa9\ -\xcd\x9f\xdc\xa4\xae\xe7\xd8t8\x7f,\xe84\x7f\xda\xc7\ -e\xc2x5,'\x05\xc8\x09\x08\x18?\x08s5\xbb\ -$/:|\x7f\xb5\xbb=\xfeX|mcl-\x8c\ -\x93\xc3e2\xfc=\xd4\x05Z\xa2\xcb\xf3\x07\x93\x9f>\ -\xad\xe5'!\x13\xc8O\xc5\xee\xc9O@#\xd4a\x1a\ -\xe3\xa3\xe1zU|lNs\xdc\x9a\xe1\xe8\xd6\xe8\xca\ -\xbe\x0a\xcf\xb1j\xbf~\xf9t{\xfd\x82\xe3\xdd2\x9f\ -\x0e\xea\x92P\xc7\x87t\x16YO\xc7t\xc5\xd6X\x0f\ -t/\x15\x9ah\xa7\xae?T\xd0E\xf6c\xf4\x83q\ -o\xbaou\x19F\x7f\xc1\xeeQX\xae\x14\x9c\xa3-\ -\x01\xf7U\xadr\xa5\x1a\xe3\xee\xa9\xeao\xa2\xd8\xfc\x86\ -\xebF\xdb\x86\xe5\xdc\xd3A\x7f\xc3t\x9c/O1\xba\ -\xa1\xae\x0b\xf7'0\x9e\x14\xa3\xdf\xf7@\xbb\xe7b\xcf\ -\x8e\xf2\xc6i\x17\xc1tP\xb8'\x81\xf9\x02Pw.\ -4o\xa3?W\x16\xb7\xfb>\x94ct\xcb\x97\x07c\ -\x04\xf7\xd90\x86\x1f\xf2\x19\xc6\xaab\xef\xb0\xa1\xe0\x9f\ -\xe9\x872\x16\xec\xd7!_`\xce\x1c\xdc\xbb\xd4e\xbc\ -\xeb\xc4\xfee=}\xf7/-\xeb\x915\xdewOg\ -\xe9w\xa4\xfa\x19j\x8d\xa1\xfb\xc7\x969Xx\x9c5\ -\xccS\xa3J?\x94\x1b4\xd0\x8f\xed\xdf\xdf\xde\xa3\xc7\ -\xfe\x9d\xba\x0d\x02\xe6\xbb\x80\xb5\x11\xe6\xb7\xc1=:\x16\ -\xf7\x0b\xd7\x1b\xb0~\xc1\xf9@\x99\x1782\xdf\xa3\x95\ -\x0fN4\xd1\x0fk\xa8Q\xad7\x83\xd9Or\xe8m\ -?\xa1n\xbf\x82\xba\xf2\xcd=\x18\x1d\x98\x8e\x0c\xf6\xbb\ -\x94Zo\x12\xf8\x9e\xb65\x9a\xe5\x86\x08\xf6\xaeR\xec\ -W\xb6=a\xbf\x0a\xeb\x90~\x18\x93\x0e\xf8L.\xfd\ -\x85\x96\x9cY\xd2B.\xb7\xcd\xfbhCG\xd3\xbck\ -c;d\x8c\xfd\x90\xba\xfd\x16\xce\x1f+9,\xcf\x0e\ -\xc6\xe5C\x19\xc8d\xf1\xa9\x8d\xf6\xdb\x8e\xed\xe7\xadb\ -\xc2\x99\x8av\x94\xd0l?\xef\xeb\xfe\x8b\xbe\xee?\xfa\ -\x1b\xfcw}\xd6\x7f\xda\xd7\xfd\xd7\x7fC\xfc@_\x8f\ -\xdf\xe8\xcb\xf13X\xfc\xd0`\x04\x09\x87?9\xf0x\ -#\xb6\xe6\x9f\xac\xd6\xbdf\x03\xffi1\x9e\xe1\xf0'\ -G\xf3\xb8\xc38-1\x84r\x84OS\x9c\x16?\xf5\ -{\xb5\x99[C\x01\xb6\x01<\x05( t\xef4\xces\xda\xbf\xdf\x14\x0b\xd1\xa2n\x09\xed\xb6\xde\ -\xc6w\xac\xf3\xdf\x81\xf5\xb1\xc1\xfe\x14\xdaN`\xbd\x10\ -X[\x01\xd6\x0d\x84\xf5\x10\xb0\xfaA\xb4\xd1\xd1\xf9\xf7\ -\x1b\xdes\xbf\x04\xb6\xd7\x845>0_\x15\x16\x8b\xd0\ -\x80\xd5^\x806)X\xbb\x02\xda\x11\xa0\xed\xbd\x93\xfb\ -\xb9N?\xbb\xd0R\x1a\xcb\x8dn v\x9c;O1\ -@\x90\xb1z\x11t\xb3Ya\xb5\x84$1\xfbX+\ -\x93A\xc17\x94\x18{\x1f\xad~~\x91\x92\xeb\xfa\xfd\ -S\xab\xbaV\xd0\xfePd;\xab\xfb4\x80\xefc\xb6\ -\x192%\xee\x03\xda\xba\xaaC/`6\x10,\x07\x18\ -\xab\x87K\xc9\x93\x866LX\xdf\xa7\xc9v\xd3]\xbb\ -#\xf4C\x1cV@I?\xbf\xe2\x9d\xae\xc7\xf2\xb01\ -;r\xdb~\xe1{\xd22\x8f-M5\xb7\xa0\x8d\xa0\ -[v\xdbF[\x09\xeeW\xacM\x0e\xa7\xd4\x06\xf8\xdd\ -\xfc\x06\x7f\x83\xf9\xd6Mc\x80\xd5z\xec:\xef\xab\xc3\ -=\x9b\xee\xd5)\xff\x0b\xb4a\x9fY\xda\x14\x8b@\xa9\ -g0\x09\xed\xd2>}\x9f\x18\x16\xf7C\xe1{5V\ -;\xe2\x8fc\x89\xd97\xe41\x1b)e\x9efb5\ -q\xbb\xe4\x87\x02|\x86g\x0d`\xcf\xaf'\xe2\xb6T\ -\x06?\xbfe\x8d\x1b\xc8\xcb\xe0\xf3\x98m\x0e\xde\xa7\xcc\ -\xd3\xe0\xcf\xcf\xa76\xfe\x16\x9d\x1c\xff}\xe2\xd8w\xa1\ -\xdd\x15\xda\xd5\xe1\xfbE\x891\xa1\xd4(\xc3\xecq\x7f\ -z\x9f!\xcd\xcf\x9c\x9b\xe7_\xa7k\xadQ\xea\x81C\ -\xb9\x01\xe5i\xed\xe7`L\xdeB\x9f=\xa4\x09\xc3Y\ -uJ\x9d4j9\xd5\x8d\xef\x9f\xfb\xe6\xa6\xd8\x1f\xca\ -\xfb\xd7I\x9f\x1bV\x8f\x5c\x1a\xad\xcf\xfeBy\xd7\x92\ -^b\xe3\x81\xc9\x5c s\x1a\xaa\xcb1?\x0cVK\ -\x06;\xa3A\x8a\x22\x07\x9a\xe4\xcf\x14\x8a\xfc)n-\ -\x7fh\xf2A\x03YU~\xd5\x00\xab\xe5\x0d\xe5\x08\xcc\ -\xa3\x87\xe3\xd7\xb2\xc1z\x1aX\x0d\xe1\x10W\x94\xf8\xf1\ -!\x90\xbfn\x1d\xca\xdf\xe2\xae\xc8_\xd0\xb7\x82\xdd#\ -)\xfe7\xd0\xaf\xb6r\x1f\xd6a\x87\xf7\x84\xcf\xa6\xda\ -h_\x7fZ\xaf\x81\x80\xe70n\xa2\xe4\xf4\x22\xec\x1a\ -\xca[\xe8\x83\xa9\xcf\x89\xc7b\x83\xca\xaf\xef\xc6\xee\x0b\ -\xfd\x0aX]\x94\x86n\xaf\xbf\xcd\xfa\x07\xceG\xf8\xac\ -\xda\xc4\x97\x18?0?+\xb8_\x13p~\x16\xdb*\ -\xd1K\xffh\xa5\x7f\xc1\xda\x19\xe5^&\x98}\x1f\xca\ -\xbf&\x1f[\xdb\x1ay\xf4\xd3\xbf\xda\xeb\x9f-\xebm\ -0\x0e\x8d\xfago\xeb\xdf\xbd\xbd\xff`\x86\xfdW\xaf\ -\xed?{{\xffm\xd3\x8b\xd6\x18\xf8lh\xa7\x80f\ -\x091\xa4\x85\x9d\x82\xb3\xfdgq\x9a\xc7\x00\xb8\xe1}\ -\xfa\x9d\xed\xae\x01\xff\x8c\x1b\xfe\x9d\xc6\xef\x06ua\x0c\ -\x83Z<\x97\xca\xdf)g/4\xe9,\xd4\xef\xd1H\ -s\xeb\xdf\xc3so\x80|\x85\xb1\x7f%\x0e\x9a\xcd:\ -}{9\xd6\xbe\xbf0\xbe\xfa\xec2\xac\xde l\x18\x9b\ -\x02\xfd\x96\xd8\xd9\x22\x8dgl\x18R|\xe1\xf0\xb9\x94\ -x\xd56\xf47\xeeA#\xaea\xeb\x1e<\xaf\x07>\ -\xa7\xd4U\x0b\xd3\xb9\xe0zU\x1d\xe1\xf9\xbb\xf1kh\ -\xf4\xe1\xc28\x22\xe2\xbb\xfb\xd8\x99$\xf0\xfb\xb5\x89/\ -(\xfe\xd4\xdf\xf3\xaf\x00\x8b\xedv\xd3\xc1\xc6\x16\xae\xb5\ -X\x1c4\xb4\x05\x00]\x03\xc6v\xfca\xfeP\xe6/\ -\xd4\xd9\xb0\xfd[\x8b\xf5to\xa7\xe6ow\xdf\x9fn\ -\xbd\xbf\xddm\xff\x07:J\xaf{\ +\x01\x9f\xd1x\x9c\xed\x1d\x09\x5c\x8c\xdb\xf7\x9bR!\xd4\ +\xc3#)e\x8dl\xf9{\xc8Z\xf6}_\x1f\x22<\ +\xbb\x92\x84,\xd5\x90%d\x97\x9d,E$B\xa4\x92\ +\x22\x22k\x12\xd9[H4\xed{\xd3\xcc|\xff{\xee\ +\xf7MM\xd3LM3\x93&\xba\xbf\xdfy\xbdI\xf3\ +}\xf7\xdes\xee\xd9\xef9\x04\xc1 T\x09\x18\x0cB\ +\x9f\x98\xa7M\x10\x0b\xd0\xff3\x99\xd4\xe7\xb65\x19D\ +\x18\xfa\x9d\xa9)\xfdy\x00A\xa4\xb7`\x10FF\xd4\ +g\x8f\xd6\x04\xd1d>\xfa?}\xfa\xb3&A\xdc\xdb\ +\xc1 45\xa9\xcf\x8bj\x10\xc4\xe2\xe3\x0cb\xfb\xb8\ +1C\xeb\xd6\xd6\xae\x8d\x1e]w\xf8\xb0A\x13\xe0_\ +\x01j\xc2\xabgZ{\xa0wj\x1b\x0e\x1f\xd4\x7f\x92\ +\xed\x87\xe4\xcf\xa3\x975\x88\xfa\xa2\x9a\xf6\xa8\xd5\x18+\ +\xa2\xc1\x86\xe8e\xdeM\xe3w\x5c>1\xe4\xb9\xd9?\ +\xb5/\xd5\xb09p\xd0\xccP\xe5\xcc\xe5'\xdb\xa6]\ +\xf3h9\xcd\xac\xd6\xf8I?\xaf\x98\xaeh|\xd9P\ +\xc9\xac\xf9 \xb7\x05C\x0f\x8c\xaeU\xbf\xc5\x88\xc6\xcf\ +'\xef\x98\xda\xff\xf9\xf1\xd0eg{t\xeb\xb4\xeb\x80\ +\xf1\xf6\xe8\x87\xcf\xb4\xe6-{\xa4\xd75\xd3\xa4k&\ +\xa7\xbb\xe9\xf4\xb4\xf4w\x09G3\xbb%\xe4Y\xfb\xe9\ +8=>~\x8c\x11\x9c\x909\xfcp\xc8\x94\x93\xd7n\ +\xae&\xec\x08\xe7\xd9\x8c\x98\x06\xdc\x97\xdf\xec\xdb\x11\xe4\ +\x1b\x87\xa0\xd3\xe4\xda9\xad\xbf\xec\xdb\xdf\xe9\xc8I\xf4\ +\xf7\x1b\xfcf\xbex\xc3\x08o2\x83\xe58%\xcc\xe4\ +\x95C\xb2r\xfb^.\x8765\xaa\xa9\x1e\xae4\x17\ +\xfd\xdd5}\xb3\xb6\x9e\xb7\xffG\xf4\x9a\xb7\xd4\x8c\xd8\ +\xca8\xa1j\xa5z9)\xf2HC\xe6\x05b\x01c\ +\x94\xd7\x83\xde\x87\xdc\xd5\xffk\x14U\x83i\x7f\x98\xac\ +=\xfda\xea\xfeN\x1a~\x1f\xfe\xc7lG\x98\x18\x07\ +\xae\x8a\xf9A\x84\xa7f5>=\x99\xd3\xe9g\xc6^\ +\x83\x8e\xcay\x8c`e\x83[ut\x9a\x10hns\ +\x88\xd9\x03\x97~ip1\xae\x1d3uJ\x9c\xee\xc4\ +\x08\x95\x8b\x87\xe6)\x99\xea\xdd\x0c\x22\xbc\xe2\xd6\x0c?\ +\xbc\xcdc\xd3|\x22\xba\xff\xd2\xbf\xdd\xdc\xd4'n\xcf\ +`\x9c\x9e\xca\xd1\xf2\xd9\x11\xdd\xc9\xac\xd9Ym\xb7\xd3\ +*\xfdg\xbe\xd1\x1f\xd7\x0b&\x16\xcd\xfc\xdb\xf5Dg\ +\x15\xaf\xa5i\xbbl\xfa\xefh\xd7\x84X\xa7\xe7\xa0\xb3\ +,\xf1@@\x07e\xad\x89\x8b\x9dM/\x12\xe1C\xb3\ +S\x1d\x1d\xd7\x7f\xb3\x1c\xcb\x989i\xce[\xfd\xc3O\ +c\x996\xcd\x99\x1bV\x92k\xbc3\x0e\x14\x9cd\xa4\ +\x05\xf0N66\xf8\xa0\x14\xde8\xed\xd3\xa3\x80\xec\xbc\ +A\xb3\xae\x13^\xdd\xbc\xf5\xd3\xe3\xcevd\xbex7\ +\xbdN\xf0K\xf3x\x83\xd4D\xe5\xb4\x1b\xb3\x1a\x0fz\ +\xf7E)\xfcBN\xca\xc0\x19\xb7F\x0e:\xd6n\x91\ +\xd7\xc6\x83f\x9d\x17\xadW7]\x9eA\xd6\x99b\x7f\ +vnH\xf8te\xbb\xd5w=,\x18\xa7\xc7\xa6^\ +\x0b\x1b;i\x96\x9e\x8f\xa6\xd6-\x96\x8aE-\xf4\xb0\ +\x0f*\x84\xc9\xa6\x9d\xeb\x9cr^\xd7\x8b\x19\x1a\xf8b\ +\xda\x8b\x0c\xe2\x87\xb3\xd7\xe7mo\x13\x0c\xce&~\x8e\ +b\xedv\xefP\x97\xe0\xd6\x9d\xe9\xcd\x1e\xad\xe9\x17\xa9\ +\xe290\xf8:\x81^\xfe\xbf-\xee\xcd\xcd\x87\x13\xde\ +\x19\x0d\x8e>\xb9\xaei\xd4\x97\x98\x96\xbf\xbd\xc3\x9c\xe1\ +5\x8fh\x13\x979\x83\x0e\xfd\xafo\x8dQ\xea\x84\xdd\ +\x87\xb8M\xcf\x1bo~\xbc\xb4\xd3\x91\x9e\x83\x17=\x99\ +`n\x17{\x7f\xcf\xf5\xa8-\x8f'\xde]f\xb3\x9c\ +11G\xb9\xed\xb4/\x1f;\xd9\x0dv\xea\xd3J%\ +&s\xc8\xa9V\xcb\x8c\x89,\xb5\xf5\xf6*kR\x9b\ +\xef\xf7&:\xd6\x98\x90\xcd\x99\xdf\xb5\x99\xaa\xbf\xc6\x14\ +\xfb\x16\xed\xec\x16Y\xb9X|f\x9c6\x09\xe9\xd3\xc1\ +N\xc5\xa9\x8f\xe5\xed}\xdc\x1a\x89\x89J\xde\xd1c\xdd\ +\x0e6L\xd4\xd2X\xe4\xa6n\xa5\x87^\x7fi\xd1\xd0\ +\x93f\x1b\x8f)\x9bF?\xf3\x1e\xcb\xd6m\xf0j=\ +;\xf1\xfd\x22\x9f\xf3\x9d\x98wW\xe5\xa6F\xa4\x1et\ +z\xc2^xs\xc6\xee\xa8\xd7*1+\xb9\x83\x96x\ +^\xdc=E\x97`/\x09\xea\x1a\x91\xba\xdb\xc9\xb0\xd7\ +\xc4\xa7\x87\xe6\xde\xf4!B\xdd\xa3\x9b\xfc5\xd9=\xd1\ +\x7f\xfad\xe2\x87\xa3\xbaYD\xea\x0e\xa7K\x11\x93\x93\ +\x991w\x1d\x99l\xeb\xe8\xe8{\x8bMZ\x18\x0c\xef\ +\xdfTs\x94K\x81\xde%\xdd\x1a\xce\x1b]\x5c\x1f/\ +\xfep\xe6\xcd\xe7\x1d\x86\xb7\x08\xdb\x5c\x03k\x9f\x86\x86\ +>J\x97\x163f\x12\xedM\xf6M\xbc9\xcfu\xf4\ +\xbac\xb9\xf9jw\x0fu\xb0k\x15\xb9y%\xd7k\ +\x15\xc95y\x9bk\xd43\xa8]~#'7\xbb\xba\ +\xfa\xb3RL\x0e\xd5%\xec>\x9e\xe9\x14\xb6\x7f\xe8\x00\ +5\xcd\xa6K<\x0bR_v\x9c\xdf\x84\xf8\xb6\xca\x0c\ +\xd1\xa9z\xfb\xf4\xddj\xee\xbcy\xee\x9d\x82\xa7F\xb4\ +6h1\xf1\xa0\xd7\xd3\xd6\xca\xa6\xb33\x1d\x86\xf8G\ +\x0e\xfaoG\xd7u'y\xa6~\x8d\x82U~\xd6o\ +\xb0\xefb\xa7\x83\xec9~\x84y\xa6\xebc\xb3\x11o\ +\x7fj(\x99F'_\x18\xe9\xef3\xe8\xbfK\x9d\x02\ +-\x83.LRg\xaeqh\xb1\x86}\xda\xf2\xf01\ +U\x9dC\x9dZ\x87\xed\xd8z\xfc\xaf:y\x9a\xb5\xba\ +\xc5\x9e\x0b\x0fX?(\xebvN\xe6\x84\xfaa\xban\ +=V\xe6\x9b\x04\x8dJ\xd1?\x196g\x95\x9d\x86'\ ++ b\xf9\xf6\x7fB\x88\xd0\xda\x0ei\xb3\x88\x1f-\ +\xb7\x98E\xb8\xb7Z_\xc7\xa6\xe0\xaf\xba=\xbe\x9e\x9b\ +\xa7\xa6Y\xb7GB{\xfb@rJ\xeb!\x9a\xcf\x02\ +\x9f\xc4\xed\xc9\xee\xdbj\x7f\xefa\xad\xd6\xb8u\xde\x18\ +e\xb3*\xf4\xad\x7f\xed5u\x0c-\x19uF\x1e\xde\ +{\xf9\xafZ\xdd\xe6\x9c\xfe\xb8\xe7\x80\x01\xc7i\xebq\ +\xcd\xba\xa9\xbe5#\x93\xa2L\x98\xc3~\x04\xab\xf5\xef\ +\xe2{\xf0\xe1'\xcf\x0e\xb3\xda\xac1\xf2=8\xb8\xd7\ +\x01\xcf\xcc\xbf=F\x84\xb4\x9d\xd6d\x1a\xa7\xa3qG\ +\xb3^\xff\x8b2_\xaenYOoH\xab\xff\xd8\xc3\ +\xd3\xcek\xfd\xc8\x09j\x5c{\xe5\xc8\x7fG\x91\xb7v\ +\xf9\xb9w\x98Q\xf3\xad\xf1\xae\xda\x0c\xab!\xfe6\xb3\ +\xfe\xfb'h\xfd\xee\xa5k\xbe\xdb\xb4\xd9\xd6\xbe\xc1\xe2\ +\x89\xbc\xe4SV7\xae\xbb\x04\x1d\xbco:\xcd,:\ +\xe4Y\x5c\xa3f\xe4\xf5\x87FF/\x8f\xde7\xf9\xa6\ +l\xea\xdab\xd1\xe1N'?\x0e\x1e0\x1aM*\xbc\ +\x81ehp-\x870\xfb\x1e\xc7\xef\x1d\x1b\xf6\x83\xe8\ +t\xb2^L\xc4O\x02mL\x1f\xde|\xf5\x03\x99\xc7\ +\xef\xf4\xdb\xb58\xd5\xd9+\xbb\xc96\xa7\x86\xb7\x08\xb6\ +\xdb\xc8\xef\xdd\xef15^Yu\x1d\xb3\xba\xe0\xaf\xbe\ +W>\xc7{\xfa5m\xda2M\xa7\xaf\x83\x81\xb6e\ +\xe8s\xab\xaeh\xca\xf7\xbfq\xe0\x95\xdb\xfd\xdc/\xdb\ +\x5c;qI\xe3\xc3\xbd\xb3\xa9*\xc1\x06\x11\xee\xd6\xbd\ +\xe6M\x0aL\xb0]\x19\xa2l\xf1\xcaH\xf9\xf4\x89}\ +\xbc)\xceY\xbes-\xdb\x1d_\xfe\xf7\xb8\xd1\x19\xab\ +\xcc~6\x0aNd7\x8b{\xdd\x94\xa2\x9e\x0e\xedg\ +\xac\x08\xb2\x0bZ\xec=={\xf3\xf1.7n[\xfc\ +\x9b\xff9X\xab\xb3V\xd3%!yY\xaa\x8e\xa7\xd7\ +\xd9\x85.o\xa8\xc14s&'9\x10G\xdcoG\ +[\xae\x9e\xdfy~\xcc\xe6\xec\xab\xb1\x8d\xf6\x853>\ +5\xe9\xfbL\xdfc\x96k\xfa\xf1\x05\xfaA\xb9\xb3\x03\ +l.N\x1a\xf7i\xb9\xde\x8f\x9c\xa8@\xe3\xf3\x7f\xad\ +\xde\xec\xfcQ\xab\xbfU\xca\xeb)\xcec\x97[9\x9f\ +\xbe\xb3:\xf0\xc5\x05\xe7F\xa6\xae6\xdb\xdd\x1a\xe6|\ +T\xf3\xe7\x8e\x18}tp\xc8\xf3\x13\xbcK!\xa6\xbe\ +z{\xfc\xf7\xcc\xb5\xb6W\xff\xfa\xba\xa9\xce\xc8v^\ +\x1a\xc1\x13[\x12\x1f\xdcG\xb6\x8cuxD\x0e\xf5\xaf\ +\xf9w\x17B\xbbkD\xf4\x8e{_\x1a\xa1\xa7\x99\xcf\ +\xed\xde\xd2L\xe7\x8d\x8fr\xea)\xd5\xa4\x03\x9dvm\ +\x9e\xac\xaeV\xeby\xf8\xca;\xc3\xfdk\xeen\x5c'\ +\xcfje\x9ef3\xb3\xbeK\x0a2\x16>\xccf\xdc\ +A+\xea\xbc\x5c\xbe\ +\xd9jaV\xcd!l\x8d\x16\xf5\xaf\x9f\xef\x9c\xb4Y\ +\xc3\xd5\x8bXZC\xb9_\x1f\xffu\x91\x99fJ3\ +\xee\x9aeg\xcdoyF9\xbf\xb5+\xb3\xbb\xf9\xd4\ +w\xf3\x8d<\xb7\xec\x1d\x96\xd2\xd6,l\xddn\xcf\x19\ +\xdd{\xdcF\x13\xeb\xfb\xe8\xf8\x8a\xa5\x89^\x06\x015\ +\x0e9\x04\xb48\xd3f\xe2\xf7\xb7\xedU\xee?\x8b\x9b\ +\xf2YoV\x0b?O\x1b\xc2J?|]K\xae\x17\ +\x22L+^J\xd3\x97[\x98\xf1f\x84\xe7\xdd\xe0!\ +\xfa\x08\x95\xce\x0fI\x8e\xf2\xd8+\xbeQ\xddN\xe7f\ +\xdc\xfc\xd0\x95\x810\xbc\xcf\xc5iV\x03t0\xc3\xb2\ +\xe7\x8d\x88\xaes\xd9|-1\xe95\xd9\xc3\xf1\xda\xbe\ +!^\xc6\xf5L\xb7\x0e\xfb\xc1Lx\xab>\xad\x19\xb1\ +z\xcc\x8d7\x13\x8fN\x9e\xadN\x10\x06\xef\xebz\xef\ +\xeab\xfc\xc3E\xd3\xfb\x1fB\xfb\xfd\xfc[Sv\xf5\ +\xe9\xe5\xb9\xae\xbd\xfe\x93\x8d\xa63\xd6\xb6\xab\x81\x84B\ +o5\xefYw.\x05\xd5\xf7\xfcR;\xed~\xe3\xf1\ +\xddf\xd5b\x8cT\x0e\xbe\xc23\x09\x7fg\xc6\x89_\ +z\xd3\xb5\xd1\xeb[\x91\xdfW2Vg\x0e\xa8y\xfb\ +\xac\xca\xde\x17\xdf\xb4\xfdwz~Q\x22|:\xde\x7f\ +lo\xa9\xc1x\xaa\x14\xfc\x82\xe7p\xce.o\xb3\xbd\ +\xb3\xcb\x93u3\xd9*6J-k|2\xd6]\xfa\ +/a\xecN.\x1f\x17\xf8wp\xc7\xfb\xff\xf9u\xab\ +\xd1!\xc0\x0b\xfd\xc2\x95\xec1k\xbe\xcb\xacU\x17\x06\ +4\xf0\x990ud\xfc\xd2\x85\x87\x16\xddn\xb2f\xc8\ +\x9e#\xab\x17\xed\xac\xdd\xa1`JO\xf4%\xdb\x8b\xb6\ +\xea\xc1\xef<\xc3\x13\x0f=\xb9\xb4\xc2*\x81u\x92S\ ++\xe8f\x8d\xcb\xe3\xc7|\xfd/\xd6z\x9b\xab\xf1\x1b\ +\xc4/B\xef.\x9a8\xf7\xc6\xf4\xae\xd3\xea\x13\xab-\ +\xdd\x16\xbf\xd5\xb1oq1g\x14a\xfe\xbc\xd1\x9c\xd0\ +\xae\x7f\xbf\x0e\xb28jm\x9c\x10\x10lK\xae\xecR\ +\xcf@\x97}{\xf0\xb2s\x93o<\xd8\xfa!mn\ +;O\x0e{\xdf\x12\xf8\xde\x95\x99]\xcf\x91\x1a\x8bf\ +\xec\xbdz%\xb5\xdd\xcdv\x8b\xae\x9d\xfa:\xfa\xc8?\ +\xf1\x81\x1f\x1c\xbe\x7fIdwj\x93\xb0&s\xc6j\ +\x8d\x9c[\xe6?\xe6Y\xbc\xecg\xb0\xf5^\xee\xe1M\ +\xc6\xeb{\xc7\xe7\xd5\x1d\xea\xb5\x98a|\x99\x5c\x8e\xb8\ +\xa1f-\xbf5\xdb\xf4]vG\x1e\xfb\xf7S\xe8\xb3\ +\xb8\xee\x9b&\xf6\xab\x93s+.\xe3\xa2\xe3\x08\xe7\x95\ +\x93\xdak\xa5\xc5\xbe\xf81\xe7DP\xc1\x10\xff\xb6u\ +\xaf]V7W\xbb\xc1&U\xdf\xf8\xd6\xf4L\xf0\xe7\ +\x9dq\xbd\x92ek?2,`r\xaf\x03!\xdf8\ +m\xda$\xf4\xe8\x12\x9e\xfc(~\x22\xc3\xdd\xc4q\x80\ +\xf2g\xfbG{\xd4\x8e|\xf9rs\xe5?\xef\x92z\ +\xbfWWIq.\xb8\x98\xcd\x1e\xf3b\xf9\x5c\x8e\xc1\ +\xc2\xa4]&\x88\xb1\xbal\xff\xa7_A\xce\xd8\xd6\xd3\ +\xdb\xbdq\xaa{\xb3\xe7\xa5\xf8\x09\xcf\xb2\x08\xef\x1b\xa4\ +\x09\xf7\xb8\xdf\xc2\x84\x8bw\x1b\x11\xe3\xe6\xf5\x0a_\x82\ +\xb8\xbd\xb1Cn\xdd\x17\xd1v_\x9d^~C3\xfa\ +\xd9\x22\xf29\xa7\x11s`\x01\xc9\xcc7\xab\xdd\xdev\ +\xf1No\xc4k_|\x19\x13\xfb62z\xc4\xd5H\ +\xe7\xad\xc7\xbb\xe4\x0c>n\xd3%q\xee\x12\x02\x11\xff\ +G\x7f\xc2\x93\xb5\xfe\xd0?K'\xbb\xd6\xcb\x8a\xeb\xca\ +hp\xa3\xc9\x89\xc0\x93\x13\xfcgX\xfd\x9c\x14\xbcO\ +c\xd9\xd1/J\xb7s\xd2:\xb6I\xf0\xed`\xb2\xea\ +\xd1\xa5\xce\x8e\x8936\xfb-\x1e?\xba\xa3\xb3e\xff\ +\x96\x8f\x1e\xce\x083\xde\xf8x\xf1(\x8b\xb1\x8dv\xff\ +Pz\xdb\x89g\xb4\x94\x17t$\xd1\x8c0Ug\xb8\ +\xa4n\x9d\xa2M.V~\xbd\xf3\xe3\x88+O\xf5\x92\ +,V|\xeaY\xef\xd0\x95u\xaf\x1a9,\x8b{2\ +H;\x90\xe4\x05mp\xb0\x5c\xb0\x22 \xb6\xdf\xc9\xc9\ +\x8d\xdf\xd7\xd2;\x15\xe5[sd\xab5i\xef}Y\ +#\xb6f\x9f|\xd52b\xb0\xc7v\xaf\x96#\xb6\x7f\ +\xabW?\xec$g\xb8\xd7+\xef\xd5\xadr\xc3\x1a\xf0\ +\x8e}\xb7\xf7J$\x9b~?\x14io\xd4\xd6v\x9c\ +Wo\xd7\xcdHrd\xae\x89\x8ey\xf1\xe3/\xf7\xb7\ +u\x17\x05L\xd6{\xe6\xbbi\xb2A/\xb7\x99:5\ +\xd1~\x9fH\xca\x99\x17\xb39h\xae\x8a\x0f\xbb\xd3I\ +t\xa4\x1b\x10[4\x12\xee\x84\xbf\x1c7i\xed\xa0O\ +c~\x8e\xaa7\xb5M\x04\xbb\xd6\x04\xaf\x88\x87aM\ +\x9b.\x99GD\xce\xbb\xf2\x83\xb1\xd3z\xa3\xf9d2\ +Z\xff\xe6\xe0#]\xea\xf6\xcc5\xdcy8L\xb7\xd5\ +\xfe\x80\xdd\xd3\x82[&\x7f\x08\x09\x22L\x8fjZM\ +h\x8f\x94\xc6\xb6S\xb4j\x866\xfc\x1a\xd6\xe0\xad\xc6\ +\xf5wo|\xff\x193\xd8>\x7f]\x8fh\xed\xb3l\ +\x8fFJc\x16\xab\xb4\xd5%\xb6D\x1c\x9d\xc9c\xd4\ +\xf7l\xf2|Y\xd7\xa1G\x1b\xb0u\xb9\xf1K\xbd\xce\ +\xf6\x9e\xe3\xfdj\xf1\xa4\xda\x8c\x0b>J:\x0d\x88\xd5\ +K\xff\xd3arW\xf7\xf4=\xff\xa5\x85\xb6\xe5\x84\xb9\ +a>\x0d\xa632\xa6\x0e\x1f\xff\xc6\xf2\xafP\xfb\x80\ +\xe9\xce\xef7&\xf4\x18\x10\xc7\xaa\xd1\xe2\x8c\xf2\x93\xab\ +\xea\xe6\xc4\xc1\xf1\x96;\x8dr>\xbeY\xb89\xf8\x00\ ++9b\xf0=D`\xaa\xcc\x06\xad\xf7\x07$\xf9\xf6\ +\x9e\xd6\xc2\xcfq\xc6D\x87\x9d\x9d_\xea&Y\xf4o\ +\x15\xe9\xb6\xccs/c\x5c(\xa2\x7fD\x0c\xc3\x1b;\ +j\x1bu9\x1e\xd6y\xe0a\x9b+A\x93\xdf\x8f\x1e\ +\x18\xf9\x99\xd8\xf3\xb8FT\xb3\xbb\x7f\xeb1u\xf3\xb3\ +Ng\xcdo\xbb\x93az\xe5\x96\xff\xdd\x9d+b\x0d\ +j\xee\xbag\x8a\x04\xc4\xe3\xec6\x0b\xba\xc6}\xed\x91\ +\xd0\xd0B\xc5\x88x\xdc\xc0m\x06\xc3\xb0\xaf\xf7$'\ +\x86\xe9)\xa4\x02<\xfc\xc69\xf4\x8e\xd5\xd4\xa0\xcd\xc5\ +\xad\xe8\x17\xcd?\xd76\xce\xbd\xc8\xa9\x1f?\xb7\x0e\x91\ +Q\xc7\xc2Q\xdbo\x0as\x87\xf2F\xf4\xa1a\xd8\x14\ +\xe6\x8aE\x97Fh\x11\xdf\xda!\xfa=\xdbU\xe9\xd2\ +M\xa5\xc8\xa6.\x9ai?\x12\xc7\xef\x8b\xea\xb6\xda\xa7\ +\xf9\xfa\xcf\xeb\x0f\xfd\xe5\xe9d06\xcfe\xdd\x80\xf0\ +L\x86y\xd2\xc8\xb6\xfd\xaf\x9b$\xce\x0f=\xefS\x7f\ +\xac\xfa\xa5\xd5W\x1c\x13\x02\x88\xfd\x13\xbb\xe6\x9e\x9a\xef\ +\x16}w\xe1\xf0\xcf[&\xf7\x8e\xba\x97\xc9\x08_9\ +\xb3\xcd\xbe]\xa3\x07\x0e\x0b\xfd:\xfb\xdb\xf4\xd9\x86^\ +ji\x1b\x88avZ]w.\xe3\x8d\x1c\xd1jM\ +\x07\x93\xc0K:./V\xc1o\xb3I\xaf/\xef\x8f\ +\xe4\x18tk\xaa\xd9\xf3\xfc\x0bc\xe6\x05eS\xeb1\ +ow?\x1f}\xf1\xfa\xcf\xe8\xff\xa6\xcf\xd9\xb7\xb7\xd7\ +\x9b1'\xf7\xd7\xdc\xcb\xd6ws\x1d\xd5rWd\xc2\ +\xe9\x88\xe9\xc4X5\xe6$\xd2a\xf7s\x87\xd6n]\ +{^[AL^\xa0\xd4G\x97\x18\xba\xa5\xdf\xe6\xc3\ +:\xdc\xa9['\xb57u9\x8a\xfe\xc84\xeb\xf6\xb3\ +m{\x87]\xf2\xeb\xef\xd6\xd8\x8b\xf73\xf9\xe5\xfd\xd7\ +\x0c\xfd7u&\xae\xda6\xad\xf3\xba\xe6\x91J\xe3\xe6\ +\x1b\xeee\x98w\xadG\x5c\x1a\xbc.d\xdc\xe2S\xf5\ +\x88\xc9\xec9\xad\x1e\xb1<\xbb\xf4\xd5%\xea\x1b+\x9b\ +\x12FV\x9b\xcc\x88\x16\xadm\xfdf\x84\x12\xfa\x19F\ +\xaa\xcc\xe7_l7\x84o\x8f\xbcOx\x1f\x8dR;\ +9\xacc\x1d\xa2\x85\xc6<\xe2\xdd(\x97n1\x83\x08\ +\xe5\xe0\xd5}g\xae7\xad=\x87\xd0\x5c\xab\xa5\xcc\xec\ +3\xf6fH\xaf\xa4\x07\xe8OG|\xec\xbfo\xc8\xdc\ +yZ\x17\xedj\xeeX\xdb\x8bh\xd5\xac\xc6\xf8\xc5\xbd\ +\xdb\xd6\xdf\xd0b\xd2\xbeG{\xfbr-\x0e\x1e9\x90\ +k\xbdr\xe2\xe0Y\x0e\xfa\xcf\xd0\x147v$n\x0e\ +S\xc9\xd0KRz|`\xba\xcb\x85\x88\xf3{g\xe5\ +\xee\x1b\xa7\xefy\xbd\x9d\xf3\x05e\xfd\xc0v7:E\ +\xb3\x9e\x8fq\x19\xd6\xf7\x90\xe7\x93!\xad\xd0\xb4/>\ +\xef\xb9~sN\x0b7\x8d\xe17C'\xadm\xf3\x00\ +=\xc3\xe5~\x92\x92G\xffK\xad\xcf?i\xa8\x1f\x93\ +Nh\xf6\xd66\xb4a\xde`\xd4\xde[{\xeed6\ +\xc9|\xa4L\xec\x1d\xf9\x15\xe9\x19?}S\xd6\x0e\xd4\ +{\xbaA\xd5\xd0B=!\x9f\xd8\x9b\xb8\xf3\xe4\xa4\xff\ +\xc6\x1a_\xad\xad\xbaanGb\xf2y\x82\xa1J\xd4\ +\xbf:_\xc9\xdc\xdbw\xcb\x1eUu\xed$\x8b\xbf\xd7\ +[LVE\xbff\xbe\xbb\xa7\xc9L:\x1c\xceza\ +g\xb82\xf9\xf5Q\x1de\xd3\xd6\xfb\xf5B\xe3'\xaa\ +\xb9G\xdf5@\x8a\xe1)W^W\xdb~D\xab\x06\ +=\xb5-\xbf\x9f\xd5g\xec\xbf\xe7\x19A\xe8\x07\x13\x84\ +~@g\x0e:&?}S\xdb!-\xb0%\xd7\x9a\ +\xa1\xff>\xbe\xc3\x16\x06\x11\xb3\xc5\xdcpO\x96\xaf\xf5\ +h\xe6.\xd5\xf53\x1e\xaa\xce~}\xf4\x84\xf5\xb6\xbd\ +\xc8\xea\x7f\xd6\xc1r\xe7]\xde\xbbq\xc7\xb3Z\xa7\xd5\ +\x09[\xea5=^M\x8bX\xbb\xbfy\xf0\x14f_\ +\xa4M\xec\xe8\xb7\xbb/\xf7x\xd2\xae\xf3\x0dU\x99c\ +\xd8!s\xda\x07O\xbf\xc7\x1c\xcb\xd1~\xd9\xc1r\xf8\ +\xec\xad\x1aF\x84M\x84\xde\x8ba\x0e\xed\x17\xd6\xe8`\ +\x93oc\x9a\x95br\xe3\xb6\xd7\xb3\x96\xc1[\xb4\x08\ +\x7f\x9b6\x06\xfd\x1a!]jo\xd6|+\xf7a\x1e\ +\xb5\xba\xc4\x06\x04\xd9\xa8\xdf\xd0Q5e\xfc\xd4X\x8c\ +\x14\xef\x91\x17zv\x5ct\xab\xf7\xb9m\xee;\xf5\xbf\ +\xdc\xef\xb0\x8d1\xcet\x8b\xc6\xe2e\x1e\xbb\x947\xb5\ +\xf1\xb7\xe9\xa5\x7f\x97\xdct\xe9\xb9\x03\x93\x91v\x0a1\ +\xc0\xb0\xb5\xef5k\xaan\x18\xf1\xe9\xda'\xfd\xfaK\ +\xea\xeb\xe5)3\x1f\x05-\x1b\xd1\xf8L\x07U\xd3\xbf\ +\xfe\xeewy\xa3\xa5I\xe8\xdd\xbdd\x5c\xaf\xcf\xb9\x87\ +w;\x99\xac\xf0\xf3\xbfk\xd0\xef\xd6\xa4Z\xca\xa7\x1f\ +\x7f\x9a0e\xbbZ\xf7\xb9\x03-\xe2FO5\x08\xe8\ +\xban\xd0\xf6\x7f]\x86\xabX\xb6u1\x22F\xdc\xce\ +\x1d\xb5K#\xb9`d\xff\xd6w\x1f\x8c\xe9\x1a\xe1\xa0\ +\xd9\x92\xbb\xa4\xcf\x12\xbb\xe5HC\xdc\xbcC\x8bh=\ +\xea\xc5r\xc3.\x8b\xe69\xab\x0d\xeb1\xef\xe4\x7f\xde\ +\xbe\x83\x8fv9\x18\x96\xdf\xb1\xf5\xdd\xa1\xe8\xdbO\x8e\ +\xd8\x9e\x1fb=4\xe4\xb9\xadMv\xdb\x81\xa7k#\ +\xbd;\xc5\xb9\xd9\xbeNC\xbe\xe4em\xb5\xf9+\xe7\ +!\xd1\xf6\xeb\x97eC\x8ef-\xa8\x994\xf6\xe6\xd2\ +\x7fz\x06\xb9G\xa6\x04\xc5\xa3/\x0e[h\xfd\xc4G\ +\x89\xc8\xbe\x1bc8>\xfd\x83ql\x0a\xdaJ\xc3\x09\ +\x17\xff&<\xf2\x07\x1f>\x1f\xd7m\xc5\x93\xcfz\xe6\ +\xc4\xa4\x83/\xbe\x1d\x1ci\xfdU\xfd\xe5{\x86\x85\x0f\ +\x19\x96\xbd\xda\xdd\xd0$\xe6D\x80I0\xf1.\xea\xc1\ +\xb2!\x17\xcf\x9d`\xaei\x1e\x13\xbfJi\xdel\x9f\ +v]?\xccn\xdb/0\xf6\x08\xfc\xb3\xc7\x13\xaf\x8b\ +\xbe\x11\x83\xf3L\x8dbB\xcey\x0e\xed\xeb;7\xdc\ +6:bl\xae\xcb~\xf4D\xd7\xdc\xce\xa1\x84\x07R\ +\xecn\xed\xff\xd8\x93\xf1a\xc7\xbd\xa1S\xf7\xac\x8bc\ +\x9cE[x*\xbaf\xbb\x8f\x19~\xdd\xb2}'\xcc\ +\x1b\xf2\x06\xcd\xe0\xe7\x87\x10\xdf'\xf6\xb7\x91\x98\xe9\xe3\ +\xf7%\xe5\xc3\xd0\xed\x8e\x0c=dCL\xb0\xf4\xbe\x1a\ +\xfeiB\xa3\x03\x99K.\xeb{\xa9(\x9f\x1e\x81\x98\ +\xdd\x88\xd1\xea\x8d\xda_ne\xb9\xa4\xaes\x96\xde\x83\ +\xcc\xa6\xcd\xe3C\x92?\x0c\xcc\xf6\xdf\x8e\x1e\x14i\xce\ +\xb9P\xb7u\xb3\x86\x97\x06-m\xa3\x17rr|\xbe\ +A\xac\xb6\x9d\xde\x9e+\xcdV=\x98\xb0\xe8B]\xce\ +\xdfs\x89\xc8\xc7\xed\x86\x9b %\x1d\xc9\x01\xad\x82\xb3\ +\xa3\xf3kOz\xec\x917\xe6h<\xd2W\x8cx\x07\ +V\x9e\xe7\xee\xe8B,98,%\x06\x09\xfb\x88\x87\ +\x1e#\x8cb\x06.\xf3\xa8\xbb\x93\xccWC\x9b>\xde\ +\x7f)\xd2\x9f\xe3\xaa*\xf7\xcb\xfa\xe1\xd0\xc3\xfar-\xa4T\x0f\ +\x1a0z\xf7\xb2\xb7\xa9\x8f~\xe4\x8e\x5c\xe3\xfa\xec>\ +\xb1(\x1c)acN\xa5\xb5\xbf\xa1\xe2r\xd4\xd9\xb4\ +\xad\x0e\xcb\xa9\xee\xf0\xc3#\xde\xbal\xf7\xf9Z\xc0\xdd\ +\xf2\xa9\xf1+\xa5+}9#\xdf\xbb\xdf\xff\xef\xd4R\ +\x8dh\xff\x94\x95\x0b\x88#\xdf\x9e\x0c\x9a\x9e?x\xc0\ +\xa4 D\xa8\xedUagG\xcd\xadS\xfb\x7f5>\ +-\xb4\xb6\x7f\xfaj\xa7\x9d\xe1\x1c\xe2\xc8c\x0b\xe5A\ +n\x93yK5N\x06\xbe\xbbP_\x95\x196%j\ +\xcd\x0a\xa4\xf7oe\xaa\xdf\x0e\xccP\xaeC\x8cDS\ +\xae\xc3\xd8\x969 ^\x0d\xd91#\xfc\xf5-\x0f \ +\xec$%7|TC\xe7qK\x17\x13\x95;\xeaL\ +r\xc4\xe1\xd0]\xce)\xc4\xc0\xe0\x9e}&\xe43\x02\ +_\xdcP7\xef2ou\xb0E\xe6#K\x9b\xe4\xd8\ +\x19W'\xf1\xfa\xb4$\x1a\xb9\xa9\xc7-\x18R\x13\x1d\ +\xb6\xe1\x8d\xb7\x8c\x08_\xb0<\xe2\xca\x89\x84\xab\xe6\x8c\ +\x18-\xa6\x17\x9a\xfc\xd3.Mw\xd8>D\xa6'R\ +\x05\x1d\x8f>\xb4\xf8y\xf6]G\x15o\x15\xf3\x80\xb0\ +\xfc\xd1H\xa1\x8b\xab\xb3Q\x09\x99M+rr\x5cg\ +\xe9\x9e\xfb\x97 fw:\xec\xf82a\xe0\xc2e\xc9\ +c\x89\xe4\x08\xf7\x8c\x1d\xe6\xc1\xdbR;\xab\xe8\xde\xbc\ +\xe8t\xfc\xc1\x85\x1e3\x03\xfc\xaf\xd6\xbe\xe8b\xfb\xe8\ +\xda\xccN\xb9_\xf4c6\xd9\x5c\xbc\xf3@\xab\xb1\xd5\ +\x93\x9c\xb9\x96\xd7\xfc\xefn\xbb\xe1;q\xd6\x15\x8ei\ +\x7f\xb3\x85D\xcd\xe3G\x9e[\x052G\xfb,M~\ +\xdf\xc6\xe1\x8c\xca\xd7\x1e[\x18\xc17\x89\x01\xce\x83\x07\ +\xaeP\xd35\xfc\xd9*\xd4\xd4\xb5\xc1\xd8\x94k\xc3\xee\ +^\xb9\xa1rzo\xbakw\xa4\xe09X?gn\ +GV\xb2\xf1\xfa\xe3Q>\x8f7\xa5\x1f\xe7\xe8\xeb\x13\ +\xf5j\x18\x22\xf6\xa1\xd2c\x9bF\x80\xf5\x8c\x8e\xbd\x9f\ +u\x9c\xbf\x02-\x7fj\xf2\x97y\xfb#G\xdc\xf9\xaa\ +E4\xd4PR\x0a\x9e\xf83b\xdf\x82\x05+\x9a\xba\ +\xda\x05\xecF6\xf4q\xafnGf<\x89\xe3|\xee\ +\x01\x8ap{\x87\xc5c\xd5\xc9q:\xc4\x8d\x08\xf7s\ +\xb9\x8b?+\xa9\xde\xb3\x9f\x12\x95k\x85\x9e\xd3)\xe0\ +K\xf4\xfaUwn\xab\x87\xab\xc4\xac\xf9Y\x7f\xc2b\ +\xc4\xff\x0f\x8fU\x03=\xf7\xef\x8fK\x8f7\xdf\xf7\xe9\ +^\xe0\xc2\xe3\xb3f\x84~tr\xb8\xf2\xa0\xf7!\x86\ +\x97z\xda,\x820E[\xb4\x860\x8bpw\xcb\xd8\ +\xc4\xd0C\xa2\xa1K\xf7\xc8\xef\xef\xbblB{\xfci\ +\xfd\xa1\xd8\xcfw\xbb?m\x9f\xbe\xdbA\xdb\xe1q\xbc\ +uk_\x15W%\xcd\x03\x9d\xda\xb9\x1c~\xf1\xcd\xa8\ +\xe7\xd5\xcf\xd9>\x13W\xd7\xf3\xb7\x9e\x911\x17)\xd9\ +G\xfe\xfdt\x1f\xbd!):j\xe1\xa5<5\xf7\xe9\ +\x84\x1da\xef\xd2\xa9\xdd\x9b6Zis\xdc\xc8\xd3_\ +\xf7|2<\xf4\xe2[V\xcbg\xb7\xee\xe4\x05\xef~\ +\xcf\xbbY?u\x9a\x11o\xdcuu\xc2\xbbi\x8c\xcd\ +\xbeq\x0d\xd0\xcbu\xd60/\x9e\xf1\x8ex\xd9q~\ +\xcf\xbc\xc5\xbbs\x8f\x91\xa6\xf9\x9d\x08\x82C\xc4\x9c\xb7\ +\xd9~\xb1\x1fb0G\x8e4\xf5\x9d\xfd\xbe\x8b#\xb2\x01\xbe\xcf\ +\x9a\x9f>\xb7\xddS\xfb\xc0n\xf6m\xb3C\xac;2\ +;Yu\x0fvq6\xfdQ\xab\x07\xd2\x8dW[]\ +\xf8\xdc\xb56\x9a\xe5\x07\x86\xdb\xd55\xd3b\x93\x0f\xe8\ +q{\x1cLV\xc2\xeb_H,t\x1b9\xfa\xad\xba\ +\xea\x86\xfc\x90\xfe{T785\x8b\x1ap/om\ +_\xe7\x11\x81\x88\x16\xde\x98\xacI\x8f0^t\xd0\xc5\ +\xec\xfekD1\x09\x0fM.G\xaa\x10>mB\x9a\ +\xfc\xdc\x7f \xdby\x87\xdf\xec\xf8\xcb\x0dk^~7\ +\xa2\xe0\xca'\x87\xb6\x1f\x95\x08c\xada\xdf\x94\xf4\xea\ +\xf0\x9a\x8c\xe8\xab>.\xa9\xb7\xe6\xbe\x03\x93/\x87\x14\ +\xa8\x04+[\x85\x8ckqaD\x7f\xcf\x90\xf9\x93\xeb\ +0]l\x87\xd6^\xa6\xa2\xd9\xf3\xcd\x9au\xba\x9d<\ +\x8f\x0d\x8f5~W[\xdf\xfaXC\x1f\xff\x19\xaf\xee\ +2\x82\xa7\x10\xfbZ&\xaf\xcfU\xcb9\xaa\xd2\xf6A\ +\x13F\x8bGm{g\xcc\xf68\xf6/s\xc0<\xec\ +\x0c\x9c\xb0\xca\xcc\xcb_\x85\xb0Z\xa5\xbfO\xf9\xe0\xcc\ +\xec\xa9#\xbc:\x12\xc4\xed\xb6\xdc\x14'\x8f\xb3\xc7\x12\ +\x17\x8df\x9c6\x19e5\x92\xad[\x7f\xfcp\xdf\x1d\ +zy\xef\xc7\x8e6#\xe08L%\xec\x22R\x0f9\ +e4\x9a\x12\xa7K^\x8a\xef\x1c\xf9Z\xc5hf\x8d\ +(U\xcd\x8b-\xb6\xf4\x0aHX\xa5\xc2\xbc\xeb\xa5\x19\ +\xa04h\xc9\xed\xc9\xb7\xdfL\xed\x98\x98\xa8\xa4\xd5k\ +\xdeR\x13%\xadC\xf6\xb9\x83\x9auGH\xcb\xbb~\ +*\xe8\xdd\xb0\xc6\xc1V\x7f\xf5\x99\xb8w\xd8\x13%\xed\ +\x13G\x97\xb6%\xb2\xdc\xb7\xeah\xe8_\x9f];\xf8\ +\xe1\x92C\x05S\x22\xd2\xea\xed[\x17\xed\xc8RvJ\ +Zu\xed\x8b\xbdC\xf3\x89\xb7\x9c\xcc\xb6\xaf\x19\xb5\xb1\ +\xb9\xe9\x7f\x87w\xae;\xb9\xf4\xc8\xe2\xf5\x83\xae>\xe8\ +\xdd\xcc\xdc\xf5\xb9\x9a\x93\xc7\x1c\x8d,\xff\x05\xb5'\xf6\ +\xd8>{\xfb\x9a\x995\x062\x1f\x1bjd\xf5Z\xa0\ +\xfdz\xecv\xf3\x9a\x9a\xff\xde\xcfz\xa21M\x93 \ +\xd0\xef\xff;4\xc9>\xf8,Ah)\x0djs\xed\ +r\x86r#U\x22XS\x7f\xc9^w\x17=oc\ +\x82\xb9\xa1\xa6\xd5\x8e\xbd\x1e\xdd\x1b{]\xe10\xeb2\ +\x88o\x17j\x06\xd5\x98Z\xa7~\xb2\x81J\xcc\xc8\xae\ +\x17\xd8\x86\xd7\x92//\xb2\x8b\xbd\x9f\x10sCyP\ +|\x07\x22\xef\xd3\xe5\xc1\xfd\xdexg{\xdb\xda\xfd\x8c\ +K \x96\xadw\x1cT\xaf\x8b\x8aWF\xe7w\xf9g\ +\xeb\xf6\xad\xf7\xc9\x09{\xbcG\x13\xc9\xb7\x82\x8c\xf7\xf5\ +\x9a\x10~*a\xcfG\xee}\xbf\x99c\x10Q\x9e\xee\ +z\xeb\xadZL\xbf\xdb\x81Zk_+\x8dZ\xe7q\ +\xa1Y\x1c\xc3\xfc\x87\xb3\x97\x9d\xb2W7\xd3o\x7f\xfb\ +\xa2\xfd\x8d\x1e\xd6\xc8\xf4(A\x80\xdf\xbc\xb1\xcf\xdb\xe0\ +&?\xafk\xfe\xfb\xa3\x9dO\x00\xef\xbaM\xff\x83\xb5\ +\x01\x1d\x16Z\xc1\xc6\xb6u\x9a\xf8=\xfd\x1f\xb3K\xef\ +\xa1y\xb9\xe7\xfe#\xb4\xb2,\xefE\xc5\xe87\xef9\ +\xa3\xf6\x87\xfe'\xa3\x875v;\x12\xc1 \x08\x1c\xc3\ +\xe8bT\xf3\xf1\xda\x09\xe1c\xde\xec\xee\xe1oqx\ +\xf2A\x0d\xc2\xb1Y\x8d\xc6\xa7U\xfa\x1f\xb6Y\xebd\ +8m\xeb\x94t=\x8f\xe9\xe9uw\xd7b\x0e`k\ +\xa1\xa7\x987\xbf\x18\xdf\xce\xe7<\xef\xa0M\xffK\xf1\ +\x8f\x09\xa3\x1f7T\x1b\x13\x1bTn\xd5\x1e\x16\xfa?\ +\xa6\xde\xe9\xcf\xc9\x87\xdd\xd5'\xb6\x1f\xaaf\xda\xdc\xae\ +\xff\xab\xa9\xe1\xf5\xda\xfd\xa4\xc2\x16>\xf3\x03L\x86u\ +\x8c\xe9\xb2s\xa9\xd2\xe9\xbd_\xfe\xa7\xa5j\xa5=\xbd\ +\xc7\x193\xffQ\xdf\x16\xb5[\xf4\xbc\xe0\xdfE\x17\xd2\ +:\x8cl\xfc\xb8\xc3\x95:\xcc\xb9\xebX\xa75\x82\x0d\ +\xd8W\xed\xcc\xdb\x8e[\xdcn\xd1\xd3\x95\x8d\x09N\xe3\ +\x0f\xdb\x03\xd4#\xb6\x5c\xdfa\xa0t\xba\xa1\xdd\x943\ +\x1a\xd35\xb3~\x9a\xf0j\xd4Q\xbd:\xac\xbfg\x0c\ +s\xca\xfb\x89\xe1\x86\xebG\xf8\x9b\xaf~\xa2F\xfc\xb5\ +\xf65\xa9\xdc\xc0\xa2\x87\x91\x96\xb6\xdfr\x08[\x0d\x1f\ +\x08\x1c\x11\ +\xe8\x15\xd5\xf2\xbe\ +\xeaA:\x8d\xbbr\xdb\x05\x02\xf8\x07\xbb\xa2Z\xcf\xaf\ +\xba\x10K\xe3Pb\xfc\x0b\xe0^\x8fUm\xdf\xff\x0e\ +\x10\xc2\x12\xf0\x11I\x88{\xf0+\xeeV\x80\xb9W\x83\ +|`7K\xc0W,\x01\xfe\xc1\xb7\x5c\xed\xd3\xfd}\ + \x85\xc6\xa9X\xfc\x0b\xe0\x1ebK~\x0a0\xe7j\ +\x90/\xf8\xb1\x04\xe2\x86\xa5\xe0\x1f\xe2\x8b\xd5\xb6\xde\xef\ +\x07\xf94nK\xe0_\x00\xf7\x90_\x10\xaa\x00s\xad\ +\x86\x8a\x81P\x96@\x0e\x89\x08\xfc\xcfb\xfdI\xb9\x1b\ +\xcbu\x11\xe8\x90,\xcb\xa64h\x93,\x0bm\xea\xff\ +\xad\xf5\x114'Y+\xf4\x05~O\xff\x9b\xa5\x0e\xf5\ +=\xf8~e\xaf\xa1|\x00\xb85\x13\x83\x7f\xc81\xbb\ +\xa5\x00s\xfc\x05\xf8Fx\x5c\xa1G&\xad\xed@&\ +o\xecI\xa6\xed\x9fHf\x9cYJf^\xb6#\xb3\ +o\xed\x22\xb3\xfd\x0f\x90\xb9\x0f\xce\x91\xb9\xa1\xee\xe8\xe7\ +Y2\xdbo\x1f\xfa\xbd3\x99yi\x1d\x99\xe1\xba\x88\ +L\xdd3\x86Lfv'\x93l\xdbS\xcf\x85\xe7\xc1\ +s\xad\xaa\x04=\xf8\xd0\xb8\x16>\xfb\x90g\xf8\x1b\xe6\ +\xeb\xe9\xd2\xe7U\x17\xe3+u\xe702\xf3\xe2\x1a2\ +\xe7\xbe+\xc9\xfe\x18JrS\xbe\x91\xbc\x9c4\x92\xc7\ +\xce#I\x1e\x8f,up\xb9\xe8\xefrI^v*\ +\xc9I\x8a!\xd9\xefC\xc8\x9c\xa0cd\xc69K2\ +e\xdb\x002i\xb5\x01\xcd\x17\x14\x9a\x16\x92i\x5c\x0b\ +\xe7\xf28*\xc0\xdc\xe4\x07p\xd6\x11\xafNZ\xd5\x86\ +L\xdd=\x86\xcc\xbe\xb9\x13\xe3\x8b\x9b\xc1Bx\xe4\x94\ +\x8e\xe7r\x0e^A>\xc9M\xfdN\xe6G\xdc&\xb3\ +\xbc\xec\xc9\x14\xa7Ad\xd2\xca\x96\x94\xacPL\x19\xe1\ +(\x84{\xb0\x0b\x1e*\xc0\xbc\xe4\x83wt\xfe\x92\xed\ +\xfe\x87\xce\xa5\x05\x99\xff\xea\x16\xc9\xcdL\x92+\xbeK\ +\x1d\x88G\x00O\xc9{r\x99L?f\x8ee\x0c\x9f\ +\xffT\xfa\xde\x14\xc1CV\xf1\x1cR\xb8o\x90\xa4\x00\ +\xf3\x92\x03\xde\xbb\x229\xbd\x96,\x88~\x86\xcee\xde\ +\xaf\xc3\xbb\x88\xc1\xcb\xcb$\xd9\xef\xee\x91\x19g-(\ +]\x01\xf8\x81b\xc8\x85$\x1a\xe7|\xfc\xc3\x9d\x93\xaa\ +{7\x03\x9d\xaf\xa45m\xd1>/#\xd9_\x9e\x91\ +$\x87]\xa9x\x17\x1e\xc3m9\xf6\xb3\xfc\x8e\x83\xf3\xfd\x1d\xf6C\ +\xffB\x1a\xc8c\x15\xd5\xdd`W>\x8eK\x07\xc0=\ +/+\xb9\xb2\xd1T\xa1\xe3\x17\xd3\x00\x9bUT\x8bD\ +q\xf1\x8f\xe4=\xf0\xfc\xdf\xf5\xdc\x0b\x8f\x82\xf8(2\ +u\xd7\xa8_A\x03\x8a\x8f\x7f\xb4\x07\xa0\xeb\xfdJy\ +\x0f\xf6\x04//\x8b\xe4e\xa7\x90\xdc\xac\x14\x1c\xeb\xe1\ +\xe5e\xffR\x9f\x12\xfbs\x18\x99\xb2\xb9_E\xd3\x80\ +b\xe3\x9f\xb6\xf1*T\xcf\xe7\xf1Hnf2\xf6\x19\ +\xe6>\xba@f\xdd\xd8\x86cy\xe0\xb7O\xdd3\x16\ +\x9f\xc3\xd4}\xe31\xff\xc9<\xbf\x92\xcc\xbe\xb9\x83\xcc\ +{z\x19\xd9\xefo\x10]\xa4U\xdc\xbc\xd0\xc8{q\ +\x9dLZ\xd7\xa9\x22\xe3\x06\x8a\x8b\x7f\x88\xd5\xaei\x87\ +\xed\xfb\x8a\x18\xbc\x9ct2?*\x98\xcc\xf2v\xc4\xbe\ +C\xbc\xcf\xd6-\x04\xf2;\x04r<,u\x8arC\ +\xe0\xe7\xca\x968\xb6\x04r\x1ar\x02\x80>y\xf9\xd9\ +\xf2\x9f$\x97Cf\xfb\xee\xa6rP*\xc6O\xa8\xb8\ +\xf8G\x00~=y\xfbv \x0e\x98\xfb\xd8\x83Ls\ +\xf9\x97L\xb25,\xc2o\xb9\xce\x98nal\x19~\ +&\xaf\xefL\xa6\x9fZ\x80\xfd\xfb 7\xe49xH\ +\xfe\x00\xef\xa9 9\xa0\x98\xf8G\xf8\x00\xbe\xcbI\x8e\ +\x93\xdf>\xb2\xf3\xc8\xfc\xf0\x9bd\xda\x81)\xe8\xfc\xb6\ +\x90o\x5c\x9e\x9fg\x80\xf8U\xfa\xc9\xffpN\x89<\ +\xf3\x0b\x0ab_\x92\xc9L\xe3\x8a\xa0\x01\xc5\xc3?\x9f\ +\xef?\xbf&\xb7\xfd\x03\xdd\x11\xf2\xb6\xe0\xb9\x15\x1a\x7f\ +\xa5\xe9 y\xc3\xff\x90\x1e\xe1D\xe5\x99\xc8e\xf0\xc8\ +\x9c\x80\x83\xb4\x1c\xf8\xcd\xf1\x8f\xce~\xc6\x99er\x8a\ +\xe3\xf1H\xf6\xbb\xfbX\xbeS\xb9\x01\xbf(\xd6\x06\xe7\ +t\x85\x1e\x99~\xc4\x8c,\xf8\x1a!\x87u v\x92\ +\xfe\x13\xd9A\xe3\xe5\xed#V,\xfc\x83,Ez\x15\ +\xd8>2\x0f\x1e\x97\xccE\xbac2\xb3\x07}\xe6+\ +\x87\x96S\xb7\x0f\x22\xf3\xdf\x06\xc9\xbe\x1e4\xf2\x9e]\ +!\x93V\xb5&\xe5\xc8\xbf\x14\x0c\xff:8o\x87\xe4\ +\x14\xc8\x8e\xfb\xb0KdR\xe5\xc5\xd5\x04h\xa0)\x99\ +\xb2\xb1'\xd6\x0de\x1d`o\xa6\x1d\xfaW\x9e\xf4\xac\ +8\xf8\xc7z\xb4\x11\x95\xbb#\xdb.\xe1s\xaf\x10\xb8\ +\x17\xa0k\xec\xc7x\x1f\x223\x0d\xe4=\xbbJ&\xd9\ +\xc8\x8d\x07(\x0e\xfe\x11MC\xfe=\xe4V\xcb2@\ +\xdec\x9e\xaf(\xb8\x17\xa0\x81\xd4\x1dCIN|\x94\ +L\xeb\xe3f%\x93\xa9{\xc7\xc9\x8b\x07(\x08\xfe\x91\ +\xce\xbf\xca\x00\xdbg\xb2\x0c\xd0\xf3\xb1\xaeWY\xf2^\ +\x02\x1aH?1\x0f\xdb\xf4\xb2\x8c\x9c\xc0\xc3X\xbf\xfc\ +m\xf0\x0fg\xc3y\x84L\xf6\x12\xd8\xf7`\xe3)X\ +\x8eu\x09:\x07\x1f#\xe4\xfc\x80\x9c\x92v@\x8c0\ +\xd9\xa1\xbb\xfeA\xef?\xbfR\xea\xd8:\xe4\ +\xd0\xa6\x1f\x9eYu\xce\xbe\x00\xdd\x83\xbe\x22m\x9c\x00\ +\xe2\x97i\x07\xa7\xca\xba\xee\xca\xc7\xbf\x95\x1e\x99\x13|\ +B\xaa=\x80\x0165\xbeW\xa5\xe8r_\x04\xfe\xc1\ +'\xc0\xf9\xf1I\xca\x95\xf3\xc8\xac\xab\x1b\xab6\xfe\xe9\ +\xfb\xd8`\xb3K\xb7\x05h\x0f\xaemV<[_R\ +\xb0\xd6\xc7\xb5\x05\xa4\x1d\xb9\x8f\xce\xcb\xaa\x03T2\xfe\ +up\x0d\x05\xb8G/\x15\xfa\x91\x1d\x9d\xb6gl\xd5\ +\xe3\xfd|(\xf4yIwG\x15\xe2\xcc\xf8n\xb1\xf4\ +\xbc\xafr\xf1\x0f\xf1\x91=cp~\x9d4\xa3 \xf6\ +\x15}w\xa6\x8a\xf1~>\x80\x0c\xd8jJr\xd3~\ +H\xb5~NR\xac\xac~\x80J\xc6\x7fSd\xc7.\ +\x90:\xd6\x0b\xb9a\xf8\xfe\x5cU\xd1\xfbK\xe0_\x17\ +\x9f_\xf6\xc7GR\xad\x1f\xf2\x16Sw\x0e\xaf\xc2\xf8\ +\xd7&3/\xae\x95Z\x07\x86\x5c\xcc*\xcb\xfb\xf9\xb0\ +\xb2\x05\x99\xfb\xf8\xa2T\xeb\xe7\xe5f\xcaj\xfbT.\ +\xfe-\xb41\x0e\xa5\x1a\xc8^\x84|\x5c\x9c\x93Y\xd9\ +8\x94\x05\x10\xee\xb2\xfd\xf7K\x87\x7fv.u\x87\xb8\ +*\xe3\xff\xf6\x1e\xe9\xd6\x9e\x9f\x8ds\xed\xaa\xfc\xf9G\ +\xf4\x0by\xaeR\xc5\x03\x10\xdf\xcc\xbch+\xcb\x19\xa8\ +\xba\xf8\xcf\xcd\x90w.D\xa5\xe1\x1fp(\x95\x0c\xc4\ +\xf8_\xfbg\xe2\x1f\xd9~`;T\xc2\x9d\xe9\x0a\xc0\ +\xbf\x94:\xd0\x9f\x8c\xff\xbcL\xaa\x96\xce\x9f~\xfe/\ +\xfd\xa1\xf8G6\xa3\x9cb\xa0\x95\x0bh\x0fp\xec[\ +\x9a\xc1- 3=VWi\xfcg]\xdf*\xe5\xda\ +e\xd6}\x14\x03\x90\xed\x0e\xf9<\xd2\x0c\xea\x0c,\xa8\ +\xba\xfa?\xf0\xbe\x0b\xab\xa4\xce\xf7\x85\x1a\xbdU\xd6\xf7\ +\x8fA\x17\xe7r\xe6=\xf7\x96\x0e\xff\x10\x03t\x99V\ +\x85\xf1\xdf\x14\xdf\xb3\x95\xf6\xce\x1c\xd4{\xabRq\x7f\ +a\xa0\xef\x0e\x16\xc4\xbd\x92j\xfd\x90/\x97\xe24\xb0\ +\xea\xfa\xff\xe8\x9cX\xf0cJ38?>\x90\xc9\xf6\ +\xdd\xaa\xb4\xff\x1f\xfc\xb7\xd2\xd6\xa6\xe5\xfc\xf8\x88k\x9d\ +V\xd9\xf8\x0f\xd0\xbf}W\x8cGi\x06\xf0\x8d\xb4#\ +U0\xf7\x83\x0fh\xdeR\xeb\xfeh\xc0\xbd\x22|\xa7\ +\xb1\xaa\xe2\x1f\xe4\xdfj\x032?\xc2O\xaa\xf5\xc3\xc8\ +\x09p\xa9|\x8f+5\xfes\xee\x80\xde#\ +3\xed+ \xfe\xab\xe8\x99\x96\x14 \xe7\xcdy8\xc9\ +aI\x97\xf3\x08\x03\xe7}\x1c1\xfb=\xee\xff\x08A\ +\xd2\xea\xb6\x94M\x83\xf7J[\xa06\xd3o@\x13r\ +\xaam#'\xde\xafx\xf8\xb7nN\xd5S\x8b\xbaG\ +\xe6\xdc=\x8a\xefHA\x0d>\xf0q`?\x1f\xbfO\ +\xdf\xf2\xaaK\x13YW\x99\xb2\xd54\x83\x9c\xf7\xeb[\ +\xe5\xc5#+\x06\xff\xfc\x1e{\xe5\xd1M\xf9w\x01\x04\ +s!9l\x1c\xe7\x87\xfb\xae\xe0\xeb\x85Zx\x90\xef\ +\x04\xf7\xc5\x92\x90\xee\xcf\xe2\xf7\xd7*F\x13\x95\x8fc\ +\xd1\xeb\xd3\xa1j\xd8\xcaX\x13\x8a\x9b\x1c\x87\xfb\xcc\xc9\ +)\xee!\x1f\xfc\x0b\xf6TD\x9f!\xa7\x15d\x1c\xf4\ +\xd9\x93\xf8\x9e:\xd8\xc3[L\xca\xac\xf1\x0b\xb9\xf2\xdc\ +\x8cD\xb2 \xe6\x05\xce\xff\x85\xfb\x1f\x10C\x80\xef&\ +\xadmO\xf7\xea\xe4\xd3\x84\x82\xd0\x03\xd4\xb0\xdd?\x09\ +\xfbke\x1d\xd0kP\x8e\xf6\xaet\xf8\x17\xec\x99\x8a\ +e\x9a!\xa2\xc9\x81\xb8njN\xd0Q\xaa\xa7bV\ +2\x99\x1f~\x0b\xcbs\x89\xf0 C,\x08\xbe\x03t\ +\x03\xef\x85\xde:\x99\x977\x90i.S\xc9d\xfb\x7f\ +\xe4U'Av\xdc#\x1e&\xeb\x80\x9er\x10/\x91\ +c\xceS\xf9\xf0O\xf3Y\xd0a\xe0\xbcA\x1fT\xa8\ +K\x07\xfd\xcd\xb8\xe9?J\xc85\xcc\xab\x1c{K\xc6\ +\xab\xd0\xb3\xe1,\xcbe \xbb\x0ah\x22\xf7\x89'\xd5\ +\x8f\xb32\xf4\x04\x9a\xe6\xa1\xde\x07\xe7\xe7g\xb9,+\ +\xe7\xee\x11y\xfb\xba$\xc4?\xe5\xa7\x87\xf3\x09\xf9:\ +\xf9o\xee\xa2\xf3\x16_\xe6\xfdu\x9c\xa3\x0b\xb5K\xcb\ +\xb4St\xb1,\x97w\xad\xdf\x9c{\xa7*\xe7\xfcC\ +/:[C2\xcb{\x93\xdcj@r\x12>P=\ +b\xe4\x9b\xef \x19\xfe\xe98\x1d\xf8\xdb\xcb;p\xfd\ +\xe2\xb2\xe6\x0c2\x04\xe2\xe0H\xa6\xcbm\x94\xea\x1f\xaf\ +\xa8\xfa\x9f\xd4:\xa1\x96\x0d\xd8x\xf2\xaa]\x0c\xcf\xc9\ +\xf4\xdcP\x11\xfa\x8c\xe4\xe7_\xcaX\x15\xf0\x8a2c\ +\x94\xfc\x1a\x10H\xaf\x93\xd7\xc0\xb91H\xee\x96\xe0=\ +\xd0\xf3\x9b\x9f3\x22\x97\xfe{\xba\x85\xf2\x18\xees\x03\ +\xbd\xcb\xb3n1\x0c\xe8\x0f%\xe3=O\x19\xf1\xdfL\ +j\xf9\x0cr\xa2\xa8\xd7\xa1\xf8g\x83]'\xed=X\ +Q\x03\xe7F\x80\xfeWl\xcf(9\x96\xed\xbb\x0b\xdb\ +\xd0)\xdb\xfac\xba.\x9fO\x81_\xfb\x9b\xd2\x7f\xe1\ +y\xa9\xce#q\x7fxN\xc2{\x99j\x18\x89\x5c\x07\ +\xaeiVa\xbd@\xca\x85\x7f\xa87\x01\xe7\xaa<\x03\ +\xdfQBzb\xa9:\x00Z\x1b\x9c\x1by\x0e|f\ +\x84u?~\xad\xa17\x81\xf8o\xb8\xc9_1O\x83\ +\x1c\x0c\xb0U!\x06\x09\xb1H\xfc\x1d\x0bm\xda\xffH\ +\x83\x05m\xdb\xa2gB\xdd\x15\xe8'\x0e}\xbe\xe1=\ +\xb2\xd4\xae)m\x80\x0e\x9by\xdeZ\x0e\ +;\x90\xcc]\x87i#\xd3s=\xf6K\xe6\xdc;\x89\ +{\x89s\xbeGQ5\xfcd\x88\xdf\x949\xd0\x9c\xa0\ +N\x1c\x0b\xf8\x93\x22\xe0\x9f\xaf\xa3\x87]*\xf7R\xd8\ +Q\xc1\xe2u\x00\x9a\xae\xe4a\x1f\xf3\x07\xe8K\xd0\xf7\ +\xbd\x04\xcf\x11\x87\x7fq\x83\xcb\xa5r\xb3*\x12\xcfb\ +F\xde3o\xda\xc7\xaf@\xfd\x7f@\x07@<\xaf\xbc\ +2\xaeT\x1d\x00\xd7\x80\x18+sM\xccb\xefCg\ +\x19t\xf0\x12\xef+/\xfe+i@\xadh\xa8\x11\xa8\ +p\xfd\xbf@\x07\xd87\xa1\xdc}\x8f(\x1d`\xb1h\ +\x1d\x00\xc9V\x88\xf3\xc8\xb3\xb7\x16\xe4\x92%o\xe8\x22\ +9\xffW\xa0\x01\xb8\x87z\xe1\x0a\xd9\xff\x0fx5\xda\ +Wiz\x1a`\xdf\x95\x98gJ{\xffE\xdc\x00\x9d\ +.I\x94\xdcTp\xfc\xffb\xdc\x97\x1f\xff\x00\xd6\xcd\ +\xc9\xdcP\xb7\xb2\x17\x83\xe4&\xf4\xea\x84:\xa7\xb9\x0f\ +\xceQ\xf9\x0a\xd6B\xbeK:\x1e\xce\xd7\xc7\xe55\xb2\ +o\xee\x14\xcdk\x14\x15\xffh\xaf\xf2\x9ezUF\xdd\ +\xf2\xf2\xe3\x1f\xe7\xac\x8b\xb8\xaf\x8ct\x02\x90\xe1\x18\xdf\ +\x88>\xe0o ?\x11\xd7g\x02\xbc\x8b\x8aY@\x1e\ +\x9cC7\x92\x93\xf8En[\x09w\xe22N\x89\xb9\ +\x13\xa7\x80\xf8\x87\x5c\x9el\xbf\xfd\xb8\x1eh%\xdce\ +\xe3\xe3_\xf2\xfe\xcf\xa0\xaf!\xbc\x82_\x1b|\x01\x90\ +\xc3\x086\x01\xe8\x85i{\xc7\xd1\xf8n.YL^\ +J\x9fBi\x03lq\xb1\xf1q\x05\xc3?\xd0}\x86\ +\x9b\x15\x95\xc7P9\xb1j~\xff\xe7r\xf4\x7f\xa7x\ +v\xc6\xd9e\xb8\xff!\xaeA[\x98\x87Q\xce\x1c\x0c\ +\xa8}\xe2e'\xd7=e\x7fyJ\x9f%\xd1\xb6\xa6\ +\x22\xe0\x1f\xfc\x9cy\xe17i\x1b\xa5R\xf3\x98\xf8\xfd\ +\xdfM\x10\xb0$\xff\x9e\xaeP\x8e\x85\xf0\xfcK\xcb\xd5\ +\x16\xf4\xc7\xe9\xe08=\xc8>\x90\x1b\x98\xa7\xc8\xe8\x03\ +\x86\xfb \xb8\x8f\xa7\xa8y+\x00\xfe\xc1w\x04>\xa5\ +\xc2\xde\x93\x95\x83w>\xb0h\xdc\xb7D\x10-\x97g\ +\xae\xd0\xc7>R\xf0\xb3\xe2\x5cNA\x80\xdfa\xff\xaa\ +@Lv9\xe5W\x82\xbb\x1c\x10\x03\x82z\x98\xe0K\ +\x07?\x1c\xc4\xb8\xf7 \x0a\xd2\x0eL\xa2{6T\ +\xfa\x1e\xfc\xa9\x90G\xe3\xb8\xf0\xec\x0b\xe1\xbf1\x82P\ +\xe9\x9f\xaf+$C\x85Aa\xed\xa1?\x05Bi\x1c\ +\x17\xc3\xbf\x10\x0d,@\x90\xaf\x00s\xad\x06\xf9B>\ +\x8d\xdb\x12\xb8\x17\xc2?\xd8\x05~\x0a0\xdfj\x90/\ +\xf8\xb1\x04l>QC\x80\x06\x86#HQ\x809W\ +\x83| \x85\xc6\xa9X\xdc\x0b\xe1\x1f\xfc\xc2\xbb\x15`\ +\xde\xd5 \x1f\xd8\xcd*\xf2\xf5\x8b\xc5\xbf\x10\x0d\xe8!\ +\x08Q\x80\xb9W\x83l\x10B\xe3\xb2L\xdc\x8b\xa0\x81\ +\x81\x08\xbe)\xc0\x1a\xaaA:\x88E0\xa0<\xb8\x17\ +\xc2?\x83E\xe9\x8c\xe9\x0a\xb0\x96j(\x1f\x00\xce\xe6\ +\xd38,\x17\xfe\x85h@\x15\x81\x03\xab\xda&\xacJ\ +\x90O\xe3LU\x1a\xdc\x8b\xa0\x81:\x08vT\xd3@\ +\x95\x80|\x1aWud\xc1}5\x0dTI\x90+\xee\ +\xc5\xd0\x80\x03\xabZ\x1fPDH\xa7q#W\xdc\x8b\ +\xa0\x01\x90)\xa0W\xc4*\xc0\x9a\xab\x81\x82X\x1a'\ +2\xc9\xfbr\xd0\x00\xe8\x94`WT\xfb\x07*\x1fB\ +h\x5cH\xa5\xe7\xcb@\x03|\x1f\x11\xf8\x96\xaa}\xc5\ +\xbf\x1eR\xe8\xbd\xd7\x13\xc4\xc9\xaf\x18B4\x00~E\ +\xf0-C|\xa1Z7\xacx\xc8\xa7\xf7z8K\xc0\ +\xa7\xfb\xabp_\x0a\x1d@l\x09|E\x10c\x962\ +\x87\xa4\x1aJ\x81\x13\xd5\xa3zT\x8f\ +\xeaQ=D\x0ef\xf1\x8fe\xf2\xd3\xe0\xe2\x9fK\xf0\ +\xe7\x98\xe2\x9f\xd5\x84?\x0b\xcb\x83\xb2\xe4\x87\xb0\xbc\x11\ +\x96G\xc2\xf2\xaa\x84<+6A\xe5\x92\xf2PX^\ +\x0a\xcbSay+,\x8fK\xc8kay^\x5c\xde\ +\xb7E?L\x09j\xdf\x19\x84>\xf5{\xf4\x8b\x96\x9d\ +(\x90t\x88\xd0[\xfeB\xd0\x17\xc1r\x04G\x11\xdc\ +D\x10TIp\x93\x9e\xc3rzN\x7f\xc9K\xc7\x12\ +z\x0e\xf8\xe0\x0d\x11\xaccQ~y\xb0\xdd9\xac\xca\ +\xb7)\xf9\xc0\xa1\xe7\x14B\xcf\xd1\x90%\x107(\xef\ +>\x08\xad]\x1f\x81\x13\x828\x05X\xa7\xa4\x10G\xcf\ +Y\xbf\xbc{ \xf0\xf7J\x08& x\xa5\x00\xeb\x91\ +\x16^\xd1kP\x92d\x0f\x04\xd6^\x13\x81-\x824\ +\x05X\x83\xac\x90F\xaf\xa5fi{ \xb4\xf6-,\ +E\xe8\x9d)?`\xd3k\x12\xb9\x07\xac\xe24o\xfb\ +\x9b\xad]p\x0flY\x22\xce\x82\xc0\xfa\xe1\xac\xfc\x0e\ +4/\x0e\xd2\xe85\x16\xae\x9fU\x9c\xcfWe^'\ +)\xbcb\x09\xc9\x05\x16%+\x9d*\x7fn\xbf\xec\xfe\ +\xbc\x13\xab\xb8~\x00\xfa\xc2/\x94\xef\xbaE\xb58\xa0\ +\xee\x06\xd4\xd2Z\xd9\x92\xaa1\x08}\x9c\xa0\xd6,\xfc\ +]\xc5\xf5\xfc\x8c\xa3\xd7\xcc_\xff\xfa_\xb2n\xbav\ +\x14\xf4\xd6\x84\x9a\x0a\x19\xee\xd6dN\xe0!\x5c\xdb<\ +?*\x88d\x7fzL\xb2\xdf?\xc0\xfdgr\x1f\x9c\ +\xc5u\x0f\xd3\x0eM\xc7\xf5\x94q\xcf;\x5c\x0bIn\ +{\xb1\x8eU\xa4\xcfWl\xbe\x0f\xae\x97\xa5\x87k\xf8\ +f\xdd\xd8\x86\xd7I\xf5Z)\xbb\xe7\x04\xd4\x97\x80\xbe\ +O\xb9\x0f\xddp\x0d\x02\xa8\xf5&\xa7}\x08a\x15\xd9\ +2\x15\x14\xcf\xd4\xa5\xeb'\x9a\xe2Z\x87\xd03C\x96\ +\x01\xf56\xf2\xdf\x06\xe1\x9aET}a\x99\xee\xdd'\ +\xb3\x8a\xec8\xf9\xdb2\xb8\xdec\x1b\x5coI\x9e\xb5\ +\xc0\xf1>\xe4e\xe3\x9a\xb0P\xb3I\x86\xda\x03\x1cV\ +\x91\x0d+\xdf\xb5\xa39A\x9d\xcb\xdcG\xe7\xe5\xda\x03\ +Cx@\xbd2\x5c\x1bSz\xfe\xc8\xb7\xdf\xe5\x8aw\ +\xa8\x87\x0a\xfc\xecW\x0c\xa8\xef\x96q\xd6B\xda\xf9\xf2\ +}\x17r[{\xf2\xa6^\xb8N\xe4\xaf\x1c\xd0\x97\x19\ +j\x9bIA\x07Ar[?\xd4\xe1\x5c\xdb\x11\xf7\x87\ +\x96xp\x0aHNR,\xc9~w\x9f\xcc}|\x91\ +\xcc\x09>\x81\xe5\x1e\xd4\xe0+\xf8\x16I\xd5\x84\x95t\ +\x0f\xd2~\x90i.\xff\x96\x97\x1f\xc8o\xfdH\x87\xc9\ +\xf6\xdf\x8ff\x22\x81L\xcb\xcd\xc4\xb5\xc2q\xdf{D\ +/T\xefJ\xbd\x22\xfc!\xfd\x07\xeaiA_\x1e\xa8\ +/\x0c\xfd\x02%\x19\x05q\x11\xf8y\xe5\x90\x0b\xf2Y\ +?\xd4\xfc?4C\xa2\x1eB\xec\xcfad\xfa\xd1Y\ +t\x8fF\xedR\xeb\xba\xf2u?\xa8?\x0c\xb4\xc1\xcb\ +\xcb,\xf3\xf9\xb9\x0f\xce\x88\xaf\x15^\x11\xeb\x07\xba\xb7\ +m\x8f\xf8\xdd\xbd\xd2'\xc6\xe5\x90\xb9\xa1\xeeT\xff\xca\ +\xf2\xea/\xb0G\xd6\xfa\xb8>\x7fY:\x04\x9c\x19\xd0\ +\x19%\xac\x9b)\xfb\xfa\xa1\xcf\xe7\x99\xa5\xa5\xcb9\x1e\ +\x17\xf7m\xa6\xfa\xc6K+\xaf)]*\xfd\xc8,\x5c\ +\x1b\xb8\xb4\x01\xfc\x03j\xc2J\xb0\xc72\xae_\x17\xeb\ +8e\xf5\xba\xc9{\xe9C\xd7\x11\x95C\x9d$\xf4\x8c\ +\x0c\xb7\xe5X\x17\x14\xbb\xdd9\x19\xa2\xfb\xe4\xca{\xfd\ +\xe8\xf9\xd03\x13\xd7\xdd\x1538I1d\x8a\xd3 \ +\x89\xeb\xb8JD\x07\xe8|C\xff\xa1\xd2\x06\xeeMU\ +\xb6<\x94y\xfdY\xd7\xb7\x95:\x8fl\x9f\xed\xf2\xaf\ +\x17\x8cd\x5c\xca\xb6\x81\xb8&\x9f\xb8\x015\x19\xa9^\ +\x83\xa5\xee\x81l\xebG6\x08\xf4\xb7\x12\x8f\xfbXJ\ +G\xaf\xa0z\xc9\xb9\xf7O\x8b}7\xf0A\xa83_\ +\x06\xddI\xbf~\xdc?\xfd\x1fl\x9b\x8a\x1b\xd0C\x07\ +\xfb6*`\xed\xb0.\xb0\x87\xc1>\x16\xbd\x01<2\ +\xf3\xbc\x8d\x98^\xe9rX?\x9c\xfd\x1dC\xb1\xee)\ +nd^\xb2-\xeb\xfd\xd2\x03\xe8\xda\xcc\x1e\xa5\xda\x96\ +\xa0\x8f\x95\xa1\x0f\xca\xb4~\xa8\x09.n\xff\xa1\xb64\ +\xfc\xbb\xfc\xf8\x9e0P\xb2\xa74[\x03\xf7M\x11\xec\ +\xcb!\xd7\xf5kc=\x0etx\x91\xeb\xcfJ!S\ +\x9d\x87W\xe0\xfa\x9ba=\x19\xf4hq#\xef\xc5\xf5\ +\xb2\xce_\x85\xad\x9f\x9b\x99\x8c\xce\xc7\x90\x8a\xad\x8d\x88\ +t\xc2\xbc\x17\xe2{,C\xbf\x95B_jE\xac\xff\ +\xf0L\x5c'_$\xfe\xa1o\xc7\xde\xf1\x15\x8b\x7f\x90\ +?o\xee\x8a_\xffS/\xcaoZ!\xeboJ\xf5\ +\xb8\xcd\x11c\xa3\x22}\x1f\xec\xbb\x8a\xe3\x7f\xba\xd8F\ +\x04;Y\xdc\xc8\x09:^q\xf2\x1f\xfc<\x9bz\x97\ +j\x8fH\xa8\x83I\x07\xb0\xff\xce#K\xd5=\xb3\xae\ +0+N\xfe[Q}G\xf2\x9e_\xc32\x08\xf4\x80\ +b\x80~\x07\xf4\x87m\x9e\x8a\x88\xeb\x80\xee\xe9\xed(\ +v\xed\xd0\xeb\x00\xf7\xe7\xac\xb0\xf5S\x00>\x9fd\xfb\ +\xae\xb8\xdfw\x09\x80~\xbd\xc2\xfdA\xe5D\xfb\xa0\xdb\ +\x16D?\x13\xbb~\xd0=\x93\xcb\xf6\x85\xc8\xbc\xfeB\ +?\x85E\x13\x04\xda\xc5\xfb\x06T\x18\xed\xeb\xe0\x1e\x06\ +\xa5\xf5:\xc1\xb2\xafl?\x88\xe4\xeb\x17\xd7\x0b\x01\xf8\ +\xc0\xd6\xfe\xd8\x07\x0b1-\x0a\xe7\xcd\x8b\xc7\xf7\xe4\xb9\ +\x0fp\xee\xb7\x0fA\xe7+Z\xec\xdaa_\xa0\x7f\x87\ +L\xf6\xefr\x81\x9a\xc7\xd0\xcbl\xa31\xd5\x83P\xf8\ +,\xc39\xbc\x016 \x0f\xf3\xa2\x82\xf8\xb7\xd8\xde\xcf\ +\xbe\xe5L\xa6\x9f\xfc\x0f\xdbi\xb8o\xcc\x0a=\xd9\xf7\ +\x01\xbd\x0bb\x81\xf9Q\xc1\xe2\xd7N\x92\xb8\x973\xee\ +\xe1(\xad\xfd\x8b\xe8\x06\xde\x03\xfa+\xac\x0d\xe2\x91`\ +\xc7C?\xd0\x12{\x8a\xf4+\xe8\x0d&\xfa\x10\xb2q\ +\x0f\x9d\x82\x98\x97d.\xb2\x85Rw\x8d\x94\xde\x16D\ +\xef\x05yS\x9a\xbd\x89\x07\x8fKf]\xb6\x93T\xef\ +*\xbe\xfe\xe5T\xads\xe8A\xc5\xf9\xf9\x19\xd7\xbb/\ +~\xa6\x84\xf4)>\x1f\xfa\xfa\xba\xf49a\x9a\xe4 \ +}qv\xd1\xfeI\x14\xd7\xa6i\x10\xf1P\x88\xf3\x14\ +\xc4\xbc(\xf35\x10[\x95\xac\x17\x97(\xfc\xeb\xe2\x18\ +<\xf4\xdf\x12\x89\xce\x9f\x9f\xa8X4\xff\xd9\xd07\x16\ +l\xc0\xcc\xa4\xb2\x97\x9f\xfa\x9d\xea\x93gI\xf5\x81K\ +;0\x19=\xab;\x89\xed\x93\x12\xfd8\xb4\xa9\xbfC\ +sI\xdb7\x1e\xc7~%\xf1-\xc3\xf9\x93@\xe6\x95\ +N\xff\x88>\xb3\xfd\x0f\x88~~\xbe\x90M\x07}\xee\ +O/.\xd97Y\xc4\xc0=\x12\xd6\xb4\xa3\xe2\xa2X\ +v=\xa7\xe2\xda\xa1\xe7\xc9L\xcf\xf5d\xfa1s\xbc\ +'\xe0\xbb\x05^\x0a=\xa7\xa0\xf7\x94$\xeb\xa66\x98\ +C\xf9\x9aJ\xd7w\xcb^?\xf8\x15\x8e\xcfE\xc8\x16\ +\xad\xd7g]\xdfZ\xb4~\xd8+4OI\x06\xf8\xeb\ +\x8a\xceL\xc7\x92\xfd\xe6\x11\xaf\xa0\xfaI\xe4\x89\xec\x03\ +X\xfa\xe0\xe1\xe7S\xfe\xe5r\xf1X\x91\xf8\x87~s\ +\xdc\x94\xaf\x22\xdfD\xf1\x80\x16\xd4\xd9\x04\xfb\x03\xf1F\ +IF\xa6\xe7\xba\xc23\x8f\xf1\x1f\x17Q\xf6\x97$Z\ +:\x0f\xd3Pao\xb2\xf2\xf1U\x91\xfc\x1fb3\x90\ +g\x80\x07\xf4AK\xfe\x8a}\xdc\xd9\xb7\xf7`\x1a\xc5\ +:\x1d\xf8_\x90\x8e\x07\xfd<\xcb\x9cb^6\xf5=\ +9\xaf\x1f|/9\x81\x87e\xf1\xad\xc3\xdaK\xc6\xbf\ +\xd1\x1c3\xce-\xc7\xb178\x0b)\x8e\xbd\xe9x\x15\ +_\xa7\xd1\xa5}\xdf\xa3%\xeas\xcda\xc5\x90\xc9L\ +\xe3B]H\x1e\xeb\x87\x98`\xe6\xf9\x95\xb2\xf6\x99\xe6\ +\xe7\xcf\x8b\xf87=\x81~Zz\x98\xbe`\xde\x18`\ +\xbf\xd1\xdf\x80\xae\x07}\xb4\xa8\x9e\x8d\x8f\xd0\x99\x89\x17\ +\xe9\x0f\x83\xd8\x18\x15\xe3l&\xf3\xfa\x81\xc7C\x1c-\ +\xc5i \x8ds\x99t*\xfe\xdd\x01\xf1\xf9/\xb4\x9d\ +\x9b\xff\xee\x1e\x96\xf3\x05_#\xb1\xcf\x89\xeaw\xa4S\ +\xc8\x0b\x81\xf7\x00\xdf\x009\x9duu\x13\x99\x17\xe6\x89\ +\xf5\x1e\xf0\x8f\xe6\xdcq)\xc2\x11\x7f\xfd\xa5\xd8\xed%\ +\x06\xe2\xed`\xcf@l\x1cb\xc2\x98\xff\xc8\xeeS\xe7\ +\xe7\xbf\x94\x9e\xff\x04\xeb\xdf6\xa0\x98\x8c\xe7$~\xc6\ +g\xbfd\xbfW\xc1>\x8e\x14\xcd@\xec\x87\xa2\xfd\xa2\ +\xbf\x85\xb3\x94\x89t\xb4b=\xfa\xd09\xc2\xfc?7\ +\x13\xef\x19\xce\x0b@2\x13\xd6\x0c\xba<\xee\x01Z\x98\ +\x03'\xd3\xba\xf9\xc0\xcf\x7f*=\xff\x8d\xbf\xfe\x0cV\ +\xd1\xfaA\x0f*\xb1~Q\xdf\xd5\x15\xdf/\x12~\x07\ +v\x05\xf4\xa8\xdbj\x8ay\x09\xf0\xc8\xd4\xbd\xe3\xb1N\ +\x05{\x86\xf5\x05\xf8[\xbeM)\x9fu\xf3\x81\x9f\xff\ +Vz\xfe#\xce_3\xc1k\xc68\xca\xcd\xc0zh\ +\xf2\x06\x89\xec\x8b\xb2Ad\x8f6\x1dy\x9c\xed\xb2`\ +=K\xc2\xfcW\xe0]\x80\x93\xd4]\xa30\xe0x\xe6\ +J\x89s\x0c\x14\x11\x84\xf3_\xcb\xce\x7f\xb6\x14\xc0\x91\ +\xe2\xf6?\x95\x14\x84\xf3\x9f\xff\xd8\xfc\xf7?\xfd\xfeC\ +\xf5\xfd\x97\xea\xfbO\xd5\xf7\xdf\xc4\xde\x05\xfb\xa3\xee?\ +\x8a\xd8\x83?\xee\xfe\xab\x98=\xf8\xa3\xee?\x97\xb2\x0f\ +\xbf\xdd\xfdw\xba\xcc\x00I\xd7?\xe0\xd7\xd9\xe1\xd7\xd3\ +\xe1\xd7\xd1\xe1\xd7\xcb\xe1\xd7\xc5\xe1\xd7k\xa8\xae{S\ +\xc9\x83I\xfd(\xc4G0\xf5\x93_\x1f\x83_\x07\x83\ +_\xff\x82_\xe7\xc2\x84\x8fw\xa8\x13a\x84\xc0\x9c\x10\ +\xa8\x13\xd1\xaa\xec:\x11\x22\xce\x85\x06\x82A\x086!\ +\xb8\x8e\xe0\x19\x82\x08\x16\xc5\x83\xe5\x09\x11\xf4\xb3\xaf\xd3\ +\xef\x1aD\xbf[b\xba\x171os\x04\x81\x08R\x7f\ +\x01\xaf\x12\x86T\xfa\xdd\xe6\xc2\xeb\x90`\xee=\x10\xf8\ +\x22(\xa8\x84y\x0bC\x01=\x97\x1e\xe2\xd6 4\xf7\ +\xc9\x08b\x14`\xde\xc2\x10C\xcf\xad\xd8\x1aD\xcc\x9d\ +\xa5\x00s\x15\x07,\xe15\xb0\x8a\xd3\x8c\x22\xee\xbb(\ +<\x14\xa3%\x16u>|\x15`n\x92\x82/\xab\xf8\ +\x99\x863.\xdf\xb3Z\xccw\xa6#\xe4O\xd3&%\ +\x8b3\x8b\x85\x02z\xce\xfc\xbd\x0f\x94\xcf\xbc\xe9\xb8\xf6\ +\x0a}\x9cW\x011\xdb\xac+\x0ed\xce\x9dC\xd8\xdf\ +\x9bs\xff\x14\x99\xed\xbb\x1b\xdf\x8f\x06\x7f[a|G\ +:\xbfS \xabH6\xc9\xce\xdf\xd1\xbc!\xef\x16\xe6\ +\x9c\x1bv\x11\xc7vx\x05yb\x82\x15<\x92\x97\x93\ +F\xb2\xbf<%\xb3|\x9c\xb0\x1fU\x8a\xbc\xa0TV\ +\x91\x5c\x95m\xcf\xd1{S\xf7\x8c\xc1\xf1\x8b\xd2\xee\x8f\ +\x88\x1b\xe0\x93\x87|\x10|\xaf\xa0|y\xad|\x9d@\ +J\x1a\xa7b\xad\x10'\x87{~\xb2\x0d\x1e\xce\x9f\x01\ +\x7fn9\xe8\x89\xaf\xcfH5w\xf0\x1fC.\xbaX\ +:\x91b@\xdc5m\xffDI\xd7\xc0\xd7\xc5\xca?\ +\x7f\xeb\xe68\x97\xa9\xb4\x5c3\xbc\xab\xec\x5c\x9c\xe3\xc1\ +\xcf}\xc4\xf7\x02\xca\x88\xe3\xc3\xdf\xe2\x9c\xa0\xb2i\x89\ +\xafG\x96s\xefu\xf0\xbdX\x88?\x8b\x9f\xc3'\x1c\ +\xe7\x85\xbc\x0b\xb8\xab\x02yS\x90\xe3\x02\xb9\xdbp\xcf\ +\x0a\x9f\x95R\xee\xa1\xb2?=\xa2cA\xa5\xae\xe1U\ +\xb9\xe7O\xe7!\x88\x8b\xaf\xc3\x9ar\x82\x8e\x15\xdd\xf7\ +,\x96w(\xc0\xff\xd1\xb9I?2\x13\xf1\xa0'b\ +\xd7\x00\xeb/\xe3\x9e@\xf9\xe7\x8f\x00\xf8\xb9\xc8\xb9g\ +\xa7\x91\x99\x1e\xab\x0b\xf3\x08\xca|\x16\xce{\xeb\x8ep\ +\xe1#\xf2y\x90c\x06\xb9\x87\xa5\xc4\x06\xcb7\x7f\xfa\ +\x0e;'9\xae\xe4\xdc\x0b\xf2\xa9<8\xfc\xb7\xe5\xe0\ +\xe3\xb0\x06\xfb\x7fH\xf6\x87\x07\xa2q\x10|B~\xfb\ +\x8f\xde\x95yi\x9d\xc8\xf7@^(\x8e\xc5K\xa3\x13\ +\xc0\x9d\x97}\x13D\xe6{Q\xb9a\xdd\xc5\xe1\xb3|\ +\xf3\xb7n!\xf2^\x07\xc4\x1f\x0b\xf3H\xca;w>\ +\xac\xd0\xc3:F\x89\x81\xf0\x0a\xb9\x1eb\x9e-\xf9\xfc\ +!/\x1f\xf1\x10\xce\x8f\x92\xe7\x16\xee\xb9\x83\xee S\ +\x5c\x13\xdf\xb5\x9e^\x227\x11\x06\xe8L2\xcf\x1fr\ +\xfa\xb6\x0f\x11y\xaf+\xdbo\xbf\xec\xf1w|o\xae\ +\x1b\xce\xaf,A\x9bO/\x8b\xcb_+\xc7\xfc)\x1a\ +\x15\xa5\xdfd^(\xf3>\x9c\x04@\xe7H\x22\xbe/\ +< G\x0a\xe7\xe3\xc8:\xff\xfd\x93\xf0\xfd\xb1\xe2\xc4\ +\xcf\xa5j<\xc8\xe1>\x09\xce\xef\x12q_\x9d\xfd\xee\ +\x1e\x95\xe7$\xe3\xfc!\x87\x81\x97\x97Ur\xff/\xad\ +\x95\xcf\xfe\xafi\x87u\xea\x12\xfb\x1f\x19 \xfb\xfe\x8b\ +\xc8w\xe1\x8f\x9c{'e\xcfy\xc0\xf9D\xbdpN\ +\x9d\xf0\xa0\xee\xeb\x89\xfc^\xb9\xf8\x0f\xe4W\xe6G\xde\ +\xc1\xb6\x09\xbe\x9b\x02\x80\xfe\x1f\xf2\xb4\x81ve\xe3?\ +\xdad\xfa\xa9\x85\x22\xef\xfbg]\xdb\x22;\xff\x01\x80\ +\xdc\xa1\xf5\x9d\xa9;$p\xb7\x04\xc9M\x0c\x90s\x22\ +\xd3}\x12]L\xdf\x90\x9f/\xf8\x1e\xce\x19\x17:c\xf9\xaf\ +\xfdp\xce\x1b\xf0\xe5\xack\x9b\xb1\x1e\x09:2\xce\xb3\ +-_\x9e1}_x\x98H\xb9\x08#\xfb\xe6\x8e\xd2\ +t\xc1b\xf3\x07\x19\x0awKA\x87\x843S\x10\x1f\ +\x85u\xe1bg\x0c\xe9o\xdc\xb4\x84\xe28F\xf6\x17\ +\xd8(\xec\xcfO0\x0d\x17\xe1\xa2\x14|\xd0~\x07\xb8\ +\xeb\x07w\xeaE\x0d\x90e8?M\x92\xf9\xc3>\xec\ +\x1c^\xe2\xee~A\xec+:\x87W\x97\xbe\xdb=\xab\ +T{\x11\xdf\xed\xb6\xd0\xc6x\xc2:\x85\xa0\xbfG \ +O\x15\xceM\xd6\xd5\x8d\xe2k\x05p9d\xe6\xe5\x0d\ +\x92\xdb/X\xbf)\x99\xf7\x0by\x99p\x1f\x8f\xff~\ +\xe0\x05\xe2\x06\xe8q\x90\xef\x96\xb8L\x0b\xd9XVX\ +nfyo\xc2k\x06\xff\x04\xc8o\xb8;\x095\xd3\ +\x00\xb7\xa5\xd9\x91\x14O+3\xef\xbb8\xfd\x8b\xb9\xb3\ +\x02\xb5\xca\xf0\xbe\xc1\xbf?\xbd\x22\xf6\x9d\x9c\x84\xf7\xd4\ +\xfd\x1at\x9e!\x8f\xb1p]H\x87\x84\xfcE|>\ +%\xb9\x13\xf0>\xa4(/\xb8\xf4\xf3\xc3\x8f{\x14\x9e\ +%\xb0A\x0a\xdf\x8b\xecS\xc8\xa3\xc4\xfa\x0d\xdc/X\ +\xdbQ,\xad\xc2\x80\x9cu\x9c\xbf\x86\xd6\x0a\xb8\x97f\ +\xe4\xbf\xbd[\x16\xcd\x0b\x02?fC\xcf_\x07\xf3\x82\ +\xdcG\x1eh\x1d\x0e\xf8lQw\xab\x9a\xe19\xe1\xda\ +\x16\xe9?\xc5\xbe;\xdboo!\x8d\x97w\xfe\xa0\x97\ +@-\x1a\xea~\x94\xc4\xfe\x1f~\xbc\xa9\xe8w\xc0\xff\ +VPwW\xc0\xee\x815\xa4\xee\x1d\x87\xcf\x1b\xf8+\ +3\x5c\x17\x93\xd9\xc8\xae\xc69\xae\x90;)\xe0C\x00\ +\x1e\xce\xbf\xf3\x92\xe9eW\xcal\x05\xe6\xcd\xce\xc3\xf4\ +\x82m\x94\x95\xe5\xce\xff\xe5\xc7\xcaD\xf27\xb8\xc3\x01\ +\xf2\x0f\xe8\x16\xdf\x99\xb5\xd0.\xba\xbb\x079\xaahM\ +\xb0\xb6\xcc\x0b\xab\xf0\x9a\x0a\xf1\x0e\xf2\xe8\xf4b|\x07\ +\x18\xe7}\x0b\x9eSn\x01>\xe7@\x97\xc0\xa3\xa1f\ +a\x92\xad\xa1\xb4\xf6\x03?\xceW\xd2\x7f\x8b\xe6\x01\xbc\ +\x9f?\xc0?YB\xc7,\xbc\xcbW\xb2\xde\x14\xe8\x03\ +8o\xfb\xe0T\x5c_\x09x\x00\x9c#\xb8\xbb\x07\xbe\ +g|\x9f\x91\x9fw,\x9d\xee\xc7\xf7\xdf\x8a\xf6\x9f\xa3\ +\xf9\x00\x0f)\x88\x0dG\xf0\x12\xdf;(\xf7\x1e\x15\xf3\ +\xf7\x0b\x82\x5cj\xa7\xf2\xfd\xe7b\xe3\x17Pk\x09p\ +\x8bA\xb4\xfdPY \x18\xbf(=~T\x91\xf7u\ +\xa5\x07\xe1\xf8\x11?~W\x15zt\x8b\x8a\xdfU\xd9\ +\xf8iU\x8f_\xff\x0e\xf9\x03\xbfC\xfeFU\xcd\x9f\ +\xc1yD\x1a\x04\x11\x03?\xd5\x08\x22\x18~*\xd3\xf9\ +G\xd5Y`2\x0f&\xfc\x87Q\xb4\xaf1\xf0S\xad\ +h\xdf!OK\x9f\xa0z\xfa\x14\xe6ii\x8a\xce\xd3\ +\x12\xc2e\x0d\x16\x95\x1b\xb8\x07\xc1c\x16\xc5\x1f\xbeJ\ +\x091\xf43\xf6\xd0\xcf\xac!L3B\xefn\x8e\xe0\ +\x10\x82\xc4\x0a8w\x89\xf4\xb3\x9b\x8b8K\x00\xffC\ +\x10V\x01\xef\x15\x860\xfa]\xc2\xeb\xfe\x15\xef\x16\x9c\ +\x03\x7f\x1fj\xd0\xfbR\xceg\xe8\x8a\xd6!%\xb73\ +\x0e\xb1\x8ahMr|\xd3\xbayaM|d\x1b\x81\ +\x9f\x18|;\xe9\xc7\xe6P9\x13\xe0\xd3-\xbbfj\ +\x22\xab\x88\xce%{7\xc4\xe4\xd6\x1b\xe1\xbc\x02\x5c\x93\ +\x1ej\x09\x09\xda\xedP\xbf\x22-\x01\xc7\xa2\xc0\xee\xc2\ +\xbam\xe9\xfb\xc1?c\x12\xac[\x07\xfb9\xe0\xbd\x12\ +\xd5\xc1G\xf6\x19\xd8\xcbP\xf3\xae\x949\xf0\xcfw\x99\ +\xefN?6\xbb\x14\x9f\x10W\xec\x9c\xa0\xde\x5c)v\ +?\x9f\xb7\x94\xb2\xe7:\x18\xcf\x90K\x22\xbc>\xf0)\ +\x80\x9f\x11h\x00\xd7@\xf0\xdfO\xf91\x84\xfc?P\ +\x03\x04|\x1c\x22\xf4\xf5\xaf\xa5\xbf_\x17\xfb\x8a\xc0\xaf\ +)8\xc0\x7f\x07\xef\xa4\xfch\xc5\xed'\xb0\xff\xc07\ +Y\xbc\xce\x17\x8f\xcc\xba\xbe\xa5\xfc\xef\x07\xbf\xde\x89y\ +\xc5\xfcz\xb0\x0f\xa9\xb8N\x9a\xb6h\xfa\xa6\xf7\x19h\ +T\xf0n5\xcc9ycOa<\x94\xfe~\xf0k\ +\x85y\x0a\xe0\x99C\xc7d\xca\xb07\xe9\xfc\x1b\xa8g\ +U\xb4\x05<\xea\xfey\xf1\xef\x8a\x7f?\xf8\x0d\xd1^\ +\x82?\x80?\x0a\xbeGIZ\xa7\x86\x8a\x8b\xb9\xfc[\ +\xcc\xf7-\x22^\x22\xfe\xfdP3\xd5i`\xb1\xb8N\ +\xde\x93\xcbd\x19y\x0f\xc5\xe7\x0f~\xcf\x9f\x9f\x04\xce\ +\xc2\x03:\x9e+\xc9\xfb\x9bb\xba\x17\xac\x17\x00\xfeM\ +\xc9\xf9\xab.\xb6\xaf\xe1Ny\xe1\xfe\xc5\xbc\xc0|S\ +\x80nJ\x7f\xff\xf6!\xc5\xea\xa5\xe5>\xf6\x90\xf0\xdd\ +\xf4\xfa\x11\xaf\x14\xc4\x1f\xc4@\x85\xe2I\xa5\xe3\x1f\xed\ +\x1f\xf0\x0f\xa0y\xc8\xad\xc0\xb9\x08\x92\xc6\xa3p\xbd\xbd\ +1\xc5\xf6/\xef\xd9\x15\xe18\x84\x88\xf7\x0b\xd8\xf5\xe8\ +o\x81\x06!\xbf\x07\xe7\xf9@\xcc\x03\x7f_2\xbb_\ +\xd0\xcf\x04CD=\xa4\xa2\xf7\xf3{\xbd ~S\x18\ +[\xa1c\xeb\xe0\x7f\x84\xfc\x0c\x88\xf3\xe2{\xde6\xad\ +K\xc5;U\x93eN1\xdc\x81\x5c\x02?\xa9\xc8\xf3\ +\x0fy~;\x86\xe2\xde2 _\xf2^\x5c\xa3\xe8\xd4\ +B\x9b\xaa\x1b\xc6?\xc2\xe8,A\x1c2\xeb\x86\x13Y\ +8g\xe1\x18\x02:\xf7\xe0\x8b\x17\x96\x15\x98vK\xc6\ +\x80\xa8\xf7C]\x1c\xc4\xbf\x0b\xe7\x9a\xfe\x83\x92\xe3\xe8\ +\x99\xa2r/ 7\x12\xe2\x18\x10\xa7\x009\x0b\xf1\x11\ +\xf0\xbd\xc13\xa0\x86\xa5p\xfe\x16\xf8\xcaD\xf0>\x81\ +\xf5\xf3\xcf:\x95\xc3\x00\xfc\x16\xea\xeb\x80\xfc\xc6\xf2V\ +`\x80\xcf\x1e\xeaxB\x0c\x0c\xd7\x92E<\x11\xf2\x93\ +\xb0\xbfVD\xdc\x01\xf2\xc5\xc0\x17*&g\x8d\xd6\x91\ +\xa9\xda\x80\xb9\xf7]1\xae3\x5c\x17b\xff6\xe4\xba\ +B\x1cVp\x80\x9f\x1bbU\xc9\x1b\x8c\x8a\xf1\x16Q\ +\x03\xea2\xc1\xbe\x94\xc23\xf8\xfa9\xf5\xd9\xba\x05\xf6\ +E\x83\xdf\x16x5\xd0>\xaeOq}+>;\xd0\ +?\x04\xe2\xc4\x98F\x817\x8b\x88\xcd\x81\xdf\x19jU\ +\x80\x5c\x869\x96\x91\xab\xc7\xb7\x0d\x8ax.Z\x1b\xd4\ +\x82\x85\xb8\x1b\xce\x0f\x82\x18(\x9d\xfb\x0by\xa4\xb8\x9e\ +\x14\xf0`\xc8SC4\x9e\xed\xbb\x0b\xe7\xffB\xedJ\ +\x1cs<<\x93\xf2\xc1JVG\x8eo\x97$\x16\xf1\ +\xac\xce\xb8n\x0d\xc8p*\x8fX\xe0\x19\xc2>?\xc1\ +\xfb\xed\x82y\xd5\x92\xf9\x05\xf9\xfagI\xfd[\xfa\xdc\ +\xe5\xf2\x00_\xff\xe6\xdb\x1fO*\xf8}\x82 h\x7f\ +(\x82\xfdUi\xf6ge\xdb\xdf\xccJ\xf4\xc6\xc0\xbb\ +\xc1O\xa1IP\xbe\x8aB?E\x8d\x92~\x0az\xce\ +\x0d\x100\x11\xbcG\x90\x8e C\x0c\xa4\xd3\x7f\xc3\xa4\ +\xbf\xc3\xff\xee9\x04\xdc\x12\xb8\x11\x7fv\xb9\xf4w\xf8\ +\xef\xe5\x96\xf8\x1e\xe4C >\x0du\xe7 \xa6\x07\xf9\ +'B|\x82+0\xe7b\xdf\x858\x19\xd4\xbc\x05\xdd\ +\x06\xc7\x82\xe9\xdeeX\xbe\xad-\xc6{\xf8\xeb-\xe4\ +C\xa0\x8f\xf0\xfbH\x80L\x86\x5c\xd7\xfc\x08\xbf\xc2\xba\ +3\xa0\xeb\x0a\xd4\x92\xe5\xefU\xe1\xf7!\xf7\x0f\x06<\ +\x03\xea\xc9\xe0\xba\xd7\xd6\xcd\xb1\xbc\x80\xb8\x92\x90\xbe\x9e\ +Q\xf8\xfd\xc2zDo\xb0n\x8c\xf3\xe2-\x04\xe2g\ +\x88_S\xb9\x08\xf9T~\x1b\x15\xdf\x11\xf8>U\x1f\ +\x06x<\xe4d\x95\xc8o\xc49\x08]q\xfdH\x88\ +\x9b'Q9*E\xdf\x07\x1b\x0b\xed7\xd4\xc3\xc3}\ +;\x84\xeb\xe5\xf2\xeb\xb1!\x1d\x02rQh\x1eN}\ +\x1fz\x06B\xdcxe\x0b\xec+H?\xb5\x80\xea\xaf\ +\x22X\xbb\x13\xfd?U\x9f\x93\xc4u\x04i}\x1f\x7f\ +\x1f\xf0\x022\x15\xea{\x81M\x08\xf8\x02\x9d\x18\xea\x99\ +\xa6\xee\x1c\x86\xf5\xf5\xec\xdb{q\xcc\x98\x9b\x9e\x88\xf5\ +OZ\xfee\xa0\x9f\xe9`\x93\xc1\x9cqn\x08]\x03\ +\x12\xf2xA\xbe\xc2w\xf89p \xfb\xa0G\x8a\x00\ +\xbdP\xf4\x8c\xf0\x93q\xde\x1a\xe7\x99C>\x04\xe8f\ +\xd0O\x03\xe4 \xc4z\xa1\x87\x16\xc4[\xa9\xbb\x0a\xc5\ +\xe8\x98:\x0b\xcbu\xb9)\xdb\x07Sz\xa0`\xcc\x16\ +\xeau\x01\x9e\xf8=\xe2\x8a\xcb\x1e>\xfdR\xe7g\xb9\ +\x0e\xb7\x1c\xb2I\xf0\xfc\xc8t~e\x1d\xff\x07\x9d\xab\ +\xf3\x85\ \x00\x00_\x84\ I\ I*\x00\x08\x00\x00\x00\x17\x00\xfe\x00\x04\x00\x01\x00\x00\ @@ -26805,336 +26919,336 @@ qt_resource_struct = b"\ \x00\x00\x03\xa8\x00\x02\x00\x00\x00\x01\x00\x00\x00+\ \x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x06\x0c\x00\x01\x00\x00\x00\x01\x00\x00\xde\xc4\ -\x00\x00\x01y\x1f\xa4\xb3Q\ -\x00\x00\x16\x86\x00\x00\x00\x00\x00\x01\x00\x05\x97+\ +\x00\x00\x01y\xd2\xb2\xf5B\ +\x00\x00\x16\x86\x00\x00\x00\x00\x00\x01\x00\x05\x9eC\ \x00\x00\x01x\xc7F\xed\xa9\ -\x00\x00\x16:\x00\x00\x00\x00\x00\x01\x00\x05\x95\x7f\ +\x00\x00\x16:\x00\x00\x00\x00\x00\x01\x00\x05\x9c\x97\ \x00\x00\x01x\xc7F\xf0\x97\ -\x00\x00\x16`\x00\x00\x00\x00\x00\x01\x00\x05\x96S\ +\x00\x00\x16`\x00\x00\x00\x00\x00\x01\x00\x05\x9dk\ \x00\x00\x01x\xc7F\xeb4\ -\x00\x00\x16\x1c\x00\x00\x00\x00\x00\x01\x00\x05\x94\x8c\ +\x00\x00\x16\x1c\x00\x00\x00\x00\x00\x01\x00\x05\x9b\xa4\ \x00\x00\x01x\xc7F\xf0\x87\ \x00\x00\x03\xa8\x00\x02\x00\x00\x00\x1f\x00\x00\x001\ \x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x13\xb4\x00\x00\x00\x00\x00\x01\x00\x05\x80\xf9\ +\x00\x00\x13\xb4\x00\x00\x00\x00\x00\x01\x00\x05\x88\x11\ \x00\x00\x01x\xc7D\x85\xca\ -\x00\x00\x14\x06\x00\x00\x00\x00\x00\x01\x00\x05\x83\x8d\ +\x00\x00\x14\x06\x00\x00\x00\x00\x00\x01\x00\x05\x8a\xa5\ \x00\x00\x01x\xc7D\x85\xcc\ -\x00\x00\x15v\x00\x00\x00\x00\x00\x01\x00\x05\x90T\ +\x00\x00\x15v\x00\x00\x00\x00\x00\x01\x00\x05\x97l\ \x00\x00\x01x\xc7D\x85\xc3\ -\x00\x00\x12\xf0\x00\x00\x00\x00\x00\x01\x00\x05z\x87\ +\x00\x00\x12\xf0\x00\x00\x00\x00\x00\x01\x00\x05\x81\x9f\ \x00\x00\x01x\xc7D\x83\xc5\ -\x00\x00\x12|\x00\x00\x00\x00\x00\x01\x00\x05w\x97\ +\x00\x00\x12|\x00\x00\x00\x00\x00\x01\x00\x05~\xaf\ \x00\x00\x01x\xc7D\x85\xbb\ -\x00\x00\x152\x00\x00\x00\x00\x00\x01\x00\x05\x8d\xc0\ +\x00\x00\x152\x00\x00\x00\x00\x00\x01\x00\x05\x94\xd8\ \x00\x00\x01x\xc7D\x85e\ -\x00\x00\x12\x9e\x00\x00\x00\x00\x00\x01\x00\x05x\xe1\ +\x00\x00\x12\x9e\x00\x00\x00\x00\x00\x01\x00\x05\x7f\xf9\ \x00\x00\x01x\xc7D\x85\xd0\ -\x00\x00\x14\xf6\x00\x00\x00\x00\x00\x01\x00\x05\x8b,\ +\x00\x00\x14\xf6\x00\x00\x00\x00\x00\x01\x00\x05\x92D\ \x00\x00\x01x\xc7D\x84\xb4\ -\x00\x00\x11\xce\x00\x01\x00\x00\x00\x01\x00\x05s\x95\ +\x00\x00\x11\xce\x00\x01\x00\x00\x00\x01\x00\x05z\xad\ \x00\x00\x01x\xc7D\x83\xca\ -\x00\x00\x12(\x00\x00\x00\x00\x00\x01\x00\x05u\xe9\ +\x00\x00\x12(\x00\x00\x00\x00\x00\x01\x00\x05}\x01\ \x00\x00\x01x\xc7D\x85\xd2\ -\x00\x00\x12\x0c\x00\x01\x00\x00\x00\x01\x00\x05u>\ +\x00\x00\x12\x0c\x00\x01\x00\x00\x00\x01\x00\x05|V\ \x00\x00\x01x\xc7D\x84\x12\ -\x00\x00\x11\xf0\x00\x00\x00\x00\x00\x01\x00\x05s\xf4\ +\x00\x00\x11\xf0\x00\x00\x00\x00\x00\x01\x00\x05{\x0c\ \x00\x00\x01x\xc7D\x84\x12\ -\x00\x00\x12\xc8\x00\x01\x00\x00\x00\x01\x00\x05z+\ +\x00\x00\x12\xc8\x00\x01\x00\x00\x00\x01\x00\x05\x81C\ \x00\x00\x01x\xc7D\x83\xcf\ -\x00\x00\x13\x12\x00\x00\x00\x00\x00\x01\x00\x05{\xd1\ +\x00\x00\x13\x12\x00\x00\x00\x00\x00\x01\x00\x05\x82\xe9\ \x00\x00\x01x\xc7D\x85\xc7\ -\x00\x00\x13\xe0\x00\x00\x00\x00\x00\x01\x00\x05\x82C\ +\x00\x00\x13\xe0\x00\x00\x00\x00\x00\x01\x00\x05\x89[\ \x00\x00\x01x\xc7D\x85\xc8\ -\x00\x00\x13\x90\x00\x00\x00\x00\x00\x01\x00\x05\x7f\xaf\ +\x00\x00\x13\x90\x00\x00\x00\x00\x00\x01\x00\x05\x86\xc7\ \x00\x00\x01x\xc7D\x85d\ -\x00\x00\x13B\x00\x00\x00\x00\x00\x01\x00\x05}\x1b\ +\x00\x00\x13B\x00\x00\x00\x00\x00\x01\x00\x05\x843\ \x00\x00\x01x\xc7D\x85\xce\ -\x00\x00\x12\x5c\x00\x01\x00\x00\x00\x01\x00\x05w3\ +\x00\x00\x12\x5c\x00\x01\x00\x00\x00\x01\x00\x05~K\ \x00\x00\x01x\xc7D\x85-\ -\x00\x00\x15\xc4\x00\x01\x00\x00\x00\x01\x00\x05\x92\xe8\ +\x00\x00\x15\xc4\x00\x01\x00\x00\x00\x01\x00\x05\x9a\x00\ \x00\x00\x01x\xc7D\x83\xcb\ -\x00\x00\x14.\x00\x01\x00\x00\x00\x01\x00\x05\x84\xd7\ +\x00\x00\x14.\x00\x01\x00\x00\x00\x01\x00\x05\x8b\xef\ \x00\x00\x01x\xc7D\x85\xb9\ -\x00\x00\x14Z\x00\x01\x00\x00\x00\x01\x00\x05\x85\xa4\ +\x00\x00\x14Z\x00\x01\x00\x00\x00\x01\x00\x05\x8c\xbc\ \x00\x00\x01x\xc7D\x83\xcc\ -\x00\x00\x13h\x00\x00\x00\x00\x00\x01\x00\x05~e\ +\x00\x00\x13h\x00\x00\x00\x00\x00\x01\x00\x05\x85}\ \x00\x00\x01x\xc7D\x85d\ -\x00\x00\x14x\x00\x00\x00\x00\x00\x01\x00\x05\x86\x04\ +\x00\x00\x14x\x00\x00\x00\x00\x00\x01\x00\x05\x8d\x1c\ \x00\x00\x01x\xc7D\x85\xb6\ -\x00\x00\x15\x94\x00\x00\x00\x00\x00\x01\x00\x05\x91\x9e\ +\x00\x00\x15\x94\x00\x00\x00\x00\x00\x01\x00\x05\x98\xb6\ \x00\x00\x01x\xc7D\x85\xd4\ -\x00\x00\x14\x9c\x00\x00\x00\x00\x00\x01\x00\x05\x87N\ +\x00\x00\x14\x9c\x00\x00\x00\x00\x00\x01\x00\x05\x8ef\ \x00\x00\x01x\xc7D\x84\x0b\ -\x00\x00\x14\xba\x00\x00\x00\x00\x00\x01\x00\x05\x88\x98\ +\x00\x00\x14\xba\x00\x00\x00\x00\x00\x01\x00\x05\x8f\xb0\ \x00\x00\x01x\xc7D\x84\x0d\ -\x00\x00\x14\xd8\x00\x00\x00\x00\x00\x01\x00\x05\x89\xe2\ +\x00\x00\x14\xd8\x00\x00\x00\x00\x00\x01\x00\x05\x90\xfa\ \x00\x00\x01x\xc7D\x84\x0e\ -\x00\x00\x15\x14\x00\x00\x00\x00\x00\x01\x00\x05\x8cv\ +\x00\x00\x15\x14\x00\x00\x00\x00\x00\x01\x00\x05\x93\x8e\ \x00\x00\x01x\xc7D\x84\x0e\ -\x00\x00\x15X\x00\x00\x00\x00\x00\x01\x00\x05\x8f\x0a\ +\x00\x00\x15X\x00\x00\x00\x00\x00\x01\x00\x05\x96\x22\ \x00\x00\x01x\xc7D\x84\x0f\ -\x00\x00\x11\xba\x00\x01\x00\x00\x00\x01\x00\x05s6\ +\x00\x00\x11\xba\x00\x01\x00\x00\x00\x01\x00\x05zN\ \x00\x00\x01x\xc7D\x84\xb5\ -\x00\x00\x15\xf0\x00\x00\x00\x00\x00\x01\x00\x05\x93B\ +\x00\x00\x15\xf0\x00\x00\x00\x00\x00\x01\x00\x05\x9aZ\ \x00\x00\x01x\xc7D\x85\xc5\ \x00\x00\x03\xa8\x00\x02\x00\x00\x00\x08\x00\x00\x00Q\ \x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00$\x98\x00\x00\x00\x00\x00\x01\x00\x06+\x0e\ +\x00\x00$\x98\x00\x00\x00\x00\x00\x01\x00\x062&\ \x00\x00\x01y+\x8f\x94\x0d\ -\x00\x00#\xa8\x00\x00\x00\x00\x00\x01\x00\x06\x16\xea\ +\x00\x00#\xa8\x00\x00\x00\x00\x00\x01\x00\x06\x1e\x02\ \x00\x00\x01y+\x8f\x94\x0b\ -\x00\x00$\x0a\x00\x00\x00\x00\x00\x01\x00\x06\x1e\xba\ +\x00\x00$\x0a\x00\x00\x00\x00\x00\x01\x00\x06%\xd2\ \x00\x00\x01y+\x8f\x94\x0b\ -\x00\x00$p\x00\x00\x00\x00\x00\x01\x00\x06&\x8c\ +\x00\x00$p\x00\x00\x00\x00\x00\x01\x00\x06-\xa4\ \x00\x00\x01x\xc7F\xf7d\ -\x00\x00#\xe6\x00\x00\x00\x00\x00\x01\x00\x06\x1a8\ +\x00\x00#\xe6\x00\x00\x00\x00\x00\x01\x00\x06!P\ \x00\x00\x01x\xc7F\xf6\xff\ -\x00\x00#D\x00\x00\x00\x00\x00\x01\x00\x06\x0f\x1e\ +\x00\x00#D\x00\x00\x00\x00\x00\x01\x00\x06\x166\ \x00\x00\x01x\xc7F\xf6\xed\ -\x00\x00$J\x00\x00\x00\x00\x00\x01\x00\x06\x22\x0a\ +\x00\x00$J\x00\x00\x00\x00\x00\x01\x00\x06)\x22\ \x00\x00\x01x\xc7F\xf6\xf0\ -\x00\x00#j\x00\x00\x00\x00\x00\x01\x00\x06\x13\xa0\ +\x00\x00#j\x00\x00\x00\x00\x00\x01\x00\x06\x1a\xb8\ \x00\x00\x01y+\x8f\x94\x0c\ \x00\x00\x16\xba\x00\x02\x00\x00\x009\x00\x00\x00Z\ \x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00 :\x00\x00\x00\x00\x00\x01\x00\x05\xf1\xf4\ +\x00\x00 :\x00\x00\x00\x00\x00\x01\x00\x05\xf9\x0c\ \x00\x00\x01x\xc7F\xf0|\ -\x00\x00#\x0e\x00\x00\x00\x00\x00\x01\x00\x06\x0a1\ +\x00\x00#\x0e\x00\x00\x00\x00\x00\x01\x00\x06\x11I\ \x00\x00\x01x\xc7F\xed\xa1\ -\x00\x00\x1e\xb2\x00\x00\x00\x00\x00\x01\x00\x05\xe2\xb6\ +\x00\x00\x1e\xb2\x00\x00\x00\x00\x00\x01\x00\x05\xe9\xce\ \x00\x00\x01x\xc7F\xef\xf0\ -\x00\x00\x19\x08\x00\x00\x00\x00\x00\x01\x00\x05\xaf\x1d\ +\x00\x00\x19\x08\x00\x00\x00\x00\x00\x01\x00\x05\xb65\ \x00\x00\x01x\xc7F\xf0\xa1\ -\x00\x00!\xbc\x00\x00\x00\x00\x00\x01\x00\x05\xff\xfd\ +\x00\x00!\xbc\x00\x00\x00\x00\x00\x01\x00\x06\x07\x15\ \x00\x00\x01x\xc7F\xf0W\ -\x00\x00\x17@\x00\x00\x00\x00\x00\x01\x00\x05\x9d\xdd\ +\x00\x00\x17@\x00\x00\x00\x00\x00\x01\x00\x05\xa4\xf5\ \x00\x00\x01x\xc7F\xed\xd6\ -\x00\x00\x19\xae\x00\x00\x00\x00\x00\x01\x00\x05\xb2\xec\ +\x00\x00\x19\xae\x00\x00\x00\x00\x00\x01\x00\x05\xba\x04\ \x00\x00\x01x\xc7F\xe9{\ -\x00\x00\x22b\x00\x00\x00\x00\x00\x01\x00\x06\x04c\ +\x00\x00\x22b\x00\x00\x00\x00\x00\x01\x00\x06\x0b{\ \x00\x00\x01x\xc7F\xef\xab\ -\x00\x00\x1b\xde\x00\x00\x00\x00\x00\x01\x00\x05\xc5\xad\ +\x00\x00\x1b\xde\x00\x00\x00\x00\x00\x01\x00\x05\xcc\xc5\ \x00\x00\x01x\xc7F\xcb~\ -\x00\x00\x18,\x00\x00\x00\x00\x00\x01\x00\x05\xa5\x22\ +\x00\x00\x18,\x00\x00\x00\x00\x00\x01\x00\x05\xac:\ \x00\x00\x01x\xc7F\xf0\x90\ -\x00\x00\x1a\xd6\x00\x00\x00\x00\x00\x01\x00\x05\xba\xbf\ +\x00\x00\x1a\xd6\x00\x00\x00\x00\x00\x01\x00\x05\xc1\xd7\ \x00\x00\x01x\xc7F\xe9@\ -\x00\x00\x1e<\x00\x00\x00\x00\x00\x01\x00\x05\xdcu\ +\x00\x00\x1e<\x00\x00\x00\x00\x00\x01\x00\x05\xe3\x8d\ \x00\x00\x01x\xc7F\xf0=\ -\x00\x00 \xe0\x00\x00\x00\x00\x00\x01\x00\x05\xf6-\ +\x00\x00 \xe0\x00\x00\x00\x00\x00\x01\x00\x05\xfdE\ \x00\x00\x01x\xc7F\xf0\x03\ -\x00\x00\x1c\xba\x00\x00\x00\x00\x00\x01\x00\x05\xd0B\ +\x00\x00\x1c\xba\x00\x00\x00\x00\x00\x01\x00\x05\xd7Z\ \x00\x00\x01x\xc7F\xed\xd8\ -\x00\x00\x1f\x8e\x00\x00\x00\x00\x00\x01\x00\x05\xec\xea\ +\x00\x00\x1f\x8e\x00\x00\x00\x00\x00\x01\x00\x05\xf4\x02\ \x00\x00\x01x\xc7F\xed\xda\ -\x00\x00\x1cT\x00\x00\x00\x00\x00\x01\x00\x05\xcb\x82\ +\x00\x00\x1cT\x00\x00\x00\x00\x00\x01\x00\x05\xd2\x9a\ \x00\x00\x01x\xc7F\xcc\x09\ -\x00\x00\x18b\x00\x00\x00\x00\x00\x01\x00\x05\xa6\x14\ +\x00\x00\x18b\x00\x00\x00\x00\x00\x01\x00\x05\xad,\ \x00\x00\x01x\xc7F\xe9f\ -\x00\x00\x1e\xe8\x00\x00\x00\x00\x00\x01\x00\x05\xe4c\ +\x00\x00\x1e\xe8\x00\x00\x00\x00\x00\x01\x00\x05\xeb{\ \x00\x00\x01x\xc7F\xe9\x86\ -\x00\x00\x1b\x0c\x00\x00\x00\x00\x00\x01\x00\x05\xbc\x0d\ +\x00\x00\x1b\x0c\x00\x00\x00\x00\x00\x01\x00\x05\xc3%\ \x00\x00\x01x\xc7F\xcb\xfe\ -\x00\x00\x1d\x96\x00\x00\x00\x00\x00\x01\x00\x05\xd7\x13\ +\x00\x00\x1d\x96\x00\x00\x00\x00\x00\x01\x00\x05\xde+\ \x00\x00\x01x\xc7F\xe9\x82\ -\x00\x00!\x16\x00\x00\x00\x00\x00\x01\x00\x05\xf7\xeb\ +\x00\x00!\x16\x00\x00\x00\x00\x00\x01\x00\x05\xff\x03\ \x00\x00\x01x\xc7F\xe7N\ -\x00\x00\x17v\x00\x00\x00\x00\x00\x01\x00\x05\x9f\xff\ +\x00\x00\x17v\x00\x00\x00\x00\x00\x01\x00\x05\xa7\x17\ \x00\x00\x01x\xc7F\xe97\ -\x00\x00\x1f\xc4\x00\x00\x00\x00\x00\x01\x00\x05\xee\xfa\ +\x00\x00\x1f\xc4\x00\x00\x00\x00\x00\x01\x00\x05\xf6\x12\ \x00\x00\x01x\xc7F\xe7\xa5\ -\x00\x00\x22\x98\x00\x00\x00\x00\x00\x01\x00\x06\x06c\ +\x00\x00\x22\x98\x00\x00\x00\x00\x00\x01\x00\x06\x0d{\ \x00\x00\x01x\xc7F\xe6\xb8\ -\x00\x00\x19\xe4\x00\x00\x00\x00\x00\x01\x00\x05\xb4\x0b\ +\x00\x00\x19\xe4\x00\x00\x00\x00\x00\x01\x00\x05\xbb#\ \x00\x00\x01x\xc7F\xef\xeb\ -\x00\x00\x1d\x16\x00\x00\x00\x00\x00\x01\x00\x05\xd3\xe3\ +\x00\x00\x1d\x16\x00\x00\x00\x00\x00\x01\x00\x05\xda\xfb\ \x00\x00\x01x\xc7F\xef\xe2\ -\x00\x00\x1bn\x00\x00\x00\x00\x00\x01\x00\x05\xc1)\ +\x00\x00\x1bn\x00\x00\x00\x00\x00\x01\x00\x05\xc8A\ \x00\x00\x01x\xc7F\xef\x93\ -\x00\x00\x1af\x00\x00\x00\x00\x00\x01\x00\x05\xb7h\ +\x00\x00\x1af\x00\x00\x00\x00\x00\x01\x00\x05\xbe\x80\ \x00\x00\x01x\xc7F\xef\xee\ -\x00\x00\x19>\x00\x00\x00\x00\x00\x01\x00\x05\xaf\xef\ +\x00\x00\x19>\x00\x00\x00\x00\x00\x01\x00\x05\xb7\x07\ \x00\x00\x01x\xc7F\xf00\ -\x00\x00\x17\xec\x00\x00\x00\x00\x00\x01\x00\x05\xa2\xf2\ +\x00\x00\x17\xec\x00\x00\x00\x00\x00\x01\x00\x05\xaa\x0a\ \x00\x00\x01x\xc7F\xed\xd3\ -\x00\x00\x16\xd0\x00\x00\x00\x00\x00\x01\x00\x05\x9b\x19\ +\x00\x00\x16\xd0\x00\x00\x00\x00\x00\x01\x00\x05\xa21\ \x00\x00\x01x\xc7F\xef\xe6\ -\x00\x00!\xf2\x00\x00\x00\x00\x00\x01\x00\x06\x01P\ +\x00\x00!\xf2\x00\x00\x00\x00\x00\x01\x00\x06\x08h\ \x00\x00\x01x\xc7F\xf0f\ -\x00\x00 p\x00\x00\x00\x00\x00\x01\x00\x05\xf2\xfb\ +\x00\x00 p\x00\x00\x00\x00\x00\x01\x00\x05\xfa\x13\ \x00\x00\x01x\xc7F\xf0k\ -\x00\x00\x1f\x1e\x00\x00\x00\x00\x00\x01\x00\x05\xe5k\ +\x00\x00\x1f\x1e\x00\x00\x00\x00\x00\x01\x00\x05\xec\x83\ \x00\x00\x01x\xc7F\xed\xc2\ -\x00\x00\x1d\xcc\x00\x00\x00\x00\x00\x01\x00\x05\xd8!\ +\x00\x00\x1d\xcc\x00\x00\x00\x00\x00\x01\x00\x05\xdf9\ \x00\x00\x01x\xc7F\xf0\x0e\ -\x00\x00\x1a&\x00\x00\x00\x00\x00\x01\x00\x05\xb5\xde\ +\x00\x00\x1a&\x00\x00\x00\x00\x00\x01\x00\x05\xbc\xf6\ \x00\x00\x01x\xc7F\xf0%\ -\x00\x00\x18\x98\x00\x00\x00\x00\x00\x01\x00\x05\xa7M\ +\x00\x00\x18\x98\x00\x00\x00\x00\x00\x01\x00\x05\xaee\ \x00\x00\x01x\xc7F\xf0I\ -\x00\x00\x17\xac\x00\x00\x00\x00\x00\x01\x00\x05\xa1s\ +\x00\x00\x17\xac\x00\x00\x00\x00\x00\x01\x00\x05\xa8\x8b\ \x00\x00\x01x\xc7F\xf0,\ -\x00\x00\x22\xce\x00\x00\x00\x00\x00\x01\x00\x06\x08\x1f\ +\x00\x00\x22\xce\x00\x00\x00\x00\x00\x01\x00\x06\x0f7\ \x00\x00\x01x\xc7F\xed\xdd\ -\x00\x00!|\x00\x00\x00\x00\x00\x01\x00\x05\xfe\x91\ +\x00\x00!|\x00\x00\x00\x00\x00\x01\x00\x06\x05\xa9\ \x00\x00\x01x\xc7F\xf04\ -\x00\x00\x1f\xfa\x00\x00\x00\x00\x00\x01\x00\x05\xf0{\ +\x00\x00\x1f\xfa\x00\x00\x00\x00\x00\x01\x00\x05\xf7\x93\ \x00\x00\x01x\xc7F\xf0*\ -\x00\x00\x1er\x00\x00\x00\x00\x00\x01\x00\x05\xdd\xd6\ +\x00\x00\x1er\x00\x00\x00\x00\x00\x01\x00\x05\xe4\xee\ \x00\x00\x01x\xc7F\xed\xc6\ -\x00\x00\x1dV\x00\x00\x00\x00\x00\x01\x00\x05\xd5\xb7\ +\x00\x00\x1dV\x00\x00\x00\x00\x00\x01\x00\x05\xdc\xcf\ \x00\x00\x01x\xc7F\xf0@\ -\x00\x00\x1c\x14\x00\x00\x00\x00\x00\x01\x00\x05\xca)\ +\x00\x00\x1c\x14\x00\x00\x00\x00\x00\x01\x00\x05\xd1A\ \x00\x00\x01x\xc7F\xf0K\ -\x00\x00\x1bB\x00\x00\x00\x00\x00\x01\x00\x05\xbe&\ +\x00\x00\x1bB\x00\x00\x00\x00\x00\x01\x00\x05\xc5>\ \x00\x00\x01x\xc7F\xed\xcb\ -\x00\x00\x1e\x0c\x00\x00\x00\x00\x00\x01\x00\x05\xd9\xa3\ +\x00\x00\x1e\x0c\x00\x00\x00\x00\x00\x01\x00\x05\xe0\xbb\ \x00\x00\x01x\xc7F\xed\xc8\ -\x00\x00 \xb0\x00\x00\x00\x00\x00\x01\x00\x05\xf4(\ +\x00\x00 \xb0\x00\x00\x00\x00\x00\x01\x00\x05\xfb@\ \x00\x00\x01x\xc7F\xef\xa6\ -\x00\x00\x1c\x8a\x00\x00\x00\x00\x00\x01\x00\x05\xcd\x7f\ +\x00\x00\x1c\x8a\x00\x00\x00\x00\x00\x01\x00\x05\xd4\x97\ \x00\x00\x01x\xc7F\xed\xce\ -\x00\x00\x17\x10\x00\x00\x00\x00\x00\x01\x00\x05\x9c\xd8\ +\x00\x00\x17\x10\x00\x00\x00\x00\x00\x01\x00\x05\xa3\xf0\ \x00\x00\x01x\xc7F\xf0\x80\ -\x00\x00\x1f^\x00\x00\x00\x00\x00\x01\x00\x05\xeb\x8c\ +\x00\x00\x1f^\x00\x00\x00\x00\x00\x01\x00\x05\xf2\xa4\ \x00\x00\x01x\xc7F\xf0:\ -\x00\x00\x19~\x00\x00\x00\x00\x00\x01\x00\x05\xb1p\ +\x00\x00\x19~\x00\x00\x00\x00\x00\x01\x00\x05\xb8\x88\ \x00\x00\x01x\xc7F\xf0(\ -\x00\x00\x222\x00\x00\x00\x00\x00\x01\x00\x06\x02\x83\ +\x00\x00\x222\x00\x00\x00\x00\x00\x01\x00\x06\x09\x9b\ \x00\x00\x01x\xc7F\xef\xdd\ -\x00\x00\x1b\xae\x00\x00\x00\x00\x00\x01\x00\x05\xc3\x18\ +\x00\x00\x1b\xae\x00\x00\x00\x00\x00\x01\x00\x05\xca0\ \x00\x00\x01x\xc7F\xed\xd1\ -\x00\x00!L\x00\x00\x00\x00\x00\x01\x00\x05\xf9\xa7\ +\x00\x00!L\x00\x00\x00\x00\x00\x01\x00\x06\x00\xbf\ \x00\x00\x01y+\x8f\x93{\ -\x00\x00\x1a\xa6\x00\x00\x00\x00\x00\x01\x00\x05\xb92\ +\x00\x00\x1a\xa6\x00\x00\x00\x00\x00\x01\x00\x05\xc0J\ \x00\x00\x01x\xc7F\xf0\x0c\ -\x00\x00\x18\xd8\x00\x00\x00\x00\x00\x01\x00\x05\xa8\xa5\ +\x00\x00\x18\xd8\x00\x00\x00\x00\x00\x01\x00\x05\xaf\xbd\ \x00\x00\x01x\xc7F\xed\xa4\ -\x00\x00\x1c\xf0\x00\x00\x00\x00\x00\x01\x00\x05\xd2\x83\ +\x00\x00\x1c\xf0\x00\x00\x00\x00\x00\x01\x00\x05\xd9\x9b\ \x00\x00\x01x\xc7F\xe9<\ -\x00\x00\x0e\xba\x00\x00\x00\x00\x00\x01\x00\x04(&\ +\x00\x00\x0e\xba\x00\x00\x00\x00\x00\x01\x00\x04/>\ \x00\x00\x01y+\x8f\x94\x12\ -\x00\x00\x0d\x0a\x00\x00\x00\x00\x00\x01\x00\x03\x91\x87\ +\x00\x00\x0d\x0a\x00\x00\x00\x00\x00\x01\x00\x03\x98\x9f\ \x00\x00\x01y+\x8f\x93\xdc\ -\x00\x00\x0e\x80\x00\x00\x00\x00\x00\x01\x00\x04#\x0e\ +\x00\x00\x0e\x80\x00\x00\x00\x00\x00\x01\x00\x04*&\ \x00\x00\x01y+\x8f\x94\x08\ -\x00\x00\x0d~\x00\x00\x00\x00\x00\x01\x00\x03\xf4\x82\ +\x00\x00\x0d~\x00\x00\x00\x00\x00\x01\x00\x03\xfb\x9a\ \x00\x00\x01y+\x8f\x93\xcd\ -\x00\x00\x09\xf6\x00\x00\x00\x00\x00\x01\x00\x032\x17\ +\x00\x00\x09\xf6\x00\x00\x00\x00\x00\x01\x00\x039/\ \x00\x00\x01y+\x8f\x94\x10\ -\x00\x00\x09f\x00\x01\x00\x00\x00\x01\x00\x02i(\ +\x00\x00\x09f\x00\x01\x00\x00\x00\x01\x00\x02p@\ \x00\x00\x01x\xc7F\xf5\xfe\ -\x00\x00\x07\x12\x00\x00\x00\x00\x00\x01\x00\x01\x87\xf3\ +\x00\x00\x07\x12\x00\x00\x00\x00\x00\x01\x00\x01\x8f\x0b\ \x00\x00\x01y+\x8f\x93\xce\ -\x00\x00\x08:\x00\x00\x00\x00\x00\x01\x00\x01\xa3\x1b\ +\x00\x00\x08:\x00\x00\x00\x00\x00\x01\x00\x01\xaa3\ \x00\x00\x01y+\x8f\x94\x0a\ -\x00\x00\x0f$\x00\x00\x00\x00\x00\x01\x00\x04jD\ +\x00\x00\x0f$\x00\x00\x00\x00\x00\x01\x00\x04q\x5c\ \x00\x00\x01x\xc7F\xf6G\ -\x00\x00\x0e\x10\x00\x00\x00\x00\x00\x01\x00\x04\x15\xa7\ +\x00\x00\x0e\x10\x00\x00\x00\x00\x00\x01\x00\x04\x1c\xbf\ \x00\x00\x01y+\x8f\x93\xe3\ -\x00\x00\x08\xd2\x00\x00\x00\x00\x00\x01\x00\x02^f\ +\x00\x00\x08\xd2\x00\x00\x00\x00\x00\x01\x00\x02e~\ \x00\x00\x01y+\x8f\x93\xd6\ -\x00\x00\x0eL\x00\x00\x00\x00\x00\x01\x00\x04\x1d\xe2\ +\x00\x00\x0eL\x00\x00\x00\x00\x00\x01\x00\x04$\xfa\ \x00\x00\x01y+\x8f\x94\x09\ -\x00\x00\x09*\x00\x00\x00\x00\x00\x01\x00\x02f\x89\ +\x00\x00\x09*\x00\x00\x00\x00\x00\x01\x00\x02m\xa1\ \x00\x00\x01y+\x8f\x94\x07\ -\x00\x00\x0c \x00\x00\x00\x00\x00\x01\x00\x03u!\ +\x00\x00\x0c \x00\x00\x00\x00\x00\x01\x00\x03|9\ \x00\x00\x01y+\x8f\x93\xd5\ -\x00\x00\x07z\x00\x00\x00\x00\x00\x01\x00\x01\x96/\ +\x00\x00\x07z\x00\x00\x00\x00\x00\x01\x00\x01\x9dG\ \x00\x00\x01y+\x8f\x93\xdf\ -\x00\x00\x08x\x00\x00\x00\x00\x00\x01\x00\x01\xbe\xd0\ +\x00\x00\x08x\x00\x00\x00\x00\x00\x01\x00\x01\xc5\xe8\ \x00\x00\x01x\xc7F\xf6*\ -\x00\x00\x0f\x9c\x00\x00\x00\x00\x00\x01\x00\x04\x87Q\ +\x00\x00\x0f\x9c\x00\x00\x00\x00\x00\x01\x00\x04\x8ei\ \x00\x00\x01y+\x8f\x94\x12\ -\x00\x00\x08T\x00\x00\x00\x00\x00\x01\x00\x01\xa9(\ +\x00\x00\x08T\x00\x00\x00\x00\x00\x01\x00\x01\xb0@\ \x00\x00\x01x\xc7F\xf61\ -\x00\x00\x0cb\x00\x00\x00\x00\x00\x01\x00\x03\x81c\ +\x00\x00\x0cb\x00\x00\x00\x00\x00\x01\x00\x03\x88{\ \x00\x00\x01y+\x8f\x93\xda\ -\x00\x00\x07B\x00\x00\x00\x00\x00\x01\x00\x01\x8c\x97\ +\x00\x00\x07B\x00\x00\x00\x00\x00\x01\x00\x01\x93\xaf\ \x00\x00\x01y+\x8f\x94\x11\ -\x00\x00\x08\xf8\x00\x00\x00\x00\x00\x01\x00\x02b\x14\ +\x00\x00\x08\xf8\x00\x00\x00\x00\x00\x01\x00\x02i,\ \x00\x00\x01y+\x8f\x93\xce\ -\x00\x00\x0a\xc0\x00\x00\x00\x00\x00\x01\x00\x03N\xe6\ +\x00\x00\x0a\xc0\x00\x00\x00\x00\x00\x01\x00\x03U\xfe\ \x00\x00\x01y+\x8f\x93\xd8\ -\x00\x00\x09\xc8\x00\x01\x00\x00\x00\x01\x00\x03\x12$\ +\x00\x00\x09\xc8\x00\x01\x00\x00\x00\x01\x00\x03\x19<\ \x00\x00\x01x\xc7F\xf5\xf8\ -\x00\x00\x06\x92\x00\x00\x00\x00\x00\x01\x00\x01|\xed\ +\x00\x00\x06\x92\x00\x00\x00\x00\x00\x01\x00\x01\x84\x05\ \x00\x00\x01y+\x8f\x93\xcc\ -\x00\x00\x0a\xf8\x00\x00\x00\x00\x00\x01\x00\x03R\x98\ +\x00\x00\x0a\xf8\x00\x00\x00\x00\x00\x01\x00\x03Y\xb0\ \x00\x00\x01y+\x8f\x93\xdb\ -\x00\x00\x0d\x98\x00\x00\x00\x00\x00\x01\x00\x03\xf8 \ +\x00\x00\x0d\x98\x00\x00\x00\x00\x00\x01\x00\x03\xff8\ \x00\x00\x01y+\x8f\x93\xdc\ -\x00\x00\x0c<\x00\x00\x00\x00\x00\x01\x00\x03|B\ +\x00\x00\x0c<\x00\x00\x00\x00\x00\x01\x00\x03\x83Z\ \x00\x00\x01y+\x8f\x93\xde\ -\x00\x00\x0bZ\x00\x00\x00\x00\x00\x01\x00\x03W)\ +\x00\x00\x0bZ\x00\x00\x00\x00\x00\x01\x00\x03^A\ \x00\x00\x01y+\x8f\x93\xd8\ -\x00\x00\x0a\x94\x00\x00\x00\x00\x00\x01\x00\x039\x16\ +\x00\x00\x0a\x94\x00\x00\x00\x00\x00\x01\x00\x03@.\ \x00\x00\x01x\xc7F\xf60\ -\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x01\x00\x04`\xcc\ +\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x01\x00\x04g\xe4\ \x00\x00\x01y+\x8f\x94\x13\ -\x00\x00\x0fN\x00\x00\x00\x00\x00\x01\x00\x04\x7f\x0c\ +\x00\x00\x0fN\x00\x00\x00\x00\x00\x01\x00\x04\x86$\ \x00\x00\x01y+\x8f\x93\xe2\ -\x00\x00\x0dD\x00\x00\x00\x00\x00\x01\x00\x03\x95\x12\ +\x00\x00\x0dD\x00\x00\x00\x00\x00\x01\x00\x03\x9c*\ \x00\x00\x01x\xc7F\xf6\x18\ -\x00\x00\x0a0\x00\x00\x00\x00\x00\x01\x00\x034\xb6\ +\x00\x00\x0a0\x00\x00\x00\x00\x00\x01\x00\x03;\xce\ \x00\x00\x01y+\x8f\x93\xd9\ -\x00\x00\x060\x00\x00\x00\x00\x00\x01\x00\x01\x1a\xc3\ +\x00\x00\x060\x00\x00\x00\x00\x00\x01\x00\x01!\xdb\ \x00\x00\x01x\xc7F\xf6\x1b\ -\x00\x00\x0b\xe2\x00\x00\x00\x00\x00\x01\x00\x03p\xae\ +\x00\x00\x0b\xe2\x00\x00\x00\x00\x00\x01\x00\x03w\xc6\ \x00\x00\x01y+\x8f\x93\xd7\ -\x00\x00\x06\xf0\x00\x00\x00\x00\x00\x01\x00\x01\x84\xba\ +\x00\x00\x06\xf0\x00\x00\x00\x00\x00\x01\x00\x01\x8b\xd2\ \x00\x00\x01y+\x8f\x93\xfd\ -\x00\x00\x07\xb8\x00\x00\x00\x00\x00\x01\x00\x01\x9bR\ +\x00\x00\x07\xb8\x00\x00\x00\x00\x00\x01\x00\x01\xa2j\ \x00\x00\x01y+\x8f\x94\x0f\ -\x00\x00\x0f\xce\x00\x00\x00\x00\x00\x01\x00\x04\x90\xf8\ +\x00\x00\x0f\xce\x00\x00\x00\x00\x00\x01\x00\x04\x98\x10\ \x00\x00\x01y+\x8f\x93\xcb\ -\x00\x00\x0e\xd0\x00\x01\x00\x00\x00\x01\x00\x04/\x99\ +\x00\x00\x0e\xd0\x00\x01\x00\x00\x00\x01\x00\x046\xb1\ \x00\x00\x01x\xc7F\xf5\xf3\ -\x00\x00\x06^\x00\x00\x00\x00\x00\x01\x00\x01zK\ +\x00\x00\x06^\x00\x00\x00\x00\x00\x01\x00\x01\x81c\ \x00\x00\x01y+\x8f\x94\x06\ -\x00\x00\x09\xb4\x00\x00\x00\x00\x00\x01\x00\x03\x0c\xa3\ +\x00\x00\x09\xb4\x00\x00\x00\x00\x00\x01\x00\x03\x13\xbb\ \x00\x00\x01y+\x8f\x93\xd0\ -\x00\x00\x0f\xf8\x00\x00\x00\x00\x00\x01\x00\x04\x93\xb2\ +\x00\x00\x0f\xf8\x00\x00\x00\x00\x00\x01\x00\x04\x9a\xca\ \x00\x00\x01x\xc7F\xf5\xf0\ -\x00\x00\x09\x86\x00\x00\x00\x00\x00\x01\x00\x02\x8c\x97\ +\x00\x00\x09\x86\x00\x00\x00\x00\x00\x01\x00\x02\x93\xaf\ \x00\x00\x01x\xc7F\xf6$\ -\x00\x00\x0d\xe4\x00\x01\x00\x00\x00\x01\x00\x03\xfb\xab\ +\x00\x00\x0d\xe4\x00\x01\x00\x00\x00\x01\x00\x04\x02\xc3\ \x00\x00\x01x\xc7F\xf6\x04\ -\x00\x00\x0c\xec\x00\x00\x00\x00\x00\x01\x00\x03\x8a\xa7\ +\x00\x00\x0c\xec\x00\x00\x00\x00\x00\x01\x00\x03\x91\xbf\ \x00\x00\x01y+\x8f\x94\x0e\ -\x00\x00\x0b\xaa\x00\x00\x00\x00\x00\x01\x00\x03[\xa0\ +\x00\x00\x0b\xaa\x00\x00\x00\x00\x00\x01\x00\x03b\xb8\ \x00\x00\x01x\xc7F\xf6L\ -\x00\x00\x06\xb8\x00\x00\x00\x00\x00\x01\x00\x01\x7f\x95\ +\x00\x00\x06\xb8\x00\x00\x00\x00\x00\x01\x00\x01\x86\xad\ \x00\x00\x01y+\x8f\x93\xe0\ -\x00\x00\x0c\xb0\x00\x00\x00\x00\x00\x01\x00\x03\x86\x07\ +\x00\x00\x0c\xb0\x00\x00\x00\x00\x00\x01\x00\x03\x8d\x1f\ \x00\x00\x01y+\x8f\x93\xdd\ -\x00\x00\x07\xea\x00\x00\x00\x00\x00\x01\x00\x01\x9d\xf4\ +\x00\x00\x07\xea\x00\x00\x00\x00\x00\x01\x00\x01\xa5\x0c\ \x00\x00\x01y+\x8f\x93\xe1\ -\x00\x00\x08\xb4\x00\x00\x00\x00\x00\x01\x00\x02H\xcc\ +\x00\x00\x08\xb4\x00\x00\x00\x00\x00\x01\x00\x02O\xe4\ \x00\x00\x01x\xc7F\xf6D\ -\x00\x00\x11\x06\x00\x00\x00\x00\x00\x01\x00\x05@\xf3\ +\x00\x00\x11\x06\x00\x00\x00\x00\x00\x01\x00\x05H\x0b\ \x00\x00\x01y+\x8f\x93\xd4\ -\x00\x00\x11\x88\x00\x00\x00\x00\x00\x01\x00\x05k\xae\ +\x00\x00\x11\x88\x00\x00\x00\x00\x00\x01\x00\x05r\xc6\ \x00\x00\x01y+\x8f\x93\xd1\ -\x00\x00\x11b\x00\x00\x00\x00\x00\x01\x00\x05Yl\ +\x00\x00\x11b\x00\x00\x00\x00\x00\x01\x00\x05`\x84\ \x00\x00\x01y+\x8f\x93\xcf\ -\x00\x00\x11\xa0\x00\x00\x00\x00\x00\x01\x00\x05o\xc9\ +\x00\x00\x11\xa0\x00\x00\x00\x00\x00\x01\x00\x05v\xe1\ \x00\x00\x01y+\x8f\x93\xd2\ -\x00\x00\x10\x94\x00\x00\x00\x00\x00\x01\x00\x059\xf7\ +\x00\x00\x10\x94\x00\x00\x00\x00\x00\x01\x00\x05A\x0f\ \x00\x00\x01x\xc7F\xf8/\ -\x00\x00\x106\x00\x00\x00\x00\x00\x01\x00\x05!\xc2\ +\x00\x00\x106\x00\x00\x00\x00\x00\x01\x00\x05(\xda\ \x00\x00\x01x\xc7F\xf8,\ -\x00\x00\x11 \x00\x00\x00\x00\x00\x01\x00\x05F\xfd\ +\x00\x00\x11 \x00\x00\x00\x00\x00\x01\x00\x05N\x15\ \x00\x00\x01x\xc7F\xf83\ -\x00\x00\x10\xdc\x00\x00\x00\x00\x00\x01\x00\x05@%\ +\x00\x00\x10\xdc\x00\x00\x00\x00\x00\x01\x00\x05G=\ \x00\x00\x01x\xc7F\xf8(\ -\x00\x00\x10`\x00\x00\x00\x00\x00\x01\x00\x05\x22O\ +\x00\x00\x10`\x00\x00\x00\x00\x00\x01\x00\x05)g\ \x00\x00\x01y+\x8f\x93\xd3\ -\x00\x00\x11J\x00\x00\x00\x00\x00\x01\x00\x05G\xa1\ +\x00\x00\x11J\x00\x00\x00\x00\x00\x01\x00\x05N\xb9\ \x00\x00\x01y+\x8f\x93\xca\ -\x00\x00\x10z\x00\x00\x00\x00\x00\x01\x00\x0509\ +\x00\x00\x10z\x00\x00\x00\x00\x00\x01\x00\x057Q\ \x00\x00\x01y+\x8f\x93\xc9\ -\x00\x00\x10\xbe\x00\x00\x00\x00\x00\x01\x00\x05:\xa6\ +\x00\x00\x10\xbe\x00\x00\x00\x00\x00\x01\x00\x05A\xbe\ \x00\x00\x01y+\x8f\x93\xe3\ " diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/aws_utils.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/aws_utils.py index b0c3c9c1b3..8152d2addc 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/aws_utils.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/aws_utils.py @@ -12,10 +12,10 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import boto3 from botocore.paginate import (PageIterator, Paginator) from botocore.client import BaseClient -from botocore.exceptions import ClientError +from botocore.exceptions import (ClientError, ConfigNotFound, NoCredentialsError, ProfileNotFound) from typing import Dict, List -from model import (constants, error_messages) +from model import error_messages from model.basic_resource_attributes import (BasicResourceAttributes, BasicResourceAttributesBuilder) """ @@ -65,8 +65,11 @@ def _initialize_boto3_aws_client(service: str, region: str = "") -> BaseClient: def setup_default_session(profile: str) -> None: - global default_session - default_session = boto3.session.Session(profile_name=profile) + try: + global default_session + default_session = boto3.session.Session(profile_name=profile) + except (ConfigNotFound, ProfileNotFound) as error: + raise RuntimeError(error) def get_default_account_id() -> str: @@ -76,6 +79,8 @@ def get_default_account_id() -> str: except ClientError as error: raise RuntimeError(error_messages.AWS_SERVICE_REQUEST_CLIENT_ERROR_MESSAGE.format( "get_caller_identity", error.response['Error']['Code'], error.response['Error']['Message'])) + except NoCredentialsError as error: + raise RuntimeError(error) def get_default_region() -> str: From 5d7aae9bd899e838e183a7b09a530e18261c4acb Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 3 Jun 2021 11:12:54 -0700 Subject: [PATCH 474/811] SPEC-2513 Fixes to enable w4459 (#1107) * fixing w4459 * Fixes for nounity * putting OLD_APARAM_USER in a common place to avoid duplicated declarations --- .../CryCommon/Maestro/Types/AnimParamType.h | 1 + Code/Framework/AzCore/Tests/AZStd/String.cpp | 16 ++++++------- .../AzCore/Tests/Math/Matrix4x4Tests.cpp | 10 ++++---- Code/Framework/AzCore/Tests/Math/ObbTests.cpp | 24 +++++++++---------- Code/Sandbox/Editor/QtViewPaneManager.cpp | 6 ++--- .../TrackView/SequenceBatchRenderDialog.cpp | 16 ++++++------- .../DiskLightFeatureProcessorInterface.h | 2 -- .../Atom/RHI/Vulkan/Code/Source/RHI/Queue.cpp | 10 ++++---- .../Source/RPI.Reflect/Shader/ShaderAsset.cpp | 5 +--- .../RPI.Reflect/Shader/ShaderVariantAsset.cpp | 5 +--- .../StaticLib/GraphCanvas/Styling/Parser.cpp | 6 ++--- .../Animation/Controls/UiTimelineCtrl.cpp | 4 ---- .../Code/Source/Animation/AnimNode.cpp | 1 - .../Code/Source/Cinematics/AnimNode.cpp | 1 - .../Code/Source/Cinematics/AnimPostFXNode.cpp | 1 - .../MicrophoneSystemComponent_Windows.cpp | 16 ++++++------- .../Source/Optimization/Constants.h | 4 ++-- .../Source/Optimization/LineSearch.cpp | 8 +++---- .../Tests/OptimizationTest.cpp | 10 ++++---- .../Benchmarks/PhysXBenchmarksUtilities.h | 6 ++--- .../Common/MSVC/Configurations_msvc.cmake | 1 - 21 files changed, 68 insertions(+), 85 deletions(-) diff --git a/Code/CryEngine/CryCommon/Maestro/Types/AnimParamType.h b/Code/CryEngine/CryCommon/Maestro/Types/AnimParamType.h index f7caf2db7f..4614b1638d 100644 --- a/Code/CryEngine/CryCommon/Maestro/Types/AnimParamType.h +++ b/Code/CryEngine/CryCommon/Maestro/Types/AnimParamType.h @@ -137,5 +137,6 @@ enum class AnimParamType Invalid = static_cast(0xFFFFFFFF) }; +static const int OLD_APARAM_USER = 100; #endif // CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMPARAMTYPE_H diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp index 5b8c176f02..a48725309a 100644 --- a/Code/Framework/AzCore/Tests/AZStd/String.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp @@ -1914,7 +1914,7 @@ namespace UnitTest TEST_F(String, StringView_CompareIsConstexpr) { using TypeParam = char; - auto MakeCompileTimeString1 = []() constexpr -> const TypeParam* + auto ThisTestMakeCompileTimeString1 = []() constexpr -> const TypeParam* { return "HelloWorld"; }; @@ -1922,7 +1922,7 @@ namespace UnitTest { return "HelloPearl"; }; - constexpr const TypeParam* compileTimeString1 = MakeCompileTimeString1(); + constexpr const TypeParam* compileTimeString1 = ThisTestMakeCompileTimeString1(); constexpr const TypeParam* compileTimeString2 = MakeCompileTimeString2(); constexpr basic_string_view lhsView(compileTimeString1); constexpr basic_string_view rhsView(compileTimeString2); @@ -1937,11 +1937,11 @@ namespace UnitTest TEST_F(String, StringView_CompareOperatorsAreConstexpr) { using TypeParam = char; - auto MakeCompileTimeString1 = []() constexpr -> const TypeParam* + auto TestMakeCompileTimeString1 = []() constexpr -> const TypeParam* { return "HelloWorld"; }; - constexpr const TypeParam* compileTimeString1 = MakeCompileTimeString1(); + constexpr const TypeParam* compileTimeString1 = TestMakeCompileTimeString1(); constexpr basic_string_view compareView(compileTimeString1); static_assert(compareView == "HelloWorld", "string_view operator== comparison has failed"); static_assert(compareView != "MadWorld", "string_view operator!= comparison has failed"); @@ -1955,7 +1955,7 @@ namespace UnitTest { auto swap_test_func = []() constexpr -> basic_string_view { - constexpr auto MakeCompileTimeString1 = []() constexpr -> const TypeParam* + constexpr auto ThisTestMakeCompileTimeString1 = []() constexpr -> const TypeParam* { if constexpr (AZStd::is_same_v) { @@ -1977,7 +1977,7 @@ namespace UnitTest return L"InuWorld"; } }; - constexpr const TypeParam* compileTimeString1 = MakeCompileTimeString1(); + constexpr const TypeParam* compileTimeString1 = ThisTestMakeCompileTimeString1(); constexpr const TypeParam* compileTimeString2 = MakeCompileTimeString2(); basic_string_view lhsView(compileTimeString1); basic_string_view rhsView(compileTimeString2); @@ -2001,7 +2001,7 @@ namespace UnitTest TYPED_TEST(BasicStringViewConstexprFixture, HashString_FunctionIsConstexpr) { - auto MakeCompileTimeString1 = []() constexpr -> const TypeParam* + auto ThisTestMakeCompileTimeString1 = []() constexpr -> const TypeParam* { if constexpr (AZStd::is_same_v) { @@ -2012,7 +2012,7 @@ namespace UnitTest return L"HelloWorld"; } }; - constexpr const TypeParam* compileTimeString1 = MakeCompileTimeString1(); + constexpr const TypeParam* compileTimeString1 = ThisTestMakeCompileTimeString1(); constexpr basic_string_view hashView(compileTimeString1); constexpr size_t compileHash = AZStd::hash>{}(hashView); static_assert(compileHash != 0, "Hash of \"HelloWorld\" should not be 0"); diff --git a/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp index a9baa3ddea..8c4fac86c2 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp @@ -59,7 +59,7 @@ namespace UnitTest TEST(MATH_Matrix4x4, TestCreateFrom) { - float testFloats[] = + float thisTestFloats[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, @@ -67,20 +67,20 @@ namespace UnitTest 13.0f, 14.0f, 15.0f, 16.0f }; float testFloatMtx[16]; - Matrix4x4 m1 = Matrix4x4::CreateFromRowMajorFloat16(testFloats); + Matrix4x4 m1 = Matrix4x4::CreateFromRowMajorFloat16(thisTestFloats); AZ_TEST_ASSERT(m1.GetRow(0) == Vector4(1.0f, 2.0f, 3.0f, 4.0f)); AZ_TEST_ASSERT(m1.GetRow(1) == Vector4(5.0f, 6.0f, 7.0f, 8.0f)); AZ_TEST_ASSERT(m1.GetRow(2) == Vector4(9.0f, 10.0f, 11.0f, 12.0f)); AZ_TEST_ASSERT(m1.GetRow(3) == Vector4(13.0f, 14.0f, 15.0f, 16.0f)); m1.StoreToRowMajorFloat16(testFloatMtx); - AZ_TEST_ASSERT(memcmp(testFloatMtx, testFloats, sizeof(testFloatMtx)) == 0); - m1 = Matrix4x4::CreateFromColumnMajorFloat16(testFloats); + AZ_TEST_ASSERT(memcmp(testFloatMtx, thisTestFloats, sizeof(testFloatMtx)) == 0); + m1 = Matrix4x4::CreateFromColumnMajorFloat16(thisTestFloats); AZ_TEST_ASSERT(m1.GetRow(0) == Vector4(1.0f, 5.0f, 9.0f, 13.0f)); AZ_TEST_ASSERT(m1.GetRow(1) == Vector4(2.0f, 6.0f, 10.0f, 14.0f)); AZ_TEST_ASSERT(m1.GetRow(2) == Vector4(3.0f, 7.0f, 11.0f, 15.0f)); AZ_TEST_ASSERT(m1.GetRow(3) == Vector4(4.0f, 8.0f, 12.0f, 16.0f)); m1.StoreToColumnMajorFloat16(testFloatMtx); - AZ_TEST_ASSERT(memcmp(testFloatMtx, testFloats, sizeof(testFloatMtx)) == 0); + AZ_TEST_ASSERT(memcmp(testFloatMtx, thisTestFloats, sizeof(testFloatMtx)) == 0); } TEST(MATH_Matrix4x4, TestCreateFromMatrix3x4) diff --git a/Code/Framework/AzCore/Tests/Math/ObbTests.cpp b/Code/Framework/AzCore/Tests/Math/ObbTests.cpp index de267b4265..5eb9057761 100644 --- a/Code/Framework/AzCore/Tests/Math/ObbTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/ObbTests.cpp @@ -119,10 +119,10 @@ namespace UnitTest TEST(MATH_Obb, Contains) { - const Vector3 position(1.0f, 2.0f, 3.0f); - const Quaternion rotation = Quaternion::CreateRotationZ(DegToRad(30.0f)); - const Vector3 halfLengths(2.0f, 1.0f, 2.5f); - const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(position, rotation, halfLengths); + const Vector3 testPosition(1.0f, 2.0f, 3.0f); + const Quaternion testRotation = Quaternion::CreateRotationZ(DegToRad(30.0f)); + const Vector3 testHalfLengths(2.0f, 1.0f, 2.5f); + const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(testPosition, testRotation, testHalfLengths); // test some pairs of points which should be just either side of the Obb boundary EXPECT_TRUE(obb.Contains(Vector3(1.35f, 3.35f, 3.5f))); EXPECT_FALSE(obb.Contains(Vector3(1.35f, 3.4f, 3.5f))); @@ -134,10 +134,10 @@ namespace UnitTest TEST(MATH_Obb, GetDistance) { - const Vector3 position(5.0f, 3.0f, 2.0f); - const Quaternion rotation = Quaternion::CreateRotationX(DegToRad(60.0f)); - const Vector3 halfLengths(0.5f, 2.0f, 1.5f); - const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(position, rotation, halfLengths); + const Vector3 testPosition(5.0f, 3.0f, 2.0f); + const Quaternion testRotation = Quaternion::CreateRotationX(DegToRad(60.0f)); + const Vector3 testHalfLengths(0.5f, 2.0f, 1.5f); + const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(testPosition, testRotation, testHalfLengths); EXPECT_NEAR(obb.GetDistance(Vector3(5.3f, 3.2f, 1.8f)), 0.0f, 1e-3f); EXPECT_NEAR(obb.GetDistance(Vector3(5.1f, 1.1f, 3.7f)), 0.9955f, 1e-3f); EXPECT_NEAR(obb.GetDistance(Vector3(4.7f, 4.5f, 4.2f)), 0.6553f, 1e-3f); @@ -146,10 +146,10 @@ namespace UnitTest TEST(MATH_Obb, GetDistanceSq) { - const Vector3 position(1.0f, 4.0f, 3.0f); - const Quaternion rotation = Quaternion::CreateRotationY(DegToRad(45.0f)); - const Vector3 halfLengths(1.5f, 3.0f, 1.0f); - const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(position, rotation, halfLengths); + const Vector3 testPosition(1.0f, 4.0f, 3.0f); + const Quaternion testRotation = Quaternion::CreateRotationY(DegToRad(45.0f)); + const Vector3 testHalfLengths(1.5f, 3.0f, 1.0f); + const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(testPosition, testRotation, testHalfLengths); EXPECT_NEAR(obb.GetDistanceSq(Vector3(1.1f, 4.3f, 2.7f)), 0.0f, 1e-3f); EXPECT_NEAR(obb.GetDistanceSq(Vector3(-0.7f, 3.5f, 2.0f)), 0.8266f, 1e-3f); EXPECT_NEAR(obb.GetDistanceSq(Vector3(2.4f, 0.5f, 1.5f)), 0.5532f, 1e-3f); diff --git a/Code/Sandbox/Editor/QtViewPaneManager.cpp b/Code/Sandbox/Editor/QtViewPaneManager.cpp index b242f3d914..3949f0516e 100644 --- a/Code/Sandbox/Editor/QtViewPaneManager.cpp +++ b/Code/Sandbox/Editor/QtViewPaneManager.cpp @@ -121,7 +121,7 @@ protected: }; #endif -Q_GLOBAL_STATIC(QtViewPaneManager, s_instance) +Q_GLOBAL_STATIC(QtViewPaneManager, s_viewPaneManagerInstance) QWidget* QtViewPane::CreateWidget() @@ -611,12 +611,12 @@ void QtViewPaneManager::UnregisterPane(const QString& name) QtViewPaneManager* QtViewPaneManager::instance() { - return s_instance(); + return s_viewPaneManagerInstance(); } bool QtViewPaneManager::exists() { - return s_instance.exists(); + return s_viewPaneManagerInstance.exists(); } void QtViewPaneManager::SetMainWindow(AzQtComponents::DockMainWindow* mainWindow, QSettings* settings, const QByteArray& lastMainWindowState) diff --git a/Code/Sandbox/Editor/TrackView/SequenceBatchRenderDialog.cpp b/Code/Sandbox/Editor/TrackView/SequenceBatchRenderDialog.cpp index 69322c481c..0abe3ced75 100644 --- a/Code/Sandbox/Editor/TrackView/SequenceBatchRenderDialog.cpp +++ b/Code/Sandbox/Editor/TrackView/SequenceBatchRenderDialog.cpp @@ -59,7 +59,7 @@ namespace { int fps; const char* fpsDesc; - } fps[] = { + } fpsOptions[] = { {24, "Film(24)"}, {25, "PAL(25)"}, {30, "NTSC(30)"}, {48, "Show(48)"}, {50, "PAL Field(50)"}, {60, "NTSC Field(60)"} }; @@ -213,9 +213,9 @@ void CSequenceBatchRenderDialog::OnInitDialog() m_ui->m_resolutionCombo->setCurrentIndex(0); // Fill the FPS combo box. - for (int i = 0; i < AZStd::size(fps); ++i) + for (int i = 0; i < AZStd::size(fpsOptions); ++i) { - m_ui->m_fpsCombo->addItem(fps[i].fpsDesc); + m_ui->m_fpsCombo->addItem(fpsOptions[i].fpsDesc); } m_ui->m_fpsCombo->setCurrentIndex(0); @@ -306,9 +306,9 @@ void CSequenceBatchRenderDialog::OnRenderItemSelChange() m_ui->m_destinationEdit->setText(item.folder); // fps bool bFound = false; - for (int i = 0; i < arraysize(fps); ++i) + for (int i = 0; i < arraysize(fpsOptions); ++i) { - if (item.fps == fps[i].fps) + if (item.fps == fpsOptions[i].fps) { m_ui->m_fpsCombo->setCurrentIndex(i); bFound = true; @@ -621,7 +621,7 @@ void CSequenceBatchRenderDialog::OnFPSEditChange() void CSequenceBatchRenderDialog::OnFPSChange(int itemIndex) { - m_customFPS = fps[itemIndex].fps; + m_customFPS = fpsOptions[itemIndex].fps; CheckForEnableUpdateButton(); } @@ -1543,13 +1543,13 @@ bool CSequenceBatchRenderDialog::SetUpNewRenderItem(SRenderItem& item) item.frameRange = Range(m_ui->m_startFrame->value() / m_fpsForTimeToFrameConversion, m_ui->m_endFrame->value() / m_fpsForTimeToFrameConversion); // fps - if (m_ui->m_fpsCombo->currentIndex() == -1 || m_ui->m_fpsCombo->currentText() != fps[m_ui->m_fpsCombo->currentIndex()].fpsDesc) + if (m_ui->m_fpsCombo->currentIndex() == -1 || m_ui->m_fpsCombo->currentText() != fpsOptions[m_ui->m_fpsCombo->currentIndex()].fpsDesc) { item.fps = m_customFPS; } else { - item.fps = fps[m_ui->m_fpsCombo->currentIndex()].fps; + item.fps = fpsOptions[m_ui->m_fpsCombo->currentIndex()].fps; } // prefix item.prefix = m_ui->BATCH_RENDER_FILE_PREFIX->text(); diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h index 50c0aa2455..ce911fecf7 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h @@ -46,8 +46,6 @@ namespace AZ uint16_t m_padding; // Explicit padding. }; - static constexpr size_t size = sizeof(DiskLightData); - //! DiskLightFeatureProcessorInterface provides an interface to acquire, release, and update a disk light. This is necessary for code outside of //! the Atom features gem to communicate with the DiskLightFeatureProcessor. class DiskLightFeatureProcessorInterface diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Queue.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Queue.cpp index 5bebc92125..88d103d282 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Queue.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Queue.cpp @@ -45,7 +45,7 @@ namespace AZ Fence* fenceToSignal) { AZStd::vector vkCommandBuffers; - AZStd::vector vkWaitSemaphores; + AZStd::vector vkWaitSemaphoreVector; // vulkan.h has a #define called vkWaitSemaphores, so we name this differently AZStd::vector vkWaitPipelineStages; AZStd::vector vkSignalSemaphores; VkSubmitInfo submitInfo; @@ -65,11 +65,11 @@ namespace AZ return item->GetNativeSemaphore(); }); vkWaitPipelineStages.reserve(waitSemaphoresInfo.size()); - vkWaitSemaphores.reserve(waitSemaphoresInfo.size()); + vkWaitSemaphoreVector.reserve(waitSemaphoresInfo.size()); AZStd::for_each(waitSemaphoresInfo.begin(), waitSemaphoresInfo.end(), [&](auto& item) { vkWaitPipelineStages.push_back(item.first); - vkWaitSemaphores.push_back(item.second->GetNativeSemaphore()); + vkWaitSemaphoreVector.push_back(item.second->GetNativeSemaphore()); // Wait until the wait semaphores has been submitted for signaling. item.second->WaitEvent(); }); @@ -77,8 +77,8 @@ namespace AZ submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.pNext = nullptr; - submitInfo.waitSemaphoreCount = static_cast(vkWaitSemaphores.size()); - submitInfo.pWaitSemaphores = vkWaitSemaphores.empty() ? nullptr : vkWaitSemaphores.data(); + submitInfo.waitSemaphoreCount = static_cast(vkWaitSemaphoreVector.size()); + submitInfo.pWaitSemaphores = vkWaitSemaphoreVector.empty() ? nullptr : vkWaitSemaphoreVector.data(); submitInfo.pWaitDstStageMask = vkWaitPipelineStages.empty() ? nullptr : vkWaitPipelineStages.data(); submitInfo.commandBufferCount = static_cast(vkCommandBuffers.size()); submitInfo.pCommandBuffers = vkCommandBuffers.empty() ? nullptr : vkCommandBuffers.data(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderAsset.cpp index 0a59772d6c..cf655d43f7 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderAsset.cpp @@ -10,6 +10,7 @@ * */ #include +#include #include #include @@ -34,10 +35,6 @@ namespace AZ uint32_t ShaderAsset::MakeAssetProductSubId(uint32_t rhiApiUniqueIndex, uint32_t subProductType) { - static constexpr uint32_t RhiIndexBitPosition = 30; - static constexpr uint32_t RhiIndexNumBits = 32 - RhiIndexBitPosition; - static constexpr uint32_t RhiIndexMaxValue = (1 << RhiIndexNumBits) - 1; - static constexpr uint32_t SubProductTypeBitPosition = 0; static constexpr uint32_t SubProductTypeNumBits = RhiIndexBitPosition - SubProductTypeBitPosition; static constexpr uint32_t SubProductTypeMaxValue = (1 << SubProductTypeNumBits) - 1; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantAsset.cpp index 7864768351..5bcdcbb569 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantAsset.cpp @@ -10,6 +10,7 @@ * */ #include +#include #include #include @@ -24,10 +25,6 @@ namespace AZ uint32_t ShaderVariantAsset::MakeAssetProductSubId( uint32_t rhiApiUniqueIndex, ShaderVariantStableId variantStableId, uint32_t subProductType) { - static constexpr uint32_t RhiIndexBitPosition = 30; - static constexpr uint32_t RhiIndexNumBits = 32 - RhiIndexBitPosition; - static constexpr uint32_t RhiIndexMaxValue = (1 << RhiIndexNumBits) - 1; - static constexpr uint32_t SubProductTypeBitPosition = 17; static constexpr uint32_t SubProductTypeNumBits = RhiIndexBitPosition - SubProductTypeBitPosition; static constexpr uint32_t SubProductTypeMaxValue = (1 << SubProductTypeNumBits) - 1; diff --git a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/Parser.cpp b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/Parser.cpp index 319996949b..db07c3ca8e 100644 --- a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/Parser.cpp +++ b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/Parser.cpp @@ -1072,8 +1072,7 @@ namespace GraphCanvas if (!id.empty()) { - Selector selector = Selector::Get(id); - result.emplace_back(selector); + result.emplace_back(Selector::Get(id)); continue; } @@ -1111,8 +1110,7 @@ namespace GraphCanvas { bits.emplace_back(stateSelector); } - Selector selector = aznew CompoundSelector(std::move(bits)); - nestedSelectors.emplace_back(selector); + nestedSelectors.emplace_back(aznew CompoundSelector(std::move(bits))); } } diff --git a/Gems/LyShine/Code/Editor/Animation/Controls/UiTimelineCtrl.cpp b/Gems/LyShine/Code/Editor/Animation/Controls/UiTimelineCtrl.cpp index 9f7fae6041..0b18539c54 100644 --- a/Gems/LyShine/Code/Editor/Animation/Controls/UiTimelineCtrl.cpp +++ b/Gems/LyShine/Code/Editor/Animation/Controls/UiTimelineCtrl.cpp @@ -23,10 +23,6 @@ #include #include -static const QColor timeMarkerCol = QColor(255, 0, 255); -static const QColor textCol = QColor(0, 0, 0); -static const QColor ltgrayCol = QColor(110, 110, 110); - QColor InterpolateColor(const QColor& c1, const QColor& c2, float fraction) { const int r = (c2.red() - c1.red()) * fraction + c1.red(); diff --git a/Gems/LyShine/Code/Source/Animation/AnimNode.cpp b/Gems/LyShine/Code/Source/Animation/AnimNode.cpp index 421e9a4fe3..369f080a15 100644 --- a/Gems/LyShine/Code/Source/Animation/AnimNode.cpp +++ b/Gems/LyShine/Code/Source/Animation/AnimNode.cpp @@ -48,7 +48,6 @@ static const EUiAnimCurveType DEFAULT_TRACK_TYPE = eUiAnimCurveType_BezierFloat; // Old serialization values that are no longer // defined in IUiAnimationSystem.h, but needed for conversion: -static const int OLD_APARAM_USER = 100; static const int OLD_ACURVE_GOTO = 21; static const int OLD_APARAM_PARTICLE_COUNT_SCALE = 95; static const int OLD_APARAM_PARTICLE_PULSE_PERIOD = 96; diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimNode.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimNode.cpp index 7fea8097ed..8398ad47fd 100644 --- a/Gems/Maestro/Code/Source/Cinematics/AnimNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/AnimNode.cpp @@ -60,7 +60,6 @@ static const EAnimCurveType DEFAULT_TRACK_TYPE = eAnimCurveType_BezierFloat; // Old serialization values that are no longer // defined in IMovieSystem.h, but needed for conversion: -static const int OLD_APARAM_USER = 100; static const int OLD_ACURVE_GOTO = 21; static const int OLD_APARAM_PARTICLE_COUNT_SCALE = 95; static const int OLD_APARAM_PARTICLE_PULSE_PERIOD = 96; diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp index 67b6ab5cdb..992527d2c4 100644 --- a/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp @@ -281,7 +281,6 @@ void CAnimPostFXNode::SerializeAnims(XmlNodeRef& xmlNode, bool bLoading, bool bL paramType.Serialize(trackNode, true); // Don't use APARAM_USER because it could change in newer versions // CAnimNode::SerializeAnims will then take care of that - static const unsigned int OLD_APARAM_USER = 100; paramType = static_cast(static_cast(paramType.GetType()) + OLD_APARAM_USER); paramType.Serialize(trackNode, false); } diff --git a/Gems/Microphone/Code/Source/Platform/Windows/MicrophoneSystemComponent_Windows.cpp b/Gems/Microphone/Code/Source/Platform/Windows/MicrophoneSystemComponent_Windows.cpp index 8b3e3c2ce6..2eb840b253 100644 --- a/Gems/Microphone/Code/Source/Platform/Windows/MicrophoneSystemComponent_Windows.cpp +++ b/Gems/Microphone/Code/Source/Platform/Windows/MicrophoneSystemComponent_Windows.cpp @@ -51,11 +51,11 @@ namespace Audio // To avoid errors, we initialize COM here with the same model. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); - const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); + const CLSID CLSID_MMDeviceEnumerator_UUID = __uuidof(MMDeviceEnumerator); + const IID IID_IMMDeviceEnumerator_UUID = __uuidof(IMMDeviceEnumerator); HRESULT hresult = CoCreateInstance( - CLSID_MMDeviceEnumerator, nullptr, - CLSCTX_ALL, IID_IMMDeviceEnumerator, + CLSID_MMDeviceEnumerator_UUID, nullptr, + CLSCTX_ALL, IID_IMMDeviceEnumerator_UUID, reinterpret_cast(&m_enumerator) ); @@ -133,8 +133,8 @@ namespace Audio AZ_Assert(m_device != nullptr, "Attempting to start a Microphone session while the device is uninitialized - Windows!\n"); // Get the IAudioClient from the device - const IID IID_IAudioClient = __uuidof(IAudioClient); - HRESULT hresult = m_device->Activate(IID_IAudioClient, CLSCTX_ALL, nullptr, reinterpret_cast(&m_audioClient)); + const IID IID_IAudioClient_UUID = __uuidof(IAudioClient); + HRESULT hresult = m_device->Activate(IID_IAudioClient_UUID, CLSCTX_ALL, nullptr, reinterpret_cast(&m_audioClient)); if (FAILED(hresult)) { @@ -182,8 +182,8 @@ namespace Audio } // Get the IAudioCaptureClient - const IID IID_IAudioCaptureClient = __uuidof(IAudioCaptureClient); - hresult = m_audioClient->GetService(IID_IAudioCaptureClient, reinterpret_cast(&m_audioCaptureClient)); + const IID IID_IAudioCaptureClient_UUID = __uuidof(IAudioCaptureClient); + hresult = m_audioClient->GetService(IID_IAudioCaptureClient_UUID, reinterpret_cast(&m_audioCaptureClient)); if (FAILED(hresult)) { diff --git a/Gems/PhysX/Code/NumericalMethods/Source/Optimization/Constants.h b/Gems/PhysX/Code/NumericalMethods/Source/Optimization/Constants.h index d480fb9cd0..feb626aa50 100644 --- a/Gems/PhysX/Code/NumericalMethods/Source/Optimization/Constants.h +++ b/Gems/PhysX/Code/NumericalMethods/Source/Optimization/Constants.h @@ -27,6 +27,6 @@ namespace NumericalMethods::Optimization const double epsilon = 1e-7; // values recommended in Nocedal and Wright for constants in the Wolfe conditions for satisfactory solution improvement - const double c1 = 1e-4; - const double c2 = 0.9; + const double WolfeConditionsC1 = 1e-4; + const double WolfeConditionsC2 = 0.9; } // namespace NumericalMethods::Optimization diff --git a/Gems/PhysX/Code/NumericalMethods/Source/Optimization/LineSearch.cpp b/Gems/PhysX/Code/NumericalMethods/Source/Optimization/LineSearch.cpp index 1325638dd2..06152446d6 100644 --- a/Gems/PhysX/Code/NumericalMethods/Source/Optimization/LineSearch.cpp +++ b/Gems/PhysX/Code/NumericalMethods/Source/Optimization/LineSearch.cpp @@ -162,16 +162,16 @@ namespace NumericalMethods::Optimization { // if the value of f corresponding to alpha1 isn't sufficiently small compared to f at x0, // then the interval [alpha0 ... alpha1] must bracket a suitable point. - if ((f_alpha1 > f_x0 + c1 * alpha1 * df_x0) || (iteration > 0 && f_alpha1 > f_alpha0)) + if ((f_alpha1 > f_x0 + WolfeConditionsC1 * alpha1 * df_x0) || (iteration > 0 && f_alpha1 > f_alpha0)) { return SelectStepSizeFromInterval(alpha0, alpha1, f_alpha0, f_alpha1, df_alpha0, - f, x0, searchDirection, f_x0, df_x0, c1, c2); + f, x0, searchDirection, f_x0, df_x0, WolfeConditionsC1, WolfeConditionsC2); } // otherwise, if the derivative corresponding to alpha1 is large enough, alpha1 already // satisfies the Wolfe conditions and so return alpha1. double df_alpha1 = DirectionalDerivative(f, x0 + alpha1 * searchDirection, searchDirection); - if (fabs(df_alpha1) <= -c2 * df_x0) + if (fabs(df_alpha1) <= -WolfeConditionsC2 * df_x0) { LineSearchResult result; result.m_outcome = LineSearchOutcome::Success; @@ -184,7 +184,7 @@ namespace NumericalMethods::Optimization if (df_alpha1 >= 0.0) { return SelectStepSizeFromInterval(alpha1, alpha0, f_alpha1, f_alpha0, df_alpha1, - f, x0, searchDirection, f_x0, df_x0, c1, c2); + f, x0, searchDirection, f_x0, df_x0, WolfeConditionsC1, WolfeConditionsC2); } // haven't found an interval which is guaranteed to bracket a suitable point, diff --git a/Gems/PhysX/Code/NumericalMethods/Tests/OptimizationTest.cpp b/Gems/PhysX/Code/NumericalMethods/Tests/OptimizationTest.cpp index b02f13d8a4..92d7e0dcba 100644 --- a/Gems/PhysX/Code/NumericalMethods/Tests/OptimizationTest.cpp +++ b/Gems/PhysX/Code/NumericalMethods/Tests/OptimizationTest.cpp @@ -158,12 +158,12 @@ namespace NumericalMethods::Optimization double f_x0 = f_alpha0; double df_x0 = df_alpha0; LineSearchResult lineSearchResult = SelectStepSizeFromInterval(alpha0, alpha1, f_alpha0, f_alpha1, df_alpha0, - testFunctionRosenbrock, x0, searchDirection, f_x0, df_x0, c1, c2); + testFunctionRosenbrock, x0, searchDirection, f_x0, df_x0, WolfeConditionsC1, WolfeConditionsC2); EXPECT_TRUE(lineSearchResult.m_outcome == LineSearchOutcome::Success); // check that the Wolfe conditions are satisfied by the returned step size - EXPECT_TRUE(lineSearchResult.m_functionValue < f_x0 + c1 * df_x0 * lineSearchResult.m_stepSize); - EXPECT_TRUE(fabs(lineSearchResult.m_derivativeValue) <= -c2 * df_x0); + EXPECT_TRUE(lineSearchResult.m_functionValue < f_x0 + WolfeConditionsC1 * df_x0 * lineSearchResult.m_stepSize); + EXPECT_TRUE(fabs(lineSearchResult.m_derivativeValue) <= -WolfeConditionsC2 * df_x0); } TEST(OptimizationTest, LineSearch_VariousSearchDirections_SatisfiesWolfeCondition) @@ -180,8 +180,8 @@ namespace NumericalMethods::Optimization EXPECT_TRUE(lineSearchResult.m_outcome == LineSearchOutcome::Success); // check that the Wolfe conditions are satisfied by the returned step size - EXPECT_TRUE(lineSearchResult.m_functionValue < f_x0 + c1 * df_x0 * lineSearchResult.m_stepSize); - EXPECT_TRUE(fabs(lineSearchResult.m_derivativeValue) <= -c2 * df_x0); + EXPECT_TRUE(lineSearchResult.m_functionValue < f_x0 + WolfeConditionsC1 * df_x0 * lineSearchResult.m_stepSize); + EXPECT_TRUE(fabs(lineSearchResult.m_derivativeValue) <= -WolfeConditionsC2 * df_x0); } } diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarksUtilities.h b/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarksUtilities.h index ab9bd58148..0971226644 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarksUtilities.h +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarksUtilities.h @@ -112,9 +112,9 @@ namespace PhysX::Benchmarks for (double percentile : percentiles) { //ensure the percentile is between 0.0 and 1.0 - const double epsilon = 0.001; - AZ::ClampIfCloseMag(percentile, 0.0, epsilon); - AZ::ClampIfCloseMag(percentile, 1.0, epsilon); + const double testEpsilon = 0.001; + AZ::ClampIfCloseMag(percentile, 0.0, testEpsilon); + AZ::ClampIfCloseMag(percentile, 1.0, testEpsilon); size_t idx = aznumeric_cast(std::round(percentile * (values.size() - 1))); std::nth_element(values.begin(), values.begin() + idx, values.end()); diff --git a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake index 24dffe56a6..f53b8aa769 100644 --- a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake +++ b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake @@ -74,7 +74,6 @@ ly_append_configurations_options( /wd4436 # the result of unary operator may be unaligned /wd4450 # declaration hides global declaration /wd4457 # declaration hides function parameter - /wd4459 # declaration hides global declaration # Enabling warnings that are disabled by default from /W4 # https://docs.microsoft.com/en-us/cpp/preprocessor/compiler-warnings-that-are-off-by-default?view=vs-2019 From 6681a5376844f9e3fcb0faebe6ffe6983c9bfa03 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Thu, 3 Jun 2021 14:13:44 -0400 Subject: [PATCH 475/811] Add the ability to remove tags. Updated some descriptions, and updated some log messages to include parameters. --- scripts/o3de/o3de/project_properties.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/scripts/o3de/o3de/project_properties.py b/scripts/o3de/o3de/project_properties.py index d8453a2c4f..7a9610a775 100644 --- a/scripts/o3de/o3de/project_properties.py +++ b/scripts/o3de/o3de/project_properties.py @@ -13,12 +13,13 @@ logging.basicConfig() def get_project_props(name: str = None, path: pathlib.Path = None) -> dict: proj_json = manifest.get_project_json_data(project_name=name, project_path=path) if not proj_json: - logger.error('Could not retrieve project.json file') + param = name if name else path + logger.error(f'Could not retrieve project.json file for {param}') return None return proj_json def edit_project_props(proj_path, proj_name, new_origin, new_display, - new_summary, new_icon, new_tag) -> int: + new_summary, new_icon, new_tag, remove_tag) -> int: proj_json = get_project_props(proj_name, proj_path) if not proj_json: @@ -36,6 +37,14 @@ def edit_project_props(proj_path, proj_name, new_origin, new_display, if 'user_tags' not in proj_json: proj_json['user_tags'] = [] proj_json['user_tags'].append(new_tag) + if remove_tag: + if 'user_tags' in proj_json: + if remove_tag in proj_json['user_tags']: + proj_json['user_tags'].remove(remove_tag) + else: + logger.warn(f'{remove_tag} not found in user_tags for removal.') + else: + logger.warn(f'user_tags property not found for removal of tag {remove_tag}.') manifest.save_o3de_manifest(proj_json, pathlib.Path(proj_path) / 'project.json') return 0 @@ -47,7 +56,8 @@ def _edit_project_props(args: argparse) -> int: args.project_display, args.project_summary, args.project_icon, - args.project_tag) + args.project_tag, + args.remove_tag) def add_parser_args(parser): group = parser.add_mutually_exclusive_group(required=True) @@ -65,7 +75,9 @@ def add_parser_args(parser): group.add_argument('-pi', '--project-icon', type=str, required=False, help='Sets the path to the projects icon resource.') group.add_argument('-pt', '--project-tag', type=str, required=False, - help='Adds a tag to canonical user tags. These tags are intended for documentation and filtering.') + help='Adds a tag to user tags. These tags are intended for documentation and filtering.') + group.add_argument('-rt', '--remove-tag', type=str, required=False, + help='Removes a tag from user tags. These tags are intended for documentation and filtering.') parser.set_defaults(func=_edit_project_props) def add_args(subparsers) -> None: From 7bba5ed2fc6f91a66fd2fbaada65ac130d7b1c87 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Thu, 3 Jun 2021 14:43:13 -0400 Subject: [PATCH 476/811] Incorporated suggestion to use setdefault to handle missing tag property rather than explicitly checking for and creating it. --- scripts/o3de/o3de/project_properties.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/scripts/o3de/o3de/project_properties.py b/scripts/o3de/o3de/project_properties.py index 7a9610a775..63ff05a8da 100644 --- a/scripts/o3de/o3de/project_properties.py +++ b/scripts/o3de/o3de/project_properties.py @@ -34,9 +34,7 @@ def edit_project_props(proj_path, proj_name, new_origin, new_display, if new_icon: proj_json['icon_path'] = new_icon if new_tag: - if 'user_tags' not in proj_json: - proj_json['user_tags'] = [] - proj_json['user_tags'].append(new_tag) + proj_json.setdefault('user_tags', []).append(new_tag) if remove_tag: if 'user_tags' in proj_json: if remove_tag in proj_json['user_tags']: @@ -75,9 +73,9 @@ def add_parser_args(parser): group.add_argument('-pi', '--project-icon', type=str, required=False, help='Sets the path to the projects icon resource.') group.add_argument('-pt', '--project-tag', type=str, required=False, - help='Adds a tag to user tags. These tags are intended for documentation and filtering.') + help='Adds a tag to user_tags property. These tags are intended for documentation and filtering.') group.add_argument('-rt', '--remove-tag', type=str, required=False, - help='Removes a tag from user tags. These tags are intended for documentation and filtering.') + help='Removes a tag from the user_tags property.') parser.set_defaults(func=_edit_project_props) def add_args(subparsers) -> None: From e99a95d909948d51b02b6fefb3f393eace5b7aca Mon Sep 17 00:00:00 2001 From: mgwynn Date: Thu, 3 Jun 2021 15:02:18 -0400 Subject: [PATCH 477/811] Added copyright header for validation --- scripts/o3de/o3de/project_properties.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/scripts/o3de/o3de/project_properties.py b/scripts/o3de/o3de/project_properties.py index 63ff05a8da..69bd1b9406 100644 --- a/scripts/o3de/o3de/project_properties.py +++ b/scripts/o3de/o3de/project_properties.py @@ -1,3 +1,14 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + import argparse import json import os From dce87534c7d9a7cb1f686d3368998093cc08b2fa Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 3 Jun 2021 14:37:16 -0500 Subject: [PATCH 478/811] Removing the Pyside implementation of the project manager python scripts (#1112) * Removing the Pyside implementation of the project manager python scripts * Removing reference to the scripts/project_manager directory The Install_common.cmake script reference to the project_manager directory has been removed. --- cmake/Platform/Common/Install_common.cmake | 1 - scripts/CMakeLists.txt | 1 - scripts/project_manager/CMakeLists.txt | 22 - scripts/project_manager/__init__.py | 10 - scripts/project_manager/projects.py | 804 ------------------ scripts/project_manager/pyside.py | 61 -- scripts/project_manager/tests/__init__.py | 10 - .../project_manager/tests/test_projects.py | 255 ------ scripts/project_manager/tests/test_pyside.py | 54 -- .../ui/create_from_template.ui | 94 -- scripts/project_manager/ui/create_gem.ui | 94 -- scripts/project_manager/ui/create_project.ui | 94 -- .../project_manager/ui/manage_gem_targets.ui | 165 ---- .../project_manager/ui/project_manager.ico | 3 - scripts/project_manager/ui/project_manager.ui | 407 --------- 15 files changed, 2075 deletions(-) delete mode 100644 scripts/project_manager/CMakeLists.txt delete mode 100755 scripts/project_manager/__init__.py delete mode 100755 scripts/project_manager/projects.py delete mode 100755 scripts/project_manager/pyside.py delete mode 100755 scripts/project_manager/tests/__init__.py delete mode 100755 scripts/project_manager/tests/test_projects.py delete mode 100755 scripts/project_manager/tests/test_pyside.py delete mode 100644 scripts/project_manager/ui/create_from_template.ui delete mode 100644 scripts/project_manager/ui/create_gem.ui delete mode 100644 scripts/project_manager/ui/create_project.ui delete mode 100644 scripts/project_manager/ui/manage_gem_targets.ui delete mode 100644 scripts/project_manager/ui/project_manager.ico delete mode 100644 scripts/project_manager/ui/project_manager.ui diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 710a8b266f..11260ab018 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -443,7 +443,6 @@ function(ly_setup_others) install(DIRECTORY ${LY_ROOT_FOLDER}/scripts/bundler - ${LY_ROOT_FOLDER}/scripts/project_manager ${LY_ROOT_FOLDER}/scripts/o3de DESTINATION ./scripts COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} diff --git a/scripts/CMakeLists.txt b/scripts/CMakeLists.txt index d3c9640665..6df0f4b77f 100644 --- a/scripts/CMakeLists.txt +++ b/scripts/CMakeLists.txt @@ -12,5 +12,4 @@ add_subdirectory(detect_file_changes) add_subdirectory(commit_validation) add_subdirectory(o3de) -add_subdirectory(project_manager) add_subdirectory(ctest) diff --git a/scripts/project_manager/CMakeLists.txt b/scripts/project_manager/CMakeLists.txt deleted file mode 100644 index 36c9ad0360..0000000000 --- a/scripts/project_manager/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -ly_download_associated_package(pyside2) - -ly_add_pytest( - NAME test_pyside - PATH ${CMAKE_CURRENT_LIST_DIR}/tests/test_pyside.py -) - -ly_add_pytest( - NAME test_projects - PATH ${CMAKE_CURRENT_LIST_DIR}/tests/test_projects.py -) \ No newline at end of file diff --git a/scripts/project_manager/__init__.py b/scripts/project_manager/__init__.py deleted file mode 100755 index 4d5680a30d..0000000000 --- a/scripts/project_manager/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# diff --git a/scripts/project_manager/projects.py b/scripts/project_manager/projects.py deleted file mode 100755 index f9f40aa4bf..0000000000 --- a/scripts/project_manager/projects.py +++ /dev/null @@ -1,804 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -# PySide project and gem selector GUI - -import os -import pathlib -import sys -import argparse -import json -import logging -import subprocess -from logging.handlers import RotatingFileHandler -from typing import List -from pyside import add_pyside_environment, is_pyside_ready, uninstall_env - -engine_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..')) -sys.path.append(engine_path) -executable_path = '' - -logger = logging.getLogger() -logger.setLevel(logging.INFO) - -from o3de import disable_gem, enable_gem, cmake, engine_template, manifest, register - -o3de_folder = manifest.get_o3de_folder() -o3de_logs_folder = manifest.get_o3de_logs_folder() -project_manager_log_file_path = o3de_logs_folder / "project_manager.log" -log_file_handler = RotatingFileHandler(filename=project_manager_log_file_path, maxBytes=1024 * 1024, backupCount=1) -formatter = logging.Formatter('%(asctime)s | %(levelname)s : %(message)s') -log_file_handler.setFormatter(formatter) -logger.addHandler(log_file_handler) - -logger.info("Starting Project Manager") - - -def initialize_pyside_from_parser(): - # Parse arguments up top. We need to know the path to our binaries and QT libs in particular to load up - # PySide - parser = argparse.ArgumentParser() - parser.add_argument('--executable-path', required=True, help='Path to Executable to launch with project') - parser.add_argument('--binaries-path', default=None, help='Path to QT Binaries necessary for PySide. If not' - ' provided executable_path folder is assumed') - parser.add_argument('--parent-pid', default=0, help='Process ID of launching process') - - args = parser.parse_args() - - logger.info(f"parent_pid is {args.parent_pid}") - global executable_path - executable_path = args.executable_path - binaries_path = args.binaries_path or os.path.dirname(executable_path) - - # Initialize PySide before imports below. This adds both PySide python modules to the python system interpreter - # path and adds the necessary paths to binaries for the DLLs to be found and load their dependencies - add_pyside_environment(binaries_path) - - -if not is_pyside_ready(): - initialize_pyside_from_parser() - -try: - from PySide2.QtWidgets import QApplication, QDialogButtonBox, QPushButton, QComboBox, QMessageBox, QFileDialog - from PySide2.QtWidgets import QListView, QLabel - from PySide2.QtUiTools import QUiLoader - from PySide2.QtCore import QFile, QObject, Qt, Signal, Slot - from PySide2.QtGui import QIcon, QStandardItemModel, QStandardItem -except ImportError as e: - logger.error(f"Failed to import PySide2 with error {e}") - exit(-1) - -logger.error(f"PySide2 imports successful") - - -class DialogLoggerSignaller(QObject): - send_to_dialog = Signal(str) - - def __init__(self, dialog_logger): - super(DialogLoggerSignaller, self).__init__() - - self.dialog_logger = dialog_logger - - -# Independent class to handle log forwarding. Logger and qt signals both use emit method. -# This class's job is to receive the logger record and then emit the formatted message through -# DialogLoggerSignaller which is what the ProjectDialog handler listens for -class DialogLogger(logging.Handler): - - def __init__(self, log_dialog, log_level=logging.INFO, forward_log_level=logging.WARNING, - message_box_log_level=logging.ERROR): - super(DialogLogger, self).__init__() - - self.log_dialog = log_dialog - self.log_level = log_level - self.forward_log_level = forward_log_level - self.message_box_log_level = message_box_log_level - self.log_records = [] - self.formatter = logging.Formatter('%(levelname)s : %(message)s') - self.setFormatter(self.formatter) - self.signaller = DialogLoggerSignaller(self) - - def emit(self, record): - self.log_records.append(record) - if record.levelno >= self.message_box_log_level: - QMessageBox.warning(None, record.levelname, record.message) - elif record.levelno >= self.forward_log_level: - self.signaller.send_to_dialog.emit(self.format(record)) - - -class ProjectManagerDialog(QObject): - """ - Main project manager dialog is responsible for displaying the project selection list and output pane - """ - - def __init__(self, parent=None): - super(ProjectManagerDialog, self).__init__(parent) - - self.ui_path = (pathlib.Path(__file__).parent / 'ui').resolve() - self.home_folder = manifest.get_home_folder() - - self.log_display = None - self.dialog_logger = DialogLogger(self) - logger.addHandler(self.dialog_logger) - logger.setLevel(logging.INFO) - - self.dialog_logger.signaller.send_to_dialog.connect(self.handle_log_message) - self.mru_file_path = o3de_folder / 'mru.json' - - self.create_from_template_ui_file_path = self.ui_path / 'create_from_template.ui' - self.create_gem_ui_file_path = self.ui_path / 'create_gem.ui' - self.create_project_ui_file_path = self.ui_path / 'create_project.ui' - self.manage_project_gem_targets_ui_file_path = self.ui_path / 'manage_gem_targets.ui' - self.project_manager_icon_file_path = self.ui_path / 'project_manager.ico' - self.project_manager_ui_file_path = self.ui_path / 'project_manager.ui' - - self.project_manager_ui_file = QFile(self.project_manager_ui_file_path.as_posix()) - self.project_manager_ui_file.open(QFile.ReadOnly) - - loader = QUiLoader() - self.dialog = loader.load(self.project_manager_ui_file) - self.dialog.setWindowIcon(QIcon(self.project_manager_icon_file_path.as_posix())) - self.dialog.setFixedSize(self.dialog.size()) - - self.project_list_box = self.dialog.findChild(QComboBox, 'projectListBox') - self.refresh_project_list() - mru = self.get_mru_list() - if len(mru): - last_mru = pathlib.Path(mru[0]).resolve() - for this_slot in range(self.project_list_box.count()): - item_text = self.project_list_box.itemText(this_slot) - if last_mru.as_posix() in item_text: - self.project_list_box.setCurrentIndex(this_slot) - break - - self.create_project_button = self.dialog.findChild(QPushButton, 'createProjectButton') - self.create_project_button.clicked.connect(self.create_project_handler) - self.create_gem_button = self.dialog.findChild(QPushButton, 'createGemButton') - self.create_gem_button.clicked.connect(self.create_gem_handler) - self.create_template_button = self.dialog.findChild(QPushButton, 'createTemplateButton') - self.create_template_button.clicked.connect(self.create_template_handler) - self.create_from_template_button = self.dialog.findChild(QPushButton, 'createFromTemplateButton') - self.create_from_template_button.clicked.connect(self.create_from_template_handler) - - self.add_project_button = self.dialog.findChild(QPushButton, 'addProjectButton') - self.add_project_button.clicked.connect(self.add_project_handler) - self.add_gem_button = self.dialog.findChild(QPushButton, 'addGemButton') - self.add_gem_button.clicked.connect(self.add_gem_handler) - self.add_template_button = self.dialog.findChild(QPushButton, 'addTemplateButton') - self.add_template_button.clicked.connect(self.add_template_handler) - self.add_restricted_button = self.dialog.findChild(QPushButton, 'addRestrictedButton') - self.add_restricted_button.clicked.connect(self.add_restricted_handler) - - self.remove_project_button = self.dialog.findChild(QPushButton, 'removeProjectButton') - self.remove_project_button.clicked.connect(self.remove_project_handler) - self.remove_gem_button = self.dialog.findChild(QPushButton, 'removeGemButton') - self.remove_gem_button.clicked.connect(self.remove_gem_handler) - self.remove_template_button = self.dialog.findChild(QPushButton, 'removeTemplateButton') - self.remove_template_button.clicked.connect(self.remove_template_handler) - self.remove_restricted_button = self.dialog.findChild(QPushButton, 'removeRestrictedButton') - self.remove_restricted_button.clicked.connect(self.remove_restricted_handler) - - self.manage_project_gem_targets_button = self.dialog.findChild(QPushButton, 'manageRuntimeGemTargetsButton') - self.manage_project_gem_targets_button.clicked.connect(self.manage_project_gem_targets_handler) - - self.log_display = self.dialog.findChild(QLabel, 'logDisplay') - - self.ok_cancel_button = self.dialog.findChild(QDialogButtonBox, 'okCancel') - self.ok_cancel_button.accepted.connect(self.accepted_handler) - - self.dialog.show() - - def refresh_project_list(self) -> None: - projects = manifest.get_all_projects() - self.project_list_box.clear() - for this_slot in range(len(projects)): - display_name = f'{os.path.basename(os.path.normpath(projects[this_slot]))} ({projects[this_slot]})' - self.project_list_box.addItem(display_name) - self.project_list_box.setItemData(self.project_list_box.count() - 1, projects[this_slot], - Qt.ToolTipRole) - - def accepted_handler(self) -> None: - """ - Override for handling "Ok" on main project dialog to first check whether the user has selected a project and - prompt them to if not. If a project is selected will attempt to open it. - :return: None - """ - if not self.project_list_box.currentText(): - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText("Please select a project") - msg_box.exec() - return - self.launch_with_project_path(self.get_selected_project_path()) - - def get_launch_project(self) -> str: - return os.path.normpath(self.get_selected_project_path()) - - def get_executable_launch_params(self) -> list: - """ - Retrieve the necessary launch parameters to make the subprocess launch call with - this is the path - to the executable such as the Editor and the path to the selected project - :return: list of params - """ - launch_params = [executable_path, - f'-regset="/Amazon/AzCore/Bootstrap/project_path={self.get_launch_project()}"'] - return launch_params - - def launch_with_project_path(self, project_path: str) -> None: - """ - Launch the desired application given the selected project - :param project_path: Path to currently selected project - :return: None - """ - logger.info(f'Attempting to open {project_path}') - self.update_mru_list(project_path) - launch_params = self.get_executable_launch_params() - logger.info(f'Launching with params {launch_params}') - subprocess.run(launch_params, env=uninstall_env()) - - def get_selected_project_path(self) -> str: - if self.project_list_box.currentIndex() == -1: - logger.warning("No project selected") - return "" - return self.project_list_box.itemData(self.project_list_box.currentIndex(), Qt.ToolTipRole) - - def get_selected_project_name(self) -> str: - project_data = manifest.get_project_json_data(project_path=self.get_selected_project_path()) - return project_data['project_name'] - - def create_project_handler(self): - """ - Opens the Create Project pane. Retrieves a list of available templates for display - :return: None - """ - loader = QUiLoader() - self.create_project_file = QFile(self.create_project_ui_file_path.as_posix()) - - if not self.create_project_file: - logger.error(f'Failed to create project UI file at {self.create_project_file}') - return - - self.create_project_dialog = loader.load(self.create_project_file) - - if not self.create_project_dialog: - logger.error(f'Failed to load create project dialog file at {self.create_project_file}') - return - - self.create_project_ok_button = self.create_project_dialog.findChild(QDialogButtonBox, 'okCancel') - self.create_project_ok_button.accepted.connect(self.create_project_accepted_handler) - - self.create_project_template_list = self.create_project_dialog.findChild(QListView, 'projectTemplates') - self.refresh_create_project_template_list() - - self.create_project_dialog.exec() - - def create_project_accepted_handler(self) -> None: - """ - Searches the available gems list for selected gems and attempts to add each one to the current project. - Updates UI after completion. - :return: None - """ - - selected_item = self.create_project_template_list.selectionModel().currentIndex() - project_template_path = self.create_project_template_list.model().data(selected_item) - if not project_template_path: - return - - folder_dialog = QFileDialog(self.dialog, "Select a Folder and Enter a New Project Name", - manifest.get_o3de_projects_folder().as_posix()) - folder_dialog.setFileMode(QFileDialog.AnyFile) - folder_dialog.setOptions(QFileDialog.ShowDirsOnly) - project_count = 0 - project_name = "MyNewProject" - while os.path.exists(os.path.join(engine_path, project_name)): - project_name = f"MyNewProject{project_count}" - project_count += 1 - folder_dialog.selectFile(project_name) - project_folder = None - if folder_dialog.exec(): - project_folder = folder_dialog.selectedFiles() - if project_folder: - if engine_template.create_project(project_path=project_folder[0], - template_path=project_template_path) == 0: - # Success - register.register(project_path=project_folder[0]) - self.refresh_project_list() - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Project {project_folder[0]} created.") - msg_box.exec() - return - - def create_gem_handler(self): - """ - Opens the Create Gem pane. Retrieves a list of available templates for display - :return: None - """ - loader = QUiLoader() - self.create_gem_file = QFile(self.create_gem_ui_file_path.as_posix()) - - if not self.create_gem_file: - logger.error(f'Failed to create gem UI file at {self.create_gem_file}') - return - - self.create_gem_dialog = loader.load(self.create_gem_file) - - if not self.create_gem_dialog: - logger.error(f'Failed to load create gem dialog file at {self.create_gem_file}') - return - - self.create_gem_ok_button = self.create_gem_dialog.findChild(QDialogButtonBox, 'okCancel') - self.create_gem_ok_button.accepted.connect(self.create_gem_accepted_handler) - - self.create_gem_template_list = self.create_gem_dialog.findChild(QListView, 'gemTemplates') - self.refresh_create_gem_template_list() - - self.create_gem_dialog.exec() - - def create_gem_accepted_handler(self) -> None: - """ - Searches the available gems list for selected gems and attempts to add each one to the current gem. - Updates UI after completion. - :return: None - """ - selected_item = self.create_gem_template_list.selectionModel().currentIndex() - gem_template_path = self.create_gem_template_list.model().data(selected_item) - if not gem_template_path: - return - - folder_dialog = QFileDialog(self.dialog, "Select a Folder and Enter a New Gem Name", - manifest.get_o3de_gems_folder().as_posix()) - folder_dialog.setFileMode(QFileDialog.AnyFile) - folder_dialog.setOptions(QFileDialog.ShowDirsOnly) - gem_count = 0 - gem_name = "MyNewGem" - while os.path.exists(os.path.join(engine_path, gem_name)): - gem_name = f"MyNewGem{gem_count}" - gem_count += 1 - folder_dialog.selectFile(gem_name) - gem_folder = None - if folder_dialog.exec(): - gem_folder = folder_dialog.selectedFiles() - if gem_folder: - if engine_template.create_gem(gem_path=gem_folder[0], - template_path=gem_template_path) == 0: - # Success - register.register(gem_path=gem_folder[0]) - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Gem {gem_folder[0]} created.") - msg_box.exec() - return - - def create_template_handler(self): - """ - Opens a foldr select dialog and lets the user select the source folder they want to make a template - out of, then opens a second folder select dialog to get where they want to put the template and it name - :return: None - """ - - source_folder = QFileDialog.getExistingDirectory(self.dialog, - "Select a Folder to make a template out of.", - manifest.get_o3de_folder().as_posix()) - if not source_folder: - return - - destination_template_folder_dialog = QFileDialog(self.dialog, - "Select where the template is to be created and named.", - manifest.get_o3de_templates_folder().as_posix()) - destination_template_folder_dialog.setFileMode(QFileDialog.AnyFile) - destination_template_folder_dialog.setOptions(QFileDialog.ShowDirsOnly) - destination_folder = None - if destination_template_folder_dialog.exec(): - destination_folder = destination_template_folder_dialog.selectedFiles() - if not destination_folder: - return - - if engine_template.create_template(source_path=source_folder, - template_path=destination_folder[0]) == 0: - # Success - register.register(template_path=destination_folder[0]) - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Template {destination_folder[0]} created.") - msg_box.exec() - return - - def create_from_template_handler(self): - """ - Opens the Create from_template pane. Retrieves a list of available from_templates for display - :return: None - """ - loader = QUiLoader() - self.create_from_template_file = QFile(self.create_from_template_ui_file_path.as_posix()) - - if not self.create_from_template_file: - logger.error(f'Failed to create from_template UI file at {self.create_from_template_file}') - return - - self.create_from_template_dialog = loader.load(self.create_from_template_file) - - if not self.create_from_template_dialog: - logger.error(f'Failed to load create from_template dialog file at {self.create_from_template_file}') - return - - self.create_from_template_ok_button = self.create_from_template_dialog.findChild(QDialogButtonBox, 'okCancel') - self.create_from_template_ok_button.accepted.connect(self.create_from_template_accepted_handler) - - self.create_from_template_list = self.create_from_template_dialog.findChild(QListView, 'genericTemplates') - self.refresh_create_from_template_list() - - self.create_from_template_dialog.exec() - - def create_from_template_accepted_handler(self) -> None: - """ - Searches the available gems list for selected gems and attempts to add each one to the current gem. - Updates UI after completion. - :return: None - """ - create_gem_item = self.get_selected_gem_template() - if not create_gem_item: - return - - folder_dialog = QFileDialog(self.dialog, "Select a Folder and Enter a New Gem Name", - manifest.get_o3de_gems_folder().as_posix()) - folder_dialog.setFileMode(QFileDialog.AnyFile) - folder_dialog.setOptions(QFileDialog.ShowDirsOnly) - gem_count = 0 - gem_name = "MyNewGem" - while os.path.exists(os.path.join(engine_path, gem_name)): - gem_name = f"MyNewGem{gem_count}" - gem_count += 1 - folder_dialog.selectFile(gem_name) - gem_folder = None - if folder_dialog.exec(): - gem_folder = folder_dialog.selectedFiles() - if gem_folder: - if engine_template.create_gem(gem_folder[0], create_gem_item[1]) == 0: - # Success - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"gem {os.path.basename(os.path.normpath(gem_folder[0]))} created." - " Build your\nnew gem before hitting OK to launch.") - msg_box.exec() - return - - def add_project_handler(self): - """ - Open a file search dialog looking for a folder which contains a valid project. If valid - will update the mru list with the new entry, if invalid will warn the user. - :return: None - """ - project_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Project Folder", - manifest.get_o3de_projects_folder().as_posix()) - if project_folder: - if register.register(project_path=project_folder) == 0: - # Success - self.refresh_project_list() - - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Added Project {project_folder}.") - msg_box.exec() - return - - def add_gem_handler(self): - """ - Open a file search dialog looking for a folder which contains a gem. If valid - will update the mru list with the new entry, if invalid will warn the user. - :return: None - """ - gem_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Gem Folder", - manifest.get_o3de_gems_folder().as_posix()) - if gem_folder: - if register.register(gem_path=gem_folder) == 0: - # Success - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Added Gem {gem_folder}.") - msg_box.exec() - return - - def add_template_handler(self): - """ - Open a file search dialog looking for a folder which contains a valid template. If valid - will update the mru list with the new entry, if invalid will warn the user. - :return: None - """ - template_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Template Folder", - manifest.get_o3de_templates_folder().as_posix()) - if template_folder: - if register.register(template_path=template_folder) == 0: - # Success - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Added Template {template_folder}.") - msg_box.exec() - return - - def add_restricted_handler(self): - """ - Open a file search dialog looking for a folder which contains a valid template. If valid - will update the mru list with the new entry, if invalid will warn the user. - :return: None - """ - restricted_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Restricted Folder", - manifest.get_o3de_restricted_folder().as_posix()) - if restricted_folder: - if register.register(restricted_path=restricted_folder) == 0: - # Success - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Added Restricted {restricted_folder}.") - msg_box.exec() - return - - def remove_project_handler(self): - """ - Open a file search dialog looking for a folder which contains a valid project. If valid - will update the mru list with the new entry, if invalid will warn the user. - :return: None - """ - project_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Project Folder", - manifest.get_o3de_projects_folder().as_posix()) - if project_folder: - if register.register(project_path=project_folder, remove=True) == 0: - # Success - self.refresh_project_list() - - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Removed Project {project_folder}.") - msg_box.exec() - return - - def remove_gem_handler(self): - """ - Open a file search dialog looking for a folder which contains a gem. If valid - will update the mru list with the new entry, if invalid will warn the user. - :return: None - """ - gem_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Gem Folder", - manifest.get_o3de_gems_folder().as_posix()) - if gem_folder: - if register.register(gem_path=gem_folder, remove=True) == 0: - # Success - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Removed Gem {gem_folder}.") - msg_box.exec() - return - - def remove_template_handler(self): - """ - Open a file search dialog looking for a folder which contains a valid template. If valid - will update the mru list with the new entry, if invalid will warn the user. - :return: None - """ - template_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Template Folder", - manifest.get_o3de_templates_folder().as_posix()) - if template_folder: - if register.register(template_path=template_folder, remove=True) == 0: - # Success - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Removed Template {template_folder}.") - msg_box.exec() - return - - def remove_restricted_handler(self): - """ - Open a file search dialog looking for a folder which contains a valid template. If valid - will update the mru list with the new entry, if invalid will warn the user. - :return: None - """ - restricted_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Restricted Folder", - manifest.get_o3de_restricted_folder().as_posix()) - if restricted_folder: - if register.register(restricted_path=restricted_folder, remove=True) == 0: - # Success - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Removed Restricted {restricted_folder}.") - msg_box.exec() - return - - def manage_project_gem_targets_handler(self): - """ - Opens the Gem management pane. Waits for the load thread to complete if still running and displays all - active gems for the current project as well as all available gems which aren't currently active. - :return: None - """ - - if not self.get_selected_project_path(): - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText("Please select a project") - msg_box.exec() - return - - loader = QUiLoader() - self.manage_project_gem_targets_file = QFile(self.manage_project_gem_targets_ui_file_path.as_posix()) - - if not self.manage_project_gem_targets_file: - logger.error(f'Failed to load manage gem targets UI file at {self.manage_project_gem_targets_ui_file_path}') - return - - self.manage_project_gem_targets_dialog = loader.load(self.manage_project_gem_targets_file) - - if not self.manage_project_gem_targets_dialog: - logger.error(f'Failed to load gems dialog file at {self.manage_project_gem_targets_ui_file_path.as_posix()}') - return - - self.manage_project_gem_targets_dialog.setWindowTitle(f"Manage Gems for Project:" - f" {self.get_selected_project_name()}") - - self.add_gem_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, 'addGemTargetsButton') - self.add_gem_button.clicked.connect(self.add_project_gem_targets_handler) - - self.available_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, - 'availableGemTargetsList') - self.refresh_project_gem_targets_available_list() - - self.remove_project_gem_targets_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, - 'removeGemTargetsButton') - self.remove_project_gem_targets_button.clicked.connect(self.remove_project_gem_targets_handler) - - self.enabled_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, - 'enabledGemTargetsList') - self.refresh_project_gem_targets_enabled_list() - - self.manage_project_gem_targets_dialog.exec() - - - def manage_project_gem_targets_get_selected_available_gems(self) -> list: - selected_items = self.available_gem_targets_list.selectionModel().selectedRows() - return [(self.available_gem_targets_list.model().data(item)) for item in selected_items] - - def manage_project_gem_targets_get_selected_enabled_gems(self) -> list: - selected_items = self.enabled_gem_targets_list.selectionModel().selectedRows() - return [(self.enabled_gem_targets_list.model().data(item)) for item in selected_items] - - def add_project_gem_targets_handler(self) -> None: - gem_paths = manifest.get_all_gems() - for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): - for gem_path in gem_paths: - enable_gem.enable_gem_in_project(gem_path=gem_path, - project_path=self.get_selected_project_path()) - self.refresh_project_gem_targets_available_list() - self.refresh_project_gem_targets_enabled_list() - return - self.refresh_project_gem_targets_available_list() - self.refresh_project_gem_targets_enabled_list() - - def remove_project_gem_targets_handler(self): - gem_paths = manifest.get_all_gems() - for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): - for gem_path in gem_paths: - disable_gem.disable_gem_in_project(gem_path=gem_path, - project_path=self.get_selected_project_path()) - self.refresh_project_gem_targets_available_list() - self.refresh_project_gem_targets_enabled_list() - return - self.refresh_project_gem_targets_available_list() - self.refresh_project_gem_targets_enabled_list() - - def refresh_project_gem_targets_enabled_list(self) -> None: - enabled_project_gem_targets_model = QStandardItemModel() - enabled_project_gems = cmake.get_project_gems(project_path=self.get_selected_project_path()) - for gem_target in sorted(enabled_project_gems): - model_item = QStandardItem(gem_target) - enabled_project_gem_targets_model.appendRow(model_item) - self.enabled_gem_targets_list.setModel(enabled_project_gem_targets_model) - - - def refresh_project_gem_targets_available_list(self) -> None: - available_project_gem_targets_model = QStandardItemModel() - enabled_project_gem_targets = cmake.get_project_gems(project_path=self.get_selected_project_path()) - all_gem_targets = manifest.get_all_gems() - for gem_target in sorted(all_gem_targets): - if gem_target not in enabled_project_gem_targets: - model_item = QStandardItem(gem_target) - available_project_gem_targets_model.appendRow(model_item) - self.available_gem_targets_list.setModel(available_project_gem_targets_model) - - - def refresh_create_project_template_list(self) -> None: - self.create_project_template_model = QStandardItemModel() - for project_template_path in manifest.get_project_templates(): - model_item = QStandardItem(project_template_path) - self.create_project_template_model.appendRow(model_item) - self.create_project_template_list.setModel(self.create_project_template_model) - - def refresh_create_gem_template_list(self) -> None: - self.create_gem_template_model = QStandardItemModel() - for gem_template_path in manifest.get_gem_templates(): - model_item = QStandardItem(gem_template_path) - self.create_gem_template_model.appendRow(model_item) - self.create_gem_template_list.setModel(self.create_gem_template_model) - - def refresh_create_from_template_list(self) -> None: - self.create_from_template_model = QStandardItemModel() - for generic_template_path in manifest.get_generic_templates(): - model_item = QStandardItem(generic_template_path) - self.create_from_template_model.appendRow(model_item) - self.create_from_template_list.setModel(self.create_from_template_model) - - def update_mru_list(self, used_project: str) -> None: - """ - Promote a supplied project name to the "most recent" in a given MRU list. - :param used_project: path to project to promote - :param file_path: path to mru list file - :return: None - """ - used_project = os.path.normpath(used_project) - if not os.path.exists(os.path.dirname(self.mru_file_path)): - os.makedirs(os.path.dirname(self.mru_file_path), exist_ok=True) - mru_data = {} - try: - with open(self.mru_file_path, 'r') as mru_file: - mru_data = json.loads(mru_file.read()) - except FileNotFoundError: - pass - except json.JSONDecodeError: - pass - - recent_list = mru_data.get('Projects', []) - recent_list = [item for item in recent_list if item.get('Path') != used_project and - self.is_project_folder(item.get('Path'))] - - new_list = [{'Path': used_project}] - new_list.extend(recent_list) - - mru_data['Projects'] = new_list - try: - with open(self.mru_file_path, 'w') as mru_file: - mru_file.write(json.dumps(mru_data, indent=1)) - except PermissionError as e: - logger.warning(f"Failed to write {self.mru_file_path} with error {e}") - - def get_mru_list(self) -> List[str]: - """ - Retrieve the current MRU list. Does not perform validation that the projects still appear valid - :return: list of full path strings to project folders - """ - if not os.path.exists(os.path.dirname(self.mru_file_path)): - return [] - try: - with open(self.mru_file_path, 'r') as mru_file: - mru_data = json.loads(mru_file.read()) - except FileNotFoundError: - return [] - except json.JSONDecodeError: - logger.error(f'MRU list at {self.mru_file_path} is not valid JSON') - return [] - - recent_list = mru_data.get('Projects', []) - return [item.get('Path') for item in recent_list if item.get('Path') is not None] - - @Slot(str) - def handle_log_message(self, message: str) -> None: - """ - Signal handler for messages from the logger. Displays the most recent warning/error - :param message: formatted log message from DialogLoggerSignaller - :return: - """ - if not self.log_display: - return - self.log_display.setText(message) - self.log_display.setToolTip(message) - - -if __name__ == "__main__": - dialog_app = QApplication(sys.argv) - my_dialog = ProjectManagerDialog() - dialog_app.exec_() - sys.exit(0) diff --git a/scripts/project_manager/pyside.py b/scripts/project_manager/pyside.py deleted file mode 100755 index 80bf327f9b..0000000000 --- a/scripts/project_manager/pyside.py +++ /dev/null @@ -1,61 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -import os -import logging - -from pathlib import Path - -logger = logging.getLogger() - -pyside_initialized = False -old_env = os.environ.copy() - -# Helper to extend OS PATH for pyside to locate our QT binaries based on our build folder -def add_pyside_environment(bin_path): - if is_pyside_ready(): - # No need to reinitialize currently - logger.info("Pyside environment already initialized") - return - global old_env - old_env = os.environ.copy() - binaries_path = Path(os.path.normpath(bin_path)) - platforms_path = binaries_path.joinpath("platforms") - logger.info(f'Adding binaries path {binaries_path}') - os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = str(platforms_path) - - path = os.environ['PATH'] - - new_path = os.pathsep.join([str(binaries_path), str(platforms_path), path]) - os.environ['PATH'] = new_path - - global pyside_initialized - pyside_initialized = True - - -def is_pyside_ready(): - return pyside_initialized - - -def is_configuration_valid(workspace): - return os.path.basename(workspace.paths.build_directory()) != "debug" - - -def uninstall_env(): - if not is_pyside_ready(): - logger.warning("Pyside not initialized") - return os.environ - - global old_env - if old_env.get("QT_QPA_PLATFORM_PLUGIN_PATH"): - old_env.pop("QT_QPA_PLATFORM_PLUGIN_PATH") - os.environ = old_env - return old_env diff --git a/scripts/project_manager/tests/__init__.py b/scripts/project_manager/tests/__init__.py deleted file mode 100755 index 4d5680a30d..0000000000 --- a/scripts/project_manager/tests/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# diff --git a/scripts/project_manager/tests/test_projects.py b/scripts/project_manager/tests/test_projects.py deleted file mode 100755 index d073cf6c7a..0000000000 --- a/scripts/project_manager/tests/test_projects.py +++ /dev/null @@ -1,255 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - - -import pytest -''' -import os -import sys -import tempfile -import logging -import pathlib -from unittest.mock import MagicMock - -logger = logging.getLogger() - -# Code lives one folder above -project_manager_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) -sys.path.append(project_manager_path) - -from pyside import add_pyside_environment, is_configuration_valid -from ly_test_tools import WINDOWS - -sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))) -executable_path = '' -from cmake.Tools import registration -from cmake.Tools import engine_template - - -class ProjectHelper: - def __init__(self): - self._temp_directory = pathlib.Path(tempfile.TemporaryDirectory().name).resolve() - self._temp_directory.mkdir(parents=True, exist_ok=True) - - self.home_path = self._temp_directory - registration.override_home_folder = self.home_path - self.engine_path = registration.get_this_engine_path() - if registration.register(engine_path=self.engine_path): - assert True, f"Failed to register the engine." - - if registration.register_shipped_engine_o3de_objects(): - assert True, f"Failed to register shipped engine objects." - - self.projects_folder = registration.get_o3de_projects_folder() - if not self.projects_folder.is_dir(): - assert True - - self.application = None - self.dialog = None - - def create_empty_projects(self): - self.project_1_dir = self.projects_folder / "Project1" - if engine_template.create_project(project_manager_path=self.project_1_dir): - assert True, f"Failed to create Project1." - - self.project_2_dir = self.projects_folder / "Project2" - if engine_template.create_project(project_manager_path=self.project_2_dir): - assert True, f"Failed to create Project2." - - self.project_3_dir = self.projects_folder / "Project3" - if engine_template.create_project(project_manager_path=self.project_3_dir): - assert True, f"Failed to create Project3." - - self.invalid_project_dir = self.projects_folder / "InvalidProject" - self.invalid_project_dir.mkdir(parents=True, exist_ok=True) - - def setup_dialog_test(self, workspace): - add_pyside_environment(workspace.paths.build_directory()) - - if not is_configuration_valid(workspace): - # This is essentially skipif debug. Our debug tests use our profile version of python, but that means we'd - # need to use the profile version of PySide which works with the profile QT libs which aren't in the debug - # folder we've built. - return None - - from PySide2.QtWidgets import QApplication, QMessageBox - - if QApplication.instance(): - self.application = QApplication.instance() - else: - self.application = QApplication(sys.argv) - assert self.application - - from projects import ProjectManagerDialog - - try: - self.dialog = ProjectManagerDialog(settings_folder=self.home_path) - return self.dialog - except Exception as e: - logger.error(f'Failed to create ProjectManagerDialog with error {e}') - return None - - def create_project_from_template(self, project_name) -> bool: - """ - Uses the dialog to create a temporary project based on the first template found - :param project_name: Name of project to create. Will be created under temp_project_root - :return: True for Success, False for failure - """ - from PySide2.QtWidgets import QWidget, QFileDialog - from projects import ProjectManagerDialog - - QWidget.exec = MagicMock() - self.dialog.create_project_handler() - QWidget.exec.assert_called_once() - - assert len(self.dialog.project_templates), 'Failed to find any project templates' - ProjectManagerDialog.get_selected_project_template = MagicMock(return_value=self.dialog.project_templates[0]) - - QFileDialog.exec = MagicMock() - create_project_path = self.projects_folder / project_name - QFileDialog.selectedFiles = MagicMock(return_value=[create_project_path]) - self.dialog.create_project_accepted_handler() - if create_project_path.is_dir(): - assert True, f"Expected project creation folder not found at {create_project_path}" - - if QWidget.exec.call_count == 2: - assert True, "Message box confirming project creation failed to show" - - -@pytest.fixture -def project_helper(): - return ProjectHelper() - - -@pytest.mark.skipif(not WINDOWS, reason="PySide2 only works on windows currently") -@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent -def test_logger_handler(workspace, project_helper): - my_dialog = project_helper.setup_dialog_test(workspace) - if not my_dialog: - return - - from PySide2.QtWidgets import QMessageBox - QMessageBox.warning = MagicMock() - logger.error(f'Testing logger') - QMessageBox.warning.assert_called_once() - - -@pytest.mark.skipif(not WINDOWS, reason="PySide2 only works on windows currently") -@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent -def test_mru_list(workspace, project_helper): - my_dialog = project_helper.setup_dialog_test(workspace) - if not my_dialog: - return - - project_helper.create_empty_projects() - - from PySide2.QtWidgets import QMessageBox - - mru_list = my_dialog.get_mru_list() - assert len(mru_list) == 0, f'MRU list unexpectedly had entries: {mru_list}' - - QMessageBox.warning = MagicMock() - my_dialog.add_project(project_helper.invalid_project_dir) - mru_list = my_dialog.get_mru_list() - assert len(mru_list) == 0, f'MRU list unexpectedly added an invalid project : {mru_list}' - QMessageBox.warning.assert_called_once() - - my_dialog.add_project(project_helper.project_1_dir) - mru_list = my_dialog.get_mru_list() - assert len(mru_list) == 1, f'MRU list failed to add project at {project_helper.project_1_dir}' - - my_dialog.add_project(project_helper.project_1_dir) - mru_list = my_dialog.get_mru_list() - assert len(mru_list) == 1, f'MRU list added project at {project_helper.project_1_dir} a second time : {mru_list}' - - my_dialog.update_mru_list(project_helper.project_1_dir) - mru_list = my_dialog.get_mru_list() - assert len(mru_list) == 1, f'MRU list added project at {project_helper.project_1_dir} a second time : {mru_list}' - - my_dialog.add_project(project_helper.project_2_dir) - mru_list = my_dialog.get_mru_list() - assert len(mru_list) == 2, f'MRU list failed to add project at {project_helper.project_2_dir}' - - assert mru_list[0] == project_helper.project_2_dir, f"{project_helper.project_2_dir} wasn't first item" - assert mru_list[1] == project_helper.project_1_dir, f"{project_helper.project_1_dir} wasn't second item" - - my_dialog.update_mru_list(project_helper.project_1_dir) - mru_list = my_dialog.get_mru_list() - assert len(mru_list) == 2, f'MRU list added wrong items {mru_list}' - assert mru_list[0] == project_helper.project_1_dir, f"{project_helper.project_1_dir} wasn't first item" - assert mru_list[1] == project_helper.project_2_dir, f"{project_helper.project_2_dir} wasn't second item" - - my_dialog.add_project(project_helper.invalid_project_dir) - mru_list = my_dialog.get_mru_list() - assert len(mru_list) == 2, f'MRU list added invalid item {mru_list}' - assert mru_list[0] == project_helper.project_1_dir, f"{project_helper.project_1_dir} wasn't first item" - assert mru_list[1] == project_helper.project_2_dir, f"{project_helper.project_2_dir} wasn't second item" - - my_dialog.add_project(project_helper.project_3_dir) - mru_list = my_dialog.get_mru_list() - assert len(mru_list) == 3, f'MRU list failed to add {project_helper.project_3_dir} : {mru_list}' - assert mru_list[0] == project_helper.project_3_dir, f"{project_helper.project_3_dir} wasn't first item" - assert mru_list[1] == project_helper.project_1_dir, f"{project_helper.project_1_dir} wasn't second item" - assert mru_list[2] == project_helper.project_2_dir, f"{project_helper.project_2_dir} wasn't third item" - - -@pytest.mark.skipif(not WINDOWS, reason="PySide2 only works on windows currently") -@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent -def test_create_project(workspace, project_helper): - my_dialog = project_helper.setup_dialog_test(workspace) - if not my_dialog: - return - - project_helper.create_project_from_template("TestCreateProject") - - -@pytest.mark.skipif(not WINDOWS, reason="PySide2 only works on windows currently") -@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent -def test_add_remove_gems(workspace, project_helper): - my_dialog = project_helper.setup_dialog_test(workspace) - if not my_dialog: - return - - my_project_name = "TestAddRemoveGems" - - project_helper.create_project_from_template(project_manager_path=my_project_name) - my_project_path = project_helper.projects_folder / my_project_name - - from PySide2.QtWidgets import QWidget, QFileDialog - from projects import ProjectManagerDialog - - assert my_dialog.get_selected_project_path() == my_project_path, "TestAddRemoveGems project not selected" - QWidget.exec = MagicMock() - my_dialog.manage_gems_handler() - assert my_dialog.manage_gem_targets_dialog, "No gem management dialog created" - QWidget.exec.assert_called_once() - - if not len(my_dialog.all_gems_list): - assert True, 'Failed to find any gems' - - my_test_gem_path = my_dialog.all_gems_list[0] - gem_data = registration.get_gem_data(my_test_gem_path) - my_test_gem_selection = (my_test_gem_name, my_test_gem_path) - ProjectManagerDialog.get_selected_add_gems = MagicMock(return_value=[my_test_gem_selection]) - - assert my_test_gem_name, "No Name set in test gem" - assert my_test_gem_name not in my_dialog.project_gem_list, f'Gem {my_test_gem_name} already in project gem list' - - my_dialog.add_gems_handler() - assert my_test_gem_name in my_dialog.project_gem_list, f'Gem {my_test_gem_name} failed to add to gem list' - - ProjectManagerDialog.get_selected_project_gems = MagicMock(return_value=[my_test_gem_name]) - my_dialog.remove_gems_handler() - assert my_test_gem_name not in my_dialog.project_gem_list, f'Gem {my_test_gem_name} still in project gem list' -''' - -def test_project_place_holder(): - pass \ No newline at end of file diff --git a/scripts/project_manager/tests/test_pyside.py b/scripts/project_manager/tests/test_pyside.py deleted file mode 100755 index c9be313f2b..0000000000 --- a/scripts/project_manager/tests/test_pyside.py +++ /dev/null @@ -1,54 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -import pytest -import sys -import os - -pyside_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) -sys.path.append(pyside_path) - -from pyside import add_pyside_environment, is_pyside_ready, is_configuration_valid - -from ly_test_tools import WINDOWS - -import logging -logger = logging.getLogger() - -@pytest.mark.skipif(not WINDOWS, reason="PySide2 only works on windows currently") -@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent -def test_add_pyside_environment(workspace): - import_failed = False - try: - import PySide2 - except ImportError: - import_failed = True - - if not import_failed: - cur_path = sys.path - logger.warning(f"Expected to fail initial import but passed. Sys path was {cur_path}") - - assert is_pyside_ready() is False, "Expected pyside not to be initialized yet" - add_pyside_environment(workspace.paths.build_directory()) - assert is_pyside_ready() is True, "Expected pyside to be initialized yet" - - try: - import PySide2 - if not is_configuration_valid(workspace): - return - from PySide2.QtWidgets import QApplication - except ImportError as e: - assert False, f"Failed to import PySide2 with error {e}" - try: - from PySide2.QtWidgets import QApplication - except ImportError as e: - assert False, f"Failed to import QApplication from PySide2.QtWidgets with error {e}" - diff --git a/scripts/project_manager/ui/create_from_template.ui b/scripts/project_manager/ui/create_from_template.ui deleted file mode 100644 index b6a8740594..0000000000 --- a/scripts/project_manager/ui/create_from_template.ui +++ /dev/null @@ -1,94 +0,0 @@ - - - createFromTemplateDialog - - - - 0 - 0 - 467 - 288 - - - - Create From Template - - - - - 50 - 250 - 400 - 32 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - 10 - 20 - 449 - 221 - - - - QAbstractItemView::SingleSelection - - - - - - 10 - 0 - 300 - 16 - - - - Available Templates - - - - - - - okCancel - accepted() - createFromTemplateDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - okCancel - rejected() - createFromTemplateDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/scripts/project_manager/ui/create_gem.ui b/scripts/project_manager/ui/create_gem.ui deleted file mode 100644 index 5a5fd14a6d..0000000000 --- a/scripts/project_manager/ui/create_gem.ui +++ /dev/null @@ -1,94 +0,0 @@ - - - createGemDialog - - - - 0 - 0 - 467 - 288 - - - - Create Gem - - - - - 50 - 250 - 400 - 32 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - 10 - 20 - 449 - 221 - - - - QAbstractItemView::SingleSelection - - - - - - 10 - 0 - 300 - 16 - - - - Available Templates - - - - - - - okCancel - accepted() - createGemDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - okCancel - rejected() - createGemDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/scripts/project_manager/ui/create_project.ui b/scripts/project_manager/ui/create_project.ui deleted file mode 100644 index 67a13325b0..0000000000 --- a/scripts/project_manager/ui/create_project.ui +++ /dev/null @@ -1,94 +0,0 @@ - - - createProjectDialog - - - - 0 - 0 - 467 - 288 - - - - Create Project - - - - - 50 - 250 - 400 - 32 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - 10 - 20 - 449 - 221 - - - - QAbstractItemView::SingleSelection - - - - - - 10 - 0 - 300 - 16 - - - - Available Templates - - - - - - - okCancel - accepted() - createProjectDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - okCancel - rejected() - createProjectDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/scripts/project_manager/ui/manage_gem_targets.ui b/scripts/project_manager/ui/manage_gem_targets.ui deleted file mode 100644 index ea9e607d42..0000000000 --- a/scripts/project_manager/ui/manage_gem_targets.ui +++ /dev/null @@ -1,165 +0,0 @@ - - - manageGemTargetsDialog - - - - 0 - 0 - 702 - 297 - - - - Manage Gem Targets - - - - - 310 - 260 - 71 - 32 - - - - Qt::Horizontal - - - QDialogButtonBox::Close - - - - - - 440 - 50 - 250 - 221 - - - - - 0 - 0 - - - - QAbstractItemView::ExtendedSelection - - - - - - 10 - 50 - 250 - 221 - - - - QAbstractItemView::ExtendedSelection - - - - - - 440 - 30 - 251 - 16 - - - - Available Gem Targets - - - - - - 10 - 30 - 251 - 16 - - - - Enabled Gem Targets - - - - - - 264 - 130 - 171 - 23 - - - - Remove Gem Targets >> - - - - - - 264 - 100 - 171 - 23 - - - - << Add Gem Targets - - - - - - 10 - 5 - 400 - 21 - - - - Adding new Gem Targets may require rebuilding - - - - - - - close - accepted() - manageGemTargetsDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - close - rejected() - manageGemTargetsDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/scripts/project_manager/ui/project_manager.ico b/scripts/project_manager/ui/project_manager.ico deleted file mode 100644 index 597266946a..0000000000 --- a/scripts/project_manager/ui/project_manager.ico +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:113be7ded1969e0d535722382b6d3730eed052a10430cf23804ae7f20414b999 -size 108278 diff --git a/scripts/project_manager/ui/project_manager.ui b/scripts/project_manager/ui/project_manager.ui deleted file mode 100644 index 6b3b5f758c..0000000000 --- a/scripts/project_manager/ui/project_manager.ui +++ /dev/null @@ -1,407 +0,0 @@ - - - Dialog - - - - 0 - 0 - 712 - 395 - - - - - 1 - 0 - - - - O3DE - - - Select and manage your projects for O3DE - - - - - 540 - 360 - 161 - 31 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - 10 - 30 - 691 - 31 - - - - Current project to launch or manage gems for. - - - - - - 10 - 10 - 47 - 13 - - - - Project - - - - - - 270 - 220 - 431 - 141 - - - - QFrame::Panel - - - QFrame::Sunken - - - - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - 10 - 70 - 241 - 151 - - - - Create - - - - - 10 - 110 - 221 - 31 - - - - Create a new O3DE object from a pre configured template. - - - Create From Template - - - - - - 10 - 20 - 221 - 31 - - - - Create a new O3DE object from a pre configured template. - - - Create Project - - - - - - 11 - 50 - 221 - 31 - - - - Create a new O3DE object from a pre configured template. - - - Create Gem - - - - - - 11 - 80 - 221 - 31 - - - - Create a new O3DE object from a pre configured template. - - - Create Template - - - - - - - 260 - 70 - 451 - 141 - - - - Registration - - - - - 10 - 80 - 211 - 31 - - - - Browse for an existing O3DE project. - - - Add Template - - - - - - 10 - 20 - 211 - 31 - - - - Browse for an existing O3DE project. - - - Add Project - - - - - - 10 - 50 - 211 - 31 - - - - Browse for an existing O3DE project. - - - Add Gem - - - - - - 10 - 110 - 211 - 31 - - - - Browse for an existing O3DE project. - - - Add Restricted - - - - - - 230 - 110 - 211 - 31 - - - - Browse for an existing O3DE project. - - - Remove Restricted - - - - - - 230 - 20 - 211 - 31 - - - - Browse for an existing O3DE project. - - - Remove Project - - - - - - 230 - 50 - 211 - 31 - - - - Browse for an existing O3DE project. - - - Remove Gem - - - - - - 230 - 80 - 211 - 31 - - - - Browse for an existing O3DE project. - - - Remove Template - - - - - - - 10 - 230 - 241 - 121 - - - - Manage Project - - - - - 10 - 80 - 221 - 31 - - - - Add or remove gems from your selected project. Gems add and remove additional assets and features to projects. - - - Manage Server Gem Targets - - - - - - 10 - 50 - 221 - 31 - - - - Add or remove gems from your selected project. Gems add and remove additional assets and features to projects. - - - Manage Tool Gem Targets - - - - - - 10 - 20 - 221 - 31 - - - - Add or remove gems from your selected project. Gems add and remove additional assets and features to projects. - - - Manage Runtime Gem Targets - - - - - - - - okCancel - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - okCancel - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - From 1b8810b9631a7cd42e141fa23f2cf6bbd1ca1ef0 Mon Sep 17 00:00:00 2001 From: Eric Phister <52085794+amzn-phist@users.noreply.github.com> Date: Thu, 3 Jun 2021 14:52:21 -0500 Subject: [PATCH 479/811] Remove Project namespace from project template (#1124) In the enabled_gems.cmake file, can remove the Project:: namespace on the project module because it's treated the same as a Gem module now. --- Templates/DefaultProject/Template/Code/enabled_gems.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Templates/DefaultProject/Template/Code/enabled_gems.cmake b/Templates/DefaultProject/Template/Code/enabled_gems.cmake index dfb7d93233..ec45be0743 100644 --- a/Templates/DefaultProject/Template/Code/enabled_gems.cmake +++ b/Templates/DefaultProject/Template/Code/enabled_gems.cmake @@ -10,7 +10,7 @@ # {END_LICENSE} set(ENABLED_GEMS - Project::${Name} + ${Name} Atom_AtomBridge Camera CameraFramework From 1245e0b327b3bbeb05ab4f181fd1403cbeaa908e Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 3 Jun 2021 15:02:03 -0500 Subject: [PATCH 480/811] Adding Tools and Builders alias to the DccScriptingInterface gem targets (#1087) * Adding a Tools and Builders variant to the DccScriptingInterface gem target to allow it to be used as a gem in the AtomTest project * Adding support to ly_create_alias to be able to specify an alias with no dependencies Updated the SettingsRegistry.cmake generation code to support generating a Gem target entry in the cmake_dependencies.*.setreg file when an interface library with no dependencies is parsed --- .../DccScriptingInterface/Code/CMakeLists.txt | 10 ++++++++ cmake/Gems.cmake | 10 ++++---- cmake/SettingsRegistry.cmake | 23 +++++++++++-------- 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Code/CMakeLists.txt b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Code/CMakeLists.txt index 76cbf6546d..bad0d743c7 100644 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Code/CMakeLists.txt @@ -9,6 +9,10 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +if(NOT PAL_TRAIT_BUILD_HOST_TOOLS) + return() +endif() + ly_add_target( NAME DccScriptingInterface.Static STATIC NAMESPACE Gem @@ -38,3 +42,9 @@ ly_add_target( PRIVATE Gem::DccScriptingInterface.Static ) + +# Any 'tool' type applications should use Gem::DccScriptingInterface.Editor: +ly_create_alias(NAME DccScriptingInterface.Tools NAMESPACE Gem TARGETS Gem::DccScriptingInterface.Editor) +# Add an empty 'builders' alias to allow the DccScriptInterface root gem path to be added to the generated +# cmake_dependencies..assetprocessor.setreg to allow the asset scan folder for it to be added +ly_create_alias(NAME DccScriptingInterface.Builders NAMESPACE Gem) diff --git a/cmake/Gems.cmake b/cmake/Gems.cmake index d418d5dcd1..169210d991 100644 --- a/cmake/Gems.cmake +++ b/cmake/Gems.cmake @@ -29,9 +29,6 @@ function(ly_create_alias) message(FATAL_ERROR "Provide the namespace of the alias to create using the NAMESPACE keyword") endif() - if (NOT ly_create_alias_TARGETS) - message(FATAL_ERROR "Provide the name of the targets the alias be associated with, using the TARGETS keyword") - endif() if(TARGET ${ly_create_alias_NAMESPACE}::${ly_create_alias_NAME}) message(FATAL_ERROR "Target already exists, cannot create an alias for it: ${ly_create_alias_NAMESPACE}::${ly_create_alias_NAME}\n" @@ -78,8 +75,11 @@ function(ly_create_alias) list(APPEND final_targets ${de_aliased_target_name}) endforeach() - ly_parse_third_party_dependencies("${final_targets}") - ly_add_dependencies(${ly_create_alias_NAME} ${final_targets}) + # add_dependencies must be called with at least one dependent target + if(final_targets) + ly_parse_third_party_dependencies("${final_targets}") + ly_add_dependencies(${ly_create_alias_NAME} ${final_targets}) + endif() # now add the final alias: add_library(${ly_create_alias_NAMESPACE}::${ly_create_alias_NAME} ALIAS ${ly_create_alias_NAME}) diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index 4d932601b4..d7ef91d284 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -25,14 +25,15 @@ set(gems_json_template [[ @target_gem_dependencies_names@ } } -}]] +} +]] ) -set(gem_module_template [[ - "@stripped_gem_target@": - { - "Modules":["$"], - "SourcePaths":["@gem_module_root_relative_to_engine_root@"] - }]] + string(APPEND gem_module_template +[=[ "@stripped_gem_target@":]=] "\n" +[=[ {]=] "\n" +[=[$<$,INTERFACE_LIBRARY>>: "Modules":["$"]]=] "$\n>" +[=[ "SourcePaths":["@gem_module_root_relative_to_engine_root@"]]=] "\n" +[=[ }]=] ) #!ly_get_gem_load_dependencies: Retrieves the list of "load" dependencies for a target @@ -161,10 +162,12 @@ function(ly_delayed_generate_settings_registry) message(FATAL_ERROR "Dependency ${gem_target} from ${target} does not exist") endif() + get_property(has_manually_added_dependencies TARGET ${gem_target} PROPERTY MANUALLY_ADDED_DEPENDENCIES SET) get_target_property(target_type ${gem_target} TYPE) - if (target_type STREQUAL "INTERFACE_LIBRARY") - # don't use interface libraries here, we only want ones which produce actual binaries. - # we have still already recursed into their dependencies - they'll show up later. + if (target_type STREQUAL "INTERFACE_LIBRARY" AND has_manually_added_dependencies) + # don't use interface libraries here, we only want ones which produce actual binaries unless the target + # is empty. We have still already recursed into their dependencies - they'll show up later. + # When the target has no dependencies however we want to add the gem root path to the generated setreg continue() endif() From 0a9d6f5f0f54419b8bab035379b1f631c97a4a53 Mon Sep 17 00:00:00 2001 From: chcurran Date: Thu, 3 Jun 2021 13:13:22 -0700 Subject: [PATCH 481/811] Bug fixes and improvements brought over from demo work. * Generic Multi Function Call ability added to extensible nodes * Code gen improvements, including allowing for more manually codewritten extension of codegen facilities * CVAR to disable automatic update of deprecated node * Fixed variable sorting error that can apply to parser/runtime added variables * Made Edit/SerializeContext ClassBuilder public, as it was needlessly private * Fixed dangerous Datum::GetValueAddress(), it now checks for an empty storage AZSTd::any, as does Datum::Empty() --- .../AzCore/AzCore/Serialization/EditContext.h | 5 +- .../AzCore/Serialization/SerializeContext.h | 10 +- .../Code/Editor/Components/EditorGraph.cpp | 5 +- .../AutoGen/ScriptCanvasNodeable_Header.jinja | 40 +- .../AutoGen/ScriptCanvasNodeable_Source.jinja | 160 +- .../ScriptCanvas_Nodeable_Macros.jinja | 5 +- .../Code/Include/ScriptCanvas/Core/Core.h | 1 - .../Code/Include/ScriptCanvas/Core/Datum.cpp | 8 +- .../Code/Include/ScriptCanvas/Core/Datum.h | 2 +- .../Code/Include/ScriptCanvas/Core/Node.cpp | 11 +- .../Code/Include/ScriptCanvas/Core/Node.h | 2 + .../Include/ScriptCanvas/Core/NodeableNode.h | 2 + .../Code/Include/ScriptCanvas/Core/PureData.h | 2 + .../Grammar/AbstractCodeModel.cpp | 193 +- .../ScriptCanvas/Grammar/AbstractCodeModel.h | 2 + .../ScriptCanvas/Grammar/ParsingUtilities.cpp | 10 +- .../Include/ScriptCanvas/Grammar/Primitives.h | 28 + .../Grammar/PrimitivesExecution.cpp | 38 +- .../Grammar/PrimitivesExecution.h | 8 + .../Include/ScriptCanvas/Results/ErrorText.h | 6 + ...UnitTest_RunAllTransformNodes.scriptcanvas | 9124 +++++++---------- 21 files changed, 4416 insertions(+), 5246 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/EditContext.h b/Code/Framework/AzCore/AzCore/Serialization/EditContext.h index ed19130579..394a6f047c 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/EditContext.h +++ b/Code/Framework/AzCore/AzCore/Serialization/EditContext.h @@ -127,13 +127,14 @@ namespace AZ */ class EditContext { + public: /// @cond EXCLUDE_DOCS class ClassBuilder; class EnumBuilder; using ClassInfo = ClassBuilder; ///< @deprecated Use EditContext::ClassBuilder using EnumInfo = EnumBuilder; ///< @deprecated Use EditContext::EnumBuilder /// @endcond - public: + AZ_CLASS_ALLOCATOR(EditContext, SystemAllocator, 0); /** @@ -186,6 +187,7 @@ namespace AZ * look at the unit tests and example to see use cases. * */ + public: class ClassBuilder { friend EditContext; @@ -399,6 +401,7 @@ namespace AZ EnumBuilder* Value(const char* name, E value); }; + private: typedef AZStd::list ClassDataListType; typedef AZStd::unordered_map EnumDataMapType; diff --git a/Code/Framework/AzCore/AzCore/Serialization/SerializeContext.h b/Code/Framework/AzCore/AzCore/Serialization/SerializeContext.h index 6806232337..279ce01039 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/SerializeContext.h +++ b/Code/Framework/AzCore/AzCore/Serialization/SerializeContext.h @@ -101,6 +101,9 @@ namespace AZ class SerializeContext : public ReflectContext { + static const unsigned int VersionClassDeprecated = (unsigned int)-1; + + public: /// @cond EXCLUDE_DOCS friend class EditContext; class ClassBuilder; @@ -108,9 +111,6 @@ namespace AZ /// @endcond class EnumBuilder; - static const unsigned int VersionClassDeprecated = (unsigned int)-1; - - public: class ClassData; struct EnumerateInstanceCallContext; struct ClassElement; @@ -1131,6 +1131,7 @@ namespace AZ * ->Version(3,&MyVersionConverter) * ->Field("data",&MyStruct::m_data); */ + public: class ClassBuilder { friend class SerializeContext; @@ -1330,7 +1331,8 @@ namespace AZ AZStd::vector* m_currentAttributes = nullptr; }; - EditContext* m_editContext; ///< Pointer to optional edit context. + private: + EditContext* m_editContext; ///< Pointer to optional edit context. UuidToClassMap m_uuidMap; ///< Map for all class in this serialize context AZStd::unordered_multimap m_classNameToUuid; /// Map all class names to their uuid AZStd::unordered_multimap m_uuidGenericMap; ///< Uuid to ClassData map of reflected classes with GenericTypeInfo diff --git a/Gems/ScriptCanvas/Code/Editor/Components/EditorGraph.cpp b/Gems/ScriptCanvas/Code/Editor/Components/EditorGraph.cpp index 6f28cbfe19..616be11dd0 100644 --- a/Gems/ScriptCanvas/Code/Editor/Components/EditorGraph.cpp +++ b/Gems/ScriptCanvas/Code/Editor/Components/EditorGraph.cpp @@ -91,7 +91,8 @@ AZ_POP_DISABLE_WARNING #include #include -//// + AZ_CVAR(bool, g_disableDeprecatedNodeUpdates, false, {}, AZ::ConsoleFunctorFlags::Null, + "Disables automatic update attempts of deprecated nodes, so that graphs that require and update can be viewed in their original form"); namespace EditorGraphCpp { @@ -3642,7 +3643,7 @@ namespace ScriptCanvasEditor if (scriptCanvasNode) { - if (scriptCanvasNode->IsDeprecated()) + if (scriptCanvasNode->IsDeprecated() && !g_disableDeprecatedNodeUpdates) { ScriptCanvas::NodeConfiguration nodeConfig = scriptCanvasNode->GetReplacementNodeConfiguration(); if (nodeConfig.IsValid()) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Header.jinja b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Header.jinja index 202fad5b60..313fd196b0 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Header.jinja +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Header.jinja @@ -22,6 +22,11 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #pragma once +#include +#include +#include +#include + #include #include @@ -43,6 +48,11 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. {% endif %} {% endif %} +{%- set attribute_Base = Class.attrib['Base'] %} +{% if not Class.attrib['Base'] is defined %} +{% set attribute_Base = "ScriptCanvas::Nodeable" %} +{% endif %} + {% if attribute_Namespace is defined %} namespace {{attribute_Namespace}} { @@ -66,6 +76,9 @@ namespace {{attribute_Namespace}} public: \ AZ_RTTI({{className}}, "{{nodeableClassName|createHashGuid}}"{% if Class.attrib['Base'] is defined %}, {{ Class.attrib['Base'] }}{% endif %}); \ static void Reflect(AZ::ReflectContext* reflection); \ + static void ExtendReflectionSerialize([[maybe_unused]] AZ::SerializeContext::ClassBuilder* builder){% if Class.attrib['ExtendReflectionSerialize'] is defined %};{% else %}{}{% endif %} \ + static void ExtendReflectionEdit([[maybe_unused]] AZ::EditContext::ClassBuilder* builder){% if Class.attrib['ExtendReflectionEdit'] is defined %};{% else %}{}{% endif %} \ + static void ExtendReflectionBehavior([[maybe_unused]] AZ::BehaviorContext::ClassBuilder<{{className}}>* builder){% if Class.attrib['ExtendReflectionBehavior'] is defined %};{% else %}{}{% endif %} \ static const char* GetDescription() { return "{{ macros.GetAttributeAsString(Class.attrib, 'Description') }}"; } \ ScriptCanvas::NodePropertyInterface* GetPropertyInterface(AZ::Crc32 propertyId) override; \ bool IsActive() const override { return false; } \ @@ -83,13 +96,33 @@ public: \ AZ_COMPONENT({{nodeableNodeName}}, {% if Class.attrib['NodeableUuid'] is defined %}"{{Class.attrib['NodeableUuid']}}"{% else %}"{{nodeableNodeName|createHashGuid}}"{% endif %}, ScriptCanvas::Nodes::NodeableNode); static void Reflect(AZ::ReflectContext* context); + + static void ExtendReflectionSerialize([[maybe_unused]] AZ::SerializeContext::ClassBuilder* builder){% if Class.attrib['ExtendReflectionSerialize'] is defined %};{% else %}{}{% endif %} + + static void ExtendReflectionEdit([[maybe_unused]] AZ::EditContext::ClassBuilder* builder){% if Class.attrib['ExtendReflectionEdit'] is defined %};{% else %}{}{% endif %} + + static void ExtendReflectionBehavior([[maybe_unused]] AZ::BehaviorContext::ClassBuilder<{{nodeableNodeName}}>* builder){% if Class.attrib['ExtendReflectionBehavior'] is defined %};{% else %}{}{% endif %} + void ConfigureSlots() override; + +{% if Class.attrib['ExtendConfigureSlots'] is defined %} + void ExtendConfigureSlots([[maybe_unused]] SlotExecution::Ins& ins, [[maybe_unused]] SlotExecution::Outs& latents); + +{% else %} + /* no slot configuration extension, Use Class attribute 'ExtendConfigureSlots' to extend them */ + +{% endif %} void ConfigureVisualExtensions() override; + size_t GenerateFingerprint() const override; -{% if Class.attrib['EntryPoint'] is defined and Class.attrib['EntryPoint'] == "true" %} + +{% if Class.attrib['EntryPoint'] is defined and Class.attrib['EntryPoint'] == "true" %} bool IsEntryPoint() const override { return true; } -{% endif %} + +{% endif %} {{nodeableNodeName}}(); + + {{Class.attrib['NodeDeclarations']}} }; } {% endif %} @@ -100,6 +133,5 @@ public: \ {{ macros.ReportErrors() }} - {% endfor %} -{% endfor %} +{% endfor %} \ No newline at end of file diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja index 71681ed73b..b977daf43b 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja @@ -19,15 +19,10 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -#include -#include -#include - #include #include #include #include - #include {% for xml in dataFiles %} @@ -47,13 +42,18 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. {%- set attribute_Category = Class.attrib['Category'] %} {%- set attribute_Uuid = Class.attrib['Uuid'] %} {%- set attribute_Icon = Class.attrib['Icon'] %} -{%- set attribute_Base = Class.attrib['Base'] %} {%- set attribute_GeneratePropertyFriend = Class.attrib['GeneratePropertyFriend'] %} {%- set attribute_Version = Class.attrib['Version'] %} {%- set attribute_VersionConverter = Class.attrib['VersionConverter'] %} {%- set attribute_EventHandler = Class.attrib['EventHandler'] %} {%- set attribute_Deprecated = Class.attrib['Deprecated'] %} + +{%- set attribute_Base = Class.attrib['Base'] %} +{% if not Class.attrib['Base'] is defined %} +{% set attribute_Base = "ScriptCanvas::Nodeable" %} +{% endif %} + {% set attribute_Namespace = undefined %} {%- if Class.attrib['Namespace'] is defined %} {% if Class.attrib['Namespace'] != "None" %} @@ -95,19 +95,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. {{CollectDisplayGroups('Output')}} {{CollectDisplayGroups('Parameter')}} -{# FOR DEBUGGING / DIAGNOSTIC - -// Standalone (No DisplayGroup) {{ global_standaloneTagMap }} -{% for key, value in global_standaloneTagMap.items() %} -// {{key}} : {{value}} -{% endfor %} - -// DisplayGrouped {{ global_displayGroupMap }} -{% for key, value in global_displayGroupMap.items() %} -// {{key}} : {{value}} -{% endfor %} -#} - {# ----------------------------------------------------------------------------------------- #} {% if attribute_Namespace is defined %} @@ -115,33 +102,6 @@ namespace {{attribute_Namespace}} { {% endif %} -{# Standard "In" function } -{{nodemacro.FunctionSignature(attribute_QualifiedName, Class)}} -{ -{%- for parameter in Class.findall('Parameter') -%} -{% if parameter.attrib['Input'] is defined and parameter.attrib['Input'] == "True" %} - -// this->{{parameter.attrib['Name']}} = arg{{loop.index0}}; - -{%- endif -%} -{% endfor %} - -{% set returnNames = [] %} -{% set returnTypes = [] %} -{%- for return in Class.findall('Parameter') -%} -{%- if return.attrib['Output'] is defined and return.attrib['Output'] == "True" -%} -{% if returnTypes.append(return.attrib['Type']) %}{% endif %} -{% if returnNames.append("this->" + return.attrib['Name']) %}{% endif %} -{%- endif -%} -{%- endfor -%} - -{% if returnNames|length() == 1 %} -return {{returnNames[0]}}; -{% elif returnNames|length() > 1 %} - return AZStd::tuple<{{returnTypes|join(", ")}}>({{returnNames|join(", ")}}); -{% endif %} -} -#} {%- set nodeableNodeName = attribute_Name + 'Node' %} {% set list_outputs = [] %} {% for output in Class.iter('Output') %} @@ -156,43 +116,81 @@ return {{returnNames[0]}}; {% for item in Class.iter('Output') %} {% if item.attrib['DisplayGroup'] is defined %}{% set displayGroup = item.attrib['DisplayGroup'] %}{% endif %} {% endfor %} +{% set branches = [] %} +{% for method in Class.findall('Input') %} +{% for branch in method.findall('Branch') %} +{% if branches.append(branch) %}{% endif %} +{% endfor %} +{% endfor %} {# ExecutionOuts #} // ExecutionOuts begin {{ nodemacro.ExecutionOutDefinitions(Class, attribute_QualifiedName)}} +{% if not Class.attrib['ExtendConfigureSlots'] is defined %} size_t {{attribute_QualifiedName}}::GetRequiredOutCount() const { return {{Class.findall('Output')|length + branches|length}}; }{% endif %} // ExecutionOuts end {# Reflect #} + +{% if Class.attrib['ExtendReflectionSerialize'] is defined %} +{% set ExtendReflectionSerialize = "defined" %} +{% set preSerialize = "serializeBuilder" %} +{% set postSerialize = ";" %} +{% else %} +{% set preSerialize = "" %} +{% set postSerialize = "" %} +{% endif %} + +{% if Class.attrib['ExtendReflectionEdit'] is defined %} +{% set ExtendReflectionEdit = "defined" %} +{% set preEdit = "editorBuilder" %} +{% set postEdit = ";" %} +{% else %} +{% set preEdit = "" %} +{% set postEdit = "" %} +{% endif %} + +{% if Class.attrib['ExtendReflectionBehavior'] is defined %} +{% set ExtendReflectionBehavior = "defined" %} +{% set preBehavior = "behaviorBuilder" %} +{% set postBehavior = ";" %} +{% else %} +{% set preBehavior = "" %} +{% set postBehavior = "" %} +{% endif %} + void {{attribute_QualifiedName}}::Reflect(AZ::ReflectContext* context) { using namespace ScriptCanvas; if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) { - serializeContext->Class<{{ attribute_Name }}{% if attribute_Base is defined %}, {{ attribute_Base }}{% endif %}>() +{% if ExtendReflectionSerialize is defined %} auto {{preSerialize}} = {% else %} {% endif %}serializeContext->Class<{{ attribute_Name }}{% if attribute_Base is defined %}, {{ attribute_Base }}{% endif %}>(){{postSerialize}} {% if attribute_EventHandler is defined %} - ->EventHandler<{{ attribute_EventHandler }}>() + {{preSerialize}}->EventHandler<{{ attribute_EventHandler }}>(){{postSerialize}} {% endif %} {# Serialized Properties #} {% for Property in Class.iter('Property') %} {% set property_Name = Property.attrib['Name'] %} - ->Field("{{ property_Name }}", &{{ attribute_Name }}::{{ property_Name | replace(' ','') }}) + {{preSerialize}}->Field("{{ property_Name }}", &{{ attribute_Name }}::{{ property_Name | replace(' ','') }}){{postSerialize}} {% endfor %} ; +{% if ExtendReflectionSerialize is defined %} + ExtendReflectionSerialize(&{{preSerialize}}); +{% endif %} + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) { - editContext->Class<{{ attribute_QualifiedName }}>("{{ attribute_PreferredClassName }}", "{{ attribute_Description }}") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - +{% if ExtendReflectionEdit is defined %} auto {{preEdit}} = {% else %} {% endif %}editContext->Class<{{ attribute_QualifiedName }}>("{{ attribute_PreferredClassName }}", "{{ attribute_Description }}"){{postEdit}} + {{preEdit}}->ClassElement(AZ::Edit::ClassElements::EditorData, ""){{postEdit}} + {{preEdit}}->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly){{postEdit}} {% if attribute_Category is defined %} - ->Attribute(AZ::Edit::Attributes::Category, "{{ attribute_Category }}") + {{preEdit}}->Attribute(AZ::Edit::Attributes::Category, "{{ attribute_Category }}"){{postEdit}} {%- endif %} {% if attribute_Icon is defined %} - ->Attribute(AZ::Edit::Attributes::Icon, "{{ attribute_Icon }}") + {{preEdit}}->Attribute(AZ::Edit::Attributes::Icon, "{{ attribute_Icon }}"){{postEdit}} {%- endif %} {% if attribute_Deprecated is defined %} - ->Attribute(AZ::Edit::Attributes::Deprecated, "{{ attribute_Deprecated }}") + {{preEdit}}->Attribute(AZ::Edit::Attributes::Deprecated, "{{ attribute_Deprecated }}"){{postEdit}} {%- endif %} {% set uihandler = 'AZ::Edit::UIHandlers::Default' %} {% for item in Class.iter('Property') %} @@ -203,29 +201,34 @@ void {{attribute_QualifiedName}}::Reflect(AZ::ReflectContext* context) {% if item.attrib['Description'] is defined %} {% set description = item.attrib['Description'] %} {% endif %} - // {{ item.attrib['Name'] }} - ->DataElement({{ uihandler }}, &{{ attribute_Name }}::{{ item.attrib['Name'] }}, "{{ item.attrib['Name'] }}", "{{ description }}") + // {{ item.attrib['Name'] }} + {{preEdit}}->DataElement({{ uihandler }}, &{{ attribute_Name }}::{{ item.attrib['Name'] }}, "{{ item.attrib['Name'] }}", "{{ description }}"){{postEdit}} {% for EditAttribute in item.iter('EditAttribute') %} - ->Attribute({{ EditAttribute.attrib['Key'] }}, {{ EditAttribute.attrib['Value'] }}) + {{preEdit}}->Attribute({{ EditAttribute.attrib['Key'] }}, {{ EditAttribute.attrib['Value'] }}){{postEdit}} {% endfor %} {% endfor %} ; +{% if ExtendReflectionEdit is defined %} + ExtendReflectionEdit(&{{preEdit}}); +{% endif %} } } // Behavior Context Reflection if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->Class<{{ attribute_Name }}>("{{ attribute_Name }}") - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::List) - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) +{% if ExtendReflectionBehavior is defined %} auto {{preBehavior}} = {% else %} {% endif %}behaviorContext->Class<{{ attribute_Name }}>("{{ attribute_Name }}"){{postBehavior}} + {{preBehavior}}->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::List){{postBehavior}} + {{preBehavior}}->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common){{postBehavior}} {% for inputMethod in Class.iter('Input') %} {% set methodName = inputMethod.attrib['Name'] %} // {{ inputMethod.attrib['Name'] }} - ->Method(Grammar::ToIdentifier("{{ macros.SlotName(methodName) }}").c_str(), &{{ attribute_Name }}::{{ macros.CleanName(methodName) }}) + {{preBehavior}}->Method(Grammar::ToIdentifier("{{ macros.SlotName(methodName) }}").c_str(), &{{ attribute_Name }}::{{ macros.CleanName(methodName) }}){{postBehavior}} {% endfor %} - ; +{% if ExtendReflectionBehavior is defined %} + ExtendReflectionBehavior(&{{preBehavior}}); +{% endif %} } } @@ -253,27 +256,32 @@ Nodes::{{ nodeableNodeName }}::{{ nodeableNodeName }}() {# NodeableNode Reflection #} void Nodes::{{ nodeableNodeName }}::Reflect(AZ::ReflectContext* context) { - {{ attribute_QualifiedName }}::Reflect(context); // Serialization Context Reflection if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) { - serializeContext->Class<{{ nodeableNodeName }}, NodeableNode>() + {%if ExtendReflectionSerialize is defined%}auto {{preSerialize}} = {%endif%}serializeContext->Class<{{ nodeableNodeName }}, NodeableNode>(){{postSerialize}} {% if attribute_Version is defined %} - ->Version({{ attribute_Version }}{% if attribute_VersionConverter is defined %}, &{{ attribute_VersionConverter }}{% endif %}) + {{preSerialize}}->Version({{ attribute_Version }}{% if attribute_VersionConverter is defined %}, &{{ attribute_VersionConverter }}{% endif %}){{postSerialize}} {% else %} - ->Version(0) + {{preSerialize}}->Version(0){{postSerialize}} +{% endif %} + ; +{% if ExtendReflectionSerialize is defined %} + ExtendReflectionSerialize(&{{preSerialize}}); {% endif %} - ; if (AZ::EditContext* editContext = serializeContext->GetEditContext()) { - editContext->Class<{{ nodeableNodeName }}>("{{ attribute_PreferredClassName }}", "{{ attribute_Description }}") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ; + {% if ExtendReflectionEdit is defined %}auto {{preEdit}} = {%endif%}editContext->Class<{{ nodeableNodeName }}>("{{ attribute_PreferredClassName }}", "{{ attribute_Description }}"){{postEdit}} + {{preEdit}}->ClassElement(AZ::Edit::ClassElements::EditorData, ""){{postEdit}} + {{preEdit}}->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly){{postEdit}} + {{preEdit}}->Attribute(AZ::Edit::Attributes::AutoExpand, true){{postEdit}} + ; +{% if ExtendReflectionEdit is defined %} + ExtendReflectionEdit(&{{preEdit}}); +{% endif %} } } } @@ -324,6 +332,7 @@ void Nodes::{{ nodeableNodeName }}::ConfigureVisualExtensions() RegisterExtension(visualExtensions); } {% endfor %} + OnConfigureVisualExtensions(); } {# ConfigureSlots #} @@ -457,6 +466,9 @@ void Nodes::{{ nodeableNodeName }}::ConfigureSlots() {% endfor %} #} +{% if Class.attrib['ExtendConfigureSlots'] is defined %} + ExtendConfigureSlots(ins, outs); +{% endif %} // Generate the execution map m_slotExecutionMap = SlotExecution::Map(AZStd::move(ins), AZStd::move(outs)); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvas_Nodeable_Macros.jinja b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvas_Nodeable_Macros.jinja index addd24f5d3..a7300791e8 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvas_Nodeable_Macros.jinja +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvas_Nodeable_Macros.jinja @@ -349,7 +349,4 @@ void {{qualifiedName}}::Call{{CleanName(outName)}}({{ExecutionOutReturnDefinitio {%- for executionOut in Class.findall('Output') -%} {{ ExecutionOutDefinition(Class, qualifiedName, executionOut, loop.index0 + branches|length) }} {%- endfor %} - -size_t {{qualifiedName}}::GetRequiredOutCount() const { return {{Class.findall('Output')|length + branches|length}}; } - -{% endmacro %} +{% endmacro %} \ No newline at end of file diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Core.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Core.h index 5b1e5eee76..8f3cefa138 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Core.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Core.h @@ -250,7 +250,6 @@ namespace ScriptCanvas }; using ScriptCanvasSettingsRequestBus = AZ::EBus; - } namespace AZStd diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp index 30e55cee49..64c9f2497d 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp @@ -1476,9 +1476,11 @@ namespace ScriptCanvas const void* Datum::GetValueAddress() const { - return m_type.GetType() != Data::eType::BehaviorContextObject - ? AZStd::any_cast(&m_storage) - : (*AZStd::any_cast(&m_storage))->Get(); + return !m_storage.empty() + ? m_type.GetType() != Data::eType::BehaviorContextObject + ? AZStd::any_cast(&m_storage) + : (*AZStd::any_cast(&m_storage))->Get() + : nullptr; } bool Datum::Initialize(const Data::Type& type, eOriginality originality, const void* source, const AZ::Uuid& sourceTypeID) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.h index 781dcb9ed8..be6f3ee37e 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.h @@ -389,7 +389,7 @@ namespace ScriptCanvas bool Datum::Empty() const { - return GetValueAddress() == nullptr; + return m_storage.empty() || GetValueAddress() == nullptr; } template diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.cpp index 4a936c8824..98d5e6b121 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.cpp @@ -3577,12 +3577,12 @@ namespace ScriptCanvas } if (targetSlotType == CombinedSlotType::DataOut - && executionSlot.GetType() == CombinedSlotType::ExecutionIn - && executionInCount > 1) + && executionSlot.GetType() == CombinedSlotType::ExecutionIn + && executionInCount > 1) { if (!executionChildSlot || executionChildSlot->GetType() != CombinedSlotType::ExecutionOut) { - return AZ::Failure(AZStd::string("Data out by ExcutionIn must have child out slot")); + return AZ::Failure(AZStd::string("Data out by ExecutionIn must have child out slot")); } } @@ -3626,6 +3626,11 @@ namespace ScriptCanvas return {}; } + Grammar::MultipleFunctionCallFromSingleSlotInfo Node::GetMultipleFunctionCallFromSingleSlotInfo([[maybe_unused]] const Slot& slot) const + { + return {}; + } + VariableId Node::GetVariableIdRead(const Slot*) const { return {}; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.h index a2d06686e9..42ffaec8da 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.h @@ -715,6 +715,8 @@ namespace ScriptCanvas virtual PropertyFields GetPropertyFields() const; + virtual Grammar::MultipleFunctionCallFromSingleSlotInfo GetMultipleFunctionCallFromSingleSlotInfo(const Slot& slot) const; + virtual VariableId GetVariableIdRead(const Slot*) const; virtual VariableId GetVariableIdWritten(const Slot*) const; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeableNode.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeableNode.h index 0193641d97..c1c9db6f8b 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeableNode.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeableNode.h @@ -73,6 +73,8 @@ namespace ScriptCanvas void ConfigureSlots() override; + virtual void OnConfigureVisualExtensions() {} + AZ::Outcome GetBehaviorContextClass() const; ConstSlotsOutcome GetBehaviorContextOutName(const Slot& inSlot) const; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/PureData.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/PureData.h index 8426e90515..7b74f3dd81 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/PureData.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/PureData.h @@ -46,6 +46,8 @@ namespace ScriptCanvas const AZStd::unordered_map>& GetPropertyNameSlotMap() const; + AZ_INLINE AZ::Outcome GetDependencies() const override { return AZ::Success(DependencyReport{}); } + ~PureData() override; protected: diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp index 732455857e..db45f6bfe3 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp @@ -2249,6 +2249,10 @@ namespace ScriptCanvas } #endif AddAllVariablesPreParse(); + if (!IsErrorFree()) + { + return; + } for (auto& nodeEntity : m_source.m_graphData->m_nodes) { @@ -2270,6 +2274,16 @@ namespace ScriptCanvas { AddError(nullptr, ValidationConstPtr(aznew NullEntityInGraph())); } + + if (!IsErrorFree()) + { + return; + } + } + + if (!IsErrorFree()) + { + return; } ParseAutoConnectedEBusHandlerVariables(); @@ -2638,7 +2652,8 @@ namespace ScriptCanvas AZStd::vector inputVariableIds; AZStd::unordered_map inputVariablesById; - for (auto variable : GetVariables()) + auto& variables = GetVariables(); + for (auto variable : variables) { auto constructionRequirement = ParseConstructionRequirement(variable); @@ -2655,18 +2670,30 @@ namespace ScriptCanvas case VariableConstructionRequirement::InputNodeable: { + if (variable->m_datum.Empty()) + { + AddError(nullptr, aznew Internal::ParseError(AZ::EntityId{}, "Empty nodeable datum in variable, probably due to a problem with azrtti declarations")); + break; + } + // I solemnly swear no harm shall come to the nodeable const Nodeable* nodeableSource = reinterpret_cast(variable->m_datum.GetAsDanger()); - AZ_Assert(nodeableSource != nullptr, "the must be a raw nodeable held by this pointer"); - AZ_Assert(azrtti_typeid(nodeableSource) != azrtti_typeid(), "type problem with nodeable"); + + if (!nodeableSource) + { + AddError(nullptr, aznew Internal::ParseError(AZ::EntityId{}, "No raw nodeable held by variable")); + break; + } + nodeablesById.push_back({ variable->m_nodeableNodeId, const_cast(nodeableSource) }); } break; case VariableConstructionRequirement::InputVariable: { - inputVariableIds.push_back(variable->m_sourceVariableId); - inputVariablesById.insert({ variable->m_sourceVariableId, variable }); + auto variableID = variable->m_sourceVariableId.IsValid() ? variable->m_sourceVariableId : VariableId::MakeVariableId(); + inputVariableIds.push_back(variableID); + inputVariablesById.insert({ variableID, variable }); // sort revealed a datum copy issue: type is not preserved, workaround below // m_runtimeInputs.m_variables.emplace_back(variable->m_sourceVariableId, variable->m_datum); } @@ -4310,6 +4337,7 @@ namespace ScriptCanvas { if (auto variable = FindVariable(execution->GetNodeId())) { + execution->MarkInputHasThisPointer(); execution->AddInput({ nullptr, variable, DebugDataSource::FromInternal() }); } else @@ -4327,6 +4355,7 @@ namespace ScriptCanvas { auto variable = AZStd::make_shared(); variable->m_datum = Datum(eventHandling->m_handlerName); + execution->MarkInputHasThisPointer(); execution->AddInput({ nullptr, variable, DebugDataSource::FromInternal() }); } else @@ -4338,6 +4367,7 @@ namespace ScriptCanvas { if (auto variable = FindVariable(execution->GetNodeId())) { + execution->MarkInputHasThisPointer(); execution->AddInput({ nullptr, variable, DebugDataSource::FromInternal() }); } else @@ -4367,12 +4397,159 @@ namespace ScriptCanvas void AbstractCodeModel::ParseMultiExecutionPost(ExecutionTreePtr execution) { ParsePropertyExtractionsPost(execution); + ParseMultipleFunctionCallPost(execution); } void AbstractCodeModel::ParseMultiExecutionPre(ExecutionTreePtr execution) { ParsePropertyExtractionsPre(execution); - } + } + + void AbstractCodeModel::ParseMultipleFunctionCallPost(ExecutionTreePtr execution) + { + auto& id = execution->GetId(); + MultipleFunctionCallFromSingleSlotInfo info = id.m_node->GetMultipleFunctionCallFromSingleSlotInfo(*id.m_slot); + + if (info.functionCalls.empty()) + { + return; + } + + auto parent = execution->ModParent(); + + if (!parent) + { + AddError(execution, aznew Internal::ParseError(id.m_node->GetEntityId(), "Null parent in MultipleFunctionCall")); + return; + } + + size_t indexInParentCall = parent->FindChildIndex(execution); + if (indexInParentCall >= parent->GetChildrenCount()) + { + AddError(execution, aznew Internal::ParseError(id.m_node->GetEntityId(), ParseErrors::MultipleFunctionCallFromSingleSlotNoChildren)); + return; + } + + ExecutionChild* executionChildInParent = &parent->ModChild(indexInParentCall); + + const size_t executionInputCount = execution->GetInputCount(); + const size_t thisInputOffset = execution->InputHasThisPointer() ? 1 : 0; + + // the original index has ALL the input from the slots on the node + // create multiple calls with separate function call nodes, but ONLY take the inputs required + // as indicated by the function call info + + AZStd::unordered_set usedSlots; + bool variadicIsFound = false; + + auto createChild = [&](auto parentCall, ExecutionChild* childInParent, auto& functionCallInfo) + { + auto child = CreateChild(parentCall, id.m_node, id.m_slot); + child->SetSymbol(Symbol::FunctionCall); + child->SetName(functionCallInfo.functionName); + child->SetNameLexicalScope(functionCallInfo.lexicalScope); + childInParent->m_execution = child; + return child; + }; + + auto addThisInput = [&](auto functionCall) + { + if (thisInputOffset != 0) + { + if (executionInputCount == 0) + { + AddError(execution, aznew Internal::ParseError(id.m_node->GetEntityId(), ParseErrors::MultipleFunctionCallFromSingleSlotNotEnoughInputForThis)); + return; + } + + const ExecutionInput& input = execution->GetInput(0); + usedSlots.insert(input.m_slot); + functionCall->AddInput(input); + } + }; + + auto addSlotInput = [&](auto functionCall, size_t inputIndex) + { + if (inputIndex >= executionInputCount) + { + AddError(execution, aznew Internal::ParseError(id.m_node->GetEntityId(), ParseErrors::MultipleFunctionCallFromSingleSlotNotEnoughInput)); + return; + } + + const ExecutionInput& input = execution->GetInput(inputIndex); + + if (usedSlots.contains(input.m_slot)) + { + AddError(execution, aznew Internal::ParseError(id.m_node->GetEntityId(), ParseErrors::MultipleFunctionCallFromSingleSlotNotEnoughInput)); + return; + } + + usedSlots.insert(input.m_slot); + + if (input.m_value->m_source == execution) + { + input.m_value->m_source = functionCall; + } + + functionCall->AddInput(input); + }; + + auto addCall = [&](auto& functionCallInfo, auto childInParent, size_t startingIndex, size_t sentinel, size_t variadicOffset = 0) + { + auto child = createChild(parent, childInParent, functionCallInfo); + addThisInput(child); + + for (size_t index = startingIndex; index < sentinel; ++index) + { + const size_t inputIndex = index + thisInputOffset + variadicOffset; + addSlotInput(child, inputIndex); + } + + child->AddChild({}); + childInParent = &child->ModChild(0); + return AZStd::make_pair(childInParent, child); + }; + + // loop through each call... + for (auto& functionCallInfo : info.functionCalls) + { + // ...first add any pre-variadic calls, using the starting index and the number of args, since they could come in any order, not input slot order... + if (!functionCallInfo.isVariadic) + { + AZStd::pair childInParentAndParent = addCall(functionCallInfo, executionChildInParent, functionCallInfo.startingIndex, functionCallInfo.startingIndex + functionCallInfo.numArguments); + executionChildInParent = childInParentAndParent.first; + parent = childInParentAndParent.second; + } + else + { + // ...then add only one variadic call if there is one... + if (variadicIsFound) + { + AddError(execution, aznew Internal::ParseError(id.m_node->GetEntityId(), ParseErrors::MultipleFunctionCallFromSingleSlotMultipleVariadic)); + return; + } + + variadicIsFound = true; + const size_t sentinel = executionInputCount == 0 ? 0 : executionInputCount - thisInputOffset; + // ... by looping through the remaining slots, striding by functionCallInfo.numArguments, making repeated calls to the function + for (size_t slotInputIndex = functionCallInfo.startingIndex; slotInputIndex < sentinel; slotInputIndex += functionCallInfo.numArguments) + { + AZStd::pair childInParentAndParent = addCall(functionCallInfo, executionChildInParent, 0, functionCallInfo.numArguments, slotInputIndex); + executionChildInParent = childInParentAndParent.first; + parent = childInParentAndParent.second; + } + } + } + + if (info.errorOnUnusedSlot && usedSlots.size() != executionInputCount) + { + AddError(execution, aznew Internal::ParseError(id.m_node->GetEntityId(), ParseErrors::MultipleFunctionCallFromSingleSlotUnused)); + } + + // parent now refers to the last child call created + parent->SwapChildren(execution); + execution->Clear(); + } void AbstractCodeModel::ParseNodelingVariables(const Node& node, NodelingType nodelingType) { @@ -5146,6 +5323,6 @@ namespace ScriptCanvas return type == Data::eType::BehaviorContextObject; } - } + } -} +} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.h index f1ad7b986b..8b8be27fab 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.h @@ -387,6 +387,8 @@ namespace ScriptCanvas void ParseMultiExecutionPre(ExecutionTreePtr execution); + void ParseMultipleFunctionCallPost(ExecutionTreePtr execution); + void ParseNodelingVariables(const Node& node, NodelingType nodelingType); void ParseOperatorArithmetic(ExecutionTreePtr execution); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/ParsingUtilities.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/ParsingUtilities.cpp index e16a3bc815..131209a521 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/ParsingUtilities.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/ParsingUtilities.cpp @@ -1132,14 +1132,14 @@ namespace ScriptCanvas } else if (variable->m_isExposedToConstruction) { - if (variable->m_sourceVariableId.IsValid()) - { - return VariableConstructionRequirement::InputVariable; - } - else if (variable->m_nodeableNodeId.IsValid()) + if (variable->m_nodeableNodeId.IsValid()) { return VariableConstructionRequirement::InputNodeable; } + else if (variable->m_sourceVariableId.IsValid()) + { + return VariableConstructionRequirement::InputVariable; + } else { AZ_Assert(false, "A member variable in the model has no valid id"); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/Primitives.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/Primitives.h index ab047fb580..d7e4fa0f72 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/Primitives.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/Primitives.h @@ -164,6 +164,34 @@ namespace ScriptCanvas virtual void PostParseExecutionTreeBody(AbstractCodeModel& /*model*/, ExecutionTreePtr /*execution*/) {} }; + // for now, no return values supported + struct MultipleFunctionCallFromSingleSlotEntry + { + AZ_TYPE_INFO(MultipleFunctionCallFromSingleSlotEntry, "{360A23A3-C490-4047-B71E-64E290E441D3}"); + AZ_CLASS_ALLOCATOR(MultipleFunctionCallFromSingleSlotEntry, AZ::SystemAllocator, 0); + + bool isVariadic = false; + AZStd::string functionName; + LexicalScope lexicalScope; + size_t numArguments = 0; // stride in case isVariadic == true + size_t startingIndex = 0; // the index of the slot order + }; + + // for now, no return values supported + struct MultipleFunctionCallFromSingleSlotInfo + { + AZ_TYPE_INFO(MultipleFunctionCallFromSingleSlotInfo, "{DF51F08A-8B28-4851-9888-9AB7CC0B90D2}"); + AZ_CLASS_ALLOCATOR(MultipleFunctionCallFromSingleSlotInfo, AZ::SystemAllocator, 0); + + // this could likely be implemented, but needs care to duplicate input that the execution-slot created + // bool errorOnReusedSlot = false; + + bool errorOnUnusedSlot = false; + + // calls are executed in the order they arrive in the vector + AZStd::vector functionCalls; + }; + struct NodeableParse : public AZStd::enable_shared_from_this { diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/PrimitivesExecution.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/PrimitivesExecution.cpp index ed61d7e838..66f609768d 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/PrimitivesExecution.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/PrimitivesExecution.cpp @@ -313,6 +313,11 @@ namespace ScriptCanvas return !m_returnValues.empty(); } + bool ExecutionTree::InputHasThisPointer() const + { + return m_inputHasThisPointer; + } + bool ExecutionTree::IsInfiniteLoopDetectionPoint() const { return m_isInfiniteLoopDetectionPoint; @@ -377,6 +382,11 @@ namespace ScriptCanvas m_isInfiniteLoopDetectionPoint = true; } + void ExecutionTree::MarkInputHasThisPointer() + { + m_inputHasThisPointer = true; + } + void ExecutionTree::MarkInputOutputPreprocessed() { m_isInputOutputPreprocessed = true; @@ -587,6 +597,32 @@ namespace ScriptCanvas m_symbol = val; } - } + void ExecutionTree::SwapChildren(ExecutionTreePtr execution) + { + if (execution) + { + m_children.swap(execution->m_children); + for (auto& child : m_children) + { + if (child.m_execution) + { + child.m_execution->SetParent(shared_from_this()); + } + } + + for (auto& orphan : execution->m_children) + { + if (orphan.m_execution) + { + orphan.m_execution->SetParent(execution); + } + } + } + else + { + ClearChildren(); + } + } + } } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/PrimitivesExecution.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/PrimitivesExecution.h index 3d0d75b313..17b86c8da4 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/PrimitivesExecution.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/PrimitivesExecution.h @@ -190,6 +190,8 @@ namespace ScriptCanvas bool HasReturnValues() const; + bool InputHasThisPointer() const; + bool IsInfiniteLoopDetectionPoint() const; void InsertChild(size_t index, const ExecutionChild& child); @@ -208,6 +210,8 @@ namespace ScriptCanvas void MarkInfiniteLoopDetectionPoint(); + void MarkInputHasThisPointer(); + void MarkInputOutputPreprocessed(); void MarkInternalOut(); @@ -262,6 +266,8 @@ namespace ScriptCanvas void SetSymbol(Symbol val); + void SwapChildren(ExecutionTreePtr execution); + private: // the (possible) slot(s) through which execution exited, along with associated output AZStd::vector m_children; @@ -275,6 +281,8 @@ namespace ScriptCanvas bool m_isInfiniteLoopDetectionPoint = false; + bool m_inputHasThisPointer = false; + bool m_isInputOutputPreprocessed = false; bool m_isInternalOut = false; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Results/ErrorText.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Results/ErrorText.h index def4fa7761..68c6a8442a 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Results/ErrorText.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Results/ErrorText.h @@ -57,6 +57,12 @@ namespace ScriptCanvas constexpr const char* MissingVariableForEBusHandlerAddress = "missing variable for ebus handler address"; constexpr const char* MissingVariableForEBusHandlerAddressConnected = "missing variable for ebus handler address"; constexpr const char* MultipleExecutionOutConnections = "This node has multiple, unordered execution Out connections"; + constexpr const char* MultipleFunctionCallFromSingleSlotMultipleVariadic = "Only one variadic call (the last one) is supported in the multi-call per single slot."; + constexpr const char* MultipleFunctionCallFromSingleSlotNoChildren = "Node missing from parent children."; + constexpr const char* MultipleFunctionCallFromSingleSlotNotEnoughInput = "Not enough input to support multi call input information."; + constexpr const char* MultipleFunctionCallFromSingleSlotNotEnoughInputForThis = "Node doesn't have enough input for a parsed this pointer."; + constexpr const char* MultipleFunctionCallFromSingleSlotReused = "Multiple function slot reused an input slot"; + constexpr const char* MultipleFunctionCallFromSingleSlotUnused = "Multiple function slot left an input slot unused."; constexpr const char* MultipleSimulaneousInputValues = "Multiple values routed to the same single input with no way to discern which to take."; constexpr const char* MultipleStartNodes = "Multiple Start nodes in a single graph. Only one is allowed."; constexpr const char* NoChildrenAfterRoot = "No children after parsing function root"; diff --git a/Gems/ScriptCanvasTesting/Assets/ScriptCanvas/UnitTests/LY_SC_UnitTest_RunAllTransformNodes.scriptcanvas b/Gems/ScriptCanvasTesting/Assets/ScriptCanvas/UnitTests/LY_SC_UnitTest_RunAllTransformNodes.scriptcanvas index 45b24bad8d..c3b3599325 100644 --- a/Gems/ScriptCanvasTesting/Assets/ScriptCanvas/UnitTests/LY_SC_UnitTest_RunAllTransformNodes.scriptcanvas +++ b/Gems/ScriptCanvasTesting/Assets/ScriptCanvas/UnitTests/LY_SC_UnitTest_RunAllTransformNodes.scriptcanvas @@ -3,34 +3,34 @@ - + - + - + - + - + - + - + @@ -62,12 +62,13 @@ + - + @@ -99,12 +100,13 @@ + - + @@ -141,12 +143,13 @@ + - + @@ -178,6 +181,7 @@ + @@ -189,7 +193,7 @@ - + @@ -199,26 +203,26 @@ - + - + - + - + - + - + @@ -250,12 +254,13 @@ + - + @@ -287,12 +292,13 @@ + - + @@ -329,12 +335,646 @@ + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -371,12 +1011,13 @@ + - + @@ -408,6 +1049,7 @@ + @@ -419,7 +1061,7 @@ - + @@ -431,7 +1073,7 @@ - + @@ -441,26 +1083,26 @@ - + - + - + - + - + - + @@ -492,12 +1134,13 @@ + - + @@ -529,484 +1172,13 @@ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -1043,12 +1215,13 @@ + - + @@ -1080,21 +1253,10 @@ + - - - - - - - - - - - - @@ -1103,7 +1265,7 @@ - + @@ -1113,26 +1275,26 @@ - + - + - + - + - + - + @@ -1164,12 +1326,13 @@ + - + @@ -1201,200 +1364,13 @@ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -1431,12 +1407,56 @@ + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1446,10 +1466,10 @@ - + - + @@ -1468,6 +1488,7 @@ + @@ -1479,9 +1500,21 @@ - + - + + + + + + + + + + + + + @@ -1489,26 +1522,26 @@ - + - + - + - + - + - + @@ -1540,12 +1573,338 @@ + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1577,12 +1936,205 @@ + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1619,12 +2171,13 @@ + - + @@ -1639,7 +2192,7 @@ - + @@ -1661,12 +2214,13 @@ + - + @@ -1676,10 +2230,10 @@ - + - + @@ -1698,6 +2252,7 @@ + @@ -1709,19 +2264,19 @@ - + - + - + @@ -1731,26 +2286,26 @@ - + - + - + - + - + - + @@ -1782,12 +2337,13 @@ + - + @@ -1819,12 +2375,13 @@ + - + @@ -1839,7 +2396,7 @@ - + @@ -1861,12 +2418,56 @@ + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1898,6 +2499,7 @@ + @@ -1909,36 +2511,107 @@ - + + + + + + + + + + + + + - + - + - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1970,12 +2643,13 @@ + - + @@ -2007,12 +2681,13 @@ + - + @@ -2049,12 +2724,205 @@ + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2091,12 +2959,13 @@ + - + @@ -2128,6 +2997,7 @@ + @@ -2139,7 +3009,7 @@ - + @@ -2151,7 +3021,7 @@ - + @@ -2161,26 +3031,26 @@ - + - + - + - + - + - + @@ -2212,12 +3082,13 @@ + - + @@ -2249,12 +3120,13 @@ + - + @@ -2291,12 +3163,56 @@ + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2328,6 +3244,7 @@ + @@ -2339,36 +3256,1196 @@ - + + + + + + + + + + + + + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + @@ -2405,12 +4482,13 @@ + - + @@ -2447,12 +4525,13 @@ + - + @@ -2484,12 +4563,13 @@ + - + @@ -2521,6 +4601,7 @@ + @@ -2565,1709 +4646,26 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + - + @@ -4299,12 +4697,13 @@ + - + @@ -4336,12 +4735,13 @@ + - + @@ -4378,12 +4778,13 @@ + - + @@ -4420,12 +4821,13 @@ + - + @@ -4457,6 +4859,7 @@ + @@ -4480,7 +4883,7 @@ - + @@ -4490,26 +4893,26 @@ - + - + - + - + - + - + @@ -4541,12 +4944,13 @@ + - + @@ -4578,12 +4982,13 @@ + - + @@ -4620,850 +5025,13 @@ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -5495,194 +5063,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -5694,9 +5075,9 @@ - + - + @@ -5704,703 +5085,35 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + - + - + - + - + @@ -6410,28 +5123,28 @@ - + - + - + - + - + - + - + @@ -6441,28 +5154,28 @@ - + - + - + - + - + - + - + @@ -6472,28 +5185,28 @@ - + - + - + - + - + - + - + @@ -6503,28 +5216,28 @@ - + - + - + - + - + - + - + @@ -6534,28 +5247,28 @@ - + - + - + - + - + - + - + @@ -6565,28 +5278,28 @@ - + - + - + - + - + - + - + @@ -6596,28 +5309,28 @@ - + - + - + - + - + - + - + @@ -6627,28 +5340,28 @@ - + - + - + - + - + - + - + @@ -6658,28 +5371,28 @@ - + - + - + - + - + - + - + @@ -6689,28 +5402,28 @@ - + - + - + - + - + - + @@ -6720,28 +5433,28 @@ - + - + - + - + - + - + - + @@ -6751,28 +5464,307 @@ - + - + - + - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -6788,7 +5780,7 @@ - + @@ -6796,7 +5788,7 @@ - + @@ -6804,7 +5796,7 @@ - + @@ -6822,15 +5814,15 @@ - - - + + + - - - + + + @@ -6838,7 +5830,7 @@ - + @@ -6846,7 +5838,7 @@ - + @@ -6863,46 +5855,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -6911,18 +5867,12 @@ - - - - - - - + @@ -6930,637 +5880,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -7586,7 +5906,7 @@ - + @@ -7594,7 +5914,7 @@ - + @@ -7602,7 +5922,595 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -7620,15 +6528,15 @@ - - - + + + - - - + + + @@ -7636,7 +6544,7 @@ - + @@ -7644,7 +6552,7 @@ - + @@ -7661,46 +6569,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -7709,18 +6581,12 @@ - - - - - - - + @@ -7728,7 +6594,7 @@ - + @@ -7746,15 +6612,15 @@ - - - + + + - - - + + + @@ -7762,7 +6628,7 @@ - + @@ -7771,9 +6637,9 @@ - - - + + + @@ -7783,7 +6649,7 @@ - + @@ -7791,49 +6657,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -7851,15 +6675,15 @@ - - - + + + - - - + + + @@ -7867,7 +6691,7 @@ - + @@ -7875,7 +6699,49 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -7893,15 +6759,15 @@ - - - + + + - - - + + + @@ -7915,60 +6781,12 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -7980,7 +6798,35 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -7988,25 +6834,33 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + @@ -8014,7 +6868,7 @@ - + From dbeee91e7bc8d654e41fb420132036d94513a6b5 Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Thu, 3 Jun 2021 15:14:19 -0500 Subject: [PATCH 482/811] SPEC-7008: Setting up LargeWorlds main tests to be skipped in Debug builds --- .../dyn_veg/test_DynamicSliceInstanceSpawner.py | 6 ++++++ .../largeworlds/dyn_veg/test_EmptyInstanceSpawner.py | 6 ++++++ .../landscape_canvas/test_GraphComponentSync.py | 11 +++++++++++ 3 files changed, 23 insertions(+) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py index ead1e8779c..9235b302b8 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py @@ -16,6 +16,7 @@ import logging # Bail on the test if ly_test_tools doesn't exist. pytest.importorskip('ly_test_tools') import ly_test_tools.environment.file_system as file_system +import ly_test_tools._internal.pytest_plugin as internal_plugin import editor_python_test_tools.hydra_test_utils as hydra from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole @@ -46,6 +47,11 @@ class TestDynamicSliceInstanceSpawner(object): @pytest.mark.parametrize("launcher_platform", ['windows_editor']) def test_DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks(self, request, editor, level, workspace, project, launcher_platform): + + # Skip test if running against Debug build + if "debug" in internal_plugin.build_directory: + pytest.skip("Does not execute against debug builds.") + # Ensure temp level does not already exist file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py index ca71cd2137..83263c614a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py @@ -16,6 +16,7 @@ import logging # Bail on the test if ly_test_tools doesn't exist. pytest.importorskip('ly_test_tools') import ly_test_tools.environment.file_system as file_system +import ly_test_tools._internal.pytest_plugin as internal_plugin import editor_python_test_tools.hydra_test_utils as hydra logger = logging.getLogger(__name__) @@ -40,6 +41,11 @@ class TestEmptyInstanceSpawner(object): @pytest.mark.SUITE_main @pytest.mark.dynveg_area def test_EmptyInstanceSpawner_EmptySpawnerWorks(self, request, editor, level, launcher_platform): + + # Skip test if running against Debug build + if "debug" in internal_plugin.build_directory: + pytest.skip("Does not execute against debug builds.") + cfg_args = [level] expected_lines = [ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py index 855764fa6f..943d0cb985 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py @@ -23,6 +23,7 @@ import pytest # Bail on the test if ly_test_tools doesn't exist. pytest.importorskip('ly_test_tools') import ly_test_tools.environment.file_system as file_system +import ly_test_tools._internal.pytest_plugin as internal_plugin import editor_python_test_tools.hydra_test_utils as hydra test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') @@ -46,6 +47,11 @@ class TestGraphComponentSync(object): @pytest.mark.BAT @pytest.mark.SUITE_main def test_LandscapeCanvas_SlotConnections_UpdateComponentReferences(self, request, editor, level, launcher_platform): + + # Skip test if running against Debug build + if "debug" in internal_plugin.build_directory: + pytest.skip("Does not execute against debug builds.") + cfg_args = [level] expected_lines = [ @@ -122,6 +128,11 @@ class TestGraphComponentSync(object): """ Verifies a Gradient Mixer can be setup in Landscape Canvas and all references are property set. """ + + # Skip test if running against Debug build + if "debug" in internal_plugin.build_directory: + pytest.skip("Does not execute against debug builds.") + cfg_args = [level] expected_lines = [ From ed0fab894b6cad4d8e151c4c109bf69307b8a285 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Thu, 3 Jun 2021 13:30:28 -0700 Subject: [PATCH 483/811] Added DiffuseGlobalIllumination level component --- .../DiffuseGlobalIlluminationComponent.cpp | 44 +++++++++ .../DiffuseGlobalIlluminationComponent.h | 38 ++++++++ ...ffuseGlobalIlluminationComponentConfig.cpp | 32 +++++++ ...DiffuseGlobalIlluminationComponentConfig.h | 43 +++++++++ ...fuseGlobalIlluminationComponentConstants.h | 23 +++++ ...eGlobalIlluminationComponentController.cpp | 92 +++++++++++++++++++ ...useGlobalIlluminationComponentController.h | 55 +++++++++++ .../DiffuseProbeGridComponent.cpp | 2 +- .../DiffuseProbeGridComponent.h | 4 +- .../DiffuseProbeGridComponentConstants.h | 0 .../DiffuseProbeGridComponentController.cpp | 4 +- .../DiffuseProbeGridComponentController.h | 2 +- ...itorDiffuseGlobalIlluminationComponent.cpp | 82 +++++++++++++++++ ...EditorDiffuseGlobalIlluminationComponent.h | 40 ++++++++ .../EditorDiffuseProbeGridComponent.cpp | 2 +- .../EditorDiffuseProbeGridComponent.h | 4 +- .../CommonFeatures/Code/Source/Module.cpp | 8 +- ...egration_commonfeatures_editor_files.cmake | 6 +- ...omlyintegration_commonfeatures_files.cmake | 14 ++- 19 files changed, 478 insertions(+), 17 deletions(-) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponent.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponent.h create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.h create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConstants.h create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.h rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridComponent.cpp (96%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridComponent.h (90%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridComponentConstants.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridComponentController.cpp (99%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridComponentController.h (98%) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseGlobalIlluminationComponent.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseGlobalIlluminationComponent.h rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/EditorDiffuseProbeGridComponent.cpp (99%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/EditorDiffuseProbeGridComponent.h (97%) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponent.cpp new file mode 100644 index 0000000000..b14bcf28b8 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponent.cpp @@ -0,0 +1,44 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include + +namespace AZ +{ + namespace Render + { + + DiffuseGlobalIlluminationComponent::DiffuseGlobalIlluminationComponent(const DiffuseGlobalIlluminationComponentConfig& config) + : BaseClass(config) + { + } + + void DiffuseGlobalIlluminationComponent::Reflect(AZ::ReflectContext* context) + { + BaseClass::Reflect(context); + + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class(); + } + + if (auto behaviorContext = azrtti_cast(context)) + { + behaviorContext->ConstantProperty("DiffuseGlobalIlluminationComponentTypeId", BehaviorConstant(Uuid(DiffuseGlobalIlluminationComponentTypeId))) + ->Attribute(AZ::Script::Attributes::Module, "render") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common); + } + } + + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponent.h new file mode 100644 index 0000000000..a54e5868cd --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponent.h @@ -0,0 +1,38 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + class DiffuseGlobalIlluminationComponent final + : public AzFramework::Components::ComponentAdapter + { + public: + using BaseClass = AzFramework::Components::ComponentAdapter; + AZ_COMPONENT(AZ::Render::DiffuseGlobalIlluminationComponent, DiffuseGlobalIlluminationComponentTypeId , BaseClass); + + DiffuseGlobalIlluminationComponent() = default; + DiffuseGlobalIlluminationComponent(const DiffuseGlobalIlluminationComponentConfig& config); + + static void Reflect(AZ::ReflectContext* context); + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.cpp new file mode 100644 index 0000000000..406da9db2e --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.cpp @@ -0,0 +1,32 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include + +namespace AZ +{ + namespace Render + { + void DiffuseGlobalIlluminationComponentConfig::Reflect(ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("QualityLevel", &DiffuseGlobalIlluminationComponentConfig::m_qualityLevel) + ; + } + } + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.h new file mode 100644 index 0000000000..23296967a5 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.h @@ -0,0 +1,43 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include + +namespace AZ +{ + namespace Render + { + enum class DiffuseGlobalIlluminationQualityLevel : uint32_t + { + Low, + Medium, + High, + + Count + }; + + class DiffuseGlobalIlluminationComponentConfig final + : public ComponentConfig + { + public: + AZ_RTTI(DiffuseGlobalIlluminationComponentConfig, "{0D0835D6-6094-4EF8-BEAC-5FF8A4E4C119}", ComponentConfig); + AZ_CLASS_ALLOCATOR(DiffuseGlobalIlluminationComponentConfig, SystemAllocator, 0); + + static void Reflect(ReflectContext* context); + + DiffuseGlobalIlluminationQualityLevel m_qualityLevel; + }; + } +} diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConstants.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConstants.h new file mode 100644 index 0000000000..e89aa65584 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConstants.h @@ -0,0 +1,23 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +namespace AZ +{ + namespace Render + { + static constexpr const char* const DiffuseGlobalIlluminationComponentTypeId = "{D51F8033-EF0D-4A13-BED3-5B193555B8D2}"; + static constexpr const char* const EditorDiffuseGlobalIlluminationComponentTypeId = "{169378DD-4052-4A60-BD63-90B02CFA69C1}"; + + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.cpp new file mode 100644 index 0000000000..4c7f37bd4a --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.cpp @@ -0,0 +1,92 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include + +//#include + +#include +//#include + +namespace AZ +{ + namespace Render + { + void DiffuseGlobalIlluminationComponentController::Reflect(ReflectContext* context) + { + DiffuseGlobalIlluminationComponentConfig::Reflect(context); + + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Configuration", &DiffuseGlobalIlluminationComponentController::m_configuration); + } + } + + void DiffuseGlobalIlluminationComponentController::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC("DiffuseGlobalIlluminationService", 0x11b9cbe1)); + } + + void DiffuseGlobalIlluminationComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC("DiffuseGlobalIlluminationService", 0x11b9cbe1)); + } + + void DiffuseGlobalIlluminationComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + AZ_UNUSED(required); + } + + DiffuseGlobalIlluminationComponentController::DiffuseGlobalIlluminationComponentController(const DiffuseGlobalIlluminationComponentConfig& config) + : m_configuration(config) + { + } + + void DiffuseGlobalIlluminationComponentController::Activate(EntityId entityId) + { + m_entityId = entityId; + } + + void DiffuseGlobalIlluminationComponentController::Deactivate() + { + //m_postProcessInterface = nullptr; + m_entityId.SetInvalid(); + } + + void DiffuseGlobalIlluminationComponentController::SetConfiguration(const DiffuseGlobalIlluminationComponentConfig& config) + { + m_configuration = config; + OnConfigChanged(); + } + + const DiffuseGlobalIlluminationComponentConfig& DiffuseGlobalIlluminationComponentController::GetConfiguration() const + { + return m_configuration; + } + + void DiffuseGlobalIlluminationComponentController::OnConfigChanged() + { + // Register the configuration with the AcesDisplayMapperFeatureProcessor for this scene. + //const AZ::RPI::Scene* scene = AZ::RPI::RPISystemInterface::Get()->GetDefaultScene().get(); + //DisplayMapperFeatureProcessorInterface* fp = scene->GetFeatureProcessor(); + //DisplayMapperConfigurationDescriptor desc; + //desc.m_operationType = m_configuration.m_displayMapperOperation; + //desc.m_ldrGradingLutEnabled = m_configuration.m_ldrColorGradingLutEnabled; + //desc.m_ldrColorGradingLut = m_configuration.m_ldrColorGradingLut; + //desc.m_acesParameterOverrides = m_configuration.m_acesParameterOverrides; + //fp->RegisterDisplayMapperConfiguration(desc); + } + + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.h new file mode 100644 index 0000000000..8700e1ffb5 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.h @@ -0,0 +1,55 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include + +#include + +//#include +//#include + +namespace AZ +{ + namespace Render + { + class DiffuseGlobalIlluminationComponentController final + { + public: + friend class EditorDiffuseGlobalIlluminationComponent; + + AZ_TYPE_INFO(AZ::Render::DiffuseGlobalIlluminationComponentController, "{7DE7D2A0-2526-447C-A11F-C31EE1332C26}"); + static void Reflect(AZ::ReflectContext* context); + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + + DiffuseGlobalIlluminationComponentController() = default; + DiffuseGlobalIlluminationComponentController(const DiffuseGlobalIlluminationComponentConfig& config); + + void Activate(EntityId entityId); + void Deactivate(); + void SetConfiguration(const DiffuseGlobalIlluminationComponentConfig& config); + const DiffuseGlobalIlluminationComponentConfig& GetConfiguration() const; + + private: + AZ_DISABLE_COPY(DiffuseGlobalIlluminationComponentController); + + void OnConfigChanged(); + + DiffuseGlobalIlluminationComponentConfig m_configuration; + EntityId m_entityId; + }; + } +} diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponent.cpp similarity index 96% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponent.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponent.cpp index 509cbb86e6..b042f594c6 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponent.cpp @@ -10,7 +10,7 @@ * */ -#include +#include namespace AZ { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponent.h similarity index 90% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponent.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponent.h index 964ce157bd..b77dceefac 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponent.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentConstants.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentConstants.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentConstants.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentConstants.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.cpp similarity index 99% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.cpp index 5fb835de15..f5ac36e7f6 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.cpp @@ -10,8 +10,8 @@ * */ -#include -#include +#include +#include #include #include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.h similarity index 98% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.h index 4122a07ba2..ef606d2170 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.h @@ -18,7 +18,7 @@ #include #include #include -#include +#include namespace AZ { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseGlobalIlluminationComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseGlobalIlluminationComponent.cpp new file mode 100644 index 0000000000..bdb5686e89 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseGlobalIlluminationComponent.cpp @@ -0,0 +1,82 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +//#include "Atom/Feature/ACES/AcesDisplayMapperFeatureProcessor.h" + +#include +#include + +namespace AZ +{ + namespace Render + { + void EditorDiffuseGlobalIlluminationComponent::Reflect(AZ::ReflectContext* context) + { + BaseClass::Reflect(context); + + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1); + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class( + "Diffuse Global Illumination", "Diffuse Global Illumination configuration") + ->ClassElement(Edit::ClassElements::EditorData, "") + ->Attribute(Edit::Attributes::Category, "Atom") + ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Component_Placeholder.svg") + ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Component_Placeholder.png") + ->Attribute(Edit::Attributes::AppearsInAddComponentMenu, AZStd::vector({ AZ_CRC("Level", 0x9aeacc13), AZ_CRC("Game", 0x232b318c) })) + ->Attribute(Edit::Attributes::AutoExpand, true) + ->Attribute(Edit::Attributes::HelpPageURL, "https://") + ; + + editContext->Class( + "ToneMapperComponentControl", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Default, &DiffuseGlobalIlluminationComponentController::m_configuration, "Configuration", "") + ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) + ; + + editContext->Class("DiffuseGlobalIlluminationComponentConfig", "") + ->ClassElement(Edit::ClassElements::EditorData, "") + ->DataElement(Edit::UIHandlers::ComboBox, &DiffuseGlobalIlluminationComponentConfig::m_qualityLevel, "Quality Level", "Quality Level") + ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + ->EnumAttribute(DiffuseGlobalIlluminationQualityLevel::Low, "Low") + ->EnumAttribute(DiffuseGlobalIlluminationQualityLevel::Medium, "Medium") + ->EnumAttribute(DiffuseGlobalIlluminationQualityLevel::High, "High") + ; + } + } + + if (auto behaviorContext = azrtti_cast(context)) + { + behaviorContext->ConstantProperty("EditorDiffuseGlobalIlluminationComponentTypeId", BehaviorConstant(Uuid(EditorDiffuseGlobalIlluminationComponentTypeId))) + ->Attribute(AZ::Script::Attributes::Module, "render") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation); + } + } + + EditorDiffuseGlobalIlluminationComponent::EditorDiffuseGlobalIlluminationComponent(const DiffuseGlobalIlluminationComponentConfig& config) + : BaseClass(config) + { + } + + u32 EditorDiffuseGlobalIlluminationComponent::OnConfigurationChanged() + { + m_controller.OnConfigChanged(); + return Edit::PropertyRefreshLevels::AttributesAndValues; + } + } +} diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseGlobalIlluminationComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseGlobalIlluminationComponent.h new file mode 100644 index 0000000000..2a478665c5 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseGlobalIlluminationComponent.h @@ -0,0 +1,40 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include + +namespace AZ +{ + namespace Render + { + class EditorDiffuseGlobalIlluminationComponent final + : public AzToolsFramework::Components::EditorComponentAdapter + { + public: + + using BaseClass = AzToolsFramework::Components::EditorComponentAdapter; + AZ_EDITOR_COMPONENT(AZ::Render::EditorDiffuseGlobalIlluminationComponent, EditorDiffuseGlobalIlluminationComponentTypeId, BaseClass); + + static void Reflect(AZ::ReflectContext* context); + + EditorDiffuseGlobalIlluminationComponent() = default; + EditorDiffuseGlobalIlluminationComponent(const DiffuseGlobalIlluminationComponentConfig& config); + + //! EditorRenderComponentAdapter overrides... + AZ::u32 OnConfigurationChanged() override; + }; + + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseProbeGridComponent.cpp similarity index 99% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseProbeGridComponent.cpp index 1e5b959803..caf9ecd007 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseProbeGridComponent.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include #include #include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseProbeGridComponent.h similarity index 97% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseProbeGridComponent.h index 15c46d45ba..2e013ca479 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/EditorDiffuseProbeGridComponent.h @@ -16,8 +16,8 @@ #include #include #include -#include -#include +#include +#include #include namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp index 2ef4e1e229..df8552e5c9 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp @@ -18,7 +18,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -47,7 +48,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -111,6 +113,7 @@ namespace AZ EntityReferenceComponent::CreateDescriptor(), GradientWeightModifierComponent::CreateDescriptor(), DiffuseProbeGridComponent::CreateDescriptor(), + DiffuseGlobalIlluminationComponent::CreateDescriptor(), DeferredFogComponent::CreateDescriptor(), SurfaceData::SurfaceDataMeshComponent::CreateDescriptor(), AttachmentComponent::CreateDescriptor(), @@ -142,6 +145,7 @@ namespace AZ EditorEntityReferenceComponent::CreateDescriptor(), EditorGradientWeightModifierComponent::CreateDescriptor(), EditorDiffuseProbeGridComponent::CreateDescriptor(), + EditorDiffuseGlobalIlluminationComponent::CreateDescriptor(), EditorDeferredFogComponent::CreateDescriptor(), SurfaceData::EditorSurfaceDataMeshComponent::CreateDescriptor(), EditorAttachmentComponent::CreateDescriptor(), diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index e58f72a121..a68c54e85f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -23,8 +23,10 @@ set(FILES Source/CoreLights/EditorDirectionalLightComponent.cpp Source/Decals/EditorDecalComponent.h Source/Decals/EditorDecalComponent.cpp - Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.h - Source/DiffuseProbeGrid/EditorDiffuseProbeGridComponent.cpp + Source/DiffuseGlobalIllumination/EditorDiffuseProbeGridComponent.h + Source/DiffuseGlobalIllumination/EditorDiffuseProbeGridComponent.cpp + Source/DiffuseGlobalIllumination/EditorDiffuseGlobalIlluminationComponent.h + Source/DiffuseGlobalIllumination/EditorDiffuseGlobalIlluminationComponent.cpp Source/Grid/EditorGridComponent.h Source/Grid/EditorGridComponent.cpp Source/ImageBasedLights/EditorImageBasedLightComponent.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake index e13d1d37d6..7745306785 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake @@ -43,10 +43,16 @@ set(FILES Source/Decals/DecalComponent.cpp Source/Decals/DecalComponentController.h Source/Decals/DecalComponentController.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridComponent.h - Source/DiffuseProbeGrid/DiffuseProbeGridComponent.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.h - Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridComponent.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridComponent.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.cpp + Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponent.h + Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponent.cpp + Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.h + Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.cpp + Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.h + Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.cpp Source/Grid/GridComponent.h Source/Grid/GridComponent.cpp Source/Grid/GridComponentConfig.cpp From d90a3d46a7ac393a12807fe66eacd4f9bab7c8f1 Mon Sep 17 00:00:00 2001 From: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> Date: Thu, 3 Jun 2021 15:59:45 -0500 Subject: [PATCH 484/811] Support for nested slice conversions (#1121) This set of changes enables conversions for singly-nested slices. Multiple nesting hierarchies are only partially supported at this point. Conversion is also significantly more deterministic, which makes it easier to convert single slices without needing to reconvert every slice or level that relies on it as well. Changes: - Added version of Instance::AddInstance() that takes in an alias to allow for deterministic aliases - Added a "SliceConverterEditorEntityContextComponent" that's used to specifically disable entity activation on creation. The disabling is done this way vs adding a new public API, because the disable shouldn't be required in any normal case outside of this tool. - Disabled more AWS gems for the SliceConverter, as they're unneeded and cause issues if they're around in the tool. - Added a small null check to the Camera Controller. - Added the actual support for slice instance conversion. This instantiates the entities, applies the data patches, turns them into a prefab instance, and generates a JSON patch out of the changes. --- .../AzCore/AzCore/Slice/SliceComponent.h | 7 +- .../Prefab/Instance/Instance.cpp | 13 +- .../Prefab/Instance/Instance.h | 1 + .../SerializeContextTools/Application.cpp | 19 +- .../SerializeContextTools/SliceConverter.cpp | 230 +++++++++++++++--- .../SerializeContextTools/SliceConverter.h | 31 ++- ...iceConverterEditorEntityContextComponent.h | 65 +++++ Code/Tools/SerializeContextTools/main.cpp | 3 +- .../serializecontexttools_files.cmake | 1 + .../Code/Source/CameraComponentController.cpp | 5 +- .../gem_autoload.serializecontexttools.setreg | 6 + 11 files changed, 330 insertions(+), 51 deletions(-) create mode 100644 Code/Tools/SerializeContextTools/SliceConverterEditorEntityContextComponent.h diff --git a/Code/Framework/AzCore/AzCore/Slice/SliceComponent.h b/Code/Framework/AzCore/AzCore/Slice/SliceComponent.h index 5ef8df0617..0c9bad6d4a 100644 --- a/Code/Framework/AzCore/AzCore/Slice/SliceComponent.h +++ b/Code/Framework/AzCore/AzCore/Slice/SliceComponent.h @@ -971,6 +971,10 @@ namespace AZ */ void RestoreCachedInstances(); + /// Returns data flags for use when instantiating an instance of this slice. + /// These data flags include those harvested from the entire slice ancestry. + const DataFlagsPerEntity& GetDataFlagsForInstances() const; + protected: ////////////////////////////////////////////////////////////////////////// @@ -1004,9 +1008,6 @@ namespace AZ DataFlagsPerEntity* GetCorrectBundleOfDataFlags(EntityId entityId); const DataFlagsPerEntity* GetCorrectBundleOfDataFlags(EntityId entityId) const; - /// Returns data flags for use when instantiating an instance of this slice. - /// These data flags include those harvested from the entire slice ancestry. - const DataFlagsPerEntity& GetDataFlagsForInstances() const; void BuildDataFlagsForInstances(); /** diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp index 8f483ec818..766a293b4a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -49,8 +50,7 @@ namespace AzToolsFramework m_alias = GenerateInstanceAlias(); m_containerEntity = containerEntity ? AZStd::move(containerEntity) : AZStd::make_unique(); - EntityAlias containerEntityAlias = GenerateEntityAlias(); - RegisterEntity(m_containerEntity->GetId(), containerEntityAlias); + RegisterEntity(m_containerEntity->GetId(), PrefabDomUtils::ContainerEntityName); } Instance::~Instance() @@ -311,8 +311,15 @@ namespace AzToolsFramework Instance& Instance::AddInstance(AZStd::unique_ptr instance) { InstanceAlias newInstanceAlias = GenerateInstanceAlias(); + return AddInstance(AZStd::move(instance), newInstanceAlias); + } + + Instance& Instance::AddInstance(AZStd::unique_ptr instance, InstanceAlias newInstanceAlias) + { AZ_Assert(instance.get(), "instance argument is nullptr"); - AZ_Assert(m_nestedInstances.find(newInstanceAlias) == m_nestedInstances.end(), "InstanceAlias' unique id collision, this should never happen."); + AZ_Assert( + m_nestedInstances.find(newInstanceAlias) == m_nestedInstances.end(), + "InstanceAlias' unique id collision, this should never happen."); instance->m_parent = this; instance->m_alias = newInstanceAlias; return *(m_nestedInstances[newInstanceAlias] = std::move(instance)); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h index 68bc395012..4a69ade6d2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h @@ -93,6 +93,7 @@ namespace AzToolsFramework void Reset(); Instance& AddInstance(AZStd::unique_ptr instance); + Instance& AddInstance(AZStd::unique_ptr instance, InstanceAlias instanceAlias); AZStd::unique_ptr DetachNestedInstance(const InstanceAlias& instanceAlias); /** diff --git a/Code/Tools/SerializeContextTools/Application.cpp b/Code/Tools/SerializeContextTools/Application.cpp index 81cc314deb..918afd731c 100644 --- a/Code/Tools/SerializeContextTools/Application.cpp +++ b/Code/Tools/SerializeContextTools/Application.cpp @@ -17,6 +17,7 @@ #include #include +#include namespace AZ { @@ -34,6 +35,9 @@ namespace AZ Application::Application(int argc, char** argv) : AzToolsFramework::ToolsApplication(&argc, &argv) { + // We need a specialized variant of EditorEntityContextCompnent for the SliceConverter, so we register the descriptor here. + RegisterComponentDescriptor(AzToolsFramework::SliceConverterEditorEntityContextComponent::CreateDescriptor()); + AZ::IO::FixedMaxPath projectPath = AZ::Utils::GetProjectPath(); if (projectPath.empty()) { @@ -110,10 +114,21 @@ namespace AZ AZ::ComponentTypeList Application::GetRequiredSystemComponents() const { - // Use all of the default system components, but also add in the ThumbnailerNullComponent so that components requiring - // a ThumbnailService can still be started up. + // By default, we use all of the standard system components. AZ::ComponentTypeList components = AzToolsFramework::ToolsApplication::GetRequiredSystemComponents(); + + // Also add in the ThumbnailerNullComponent so that components requiring a ThumbnailService can still be started up. components.emplace_back(azrtti_typeid()); + + // The Slice Converter requires a specialized variant of the EditorEntityContextComponent that exposes the ability + // to disable the behavior of activating entities on creation. During conversion, the creation flow will be triggered, + // but entity activation requires a significant amount of subsystem initialization that's unneeded for conversion. + // So, to get around this, we swap out EditorEntityContextComponent with SliceConverterEditorEntityContextComponent. + components.erase( + AZStd::remove( + components.begin(), components.end(), azrtti_typeid()), + components.end()); + components.emplace_back(azrtti_typeid()); return components; } } // namespace SerializeContextTools diff --git a/Code/Tools/SerializeContextTools/SliceConverter.cpp b/Code/Tools/SerializeContextTools/SliceConverter.cpp index d06534e303..56b3689d6b 100644 --- a/Code/Tools/SerializeContextTools/SliceConverter.cpp +++ b/Code/Tools/SerializeContextTools/SliceConverter.cpp @@ -30,13 +30,16 @@ #include #include #include +#include #include #include #include #include #include +#include #include + // SliceConverter reads in a slice file (saved in an ObjectStream format), instantiates it, creates a prefab out of the data, // and saves the prefab in a JSON format. This can be used for one-time migrations of slices or slice-based levels to prefabs. // @@ -99,12 +102,26 @@ namespace AZ bool result = true; rapidjson::StringBuffer scratchBuffer; + // For slice conversion, disable the EditorEntityContextComponent logic that activates entities on creation. + // This prevents a lot of error messages and crashes during conversion due to lack of full environment and subsystem setup. + AzToolsFramework::SliceConverterEditorEntityContextComponent::DisableOnContextEntityLogic(); + // Loop through the list of requested files and convert them. AZStd::vector fileList = Utilities::ReadFileListFromCommandLine(application, "files"); for (AZStd::string& filePath : fileList) { bool convertResult = ConvertSliceFile(convertSettings.m_serializeContext, filePath, isDryRun); result = result && convertResult; + + // Clear out all registered prefab templates between each top-level file that gets processed. + auto prefabSystemComponentInterface = AZ::Interface::Get(); + for (auto templateId : m_createdTemplateIds) + { + // We don't just want to call RemoveAllTemplates() because the root template should remain between file conversions. + prefabSystemComponentInterface->RemoveTemplate(templateId); + } + m_aliasIdMapper.clear(); + m_createdTemplateIds.clear(); } DisconnectFromAssetProcessor(); @@ -114,6 +131,13 @@ namespace AZ bool SliceConverter::ConvertSliceFile( AZ::SerializeContext* serializeContext, const AZStd::string& slicePath, bool isDryRun) { + /* To convert a slice file, we read the input file in via ObjectStream, then use the "class ready" callback to convert + * the data in memory to a Prefab. + * If the input file is a level file (.ly), we actually need to load the level slice file ("levelentities.editor_xml") from + * within the level file, which effectively is a zip file of the level slice file and a bunch of legacy level files that won't + * be converted, since the systems that would use them no longer exist. + */ + bool result = true; bool packOpened = false; @@ -144,7 +168,7 @@ namespace AZ AZ_STRING_ARG(fileExtension.Native())); } - auto callback = [&outputPath, isDryRun](void* classPtr, const Uuid& classId, SerializeContext* context) + auto callback = [this, &outputPath, isDryRun](void* classPtr, const Uuid& classId, SerializeContext* context) { if (classId != azrtti_typeid()) { @@ -178,6 +202,13 @@ namespace AZ bool SliceConverter::ConvertSliceToPrefab( AZ::SerializeContext* serializeContext, AZ::IO::PathView outputPath, bool isDryRun, AZ::Entity* rootEntity) { + /* Given a root slice entity, we convert it to a prefab by doing the following: + * - Locate the SliceComponent + * - Take all the entities directly located on the slice, and put them into a prefab + * - Fix up any top-level entities to have the prefab container entity as their parent + * - If there are any nested slice instances, convert the nested slices to prefabs, then convert the instances. + */ + auto prefabSystemComponentInterface = AZ::Interface::Get(); // Find the slice from the root entity. @@ -192,9 +223,14 @@ namespace AZ SliceComponent::EntityList sliceEntities = sliceComponent->GetNewEntities(); AZ_Printf("Convert-Slice", " Slice contains %zu entities.\n", sliceEntities.size()); - // Create the Prefab with the entities from the slice + // Create the Prefab with the entities from the slice. + // The entities are added in a separate step so that we can give them deterministic entity aliases that match their entity Ids AZStd::unique_ptr sourceInstance( - prefabSystemComponentInterface->CreatePrefab(sliceEntities, {}, outputPath)); + prefabSystemComponentInterface->CreatePrefab({}, {}, outputPath)); + for (auto& entity : sliceEntities) + { + sourceInstance->AddEntity(*entity, AZStd::string::format("Entity_%s", entity->GetId().ToString().c_str())); + } // Dispatch events here, because prefab creation might trigger asset loads in rare circumstances. AZ::Data::AssetManager::Instance().DispatchEvents(); @@ -204,12 +240,28 @@ namespace AZ AzToolsFramework::Prefab::EntityOptionalReference container = sourceInstance->GetContainerEntity(); FixPrefabEntities(container->get(), sliceEntities); + // Keep track of the template Id we created, we're going to remove it at the end of slice file conversion to make sure + // the data doesn't stick around between file conversions. auto templateId = sourceInstance->GetTemplateId(); if (templateId == AzToolsFramework::Prefab::InvalidTemplateId) { AZ_Printf("Convert-Slice", " Path error. Path could be invalid, or the prefab may not be loaded in this level.\n"); return false; } + m_createdTemplateIds.emplace(templateId); + + // Save off a mapping of the original slice entity IDs to the new prefab template entity aliases. + // When converting nested slices, this mapping will be needed to fix up the parent entity hierarchy correctly. + auto entityAliases = sourceInstance->GetEntityAliases(); + for (auto& alias : entityAliases) + { + auto id = sourceInstance->GetEntityId(alias); + auto result = m_aliasIdMapper.emplace(TemplateEntityIdPair(templateId, id), alias); + if (!result.second) + { + AZ_Printf("Convert-Slice", " Duplicate entity alias -> entity id entries found, conversion may not be successful.\n"); + } + } // Update the prefab template with the fixed-up data in our prefab instance. AzToolsFramework::Prefab::PrefabDom prefabDom; @@ -254,21 +306,26 @@ namespace AZ // via an EditorRequests EBus in CreatePrefab, but the subsystem that listens for it isn't present in this tool.) AzToolsFramework::EditorEntityContextRequestBus::Broadcast( &AzToolsFramework::EditorEntityContextRequestBus::Events::AddRequiredComponents, containerEntity); - containerEntity.AddComponent(aznew AzToolsFramework::Prefab::EditorPrefabComponent()); + if (containerEntity.FindComponent() == nullptr) + { + containerEntity.AddComponent(aznew AzToolsFramework::Prefab::EditorPrefabComponent()); + } + + // Make all the components on the container entity have deterministic component IDs, so that multiple runs of the tool + // on the same slice will produce the same prefab output. We're going to cheat a bit and just use the component type hash + // as the component ID. This would break if we had multiple components of the same type, but that currently doesn't + // happen for the container entity. + auto containerComponents = containerEntity.GetComponents(); + for (auto& component : containerComponents) + { + component->SetId(component->GetUnderlyingComponentType().GetHash()); + } // Reparent any root-level slice entities to the container entity. for (auto entity : sliceEntities) { - AzToolsFramework::Components::TransformComponent* transformComponent = - entity->FindComponent(); - if (transformComponent) - { - if (!transformComponent->GetParentId().IsValid()) - { - transformComponent->SetParent(containerEntity.GetId()); - transformComponent->UpdateCachedWorldTransform(); - } - } + constexpr bool onlySetIfInvalid = true; + SetParentEntity(*entity, containerEntity.GetId(), onlySetIfInvalid); } } @@ -276,9 +333,13 @@ namespace AZ SliceComponent* sliceComponent, AzToolsFramework::Prefab::Instance* sourceInstance, AZ::SerializeContext* serializeContext, bool isDryRun) { + /* Given a root slice, find all the nested slices and convert them. */ + + // Get the list of nested slices that this slice uses. const SliceComponent::SliceList& sliceList = sliceComponent->GetSlices(); auto prefabSystemComponentInterface = AZ::Interface::Get(); + // For each nested slice, convert it. for (auto& slice : sliceList) { // Get the nested slice asset @@ -312,7 +373,7 @@ namespace AZ return false; } - // Load the prefab template for the newly-created nested prefab. + // Find the prefab template we created for the newly-created nested prefab. // To get the template, we need to take our absolute slice path and turn it into a project-relative prefab path. AZ::IO::Path nestedPrefabPath = assetPath; nestedPrefabPath.ReplaceExtension("prefab"); @@ -346,11 +407,25 @@ namespace AZ } bool SliceConverter::ConvertSliceInstance( - [[maybe_unused]] AZ::SliceComponent::SliceInstance& instance, - [[maybe_unused]] AZ::Data::Asset& sliceAsset, + AZ::SliceComponent::SliceInstance& instance, + AZ::Data::Asset& sliceAsset, AzToolsFramework::Prefab::TemplateReference nestedTemplate, AzToolsFramework::Prefab::Instance* topLevelInstance) { + /* To convert a slice instance, it's important to understand the similarities and differences between slices and prefabs. + * Both slices and prefabs have the concept of instances of a nested slice/prefab, where each instance can have its own + * set of changed data (transforms, component values, etc). + * For slices, the changed data comes from applying a DataPatch to an instantiated set of entities from the nested slice. + * From prefabs, the changed data comes from Json patches that are applied to the instantiated set of entities from the + * nested prefab. The prefab instance entities also have different IDs than the slice instance entities, so we'll need + * to remap some of them along the way. + * To get from one to the other, we'll need to do the following: + * - Instantiate the nested slice and nested prefab + * - Patch the nested slice instance and fix up the entity ID references + * - Replace the nested prefab instance entities with the fixed-up slice ones + * - Add the nested instance (and the link patch) to the top-level prefab + */ + auto instanceToTemplateInterface = AZ::Interface::Get(); auto prefabSystemComponentInterface = AZ::Interface::Get(); @@ -371,22 +446,83 @@ namespace AZ AzToolsFramework::Prefab::PrefabDom unmodifiedNestedInstanceDom; instanceToTemplateInterface->GenerateDomForInstance(unmodifiedNestedInstanceDom, *(nestedInstance.get())); - // Currently, DataPatch conversions for nested slices aren't implemented, so all nested slice overrides will - // be lost. - AZ_Warning( - "Convert-Slice", false, " Nested slice instances will lose all of their override data during conversion.", - nestedTemplate->get().GetFilePath().c_str()); + // Instantiate a new instance of the nested slice + SliceComponent* dependentSlice = sliceAsset.Get()->GetComponent(); + [[maybe_unused]] AZ::SliceComponent::InstantiateResult instantiationResult = dependentSlice->Instantiate(); + AZ_Assert(instantiationResult == AZ::SliceComponent::InstantiateResult::Success, "Failed to instantiate instance"); - // Set the container entity of the nested prefab to have the top-level prefab as the parent. - // Once DataPatch conversions are supported, this will need to change to nest the prefab under the appropriate entity - // within the level. + // Apply the data patch for this instance of the nested slice. This will provide us with a version of the slice's entities + // with all data overrides applied to them. + DataPatch::FlagsMap sourceDataFlags = dependentSlice->GetDataFlagsForInstances().GetDataFlagsForPatching(); + DataPatch::FlagsMap targetDataFlags = instance.GetDataFlags().GetDataFlagsForPatching(&instance.GetEntityIdToBaseMap()); + AZ::ObjectStream::FilterDescriptor filterDesc(AZ::Data::AssetFilterNoAssetLoading); + + AZ::SliceComponent::InstantiatedContainer sourceObjects(false); + dependentSlice->GetEntities(sourceObjects.m_entities); + dependentSlice->GetAllMetadataEntities(sourceObjects.m_metadataEntities); + + const DataPatch& dataPatch = instance.GetDataPatch(); + auto instantiated = + dataPatch.Apply(&sourceObjects, dependentSlice->GetSerializeContext(), filterDesc, sourceDataFlags, targetDataFlags); + + // Run through all the instantiated entities and fix up their parent hierarchy: + // - Invalid parents need to get set to the container. + // - Valid parents into the top-level instance mean that the nested slice instance is also child-nested under an entity. + // Prefabs handle this type of nesting differently - we need to set the parent to the container, and the container's + // parent to that other instance. auto containerEntity = nestedInstance->GetContainerEntity(); - AzToolsFramework::Components::TransformComponent* transformComponent = - containerEntity->get().FindComponent(); - if (transformComponent) + auto containerEntityId = containerEntity->get().GetId(); + for (auto entity : instantiated->m_entities) { - transformComponent->SetParent(topLevelInstance->GetContainerEntityId()); - transformComponent->UpdateCachedWorldTransform(); + AzToolsFramework::Components::TransformComponent* transformComponent = + entity->FindComponent(); + if (transformComponent) + { + bool onlySetIfInvalid = true; + auto parentId = transformComponent->GetParentId(); + if (parentId.IsValid()) + { + auto parentAlias = m_aliasIdMapper.find(TemplateEntityIdPair(topLevelInstance->GetTemplateId(), parentId)); + if (parentAlias != m_aliasIdMapper.end()) + { + // Set the container's parent to this entity's parent, and set this entity's parent to the container + // (i.e. go from A->B to A->container->B) + auto newParentId = topLevelInstance->GetEntityId(parentAlias->second); + SetParentEntity(containerEntity->get(), newParentId, false); + onlySetIfInvalid = false; + } + } + + SetParentEntity(*entity, containerEntityId, onlySetIfInvalid); + } + } + + // Replace all the entities in the instance with the new patched ones. + // (This is easier than trying to figure out what the patched data changes are - we can let the JSON patch handle it for us) + nestedInstance->RemoveNestedEntities( + [](const AZStd::unique_ptr&) + { + return true; + }); + for (auto& entity : instantiated->m_entities) + { + auto entityAlias = m_aliasIdMapper.find(TemplateEntityIdPair(nestedInstance->GetTemplateId(), entity->GetId())); + if (entityAlias != m_aliasIdMapper.end()) + { + nestedInstance->AddEntity(*entity, entityAlias->second); + } + else + { + AZ_Assert(false, "Failed to find entity alias."); + nestedInstance->AddEntity(*entity); + } + } + + // Set the container entity of the nested prefab to have the top-level prefab as the parent if it hasn't already gotten + // another entity as its parent. + { + constexpr bool onlySetIfInvalid = true; + SetParentEntity(containerEntity->get(), topLevelInstance->GetContainerEntityId(), onlySetIfInvalid); } // Add the nested instance itself to the top-level prefab. To do this, we need to add it to our top-level instance, @@ -395,7 +531,22 @@ namespace AZ AzToolsFramework::Prefab::PrefabDom topLevelInstanceDomBefore; instanceToTemplateInterface->GenerateDomForInstance(topLevelInstanceDomBefore, *topLevelInstance); - AzToolsFramework::Prefab::Instance& addedInstance = topLevelInstance->AddInstance(AZStd::move(nestedInstance)); + // When creating the new instance, we would like to have deterministic instance aliases. Prefabs that depend on this one + // will have patches that reference the alias, so if we reconvert this slice a second time, we would like it to produce + // the same results. To get a deterministic and unique alias, we rely on the slice instance. The slice instance contains + // a map of slice entity IDs to unique instance entity IDs. We'll just consistently use the first entry in the map as the + // unique instance ID. + AZStd::string instanceAlias; + auto entityIdMap = instance.GetEntityIdMap(); + if (!entityIdMap.empty()) + { + instanceAlias = AZStd::string::format("Instance_%s", entityIdMap.begin()->second.ToString().c_str()); + } + else + { + instanceAlias = AZStd::string::format("Instance_%s", AZ::Entity::MakeId().ToString().c_str()); + } + AzToolsFramework::Prefab::Instance& addedInstance = topLevelInstance->AddInstance(AZStd::move(nestedInstance), instanceAlias); AzToolsFramework::Prefab::PrefabDom topLevelInstanceDomAfter; instanceToTemplateInterface->GenerateDomForInstance(topLevelInstanceDomAfter, *topLevelInstance); @@ -418,9 +569,26 @@ namespace AZ AzToolsFramework::Prefab::InvalidLinkId); prefabSystemComponentInterface->PropagateTemplateChanges(topLevelInstance->GetTemplateId()); + AZ::Interface::Get()->UpdateTemplateInstancesInQueue(); + return true; } + void SliceConverter::SetParentEntity(const AZ::Entity& entity, const AZ::EntityId& parentId, bool onlySetIfInvalid) + { + AzToolsFramework::Components::TransformComponent* transformComponent = + entity.FindComponent(); + if (transformComponent) + { + // Only set the parent if we didn't set the onlySetIfInvalid flag, or if we did and the parent is currently invalid + if (!onlySetIfInvalid || !transformComponent->GetParentId().IsValid()) + { + transformComponent->SetParent(parentId); + transformComponent->UpdateCachedWorldTransform(); + } + } + } + void SliceConverter::PrintPrefab(AzToolsFramework::Prefab::TemplateId templateId) { auto prefabSystemComponentInterface = AZ::Interface::Get(); diff --git a/Code/Tools/SerializeContextTools/SliceConverter.h b/Code/Tools/SerializeContextTools/SliceConverter.h index bec893ff56..82dcf30383 100644 --- a/Code/Tools/SerializeContextTools/SliceConverter.h +++ b/Code/Tools/SerializeContextTools/SliceConverter.h @@ -39,24 +39,35 @@ namespace AZ class SliceConverter : public Converter { public: - static bool ConvertSliceFiles(Application& application); + bool ConvertSliceFiles(Application& application); private: - static bool ConnectToAssetProcessor(); - static void DisconnectFromAssetProcessor(); + using TemplateEntityIdPair = AZStd::pair; - static bool ConvertSliceFile(AZ::SerializeContext* serializeContext, const AZStd::string& slicePath, bool isDryRun); - static bool ConvertSliceToPrefab( + bool ConnectToAssetProcessor(); + void DisconnectFromAssetProcessor(); + + bool ConvertSliceFile(AZ::SerializeContext* serializeContext, const AZStd::string& slicePath, bool isDryRun); + bool ConvertSliceToPrefab( AZ::SerializeContext* serializeContext, AZ::IO::PathView outputPath, bool isDryRun, AZ::Entity* rootEntity); - static void FixPrefabEntities(AZ::Entity& containerEntity, SliceComponent::EntityList& sliceEntities); - static bool ConvertNestedSlices( + void FixPrefabEntities(AZ::Entity& containerEntity, SliceComponent::EntityList& sliceEntities); + bool ConvertNestedSlices( SliceComponent* sliceComponent, AzToolsFramework::Prefab::Instance* sourceInstance, AZ::SerializeContext* serializeContext, bool isDryRun); - static bool ConvertSliceInstance( + bool ConvertSliceInstance( AZ::SliceComponent::SliceInstance& instance, AZ::Data::Asset& sliceAsset, AzToolsFramework::Prefab::TemplateReference nestedTemplate, AzToolsFramework::Prefab::Instance* topLevelInstance); - static void PrintPrefab(AzToolsFramework::Prefab::TemplateId templateId); - static bool SavePrefab(AZ::IO::PathView outputPath, AzToolsFramework::Prefab::TemplateId templateId); + void SetParentEntity(const AZ::Entity& entity, const AZ::EntityId& parentId, bool onlySetIfInvalid); + void PrintPrefab(AzToolsFramework::Prefab::TemplateId templateId); + bool SavePrefab(AZ::IO::PathView outputPath, AzToolsFramework::Prefab::TemplateId templateId); + + // Track all of the entity IDs created and the prefab entity aliases that map to them. This mapping is used + // with nested slice conversion to remap parent entity IDs to the correct prefab entity IDs. + AZStd::unordered_map m_aliasIdMapper; + + // Track all of the created prefab template IDs on a slice conversion so that they can get removed at the end of the + // conversion for that file. + AZStd::unordered_set m_createdTemplateIds; }; } // namespace SerializeContextTools } // namespace AZ diff --git a/Code/Tools/SerializeContextTools/SliceConverterEditorEntityContextComponent.h b/Code/Tools/SerializeContextTools/SliceConverterEditorEntityContextComponent.h new file mode 100644 index 0000000000..166cb2abdf --- /dev/null +++ b/Code/Tools/SerializeContextTools/SliceConverterEditorEntityContextComponent.h @@ -0,0 +1,65 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include + +namespace AzToolsFramework +{ + // This class is an inelegant workaround for use by the Slice Converter to selectively disable entity add/remove logic + // during slice conversion in the EditorEntityContextComponent. Specifically, the standard versions of these methods will + // attempt to activate the entities as they're added. This is both unnecessary and undesirable during slice conversion, since + // entity activation requires a lot of subsystems to be active and valid. + // Instead, by selectively disabling this logic, the entities can remain in an initialized state, which is sufficient for conversion, + // without requiring those extra subsystems. + + // This problem also could have been solved by adding APIs to the EditorEntityContextComponent or the EntityContext, but there aren't + // any other known valid use cases for disabling this logic, so the extra APIs would simply encourage "bad behavior" by using them + // when they likely aren't necessary or desired. + + class SliceConverterEditorEntityContextComponent + : public EditorEntityContextComponent + { + public: + + AZ_COMPONENT(SliceConverterEditorEntityContextComponent, "{1CB0C38F-8E85-4422-91C6-E1F3B9B4B853}"); + + SliceConverterEditorEntityContextComponent() : EditorEntityContextComponent() {} + + // Simple API to selectively disable this logic *only* when performing slice to prefab conversion. + static void DisableOnContextEntityLogic() + { + m_enableOnContextEntityLogic = false; + } + + protected: + + void OnContextEntitiesAdded([[maybe_unused]] const EntityList& entities) override + { + if (m_enableOnContextEntityLogic) + { + EditorEntityContextComponent::OnContextEntitiesAdded(entities); + } + } + + void OnContextEntityRemoved([[maybe_unused]] const AZ::EntityId& id) override + { + if (m_enableOnContextEntityLogic) + { + EditorEntityContextComponent::OnContextEntityRemoved(id); + } + } + + // By default, act just like the EditorEntityContextComponent + static inline bool m_enableOnContextEntityLogic = true; + }; +} // namespace AzToolsFramework diff --git a/Code/Tools/SerializeContextTools/main.cpp b/Code/Tools/SerializeContextTools/main.cpp index d9f2cfbcc2..28eeb5ebe8 100644 --- a/Code/Tools/SerializeContextTools/main.cpp +++ b/Code/Tools/SerializeContextTools/main.cpp @@ -125,7 +125,8 @@ int main(int argc, char** argv) } else if (AZ::StringFunc::Equal("convert-slice", action.c_str())) { - result = SliceConverter::ConvertSliceFiles(application); + SliceConverter sliceConverter; + result = sliceConverter.ConvertSliceFiles(application); } else { diff --git a/Code/Tools/SerializeContextTools/serializecontexttools_files.cmake b/Code/Tools/SerializeContextTools/serializecontexttools_files.cmake index 814c55ea08..3427357149 100644 --- a/Code/Tools/SerializeContextTools/serializecontexttools_files.cmake +++ b/Code/Tools/SerializeContextTools/serializecontexttools_files.cmake @@ -17,6 +17,7 @@ set(FILES Dumper.h Dumper.cpp main.cpp + SliceConverterEditorEntityContextComponent.h SliceConverter.h SliceConverter.cpp Utilities.h diff --git a/Gems/Camera/Code/Source/CameraComponentController.cpp b/Gems/Camera/Code/Source/CameraComponentController.cpp index d0a124067b..cad666c1cd 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.cpp +++ b/Gems/Camera/Code/Source/CameraComponentController.cpp @@ -178,7 +178,10 @@ namespace Camera if ((!m_viewSystem)||(!m_system)) { // perform first-time init - m_system = gEnv->pSystem; + if (gEnv) + { + m_system = gEnv->pSystem; + } if (m_system) { // Initialize local view. diff --git a/Registry/gem_autoload.serializecontexttools.setreg b/Registry/gem_autoload.serializecontexttools.setreg index e7e88dd6a6..0f74355084 100644 --- a/Registry/gem_autoload.serializecontexttools.setreg +++ b/Registry/gem_autoload.serializecontexttools.setreg @@ -10,6 +10,9 @@ "PythonAssetBuilder.Editor": { "AutoLoad": false }, + "AWSCore": { + "AutoLoad": false + }, "AWSCore.Editor": { "AutoLoad": false }, @@ -21,6 +24,9 @@ }, "AWSMetrics": { "AutoLoad": false + }, + "AWSMetrics.Editor": { + "AutoLoad": false } } } From fda28bb7b2504e7b2d2fc7cbdd344f373bf957ef Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Thu, 3 Jun 2021 14:02:40 -0700 Subject: [PATCH 485/811] LYN-1818 | [USE CASE] Reparenting between different prefab instances by drag/drop in the Outliner (#1088) * Add the last known parent to the prefab undo cache to detect changes in the owning instance. Still WIP. * Progress in handling reparenting. Still WIP, need a change in CreateLink that will be addressed in a separate branch and then merged back. * A few fixes, reparenting now works with entities. Still working on instances. * Fix assert crashing the Editor because of the arguments being in the wrong order. * Handle moving the patches when removing and recreating links when reparenting nested instances. * Rearrange some code to prevent including instance removal in instance update undo node, as it would be redundant and cause errors in some edge cases. * Reorder instance reparenting to account for correct order of operation during undo/redo * Fix order of operations to support multiple operations in one edit (reparenting to non-container entities while changing instance) * Add function to refresh patches on links to allow aliases to be restored correctly on reparenting. * Removed RefreshEntityPatchOnLink function. Introduced a simpler way of handling porting patches. * Removing unnecessary code that was left after testing. * Minor fixes to naming and comments. * Restore previous error, no longer printing the failed patch. * Remove unused includes. * Restore include removed by mistake. * Simplified patches retrieval by using internal function. Renamed some internal functions and variables to be more accurate. --- .../Prefab/PrefabPublicHandler.cpp | 221 +++++++++++++++--- .../Prefab/PrefabPublicHandler.h | 10 +- .../Prefab/PrefabSystemComponent.cpp | 4 +- .../Prefab/PrefabUndoCache.cpp | 24 +- .../AzToolsFramework/Prefab/PrefabUndoCache.h | 13 +- 5 files changed, 217 insertions(+), 55 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 90c3dd10ae..27c812ff9d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -297,7 +297,7 @@ namespace AzToolsFramework m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, containerEntityId); // Update the cache - this prevents these changes from being stored in the regular undo/redo nodes - m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter)); + m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter), parentEntityId); return AZStd::move(patch); } @@ -595,54 +595,199 @@ namespace AzToolsFramework { // Create Undo node on entities if they belong to an instance InstanceOptionalReference owningInstance = m_instanceEntityMapperInterface->FindOwningInstance(entityId); - - if (owningInstance.has_value()) + if (!owningInstance.has_value()) { - PrefabDom afterState; - AZ::Entity* entity = GetEntityById(entityId); - if (entity) + return; + } + + AZ::Entity* entity = GetEntityById(entityId); + if (!entity) + { + m_prefabUndoCache.PurgeCache(entityId); + return; + } + + PrefabDom beforeState; + AZ::EntityId beforeParentId; + m_prefabUndoCache.Retrieve(entityId, beforeState, beforeParentId); + + PrefabDom afterState; + AZ::EntityId afterParentId; + AZ::TransformBus::EventResult(afterParentId, entityId, &AZ::TransformBus::Events::GetParentId); + + m_instanceToTemplateInterface->GenerateDomForEntity(afterState, *entity); + + PrefabDom patch; + m_instanceToTemplateInterface->GeneratePatch(patch, beforeState, afterState); + m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, entityId); + + if (patch.IsArray() && !patch.Empty() && beforeState.IsObject()) + { + bool isInstanceContainerEntity = IsInstanceContainerEntity(entityId) && !IsLevelInstanceContainerEntity(entityId); + bool isNewParentOwnedByDifferentInstance = false; + + if (beforeParentId != afterParentId) { - PrefabDom beforeState; - m_prefabUndoCache.Retrieve(entityId, beforeState); + // If the entity parent changed, verify if the owning instance changed too + InstanceOptionalReference beforeOwningInstance = m_instanceEntityMapperInterface->FindOwningInstance(beforeParentId); + InstanceOptionalReference afterOwningInstance = m_instanceEntityMapperInterface->FindOwningInstance(afterParentId); - m_instanceToTemplateInterface->GenerateDomForEntity(afterState, *entity); - - PrefabDom patch; - m_instanceToTemplateInterface->GeneratePatch(patch, beforeState, afterState); - - if (patch.IsArray() && !patch.Empty() && beforeState.IsObject()) + if (beforeOwningInstance.has_value() && afterOwningInstance.has_value() && + (&beforeOwningInstance->get() != &afterOwningInstance->get())) { - if (IsInstanceContainerEntity(entityId) && !IsLevelInstanceContainerEntity(entityId)) - { - m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, entityId); - - // Save these changes as patches to the link - PrefabUndoLinkUpdate* linkUpdate = - aznew PrefabUndoLinkUpdate(AZStd::to_string(static_cast(entityId))); - linkUpdate->SetParent(parentUndoBatch); - linkUpdate->Capture(patch, owningInstance->get().GetLinkId()); - - linkUpdate->Redo(); - } - else - { - // Update the state of the entity - PrefabUndoEntityUpdate* state = aznew PrefabUndoEntityUpdate(AZStd::to_string(static_cast(entityId))); - state->SetParent(parentUndoBatch); - state->Capture(beforeState, afterState, entityId); - - state->Redo(); - } + isNewParentOwnedByDifferentInstance = true; } + } - // Update the cache - m_prefabUndoCache.Store(entityId, AZStd::move(afterState)); + if (isInstanceContainerEntity) + { + if (isNewParentOwnedByDifferentInstance) + { + Internal_HandleInstanceChange(parentUndoBatch, entity, beforeParentId, afterParentId); + + PrefabDom afterStateafterReparenting; + m_instanceToTemplateInterface->GenerateDomForEntity(afterStateafterReparenting, *entity); + + PrefabDom newPatch; + m_instanceToTemplateInterface->GeneratePatch(newPatch, afterState, afterStateafterReparenting); + m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(newPatch, entityId); + + InstanceOptionalReference owningInstanceAfterReparenting = + m_instanceEntityMapperInterface->FindOwningInstance(entityId); + + Internal_HandleContainerOverride( + parentUndoBatch, entityId, newPatch, owningInstanceAfterReparenting->get().GetLinkId()); + } + else + { + Internal_HandleContainerOverride( + parentUndoBatch, entityId, patch, owningInstance->get().GetLinkId()); + } } else { - m_prefabUndoCache.PurgeCache(entityId); + Internal_HandleEntityChange(parentUndoBatch, entityId, beforeState, afterState); + + if (isNewParentOwnedByDifferentInstance) + { + Internal_HandleInstanceChange(parentUndoBatch, entity, beforeParentId, afterParentId); + } } } + + m_prefabUndoCache.UpdateCache(entityId); + } + + void PrefabPublicHandler::Internal_HandleContainerOverride( + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, const PrefabDom& patch, const LinkId linkId) + { + // Save these changes as patches to the link + PrefabUndoLinkUpdate* linkUpdate = aznew PrefabUndoLinkUpdate(AZStd::to_string(static_cast(entityId))); + linkUpdate->SetParent(undoBatch); + linkUpdate->Capture(patch, linkId); + + linkUpdate->Redo(); + } + + void PrefabPublicHandler::Internal_HandleEntityChange( + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, PrefabDom& beforeState, PrefabDom& afterState) + { + // Update the state of the entity + PrefabUndoEntityUpdate* state = aznew PrefabUndoEntityUpdate(AZStd::to_string(static_cast(entityId))); + state->SetParent(undoBatch); + state->Capture(beforeState, afterState, entityId); + + state->Redo(); + } + + void PrefabPublicHandler::Internal_HandleInstanceChange( + UndoSystem::URSequencePoint* undoBatch, AZ::Entity* entity, AZ::EntityId beforeParentId, AZ::EntityId afterParentId) + { + // If the entity parent changed, verify if the owning instance changed too + InstanceOptionalReference beforeOwningInstance = m_instanceEntityMapperInterface->FindOwningInstance(beforeParentId); + InstanceOptionalReference afterOwningInstance = m_instanceEntityMapperInterface->FindOwningInstance(afterParentId); + + EntityList entities; + AZStd::vector instances; + + // Retrieve all descendant entities and instances of this entity that belonged to the same owning instance. + RetrieveAndSortPrefabEntitiesAndInstances({ entity }, beforeOwningInstance->get(), entities, instances); + + AZStd::vector> instanceUniquePtrs; + AZStd::vector> instancePatches; + + // Remove Entities and Instances from the prior instance + { + // Remove Instances + for (Instance* nestedInstance : instances) + { + auto linkRef = m_prefabSystemComponentInterface->FindLink(nestedInstance->GetLinkId()); + + PrefabDom oldLinkPatches; + + if (linkRef.has_value()) + { + auto patches = linkRef->get().GetLinkPatches(); + if (patches.has_value()) + { + oldLinkPatches.CopyFrom(patches->get(), oldLinkPatches.GetAllocator()); + } + } + + auto nestedInstanceUniquePtr = beforeOwningInstance->get().DetachNestedInstance(nestedInstance->GetInstanceAlias()); + RemoveLink(nestedInstanceUniquePtr, beforeOwningInstance->get().GetTemplateId(), undoBatch); + + instancePatches.emplace_back(AZStd::make_pair(nestedInstanceUniquePtr.get(), AZStd::move(oldLinkPatches))); + instanceUniquePtrs.emplace_back(AZStd::move(nestedInstanceUniquePtr)); + } + + // Get the previous state of the prior instance for undo/redo purposes + PrefabDom beforeInstanceDomBeforeRemoval; + m_instanceToTemplateInterface->GenerateDomForInstance(beforeInstanceDomBeforeRemoval, beforeOwningInstance->get()); + + // Remove Entities + for (AZ::Entity* nestedEntity : entities) + { + beforeOwningInstance->get().DetachEntity(nestedEntity->GetId()).release(); + } + + // Create the Update node for the prior owning instance + // Instance removal will be taken care of from the RemoveLink function for undo/redo purposes + PrefabUndoHelpers::UpdatePrefabInstance( + beforeOwningInstance->get(), "Update prior prefab instance", beforeInstanceDomBeforeRemoval, undoBatch); + } + + // Add Entities and Instances to new instance + { + // Add Instances + for (auto& instanceUniquePtr : instanceUniquePtrs) + { + afterOwningInstance->get().AddInstance(AZStd::move(instanceUniquePtr)); + } + + // Create Links + for (auto& instanceInfo : instancePatches) + { + // Add a new link with the old dom + CreateLink( + *instanceInfo.first, afterOwningInstance->get().GetTemplateId(), undoBatch, + AZStd::move(instanceInfo.second)); + } + + // Get the previous state of the new instance for undo/redo purposes + PrefabDom afterInstanceDomBeforeAdd; + m_instanceToTemplateInterface->GenerateDomForInstance(afterInstanceDomBeforeAdd, afterOwningInstance->get()); + + // Add Entities + for (AZ::Entity* nestedEntity : entities) + { + afterOwningInstance->get().AddEntity(*nestedEntity); + } + + // Create the Update node for the new owning instance + PrefabUndoHelpers::UpdatePrefabInstance( + afterOwningInstance->get(), "Update new prefab instance", afterInstanceDomBeforeAdd, undoBatch); + } } bool PrefabPublicHandler::IsInstanceContainerEntity(AZ::EntityId entityId) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index e7b6f8c932..99fe8e5b67 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -90,8 +90,8 @@ namespace AzToolsFramework /** * Creates a link between the templates of an instance and its parent. * - * \param sourceInstance The instance that corresponds to the source template of the link. - * \param targetInstance The id of the target template. + * \param sourceInstance The instance that corresponds to the source template of the link (child). + * \param targetInstance The id of the target template (parent). * \param undoBatch The undo batch to set as parent for this create link action. * \param patch The patch to store in the newly created link dom. * \param isUndoRedoSupportNeeded The flag indicating whether the link should be created with undo/redo support or not. @@ -134,6 +134,12 @@ namespace AzToolsFramework bool IsCyclicalDependencyFound( InstanceOptionalConstReference instance, const AZStd::unordered_set& templateSourcePaths); + static void Internal_HandleContainerOverride( + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, const PrefabDom& patch, const LinkId linkId); + static void Internal_HandleEntityChange( + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, PrefabDom& beforeState, PrefabDom& afterState); + void Internal_HandleInstanceChange(UndoSystem::URSequencePoint* undoBatch, AZ::Entity* entity, AZ::EntityId beforeParentId, AZ::EntityId afterParentId); + void UpdateLinkPatchesWithNewEntityAliases( PrefabDom& linkPatch, const AZStd::unordered_map& oldEntityAliases, diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index c42dbe792a..5f5564b4e1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -706,14 +706,14 @@ namespace AzToolsFramework "Prefab - PrefabSystemComponent::RemoveLink - " "Failed to remove Link with Id '%llu' for Instance '%s' of source Template with Id '%llu' " "from TemplateToLinkIdsMap.", - linkId, link.GetSourceTemplateId(), link.GetInstanceName().c_str()); + linkId, link.GetInstanceName().c_str(), link.GetSourceTemplateId()); result = RemoveLinkFromTargetTemplate(linkId, link); AZ_Assert(result, "Prefab - PrefabSystemComponent::RemoveLink - " "Failed to remove Link with Id '%llu' for Instance '%s' of source Template with Id '%llu' " "from target Template with Id '%llu'.", - linkId, link.GetSourceTemplateId(), link.GetInstanceName().c_str(), link.GetTargetTemplateId()); + linkId, link.GetInstanceName().c_str(), link.GetSourceTemplateId(), link.GetTargetTemplateId()); m_linkIdMap.erase(linkId); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.cpp index 7891e2c2e0..78c76cc8e5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.cpp @@ -73,14 +73,16 @@ namespace AzToolsFramework } PrefabDom oldData; - Retrieve(entityId, oldData); + AZ::EntityId oldParentId; + Retrieve(entityId, oldData, oldParentId); UpdateCache(entityId); PrefabDom newData; - Retrieve(entityId, newData); + AZ::EntityId newParentId; + Retrieve(entityId, newData, newParentId); - if (newData != oldData) + if (newData != oldData || oldParentId != newParentId) { // display a useful message AZ::Entity* entity = nullptr; @@ -106,7 +108,7 @@ namespace AzToolsFramework // Clear out newly generated data and // replace with original data to ensure debug mode has the same data as profile/release // in the event of the consistency check failing. - m_entitySavedStates[entityId] = AZStd::move(oldData); + m_entitySavedStates[entityId] = {AZStd::move(oldData), oldParentId}; #endif // ENABLE_UNDOCACHE_CONSISTENCY_CHECKS } @@ -140,10 +142,13 @@ namespace AzToolsFramework return; } + AZ::EntityId parentId; + AZ::TransformBus::EventResult(parentId, entityId, &AZ::TransformBus::Events::GetParentId); + // Capture it PrefabDom entityDom; m_instanceToTemplateInterface->GenerateDomForEntity(entityDom, *entity); - m_entitySavedStates.emplace(AZStd::make_pair(entityId, AZStd::move(entityDom))); + m_entitySavedStates[entityId] = {AZStd::move(entityDom), parentId}; AZLOG("Prefab Undo", "Correctly updated cache for entity of id %llu (%s)", static_cast(entityId), entity->GetName().c_str()); @@ -155,7 +160,7 @@ namespace AzToolsFramework m_entitySavedStates.erase(entityId); } - bool PrefabUndoCache::Retrieve(const AZ::EntityId& entityId, PrefabDom& outDom) + bool PrefabUndoCache::Retrieve(const AZ::EntityId& entityId, PrefabDom& outDom, AZ::EntityId& parentId) { auto it = m_entitySavedStates.find(entityId); @@ -164,14 +169,15 @@ namespace AzToolsFramework return false; } - outDom = AZStd::move(m_entitySavedStates[entityId]); + outDom = AZStd::move(m_entitySavedStates[entityId].dom); + parentId = m_entitySavedStates[entityId].parentId; m_entitySavedStates.erase(entityId); return true; } - void PrefabUndoCache::Store(const AZ::EntityId& entityId, PrefabDom&& dom) + void PrefabUndoCache::Store(const AZ::EntityId& entityId, PrefabDom&& dom, const AZ::EntityId& parentId) { - m_entitySavedStates.emplace(AZStd::make_pair(entityId, AZStd::move(dom))); + m_entitySavedStates[entityId] = {AZStd::move(dom), parentId}; } void PrefabUndoCache::Clear() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.h index 924c93f44b..3a3ac92d7c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.h @@ -46,14 +46,19 @@ namespace AzToolsFramework void Validate(const AZ::EntityId& entityId) override; // Retrieve the last known state for an entity - bool Retrieve(const AZ::EntityId& entityId, PrefabDom& outDom); + bool Retrieve(const AZ::EntityId& entityId, PrefabDom& outDom, AZ::EntityId& parentId); // Store dom as the cached state of entityId - void Store(const AZ::EntityId& entityId, PrefabDom&& dom); + void Store(const AZ::EntityId& entityId, PrefabDom&& dom, const AZ::EntityId& parentId); private: - typedef AZStd::unordered_map EntityDomMap; - EntityDomMap m_entitySavedStates; + struct PrefabUndoCacheItem + { + PrefabDom dom; + AZ::EntityId parentId; + }; + typedef AZStd::unordered_map EntityCache; + EntityCache m_entitySavedStates; InstanceEntityMapperInterface* m_instanceEntityMapperInterface = nullptr; InstanceToTemplateInterface* m_instanceToTemplateInterface = nullptr; From 3634277317fa1777cda9849175f1a3b0aeda1423 Mon Sep 17 00:00:00 2001 From: Eric Phister <52085794+amzn-phist@users.noreply.github.com> Date: Thu, 3 Jun 2021 16:15:46 -0500 Subject: [PATCH 486/811] Project dll is not loaded by the AP when opened from the launcher (#1123) * Fixes locating the project dll when using SDK SDK engine usage has project dll in the project build path, but searching for module filepaths for loading would have a passing SystemFile::Exists check but no full filepath was amended to the module. This causes the module to fail to load. * Fix locating project module for UnixLike platforms Fixes the issue with project-centric workflows running GameLauncher, and it opens AP which can't find the project dynamic module. From AP's perspective, the project module is not in the executable directory, which is in engine bin. The SystemFile::Exists check is true on the file because it uses the 'cwd'. In that situation, an absolute path must be obtained for the module to be loaded. * Add missing header to fix UnixLike builds * Applies a suggested change from PR Use operator-> on the AZStd::optional * Add semicolon to a class macro line Prevent auto formatting indenting the following line. --- .../Module/DynamicModuleHandle_UnixLike.cpp | 23 +++++++++++++------ .../Module/DynamicModuleHandle_WinAPI.cpp | 16 ++++++++++--- 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Module/DynamicModuleHandle_UnixLike.cpp b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Module/DynamicModuleHandle_UnixLike.cpp index 8e2b40aaca..f9da818b4f 100644 --- a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Module/DynamicModuleHandle_UnixLike.cpp +++ b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Module/DynamicModuleHandle_UnixLike.cpp @@ -13,9 +13,10 @@ #include #include #include - #include #include +#include + #include #include @@ -61,10 +62,11 @@ namespace AZ // If it doesn't attempt to append the path to the executable path if (!AZ::IO::SystemFile::Exists(fullFilePath.c_str())) { - auto candidatePath = Platform::GetModulePath() / fullFilePath; + AZ::IO::FixedMaxPath candidatePath = Platform::GetModulePath() / fullFilePath; if (AZ::IO::SystemFile::Exists(candidatePath.c_str())) { - fullFilePath = candidatePath; + m_fileName.assign(candidatePath.Native().c_str(), candidatePath.Native().size()); + return; } } @@ -74,19 +76,26 @@ namespace AZ { if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { - if(AZ::IO::FixedMaxPath projectModulePath; + if (AZ::IO::FixedMaxPath projectModulePath; settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath)) { projectModulePath /= fullFilePath; if (AZ::IO::SystemFile::Exists(projectModulePath.c_str())) { - fullFilePath = projectModulePath; + m_fileName.assign(projectModulePath.c_str(), projectModulePath.Native().size()); } } } } - - m_fileName = AZStd::string_view{fullFilePath.Native()}; + else + { + // The module does exist (in 'cwd'), but still needs to be an absolute path for the module to be loaded. + AZStd::optional absPathOptional = AZ::Utils::ConvertToAbsolutePath(m_fileName); + if (absPathOptional.has_value()) + { + m_fileName.assign(absPathOptional->c_str(), absPathOptional->size()); + } + } } ~DynamicModuleHandleUnixLike() override diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp index 9daabfb86b..aeb8a81d09 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp @@ -24,9 +24,9 @@ namespace AZ : public DynamicModuleHandle { public: - AZ_CLASS_ALLOCATOR(DynamicModuleHandleWindows, OSAllocator, 0) + AZ_CLASS_ALLOCATOR(DynamicModuleHandleWindows, OSAllocator, 0); - DynamicModuleHandleWindows(const char* fullFileName) + DynamicModuleHandleWindows(const char* fullFileName) : DynamicModuleHandle(fullFileName) , m_handle(nullptr) { @@ -52,6 +52,7 @@ namespace AZ if (AZ::IO::SystemFile::Exists(candidatePath.c_str())) { m_fileName.assign(candidatePath.Native().c_str(), candidatePath.Native().size()); + return; } } } @@ -65,7 +66,7 @@ namespace AZ // Therefore an existence check is needed if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { - if(AZ::IO::FixedMaxPath projectModulePath; + if (AZ::IO::FixedMaxPath projectModulePath; settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath)) { projectModulePath /= AZStd::string_view(m_fileName); @@ -76,6 +77,15 @@ namespace AZ } } } + else + { + // The module does exist (in 'cwd'), but still needs to be an absolute path for the module to be loaded. + AZStd::optional absPathOptional = AZ::Utils::ConvertToAbsolutePath(m_fileName); + if (absPathOptional.has_value()) + { + m_fileName.assign(absPathOptional->c_str(), absPathOptional->size()); + } + } } ~DynamicModuleHandleWindows() override From c55f65b78ff1dbc36de9654af0b8e429a206ca42 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Thu, 3 Jun 2021 15:35:16 -0700 Subject: [PATCH 487/811] Integrate parts of Session Server API --- .../Source/MultiplayerSystemComponent.cpp | 28 +++++++++++++++++++ .../Code/Source/MultiplayerSystemComponent.h | 14 ++++++++++ 2 files changed, 42 insertions(+) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 0818f605df..50da2136fb 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -29,6 +29,8 @@ #include #include #include +#include +#include #include #include @@ -142,6 +144,7 @@ namespace Multiplayer void MultiplayerSystemComponent::Activate() { AZ::TickBus::Handler::BusConnect(); + AzFramework::SessionNotificationBus::Handler::BusConnect(); m_networkInterface = AZ::Interface::Get()->CreateNetworkInterface(AZ::Name(MPNetworkInterfaceName), sv_protocol, TrustZone::ExternalClientToServer, *this); m_consoleCommandHandler.Connect(AZ::Interface::Get()->GetConsoleCommandInvokedEvent()); AZ::Interface::Register(this); @@ -153,9 +156,34 @@ namespace Multiplayer void MultiplayerSystemComponent::Deactivate() { AZ::Interface::Unregister(this); + AzFramework::SessionNotificationBus::Handler::BusDisconnect(); AZ::TickBus::Handler::BusDisconnect(); } + bool MultiplayerSystemComponent::OnSessionHealthCheck() + { + return true; + } + + bool MultiplayerSystemComponent::OnCreateSessionBegin(const AzFramework::SessionConfig& sessionConfig) + { + Multiplayer::MultiplayerAgentType serverType = sv_isDedicated ? MultiplayerAgentType::DedicatedServer : MultiplayerAgentType::ClientServer; + AZ::Interface::Get()->InitializeMultiplayer(serverType); + return m_networkInterface->Listen(sessionConfig.m_port); + } + + bool MultiplayerSystemComponent::OnDestroySessionBegin() + { + bool disconnectSuccessful = true; + IConnectionSet& connectionSet = m_networkInterface->GetConnectionSet(); + connectionSet.VisitConnections([&disconnectSuccessful](IConnection& connection) + { + bool didDisconnect = connection.Disconnect(DisconnectReason::TerminatedByServer, TerminationEndpoint::Remote); + disconnectSuccessful = disconnectSuccessful && didDisconnect; + }); + return disconnectSuccessful; + } + void MultiplayerSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { AZ::TimeMs deltaTimeMs = aznumeric_cast(static_cast(deltaTime * 1000.0f)); diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index e8e05a9d4c..bd989cf841 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -25,8 +25,14 @@ #include #include #include +#include #include +namespace AzFramework +{ + struct SessionConfig; +} + namespace AzNetworking { class INetworkInterface; @@ -38,6 +44,7 @@ namespace Multiplayer class MultiplayerSystemComponent final : public AZ::Component , public AZ::TickBus::Handler + , public AzFramework::SessionNotificationBus::Handler , public AzNetworking::IConnectionListener , public IMultiplayer { @@ -58,6 +65,13 @@ namespace Multiplayer void Deactivate() override; //! @} + //! AzFramework::SessionNotificationBus::Handler overrides. + //! @{ + bool OnSessionHealthCheck() override; + bool OnCreateSessionBegin(const AzFramework::SessionConfig& sessionConfig) override; + bool OnDestroySessionBegin() override; + //! @} + //! AZ::TickBus::Handler overrides. //! @{ void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; From d1f23aff62c4644ba7b3f9f8386c8014479f8b3b Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Thu, 3 Jun 2021 17:38:22 -0500 Subject: [PATCH 488/811] SPEC-7008: Excluding more main tests from Debug test runs --- .../Gem/PythonTests/editor/test_BasicEditorWorkflows.py | 5 +++++ .../largeworlds/landscape_canvas/test_GraphComponentSync.py | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/editor/test_BasicEditorWorkflows.py b/AutomatedTesting/Gem/PythonTests/editor/test_BasicEditorWorkflows.py index b045b364a3..f65401f007 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/test_BasicEditorWorkflows.py +++ b/AutomatedTesting/Gem/PythonTests/editor/test_BasicEditorWorkflows.py @@ -15,6 +15,7 @@ import pytest # Bail on the test if ly_test_tools doesn't exist. pytest.importorskip('ly_test_tools') import ly_test_tools.environment.file_system as file_system +import ly_test_tools._internal.pytest_plugin as internal_plugin import editor_python_test_tools.hydra_test_utils as hydra test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") @@ -40,6 +41,10 @@ class TestBasicEditorWorkflows(object): @pytest.mark.SUITE_main def test_BasicEditorWorkflows_LevelEntityComponentCRUD(self, request, editor, level, launcher_platform): + # Skip test if running against Debug build + if "debug" in internal_plugin.build_directory: + pytest.skip("Does not execute against debug builds.") + expected_lines = [ "Create and load new level: True", "New entity creation: True", diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py index 943d0cb985..e7dc046480 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py @@ -132,7 +132,7 @@ class TestGraphComponentSync(object): # Skip test if running against Debug build if "debug" in internal_plugin.build_directory: pytest.skip("Does not execute against debug builds.") - + cfg_args = [level] expected_lines = [ From 792176d7640d3b5ac80f8da82c9a407da3705272 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Thu, 3 Jun 2021 16:02:16 -0700 Subject: [PATCH 489/811] Cached occlusion plane corner points and AABB in the feature processor --- .../OcclusionCullingPlaneFeatureProcessor.cpp | 49 ++++++++++++++++-- .../OcclusionCullingPlaneFeatureProcessor.h | 4 ++ .../Code/Include/Atom/RPI.Public/Culling.h | 16 +++++- .../RPI/Code/Source/RPI.Public/Culling.cpp | 51 +++++-------------- 4 files changed, 76 insertions(+), 44 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp index b9866a925f..ff7c32ba08 100644 --- a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp @@ -33,6 +33,7 @@ namespace AZ void OcclusionCullingPlaneFeatureProcessor::Activate() { m_occlusionCullingPlanes.reserve(InitialOcclusionCullingPlanesAllocationSize); + m_rpiOcclusionPlanes.reserve(InitialOcclusionCullingPlanesAllocationSize); EnableSceneNotification(); } @@ -48,13 +49,46 @@ namespace AZ } void OcclusionCullingPlaneFeatureProcessor::OnBeginPrepareRender() - { - AZStd::vector occlusionCullingPlanes; - for (auto& occlusionCullingPlane : m_occlusionCullingPlanes) + { + if (m_rpiListNeedsUpdate) { - occlusionCullingPlanes.push_back(occlusionCullingPlane->GetTransform()); + // rebuild the RPI occlusion list + m_rpiOcclusionPlanes.clear(); + + for (auto& occlusionCullingPlane : m_occlusionCullingPlanes) + { + if (!occlusionCullingPlane->GetEnabled()) + { + continue; + } + + RPI::CullingScene::OcclusionPlane rpiOcclusionPlane; + + static const Vector3 BL = Vector3(-0.5f, -0.5f, 0.0f); + static const Vector3 BR = Vector3(0.5f, -0.5f, 0.0f); + static const Vector3 TL = Vector3(-0.5f, 0.5f, 0.0f); + static const Vector3 TR = Vector3(0.5f, 0.5f, 0.0f); + + const AZ::Transform& transform = occlusionCullingPlane->GetTransform(); + + // convert corners to world space + rpiOcclusionPlane.m_cornerBL = transform.TransformPoint(BL); + rpiOcclusionPlane.m_cornerBR = transform.TransformPoint(BR); + rpiOcclusionPlane.m_cornerTL = transform.TransformPoint(TL); + rpiOcclusionPlane.m_cornerTR = transform.TransformPoint(TR); + + // build world space AABB + AZ::Vector3 aabbMin = rpiOcclusionPlane.m_cornerBL.GetMin(rpiOcclusionPlane.m_cornerTR); + AZ::Vector3 aabbMax = rpiOcclusionPlane.m_cornerBL.GetMax(rpiOcclusionPlane.m_cornerTR); + rpiOcclusionPlane.m_aabb = Aabb::CreateFromMinMax(aabbMin, aabbMax); + + m_rpiOcclusionPlanes.push_back(rpiOcclusionPlane); + } + + GetParentScene()->GetCullingScene()->SetOcclusionPlanes(m_rpiOcclusionPlanes); + + m_rpiListNeedsUpdate = false; } - GetParentScene()->GetCullingScene()->SetOcclusionCullingPlanes(occlusionCullingPlanes); } OcclusionCullingPlaneHandle OcclusionCullingPlaneFeatureProcessor::AddOcclusionCullingPlane(const AZ::Transform& transform) @@ -63,6 +97,8 @@ namespace AZ occlusionCullingPlane->Init(GetParentScene()); occlusionCullingPlane->SetTransform(transform); m_occlusionCullingPlanes.push_back(occlusionCullingPlane); + m_rpiListNeedsUpdate = true; + return occlusionCullingPlane; } @@ -78,18 +114,21 @@ namespace AZ AZ_Assert(itEntry != m_occlusionCullingPlanes.end(), "RemoveOcclusionCullingPlane called with an occlusion plane that is not in the occlusion plane list"); m_occlusionCullingPlanes.erase(itEntry); occlusionCullingPlane = nullptr; + m_rpiListNeedsUpdate = true; } void OcclusionCullingPlaneFeatureProcessor::SetTransform(const OcclusionCullingPlaneHandle& occlusionCullingPlane, const AZ::Transform& transform) { AZ_Assert(occlusionCullingPlane.get(), "SetTransform called with an invalid handle"); occlusionCullingPlane->SetTransform(transform); + m_rpiListNeedsUpdate = true; } void OcclusionCullingPlaneFeatureProcessor::SetEnabled(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool enabled) { AZ_Assert(occlusionCullingPlane.get(), "Enable called with an invalid handle"); occlusionCullingPlane->SetEnabled(enabled); + m_rpiListNeedsUpdate = true; } void OcclusionCullingPlaneFeatureProcessor::ShowVisualization(const OcclusionCullingPlaneHandle& occlusionCullingPlane, bool showVisualization) diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h index 211254742f..8b3ac3f58d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.h @@ -57,6 +57,10 @@ namespace AZ // list of occlusion planes const size_t InitialOcclusionCullingPlanesAllocationSize = 64; OcclusionCullingPlaneVector m_occlusionCullingPlanes; + + // prebuilt list of RPI scene occlusion planes + RPI::CullingScene::OcclusionPlaneVector m_rpiOcclusionPlanes; + bool m_rpiListNeedsUpdate = false; }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h index 295797d2dd..2a9c133b5c 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h @@ -215,8 +215,20 @@ namespace AZ void Activate(const class Scene* parentScene); void Deactivate(); + struct OcclusionPlane + { + // World space corners of the occluson plane + Vector3 m_cornerBL; + Vector3 m_cornerBR; + Vector3 m_cornerTL; + Vector3 m_cornerTR; + + Aabb m_aabb; + }; + using OcclusionPlaneVector = AZStd::vector; + //! Sets a list of occlusion planes to be used during the culling process. - void SetOcclusionCullingPlanes(const AZStd::vector& occlusionCullingPlanes) { m_occlusionCullingPlanes = occlusionCullingPlanes; } + void SetOcclusionPlanes(const OcclusionPlaneVector& occlusionPlanes) { m_occlusionPlanes = occlusionPlanes; } //! Notifies the CullingScene that culling will begin for this frame. void BeginCulling(const AZStd::vector& views); @@ -258,7 +270,7 @@ namespace AZ AzFramework::IVisibilityScene* m_visScene = nullptr; CullingDebugContext m_debugCtx; AZStd::concurrency_checker m_cullDataConcurrencyCheck; - AZStd::vector m_occlusionCullingPlanes; + OcclusionPlaneVector m_occlusionPlanes; }; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index 3f28805888..7ee2c4a8d2 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -546,60 +546,37 @@ namespace AZ #if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED // setup occlusion culling, if necessary - MaskedOcclusionCulling* maskedOcclusionCulling = m_occlusionCullingPlanes.empty() ? nullptr : view.GetMaskedOcclusionCulling(); + MaskedOcclusionCulling* maskedOcclusionCulling = m_occlusionPlanes.empty() ? nullptr : view.GetMaskedOcclusionCulling(); if (maskedOcclusionCulling) { // frustum cull occlusion planes - using OccluderEntry = AZStd::pair; - AZStd::vector visibleOccluders; - for (const AZ::Transform& transform : m_occlusionCullingPlanes) + using VisibleOcclusionPlane = AZStd::pair; + AZStd::vector visibleOccluders; + for (const auto& occlusionPlane : m_occlusionPlanes) { - static const AZ::Vector3 BL(-0.5f, -0.5f, 0.0f); - static const AZ::Vector3 TR(0.5f, 0.5f, 0.0f); - - AZ::Vector3 P1 = transform.TransformPoint(BL); - AZ::Vector3 P2 = transform.TransformPoint(TR); - - AZ::Vector3 aabbMin = P1.GetMin(P2); - AZ::Vector3 aabbMax = P1.GetMax(P2); - - AZ::Aabb occluderAabb = Aabb::CreateFromMinMax(aabbMin, aabbMax); - if (ShapeIntersection::Overlaps(frustum, occluderAabb)) + if (ShapeIntersection::Overlaps(frustum, occlusionPlane.m_aabb)) { // occluder is visible, compute view space distance and add to list - float depth = (view.GetWorldToViewMatrix() * occluderAabb.GetMin()).GetZ(); - depth = AZStd::min(depth, (view.GetWorldToViewMatrix() * occluderAabb.GetMax()).GetZ()); + float depth = (view.GetWorldToViewMatrix() * occlusionPlane.m_aabb.GetMin()).GetZ(); + depth = AZStd::min(depth, (view.GetWorldToViewMatrix() * occlusionPlane.m_aabb.GetMax()).GetZ()); - visibleOccluders.push_back(AZStd::make_pair(transform, depth)); + visibleOccluders.push_back(AZStd::make_pair(occlusionPlane, depth)); } } // sort the occlusion planes by view space distance, front-to-back - AZStd::sort(visibleOccluders.begin(), visibleOccluders.end(), [](const OccluderEntry& LHS, const OccluderEntry& RHS) + AZStd::sort(visibleOccluders.begin(), visibleOccluders.end(), [](const VisibleOcclusionPlane& LHS, const VisibleOcclusionPlane& RHS) { return LHS.second > RHS.second; }); - for (const OccluderEntry& occluder : visibleOccluders) + for (const VisibleOcclusionPlane& occlusionPlane: visibleOccluders) { - const AZ::Transform& transform = occluder.first; - - // find the corners of the plane - static const Vector3 BL = Vector3(-0.5f, -0.5f, 0.0f); - static const Vector3 BR = Vector3(0.5f, -0.5f, 0.0f); - static const Vector3 TL = Vector3(-0.5f, 0.5f, 0.0f); - static const Vector3 TR = Vector3(0.5f, 0.5f, 0.0f); - - Vector3 planeBL = transform.TransformPoint(BL); - Vector3 planeBR = transform.TransformPoint(BR); - Vector3 planeTL = transform.TransformPoint(TL); - Vector3 planeTR = transform.TransformPoint(TR); - // convert to clip-space - Vector4 projectedBL = view.GetWorldToClipMatrix() * Vector4(planeBL); - Vector4 projectedBR = view.GetWorldToClipMatrix() * Vector4(planeBR); - Vector4 projectedTL = view.GetWorldToClipMatrix() * Vector4(planeTL); - Vector4 projectedTR = view.GetWorldToClipMatrix() * Vector4(planeTR); + Vector4 projectedBL = view.GetWorldToClipMatrix() * Vector4(occlusionPlane.first.m_cornerBL); + Vector4 projectedBR = view.GetWorldToClipMatrix() * Vector4(occlusionPlane.first.m_cornerBR); + Vector4 projectedTL = view.GetWorldToClipMatrix() * Vector4(occlusionPlane.first.m_cornerTL); + Vector4 projectedTR = view.GetWorldToClipMatrix() * Vector4(occlusionPlane.first.m_cornerTR); // store to float array float verts[16]; From 85e6d06c2c203b7883053f97e8827689e10a5ae2 Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 3 Jun 2021 16:09:10 -0700 Subject: [PATCH 490/811] [default_3rdparty] add 3rd party to engine registration + specific path registration fixes --- .../ProjectManager/Source/PythonBindings.cpp | 22 +++--------- scripts/o3de/o3de/manifest.py | 8 +++++ scripts/o3de/o3de/register.py | 35 +++++++++++++++---- 3 files changed, 42 insertions(+), 23 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 7062d886da..e2c84b2b5f 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -383,7 +383,7 @@ namespace O3DE::ProjectManager engineInfo.m_defaultProjectsFolder = Py_To_String(o3deData["default_projects_folder"]); engineInfo.m_defaultRestrictedFolder = Py_To_String(o3deData["default_restricted_folder"]); engineInfo.m_defaultTemplatesFolder = Py_To_String(o3deData["default_templates_folder"]); - engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData,"third_party_path",""); + engineInfo.m_thirdPartyPath = Py_To_String(o3deData["default_third_party_folder"]); } auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath); @@ -420,6 +420,7 @@ namespace O3DE::ProjectManager pybind11::str defaultProjectsFolder = engineInfo.m_defaultProjectsFolder.toStdString(); pybind11::str defaultGemsFolder = engineInfo.m_defaultGemsFolder.toStdString(); pybind11::str defaultTemplatesFolder = engineInfo.m_defaultTemplatesFolder.toStdString(); + pybind11::str defaultThridPartyFolder = engineInfo.m_thirdPartyPath.toStdString(); auto registrationResult = m_register.attr("register")( enginePath, // engine_path @@ -432,28 +433,15 @@ namespace O3DE::ProjectManager pybind11::none(), // default_engines_folder defaultProjectsFolder, defaultGemsFolder, - defaultTemplatesFolder + defaultTemplatesFolder, + pybind11::none(), // default_restricted_folder + defaultThridPartyFolder ); if (registrationResult.cast() != 0) { result = false; } - - auto manifest = m_manifest.attr("load_o3de_manifest")(); - if (pybind11::isinstance(manifest)) - { - try - { - manifest["third_party_path"] = engineInfo.m_thirdPartyPath.toStdString(); - m_manifest.attr("save_o3de_manifest")(manifest); - } - catch ([[maybe_unused]] const std::exception& e) - { - AZ_Warning("PythonBindings", false, "Failed to set third party path."); - } - } - }); return result; diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index edcd44c525..3fa21721c2 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -97,6 +97,12 @@ def get_o3de_logs_folder() -> pathlib.Path: return logs_folder +def get_o3de_third_party_folder() -> pathlib.Path: + third_party_folder = get_o3de_folder() / '3rdParty' + third_party_folder.mkdir(parents=True, exist_ok=True) + return third_party_folder + + # o3de manifest file methods def get_o3de_manifest() -> pathlib.Path: manifest_path = get_o3de_folder() / 'o3de_manifest.json' @@ -113,6 +119,7 @@ def get_o3de_manifest() -> pathlib.Path: default_gems_folder = get_o3de_gems_folder() default_templates_folder = get_o3de_templates_folder() default_restricted_folder = get_o3de_restricted_folder() + default_third_party_folder = get_o3de_third_party_folder() default_projects_restricted_folder = default_projects_folder / 'Restricted' default_projects_restricted_folder.mkdir(parents=True, exist_ok=True) @@ -129,6 +136,7 @@ def get_o3de_manifest() -> pathlib.Path: json_data.update({'default_gems_folder': default_gems_folder.as_posix()}) json_data.update({'default_templates_folder': default_templates_folder.as_posix()}) json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) + json_data.update({'default_third_party_folder': default_third_party_folder.as_posix()}) json_data.update({'projects': []}) json_data.update({'external_subdirectories': []}) diff --git a/scripts/o3de/o3de/register.py b/scripts/o3de/o3de/register.py index 68575488dc..2e37f04acf 100644 --- a/scripts/o3de/o3de/register.py +++ b/scripts/o3de/o3de/register.py @@ -486,7 +486,7 @@ def register_default_engines_folder(json_data: dict, remove: bool = False) -> int: return register_default_o3de_object_folder(json_data, manifest.get_o3de_engines_folder() if remove else default_engines_folder, - 'default_engines_folder', remove) + 'default_engines_folder') def register_default_projects_folder(json_data: dict, @@ -494,7 +494,7 @@ def register_default_projects_folder(json_data: dict, remove: bool = False) -> int: return register_default_o3de_object_folder(json_data, manifest.get_o3de_projects_folder() if remove else default_projects_folder, - 'default_projects_folder', remove) + 'default_projects_folder') def register_default_gems_folder(json_data: dict, @@ -502,7 +502,7 @@ def register_default_gems_folder(json_data: dict, remove: bool = False) -> int: return register_default_o3de_object_folder(json_data, manifest.get_o3de_gems_folder() if remove else default_gems_folder, - 'default_gems_folder', remove) + 'default_gems_folder') def register_default_templates_folder(json_data: dict, @@ -510,16 +510,22 @@ def register_default_templates_folder(json_data: dict, remove: bool = False) -> int: return register_default_o3de_object_folder(json_data, manifest.get_o3de_templates_folder() if remove else default_templates_folder, - 'default_templates_folder', remove) + 'default_templates_folder') def register_default_restricted_folder(json_data: dict, default_restricted_folder: str or pathlib.Path, - reset_to_default: bool = False) -> int: + remove: bool = False) -> int: return register_default_o3de_object_folder(json_data, manifest.get_o3de_restricted_folder() if remove else default_restricted_folder, - 'default_restricted_folder', remove) + 'default_restricted_folder') +def register_default_third_party_folder(json_data: dict, + default_third_party_folder: str or pathlib.Path, + remove: bool = False) -> int: + return register_default_o3de_object_folder(json_data, + manifest.get_o3de_third_party_folder() if remove else default_third_party_folder, + 'default_third_party_folder') def register(engine_path: str or pathlib.Path = None, project_path: str or pathlib.Path = None, @@ -533,6 +539,7 @@ def register(engine_path: str or pathlib.Path = None, default_gems_folder: str or pathlib.Path = None, default_templates_folder: str or pathlib.Path = None, default_restricted_folder: str or pathlib.Path = None, + default_third_party_folder: str or pathlib.Path = None, external_subdir_engine_path: pathlib.Path = None, external_subdir_project_path: pathlib.Path = None, remove: bool = False, @@ -553,6 +560,7 @@ def register(engine_path: str or pathlib.Path = None, :param default_gems_folder: default gems folder :param default_templates_folder: default templates folder :param default_restricted_folder: default restricted code folder + :param default_third_party_folder: default 3rd party cache folder :param external_subdir_engine_path: Path to the engine to use when registering an external subdirectory. The registration occurs in the engine.json file in this case :param external_subdir_engine_path: Path to the project to use when registering an external subdirectory. @@ -620,6 +628,9 @@ def register(engine_path: str or pathlib.Path = None, elif isinstance(default_restricted_folder, str) or isinstance(default_restricted_folder, pathlib.PurePath): result = register_default_restricted_folder(json_data, default_restricted_folder, remove) + elif isinstance(default_third_party_folder, str) or isinstance(default_third_party_folder, pathlib.PurePath): + result = register_default_third_party_folder(json_data, default_third_party_folder, remove) + # engine is done LAST # Now that everything that could have an engine context is done, if the engine is supplied that means this is # registering the engine itself @@ -712,6 +723,15 @@ def remove_invalid_o3de_objects() -> None: f" Set default {default_restricted_folder}") register(default_restricted_folder=default_restricted_folder.as_posix()) + default_third_party_folder = pathlib.Path(json_data['default_third_party_folder']).resolve() + if not default_third_party_folder.is_dir(): + default_third_party_folder = manifest.get_o3de_folder() / '3rdParty' + default_third_party_folder.mkdir(parents=True, exist_ok=True) + logger.warn( + f"Default 3rd Party folder {default_third_party_folder} is invalid." + f" Set default {default_third_party_folder}") + register(default_third_party_folder=default_third_party_folder.as_posix()) + def _run_register(args: argparse) -> int: if args.override_home_folder: @@ -751,6 +771,7 @@ def _run_register(args: argparse) -> int: default_gems_folder=args.default_gems_folder, default_templates_folder=args.default_templates_folder, default_restricted_folder=args.default_restricted_folder, + default_third_party_folder=args.default_third_party_folder, external_subdir_engine_path=args.external_subdirectory_engine_path, external_subdir_project_path=args.external_subdirectory_project_path, remove=args.remove, @@ -804,6 +825,8 @@ def add_parser_args(parser): help='The default templates folder to register/remove.') group.add_argument('-drf', '--default-restricted-folder', type=str, required=False, help='The default restricted folder to register/remove.') + group.add_argument('-dtpf', '--default-third-party-folder', type=str, required=False, + help='The default 3rd Party folder to register/remove.') group.add_argument('-u', '--update', action='store_true', required=False, default=False, help='Refresh the repo cache.') From 816d05ef2d85843c86fd47265cc8cf1a3b55c3c5 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 3 Jun 2021 18:16:22 -0500 Subject: [PATCH 491/811] Updating manifest.py template query functions (#1113) * Updating manifest.py template query functions The get_project_templates, get_gem_templates and get_generic_templates methods have been renamed to indicate that the methods return the templates that can be used in a create-project, create-gem and create-from-template command of the engine_template.py Updated the print_registration.py script to support outputing project specific gems and templates. Add a unit test script for the manifest.py script. Added unit test to validate the new functions: `get_templates_for_project_creation` `get_templates_for_gem_creation` `get_templates_for_generic_creation` * Implementing the project print registration methods Added implementations of the project print registration methods and tested them locally Removed implementations of the download print registration methods, since they have not went through app-sec review. * Renaming get_restricted_data to get_restricted_json_data Fixed the get_registered method in manifest.py when looking up projects * Updated the print_manifest_json_data calls to return the result --- .../ProjectManager/Source/PythonBindings.cpp | 215 ++++---- scripts/o3de/o3de/manifest.py | 97 ++-- scripts/o3de/o3de/print_registration.py | 496 +++++++++--------- scripts/o3de/tests/CMakeLists.txt | 7 + scripts/o3de/tests/unit_test_manifest.py | 111 ++++ scripts/o3de/tests/unit_test_utils.py | 2 +- 6 files changed, 542 insertions(+), 386 deletions(-) create mode 100644 scripts/o3de/tests/unit_test_manifest.py diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 7062d886da..18b29c496f 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -294,7 +294,8 @@ namespace O3DE::ProjectManager RegisterThisEngine(); return result == 0 && !PyErr_Occurred(); - } catch ([[maybe_unused]] const std::exception& e) + } + catch ([[maybe_unused]] const std::exception& e) { AZ_Warning("ProjectManagerWindow", false, "Py_Initialize() failed with %s", e.what()); return false; @@ -320,25 +321,25 @@ namespace O3DE::ProjectManager bool registrationResult = true; // already registered is considered successful bool pythonResult = ExecuteWithLock( [&] + { + // check current engine path against all other registered engines + // to see if we are already registered + auto allEngines = m_manifest.attr("get_engines")(); + if (pybind11::isinstance(allEngines)) { - // check current engine path against all other registered engines - // to see if we are already registered - auto allEngines = m_manifest.attr("get_engines")(); - if (pybind11::isinstance(allEngines)) + for (auto engine : allEngines) { - for (auto engine : allEngines) + AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"])); + if (enginePath.Compare(m_enginePath) == 0) { - AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"])); - if (enginePath.Compare(m_enginePath) == 0) - { - return; - } + return; } } + } - auto result = m_register.attr("register")(m_enginePath.c_str()); - registrationResult = (result.cast() == 0); - }); + auto result = m_register.attr("register")(m_enginePath.c_str()); + registrationResult = (result.cast() == 0); + }); bool finalResult = (registrationResult && pythonResult); AZ_Assert(finalResult, "Registration of this engine failed!"); @@ -378,12 +379,12 @@ namespace O3DE::ProjectManager auto o3deData = m_manifest.attr("load_o3de_manifest")(); if (pybind11::isinstance(o3deData)) { - engineInfo.m_path = Py_To_String(enginePath); - engineInfo.m_defaultGemsFolder = Py_To_String(o3deData["default_gems_folder"]); - engineInfo.m_defaultProjectsFolder = Py_To_String(o3deData["default_projects_folder"]); + engineInfo.m_path = Py_To_String(enginePath); + engineInfo.m_defaultGemsFolder = Py_To_String(o3deData["default_gems_folder"]); + engineInfo.m_defaultProjectsFolder = Py_To_String(o3deData["default_projects_folder"]); engineInfo.m_defaultRestrictedFolder = Py_To_String(o3deData["default_restricted_folder"]); - engineInfo.m_defaultTemplatesFolder = Py_To_String(o3deData["default_templates_folder"]); - engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData,"third_party_path",""); + engineInfo.m_defaultTemplatesFolder = Py_To_String(o3deData["default_templates_folder"]); + engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData, "third_party_path", ""); } auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath); @@ -391,8 +392,8 @@ namespace O3DE::ProjectManager { try { - engineInfo.m_version = Py_To_String_Optional(engineData,"O3DEVersion","0.0.0.0"); - engineInfo.m_name = Py_To_String_Optional(engineData,"engine_name","O3DE"); + engineInfo.m_version = Py_To_String_Optional(engineData, "O3DEVersion", "0.0.0.0"); + engineInfo.m_name = Py_To_String_Optional(engineData, "engine_name", "O3DE"); } catch ([[maybe_unused]] const std::exception& e) { @@ -416,19 +417,19 @@ namespace O3DE::ProjectManager bool PythonBindings::SetEngineInfo(const EngineInfo& engineInfo) { bool result = ExecuteWithLock([&] { - pybind11::str enginePath = engineInfo.m_path.toStdString(); - pybind11::str defaultProjectsFolder = engineInfo.m_defaultProjectsFolder.toStdString(); - pybind11::str defaultGemsFolder = engineInfo.m_defaultGemsFolder.toStdString(); + pybind11::str enginePath = engineInfo.m_path.toStdString(); + pybind11::str defaultProjectsFolder = engineInfo.m_defaultProjectsFolder.toStdString(); + pybind11::str defaultGemsFolder = engineInfo.m_defaultGemsFolder.toStdString(); pybind11::str defaultTemplatesFolder = engineInfo.m_defaultTemplatesFolder.toStdString(); auto registrationResult = m_register.attr("register")( - enginePath, // engine_path - pybind11::none(), // project_path + enginePath, // engine_path + pybind11::none(), // project_path pybind11::none(), // gem_path - pybind11::none(), // external_subdir_path - pybind11::none(), // template_path - pybind11::none(), // restricted_path - pybind11::none(), // repo_uri + pybind11::none(), // external_subdir_path + pybind11::none(), // template_path + pybind11::none(), // restricted_path + pybind11::none(), // repo_uri pybind11::none(), // default_engines_folder defaultProjectsFolder, defaultGemsFolder, @@ -477,12 +478,12 @@ namespace O3DE::ProjectManager QVector gems; auto result = ExecuteWithLockErrorHandling([&] + { + for (auto path : m_manifest.attr("get_engine_gems")()) { - for (auto path : m_manifest.attr("get_engine_gems")()) - { - gems.push_back(GemInfoFromPath(path)); - } - }); + gems.push_back(GemInfoFromPath(path)); + } + }); if (!result.IsSuccess()) { return AZ::Failure(result.GetError().c_str()); @@ -497,13 +498,13 @@ namespace O3DE::ProjectManager QVector gems; auto result = ExecuteWithLockErrorHandling([&] + { + pybind11::str pyProjectPath = projectPath.toStdString(); + for (auto path : m_manifest.attr("get_all_gems")(pyProjectPath)) { - pybind11::str pyProjectPath = projectPath.toStdString(); - for (auto path : m_manifest.attr("get_all_gems")(pyProjectPath)) - { - gems.push_back(GemInfoFromPath(path)); - } - }); + gems.push_back(GemInfoFromPath(path)); + } + }); if (!result.IsSuccess()) { return AZ::Failure(result.GetError().c_str()); @@ -518,12 +519,12 @@ namespace O3DE::ProjectManager // Retrieve the path to the cmake file that lists the enabled gems. pybind11::str enabledGemsFilename; auto result = ExecuteWithLockErrorHandling([&] - { - const pybind11::str pyProjectPath = projectPath.toStdString(); - enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")( - pybind11::none(), // project_name - pyProjectPath); // project_path - }); + { + const pybind11::str pyProjectPath = projectPath.toStdString(); + enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")( + pybind11::none(), // project_name + pyProjectPath); // project_path + }); if (!result.IsSuccess()) { return AZ::Failure(result.GetError().c_str()); @@ -532,13 +533,13 @@ namespace O3DE::ProjectManager // Retrieve the actual list of names from the cmake file. QVector gemNames; result = ExecuteWithLockErrorHandling([&] + { + const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename); + for (auto gemName : pyGemNames) { - const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename); - for (auto gemName : pyGemNames) - { - gemNames.push_back(Py_To_String(gemName)); - } - }); + gemNames.push_back(Py_To_String(gemName)); + } + }); if (!result.IsSuccess()) { return AZ::Failure(result.GetError().c_str()); @@ -552,13 +553,13 @@ namespace O3DE::ProjectManager bool registrationResult = false; bool result = ExecuteWithLock( [&] - { - pybind11::str projectPath = path.toStdString(); - auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath); + { + pybind11::str projectPath = path.toStdString(); + auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath); - // Returns an exit code so boolify it then invert result - registrationResult = !pythonRegistrationResult.cast(); - }); + // Returns an exit code so boolify it then invert result + registrationResult = !pythonRegistrationResult.cast(); + }); return result && registrationResult; } @@ -568,30 +569,30 @@ namespace O3DE::ProjectManager bool registrationResult = false; bool result = ExecuteWithLock( [&] - { - pybind11::str projectPath = path.toStdString(); - auto pythonRegistrationResult = m_register.attr("register")( - pybind11::none(), // engine_path - projectPath, // project_path - pybind11::none(), // gem_path - pybind11::none(), // external_subdir_path - pybind11::none(), // template_path - pybind11::none(), // restricted_path - pybind11::none(), // repo_uri - pybind11::none(), // default_engines_folder - pybind11::none(), // default_projects_folder - pybind11::none(), // default_gems_folder - pybind11::none(), // default_templates_folder - pybind11::none(), // default_restricted_folder - pybind11::none(), // external_subdir_engine_path - pybind11::none(), // external_subdir_project_path - true, // remove - false // force + { + pybind11::str projectPath = path.toStdString(); + auto pythonRegistrationResult = m_register.attr("register")( + pybind11::none(), // engine_path + projectPath, // project_path + pybind11::none(), // gem_path + pybind11::none(), // external_subdir_path + pybind11::none(), // template_path + pybind11::none(), // restricted_path + pybind11::none(), // repo_uri + pybind11::none(), // default_engines_folder + pybind11::none(), // default_projects_folder + pybind11::none(), // default_gems_folder + pybind11::none(), // default_templates_folder + pybind11::none(), // default_restricted_folder + pybind11::none(), // external_subdir_engine_path + pybind11::none(), // external_subdir_project_path + true, // remove + false // force ); - - // Returns an exit code so boolify it then invert result - registrationResult = !pythonRegistrationResult.cast(); - }); + + // Returns an exit code so boolify it then invert result + registrationResult = !pythonRegistrationResult.cast(); + }); return result && registrationResult; } @@ -649,12 +650,12 @@ namespace O3DE::ProjectManager try { // required - gemInfo.m_name = Py_To_String(data["gem_name"]); + gemInfo.m_name = Py_To_String(data["gem_name"]); // optional gemInfo.m_displayName = Py_To_String_Optional(data, "DisplayName", gemInfo.m_name); - gemInfo.m_summary = Py_To_String_Optional(data, "Summary", ""); - gemInfo.m_version = Py_To_String_Optional(data, "Version", ""); + gemInfo.m_summary = Py_To_String_Optional(data, "Summary", ""); + gemInfo.m_version = Py_To_String_Optional(data, "Version", ""); if (data.contains("Tags")) { @@ -685,7 +686,7 @@ namespace O3DE::ProjectManager try { projectInfo.m_projectName = Py_To_String(projectData["project_name"]); - projectInfo.m_displayName = Py_To_String_Optional(projectData,"display_name", projectInfo.m_projectName); + projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName); } catch ([[maybe_unused]] const std::exception& e) { @@ -727,33 +728,33 @@ namespace O3DE::ProjectManager AZ::Outcome PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath) { return ExecuteWithLockErrorHandling([&] - { - pybind11::str pyGemPath = gemPath.toStdString(); - pybind11::str pyProjectPath = projectPath.toStdString(); + { + pybind11::str pyGemPath = gemPath.toStdString(); + pybind11::str pyProjectPath = projectPath.toStdString(); - m_enableGemProject.attr("enable_gem_in_project")( - pybind11::none(), // gem name not needed as path is provided - pyGemPath, - pybind11::none(), // project name not needed as path is provided - pyProjectPath + m_enableGemProject.attr("enable_gem_in_project")( + pybind11::none(), // gem name not needed as path is provided + pyGemPath, + pybind11::none(), // project name not needed as path is provided + pyProjectPath ); - }); + }); } AZ::Outcome PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath) { return ExecuteWithLockErrorHandling([&] - { - pybind11::str pyGemPath = gemPath.toStdString(); - pybind11::str pyProjectPath = projectPath.toStdString(); + { + pybind11::str pyGemPath = gemPath.toStdString(); + pybind11::str pyProjectPath = projectPath.toStdString(); - m_disableGemProject.attr("disable_gem_in_project")( - pybind11::none(), // gem name not needed as path is provided - pyGemPath, - pybind11::none(), // project name not needed as path is provided - pyProjectPath + m_disableGemProject.attr("disable_gem_in_project")( + pybind11::none(), // gem name not needed as path is provided + pyGemPath, + pybind11::none(), // project name not needed as path is provided + pyProjectPath ); - }); + }); } bool PythonBindings::UpdateProject([[maybe_unused]] const ProjectInfo& projectInfo) @@ -773,8 +774,8 @@ namespace O3DE::ProjectManager { // required templateInfo.m_displayName = Py_To_String(data["display_name"]); - templateInfo.m_name = Py_To_String(data["template_name"]); - templateInfo.m_summary = Py_To_String(data["summary"]); + templateInfo.m_name = Py_To_String(data["template_name"]); + templateInfo.m_summary = Py_To_String(data["summary"]); // optional if (data.contains("canonical_tags")) @@ -806,7 +807,7 @@ namespace O3DE::ProjectManager QVector templates; bool result = ExecuteWithLock([&] { - for (auto path : m_manifest.attr("get_project_templates")()) + for (auto path : m_manifest.attr("get_templates_for_project_creation")()) { templates.push_back(ProjectTemplateInfoFromPath(path)); } diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index edcd44c525..bcb331d9f4 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -302,64 +302,95 @@ def get_project_external_subdirectories(project_path: pathlib.Path) -> list: project_object['external_subdirectories'])) if 'external_subdirectories' in project_object else [] +def get_project_templates(project_path: pathlib.Path) -> list: + project_object = get_project_json_data(project_path=project_path) + return list(map(lambda rel_path: (pathlib.Path(project_path) / rel_path).as_posix(), + project_object['templates'])) + + +def get_project_restricted(project_path: pathlib.Path) -> list: + project_object = get_project_json_data(project_path=project_path) + return list(map(lambda rel_path: (pathlib.Path(project_path) / rel_path).as_posix(), + project_object['restricted'])) if 'restricted' in project_object else [] + + # Combined manifest queries def get_all_projects() -> list: - projects_data = set(get_projects()) - projects_data.update(get_engine_projects()) - return list(projects_data) + projects_data = get_projects() + projects_data.extend(get_engine_projects()) + # Remove duplicates from the list + return list(dict.fromkeys(projects_data)) def get_all_gems(project_path: pathlib.Path = None) -> list: - gems_data = set(get_gems()) - gems_data.update(get_engine_gems()) + gems_data = get_gems() + gems_data.extend(get_engine_gems()) if project_path: - gems_data.update(get_project_gems(project_path)) - return list(gems_data) + gems_data.extend(get_project_gems(project_path)) + return list(dict.fromkeys(gems_data)) def get_all_external_subdirectories(project_path: pathlib.Path = None) -> list: - external_subdirectories_data = set(get_external_subdirectories()) - external_subdirectories_data.update(get_engine_external_subdirectories()) + external_subdirectories_data = get_external_subdirectories() + external_subdirectories_data.extend(get_engine_external_subdirectories()) if project_path: - external_subdirectories_data.update(get_project_external_subdirectories(project_path)) - return list(templates_data) + external_subdirectories_data.extend(get_project_external_subdirectories(project_path)) + return list(dict.fromkeys(external_subdirectories_data)) -def get_all_templates() -> list: - templates_data = set(get_templates()) - templates_data.update(get_engine_templates()) - return list(templates_data) +def get_all_templates(project_path: pathlib.Path = None) -> list: + templates_data = get_templates() + templates_data.extend(get_engine_templates()) + if project_path: + templates_data.extend(get_project_templates(project_path)) + return list(dict.fromkeys(templates_data)) def get_all_restricted() -> list: - restricted_data = set(get_restricted()) - restricted_data.update(get_engine_restricted()) - return list(gems_data) + restricted_data = get_restricted() + restricted_data.extend(get_engine_restricted()) + if project_path: + restricted_data.extend(get_project_restricted(project_path)) + return list(dict.fromkeys(restricted_data)) # Template functions -def get_project_templates(): # temporary until we have a better way to do this... maybe template_type element +def get_templates_for_project_creation(): project_templates = [] - for template in get_all_templates(): - if 'Project' in template: - project_templates.append(template) + for template_path in get_all_templates(): + template_path = pathlib.Path(template_path) + template_json_path = pathlib.Path(template_path) / 'template.json' + if not validation.valid_o3de_template_json(template_json_path): + continue + + project_json_path = template_path / 'Template' / 'project.json' + if validation.valid_o3de_project_json(project_json_path): + project_templates.append(template_path) return project_templates -def get_gem_templates(): # temporary until we have a better way to do this... maybe template_type element +def get_templates_for_gem_creation(): gem_templates = [] - for template in get_all_templates(): - if 'Gem' in template: - gem_templates.append(template) + for template_path in get_all_templates(): + template_path = pathlib.Path(template_path) + template_json_path = pathlib.Path(template_path) / 'template.json' + if not validation.valid_o3de_template_json(template_json_path): + continue + + gem_json_path = template_path / 'Template' / 'gem.json' + if validation.valid_o3de_gem_json(gem_json_path): + gem_templates.append(template_path) return gem_templates -def get_generic_templates(): # temporary until we have a better way to do this... maybe template_type element - generic_templates = [] - for template in get_all_templates(): - if 'Project' not in template and 'Gem' not in template: - generic_templates.append(template) - return generic_templates +def get_templates_for_generic_creation(): # temporary until we have a better way to do this... maybe template_type element + def filter_project_and_gem_templates_out(template_path, + templates_for_project_creation = get_templates_for_project_creation(), + templates_for_gem_creation = get_templates_for_gem_creation()): + template_path = pathlib.Path(template_path) + return template_path not in templates_for_project_creation and template_path not in templates_for_gem_creation + + return list(filter(filter_project_and_gem_templates_out, get_all_templates())) def get_all_restricted() -> list: @@ -515,7 +546,7 @@ def get_template_json_data(template_name: str = None, return None -def get_restricted_data(restricted_name: str = None, +def get_restricted_json_data(restricted_name: str = None, restricted_path: str or pathlib.Path = None) -> dict or None: if not restricted_name and not restricted_path: logger.error('Must specify either a Restricted name or Restricted Path.') diff --git a/scripts/o3de/o3de/print_registration.py b/scripts/o3de/o3de/print_registration.py index 292f2224bc..e5c7a1afc0 100644 --- a/scripts/o3de/o3de/print_registration.py +++ b/scripts/o3de/o3de/print_registration.py @@ -13,6 +13,7 @@ import argparse import json import hashlib import logging +import pathlib import sys import urllib.parse @@ -21,219 +22,251 @@ from o3de import manifest, validation logger = logging.getLogger() logging.basicConfig() -def print_this_engine(verbose: int) -> None: + +def get_project_path(project_path: pathlib.Path, project_name: str) -> pathlib.Path: + if not project_name and not project_path: + logger.error(f'Must either specify a Project path or Project Name.') + return None + + if not project_path: + project_path = manifest.get_registered(project_name=project_name) + if not project_path: + logger.error(f'Unable to locate project path from the registered manifest json files:' + f' {str(pathlib.Path("~/.o3de/o3de_manifest.json").expanduser())}, engine.json') + return None + + if not project_path.is_dir(): + logger.error(f'Project path {project_path} is not a folder.') + return None + + return project_path + + +def print_this_engine(verbose: int) -> int: engine_data = manifest.get_this_engine() print(json.dumps(engine_data, indent=4)) + result = True if verbose > 0: - print_engines_data(engine_data) + result = print_manifest_json_data(engine_data, 'engine.json', 'This Engine', + manifest.get_engine_json_data, 'engine_path') + return 0 if result else 1 def print_engines(verbose: int) -> None: engines_data = manifest.get_engines() print(json.dumps(engines_data, indent=4)) + if verbose > 0: - print_engines_data(engines_data) + return print_manifest_json_data(engines_data, 'engine.json', 'Engines', + manifest.get_engine_json_data, 'engine_path') + return 0 -def print_projects(verbose: int) -> None: +def print_projects(verbose: int) -> int: projects_data = manifest.get_projects() print(json.dumps(projects_data, indent=4)) + if verbose > 0: - print_projects_data(projects_data) + return print_manifest_json_data(projects_data, 'project.json', 'Projects', + manifest.get_project_json_data, 'project_path') + return 0 -def print_gems(verbose: int) -> None: +def print_gems(verbose: int) -> int: gems_data = manifest.get_gems() print(json.dumps(gems_data, indent=4)) + if verbose > 0: - print_gems_data(gems_data) + return print_manifest_json_data(gems_data, 'gem.json', 'Gems', + manifest.get_gem_json_data, 'gem_path') + return 0 -def print_templates(verbose: int) -> None: +def print_templates(verbose: int) -> int: templates_data = manifest.get_templates() print(json.dumps(templates_data, indent=4)) + if verbose > 0: - print_templates_data(templates_data) + return print_manifest_json_data(templates_data, 'template.json', 'Templates', + manifest.get_template_json_data, 'template_path') + return 0 -def print_restricted(verbose: int) -> None: +def print_restricted(verbose: int) -> int: restricted_data = manifest.get_restricted() print(json.dumps(restricted_data, indent=4)) - if verbose > 0: - print_restricted_data(restricted_data) -def print_engine_projects(verbose: int) -> None: + if verbose > 0: + return print_manifest_json_data(restricted_data, 'restricted.json', 'Restricted', + manifest.get_restricted_json_data, 'restricted_path') + return 0 + + +# Engine output methods +def print_engine_projects(verbose: int) -> int: engine_projects_data = manifest.get_engine_projects() print(json.dumps(engine_projects_data, indent=4)) + if verbose > 0: - print_projects_data(engine_projects_data) + return print_manifest_json_data(engine_projects_data, 'project.json', 'Projects', + manifest.get_project_json_data, 'project_path') + return 0 -def print_engine_gems(verbose: int) -> None: +def print_engine_gems(verbose: int) -> int: engine_gems_data = manifest.get_engine_gems() print(json.dumps(engine_gems_data, indent=4)) + if verbose > 0: - print_gems_data(engine_gems_data) + return print_manifest_json_data(engine_gems_data, 'gem.json', 'Gems', + manifest.get_gem_json_data, 'gem_path') + return 0 -def print_engine_templates(verbose: int) -> None: +def print_engine_templates(verbose: int) -> int: engine_templates_data = manifest.get_engine_templates() print(json.dumps(engine_templates_data, indent=4)) + if verbose > 0: - print_templates_data(engine_templates_data) + return print_manifest_json_data(engine_templates_data, 'template.json', 'Templates', + manifest.get_template_json_data, 'template_path') + return 0 -def print_engine_restricted(verbose: int) -> None: +def print_engine_restricted(verbose: int) -> int: engine_restricted_data = manifest.get_engine_restricted() print(json.dumps(engine_restricted_data, indent=4)) + if verbose > 0: - print_restricted_data(engine_restricted_data) + return print_manifest_json_data(engine_restricted_data, 'restricted.json', 'Restricted', + manifest.get_restricted_json_data, 'restricted_path') + return 0 -def print_engine_external_subdirectories(verbose: int) -> None: +def print_engine_external_subdirectories() -> int: external_subdirs_data = manifest.get_engine_external_subdirectories() print(json.dumps(external_subdirs_data, indent=4)) + return 0 -def print_all_projects(verbose: int) -> None: +# Project output methods +def print_project_gems(verbose: int, project_path: pathlib.Path, project_name: str) -> int: + project_path = get_project_path(project_path, project_name) + if not project_path: + return 1 + + project_gems_data = manifest.get_project_gems(project_path) + print(json.dumps(project_gems_data, indent=4)) + + if verbose > 0: + return print_manifest_json_data(project_gems_data, 'gem.json', 'Gems', + manifest.get_gem_json_data, 'gem_path') + return 0 + + +def print_project_external_subdirectories(project_path: pathlib.Path, project_name: str) -> int: + project_path = get_project_path(project_path, project_name) + if not project_path: + return 1 + + external_subdirs_data = manifest.get_project_external_subdirectories(project_path) + print(json.dumps(external_subdirs_data, indent=4)) + return 0 + + +def print_project_templates(verbose: int, project_path: pathlib.Path, project_name: str) -> int: + project_path = get_project_path(project_path, project_name) + if not project_path: + return 1 + + project_templates_data = manifest.get_project_templates(project_path) + print(json.dumps(project_templates_data, indent=4)) + if verbose > 0: + return print_manifest_json_data(project_templates_data, 'template.json', 'Templates', + manifest.get_template_json_data, 'template_path') + return 0 + + +def print_project_restricted(verbose: int, project_path: pathlib.Path, project_name: str) -> int: + project_path = get_project_path(project_path, project_name) + if not project_path: + return 1 + + project_restricted_data = manifest.get_project_restricted(project_path) + print(json.dumps(project_restricted_data, indent=4)) + if verbose > 0: + return print_manifest_json_data(project_restricted_data, 'restricted.json', 'Restricted', + manifest.get_restricted_json_data, 'restricted_path') + return 0 + + +def print_all_projects(verbose: int) -> int: all_projects_data = manifest.get_all_projects() print(json.dumps(all_projects_data, indent=4)) + if verbose > 0: - print_projects_data(all_projects_data) + return print_manifest_json_data(all_projects_data, 'project.json', 'Projects', + manifest.get_project_json_data, 'project_path') + return 0 -def print_all_gems(verbose: int) -> None: +def print_all_gems(verbose: int) -> int: all_gems_data = manifest.get_all_gems() print(json.dumps(all_gems_data, indent=4)) + if verbose > 0: - print_gems_data(all_gems_data) + return print_manifest_json_data(all_gems_data, 'gem.json', 'Gems', + manifest.get_gem_json_data, 'gem_path') + return 0 -def print_all_templates(verbose: int) -> None: +def print_all_external_subdirectories() -> int: + all_external_subdirectories_data = manifest.get_all_external_subdirectories() + print(json.dumps(all_external_subdirectories_data, indent=4)) + return 0 + +def print_all_templates(verbose: int) -> int: all_templates_data = manifest.get_all_templates() print(json.dumps(all_templates_data, indent=4)) + if verbose > 0: - print_templates_data(all_templates_data) + return print_manifest_json_data(all_templates_data, 'template.json', 'Templates', + manifest.get_template_json_data, 'template_path') + return 0 -def print_all_restricted(verbose: int) -> None: +def print_all_restricted(verbose: int) -> int: all_restricted_data = manifest.get_all_restricted() print(json.dumps(all_restricted_data, indent=4)) + if verbose > 0: - print_restricted_data(all_restricted_data) + return print_manifest_json_data(all_restricted_data, 'restricted.json', 'Restricted', + manifest.get_restricted_json_data, 'restricted_path') + return 0 -def print_engines_data(engines_data: dict) -> None: +def print_manifest_json_data(uri_json_data: dict, json_filename: str, + print_prefix: str, get_json_func: callable, get_json_data_kw: str) -> int: print('\n') - print("Engines================================================") - for engine_object in engines_data: + print(f"{print_prefix}================================================") + for manifest_uri in uri_json_data: # if it's not local it should be in the cache - engine_uri = engine_object['path'] - parsed_uri = urllib.parse.urlparse(engine_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - repo_sha256 = hashlib.sha256(engine_uri.encode()) + parsed_uri = urllib.parse.urlparse(manifest_uri) + if parsed_uri.scheme in ['http', 'https', 'ftp', 'ftps']: + repo_sha256 = hashlib.sha256(manifest_uri.encode()) cache_folder = manifest.get_o3de_cache_folder() - engine = cache_folder / str(repo_sha256.hexdigest() + '.json') - print(f'{engine_uri}/engine.json cached as:') + manifest_json_path = cache_folder / str(repo_sha256.hexdigest() + '.json') else: - engine_json = pathlib.Path(engine_uri).resolve() / 'engine.json' + manifest_json_path = pathlib.Path(manifest_uri).resolve() / json_filename - with engine_json.open('r') as f: - try: - engine_json_data = json.load(f) - except json.JSONDecodeError as e: - logger.warn(f'{engine_json} failed to load: {str(e)}') - else: - print(engine_json) - print(json.dumps(engine_json_data, indent=4)) - print('\n') + json_data = get_json_func(**{get_json_data_kwargs: manifest_json_path}) + if json_data: + print(manifest_json_path) + print(json.dumps(json_data, indent=4) + '\n') + return 0 -def print_projects_data(projects_data: dict) -> None: - print('\n') - print("Projects================================================") - for project_uri in projects_data: - # if it's not local it should be in the cache - parsed_uri = urllib.parse.urlparse(project_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - repo_sha256 = hashlib.sha256(project_uri.encode()) - cache_folder = manifest.get_o3de_cache_folder() - project_json = cache_folder / str(repo_sha256.hexdigest() + '.json') - else: - project_json = pathlib.Path(project_uri).resolve() / 'project.json' - - with project_json.open('r') as f: - try: - project_json_data = json.load(f) - except json.JSONDecodeError as e: - logger.warn(f'{project_json} failed to load: {str(e)}') - else: - print(project_json) - print(json.dumps(project_json_data, indent=4)) - print('\n') - - -def print_gems_data(gems_data: dict) -> None: - print('\n') - print("Gems================================================") - for gem_uri in gems_data: - # if it's not local it should be in the cache - parsed_uri = urllib.parse.urlparse(gem_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - repo_sha256 = hashlib.sha256(gem_uri.encode()) - cache_folder = manifest.get_o3de_cache_folder() - gem_json = cache_folder / str(repo_sha256.hexdigest() + '.json') - else: - gem_json = pathlib.Path(gem_uri).resolve() / 'gem.json' - - with gem_json.open('r') as f: - try: - gem_json_data = json.load(f) - except json.JSONDecodeError as e: - logger.warn(f'{gem_json} failed to load: {str(e)}') - else: - print(gem_json) - print(json.dumps(gem_json_data, indent=4)) - print('\n') - - -def print_templates_data(templates_data: dict) -> None: - print('\n') - print("Templates================================================") - for template_uri in templates_data: - # if it's not local it should be in the cache - parsed_uri = urllib.parse.urlparse(template_uri) - if parsed_uri.scheme == 'http' or \ - parsed_uri.scheme == 'https' or \ - parsed_uri.scheme == 'ftp' or \ - parsed_uri.scheme == 'ftps': - repo_sha256 = hashlib.sha256(template_uri.encode()) - cache_folder = manifest.get_o3de_cache_folder() - template_json = cache_folder / str(repo_sha256.hexdigest() + '.json') - else: - template_json = pathlib.Path(template_uri).resolve() / 'template.json' - - with template_json.open('r') as f: - try: - template_json_data = json.load(f) - except json.JSONDecodeError as e: - logger.warn(f'{template_json} failed to load: {str(e)}') - else: - print(template_json) - print(json.dumps(template_json_data, indent=4)) - print('\n') - - -def print_repos_data(repos_data: dict) -> None: +def print_repos_data(repos_data: dict) -> int: print('\n') print("Repos================================================") cache_folder = manifest.get_o3de_cache_folder() @@ -251,29 +284,16 @@ def print_repos_data(repos_data: dict) -> None: print(cache_file) print(json.dumps(repo_json_data, indent=4)) print('\n') - - -def print_restricted_data(restricted_data: dict) -> None: - print('\n') - print("Restricted================================================") - for restricted_path in restricted_data: - restricted_json = pathlib.Path(restricted_path).resolve() / 'restricted.json' - with restricted_json.open('r') as f: - try: - restricted_json_data = json.load(f) - except json.JSONDecodeError as e: - logger.warn(f'{restricted_json} failed to load: {str(e)}') - else: - print(restricted_json) - print(json.dumps(restricted_json_data, indent=4)) - print('\n') + return 0 def register_show_repos(verbose: int) -> None: - repos_data = get_repos() + repos_data = manifest.get_repos() print(json.dumps(repos_data, indent=4)) + if verbose > 0: - print_repos_data(repos_data) + return print_repos_data(repos_data) == 0 + return 0 def register_show(verbose: int) -> None: @@ -281,13 +301,15 @@ def register_show(verbose: int) -> None: print(f"{manifest.get_o3de_manifest()}:") print(json.dumps(json_data, indent=4)) + result = True if verbose > 0: - print_engines_data(manifest.get_engines()) - print_projects_data(manifest.get_all_projects()) - print_gems_data(manifest.get_gems()) - print_templates_data(manifest.get_all_templates()) - print_restricted_data(manifest.get_all_restricted()) - print_repos_data(manifest.get_repos()) + result = print_manifest_json_data(manifest.get_engines()) == 0 and result + result = print_manifest_json_data(manifest.get_all_projects()) == 0 and result + result = print_manifest_json_data(manifest.get_gems()) == 0 and result + result = print_manifest_json_data(manifest.get_all_templates()) == 0 and result + result = print_manifest_json_data(manifest.get_all_restricted()) == 0 and result + result = print_repos_data(manifest.get_repos()) == 0 and result + return 0 if result else 1 def _run_register_show(args: argparse) -> int: @@ -295,75 +317,53 @@ def _run_register_show(args: argparse) -> int: manifest.override_home_folder = args.override_home_folder if args.this_engine: - print_this_engine(args.verbose) - return 0 - + return print_this_engine(args.verbose) elif args.engines: - print_engines(args.verbose) - return 0 + return print_engines(args.verbose) elif args.projects: - print_projects(args.verbose) - return 0 + return print_projects(args.verbose) elif args.gems: - print_gems(args.verbose) - return 0 + return print_gems(args.verbose) elif args.templates: - print_templates(args.verbose) - return 0 + return print_templates(args.verbose) elif args.repos: - register_show_repos(args.verbose) - return 0 + return register_show_repos(args.verbose) elif args.restricted: - print_restricted(args.verbose) - return 0 + return print_restricted(args.verbose) elif args.engine_projects: - print_engine_projects(args.verbose) - return 0 + return print_engine_projects(args.verbose) elif args.engine_gems: - print_engine_gems(args.verbose) - return 0 - elif args.engine_templates: - print_engine_templates(args.verbose) - return 0 - elif args.engine_restricted: - print_engine_restricted(args.verbose) - return 0 + return print_engine_gems(args.verbose) elif args.engine_external_subdirectories: - print_engine_external_subdirectories(args.verbose) - return 0 + return print_engine_external_subdirectories() + elif args.engine_templates: + return print_engine_templates(args.verbose) + elif args.engine_restricted: + return print_engine_restricted(args.verbose) + + elif args.project_gems: + return print_project_gems(args.verbose, args.project_path, args.project_name) + elif args.project_external_subdirectories: + return print_project_external_subdirectories(args.project_path, args.project_name) + elif args.project_templates: + return print_project_templates(args.verbose, args.project_path, args.project_name) + elif args.project_restricted: + return print_project_restricted(args.verbose, args.project_path, args.project_name) elif args.all_projects: - print_all_projects(args.verbose) - return 0 + return print_all_projects(args.verbose) elif args.all_gems: - print_all_gems(args.verbose) - return 0 + return print_all_gems(args.verbose) + elif args.all_external_subdirectories: + return print_all_external_subdirectories() elif args.all_templates: - print_all_templates(args.verbose) - return 0 + return print_all_templates(args.verbose) elif args.all_restricted: - print_all_restricted(args.verbose) - return 0 + return print_all_restricted(args.verbose) - elif args.downloadables: - print_downloadables(args.verbose) - return 0 - if args.downloadable_engines: - print_downloadable_engines(args.verbose) - return 0 - elif args.downloadable_projects: - print_downloadable_projects(args.verbose) - return 0 - elif args.downloadable_gems: - print_downloadable_gems(args.verbose) - return 0 - elif args.downloadable_templates: - print_downloadable_templates(args.verbose) - return 0 else: - register_show(args.verbose) - return 0 + return register_show(args.verbose) def add_parser_args(parser): @@ -376,78 +376,84 @@ def add_parser_args(parser): group = parser.add_mutually_exclusive_group(required=False) group.add_argument('-te', '--this-engine', action='store_true', required=False, default=False, - help='Just the local engines.') + help='Output the current engine path.') group.add_argument('-e', '--engines', action='store_true', required=False, default=False, - help='Just the local engines.') + help='Output the engines registered in the global ~/.o3de/o3de_manifest.json.') group.add_argument('-p', '--projects', action='store_true', required=False, default=False, - help='Just the local projects.') + help='Output the projects registered in the global ~/.o3de/o3de_manifest.json.') group.add_argument('-g', '--gems', action='store_true', required=False, default=False, - help='Just the local gems.') + help='Output the gems registered in the global ~/.o3de/o3de_manifest.json.') group.add_argument('-t', '--templates', action='store_true', required=False, default=False, - help='Just the local templates.') + help='Output the templates registered in the global ~/.o3de/o3de_manifest.json.') group.add_argument('-r', '--repos', action='store_true', required=False, default=False, - help='Just the local repos. Ignores repos.') + help='Output the repos registered in the global ~/.o3de/o3de_manifest.json. Ignores repos.') group.add_argument('-rs', '--restricted', action='store_true', required=False, default=False, - help='The local restricted folders.') + help='Output the restricted directories registered in the global ~/.o3de/o3de_manifest.json.') group.add_argument('-ep', '--engine-projects', action='store_true', required=False, default=False, - help='Just the local projects. Ignores repos.') + help='Output the projects registered in the current engine engine.json. Ignores repos.') group.add_argument('-eg', '--engine-gems', action='store_true', required=False, default=False, - help='Just the local gems. Ignores repos') + help='Output the gems registered in the current engine engine.json. Ignores repos') group.add_argument('-et', '--engine-templates', action='store_true', required=False, default=False, - help='Just the local templates. Ignores repos.') + help='Output the templates registered in the current engine engine.json. Ignores repos.') group.add_argument('-ers', '--engine-restricted', action='store_true', required=False, default=False, - help='The restricted folders.') - group.add_argument('-x', '--engine-external-subdirectories', action='store_true', required=False, + help='Output the restricted directories registered in the current engine engine.json.') + group.add_argument('-ees', '--engine-external-subdirectories', action='store_true', required=False, default=False, - help='The external subdirectories.') + help='Output the external subdirectories registered in the current engine engine.json.') + + group.add_argument('-pg', '--project-gems', action='store_true', + default=False, + help='Returns the gems registered with the project.json.') + group.add_argument('-pt', '--project-templates', action='store_true', + default=False, + help='Returns the templates registered with the project.json.') + group.add_argument('-prs', '--project-restricted', action='store_true', + default=False, + help='Returns the restricted directories registered with the project.json.') + group.add_argument('-pes', '--project-external-subdirectories', action='store_true', + default=False, + help='Returns the external subdirectories register with the project.json.') group.add_argument('-ap', '--all-projects', action='store_true', required=False, default=False, - help='Just the local projects. Ignores repos.') + help='Output all projects registered in the ~/.o3de/o3de_manifest.json and the current engine.json. Ignores repos.') group.add_argument('-ag', '--all-gems', action='store_true', required=False, default=False, - help='Just the local gems. Ignores repos') + help='Output all gems registered in the ~/.o3de/o3de_manifest.json and the current engine.json. Ignores repos') group.add_argument('-at', '--all-templates', action='store_true', required=False, default=False, - help='Just the local templates. Ignores repos.') - group.add_argument('-ars', '--all-restricted', action='store_true', required=False, + help='Output all templates registered in the ~/.o3de/o3de_manifest.json and the current engine.json. Ignores repos.') + group.add_argument('-ares', '--all-restricted', action='store_true', required=False, default=False, - help='The restricted folders.') - - group.add_argument('-d', '--downloadables', action='store_true', required=False, + help='Output all restricted directory registered in the ~/.o3de/o3de_manifest.json and the current engine.json.') + group.add_argument('-aes', '--all-external-subdirectories', action='store_true', default=False, - help='Combine all repos into a single list of resources.') - group.add_argument('-de', '--downloadable-engines', action='store_true', required=False, - default=False, - help='Combine all repos engines into a single list of resources.') - group.add_argument('-dp', '--downloadable-projects', action='store_true', required=False, - default=False, - help='Combine all repos projects into a single list of resources.') - group.add_argument('-dg', '--downloadable-gems', action='store_true', required=False, - default=False, - help='Combine all repos gems into a single list of resources.') - group.add_argument('-dt', '--downloadable-templates', action='store_true', required=False, - default=False, - help='Combine all repos templates into a single list of resources.') + help='Output all external subdirectories registered in the ~/.o3de/o3de_manifest.json and the current engine.json.') parser.add_argument('-v', '--verbose', action='count', required=False, - default=0, - help='How verbose do you want the output to be.') + default=0, + help='How verbose do you want the output to be.') + + project_group = parser.add_mutually_exclusive_group(required=False) + project_group.add_argument('-pp', '--project-path', type=pathlib.Path, + help='The path to a project.') + project_group.add_argument('-pn', '--project-name', type=str, + help='The name of a project.') parser.add_argument('-ohf', '--override-home-folder', type=str, required=False, - help='By default the home folder is the user folder, override it to this folder.') + help='By default the home folder is the user folder, override it to this folder.') parser.set_defaults(func=_run_register_show) diff --git a/scripts/o3de/tests/CMakeLists.txt b/scripts/o3de/tests/CMakeLists.txt index 0526c7740d..82b994e387 100644 --- a/scripts/o3de/tests/CMakeLists.txt +++ b/scripts/o3de/tests/CMakeLists.txt @@ -34,3 +34,10 @@ ly_add_pytest( TEST_SUITE smoke EXCLUDE_TEST_RUN_TARGET_FROM_IDE ) + +ly_add_pytest( + NAME o3de_manifest + PATH ${CMAKE_CURRENT_LIST_DIR}/unit_test_manifest.py + TEST_SUITE smoke + EXCLUDE_TEST_RUN_TARGET_FROM_IDE +) diff --git a/scripts/o3de/tests/unit_test_manifest.py b/scripts/o3de/tests/unit_test_manifest.py new file mode 100644 index 0000000000..98430c227b --- /dev/null +++ b/scripts/o3de/tests/unit_test_manifest.py @@ -0,0 +1,111 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +import argparse +import json +import logging +import pytest +import pathlib +from unittest.mock import patch + +from o3de import manifest + + +@pytest.mark.parametrize("valid_project_json_paths, valid_gem_json_paths", [ + pytest.param([pathlib.Path('D:/o3de/Templates/DefaultProject/Template/project.json')], + [pathlib.Path('D:/o3de/Templates/DefaultGem/Template/gem.json')]) +]) +class TestGetTemplatesForCreation: + @staticmethod + def get_templates() -> list: + return [] + + @staticmethod + def get_project_templates() -> list: + return [] + + @staticmethod + def get_engine_templates() -> list: + return [pathlib.Path('D:/o3de/Templates/DefaultProject'), pathlib.Path('D:/o3de/Templates/DefaultGem')] + + + @pytest.mark.parametrize("expected_template_paths", [ + pytest.param([]) + ] + ) + def test_get_templates_for_generic_creation(self, valid_project_json_paths, valid_gem_json_paths, + expected_template_paths): + def validate_project_json(template_path) -> bool: + return pathlib.Path(template_path) in valid_project_json_paths + + def validate_gem_json(template_path) -> bool: + return pathlib.Path(template_path) in valid_gem_json_paths + + with patch('o3de.manifest.get_templates', side_effect=self.get_templates) as get_templates_patch, \ + patch('o3de.manifest.get_project_templates', side_effect=self.get_project_templates)\ + as get_project_templates_patch, \ + patch('o3de.manifest.get_engine_templates', side_effect=self.get_engine_templates)\ + as get_engine_templates_patch, \ + patch('o3de.validation.valid_o3de_template_json', return_value=True) as validate_template_json,\ + patch('o3de.validation.valid_o3de_project_json', side_effect=validate_project_json) as validate_project_json,\ + patch('o3de.validation.valid_o3de_gem_json', side_effect=validate_gem_json) as validate_gem_json: + templates = manifest.get_templates_for_generic_creation() + assert templates == expected_template_paths + + + @pytest.mark.parametrize("expected_template_paths", [ + pytest.param([pathlib.Path('D:/o3de/Templates/DefaultProject')]) + ] + ) + def test_get_templates_for_gem_creation(self, valid_project_json_paths, valid_gem_json_paths, + expected_template_paths): + def validate_project_json(template_path) -> bool: + return pathlib.Path(template_path) in valid_project_json_paths + + def validate_gem_json(template_path) -> bool: + return pathlib.Path(template_path) in valid_gem_json_paths + + with patch('o3de.manifest.get_templates', side_effect=self.get_templates) as get_templates_patch, \ + patch('o3de.manifest.get_project_templates', side_effect=self.get_project_templates) \ + as get_project_templates_patch, \ + patch('o3de.manifest.get_engine_templates', side_effect=self.get_engine_templates) \ + as get_engine_templates_patch, \ + patch('o3de.validation.valid_o3de_template_json', return_value=True) as validate_template_json, \ + patch('o3de.validation.valid_o3de_project_json', + side_effect=validate_project_json) as validate_project_json, \ + patch('o3de.validation.valid_o3de_gem_json', side_effect=validate_gem_json) as validate_gem_json: + templates = manifest.get_templates_for_project_creation() + assert templates == expected_template_paths + + + @pytest.mark.parametrize("expected_template_paths", [ + pytest.param([pathlib.Path('D:/o3de/Templates/DefaultGem')]) + ] + ) + def test_get_templates_for_project_creation(self, valid_project_json_paths, valid_gem_json_paths, + expected_template_paths): + def validate_project_json(template_path) -> bool: + return pathlib.Path(template_path) in valid_project_json_paths + + def validate_gem_json(template_path) -> bool: + return pathlib.Path(template_path) in valid_gem_json_paths + + with patch('o3de.manifest.get_templates', side_effect=self.get_templates) as get_templates_patch, \ + patch('o3de.manifest.get_project_templates', side_effect=self.get_project_templates) \ + as get_project_templates_patch, \ + patch('o3de.manifest.get_engine_templates', side_effect=self.get_engine_templates) \ + as get_engine_templates_patch, \ + patch('o3de.validation.valid_o3de_template_json', return_value=True) as validate_template_json, \ + patch('o3de.validation.valid_o3de_project_json', + side_effect=validate_project_json) as validate_project_json, \ + patch('o3de.validation.valid_o3de_gem_json', side_effect=validate_gem_json) as validate_gem_json: + templates = manifest.get_templates_for_gem_creation() + assert templates == expected_template_paths \ No newline at end of file diff --git a/scripts/o3de/tests/unit_test_utils.py b/scripts/o3de/tests/unit_test_utils.py index e7d59b507b..4fe22b1f72 100755 --- a/scripts/o3de/tests/unit_test_utils.py +++ b/scripts/o3de/tests/unit_test_utils.py @@ -11,7 +11,7 @@ import pytest -from . import utils +from o3de import utils @pytest.mark.parametrize( "value, expected_result", [ From deb3c5e74a9cfa1725c77711bc584952b4231a79 Mon Sep 17 00:00:00 2001 From: cgalvan Date: Thu, 3 Jun 2021 18:20:59 -0500 Subject: [PATCH 492/811] [LYN-2446] Implemented support for duplicating instances. (#1097) * [LYN-2446] Implemented support for duplicating instances. * [LYN-2446] Addressed PR feedback. * [LYN-2446] Addressed additional PR feedback. --- .../Prefab/Instance/Instance.h | 4 +- .../Instance/InstanceUpdateExecutor.cpp | 24 ++ .../Prefab/PrefabPublicHandler.cpp | 290 +++++++++++++----- .../Prefab/PrefabPublicHandler.h | 27 ++ 4 files changed, 259 insertions(+), 86 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h index 4a69ade6d2..d14203e2e5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.h @@ -174,6 +174,8 @@ namespace AzToolsFramework static EntityAlias GenerateEntityAlias(); AliasPath GetAbsoluteInstanceAliasPath() const; + static InstanceAlias GenerateInstanceAlias(); + protected: /** * Gets the entities owned by this instance @@ -190,8 +192,6 @@ namespace AzToolsFramework bool RegisterEntity(const AZ::EntityId& entityId, const EntityAlias& entityAlias); AZStd::unique_ptr DetachEntity(const EntityAlias& entityAlias); - static InstanceAlias GenerateInstanceAlias(); - // Provide access to private data members in the serializer friend class JsonInstanceSerializer; friend class InstanceEntityIdMapper; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.cpp index e0d29f2ab1..6194adf784 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.cpp @@ -152,6 +152,30 @@ namespace AzToolsFramework Instance::EntityList newEntities; if (PrefabDomUtils::LoadInstanceFromPrefabDom(*instanceToUpdate, newEntities, currentTemplate.GetPrefabDom())) { + // If a link was created for a nested instance before the changes were propagated, + // then we associate it correctly here + instanceToUpdate->GetNestedInstances([&](AZStd::unique_ptr& nestedInstance) { + if (nestedInstance->GetLinkId() != InvalidLinkId) + { + return; + } + + for (auto linkId : currentTemplate.GetLinks()) + { + LinkReference nestedLink = m_prefabSystemComponentInterface->FindLink(linkId); + if (!nestedLink.has_value()) + { + continue; + } + + if (nestedLink->get().GetInstanceName() == nestedInstance->GetInstanceAlias()) + { + nestedInstance->SetLinkId(linkId); + break; + } + } + }); + AzToolsFramework::EditorEntityContextRequestBus::Broadcast( &AzToolsFramework::EditorEntityContextRequests::HandleEntitiesAdded, newEntities); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 27c812ff9d..4656dcf48f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -899,16 +899,29 @@ namespace AzToolsFramework if (!EntitiesBelongToSameInstance(entityIds)) { - return AZ::Failure(AZStd::string("Cannot duplicate multiple " - "entities belonging to different instances with one operation.")); + return AZ::Failure(AZStd::string("Cannot duplicate multiple entities belonging to different instances with one operation." + "Change your selection to contain entities in the same instance.")); } // We've already verified the entities are all owned by the same instance, // so we can just retrieve our instance from the first entity in the list. - InstanceOptionalReference commonEntityOwningInstance = GetOwnerInstanceByEntityId(entityIds[0]); - AZ_Assert( - commonEntityOwningInstance.has_value(), - "Failed to duplicate : Couldn't get a valid owning instance for the common root entity of the entities provided"); + AZ::EntityId firstEntityIdToDuplicate = entityIds[0]; + InstanceOptionalReference commonOwningInstance = GetOwnerInstanceByEntityId(firstEntityIdToDuplicate); + if (!commonOwningInstance.has_value()) + { + return AZ::Failure(AZStd::string("Failed to duplicate : Couldn't get a valid owning instance for the common root entity of the entities provided.")); + } + + // If the first entity id is a container entity id, then we need to mark its parent as the common owning instance because you + // cannot duplicate an instance from itself. + if (commonOwningInstance->get().GetContainerEntityId() == firstEntityIdToDuplicate) + { + commonOwningInstance = commonOwningInstance->get().GetParentInstance(); + } + if (!commonOwningInstance.has_value()) + { + return AZ::Failure(AZStd::string("Failed to duplicate : Couldn't get a valid owning instance for the common root entity of the entities provided.")); + } // This will cull out any entities that have ancestors in the list, since we will end up duplicating // the full nested hierarchy with what is returned from RetrieveAndSortPrefabEntitiesAndInstances @@ -921,105 +934,63 @@ namespace AzToolsFramework { AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "DuplicateEntitiesInInstance::UndoCaptureAndDuplicateEntities"); - // Take a snapshot of the instance DOM before we manipulate it - Prefab::PrefabDom instanceDomBefore; - m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, commonEntityOwningInstance->get()); - AZStd::vector entities; AZStd::vector instances; - // Gather all entities/instances in the hierarchy, but don't detach them because we are duplicating not deleting. EntityList inputEntityList = EntityIdSetToEntityList(duplicationSet); - bool success = RetrieveAndSortPrefabEntitiesAndInstances(inputEntityList, commonEntityOwningInstance->get(), entities, instances); + bool success = RetrieveAndSortPrefabEntitiesAndInstances(inputEntityList, commonOwningInstance->get(), entities, instances); if (!success) { return AZ::Failure(AZStd::string("Failed to retrieve entities and instances from the given list of entity ids for duplication")); } - // Make a copy of our before instance DOM where we will add our duplicated entities - Prefab::PrefabDom instanceDomAfter; + // Take a snapshot of the instance DOM before we manipulate it + PrefabDom instanceDomBefore; + m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, commonOwningInstance->get()); + + // Make a copy of our before instance DOM where we will add our duplicated entities and/or instances + PrefabDom instanceDomAfter; instanceDomAfter.CopyFrom(instanceDomBefore, instanceDomAfter.GetAllocator()); - AZStd::unordered_map oldAliasToNewAliasMap; - AZStd::unordered_map aliasToEntityDomMap; + EntityIdList duplicatedEntityAndInstanceIds; - for (AZ::Entity* entity : entities) - { - EntityAliasOptionalReference oldAliasRef = commonEntityOwningInstance->get().GetEntityAlias(entity->GetId()); - AZ_Assert(oldAliasRef.has_value(), "No alias found for Entity in the DOM"); - EntityAlias oldAlias = oldAliasRef.value(); + // Duplicate any nested entities and instances as requested + AZStd::unordered_map newInstanceAliasToOldInstanceMap; + DuplicateNestedEntitiesInInstance(commonOwningInstance->get(), + entities, instanceDomAfter, duplicatedEntityAndInstanceIds); + DuplicateNestedInstancesInInstance(commonOwningInstance->get(), + instances, instanceDomAfter, duplicatedEntityAndInstanceIds, + newInstanceAliasToOldInstanceMap); - // Give this the outer allocator so that the memory reference will be valid when - // it gets used for AddMember - Prefab::PrefabDom entityDomBefore(&instanceDomAfter.GetAllocator()); - m_instanceToTemplateInterface->GenerateDomForEntity(entityDomBefore, *entity); - - // Keep track of the old alias <-> new alias mapping for this duplicated entity - // so we can fixup references later - EntityAlias newEntityAlias = Instance::GenerateEntityAlias(); - oldAliasToNewAliasMap.insert(AZStd::make_pair(oldAlias, newEntityAlias)); - - rapidjson::StringBuffer buffer; - rapidjson::Writer writer(buffer); - entityDomBefore.Accept(writer); - - // Store our duplicated Entity DOM with its new alias as a string - // so that we can fixup entity alias references before adding it - // to the Entities member of our instance DOM - QString entityDomString(buffer.GetString()); - aliasToEntityDomMap.insert(AZStd::make_pair(newEntityAlias, entityDomString)); - } - - auto entitiesIter = instanceDomAfter.FindMember(PrefabDomUtils::EntitiesName); - AZ_Assert(entitiesIter != instanceDomAfter.MemberEnd(), "Instance DOM missing the Entities member."); - - // Now that all the duplicated Entity DOMs have been created, we need to iterate - // through them and replace any previous EntityAlias references with the new ones. - // These are more than just parent entity references for nested entities, this will - // also cover any EntityId references that were made in the components between them. - for (auto aliasEntityPair : aliasToEntityDomMap) - { - EntityAlias newEntityAlias = aliasEntityPair.first; - QString newEntityDomString = aliasEntityPair.second; - - // Replace all of the old alias references with the new ones - // We bookend the aliases with \" and also with a / as an extra precaution to prevent - // inadvertently replacing a matching string vs. where an actual EntityId is expected - // This will cover both cases where an alias could be used in a normal entity vs. an instance - for (auto aliasMapIter : oldAliasToNewAliasMap) - { - ReplaceOldAliases(newEntityDomString, aliasMapIter.first, aliasMapIter.second); - } - - // Create the new Entity DOM from parsing the JSON string - Prefab::PrefabDom entityDomAfter(&instanceDomAfter.GetAllocator()); - entityDomAfter.Parse(newEntityDomString.toUtf8().constData()); - - // Add the new Entity DOM to the Entities member of the instance - rapidjson::Value aliasName(newEntityAlias.c_str(), newEntityAlias.length(), instanceDomAfter.GetAllocator()); - entitiesIter->value.AddMember(AZStd::move(aliasName), entityDomAfter, instanceDomAfter.GetAllocator()); - } - - PrefabUndoInstance* command = aznew PrefabUndoInstance("Entity duplication"); + PrefabUndoInstance* command = aznew PrefabUndoInstance("Entity/Instance duplication"); command->SetParent(undoBatch.GetUndoBatch()); - command->Capture(instanceDomBefore, instanceDomAfter, commonEntityOwningInstance->get().GetTemplateId()); - command->RunRedo(); + command->Capture(instanceDomBefore, instanceDomAfter, commonOwningInstance->get().GetTemplateId()); + command->Redo(); - EntityIdList duplicatedEntityIds; - for (auto aliasMapIter : oldAliasToNewAliasMap) + // Create links for our duplicated instances (if any were duplicated) + for (auto [newInstanceAlias, oldInstance] : newInstanceAliasToOldInstanceMap) { - EntityAlias newEntityAlias = aliasMapIter.second; + LinkId oldLinkId = oldInstance->GetLinkId(); + auto linkRef = m_prefabSystemComponentInterface->FindLink(oldLinkId); + AZ_Assert( + linkRef.has_value(), "Unable to find link with id '%llu' during instance duplication.", + oldLinkId); - AliasPath absoluteEntityPath = commonEntityOwningInstance->get().GetAbsoluteInstanceAliasPath(); - absoluteEntityPath.Append(newEntityAlias); + PrefabDomValueReference linkPatches = linkRef->get().GetLinkPatches(); + AZ_Assert( + linkPatches.has_value(), "Link with id '%llu' is missing patches.", + oldLinkId); - AZ::EntityId newEntityId = InstanceEntityIdMapper::GenerateEntityIdForAliasPath(absoluteEntityPath); - duplicatedEntityIds.push_back(newEntityId); + PrefabDom linkPatchesCopy; + linkPatchesCopy.CopyFrom(linkPatches->get(), linkPatchesCopy.GetAllocator()); + + m_prefabSystemComponentInterface->CreateLink( + commonOwningInstance->get().GetTemplateId(), oldInstance->GetTemplateId(), newInstanceAlias, linkPatchesCopy); } - // Select the duplicated entities - auto selectionUndo = aznew SelectionCommand(duplicatedEntityIds, "Select Duplicated Entities"); + // Select the duplicated entities/instances + auto selectionUndo = aznew SelectionCommand(duplicatedEntityAndInstanceIds, "Select Duplicated Entities/Instances"); selectionUndo->SetParent(undoBatch.GetUndoBatch()); ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequestBus::Events::RunRedoSeparately, selectionUndo); } @@ -1508,8 +1479,159 @@ namespace AzToolsFramework return true; } + void PrefabPublicHandler::DuplicateNestedEntitiesInInstance(Instance& commonOwningInstance, + const AZStd::vector& entities, PrefabDom& domToAddDuplicatedEntitiesUnder, + EntityIdList& duplicatedEntityIds) + { + if (entities.empty()) + { + return; + } + + AZStd::unordered_map oldAliasToNewAliasMap; + AZStd::unordered_map aliasToEntityDomMap; + + for (AZ::Entity* entity : entities) + { + EntityAliasOptionalReference oldAliasRef = commonOwningInstance.GetEntityAlias(entity->GetId()); + AZ_Assert(oldAliasRef.has_value(), "No alias found for Entity in the DOM"); + EntityAlias oldAlias = oldAliasRef.value(); + + // Give this the outer allocator so that the memory reference will be valid when + // it gets used for AddMember + PrefabDom entityDomBefore(&domToAddDuplicatedEntitiesUnder.GetAllocator()); + m_instanceToTemplateInterface->GenerateDomForEntity(entityDomBefore, *entity); + + // Keep track of the old alias <-> new alias mapping for this duplicated entity + // so we can fixup references later + EntityAlias newEntityAlias = Instance::GenerateEntityAlias(); + oldAliasToNewAliasMap.emplace(oldAlias, newEntityAlias); + + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + entityDomBefore.Accept(writer); + + // Store our duplicated Entity DOM with its new alias as a string + // so that we can fixup entity alias references before adding it + // to the Entities member of our instance DOM + QString entityDomString(buffer.GetString()); + aliasToEntityDomMap.emplace(newEntityAlias, entityDomString); + } + + auto entitiesIter = domToAddDuplicatedEntitiesUnder.FindMember(PrefabDomUtils::EntitiesName); + AZ_Assert(entitiesIter != domToAddDuplicatedEntitiesUnder.MemberEnd(), "Instance DOM missing the Entities member."); + + // Now that all the duplicated Entity DOMs have been created, we need to iterate + // through them and replace any previous EntityAlias references with the new ones. + // These are more than just parent entity references for nested entities, this will + // also cover any EntityId references that were made in the components between them. + for (auto [newEntityAlias, newEntityDomString] : aliasToEntityDomMap) + { + // Replace all of the old alias references with the new ones + for (auto [oldAlias, newAlias] : oldAliasToNewAliasMap) + { + ReplaceOldAliases(newEntityDomString, oldAlias, newAlias); + } + + // Create the new Entity DOM from parsing the JSON string + PrefabDom entityDomAfter(&domToAddDuplicatedEntitiesUnder.GetAllocator()); + entityDomAfter.Parse(newEntityDomString.toUtf8().constData()); + + // Add the new Entity DOM to the Entities member of the instance + rapidjson::Value aliasName(newEntityAlias.c_str(), newEntityAlias.length(), domToAddDuplicatedEntitiesUnder.GetAllocator()); + entitiesIter->value.AddMember(AZStd::move(aliasName), entityDomAfter, domToAddDuplicatedEntitiesUnder.GetAllocator()); + } + + for (auto aliasMapIter : oldAliasToNewAliasMap) + { + EntityAlias newEntityAlias = aliasMapIter.second; + + AliasPath absoluteEntityPath = commonOwningInstance.GetAbsoluteInstanceAliasPath(); + absoluteEntityPath.Append(newEntityAlias); + + AZ::EntityId newEntityId = InstanceEntityIdMapper::GenerateEntityIdForAliasPath(absoluteEntityPath); + duplicatedEntityIds.push_back(newEntityId); + } + } + + void PrefabPublicHandler::DuplicateNestedInstancesInInstance(Instance& commonOwningInstance, + const AZStd::vector& instances, PrefabDom& domToAddDuplicatedInstancesUnder, + EntityIdList& duplicatedEntityIds, AZStd::unordered_map& newInstanceAliasToOldInstanceMap) + { + if (instances.empty()) + { + return; + } + + AZStd::unordered_map oldInstanceAliasToNewInstanceAliasMap; + AZStd::unordered_map aliasToInstanceDomMap; + + for (auto instance : instances) + { + PrefabDom nestedInstanceDomBefore; + m_instanceToTemplateInterface->GenerateDomForInstance(nestedInstanceDomBefore, *instance); + + // Keep track of the old alias <-> new alias mapping for this duplicated instance + // so we can fixup references later + InstanceAlias oldAlias = instance->GetInstanceAlias(); + InstanceAlias newInstanceAlias = Instance::GenerateInstanceAlias(); + oldInstanceAliasToNewInstanceAliasMap.emplace(oldAlias, newInstanceAlias); + + // Keep track of our new instance alias with the Instance it was duplicated from, + // so that after all instances are duplicated, we can go back and create links for them + newInstanceAliasToOldInstanceMap.emplace(newInstanceAlias, instance); + + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + nestedInstanceDomBefore.Accept(writer); + + // Store our duplicated Instance DOM with its new alias as a string + // so that we can fixup instance alias references before adding it + // to the Instances member of our instance DOM + QString instanceDomString(buffer.GetString()); + aliasToInstanceDomMap.emplace(newInstanceAlias, instanceDomString); + } + + auto instancesIter = domToAddDuplicatedInstancesUnder.FindMember(PrefabDomUtils::InstancesName); + AZ_Assert(instancesIter != domToAddDuplicatedInstancesUnder.MemberEnd(), "Instance DOM missing the Instances member."); + + // Now that all the duplicated Instance DOMs have been created, we need to iterate + // through them and replace any previous InstanceAlias references with the new ones. + for (auto [newInstanceAlias, newInstanceDomString]: aliasToInstanceDomMap) + { + // Replace all of the old alias references with the new ones + for (auto [oldAlias, newAlias] : oldInstanceAliasToNewInstanceAliasMap) + { + ReplaceOldAliases(newInstanceDomString, oldAlias, newAlias); + } + + // Create the new Instance DOM from parsing the JSON string + PrefabDom nestedInstanceDomAfter(&domToAddDuplicatedInstancesUnder.GetAllocator()); + nestedInstanceDomAfter.Parse(newInstanceDomString.toUtf8().constData()); + + // Add the new Instance DOM to the Instances member of the instance + rapidjson::Value aliasName(newInstanceAlias.c_str(), newInstanceAlias.length(), domToAddDuplicatedInstancesUnder.GetAllocator()); + instancesIter->value.AddMember(AZStd::move(aliasName), nestedInstanceDomAfter, domToAddDuplicatedInstancesUnder.GetAllocator()); + } + + for (auto aliasMapIter : oldInstanceAliasToNewInstanceAliasMap) + { + InstanceAlias newInstanceAlias = aliasMapIter.second; + + AliasPath absoluteInstancePath = commonOwningInstance.GetAbsoluteInstanceAliasPath(); + absoluteInstancePath.Append(newInstanceAlias); + + AZ::EntityId newEntityId = InstanceEntityIdMapper::GenerateEntityIdForAliasPath(absoluteInstancePath); + duplicatedEntityIds.push_back(newEntityId); + } + } + void PrefabPublicHandler::ReplaceOldAliases(QString& stringToReplace, AZStd::string_view oldAlias, AZStd::string_view newAlias) { + // Replace all of the old alias references with the new ones + // We bookend the aliases with \" and also with a / as an extra precaution to prevent + // inadvertently replacing a matching string vs. where an actual EntityId is expected + // This will cover both cases where an alias could be used in a normal entity vs. an instance QString oldAliasQuotes = QString("\"%1\"").arg(oldAlias.data()); QString newAliasQuotes = QString("\"%1\"").arg(newAlias.data()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 99fe8e5b67..167791d1c1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -73,6 +73,33 @@ namespace AzToolsFramework InstanceOptionalReference GetOwnerInstanceByEntityId(AZ::EntityId entityId) const; bool EntitiesBelongToSameInstance(const EntityIdList& entityIds) const; + + /** + * Duplicate a list of entities owned by a common owning instance by directly + * copying/modifying their entries in the instance DOM + * + * \param commonOwningInstance The common owning instance of all the entities being duplicated. + * \param entities The list of Entities that will be duplicated. + * \param domToAddDuplicatedEntitiesUnder The DOM of the common owning instance where the duplicated + * entity DOM values will be added to. + * \param duplicatedEntityIds A list of EntityIds corresponding to the entities that were duplicated. + */ + void DuplicateNestedEntitiesInInstance(Instance& commonOwningInstance, + const AZStd::vector& entities, PrefabDom& domToAddDuplicatedEntitiesUnder, + EntityIdList& duplicatedEntityIds); + /** + * Duplicate a list of instances owned by a common owning instance by directly + * copying/modifying their entries in the instance DOM + * + * \param commonOwningInstance The common owning instance of all the instances being duplicated. + * \param entities The list of Instances that will be duplicated. + * \param domToAddDuplicatedInstancesUnder The DOM of the common owning instance where the duplicated + * instance DOM values will be added to. + * \param duplicatedEntityIds A list of EntityIds corresponding to the instances that were duplicated. + */ + void DuplicateNestedInstancesInInstance(Instance& commonOwningInstance, + const AZStd::vector& instances, PrefabDom& domToAddDuplicatedInstancesUnder, + EntityIdList& duplicatedEntityIds, AZStd::unordered_map& newInstanceAliasToOldInstanceMap); /** * Applies the correct transform changes to the container entity based on the parent and child entities provided, and returns an appropriate patch. From 08a2e50ee34ad1a77009334552a1bd94a59ec7a3 Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 3 Jun 2021 16:28:15 -0700 Subject: [PATCH 493/811] [default_3rdparty] missed updating a call to register --- Code/Tools/ProjectManager/Source/PythonBindings.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 837235cedc..ee4e30846b 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -572,6 +572,7 @@ namespace O3DE::ProjectManager pybind11::none(), // default_gems_folder pybind11::none(), // default_templates_folder pybind11::none(), // default_restricted_folder + pybind11::none(), // default_third_party_folder pybind11::none(), // external_subdir_engine_path pybind11::none(), // external_subdir_project_path true, // remove From 29ac17a090912f483ddb1d6853eea18af8058324 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 3 Jun 2021 18:05:05 -0700 Subject: [PATCH 494/811] SPEC-7135 Provide a method to re-trigger compiler detection for changes that require it (#1092) * SPEC-7135 Provide a method to re-trigger compiler detection for changes that require it * removing check (is wrong and is not necessary) * Invert existance check * add empty lines at the end * Clean is triggering on each build * clearing if the variable is false * test code to understand what is going on... * yeap, looks good * handling "false" in linux/mac * fix for linux/mac * Fixing typos --- scripts/build/Platform/Linux/build_linux.sh | 3 +- scripts/build/Platform/Linux/clean_linux.sh | 37 ++++++++++++++++- scripts/build/Platform/Mac/build_mac.sh | 1 + scripts/build/Platform/Mac/clean_mac.sh | 37 ++++++++++++++++- .../build/Platform/Windows/build_windows.cmd | 3 +- .../build/Platform/Windows/clean_windows.cmd | 41 ++++++++++++++++++- 6 files changed, 116 insertions(+), 6 deletions(-) diff --git a/scripts/build/Platform/Linux/build_linux.sh b/scripts/build/Platform/Linux/build_linux.sh index d96fd32371..ef1b1dcb96 100755 --- a/scripts/build/Platform/Linux/build_linux.sh +++ b/scripts/build/Platform/Linux/build_linux.sh @@ -14,6 +14,7 @@ set -o errexit # exit on the first failure encountered BASEDIR=$(dirname "$0") source $BASEDIR/env_linux.sh +source $BASEDIR/clean_linux.sh mkdir -p ${OUTPUT_DIRECTORY} SOURCE_DIRECTORY=${PWD} @@ -46,4 +47,4 @@ fi echo [ci_build] cmake --build . --target ${CMAKE_TARGET} --config ${CONFIGURATION} -j $(grep -c processor /proc/cpuinfo) -- ${CMAKE_NATIVE_BUILD_ARGS} cmake --build . --target ${CMAKE_TARGET} --config ${CONFIGURATION} -j $(grep -c processor /proc/cpuinfo) -- ${CMAKE_NATIVE_BUILD_ARGS} -popd \ No newline at end of file +popd diff --git a/scripts/build/Platform/Linux/clean_linux.sh b/scripts/build/Platform/Linux/clean_linux.sh index a21527d319..a314859877 100755 --- a/scripts/build/Platform/Linux/clean_linux.sh +++ b/scripts/build/Platform/Linux/clean_linux.sh @@ -12,6 +12,16 @@ set -o errexit # exit on the first failure encountered +# Jenkins defines environment variables for parameters and passes "false" to variables +# that are not set. Here we clear them if they are false so we can also just define them +# from command line +if [[ "${CLEAN_ASSETS}" == "false" ]]; then + CLEAN_ASSETS= +fi +if [[ "${CLEAN_OUTPUT_DIRECTORY}" == "false" ]]; then + CLEAN_OUTPUT_DIRECTORY= +fi + if [[ -n "$CLEAN_ASSETS" ]]; then echo "[ci_build] CLEAN_ASSETS option set" for project in $(echo $CMAKE_LY_PROJECTS | sed "s/;/ /g") @@ -23,10 +33,35 @@ if [[ -n "$CLEAN_ASSETS" ]]; then done fi +# If the node label changes, we issue a clean output since node changes can change SDK/CMake/toolchains/etc +LAST_CONFIGURE_NODE_LABEL_FILE=ci_last_node_label.txt +if [[ -n "$NODE_LABEL" ]]; then + if [[ -d $OUTPUT_DIRECTORY ]]; then + pushd $OUTPUT_DIRECTORY + if [[ -e ${LAST_CONFIGURE_NODE_LABEL_FILE} ]]; then + LAST_NODE_LABEL=$(<${LAST_CONFIGURE_NODE_LABEL_FILE}) + else + LAST_NODE_LABEL= + fi + # Detect if the node label has changed + if [[ "${LAST_NODE_LABEL}" != "${NODE_LABEL}" ]]; then + echo [ci_build] Last run was done with node label \"${LAST_NODE_LABEL}\", new node label is \"${NODE_LABEL}\", forcing CLEAN_OUTPUT_DIRECTORY + CLEAN_OUTPUT_DIRECTORY=1 + fi + popd + fi +fi + if [[ -n "$CLEAN_OUTPUT_DIRECTORY" ]]; then echo "[ci_build] CLEAN_OUTPUT_DIRECTORY option set" if [[ -d $OUTPUT_DIRECTORY ]]; then echo "[ci_build] Deleting \"${OUTPUT_DIRECTORY}\"" rm -rf ${OUTPUT_DIRECTORY} fi -fi \ No newline at end of file +fi + +mkdir -p ${OUTPUT_DIRECTORY} +# Save the node label +pushd $OUTPUT_DIRECTORY +echo "${NODE_LABEL}" > ${LAST_CONFIGURE_NODE_LABEL_FILE} +popd diff --git a/scripts/build/Platform/Mac/build_mac.sh b/scripts/build/Platform/Mac/build_mac.sh index 473a968d98..4a61f97fe4 100755 --- a/scripts/build/Platform/Mac/build_mac.sh +++ b/scripts/build/Platform/Mac/build_mac.sh @@ -14,6 +14,7 @@ set -o errexit # exit on the first failure encountered BASEDIR=$(dirname "$0") source $BASEDIR/env_mac.sh +source $BASEDIR/clean_mac.sh mkdir -p ${OUTPUT_DIRECTORY} SOURCE_DIRECTORY=${PWD} diff --git a/scripts/build/Platform/Mac/clean_mac.sh b/scripts/build/Platform/Mac/clean_mac.sh index a21527d319..a314859877 100755 --- a/scripts/build/Platform/Mac/clean_mac.sh +++ b/scripts/build/Platform/Mac/clean_mac.sh @@ -12,6 +12,16 @@ set -o errexit # exit on the first failure encountered +# Jenkins defines environment variables for parameters and passes "false" to variables +# that are not set. Here we clear them if they are false so we can also just define them +# from command line +if [[ "${CLEAN_ASSETS}" == "false" ]]; then + CLEAN_ASSETS= +fi +if [[ "${CLEAN_OUTPUT_DIRECTORY}" == "false" ]]; then + CLEAN_OUTPUT_DIRECTORY= +fi + if [[ -n "$CLEAN_ASSETS" ]]; then echo "[ci_build] CLEAN_ASSETS option set" for project in $(echo $CMAKE_LY_PROJECTS | sed "s/;/ /g") @@ -23,10 +33,35 @@ if [[ -n "$CLEAN_ASSETS" ]]; then done fi +# If the node label changes, we issue a clean output since node changes can change SDK/CMake/toolchains/etc +LAST_CONFIGURE_NODE_LABEL_FILE=ci_last_node_label.txt +if [[ -n "$NODE_LABEL" ]]; then + if [[ -d $OUTPUT_DIRECTORY ]]; then + pushd $OUTPUT_DIRECTORY + if [[ -e ${LAST_CONFIGURE_NODE_LABEL_FILE} ]]; then + LAST_NODE_LABEL=$(<${LAST_CONFIGURE_NODE_LABEL_FILE}) + else + LAST_NODE_LABEL= + fi + # Detect if the node label has changed + if [[ "${LAST_NODE_LABEL}" != "${NODE_LABEL}" ]]; then + echo [ci_build] Last run was done with node label \"${LAST_NODE_LABEL}\", new node label is \"${NODE_LABEL}\", forcing CLEAN_OUTPUT_DIRECTORY + CLEAN_OUTPUT_DIRECTORY=1 + fi + popd + fi +fi + if [[ -n "$CLEAN_OUTPUT_DIRECTORY" ]]; then echo "[ci_build] CLEAN_OUTPUT_DIRECTORY option set" if [[ -d $OUTPUT_DIRECTORY ]]; then echo "[ci_build] Deleting \"${OUTPUT_DIRECTORY}\"" rm -rf ${OUTPUT_DIRECTORY} fi -fi \ No newline at end of file +fi + +mkdir -p ${OUTPUT_DIRECTORY} +# Save the node label +pushd $OUTPUT_DIRECTORY +echo "${NODE_LABEL}" > ${LAST_CONFIGURE_NODE_LABEL_FILE} +popd diff --git a/scripts/build/Platform/Windows/build_windows.cmd b/scripts/build/Platform/Windows/build_windows.cmd index 3e995e1905..474c1720df 100644 --- a/scripts/build/Platform/Windows/build_windows.cmd +++ b/scripts/build/Platform/Windows/build_windows.cmd @@ -13,6 +13,7 @@ REM SETLOCAL EnableDelayedExpansion CALL %~dp0env_windows.cmd +CALL %~dp0clean_windows.cmd IF NOT EXIST "%OUTPUT_DIRECTORY%" ( MKDIR %OUTPUT_DIRECTORY%. @@ -70,4 +71,4 @@ EXIT /b 0 :error POPD -EXIT /b 1 \ No newline at end of file +EXIT /b 1 diff --git a/scripts/build/Platform/Windows/clean_windows.cmd b/scripts/build/Platform/Windows/clean_windows.cmd index 38c1d45c21..60ad445d4d 100644 --- a/scripts/build/Platform/Windows/clean_windows.cmd +++ b/scripts/build/Platform/Windows/clean_windows.cmd @@ -12,6 +12,16 @@ REM SETLOCAL EnableDelayedExpansion +REM Jenkins defines environment variables for parameters and passes "false" to variables +REM that are not set. Here we clear them if they are false so we can also just define them +REM from command line +IF "%CLEAN_ASSETS%"=="false" ( + set CLEAN_ASSETS= +) +IF "%CLEAN_OUTPUT_DIRECTORY%"=="false" ( + set CLEAN_OUTPUT_DIRECTORY= +) + IF DEFINED CLEAN_ASSETS ( ECHO [ci_build] CLEAN_ASSETS option set FOR %%P in (%CMAKE_LY_PROJECTS%) do ( @@ -19,7 +29,26 @@ IF DEFINED CLEAN_ASSETS ( ECHO [ci_build] Deleting "%%P\Cache" DEL /s /q /f %%P\Cache 1>nul ) - ) + ) +) + +REM If the node label changes, we issue a clean output since node changes can change SDK/CMake/toolchains/etc +SET LAST_CONFIGURE_NODE_LABEL_FILE=ci_last_node_label.txt +IF DEFINED NODE_LABEL ( + IF EXIST %OUTPUT_DIRECTORY% ( + PUSHD %OUTPUT_DIRECTORY% + IF EXIST !LAST_CONFIGURE_NODE_LABEL_FILE! ( + FOR /F "delims=" %%x in (%LAST_CONFIGURE_NODE_LABEL_FILE%) DO SET LAST_NODE_LABEL=%%x + ) ELSE ( + SET LAST_NODE_LABEL= + ) + REM Detect if the node label has changed + IF !LAST_NODE_LABEL! NEQ !NODE_LABEL! ( + ECHO [ci_build] Last run was done with node label "!LAST_NODE_LABEL!", new node label is "!NODE_LABEL!", forcing CLEAN_OUTPUT_DIRECTORY + SET CLEAN_OUTPUT_DIRECTORY=1 + ) + POPD + ) ) IF DEFINED CLEAN_OUTPUT_DIRECTORY ( @@ -28,4 +57,12 @@ IF DEFINED CLEAN_OUTPUT_DIRECTORY ( ECHO [ci_build] Deleting "%OUTPUT_DIRECTORY%" DEL /s /q /f %OUTPUT_DIRECTORY% 1>nul ) -) \ No newline at end of file +) + +IF NOT EXIST "%OUTPUT_DIRECTORY%" ( + MKDIR %OUTPUT_DIRECTORY%. +) +REM Save the node label +PUSHD %OUTPUT_DIRECTORY% +ECHO !NODE_LABEL!> !LAST_CONFIGURE_NODE_LABEL_FILE! +POPD From 4405c2275fdc38e04d3d075eaf5e4c8a0a56ea86 Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 3 Jun 2021 18:23:01 -0700 Subject: [PATCH 495/811] [default_3rdparty] changed CLI argument type to pathlib.Path and removed optional str type from usage --- scripts/o3de/o3de/register.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/o3de/o3de/register.py b/scripts/o3de/o3de/register.py index 2e37f04acf..4e73edca7f 100644 --- a/scripts/o3de/o3de/register.py +++ b/scripts/o3de/o3de/register.py @@ -521,7 +521,7 @@ def register_default_restricted_folder(json_data: dict, 'default_restricted_folder') def register_default_third_party_folder(json_data: dict, - default_third_party_folder: str or pathlib.Path, + default_third_party_folder: pathlib.Path, remove: bool = False) -> int: return register_default_o3de_object_folder(json_data, manifest.get_o3de_third_party_folder() if remove else default_third_party_folder, @@ -539,7 +539,7 @@ def register(engine_path: str or pathlib.Path = None, default_gems_folder: str or pathlib.Path = None, default_templates_folder: str or pathlib.Path = None, default_restricted_folder: str or pathlib.Path = None, - default_third_party_folder: str or pathlib.Path = None, + default_third_party_folder: pathlib.Path = None, external_subdir_engine_path: pathlib.Path = None, external_subdir_project_path: pathlib.Path = None, remove: bool = False, @@ -628,7 +628,7 @@ def register(engine_path: str or pathlib.Path = None, elif isinstance(default_restricted_folder, str) or isinstance(default_restricted_folder, pathlib.PurePath): result = register_default_restricted_folder(json_data, default_restricted_folder, remove) - elif isinstance(default_third_party_folder, str) or isinstance(default_third_party_folder, pathlib.PurePath): + elif default_third_party_folder: result = register_default_third_party_folder(json_data, default_third_party_folder, remove) # engine is done LAST @@ -825,7 +825,7 @@ def add_parser_args(parser): help='The default templates folder to register/remove.') group.add_argument('-drf', '--default-restricted-folder', type=str, required=False, help='The default restricted folder to register/remove.') - group.add_argument('-dtpf', '--default-third-party-folder', type=str, required=False, + group.add_argument('-dtpf', '--default-third-party-folder', type=pathlib.Path, required=False, help='The default 3rd Party folder to register/remove.') group.add_argument('-u', '--update', action='store_true', required=False, default=False, From 9e7f8e45ebb073c3cb58bb2157d7368fb77f96d0 Mon Sep 17 00:00:00 2001 From: scottr Date: Thu, 3 Jun 2021 18:23:54 -0700 Subject: [PATCH 496/811] [default_3rdparty] fixed typo --- Code/Tools/ProjectManager/Source/PythonBindings.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index ee4e30846b..37e636caef 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -421,7 +421,7 @@ namespace O3DE::ProjectManager pybind11::str defaultProjectsFolder = engineInfo.m_defaultProjectsFolder.toStdString(); pybind11::str defaultGemsFolder = engineInfo.m_defaultGemsFolder.toStdString(); pybind11::str defaultTemplatesFolder = engineInfo.m_defaultTemplatesFolder.toStdString(); - pybind11::str defaultThridPartyFolder = engineInfo.m_thirdPartyPath.toStdString(); + pybind11::str defaultThirdPartyFolder = engineInfo.m_thirdPartyPath.toStdString(); auto registrationResult = m_register.attr("register")( enginePath, // engine_path @@ -436,7 +436,7 @@ namespace O3DE::ProjectManager defaultGemsFolder, defaultTemplatesFolder, pybind11::none(), // default_restricted_folder - defaultThridPartyFolder + defaultThirdPartyFolder ); if (registrationResult.cast() != 0) From 2449a9322d20d8e91afd4b7cb8813fbcd628429f Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Thu, 3 Jun 2021 18:40:44 -0700 Subject: [PATCH 497/811] Changed the occlusion culling plane model to be on the XZ plane and adjusted the corner point computations --- .../Common/Assets/Models/OcclusionCullingPlane.fbx | 4 ++-- .../OcclusionCullingPlaneFeatureProcessor.cpp | 10 +++++----- Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h | 2 +- Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp | 10 +++++----- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Models/OcclusionCullingPlane.fbx b/Gems/Atom/Feature/Common/Assets/Models/OcclusionCullingPlane.fbx index b274bfa282..f91d1015f9 100644 --- a/Gems/Atom/Feature/Common/Assets/Models/OcclusionCullingPlane.fbx +++ b/Gems/Atom/Feature/Common/Assets/Models/OcclusionCullingPlane.fbx @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0a1f8d75dcd85e8b4aa57f6c0c81af0300ff96915ba3c2b591095c215d5e1d8c -size 12072 +oid sha256:75cdf73fcb9698a76a38294a1cf927a4fb41a34869e0429e1f02bf8d361a7258 +size 20400 diff --git a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp index ff7c32ba08..3c61f616d9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/OcclusionCullingPlane/OcclusionCullingPlaneFeatureProcessor.cpp @@ -64,18 +64,18 @@ namespace AZ RPI::CullingScene::OcclusionPlane rpiOcclusionPlane; - static const Vector3 BL = Vector3(-0.5f, -0.5f, 0.0f); - static const Vector3 BR = Vector3(0.5f, -0.5f, 0.0f); - static const Vector3 TL = Vector3(-0.5f, 0.5f, 0.0f); - static const Vector3 TR = Vector3(0.5f, 0.5f, 0.0f); + static const Vector3 BL = Vector3(-0.5f, 0.0f, -0.5f); + static const Vector3 TL = Vector3(-0.5f, 0.0f, 0.5f); + static const Vector3 TR = Vector3( 0.5f, 0.0f, 0.5f); + static const Vector3 BR = Vector3( 0.5f, 0.0f, -0.5f); const AZ::Transform& transform = occlusionCullingPlane->GetTransform(); // convert corners to world space rpiOcclusionPlane.m_cornerBL = transform.TransformPoint(BL); - rpiOcclusionPlane.m_cornerBR = transform.TransformPoint(BR); rpiOcclusionPlane.m_cornerTL = transform.TransformPoint(TL); rpiOcclusionPlane.m_cornerTR = transform.TransformPoint(TR); + rpiOcclusionPlane.m_cornerBR = transform.TransformPoint(BR); // build world space AABB AZ::Vector3 aabbMin = rpiOcclusionPlane.m_cornerBL.GetMin(rpiOcclusionPlane.m_cornerTR); diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h index 2a9c133b5c..2354a4feea 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Culling.h @@ -219,9 +219,9 @@ namespace AZ { // World space corners of the occluson plane Vector3 m_cornerBL; - Vector3 m_cornerBR; Vector3 m_cornerTL; Vector3 m_cornerTR; + Vector3 m_cornerBR; Aabb m_aabb; }; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index 7ee2c4a8d2..9f0a17f294 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -574,18 +574,18 @@ namespace AZ { // convert to clip-space Vector4 projectedBL = view.GetWorldToClipMatrix() * Vector4(occlusionPlane.first.m_cornerBL); - Vector4 projectedBR = view.GetWorldToClipMatrix() * Vector4(occlusionPlane.first.m_cornerBR); Vector4 projectedTL = view.GetWorldToClipMatrix() * Vector4(occlusionPlane.first.m_cornerTL); Vector4 projectedTR = view.GetWorldToClipMatrix() * Vector4(occlusionPlane.first.m_cornerTR); + Vector4 projectedBR = view.GetWorldToClipMatrix() * Vector4(occlusionPlane.first.m_cornerBR); // store to float array float verts[16]; projectedBL.StoreToFloat4(&verts[0]); - projectedBR.StoreToFloat4(&verts[4]); - projectedTL.StoreToFloat4(&verts[8]); - projectedTR.StoreToFloat4(&verts[12]); + projectedTL.StoreToFloat4(&verts[4]); + projectedTR.StoreToFloat4(&verts[8]); + projectedBR.StoreToFloat4(&verts[12]); - static uint32_t indices[6] = { 0, 2, 1, 2, 3, 1 }; + static uint32_t indices[6] = { 0, 1, 2, 2, 3, 0 }; // render into the occlusion buffer, specifying BACKFACE_NONE so it functions as a double-sided occluder maskedOcclusionCulling->RenderTriangles((float*)verts, indices, 2, nullptr, MaskedOcclusionCulling::BACKFACE_NONE); From fe98c34f5060ffe9053932eb0b71838d494787dc Mon Sep 17 00:00:00 2001 From: rhongAMZ <69218254+rhongAMZ@users.noreply.github.com> Date: Thu, 3 Jun 2021 19:59:29 -0700 Subject: [PATCH 498/811] EMFX - Refactor the emfx actor asset loading. (#1101) Refactor emfx asset loading. The mesh asset, skinMetaAsset and morphTargetMeta asset are part of the dependency. --- .../CommandSystem/Source/ImporterCommands.cpp | 5 +- .../RCExt/Actor/ActorGroupExporter.cpp | 52 +++-- .../Pipeline/RCExt/Actor/ActorGroupExporter.h | 3 + .../EMotionFX/Code/EMotionFX/Source/Actor.cpp | 183 ++++++------------ Gems/EMotionFX/Code/EMotionFX/Source/Actor.h | 43 ++-- .../Source/Integration/Assets/ActorAsset.cpp | 3 + .../Integration/Components/ActorComponent.cpp | 46 +---- .../Integration/Components/ActorComponent.h | 4 - .../Components/EditorActorComponent.cpp | 39 +--- .../Editor/Components/EditorActorComponent.h | 4 - 10 files changed, 137 insertions(+), 245 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.cpp index ff05b603c0..08e1ddbb08 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.cpp @@ -94,8 +94,9 @@ namespace CommandSystem return false; } - actor->LoadRemainingAssets(); - actor->CheckFinalizeActor(); + // Because the actor is directly loaded from disk (without going through an actor asset), we need to ask for a blocking + // load for the asset that actor is depend on. + actor->Finalize(EMotionFX::Actor::LoadRequirement::RequireBlockingLoad); // set the actor id in case we have specified it as parameter if (actorID != MCORE_INVALIDINDEX32) diff --git a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp index c7c6b86aea..d5f53e72c5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp @@ -52,7 +52,7 @@ namespace EMotionFX AZ::SerializeContext* serializeContext = azrtti_cast(context); if (serializeContext) { - serializeContext->Class()->Version(1); + serializeContext->Class()->Version(2); } } @@ -117,21 +117,6 @@ namespace EMotionFX ExporterLib::SaveActor(filename, m_actor.get(), MCore::Endian::ENDIAN_LITTLE, GetMeshAssetId(context)); -#ifdef EMOTIONFX_ACTOR_DEBUG - // Use there line to create a log file and inspect detail debug info - AZStd::string folderPath; - AzFramework::StringFunc::Path::GetFolderPath(filename.c_str(), folderPath); - AZStd::string logFilename = folderPath; - logFilename += "EMotionFXExporter_Log.txt"; - MCore::GetLogManager().CreateLogFile(logFilename.c_str()); - EMotionFX::GetImporter().SetLogDetails(true); - filename += ".xac"; - - // use this line to load the actor from the saved actor file - EMotionFX::Actor* testLoadingActor = EMotionFX::GetImporter().LoadActor(AZStd::string(filename.c_str())); - MCore::Destroy(testLoadingActor); -#endif // EMOTIONFX_ACTOR_DEBUG - static AZ::Data::AssetType emotionFXActorAssetType("{F67CC648-EA51-464C-9F5D-4A9CE41A7F86}"); // from ActorAsset.h in EMotionFX Gem AZ::SceneAPI::Events::ExportProduct& product = context.m_products.AddProduct(AZStd::move(filename), context.m_group.GetId(), emotionFXActorAssetType, AZStd::nullopt, AZStd::nullopt); @@ -141,6 +126,26 @@ namespace EMotionFX product.m_legacyPathDependencies.emplace_back(AZStd::move(materialPathReference)); } + // Mesh asset, skin meta asset and morph target meta asset are sub assets for actor asset. + // In here we set them as the dependency of the actor asset. That make sure those assets get automatically loaded before actor asset. + // Default to the first product until we are able to establish a link between mesh and actor (ATOM-13590). + const AZ::Data::AssetType assetDependencyList[] = { + azrtti_typeid(), + azrtti_typeid(), + azrtti_typeid() + }; + + for (const AZ::Data::AssetType& assetDependency : assetDependencyList) + { + AZStd::optional result = GetFirstProductByType(context, assetDependency); + if (result != AZStd::nullopt) + { + AZ::SceneAPI::Events::ExportProduct exportProduct = result.value(); + exportProduct.m_dependencyFlags = AZ::Data::ProductDependencyInfo::CreateFlags(AZ::Data::AssetLoadBehavior::PreLoad); + product.m_productDependencies.emplace_back(exportProduct); + } + } + return SceneEvents::ProcessingResult::Success; } @@ -171,5 +176,20 @@ namespace EMotionFX return AZStd::nullopt; } + + AZStd::optional ActorGroupExporter::GetFirstProductByType( + const ActorGroupExportContext& context, AZ::Data::AssetType type) + { + const AZStd::vector& products = context.m_products.GetProducts(); + for (const AZ::SceneAPI::Events::ExportProduct& product : products) + { + if (product.m_assetType == type) + { + return product; + } + } + + return AZStd::nullopt; + } } // namespace Pipeline } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.h b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.h index 451d1f4bb4..585126c07b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.h +++ b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.h @@ -14,6 +14,7 @@ #include #include #include +#include #include @@ -44,6 +45,8 @@ namespace EMotionFX //! Get the mesh asset id to which the actor is linked to by default. AZStd::optional GetMeshAssetId(const ActorGroupExportContext& context) const; + static AZStd::optional GetFirstProductByType( + const ActorGroupExportContext& context, AZ::Data::AssetType type); AutoRegisteredActor m_actor; AZStd::vector m_actorMaterialReferences; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp index 403e7ec05a..67f0773aec 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -125,7 +125,6 @@ namespace EMotionFX Actor::~Actor() { - AZ::Data::AssetBus::MultiHandler::BusDisconnect(); ActorNotificationBus::Broadcast(&ActorNotificationBus::Events::OnActorDestroyed, this); GetEventManager().OnDeleteActor(this); @@ -1463,108 +1462,78 @@ namespace EMotionFX return morphTargetMetaAssetInfo.m_assetId.IsValid(); } - void Actor::OnAssetReady(AZ::Data::Asset asset) - { - if (asset == m_meshAsset) - { - m_meshAsset = asset; - } - if (asset == m_skinMetaAsset) - { - m_skinMetaAsset = asset; - } - if (asset == m_morphTargetMetaAsset) - { - m_morphTargetMetaAsset = asset; - } - - CheckFinalizeActor(); - } - - void Actor::CheckFinalizeActor() + void Actor::Finalize(LoadRequirement loadReq) { AZStd::scoped_lock lock(m_mutex); - if (m_meshAsset.IsReady()) + // Load the mesh asset, skin meta asset and morph target asset. + // Those sub assets should have already been setup as dependency of actor asset, so they should already be loaded when we reach here. + // Only exception is that when the actor is not loaded by an actor asset, for which we need to do a blocking load. + if (m_meshAssetId.IsValid()) { - const AZ::Data::AssetId meshAssetId = m_meshAsset.GetId(); - const bool skinMetaAssetExists = DoesSkinMetaAssetExist(meshAssetId); - const bool morphTargetMetaAssetExists = DoesMorphTargetMetaAssetExist(m_meshAsset.GetId()); + // Get the mesh asset. + m_meshAsset = AZ::Data::AssetManager::Instance().GetAsset(m_meshAssetId, AZ::Data::AssetLoadBehavior::PreLoad); - m_skinToSkeletonIndexMap.clear(); - - // Skin and morph target meta assets are ready, fill the runtime mesh data. - if ((!skinMetaAssetExists || m_skinMetaAsset.IsReady()) && - (!morphTargetMetaAssetExists || m_morphTargetMetaAsset.IsReady())) + // Get the skin meta asset. + const AZ::Data::AssetId skinMetaAssetId = ConstructSkinMetaAssetId(m_meshAssetId); + if (DoesSkinMetaAssetExist(m_meshAssetId) && skinMetaAssetId.IsValid()) { - // Optional, not all actors have a skinned meshes. - if (skinMetaAssetExists) + m_skinMetaAsset = AZ::Data::AssetManager::Instance().GetAsset( + skinMetaAssetId, AZ::Data::AssetLoadBehavior::PreLoad); + } + + // Get the morph target meta asset. + const AZ::Data::AssetId morphTargetMetaAssetId = ConstructMorphTargetMetaAssetId(m_meshAssetId); + if (DoesMorphTargetMetaAssetExist(m_meshAssetId) && morphTargetMetaAssetId.IsValid()) + { + m_morphTargetMetaAsset = AZ::Data::AssetManager::Instance().GetAsset( + morphTargetMetaAssetId, AZ::Data::AssetLoadBehavior::PreLoad); + } + + if (loadReq == LoadRequirement::RequireBlockingLoad) + { + if (m_skinMetaAsset.IsLoading()) { - m_skinToSkeletonIndexMap = ConstructSkinToSkeletonIndexMap(m_skinMetaAsset); + m_skinMetaAsset.BlockUntilLoadComplete(); } - - ConstructMeshes(m_skinToSkeletonIndexMap); - - // Optional, not all actors have morph targets. - if (morphTargetMetaAssetExists) + if (m_morphTargetMetaAsset.IsLoading()) { - ConstructMorphTargets(); + m_morphTargetMetaAsset.BlockUntilLoadComplete(); } - else + if (m_meshAsset.IsLoading()) { - // Optional, not all actors have morph targets. - const size_t numLODLevels = m_meshAsset->GetLodAssets().size(); - mMorphSetups.Resize(numLODLevels); - for (AZ::u32 i = 0; i < numLODLevels; ++i) - { - mMorphSetups[i] = nullptr; - } + m_meshAsset.BlockUntilLoadComplete(); } - - SetActorReady(); - - // Do not release the mesh assets. We need the mesh data to initialize future instances of the render actor instances. - //m_meshAsset.Release(); - //m_skinMetaAsset.Release(); - //m_morphTargetMetaAsset.Release(); } } - } - void Actor::LoadRemainingAssets() - { - // Everything is ready already or no (skeleton-only) or an invalid mesh asset assigned. Emit ready signal directly. - if (m_isReady || !m_meshAssetId.IsValid()) + if (m_meshAsset.IsReady()) { - SetActorReady(); - return; + if (m_skinMetaAsset.IsReady()) + { + m_skinToSkeletonIndexMap = ConstructSkinToSkeletonIndexMap(m_skinMetaAsset); + } + ConstructMeshes(); + + if (m_morphTargetMetaAsset.IsReady()) + { + ConstructMorphTargets(); + } + else + { + // Optional, not all actors have morph targets. + const size_t numLODLevels = m_meshAsset->GetLodAssets().size(); + mMorphSetups.Resize(numLODLevels); + for (AZ::u32 i = 0; i < numLODLevels; ++i) + { + mMorphSetups[i] = nullptr; + } + } } - LoadMeshAssetsQueued(); - } - - void Actor::OnAssetReloaded(AZ::Data::Asset asset) - { - if (asset == m_meshAsset) - { - m_meshAsset = asset; - } - if (asset == m_skinMetaAsset) - { - m_skinMetaAsset = asset; - } - if (asset == m_morphTargetMetaAsset) - { - m_morphTargetMetaAsset = asset; - } - - CheckFinalizeActor(); - } - - void Actor::SetActorReady() - { m_isReady = true; ActorNotificationBus::Broadcast(&ActorNotificationBus::Events::OnActorReady, this); + // Do not release the mesh assets. We need the mesh data to initialize future instances of the render actor instances. } // update the static AABB (very heavy as it has to create an actor instance, update mesh deformers, calculate the mesh based bounds etc) @@ -2792,37 +2761,6 @@ namespace EMotionFX m_meshAssetId = assetId; } - void Actor::LoadMeshAssetsQueued() - { - AZStd::scoped_lock lock(m_mutex); - - // Mesh asset will be queue loaded on post init. - if (m_meshAssetId.IsValid()) - { - m_isReady = false; - AZ::Data::AssetBus::MultiHandler::BusDisconnect(); - - AZ::Data::AssetBus::MultiHandler::BusConnect(m_meshAssetId); - m_meshAsset = AZ::Data::AssetManager::Instance().GetAsset(m_meshAssetId, AZ::Data::AssetLoadBehavior::Default); - - // Skin meta asset - if (DoesSkinMetaAssetExist(m_meshAssetId)) - { - const AZ::Data::AssetId skinMetaAssetId = ConstructSkinMetaAssetId(m_meshAssetId); - AZ::Data::AssetBus::MultiHandler::BusConnect(skinMetaAssetId); - m_skinMetaAsset = AZ::Data::AssetManager::Instance().GetAsset(skinMetaAssetId, AZ::Data::AssetLoadBehavior::Default); - } - - // Morph target meta asset - if (DoesMorphTargetMetaAssetExist(m_meshAssetId)) - { - const AZ::Data::AssetId morphTargetMetaAssetId = ConstructMorphTargetMetaAssetId(m_meshAssetId); - AZ::Data::AssetBus::MultiHandler::BusConnect(morphTargetMetaAssetId); - m_morphTargetMetaAsset = AZ::Data::AssetManager::Instance().GetAsset(morphTargetMetaAssetId, AZ::Data::AssetLoadBehavior::Default); - } - } - } - Node* Actor::FindMeshJoint(const AZ::Data::Asset& lodModelAsset) const { const AZStd::array_view& sourceMeshes = lodModelAsset->GetMeshes(); @@ -2843,7 +2781,7 @@ namespace EMotionFX return mSkeleton->GetNode(0); } - void Actor::ConstructMeshes(const AZStd::unordered_map& skinToSkeletonIndexMap) + void Actor::ConstructMeshes() { AZ_Assert(m_meshAsset.IsReady(), "Mesh asset should be fully loaded and ready."); @@ -2855,7 +2793,8 @@ namespace EMotionFX SetNumLODLevels(numLODLevels, /*adjustMorphSetup=*/false); const uint32 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. + // Remove all the materials and add them back based on the meshAsset. Eventually we will remove all the material from Actor and + // GLActor. RemoveAllMaterials(); mMaterials.Resize(numLODLevels); @@ -2866,7 +2805,7 @@ namespace EMotionFX lodLevels[lodLevel].mNodeInfos.Resize(numNodes); // Create a single mesh for the actor. - Mesh* mesh = Mesh::CreateFromModelLod(lodAsset, skinToSkeletonIndexMap); + Mesh* mesh = Mesh::CreateFromModelLod(lodAsset, m_skinToSkeletonIndexMap); // Find an owning joint for the mesh. Node* meshJoint = FindMeshJoint(lodAsset); @@ -2896,13 +2835,14 @@ namespace EMotionFX continue; } - EMotionFX::SkinningInfoVertexAttributeLayer* skinLayer = static_cast(vertexAttributeLayer); + EMotionFX::SkinningInfoVertexAttributeLayer* skinLayer = + static_cast(vertexAttributeLayer); const AZ::u32 numOrgVerts = skinLayer->GetNumAttributes(); AZStd::set localJointIndices = skinLayer->CalcLocalJointIndices(numOrgVerts); const AZ::u32 numLocalJoints = static_cast(localJointIndices.size()); - // 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. + // 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. const bool dualQuatSkinning = true; if (dualQuatSkinning) { @@ -2970,7 +2910,8 @@ namespace EMotionFX void Actor::ConstructMorphTargets() { - AZ_Assert(m_meshAsset.IsReady() && m_morphTargetMetaAsset.IsReady(), "Mesh as well as morph target meta asset asset should be fully loaded and ready."); + AZ_Assert(m_meshAsset.IsReady() && m_morphTargetMetaAsset.IsReady(), + "Mesh as well as morph target meta asset asset should be fully loaded and ready."); AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; const AZStd::array_view>& lodAssets = m_meshAsset->GetLodAssets(); const size_t numLODLevels = lodAssets.size(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h index 9bf0daf046..3fe9711f18 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h @@ -63,7 +63,6 @@ namespace EMotionFX * still share the same data from the Actor class. The Actor contains information about the hierarchy/structure of the characters. */ class EMFX_API Actor - : private AZ::Data::AssetBus::MultiHandler { public: AZ_CLASS_ALLOCATOR_DECL @@ -101,6 +100,12 @@ namespace EMotionFX uint8 mFlags; // bitfield with MIRRORFLAG_ prefix }; + enum class LoadRequirement : bool + { + RequireBlockingLoad, + AllowAsyncLoad + }; + //------------------------------------------------ /** @@ -885,36 +890,35 @@ namespace EMotionFX bool GetOptimizeSkeleton() const { return m_optimizeSkeleton; } void SetMeshAssetId(const AZ::Data::AssetId& assetId); - void CheckFinalizeActor(); - void LoadMeshAssetsQueued(); - void LoadRemainingAssets(); + AZ::Data::AssetId GetMeshAssetId() const { return m_meshAssetId; }; const AZ::Data::Asset& GetMeshAsset() const { return m_meshAsset; } const AZ::Data::Asset& GetSkinMetaAsset() const { return m_skinMetaAsset; } const AZ::Data::Asset& GetMorphTargetMetaAsset() const { return m_morphTargetMetaAsset; } - const AZStd::unordered_map& GetSkinToSkeletonIndexMap() const { return m_skinToSkeletonIndexMap; } - void SetMeshAsset(AZ::Data::Asset asset) { m_meshAsset = asset; } - void SetSkinMetaAsset(AZ::Data::Asset asset) { m_skinMetaAsset = asset; } - void SetMorphTargetMetaAsset(AZ::Data::Asset asset) { m_morphTargetMetaAsset = asset; } + /** + * Is the actor fully ready? + * @result True in case the actor as well as its dependent files (e.g. mesh, skin, morph targets) are fully loaded and initialized. + **/ + bool IsReady() const { return m_isReady; } /** - * Is the actor fully ready? - * @result True in case the actor as well as its dependent files (e.g. mesh, skin, morph targets) are fully loaded and initialized. - **/ - bool IsReady() const { return m_isReady; } + * Finalize the actor with preload assets (mesh, skinmeta and morph target assets). + * LoadRequirement - We won't need a blocking load if the actor is part of the actor asset, as that will trigger the preload assets + * to load and get ready before finalize has been reached. + * However, if we are calling this on an actor that bypassed the asset system (e.g loading the actor directly from disk), it will require + * a blocking load. This option is now being used because emfx editor does not fully integrate with the asset system. + */ + void Finalize(LoadRequirement loadReq = LoadRequirement::AllowAsyncLoad); private: void InsertJointAndParents(AZ::u32 jointIndex, AZStd::unordered_set& includedJointIndices); - // AZ::Data::AssetBus::Handler - void OnAssetReady(AZ::Data::Asset asset) override; - void OnAssetReloaded(AZ::Data::Asset asset) override; - AZStd::unordered_map ConstructSkinToSkeletonIndexMap(const AZ::Data::Asset& skinMetaAsset); - void ConstructMeshes(const AZStd::unordered_map& skinToSkeletonIndexMap); + void ConstructMeshes(); void ConstructMorphTargets(); + Node* FindJointByMeshName(const AZStd::string_view meshName) const; // per node info (shared between lods) @@ -966,9 +970,6 @@ namespace EMotionFX Node* FindMeshJoint(const AZ::Data::Asset& lodModelAsset) const; - void SetActorReady(); - bool m_isReady = false; - Skeleton* mSkeleton; /**< The skeleton, containing the nodes and bind pose. */ MCore::Array mDependencies; /**< The dependencies on other actors (shared meshes and transforms). */ AZStd::vector mNodeInfos; /**< The per node info, shared between lods. */ @@ -992,7 +993,7 @@ namespace EMotionFX bool mDirtyFlag; /**< The dirty flag which indicates whether the user has made changes to the actor since the last file save operation. */ bool mUsedForVisualization; /**< Indicates if the actor is used for visualization specific things and is not used as a normal in-game actor. */ bool m_optimizeSkeleton; /**< Indicates if we should perform/ */ - + bool m_isReady = false; /**< If actor as well as its dependent files are fully loaded and initialized.*/ #if defined(EMFX_DEVELOPMENT_BUILD) bool mIsOwnedByRuntime; /**< Set if the actor is used/owned by the engine runtime. */ #endif // EMFX_DEVELOPMENT_BUILD diff --git a/Gems/EMotionFX/Code/Source/Integration/Assets/ActorAsset.cpp b/Gems/EMotionFX/Code/Source/Integration/Assets/ActorAsset.cpp index 518db289e2..539b656754 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Assets/ActorAsset.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Assets/ActorAsset.cpp @@ -68,6 +68,9 @@ namespace EMotionFX &actorSettings, ""); + assetData->m_emfxActor->Finalize(); + + // Clear out the EMFX raw asset data. assetData->ReleaseEMotionFXData(); if (!assetData->m_emfxActor) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp index 982b62fbcf..f41ef165c8 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp @@ -154,17 +154,15 @@ namespace EMotionFX Actor* actor = m_configuration.m_actorAsset->GetActor(); if (actor) { - OnActorReady(actor); + CheckActorCreation(); } } ////////////////////////////////////////////////////////////////////////// ActorComponent::ActorComponent(const Configuration* configuration) : m_debugDrawRoot(false) - , m_sceneFinishSimHandler([this]( - [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - float fixedDeltatime - ) + , m_sceneFinishSimHandler([this]([[maybe_unused]] AzPhysics::SceneHandle sceneHandle, + float fixedDeltatime) { if (m_actorInstance) { @@ -192,18 +190,9 @@ namespace EMotionFX if (cfg.m_actorAsset.GetId().IsValid()) { - EMotionFX::ActorNotificationBus::Handler::BusDisconnect(); AZ::Data::AssetBus::Handler::BusDisconnect(); - EMotionFX::ActorNotificationBus::Handler::BusConnect(); AZ::Data::AssetBus::Handler::BusConnect(cfg.m_actorAsset.GetId()); cfg.m_actorAsset.QueueLoad(); - - // In case the asset was already loaded fully, create the actor directly. - if (cfg.m_actorAsset.IsReady() && - cfg.m_actorAsset->GetActor()) - { - cfg.m_actorAsset->GetActor()->LoadRemainingAssets(); - } } AZ::TickBus::Handler::BusConnect(); @@ -231,7 +220,6 @@ namespace EMotionFX LmbrCentral::AttachmentComponentNotificationBus::Handler::BusDisconnect(); AZ::TransformNotificationBus::MultiHandler::BusDisconnect(); AZ::Data::AssetBus::Handler::BusDisconnect(); - EMotionFX::ActorNotificationBus::Handler::BusDisconnect(); DestroyActor(); m_configuration.m_actorAsset.Release(); @@ -314,28 +302,12 @@ namespace EMotionFX Actor* actor = m_configuration.m_actorAsset->GetActor(); AZ_Assert(m_configuration.m_actorAsset.IsReady() && actor, "Actor asset should be loaded and actor valid."); - actor->LoadRemainingAssets(); - actor->CheckFinalizeActor(); + CheckActorCreation(); } void ActorComponent::OnAssetReloaded(AZ::Data::Asset asset) { - DestroyActor(); - m_configuration.m_actorAsset = asset; - - const Actor* oldActor = m_configuration.m_actorAsset->GetActor(); - AZ::Data::Asset meshAsset = oldActor->GetMeshAsset(); - AZ::Data::Asset skinMetaAsset = oldActor->GetSkinMetaAsset(); - AZ::Data::Asset morphTargetMetaAsset = oldActor->GetMorphTargetMetaAsset(); - - m_configuration.m_actorAsset = asset; - Actor* newActor = m_configuration.m_actorAsset->GetActor(); - AZ_Assert(m_configuration.m_actorAsset.IsReady() && newActor, "Actor asset should be loaded and actor valid."); - - newActor->SetMeshAsset(meshAsset); - newActor->SetSkinMetaAsset(skinMetaAsset); - newActor->SetMorphTargetMetaAsset(morphTargetMetaAsset); - newActor->CheckFinalizeActor(); + OnAssetReady(asset); } bool ActorComponent::IsPhysicsSceneSimulationFinishEventConnected() const @@ -850,13 +822,5 @@ namespace EMotionFX m_actorInstance->RemoveAttachment(targetActorInstance); } } - - void ActorComponent::OnActorReady(Actor* actor) - { - if (m_configuration.m_actorAsset && m_configuration.m_actorAsset->GetActor() == actor) - { - CheckActorCreation(); - } - } } // namespace Integration } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h index 8188da19b4..4172ce63bc 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h @@ -44,7 +44,6 @@ namespace EMotionFX , private LmbrCentral::AttachmentComponentNotificationBus::Handler , private AzFramework::CharacterPhysicsDataRequestBus::Handler , private AzFramework::RagdollPhysicsNotificationBus::Handler - , private EMotionFX::ActorNotificationBus::Handler { public: AZ_COMPONENT(ActorComponent, "{BDC97E7F-A054-448B-A26F-EA2B5D78E377}"); @@ -168,9 +167,6 @@ namespace EMotionFX void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; int GetTickOrder() override; - // ActorNotificationBus::Handler - void OnActorReady(Actor* actor) override; - void CheckActorCreation(); void DestroyActor(); void CheckAttachToEntity(); diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index d22bb0007f..7d5b7ade00 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp @@ -156,8 +156,6 @@ namespace EMotionFX ////////////////////////////////////////////////////////////////////////// void EditorActorComponent::Activate() { - EMotionFX::ActorNotificationBus::Handler::BusConnect(); - LoadActorAsset(); const AZ::EntityId entityId = GetEntityId(); @@ -186,8 +184,6 @@ namespace EMotionFX AZ::TickBus::Handler::BusDisconnect(); AZ::Data::AssetBus::Handler::BusDisconnect(); - EMotionFX::ActorNotificationBus::Handler::BusDisconnect(); - DestroyActorInstance(); m_actorAsset.Release(); } @@ -234,13 +230,6 @@ namespace EMotionFX AZ::Data::AssetBus::Handler::BusDisconnect(); AZ::Data::AssetBus::Handler::BusConnect(m_actorAsset.GetId()); m_actorAsset.QueueLoad(); - - // In case the asset was already loaded fully, create the actor directly. - if (m_actorAsset.IsReady() && - m_actorAsset->GetActor()) - { - m_actorAsset->GetActor()->LoadRemainingAssets(); - } } else { @@ -475,27 +464,13 @@ namespace EMotionFX Actor* actor = m_actorAsset->GetActor(); AZ_Assert(m_actorAsset.IsReady() && actor, "Actor asset should be loaded and actor valid."); - actor->LoadRemainingAssets(); - actor->CheckFinalizeActor(); + CheckActorCreation(); } void EditorActorComponent::OnAssetReloaded(AZ::Data::Asset asset) { DestroyActorInstance(); - - const Actor* oldActor = m_actorAsset->GetActor(); - AZ::Data::Asset meshAsset = oldActor->GetMeshAsset(); - AZ::Data::Asset skinMetaAsset = oldActor->GetSkinMetaAsset(); - AZ::Data::Asset morphTargetMetaAsset = oldActor->GetMorphTargetMetaAsset(); - - m_actorAsset = asset; - Actor* newActor = m_actorAsset->GetActor(); - AZ_Assert(m_actorAsset.IsReady() && newActor, "Actor asset should be loaded and actor valid."); - - newActor->SetMeshAsset(meshAsset); - newActor->SetSkinMetaAsset(skinMetaAsset); - newActor->SetMorphTargetMetaAsset(morphTargetMetaAsset); - newActor->CheckFinalizeActor(); + OnAssetReady(asset); } void EditorActorComponent::SetActorAsset(AZ::Data::Asset actorAsset) @@ -505,7 +480,7 @@ namespace EMotionFX Actor* actor = m_actorAsset->GetActor(); if (actor) { - OnActorReady(actor); + CheckActorCreation(); } } @@ -818,14 +793,6 @@ namespace EMotionFX return false; } - void EditorActorComponent::OnActorReady(Actor* actor) - { - if (m_actorAsset && m_actorAsset->GetActor() == actor) - { - CheckActorCreation(); - } - } - void EditorActorComponent::CheckActorCreation() { // Enable/disable debug drawing. diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.h index 8ddd95c3b7..5dabbe4ada 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.h @@ -45,7 +45,6 @@ namespace EMotionFX , private AzToolsFramework::EditorComponentSelectionRequestsBus::Handler , private AzToolsFramework::EditorVisibilityNotificationBus::Handler , public AzFramework::BoundsRequestBus::Handler - , private EMotionFX::ActorNotificationBus::Handler { public: AZ_EDITOR_COMPONENT(EditorActorComponent, "{A863EE1B-8CFD-4EDD-BA0D-1CEC2879AD44}"); @@ -142,9 +141,6 @@ namespace EMotionFX void OnAttached(AZ::EntityId targetId) override; void OnDetached(AZ::EntityId targetId) override; - // ActorNotificationBus::Handler - void OnActorReady(Actor* actor) override; - void CheckActorCreation(); void BuildGameEntity(AZ::Entity* gameEntity) override; From f39460e617d56358c83c8227203b83f547d386e5 Mon Sep 17 00:00:00 2001 From: Nicholas Van Sickle Date: Thu, 3 Jun 2021 20:08:51 -0700 Subject: [PATCH 499/811] Fix rare re-entrancy issue with CCryEditApp::IdleProcessing (#1134) This issue manifested in a crash in rare circumstances when the Editor lost and gained focus while a modal dialog was active. After investigation, it was discovered that native event processing can lead to IdleProcessing being called again from the main thread while idle processing is still happening. As this is unintentional and generally undesirable, we now guard against this within the IdleProcessing method. --- Code/Sandbox/Editor/CryEdit.cpp | 8 ++++++++ Code/Sandbox/Editor/CryEdit.h | 2 ++ 2 files changed, 10 insertions(+) diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index c723e6049a..a972a4bd9b 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -2281,6 +2281,14 @@ int CCryEditApp::IdleProcessing(bool bBackgroundUpdate) return 0; } + // Ensure we don't get called re-entrantly + // This can occur when a nested Qt event loop fires (e.g. by way of a modal dialog calling exec) + if (m_idleProcessingRunning) + { + return 0; + } + QScopedValueRollback guard(m_idleProcessingRunning, true); + //////////////////////////////////////////////////////////////////////// // Call the update function of the engine //////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/CryEdit.h b/Code/Sandbox/Editor/CryEdit.h index dc4f015faf..e37fb53561 100644 --- a/Code/Sandbox/Editor/CryEdit.h +++ b/Code/Sandbox/Editor/CryEdit.h @@ -335,6 +335,8 @@ private: // If this flag is set, the next OnIdle() will update, even if the app is in the background, and then // this flag will be reset. bool m_bForceProcessIdle = false; + // This is set while IdleProcessing is running to prevent re-entrancy + bool m_idleProcessingRunning = false; // Keep the editor alive, even if no focus is set bool m_bKeepEditorActive = false; // Currently creating a new level From 34449e2fc9085e2cf5d3a7e2836479f4977d65b7 Mon Sep 17 00:00:00 2001 From: Nicholas Van Sickle Date: Thu, 3 Jun 2021 20:09:04 -0700 Subject: [PATCH 500/811] Guard GridComponent against arbitrarily high grid sizes (#1135) Also do bounds checking at runtime in the controller for safety. --- .../Code/Source/Grid/EditorGridComponent.cpp | 7 ++++--- .../Code/Source/Grid/GridComponentController.cpp | 6 +++--- .../Code/Source/Grid/GridComponentController.h | 4 ++++ 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/EditorGridComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/EditorGridComponent.cpp index f500bdd6e2..81fc3aa170 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/EditorGridComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/EditorGridComponent.cpp @@ -54,13 +54,14 @@ namespace AZ ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Default, &GridComponentConfig::m_gridSize, "Grid Size", "Grid width and depth") - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Min, GridComponentController::MinGridSize) + ->Attribute(AZ::Edit::Attributes::Max, GridComponentController::MaxGridSize) ->Attribute(AZ::Edit::Attributes::Suffix, " m") ->DataElement(AZ::Edit::UIHandlers::Default, &GridComponentConfig::m_primarySpacing, "Primary Grid Spacing", "Amount of space between grid lines") - ->Attribute(AZ::Edit::Attributes::Min, 0.01f) + ->Attribute(AZ::Edit::Attributes::Min, GridComponentController::MinSpacing) ->Attribute(AZ::Edit::Attributes::Suffix, " m") ->DataElement(AZ::Edit::UIHandlers::Default, &GridComponentConfig::m_secondarySpacing, "Secondary Grid Spacing", "Amount of space between sub-grid lines") - ->Attribute(AZ::Edit::Attributes::Min, 0.01f) + ->Attribute(AZ::Edit::Attributes::Min, GridComponentController::MinSpacing) ->Attribute(AZ::Edit::Attributes::Suffix, " m") ->DataElement(AZ::Edit::UIHandlers::Color, &GridComponentConfig::m_axisColor, "Axis Color", "Color of the grid axis") ->DataElement(AZ::Edit::UIHandlers::Color, &GridComponentConfig::m_primaryColor, "Primary Color", "Color of the primary grid lines") diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/GridComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/GridComponentController.cpp index c2f9c896af..279c8d9035 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/GridComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/GridComponentController.cpp @@ -115,7 +115,7 @@ namespace AZ void GridComponentController::SetSize(float gridSize) { - m_configuration.m_gridSize = gridSize; + m_configuration.m_gridSize = AZStd::clamp(gridSize, MinGridSize, MaxGridSize); m_dirty = true; } @@ -126,7 +126,7 @@ namespace AZ void GridComponentController::SetPrimarySpacing(float gridPrimarySpacing) { - m_configuration.m_primarySpacing = gridPrimarySpacing; + m_configuration.m_primarySpacing = AZStd::max(gridPrimarySpacing, MinSpacing); m_dirty = true; } @@ -137,7 +137,7 @@ namespace AZ void GridComponentController::SetSecondarySpacing(float gridSecondarySpacing) { - m_configuration.m_secondarySpacing = gridSecondarySpacing; + m_configuration.m_secondarySpacing = AZStd::max(gridSecondarySpacing, MinSpacing); m_dirty = true; } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/GridComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/GridComponentController.h index afba6d8327..ad603f11e1 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/GridComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Grid/GridComponentController.h @@ -46,6 +46,10 @@ namespace AZ void SetConfiguration(const GridComponentConfig& config); const GridComponentConfig& GetConfiguration() const; + static constexpr float MinGridSize = 0.0f; + static constexpr float MaxGridSize = 1000000.0f; + static constexpr float MinSpacing = 0.01f; + private: AZ_DISABLE_COPY(GridComponentController); From 30eedc1c554c8ae01e5be9d22cc372d757cd7bd0 Mon Sep 17 00:00:00 2001 From: Nicholas Van Sickle Date: Thu, 3 Jun 2021 20:09:15 -0700 Subject: [PATCH 501/811] Avoid more sources of camera update re-entrancy that can lead to stack overflow (#1136) --- Code/Sandbox/Editor/EditorViewportWidget.cpp | 3 +++ Gems/Camera/Code/Source/CameraComponentController.cpp | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 667179e3cd..0d3405f8f0 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -2887,9 +2887,12 @@ void EditorViewportWidget::UpdateCameraFromViewportContext() AZ::Matrix3x4 matrix; matrix.SetBasisAndTranslation(cameraState.m_side, cameraState.m_forward, cameraState.m_up, cameraState.m_position); auto m = AZMatrix3x4ToLYMatrix3x4(matrix); + + m_updatingCameraPosition = true; SetViewTM(m); SetFOV(cameraState.m_fovOrZoom); m_Camera.SetZRange(cameraState.m_nearClip, cameraState.m_farClip); + m_updatingCameraPosition = false; } void EditorViewportWidget::SetAsActiveViewport() diff --git a/Gems/Camera/Code/Source/CameraComponentController.cpp b/Gems/Camera/Code/Source/CameraComponentController.cpp index cad666c1cd..78bd131002 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.cpp +++ b/Gems/Camera/Code/Source/CameraComponentController.cpp @@ -387,6 +387,11 @@ namespace Camera void CameraComponentController::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) { + if (m_updatingTransformFromEntity) + { + return; + } + if (m_view) { CCamera& camera = m_view->GetCamera(); From 4a1d713227af339b2fbb86eb02c936cc079863c5 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 3 Jun 2021 22:36:34 -0500 Subject: [PATCH 502/811] Fix recursive attempts to open the log file in the GameLauncher (#1114) * Fix recursive attempts to open the log file in the GameLauncher The AzFramework Application has been updated to default the @user@ and @log@ aliases to the /user and /user/log folder respectively if a project isn't set. Fixed the SystemFile class to support negative offsets if Seek() as per standard seek function such as fseek Updated the CrySystem CLog class to use SystemFile instead of FileIOBase to avoid any asserts that would cause CLog::OpenFile to be recursively called infinitely * Removing unused Force Closed variable * AZ::IO::SystemFile build fixes for Unix platforms. Added a copy constructor for LUAEditorContextInterface.h to fix the LuaEditor build * Adding missing includes to the WindowsAPI and Android SystemFile headers --- Code/CryEngine/CrySystem/Log.cpp | 106 +++++++++--------- Code/CryEngine/CrySystem/Log.h | 18 ++- Code/CryEngine/CrySystem/SystemInit.cpp | 2 +- .../Framework/AzCore/AzCore/IO/SystemFile.cpp | 60 ++++++---- Code/Framework/AzCore/AzCore/IO/SystemFile.h | 21 ++-- .../Settings/SettingsRegistryMergeUtils.cpp | 2 + .../Android/AzCore/IO/SystemFile_Android.cpp | 10 +- .../Android/AzCore/IO/SystemFile_Android.h | 6 +- .../Common/Apple/AzCore/IO/SystemFile_Apple.h | 5 +- .../UnixLike/AzCore/IO/SystemFile_UnixLike.h | 6 +- .../AzCore/IO/SystemFile_UnixLikeDefault.cpp | 6 +- .../WinAPI/AzCore/IO/SystemFile_WinAPI.cpp | 8 +- .../WinAPI/AzCore/IO/SystemFile_WinAPI.h | 6 +- .../AzFramework/Application/Application.cpp | 13 ++- .../Source/LUA/LUAEditorContextInterface.h | 46 ++++++++ 15 files changed, 200 insertions(+), 115 deletions(-) diff --git a/Code/CryEngine/CrySystem/Log.cpp b/Code/CryEngine/CrySystem/Log.cpp index b8241ee865..af5170e4e5 100644 --- a/Code/CryEngine/CrySystem/Log.cpp +++ b/Code/CryEngine/CrySystem/Log.cpp @@ -26,6 +26,7 @@ #include #include +#include #ifdef WIN32 #include @@ -88,7 +89,6 @@ CLog::CLog(ISystem* pSystem) m_nMainThreadId = CryGetCurrentThreadId(); - m_logFileHandle = AZ::IO::InvalidHandle; #if defined(KEEP_LOG_FILE_OPEN) m_bFirstLine = true; #endif @@ -162,35 +162,6 @@ void CLog::RegisterConsoleVariables() REGISTER_COMMAND("log_flush", &LogFlushFile, 0, "Flush the log file"); #endif } - /* - //testbed - { - int iSave0 = m_pLogVerbosity->GetIVal(); - int iSave1 = m_pLogFileVerbosity->GetIVal(); - - for(int i=0;i<=4;++i) - { - m_pLogVerbosity->Set(i); - m_pLogFileVerbosity->Set(i); - - LogWithType(eAlways,"CLog selftest: Verbosity=%d FileVerbosity=%d",m_pLogVerbosity->GetIVal(),m_pLogFileVerbosity->GetIVal()); - LogWithType(eAlways,"--------------"); - - LogWithType(eError,"eError"); - LogWithType(eWarning,"eWarning"); - LogWithType(eMessage,"eMessage"); - LogWithType(eInput,"eInput"); - LogWithType(eInputResponse,"eInputResponse"); - - LogWarning("LogWarning()"); - LogError("LogError()"); - LogWithType(eAlways,"--------------"); - } - - m_pLogVerbosity->Set(iSave0); - m_pLogFileVerbosity->Set(iSave1); - } - */ #undef DEFAULT_VERBOSITY } @@ -210,7 +181,7 @@ CLog::~CLog() UnregisterConsoleVariables(); - CloseLogFile(true); + CloseLogFile(); } void CLog::UnregisterConsoleVariables() @@ -224,31 +195,36 @@ void CLog::UnregisterConsoleVariables() } ////////////////////////////////////////////////////////////////////////// -void CLog::CloseLogFile([[maybe_unused]] bool forceClose) +void CLog::CloseLogFile() { - if (m_logFileHandle != AZ::IO::InvalidHandle) - { - AZ::IO::FileIOBase::GetDirectInstance()->Close(m_logFileHandle); - m_logFileHandle = AZ::IO::InvalidHandle; - } + m_logFileHandle.Close(); } ////////////////////////////////////////////////////////////////////////// -AZ::IO::HandleType CLog::OpenLogFile(const char* filename, const char* mode) +bool CLog::OpenLogFile(const char* filename, int mode) { - using namespace AZ::IO; - - AZ_Assert(m_logFileHandle == AZ::IO::InvalidHandle, "Attempt to open log file when one is already open. This would lead to a handle leak."); - - if ((!filename) || (filename[0] == 0)) + if (m_logFileHandle.IsOpen()) { - return m_logFileHandle; + // Can only AZ_Assert if a file is open, otherwise the AZ_Assert + // would eventually lead to OpenLogFile being opened up again + AZ_Assert(false, "Attempt to open log file when one is already open. This would lead to a handle leak."); + return false; + } + + if (filename == nullptr || filename[0] == '\0') + { + return false; } // it is assumed that @log@ points at the appropriate place (so for apple, to the user profile dir) - AZ::IO::FileIOBase::GetDirectInstance()->Open(filename, AZ::IO::GetOpenModeFromStringMode(mode), m_logFileHandle); + AZ::IO::FileIOBase* fileSystem = AZ::IO::FileIOBase::GetDirectInstance(); + if (AZ::IO::FixedMaxPath logFilePath; fileSystem->ReplaceAlias(logFilePath, filename)) + { + logFilePath = logFilePath.LexicallyNormal(); + m_logFileHandle.Open(logFilePath.c_str(), mode); + } - if (m_logFileHandle != AZ::IO::InvalidHandle) + if (m_logFileHandle.IsOpen()) { #if defined(KEEP_LOG_FILE_OPEN) m_bFirstLine = true; @@ -257,11 +233,11 @@ AZ::IO::HandleType CLog::OpenLogFile(const char* filename, const char* mode) else { #if defined(LINUX) || defined(APPLE) - syslog(LOG_NOTICE, "Failed to open log file [%s], mode [%s]", filename, mode); + syslog(LOG_NOTICE, "Failed to open log file [%s], mode [%d]", filename, mode); #endif } - return m_logFileHandle; + return m_logFileHandle.IsOpen(); } ////////////////////////////////////////////////////////////////////////// @@ -1114,12 +1090,15 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[ if (logToFile) { - if (m_logFileHandle == AZ::IO::InvalidHandle) + if (!m_logFileHandle.IsOpen()) { - OpenLogFile(m_szFilename, "w+t"); + constexpr auto openMode = AZ::IO::SystemFile::OpenMode::SF_OPEN_APPEND + | AZ::IO::SystemFile::OpenMode::SF_OPEN_CREATE + | AZ::IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY; + OpenLogFile(m_szFilename, openMode); } - if (m_logFileHandle != AZ::IO::InvalidHandle) + if (m_logFileHandle.IsOpen()) { #if defined(KEEP_LOG_FILE_OPEN) if (m_bFirstLine) @@ -1130,9 +1109,9 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[ if (bAdd) { // if adding to a prior line erase the \n at the end. - AZ::IO::FileIOBase::GetDirectInstance()->Seek(m_logFileHandle, -2, AZ::IO::SeekType::SeekFromEnd); + m_logFileHandle.Seek(-2, AZ::IO::SystemFile::SeekMode::SF_SEEK_END); } - AZ::IO::FPutS(tempString.c_str(), m_logFileHandle); + m_logFileHandle.Write(tempString.c_str(), tempString.size()); #if !defined(KEEP_LOG_FILE_OPEN) CloseLogFile(); #endif @@ -1383,6 +1362,23 @@ bool CLog::SetFileName(const char* fileNameOrAbsolutePath, bool backupLogs) CreateBackupFile(); + AZ::IO::FileIOBase* fileSystem = AZ::IO::FileIOBase::GetDirectInstance(); + AZ::IO::FixedMaxPath newLogFilePath; + if (fileSystem->ReplaceAlias(newLogFilePath, m_szFilename)) + { + newLogFilePath = newLogFilePath.LexicallyNormal(); + } + if (m_logFileHandle.IsOpen() && newLogFilePath != m_logFileHandle.Name()) + { + constexpr auto openMode = AZ::IO::SystemFile::OpenMode::SF_OPEN_APPEND + | AZ::IO::SystemFile::OpenMode::SF_OPEN_CREATE + | AZ::IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY; + if(AZ::IO::SystemFile newLogFile; newLogFile.Open(m_szFilename, openMode)) + { + m_logFileHandle = AZStd::move(newLogFile); + } + } + return true; } @@ -1537,9 +1533,9 @@ const char* CLog::GetModuleFilter() void CLog::FlushAndClose() { #if defined(KEEP_LOG_FILE_OPEN) - if (m_logFileHandle) + if (m_logFileHandle.IsOpen()) { - CloseLogFile(true); + CloseLogFile(); } #endif } diff --git a/Code/CryEngine/CrySystem/Log.h b/Code/CryEngine/CrySystem/Log.h index 911043871a..e19c2d19da 100644 --- a/Code/CryEngine/CrySystem/Log.h +++ b/Code/CryEngine/CrySystem/Log.h @@ -137,8 +137,8 @@ private: // ------------------------------------------------------------------- void LogStringToConsole(const char* szString, ELogType logType, bool bAdd) {} #endif // !defined(EXCLUDE_NORMAL_LOG) - AZ::IO::HandleType OpenLogFile(const char* filename, const char* mode); - void CloseLogFile(bool force = false); + bool OpenLogFile(const char* filename, int mode); + void CloseLogFile(); // will format the message into m_szTemp void FormatMessage(const char* szCommand, ...) PRINTF_PARAMS(2, 3); @@ -152,15 +152,11 @@ private: // ------------------------------------------------------------------- virtual const char* GetAssetScopeString(); #endif - ISystem* m_pSystem; // - float m_fLastLoadingUpdateTime; // for non-frequent streamingEngine update - //char m_szTemp[MAX_TEMP_LENGTH_SIZE]; // - char m_szFilename[MAX_FILENAME_SIZE]; // can be with path - mutable char m_sBackupFilename[MAX_FILENAME_SIZE]; // can be with path - AZ::IO::HandleType m_logFileHandle; - CryStackStringT m_LogMode; //mode m_pLogFile has been opened with - AZ::IO::HandleType m_errFileHandle; - int m_nErrCount; + ISystem* m_pSystem; // + float m_fLastLoadingUpdateTime; // for non-frequent streamingEngine update + char m_szFilename[MAX_FILENAME_SIZE]; // can be with path + mutable char m_sBackupFilename[MAX_FILENAME_SIZE]; // can be with path + AZ::IO::SystemFile m_logFileHandle; bool m_backupLogs; diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 4a4296bbb5..97a3bbbe54 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -1208,7 +1208,7 @@ bool CSystem::Init(const SSystemInitParams& startupParams) { assetPlatform = AzFramework::OSPlatformToDefaultAssetPlatform(AZ_TRAIT_OS_PLATFORM_CODENAME); AZ_Warning(AZ_TRACE_SYSTEM_WINDOW, false, R"(A valid asset platform is missing in "%s/assets" key in the SettingsRegistry.)""\n" - R"(This typically done by setting he "assets" field in the bootstrap.cfg for within a .setreg file)""\n" + R"(This typically done by setting the "assets" field within a .setreg file)""\n" R"(A fallback of %s will be used.)", AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, assetPlatform.c_str()); diff --git a/Code/Framework/AzCore/AzCore/IO/SystemFile.cpp b/Code/Framework/AzCore/AzCore/IO/SystemFile.cpp index 7c535d4aaf..6887d22ba7 100644 --- a/Code/Framework/AzCore/AzCore/IO/SystemFile.cpp +++ b/Code/Framework/AzCore/AzCore/IO/SystemFile.cpp @@ -30,7 +30,7 @@ namespace Platform using FileHandleType = SystemFile::FileHandleType; - void Seek(FileHandleType handle, const SystemFile* systemFile, SizeType offset, SystemFile::SeekMode mode); + void Seek(FileHandleType handle, const SystemFile* systemFile, SystemFile::SeekSizeType offset, SystemFile::SeekMode mode); SystemFile::SizeType Tell(FileHandleType handle, const SystemFile* systemFile); bool Eof(FileHandleType handle, const SystemFile* systemFile); AZ::u64 ModificationTime(FileHandleType handle, const SystemFile* systemFile); @@ -68,9 +68,8 @@ void SystemFile::CreatePath(const char* fileName) } SystemFile::SystemFile() + : m_handle{ AZ_TRAIT_SYSTEMFILE_INVALID_HANDLE } { - m_fileName[0] = '\0'; - m_handle = AZ_TRAIT_SYSTEMFILE_INVALID_HANDLE; } SystemFile::~SystemFile() @@ -81,6 +80,25 @@ SystemFile::~SystemFile() } } +SystemFile::SystemFile(SystemFile&& other) + : SystemFile{} +{ + AZStd::swap(m_fileName, other.m_fileName); + AZStd::swap(m_handle, other.m_handle); +} + +SystemFile& SystemFile::operator=(SystemFile&& other) +{ + // Close the current file and take over the SystemFile handle and filename + Close(); + m_fileName = AZStd::move(other.m_fileName); + m_handle = AZStd::move(other.m_handle); + other.m_fileName = {}; + other.m_handle = AZ_TRAIT_SYSTEMFILE_INVALID_HANDLE; + + return *this; +} + bool SystemFile::Open(const char* fileName, int mode, int platformFlags) { AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Open - %s", fileName); @@ -88,42 +106,42 @@ bool SystemFile::Open(const char* fileName, int mode, int platformFlags) if (fileName) // If we reopen the file we are allowed to have NULL file name { - if (strlen(fileName) > AZ_ARRAY_SIZE(m_fileName) - 1) + if (strlen(fileName) > m_fileName.max_size()) { EBUS_EVENT(FileIOEventBus, OnError, this, nullptr, 0); return false; } // store the filename - azsnprintf(m_fileName, AZ_ARRAY_SIZE(m_fileName), "%s", fileName); + m_fileName = fileName; } if (FileIOBus::HasHandlers()) { bool isOpen = false; bool isHandled = false; - EBUS_EVENT_RESULT(isHandled, FileIOBus, OnOpen, *this, m_fileName, mode, platformFlags, isOpen); + EBUS_EVENT_RESULT(isHandled, FileIOBus, OnOpen, *this, m_fileName.c_str(), mode, platformFlags, isOpen); if (isHandled) { return isOpen; } } - AZ_Assert(!IsOpen(), "This file (%s) is already open!", m_fileName); + AZ_Assert(!IsOpen(), "This file (%s) is already open!", m_fileName.c_str()); return PlatformOpen(mode, platformFlags); } bool SystemFile::ReOpen(int mode, int platformFlags) { - AZ_Assert(strlen(m_fileName) > 0, "Missing filename. You must call open first!"); + AZ_Assert(!m_fileName.empty(), "Missing filename. You must call open first!"); return Open(0, mode, platformFlags); } void SystemFile::Close() { - AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Close - %s", m_fileName); - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Close - %s", m_fileName); + AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Close - %s", m_fileName.c_str()); + AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Close - %s", m_fileName.c_str()); if (FileIOBus::HasHandlers()) { @@ -138,9 +156,9 @@ void SystemFile::Close() PlatformClose(); } -void SystemFile::Seek(SizeType offset, SeekMode mode) +void SystemFile::Seek(SeekSizeType offset, SeekMode mode) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Seek - %s:%i", m_fileName, offset); + AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Seek - %s:%i", m_fileName.c_str(), offset); if (FileIOBus::HasHandlers()) { @@ -167,15 +185,15 @@ bool SystemFile::Eof() AZ::u64 SystemFile::ModificationTime() { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::ModTime - %s", m_fileName); + AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::ModTime - %s", m_fileName.c_str()); return Platform::ModificationTime(m_handle, this); } SystemFile::SizeType SystemFile::Read(SizeType byteSize, void* buffer) { - AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Read - %s:%i", m_fileName, byteSize); - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Read - %s:%i", m_fileName, byteSize); + AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Read - %s:%i", m_fileName.c_str(), byteSize); + AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Read - %s:%i", m_fileName.c_str(), byteSize); if (FileIOBus::HasHandlers()) { @@ -193,8 +211,8 @@ SystemFile::SizeType SystemFile::Read(SizeType byteSize, void* buffer) SystemFile::SizeType SystemFile::Write(const void* buffer, SizeType byteSize) { - AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Write - %s:%i", m_fileName, byteSize); - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Write - %s:%i", m_fileName, byteSize); + AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Write - %s:%i", m_fileName.c_str(), byteSize); + AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Write - %s:%i", m_fileName.c_str(), byteSize); if (FileIOBus::HasHandlers()) { @@ -212,14 +230,14 @@ SystemFile::SizeType SystemFile::Write(const void* buffer, SizeType byteSize) void SystemFile::Flush() { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Flush - %s", m_fileName); + AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Flush - %s", m_fileName.c_str()); Platform::Flush(m_handle, this); } SystemFile::SizeType SystemFile::Length() const { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Length - %s", m_fileName); + AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Length - %s", m_fileName.c_str()); return Platform::Length(m_handle, this); } @@ -379,9 +397,9 @@ namespace HasPosixEnumOption(PermissionModeFlags::Write); #undef HasPosixEnumOption -} +} + - FileDescriptorRedirector::FileDescriptorRedirector(int sourceFileDescriptor) : m_sourceFileDescriptor(sourceFileDescriptor) { diff --git a/Code/Framework/AzCore/AzCore/IO/SystemFile.h b/Code/Framework/AzCore/AzCore/IO/SystemFile.h index 0ce8197b18..065aa124ca 100644 --- a/Code/Framework/AzCore/AzCore/IO/SystemFile.h +++ b/Code/Framework/AzCore/AzCore/IO/SystemFile.h @@ -12,10 +12,11 @@ #pragma once #include -#include -#include +#include #include +#include +#include // Establish a consistent size that works across platforms. It's actually larger than this // on platforms we support, but this is a good least common denominator @@ -51,11 +52,15 @@ namespace AZ }; using SizeType = AZ::IO::Internal::SizeType; + using SeekSizeType = AZ::IO::Internal::SeekSizeType; using FileHandleType = AZ::IO::Internal::FileHandleType; SystemFile(); ~SystemFile(); + SystemFile(SystemFile&&); + SystemFile& operator=(SystemFile&&); + /** * Opens a file. * \param fileName full file name including path @@ -69,7 +74,7 @@ namespace AZ /// Closes a file, if file already close it has no effect. void Close(); /// Seek in current file. - void Seek(SizeType offset, SeekMode mode); + void Seek(SeekSizeType offset, SeekMode mode); /// Get the cursor position in the current file. SizeType Tell(); /// Is the cursor at the end of the file? @@ -87,7 +92,7 @@ namespace AZ /// Return disc offset if possible, otherwise 0 SizeType DiskOffset() const; /// Return file name or NULL if file is not open. - AZ_FORCE_INLINE const char* Name() const { return m_fileName; } + AZ_FORCE_INLINE const char* Name() const { return m_fileName.c_str(); } bool IsOpen() const; /// Return native handle to the file. @@ -124,12 +129,12 @@ namespace AZ private: static void CreatePath(const char * fileName); - + bool PlatformOpen(int mode, int platformFlags); void PlatformClose(); - - FileHandleType m_handle; - char m_fileName[AZ_MAX_PATH_LEN]; + + FileHandleType m_handle; + AZ::IO::FixedMaxPathString m_fileName; }; /** diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp index 2abef3f808..2d2acd9d44 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp @@ -641,6 +641,8 @@ namespace AZ::SettingsRegistryMergeUtils } else { + // Set the default ProjectUserPath to the /user directory + registry.Set(FilePathKey_ProjectUserPath, (engineRoot / "user").LexicallyNormal().Native()); AZ_TracePrintf("SettingsRegistryMergeUtils", R"(Project path isn't set in the Settings Registry at "%.*s". Project-related filepaths will not be set)" "\n", aznumeric_cast(projectPathKey.size()), projectPathKey.data()); diff --git a/Code/Framework/AzCore/Platform/Android/AzCore/IO/SystemFile_Android.cpp b/Code/Framework/AzCore/Platform/Android/AzCore/IO/SystemFile_Android.cpp index 2b1ebf54aa..c9950d2dfa 100644 --- a/Code/Framework/AzCore/Platform/Android/AzCore/IO/SystemFile_Android.cpp +++ b/Code/Framework/AzCore/Platform/Android/AzCore/IO/SystemFile_Android.cpp @@ -101,7 +101,7 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags) createPath = (mode & SF_OPEN_CREATE_PATH) == SF_OPEN_CREATE_PATH; } - bool isApkFile = AZ::Android::Utils::IsApkPath(m_fileName); + bool isApkFile = AZ::Android::Utils::IsApkPath(m_fileName.c_str()); if (createPath) { @@ -111,19 +111,19 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags) return false; } - CreatePath(m_fileName); + CreatePath(m_fileName.c_str()); } int errorCode = 0; if (isApkFile) { AZ::u64 size = 0; - m_handle = AZ::Android::APKFileHandler::Open(m_fileName, openMode, size); + m_handle = AZ::Android::APKFileHandler::Open(m_fileName.c_str(), openMode, size); errorCode = EACCES; // general error when a file can't be opened from inside the APK } else { - m_handle = fopen(m_fileName, openMode); + m_handle = fopen(m_fileName.c_str(), openMode); errorCode = errno; } @@ -233,7 +233,7 @@ namespace Platform } } - void Seek(FileHandleType handle, const SystemFile* systemFile, SizeType offset, SystemFile::SeekMode mode) + void Seek(FileHandleType handle, const SystemFile* systemFile, SystemFile::SeekSizeType offset, SystemFile::SeekMode mode) { if (handle != PlatformSpecificInvalidHandle) { diff --git a/Code/Framework/AzCore/Platform/Android/AzCore/IO/SystemFile_Android.h b/Code/Framework/AzCore/Platform/Android/AzCore/IO/SystemFile_Android.h index 7ccc6a076e..50255f24d4 100644 --- a/Code/Framework/AzCore/Platform/Android/AzCore/IO/SystemFile_Android.h +++ b/Code/Framework/AzCore/Platform/Android/AzCore/IO/SystemFile_Android.h @@ -15,6 +15,9 @@ #include #include #include +#include + +#include namespace AZ { @@ -23,6 +26,7 @@ namespace AZ namespace Internal { using SizeType = AZ::u64; + using SeekSizeType = AZ::s64; using FileHandleType = FILE*; } @@ -37,7 +41,7 @@ namespace AZ #else Temporary = 0, // (Not applicable for this platform) Applies only when used with CREAT. Creates a file as temporary; the file is deleted when the last file descriptor is closed. PermissionMode equired when CREAT is specified. #endif - Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists. + Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists. Truncate = O_TRUNC, // Opens a file and truncates it to zero length; the file must have write permission. Cannot be specified with RDONLY. // Note: The TRUNC flag destroys the contents of the specified file. diff --git a/Code/Framework/AzCore/Platform/Common/Apple/AzCore/IO/SystemFile_Apple.h b/Code/Framework/AzCore/Platform/Common/Apple/AzCore/IO/SystemFile_Apple.h index 902dca4142..3967cafc90 100644 --- a/Code/Framework/AzCore/Platform/Common/Apple/AzCore/IO/SystemFile_Apple.h +++ b/Code/Framework/AzCore/Platform/Common/Apple/AzCore/IO/SystemFile_Apple.h @@ -22,9 +22,10 @@ namespace AZ namespace Internal { using SizeType = AZ::u64; + using SeekSizeType = AZ::s64; using FileHandleType = int; } - + namespace PosixInternal { enum class OpenFlags : int @@ -36,7 +37,7 @@ namespace AZ #else Temporary = 0, // (Not applicable for this platform) Applies only when used with CREAT. Creates a file as temporary; the file is deleted when the last file descriptor is closed. PermissionMode equired when CREAT is specified. #endif - Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists. + Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists. Truncate = O_TRUNC, // Opens a file and truncates it to zero length; the file must have write permission. Cannot be specified with RDONLY. // Note: The TRUNC flag destroys the contents of the specified file. diff --git a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.h b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.h index 0f55c0511b..e2d985d84e 100644 --- a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.h +++ b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.h @@ -13,6 +13,9 @@ #include #include +#include + +#include namespace AZ { @@ -21,6 +24,7 @@ namespace AZ namespace Internal { using SizeType = AZ::u64; + using SeekSizeType = AZ::s64; using FileHandleType = int; } @@ -35,7 +39,7 @@ namespace AZ #else Temporary = 0, // (Not applicable for this platform) Applies only when used with CREAT. Creates a file as temporary; the file is deleted when the last file descriptor is closed. PermissionMode equired when CREAT is specified. #endif - Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists. + Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists. Truncate = O_TRUNC, // Opens a file and truncates it to zero length; the file must have write permission. Cannot be specified with RDONLY. // Note: The TRUNC flag destroys the contents of the specified file. diff --git a/Code/Framework/AzCore/Platform/Common/UnixLikeDefault/AzCore/IO/SystemFile_UnixLikeDefault.cpp b/Code/Framework/AzCore/Platform/Common/UnixLikeDefault/AzCore/IO/SystemFile_UnixLikeDefault.cpp index 3e40936d66..b5c3041113 100644 --- a/Code/Framework/AzCore/Platform/Common/UnixLikeDefault/AzCore/IO/SystemFile_UnixLikeDefault.cpp +++ b/Code/Framework/AzCore/Platform/Common/UnixLikeDefault/AzCore/IO/SystemFile_UnixLikeDefault.cpp @@ -86,9 +86,9 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags) if (createPath) { - CreatePath(m_fileName); + CreatePath(m_fileName.c_str()); } - m_handle = open(m_fileName, desiredAccess, permissions); + m_handle = open(m_fileName.c_str(), desiredAccess, permissions); if (m_handle == PlatformSpecificInvalidHandle) { @@ -119,7 +119,7 @@ namespace Platform { using FileHandleType = AZ::IO::SystemFile::FileHandleType; - void Seek(FileHandleType handle, const SystemFile* systemFile, SizeType offset, SystemFile::SeekMode mode) + void Seek(FileHandleType handle, const SystemFile* systemFile, SystemFile::SeekSizeType offset, SystemFile::SeekMode mode) { if (handle != PlatformSpecificInvalidHandle) { diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp index e01008b1a0..fa77acb967 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp @@ -209,19 +209,19 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags) if (createPath) { - CreatePath(m_fileName); + CreatePath(m_fileName.c_str()); } # ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; m_handle = INVALID_HANDLE_VALUE; - if (mbstowcs_s(&numCharsConverted, fileNameW, m_fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) + if (mbstowcs_s(&numCharsConverted, fileNameW, m_fileName.c_str(), AZ_ARRAY_SIZE(fileNameW) - 1) == 0) { m_handle = CreateFileW(fileNameW, dwDesiredAccess, dwShareMode, 0, dwCreationDisposition, dwFlagsAndAttributes, 0); } # else //!_UNICODE - m_handle = CreateFile(m_fileName, dwDesiredAccess, dwShareMode, 0, dwCreationDisposition, dwFlagsAndAttributes, 0); + m_handle = CreateFile(m_fileName.c_str(), dwDesiredAccess, dwShareMode, 0, dwCreationDisposition, dwFlagsAndAttributes, 0); # endif // !_UNICODE if (m_handle == INVALID_HANDLE_VALUE) @@ -261,7 +261,7 @@ namespace Platform { using FileHandleType = AZ::IO::SystemFile::FileHandleType; - void Seek(FileHandleType handle, const SystemFile* systemFile, SizeType offset, SystemFile::SeekMode mode) + void Seek(FileHandleType handle, const SystemFile* systemFile, SystemFile::SeekSizeType offset, SystemFile::SeekMode mode) { if (handle != PlatformSpecificInvalidHandle) { diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.h b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.h index 7f69a6b66d..09ea48c40b 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.h +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.h @@ -13,6 +13,9 @@ #include #include +#include + +#include namespace AZ { @@ -21,6 +24,7 @@ namespace AZ namespace Internal { using SizeType = AZ::u64; + using SeekSizeType = AZ::s64; using FileHandleType = void*; } @@ -31,7 +35,7 @@ namespace AZ Append = _O_APPEND, // Moves the file pointer to the end of the file before every write operation. Create = _O_CREAT, // Creates a file and opens it for writing. Has no effect if the file specified by filename exists. PermissionMode is required. Temporary = _O_TEMPORARY, // Applies only when used with CREAT. Creates a file as temporary; the file is deleted when the last file descriptor is closed. PermissionMode equired when CREAT is specified. - Exclusive = _O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists. + Exclusive = _O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists. Truncate = _O_TRUNC, // Opens a file and truncates it to zero length; the file must have write permission. Cannot be specified with RDONLY. // Note: The TRUNC flag destroys the contents of the specified file. diff --git a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp index c65ba373f8..bc0c9e537a 100644 --- a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp +++ b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp @@ -711,8 +711,8 @@ namespace AzFramework } } - AZ::IO::FixedMaxPath projectUserPath; - if (m_settingsRegistry->Get(projectUserPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectUserPath)) + if (AZ::IO::FixedMaxPath projectUserPath; + m_settingsRegistry->Get(projectUserPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectUserPath)) { fileIoBase->SetAlias("@user@", projectUserPath.c_str()); AZ::IO::FixedMaxPath projectLogPath = projectUserPath / "log"; @@ -721,6 +721,15 @@ namespace AzFramework CreateUserCache(projectUserPath, *fileIoBase); } + else + { + AZ::IO::FixedMaxPath fallbackLogPath = GetEngineRoot(); + fallbackLogPath /= "user"; + fileIoBase->SetAlias("@user@", fallbackLogPath.c_str()); + fallbackLogPath /= "log"; + fileIoBase->SetAlias("@log@", fallbackLogPath.c_str()); + fileIoBase->CreatePath(fallbackLogPath.c_str()); + } } } diff --git a/Code/Tools/Standalone/Source/LUA/LUAEditorContextInterface.h b/Code/Tools/Standalone/Source/LUA/LUAEditorContextInterface.h index 1bbfe83126..01051f42e3 100644 --- a/Code/Tools/Standalone/Source/LUA/LUAEditorContextInterface.h +++ b/Code/Tools/Standalone/Source/LUA/LUAEditorContextInterface.h @@ -70,6 +70,52 @@ namespace LUAEditor , m_bIsModified(false) , m_bIsBeingSaved(false) , m_PresetLineAtOpen(1){} + + // Copy constructor does not copy over open file handle + DocumentInfo(const DocumentInfo& other) + : m_assetId(other.m_assetId) + , m_scriptAsset(other.m_scriptAsset) + , m_assetName(other.m_assetName) + , m_displayName(other.m_displayName) + , m_lastKnownModTime(other.m_lastKnownModTime) + , m_sourceControlInfo(other.m_sourceControlInfo) + , m_bSourceControl_Ready(other.m_bSourceControl_Ready) + , m_bSourceControl_BusyGettingStats(other.m_bSourceControl_BusyGettingStats) + , m_bSourceControl_BusyRequestingEdit(other.m_bSourceControl_BusyRequestingEdit) + , m_bSourceControl_CanWrite(other.m_bSourceControl_CanWrite) + , m_bSourceControl_CanCheckOut(other.m_bSourceControl_CanCheckOut) + , m_bDataIsLoaded(other.m_bDataIsLoaded) + , m_bDataIsWritten(other.m_bDataIsWritten) + , m_bCloseAfterSave(other.m_bCloseAfterSave) + , m_bUntitledDocument(other.m_bUntitledDocument) + , m_bIsModified(other.m_bIsModified) + , m_bIsBeingSaved(other.m_bIsBeingSaved) + , m_PresetLineAtOpen(other.m_PresetLineAtOpen) + {} + + DocumentInfo& operator=(const DocumentInfo& other) + { + m_assetId = other.m_assetId; + m_scriptAsset = other.m_scriptAsset; + m_assetName = other.m_assetName; + m_displayName = other.m_displayName; + m_lastKnownModTime = other.m_lastKnownModTime; + m_sourceControlInfo = other.m_sourceControlInfo; + m_bSourceControl_Ready = other.m_bSourceControl_Ready; + m_bSourceControl_BusyGettingStats = other.m_bSourceControl_BusyGettingStats; + m_bSourceControl_BusyRequestingEdit = other.m_bSourceControl_BusyRequestingEdit; + m_bSourceControl_CanWrite = other.m_bSourceControl_CanWrite; + m_bSourceControl_CanCheckOut = other.m_bSourceControl_CanCheckOut; + m_bDataIsLoaded = other.m_bDataIsLoaded; + m_bDataIsWritten = other.m_bDataIsWritten; + m_bCloseAfterSave = other.m_bCloseAfterSave; + m_bUntitledDocument = other.m_bUntitledDocument; + m_bIsModified = other.m_bIsModified; + m_bIsBeingSaved = other.m_bIsBeingSaved; + m_PresetLineAtOpen = other.m_PresetLineAtOpen; + + return *this; + } }; class ContextInterface From f20ae8345a398c7fd763638173f1ec76b65970a5 Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Thu, 3 Jun 2021 21:58:46 -0700 Subject: [PATCH 503/811] Add Open Project folder menu item --- .../Source/ProjectButtonWidget.cpp | 30 +++++++++---------- .../Source/ProjectButtonWidget.h | 4 --- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp index b1dbd984fb..ee4d48fe7f 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp @@ -11,7 +11,7 @@ */ #include - +#include #include #include @@ -81,18 +81,24 @@ namespace O3DE::ProjectManager m_projectImageLabel = new LabelButton(this); m_projectImageLabel->setFixedSize(s_projectImageWidth, s_projectImageHeight); m_projectImageLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + connect(m_projectImageLabel, &LabelButton::triggered, [this]() { emit OpenProject(m_projectInfo.m_path); }); vLayout->addWidget(m_projectImageLabel); m_projectImageLabel->setPixmap( QPixmap(m_projectInfo.m_imagePath).scaled(m_projectImageLabel->size(), Qt::KeepAspectRatioByExpanding)); - QMenu* newProjectMenu = new QMenu(this); - m_editProjectAction = newProjectMenu->addAction(tr("Edit Project Settings...")); - newProjectMenu->addSeparator(); - m_copyProjectAction = newProjectMenu->addAction(tr("Duplicate")); - newProjectMenu->addSeparator(); - m_removeProjectAction = newProjectMenu->addAction(tr("Remove from O3DE")); - m_deleteProjectAction = newProjectMenu->addAction(tr("Delete this Project")); + QMenu* menu = new QMenu(this); + menu->addAction(tr("Edit Project Settings..."), this, [this]() { emit EditProject(m_projectInfo.m_path); }); + menu->addSeparator(); + menu->addAction(tr("Open Project folder..."), this, [this]() + { + AzQtComponents::ShowFileOnDesktop(m_projectInfo.m_path); + }); + menu->addSeparator(); + menu->addAction(tr("Duplicate"), this, [this]() { emit CopyProject(m_projectInfo.m_path); }); + menu->addSeparator(); + menu->addAction(tr("Remove from O3DE"), this, [this]() { emit RemoveProject(m_projectInfo.m_path); }); + menu->addAction(tr("Delete this Project"), this, [this]() { emit DeleteProject(m_projectInfo.m_path); }); QFrame* footer = new QFrame(this); QHBoxLayout* hLayout = new QHBoxLayout(); @@ -104,17 +110,11 @@ namespace O3DE::ProjectManager QPushButton* projectMenuButton = new QPushButton(this); projectMenuButton->setObjectName("projectMenuButton"); - projectMenuButton->setMenu(newProjectMenu); + projectMenuButton->setMenu(menu); hLayout->addWidget(projectMenuButton); } vLayout->addWidget(footer); - - connect(m_projectImageLabel, &LabelButton::triggered, [this]() { emit OpenProject(m_projectInfo.m_path); }); - connect(m_editProjectAction, &QAction::triggered, [this]() { emit EditProject(m_projectInfo.m_path); }); - connect(m_copyProjectAction, &QAction::triggered, [this]() { emit CopyProject(m_projectInfo.m_path); }); - connect(m_removeProjectAction, &QAction::triggered, [this]() { emit RemoveProject(m_projectInfo.m_path); }); - connect(m_deleteProjectAction, &QAction::triggered, [this]() { emit DeleteProject(m_projectInfo.m_path); }); } void ProjectButton::SetButtonEnabled(bool enabled) diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h index 3ac69b7603..bb61f7354b 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h @@ -71,9 +71,5 @@ namespace O3DE::ProjectManager ProjectInfo m_projectInfo; LabelButton* m_projectImageLabel; - QAction* m_editProjectAction; - QAction* m_copyProjectAction; - QAction* m_removeProjectAction; - QAction* m_deleteProjectAction; }; } // namespace O3DE::ProjectManager From 0e4a632417625d1dceb28a2d62d14a0aa8d277e9 Mon Sep 17 00:00:00 2001 From: moudgils Date: Thu, 3 Jun 2021 22:45:50 -0700 Subject: [PATCH 504/811] Add support for re-binding SRG entries if the drawItem has a new pso which changes how a srg is used in the shader. Also optimized api usage to use single call for UseResource and for setting stream buffers. --- .../Shaders/MorphTargets/MorphTargetSRG.azsli | 2 +- .../Metal/Code/Source/RHI/ArgumentBuffer.cpp | 133 +++++++++--------- .../Metal/Code/Source/RHI/ArgumentBuffer.h | 15 +- .../RHI/Metal/Code/Source/RHI/CommandList.cpp | 56 ++++++-- .../RHI/Metal/Code/Source/RHI/CommandList.h | 1 + .../Metal/Code/Source/RHI/PipelineLayout.cpp | 7 + .../Metal/Code/Source/RHI/PipelineLayout.h | 6 + 7 files changed, 134 insertions(+), 86 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetSRG.azsli b/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetSRG.azsli index 171e803c2c..83193c8559 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetSRG.azsli +++ b/Gems/Atom/Feature/Common/Assets/Shaders/MorphTargets/MorphTargetSRG.azsli @@ -16,7 +16,7 @@ ShaderResourceGroup MorphTargetPassSrg : SRG_PerPass { - RWStruturedBuffer m_accumulatedDeltas; + RWStructuredBuffer m_accumulatedDeltas; } // This class represents the data that is passed to the morph target compute shader of an individual delta diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp index 6ffd15e0bc..1e2edc6520 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp @@ -386,6 +386,11 @@ namespace AZ void ArgumentBuffer::AddUntrackedResourcesToEncoder(id commandEncoder, const ShaderResourceGroupVisibility& srgResourcesVisInfo) const { + + ComputeResourcesToMakeResidentMap resourcesToMakeResidentCompute; + GraphicsResourcesToMakeResidentMap resourcesToMakeResidentGraphics; + + //Cache the constant buffer associated with a srg if (m_constantBufferSize) { uint8_t numBitsSet = RHI::CountBitsSet(static_cast(srgResourcesVisInfo.m_constantDataStageMask)); @@ -393,28 +398,19 @@ namespace AZ { if(RHI::CheckBitsAny(srgResourcesVisInfo.m_constantDataStageMask, RHI::ShaderStageMask::Compute)) { - [static_cast>(commandEncoder) useResource:m_constantBuffer.GetGpuAddress>() usage:MTLResourceUsageRead]; + resourcesToMakeResidentCompute[MTLResourceUsageRead].m_resourceArray[resourcesToMakeResidentCompute[MTLResourceUsageRead].m_resourceArrayLen++] = m_constantBuffer.GetGpuAddress>(); } else { MTLRenderStages mtlRenderStages = GetRenderStages(srgResourcesVisInfo.m_constantDataStageMask); - [static_cast>(commandEncoder) useResource:m_constantBuffer.GetGpuAddress>() - usage:MTLResourceUsageRead - stages:mtlRenderStages]; + AZStd::pair key = AZStd::make_pair(MTLResourceUsageRead, mtlRenderStages); + resourcesToMakeResidentGraphics[key].m_resourceArray[resourcesToMakeResidentGraphics[key].m_resourceArrayLen++] = m_constantBuffer.GetGpuAddress>(); } - } } - ApplyUseResource(commandEncoder, m_resourceBindings, srgResourcesVisInfo); - } - - void ArgumentBuffer::ApplyUseResource(id encoder, - const ResourceBindingsMap& resourceMap, - const ShaderResourceGroupVisibility& srgResourcesVisInfo) const - { - - CommandEncoderType encodeType = CommandEncoderType::Invalid; - for (const auto& it : resourceMap) + + //Cach all the resources within a srg that are used by the shader based on the visibility information + for (const auto& it : m_resourceBindings) { //Extract the visibility mask for the give resource auto visMaskIt = srgResourcesVisInfo.m_resourcesStageMask.find(it.first); @@ -426,75 +422,50 @@ namespace AZ { if(RHI::CheckBitsAny(visMaskIt->second, RHI::ShaderStageMask::Compute)) { - //Call UseResource on all resources for Compute stage - ApplyUseResourceToCompute(encoder, it.second); - encodeType = CommandEncoderType::Compute; + ApplyUseResourceToCompute(commandEncoder, it.second, resourcesToMakeResidentCompute); } else { - //Call UseResource on all resources for Vertex and Fragment stages AZ_Assert(RHI::CheckBitsAny(visMaskIt->second, RHI::ShaderStageMask::Vertex) || RHI::CheckBitsAny(visMaskIt->second, RHI::ShaderStageMask::Fragment), "The visibility mask %i is not set for Vertex or fragment stage", visMaskIt->second); - ApplyUseResourceToGraphic(encoder, visMaskIt->second, it.second); - encodeType = CommandEncoderType::Render; + ApplyUseResourceToGraphic(commandEncoder, visMaskIt->second, it.second, resourcesToMakeResidentGraphics); } } } - } - - void ArgumentBuffer::ApplyUseResourceToCompute(id encoder, const ResourceBindingsSet& resourceBindingDataSet) const - { - for (const auto& resourceBindingData : resourceBindingDataSet) - { - ResourceType rescType = resourceBindingData.m_resourcPtr->GetResourceType(); - switch(rescType) - { - case ResourceType::MtlTextureType: - { - MTLResourceUsage resourceUsage = GetImageResourceUsage(resourceBindingData.m_imageAccess); - [static_cast>(encoder) useResource:resourceBindingData.m_resourcPtr->GetGpuAddress>() usage:resourceUsage]; - - break; - } - case ResourceType::MtlBufferType: - { - MTLResourceUsage resourceUsage = GetBufferResourceUsage(resourceBindingData.m_bufferAccess); - [static_cast>(encoder) useResource:resourceBindingData.m_resourcPtr->GetGpuAddress>() usage:resourceUsage]; - - break; - } - default: - { - AZ_Assert(false, "Undefined Resource type"); - } - } - } - } - - void ArgumentBuffer::ApplyUseResourceToGraphic(id encoder, RHI::ShaderStageMask visShaderMask, const ResourceBindingsSet& resourceBindingDataSet) const - { - MTLRenderStages mtlRenderStages = GetRenderStages(visShaderMask); + //Call UseResource on all resources for Compute stage + for (const auto& key : resourcesToMakeResidentCompute) + { + [static_cast>(commandEncoder) useResources: key.second.m_resourceArray.data() + count: key.second.m_resourceArrayLen + usage: key.first]; + } + + //Call UseResource on all resources for Vertex and Fragment stages + for (const auto& key : resourcesToMakeResidentGraphics) + { + [static_cast>(commandEncoder) useResources: key.second.m_resourceArray.data() + count: key.second.m_resourceArrayLen + usage: key.first.first + stages: key.first.second]; + } + } + + void ArgumentBuffer::ApplyUseResourceToCompute(id encoder, const ResourceBindingsSet& resourceBindingDataSet, ComputeResourcesToMakeResidentMap& resourcesToMakeResidentMap) const + { for (const auto& resourceBindingData : resourceBindingDataSet) { ResourceType rescType = resourceBindingData.m_resourcPtr->GetResourceType(); + MTLResourceUsage resourceUsage = MTLResourceUsageRead; switch(rescType) { case ResourceType::MtlTextureType: { - MTLResourceUsage resourceUsage = GetImageResourceUsage(resourceBindingData.m_imageAccess); - [static_cast>(encoder) useResource:resourceBindingData.m_resourcPtr->GetGpuAddress>() - usage:resourceUsage - stages:mtlRenderStages]; - + resourceUsage |= GetImageResourceUsage(resourceBindingData.m_imageAccess); break; } case ResourceType::MtlBufferType: { - MTLResourceUsage resourceUsage = GetBufferResourceUsage(resourceBindingData.m_bufferAccess); - [static_cast>(encoder) useResource:resourceBindingData.m_resourcPtr->GetGpuAddress>() - usage:resourceUsage - stages:mtlRenderStages]; - + resourceUsage |= GetBufferResourceUsage(resourceBindingData.m_bufferAccess); break; } default: @@ -502,8 +473,38 @@ namespace AZ AZ_Assert(false, "Undefined Resource type"); } } + resourcesToMakeResidentMap[resourceUsage].m_resourceArray[resourcesToMakeResidentMap[resourceUsage].m_resourceArrayLen++] = resourceBindingData.m_resourcPtr->GetGpuAddress>(); + } + } + + void ArgumentBuffer::ApplyUseResourceToGraphic(id encoder, RHI::ShaderStageMask visShaderMask, const ResourceBindingsSet& resourceBindingDataSet, GraphicsResourcesToMakeResidentMap& resourcesToMakeResidentMap) const + { + + MTLRenderStages mtlRenderStages = GetRenderStages(visShaderMask); + MTLResourceUsage resourceUsage = MTLResourceUsageRead; + for (const auto& resourceBindingData : resourceBindingDataSet) + { + ResourceType rescType = resourceBindingData.m_resourcPtr->GetResourceType(); + switch(rescType) + { + case ResourceType::MtlTextureType: + { + resourceUsage |= GetImageResourceUsage(resourceBindingData.m_imageAccess); + break; + } + case ResourceType::MtlBufferType: + { + resourceUsage |= GetBufferResourceUsage(resourceBindingData.m_bufferAccess); + break; + } + default: + { + AZ_Assert(false, "Undefined Resource type"); + } + } + AZStd::pair key = AZStd::make_pair(resourceUsage, mtlRenderStages); + resourcesToMakeResidentMap[key].m_resourceArray[resourcesToMakeResidentMap[key].m_resourceArrayLen++] = resourceBindingData.m_resourcPtr->GetGpuAddress>(); } } - } } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h index a5a8e00e69..2434b8312d 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h @@ -119,8 +119,17 @@ namespace AZ using ResourceBindingsMap = AZStd::unordered_map; ResourceBindingsMap m_resourceBindings; - void ApplyUseResourceToCompute(id encoder, const ResourceBindingsSet& resourceBindingData) const; - void ApplyUseResourceToGraphic(id encoder, RHI::ShaderStageMask visShaderMask, const ResourceBindingsSet& resourceBindingDataSet) const; + static const int MaxEntriesInArgTable = 31; + struct MetalResourceArray + { + AZStd::array, MaxEntriesInArgTable> m_resourceArray; + int m_resourceArrayLen = 0; + }; + using ComputeResourcesToMakeResidentMap = AZStd::unordered_map; + using GraphicsResourcesToMakeResidentMap = AZStd::unordered_map, MetalResourceArray>; + + void ApplyUseResourceToCompute(id encoder, const ResourceBindingsSet& resourceBindingData, ComputeResourcesToMakeResidentMap& resourcesToMakeResidentMap) const; + void ApplyUseResourceToGraphic(id encoder, RHI::ShaderStageMask visShaderMask, const ResourceBindingsSet& resourceBindingDataSet, GraphicsResourcesToMakeResidentMap& resourcesToMakeResidentMap) const; //! Use visibility information to call UseResource on all resources for this Argument Buffer void ApplyUseResource(id encoder, const ResourceBindingsMap& resourceMap, @@ -144,8 +153,6 @@ namespace AZ #endif ShaderResourceGroupPool* m_srgPool = nullptr; - - static const int MaxEntriesInArgTable = 31; NSCache* m_samplerCache; }; } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.cpp index 3eca8dabd8..10fbe372b1 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.cpp @@ -258,24 +258,19 @@ namespace AZ continue; } + uint32_t srgVisIndex = pipelineLayout.GetSlotByIndex(shaderResourceGroup->GetBindingSlot()); + const RHI::ShaderStageMask& srgVisInfo = pipelineLayout.GetSrgVisibility(srgVisIndex); + if (bindings.m_srgsByIndex[srgIndex] != shaderResourceGroup) { bindings.m_srgsByIndex[srgIndex] = shaderResourceGroup; auto& compiledArgBuffer = shaderResourceGroup->GetCompiledArgumentBuffer(); - id argBuffer = compiledArgBuffer.GetArgEncoderBuffer(); size_t argBufferOffset = compiledArgBuffer.GetOffset(); - - uint32_t srgVisIndex = pipelineLayout.GetSlotByIndex(shaderResourceGroup->GetBindingSlot()); - const RHI::ShaderStageMask& srgVisInfo = pipelineLayout.GetSrgVisibility(srgVisIndex); - + if(srgVisInfo != RHI::ShaderStageMask::None) { - const ShaderResourceGroupVisibility& srgResourcesVisInfo = pipelineLayout.GetSrgResourcesVisibility(srgVisIndex); - - //For graphics and compute encoder bind the argument buffer and - //make the resource resident for the duration of the work associated with the current scope - //and ensure that it's in a format compatible with the appropriate metal function. + //For graphics and compute encoder bind the argument buffer if(m_commandEncoderType == CommandEncoderType::Render) { id renderEncoder = GetEncoder>(); @@ -293,7 +288,6 @@ namespace AZ offset:argBufferOffset atIndex:slotIndex]; } - shaderResourceGroup->AddUntrackedResourcesToEncoder(m_encoder, srgResourcesVisInfo); } else if(m_commandEncoderType == CommandEncoderType::Compute) { @@ -301,6 +295,28 @@ namespace AZ [computeEncoder setBuffer:argBuffer offset:argBufferOffset atIndex:pipelineLayout.GetSlotByIndex(srgIndex)]; + } + } + } + + //Check againgst the srg resources visibility hash as it is possible for draw items to have different PSO in the same pass. + const AZ::HashValue64 srgResourcesVisHash = pipelineLayout.GetSrgResourcesVisibilityHash(srgVisIndex); + if(bindings.m_srgVisHashByIndex[srgIndex] != srgResourcesVisHash) + { + bindings.m_srgVisHashByIndex[srgIndex] = srgResourcesVisHash; + if(srgVisInfo != RHI::ShaderStageMask::None) + { + const ShaderResourceGroupVisibility& srgResourcesVisInfo = pipelineLayout.GetSrgResourcesVisibility(srgVisIndex); + + //For graphics and compute encoder bind the argument buffer and + //make the resource resident for the duration of the work associated with the current scope + //and ensure that it's in a format compatible with the appropriate metal function. + if(m_commandEncoderType == CommandEncoderType::Render) + { + shaderResourceGroup->AddUntrackedResourcesToEncoder(m_encoder, srgResourcesVisInfo); + } + else if(m_commandEncoderType == CommandEncoderType::Compute) + { shaderResourceGroup->AddUntrackedResourcesToEncoder(m_encoder, srgResourcesVisInfo); } } @@ -447,6 +463,7 @@ namespace AZ for (size_t i = 0; i < bindings.m_srgsByIndex.size(); ++i) { bindings.m_srgsByIndex[i] = nullptr; + bindings.m_srgVisHashByIndex[i] = AZ::HashValue64{0}; } const PipelineLayout& pipelineLayout = pipelineState->GetPipelineLayout(); @@ -469,6 +486,10 @@ namespace AZ void CommandList::SetStreamBuffers(const RHI::StreamBufferView* streams, uint32_t count) { + int bufferArrayLen = 0; + AZStd::array, METAL_MAX_ENTRIES_BUFFER_ARG_TABLE> mtlStreamBuffers; + AZStd::array mtlStreamBufferOffsets; + AZ::HashValue64 streamsHash = AZ::HashValue64{0}; for (uint32_t i = 0; i < count; ++i) { @@ -479,18 +500,23 @@ namespace AZ { m_state.m_streamsHash = streamsHash; AZ_Assert(count <= METAL_MAX_ENTRIES_BUFFER_ARG_TABLE , "Slots needed cannot exceed METAL_MAX_ENTRIES_BUFFER_ARG_TABLE"); - for (uint32_t i = 0; i < count; ++i) + + NSRange range = {METAL_MAX_ENTRIES_BUFFER_ARG_TABLE - count, count}; + //For metal the stream buffers are populated from bottom to top as the top slots are taken by argument buffers + for (int i = count-1; i >= 0; --i) { if (streams[i].GetBuffer()) { const Buffer * buff = static_cast(streams[i].GetBuffer()); id mtlBuff = buff->GetMemoryView().GetGpuAddress>(); - uint32_t VBIndex = (METAL_MAX_ENTRIES_BUFFER_ARG_TABLE - 1) - i; uint32_t offset = streams[i].GetByteOffset() + buff->GetMemoryView().GetOffset(); - id renderEncoder = GetEncoder>(); - [renderEncoder setVertexBuffer: mtlBuff offset: offset atIndex: VBIndex]; + mtlStreamBuffers[bufferArrayLen] = mtlBuff; + mtlStreamBufferOffsets[bufferArrayLen] = offset; + bufferArrayLen++; } } + id renderEncoder = GetEncoder>(); + [renderEncoder setVertexBuffers: mtlStreamBuffers.data() offsets: mtlStreamBufferOffsets.data() withRange: range]; } } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.h index 6660beb2c4..dd4e382471 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.h @@ -99,6 +99,7 @@ namespace AZ { AZStd::array m_srgsByIndex; AZStd::array m_srgsBySlot; + AZStd::array m_srgVisHashByIndex; }; ShaderResourceBindings& GetShaderResourceBindingsByPipelineType(RHI::PipelineStateType pipelineType); diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/PipelineLayout.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/PipelineLayout.cpp index f237884aab..70d36f8d6d 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/PipelineLayout.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/PipelineLayout.cpp @@ -70,6 +70,7 @@ namespace AZ m_srgVisibilities.resize(RHI::Limits::Pipeline::ShaderResourceGroupCountMax); m_srgResourcesVisibility.resize(RHI::Limits::Pipeline::ShaderResourceGroupCountMax); + m_srgResourcesVisibilityHash.resize(RHI::Limits::Pipeline::ShaderResourceGroupCountMax); for (uint32_t srgLayoutIdx = 0; srgLayoutIdx < groupLayoutCount; ++srgLayoutIdx) { const RHI::ShaderResourceGroupLayout& srgLayout = *descriptor.GetShaderResourceGroupLayout(srgLayoutIdx); @@ -111,6 +112,7 @@ namespace AZ m_srgVisibilities[srgIndex] = mask; m_srgResourcesVisibility[srgIndex] = srgVis; + m_srgResourcesVisibilityHash[srgIndex] = srgVis.GetHash(); } // Cache the inline constant size and slot index @@ -141,6 +143,11 @@ namespace AZ return m_srgResourcesVisibility[index]; } + const AZ::HashValue64 PipelineLayout::GetSrgResourcesVisibilityHash(uint32_t index) const + { + return m_srgResourcesVisibilityHash[index]; + } + uint32_t PipelineLayout::GetRootConstantsSize() const { return m_rootConstantsSize; diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/PipelineLayout.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/PipelineLayout.h index e8cd249393..6fd06ea29b 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/PipelineLayout.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/PipelineLayout.h @@ -57,6 +57,9 @@ namespace AZ /// Returns srgVisibility data const ShaderResourceGroupVisibility& GetSrgResourcesVisibility(uint32_t index) const; + /// Returns srgVisibility hash + const AZ::HashValue64 GetSrgResourcesVisibilityHash(uint32_t index) const; + /// Returns the root constant specific layout information uint32_t GetRootConstantsSize() const; uint32_t GetRootConstantsSlotIndex() const; @@ -84,6 +87,9 @@ namespace AZ /// Cache Visibility across all the resources within the SRG AZStd::fixed_vector m_srgResourcesVisibility; + /// Cache Visibility hash across all the resources within the SRG + AZStd::fixed_vector m_srgResourcesVisibilityHash; + uint32_t m_rootConstantSlotIndex = (uint32_t)-1; uint32_t m_rootConstantsSize = 0; }; From fefa46dd6a8c563853b2cae7d3498ad617252881 Mon Sep 17 00:00:00 2001 From: Doug McDiarmid Date: Fri, 4 Jun 2021 02:39:25 -0700 Subject: [PATCH 505/811] Added DiffuseGlobalIlluminationFeatureProcessor and moved the DiffuseProbeGrid files to the DiffuseGlobalIllumination directory --- .../DiffuseComposite.azsl | 12 +- .../DiffuseProbeGridDownsample.azsl | 12 +- ...balIlluminationFeatureProcessorInterface.h | 40 +++++++ ...iffuseProbeGridFeatureProcessorInterface.h | 0 .../Code/Source/CommonSystemComponent.cpp | 20 ++-- ...fuseGlobalIlluminationFeatureProcessor.cpp | 113 ++++++++++++++++++ ...iffuseGlobalIlluminationFeatureProcessor.h | 52 ++++++++ .../DiffuseProbeGrid.cpp | 2 +- .../DiffuseProbeGrid.h | 2 +- .../DiffuseProbeGridBlendDistancePass.cpp | 4 +- .../DiffuseProbeGridBlendDistancePass.h | 0 .../DiffuseProbeGridBlendIrradiancePass.cpp | 4 +- .../DiffuseProbeGridBlendIrradiancePass.h | 0 .../DiffuseProbeGridBorderUpdatePass.cpp | 4 +- .../DiffuseProbeGridBorderUpdatePass.h | 0 .../DiffuseProbeGridClassificationPass.cpp | 4 +- .../DiffuseProbeGridClassificationPass.h | 3 +- .../DiffuseProbeGridFeatureProcessor.cpp | 2 +- .../DiffuseProbeGridFeatureProcessor.h | 4 +- .../DiffuseProbeGridRayTracingPass.cpp | 4 +- .../DiffuseProbeGridRayTracingPass.h | 2 +- .../DiffuseProbeGridRelocationPass.cpp | 4 +- .../DiffuseProbeGridRelocationPass.h | 3 +- .../DiffuseProbeGridRenderPass.cpp | 4 +- .../DiffuseProbeGridRenderPass.h | 0 .../DiffuseProbeGridTextureReadback.cpp | 4 +- .../DiffuseProbeGridTextureReadback.h | 2 +- .../Code/atom_feature_common_files.cmake | 42 +++---- .../atom_feature_common_public_files.cmake | 3 +- ...DiffuseGlobalIlluminationComponentConfig.h | 10 +- ...eGlobalIlluminationComponentController.cpp | 25 ++-- ...useGlobalIlluminationComponentController.h | 7 +- .../DiffuseProbeGridComponentController.h | 2 +- 33 files changed, 291 insertions(+), 99 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessorInterface.h rename Gems/Atom/Feature/Common/Code/Include/Atom/Feature/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridFeatureProcessorInterface.h (100%) create mode 100644 Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessor.cpp create mode 100644 Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessor.h rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGrid.cpp (99%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGrid.h (99%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridBlendDistancePass.cpp (98%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridBlendDistancePass.h (100%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridBlendIrradiancePass.cpp (98%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridBlendIrradiancePass.h (100%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridBorderUpdatePass.cpp (98%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridBorderUpdatePass.h (100%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridClassificationPass.cpp (98%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridClassificationPass.h (97%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridFeatureProcessor.cpp (99%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridFeatureProcessor.h (98%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridRayTracingPass.cpp (99%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridRayTracingPass.h (98%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridRelocationPass.cpp (98%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridRelocationPass.h (97%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridRenderPass.cpp (98%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridRenderPass.h (100%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridTextureReadback.cpp (98%) rename Gems/Atom/Feature/Common/Code/Source/{DiffuseProbeGrid => DiffuseGlobalIllumination}/DiffuseProbeGridTextureReadback.h (96%) diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseComposite.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseComposite.azsl index b3b26c4d42..3e2fda8d5d 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseComposite.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseComposite.azsl @@ -37,6 +37,9 @@ ShaderResourceGroup PassSrg : SRG_PerPass AddressV = Clamp; AddressW = Clamp; }; + + // scale multiplier of the downsampled size to the fullscreen size (e.g., 4) + uint m_imageScale; } #include @@ -148,13 +151,10 @@ float3 SampleGlobalIBL(uint sampleIndex, uint2 screenCoords, float depth, float3 PSOutput MainPS(VSOutput IN, in uint sampleIndex : SV_SampleIndex) { uint2 screenCoords = IN.m_position.xy; - - // [GFX TODO][ATOM-6172] Add image scale PassSrg constant to the DiffuseProbeGrid downsample/upsample - const uint ImageScale = 4; - const float ImageScaleInverse = 1.0f / ImageScale; + float imageScaleInverse = 1.0f / PassSrg::m_imageScale; // compute image coords for the downsampled probe irradiance image - uint2 probeIrradianceCoords = screenCoords * ImageScaleInverse; + uint2 probeIrradianceCoords = screenCoords * imageScaleInverse; float depth = PassSrg::m_depth.Load(screenCoords, sampleIndex).r; float4 encodedNormal = PassSrg::m_normal.Load(screenCoords, sampleIndex); @@ -165,7 +165,7 @@ PSOutput MainPS(VSOutput IN, in uint sampleIndex : SV_SampleIndex) float3 diffuse = float3(0.0f, 0.0f, 0.0f); if (useProbeIrradiance > 0.0f) { - float3 irradiance = SampleProbeIrradiance(sampleIndex, probeIrradianceCoords, depth, normal, albedo, ImageScale); + float3 irradiance = SampleProbeIrradiance(sampleIndex, probeIrradianceCoords, depth, normal, albedo, PassSrg::m_imageScale); diffuse = (albedo.rgb / PI) * irradiance; } else diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseProbeGridDownsample.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseProbeGridDownsample.azsl index e051317567..85772c6577 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseProbeGridDownsample.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseProbeGridDownsample.azsl @@ -31,6 +31,9 @@ ShaderResourceGroup PassSrg : SRG_PerPass AddressV = Clamp; AddressW = Clamp; }; + + // scale multiplier of the downsampled size to the fullscreen size (e.g., 4) + uint m_outputImageScale; } #include @@ -56,16 +59,13 @@ struct PSOutput // Pixel Shader PSOutput MainPS(VSOutput IN, in uint sampleIndex : SV_SampleIndex) { - // the downsample is 1/4 resolution - // [GFX TODO][ATOM-6172] Add image scale PassSrg constant to the DiffuseProbeGrid downsample/upsample - const uint ImageScale = 4; - uint2 screenCoords = IN.m_position.xy * ImageScale; + uint2 screenCoords = IN.m_position.xy * PassSrg::m_outputImageScale; float downsampledDepth = 0; float4 downsampledEncodedNormal; - for (uint y = 0; y < ImageScale; ++y) + for (uint y = 0; y < PassSrg::m_outputImageScale; ++y) { - for (uint x = 0; x < ImageScale; ++x) + for (uint x = 0; x < PassSrg::m_outputImageScale; ++x) { float depth = PassSrg::m_depth.Load(screenCoords + int2(x, y), sampleIndex).r; float4 encodedNormal = PassSrg::m_normal.Load(screenCoords + int2(x, y), sampleIndex); diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessorInterface.h new file mode 100644 index 0000000000..88faac1728 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessorInterface.h @@ -0,0 +1,40 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include + +namespace AZ +{ + namespace Render + { + enum class DiffuseGlobalIlluminationQualityLevel : uint8_t + { + Low, + Medium, + High + }; + + //! This class provides general features and configuration for the diffuse global illumination environment, + //! which consists of DiffuseProbeGrids and the diffuse Global IBL cubemap. + class DiffuseGlobalIlluminationFeatureProcessorInterface + : public RPI::FeatureProcessor + { + public: + AZ_RTTI(AZ::Render::DiffuseProbeGridFeatureProcessorInterface, "{BD8CA35A-47C3-4FD8-932B-18495EF07527}"); + + virtual void SetQualityLevel(DiffuseGlobalIlluminationQualityLevel qualityLevel) = 0; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessorInterface.h similarity index 100% rename from Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h rename to Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessorInterface.h diff --git a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp index 00c55cbade..87e134477a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp @@ -91,14 +91,15 @@ #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -135,6 +136,7 @@ namespace AZ LightingPreset::Reflect(context); ModelPreset::Reflect(context); DiffuseProbeGridFeatureProcessor::Reflect(context); + DiffuseGlobalIlluminationFeatureProcessor::Reflect(context); RayTracingFeatureProcessor::Reflect(context); if (SerializeContext* serialize = azrtti_cast(context)) @@ -191,6 +193,7 @@ namespace AZ AZ::RPI::FeatureProcessorFactory::Get()->RegisterFeatureProcessor(); AZ::RPI::FeatureProcessorFactory::Get()->RegisterFeatureProcessor(); AZ::RPI::FeatureProcessorFactory::Get()->RegisterFeatureProcessor(); + AZ::RPI::FeatureProcessorFactory::Get()->RegisterFeatureProcessor(); AZ::RPI::FeatureProcessorFactory::Get()->RegisterFeatureProcessor(); // Add SkyBox pass @@ -285,6 +288,7 @@ namespace AZ void CommonSystemComponent::Deactivate() { AZ::RPI::FeatureProcessorFactory::Get()->UnregisterFeatureProcessor(); + AZ::RPI::FeatureProcessorFactory::Get()->UnregisterFeatureProcessor(); AZ::RPI::FeatureProcessorFactory::Get()->UnregisterFeatureProcessor(); AZ::RPI::FeatureProcessorFactory::Get()->UnregisterFeatureProcessor(); AZ::RPI::FeatureProcessorFactory::Get()->UnregisterFeatureProcessor(); diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessor.cpp new file mode 100644 index 0000000000..5040665456 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessor.cpp @@ -0,0 +1,113 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + void DiffuseGlobalIlluminationFeatureProcessor::Reflect(ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext + ->Class() + ->Version(0); + } + } + + void DiffuseGlobalIlluminationFeatureProcessor::Activate() + { + EnableSceneNotification(); + } + + void DiffuseGlobalIlluminationFeatureProcessor::Deactivate() + { + DisableSceneNotification(); + } + + void DiffuseGlobalIlluminationFeatureProcessor::SetQualityLevel(DiffuseGlobalIlluminationQualityLevel qualityLevel) + { + m_qualityLevel = qualityLevel; + + UpdatePasses(); + } + + void DiffuseGlobalIlluminationFeatureProcessor::OnRenderPipelinePassesChanged([[maybe_unused]] RPI::RenderPipeline* renderPipeline) + { + UpdatePasses(); + } + + void DiffuseGlobalIlluminationFeatureProcessor::OnRenderPipelineAdded([[maybe_unused]] RPI::RenderPipelinePtr pipeline) + { + UpdatePasses(); + } + + void DiffuseGlobalIlluminationFeatureProcessor::UpdatePasses() + { + float sizeMultiplier = 0.0f; + switch (m_qualityLevel) + { + case DiffuseGlobalIlluminationQualityLevel::Low: + sizeMultiplier = 0.25f; + break; + case DiffuseGlobalIlluminationQualityLevel::Medium: + sizeMultiplier = 0.5f; + break; + case DiffuseGlobalIlluminationQualityLevel::High: + sizeMultiplier = 1.0f; + break; + default: + AZ_Assert(false, "Unknown DiffuseGlobalIlluminationQualityLevel [%d]", m_qualityLevel); + break; + } + + // update the size multiplier on the DiffuseProbeGridDownsamplePass output + AZStd::vector downsamplePassHierarchy = { Name("DiffuseGlobalIlluminationPass"), Name("DiffuseProbeGridDownsamplePass") }; + RPI::PassHierarchyFilter downsamplePassFilter(downsamplePassHierarchy); + const AZStd::vector& downsamplePasses = RPI::PassSystemInterface::Get()->FindPasses(downsamplePassFilter); + for (RPI::Pass* pass : downsamplePasses) + { + for (uint32_t outputIndex = 0; outputIndex < pass->GetOutputCount(); ++outputIndex) + { + RPI::Ptr outputAttachment = pass->GetOutputBinding(outputIndex).m_attachment; + RPI::PassAttachmentSizeMultipliers& sizeMultipliers = outputAttachment->m_sizeMultipliers; + + sizeMultipliers.m_widthMultiplier = sizeMultiplier; + sizeMultipliers.m_heightMultiplier = sizeMultiplier; + } + + // set the output scale on the PassSrg + RPI::FullscreenTrianglePass* downsamplePass = static_cast(pass); + auto constantIndex = downsamplePass->GetShaderResourceGroup()->FindShaderInputConstantIndex(Name("m_outputImageScale")); + downsamplePass->GetShaderResourceGroup()->SetConstant(constantIndex, aznumeric_cast(1.0f / sizeMultiplier)); + } + + // update the image scale on the DiffuseComposite pass + AZStd::vector compositePassHierarchy = { Name("DiffuseGlobalIlluminationPass"), Name("DiffuseCompositePass") }; + RPI::PassHierarchyFilter compositePassFilter(compositePassHierarchy); + const AZStd::vector& compositePasses = RPI::PassSystemInterface::Get()->FindPasses(compositePassFilter); + for (RPI::Pass* pass : compositePasses) + { + RPI::FullscreenTrianglePass* compositePass = static_cast(pass); + auto constantIndex = compositePass->GetShaderResourceGroup()->FindShaderInputConstantIndex(Name("m_imageScale")); + compositePass->GetShaderResourceGroup()->SetConstant(constantIndex, aznumeric_cast(1.0f / sizeMultiplier)); + } + } + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessor.h new file mode 100644 index 0000000000..81dc1487fa --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessor.h @@ -0,0 +1,52 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include + +namespace AZ +{ + namespace Render + { + //! This class provides general features and configuration for the diffuse global illumination environment, + //! which consists of DiffuseProbeGrids and the diffuse Global IBL cubemap. + class DiffuseGlobalIlluminationFeatureProcessor final + : public DiffuseGlobalIlluminationFeatureProcessorInterface + { + public: + AZ_RTTI(AZ::Render::DiffuseGlobalIlluminationFeatureProcessor, "{14F7DF46-AA2C-49EF-8A2C-0A7CB7390BB7}", DiffuseGlobalIlluminationFeatureProcessorInterface); + + static void Reflect(AZ::ReflectContext* context); + + DiffuseGlobalIlluminationFeatureProcessor() = default; + virtual ~DiffuseGlobalIlluminationFeatureProcessor() = default; + + void Activate() override; + void Deactivate() override; + + // DiffuseGlobalIlluminationFeatureProcessorInterface overrides + void SetQualityLevel(DiffuseGlobalIlluminationQualityLevel qualityLevel) override; + + private: + AZ_DISABLE_COPY_MOVE(DiffuseGlobalIlluminationFeatureProcessor); + + // RPI::SceneNotificationBus::Handler overrides + void OnRenderPipelinePassesChanged(RPI::RenderPipeline* renderPipeline) override; + void OnRenderPipelineAdded(RPI::RenderPipelinePtr pipeline) override; + + void UpdatePasses(); + + DiffuseGlobalIlluminationQualityLevel m_qualityLevel = DiffuseGlobalIlluminationQualityLevel::Low; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGrid.cpp similarity index 99% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.cpp rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGrid.cpp index a55d8fc78c..cfdfd9efa4 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGrid.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include #include #include #include diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGrid.h similarity index 99% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGrid.h index ff6ad719cf..4a732ae7af 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGrid.h +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGrid.h @@ -17,7 +17,7 @@ #include #include #include -#include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp similarity index 98% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.cpp rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp index 2a06dacf3f..04e68136f1 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp @@ -10,7 +10,6 @@ * */ -#include #include #include #include @@ -18,7 +17,8 @@ #include #include #include -#include +#include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.h similarity index 100% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.h rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.h diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp similarity index 98% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.cpp rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp index 4818018ea3..f1fe792542 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp @@ -10,7 +10,6 @@ * */ -#include #include #include #include @@ -18,7 +17,8 @@ #include #include #include -#include +#include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.h similarity index 100% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.h rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.h diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp similarity index 98% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.cpp rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp index 8821de8a9d..a24d54d9b7 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp @@ -10,7 +10,6 @@ * */ -#include #include #include #include @@ -18,7 +17,8 @@ #include #include #include -#include +#include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.h similarity index 100% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.h rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.h diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp similarity index 98% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.cpp rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp index 65f1c2dd5a..8d39e6fcc8 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp @@ -10,7 +10,6 @@ * */ -#include #include #include #include @@ -22,7 +21,8 @@ #include #include #include -#include +#include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.h similarity index 97% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.h rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.h index 677e16ac42..eef59c3753 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.h @@ -12,7 +12,6 @@ #pragma once #include - #include #include #include @@ -22,7 +21,7 @@ #include #include #include -#include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp similarity index 99% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp index 060d51d1d0..ba24bcc001 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.h similarity index 98% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.h rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.h index 19e9bf1b1d..3fb70830d0 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.cpp similarity index 99% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.cpp rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.cpp index 65d71b8272..c77f66645e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.cpp @@ -10,7 +10,6 @@ * */ -#include #include #include #include @@ -25,7 +24,8 @@ #include #include #include -#include +#include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.h similarity index 98% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.h rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.h index bb35803e51..910537a2f1 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.h @@ -19,7 +19,7 @@ #include #include #include -#include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp similarity index 98% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.cpp rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp index 86a26f002d..2f0ed373b9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp @@ -10,7 +10,6 @@ * */ -#include #include #include #include @@ -22,7 +21,8 @@ #include #include #include -#include +#include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.h similarity index 97% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.h rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.h index 437ac2f3f5..1900f8b786 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.h @@ -12,7 +12,6 @@ #pragma once #include - #include #include #include @@ -22,7 +21,7 @@ #include #include #include -#include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.cpp similarity index 98% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.cpp rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.cpp index 4f9221a65f..f025079994 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.cpp @@ -10,12 +10,12 @@ * */ -#include -#include #include #include #include #include +#include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.h similarity index 100% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.h rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.h diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridTextureReadback.cpp similarity index 98% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridTextureReadback.cpp index bc619cc277..5465d0da33 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridTextureReadback.cpp @@ -10,8 +10,8 @@ * */ -#include -#include +#include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.h b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridTextureReadback.h similarity index 96% rename from Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.h rename to Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridTextureReadback.h index 1becd6fb3e..6f7ebb9240 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.h +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridTextureReadback.h @@ -14,7 +14,7 @@ #include #include #include -#include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake index 76b71e5fae..0df5501803 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -119,26 +119,28 @@ set(FILES Source/Decals/AsyncLoadTracker.h Source/Decals/DecalTextureArrayFeatureProcessor.h Source/Decals/DecalTextureArrayFeatureProcessor.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridRayTracingPass.h - Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridBlendIrradiancePass.h - Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridBlendDistancePass.h - Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridBorderUpdatePass.h - Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridRelocationPass.h - Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridClassificationPass.h - Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridRenderPass.h - Source/DiffuseProbeGrid/DiffuseProbeGrid.cpp - Source/DiffuseProbeGrid/DiffuseProbeGrid.h - Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.cpp - Source/DiffuseProbeGrid/DiffuseProbeGridTextureReadback.h - Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.h - Source/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessor.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.h + Source/DiffuseGlobalIllumination/DiffuseProbeGrid.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGrid.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridTextureReadback.cpp + Source/DiffuseGlobalIllumination/DiffuseProbeGridTextureReadback.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.h + Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp + Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessor.h + Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessor.cpp Source/DisplayMapper/AcesOutputTransformPass.cpp Source/DisplayMapper/AcesOutputTransformLutPass.cpp Source/DisplayMapper/ApplyShaperLookupTablePass.cpp diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake index 9034859707..9f9c64dd46 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake @@ -22,7 +22,8 @@ set(FILES Include/Atom/Feature/CoreLights/SimpleSpotLightFeatureProcessorInterface.h Include/Atom/Feature/CoreLights/ShadowConstants.h Include/Atom/Feature/Decals/DecalFeatureProcessorInterface.h - Include/Atom/Feature/DiffuseProbeGrid/DiffuseProbeGridFeatureProcessorInterface.h + Include/Atom/Feature/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessorInterface.h + Include/Atom/Feature/DiffuseGlobalIllumination/DiffuseGlobalIlluminationFeatureProcessorInterface.h Include/Atom/Feature/DisplayMapper/DisplayMapperFeatureProcessorInterface.h Include/Atom/Feature/ImageBasedLights/ImageBasedLightFeatureProcessorInterface.h Include/Atom/Feature/Mesh/MeshFeatureProcessorInterface.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.h index 23296967a5..fb99a99e1a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentConfig.h @@ -14,20 +14,12 @@ #include #include +#include namespace AZ { namespace Render { - enum class DiffuseGlobalIlluminationQualityLevel : uint32_t - { - Low, - Medium, - High, - - Count - }; - class DiffuseGlobalIlluminationComponentConfig final : public ComponentConfig { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.cpp index 4c7f37bd4a..a9feb0185c 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.cpp @@ -11,11 +11,8 @@ */ #include - -//#include - +#include #include -//#include namespace AZ { @@ -55,18 +52,22 @@ namespace AZ void DiffuseGlobalIlluminationComponentController::Activate(EntityId entityId) { - m_entityId = entityId; + AZ_UNUSED(entityId); + + const RPI::Scene* scene = AZ::RPI::RPISystemInterface::Get()->GetDefaultScene().get(); + m_featureProcessor = scene->GetFeatureProcessor(); + + OnConfigChanged(); } void DiffuseGlobalIlluminationComponentController::Deactivate() { - //m_postProcessInterface = nullptr; - m_entityId.SetInvalid(); } void DiffuseGlobalIlluminationComponentController::SetConfiguration(const DiffuseGlobalIlluminationComponentConfig& config) { m_configuration = config; + OnConfigChanged(); } @@ -77,15 +78,7 @@ namespace AZ void DiffuseGlobalIlluminationComponentController::OnConfigChanged() { - // Register the configuration with the AcesDisplayMapperFeatureProcessor for this scene. - //const AZ::RPI::Scene* scene = AZ::RPI::RPISystemInterface::Get()->GetDefaultScene().get(); - //DisplayMapperFeatureProcessorInterface* fp = scene->GetFeatureProcessor(); - //DisplayMapperConfigurationDescriptor desc; - //desc.m_operationType = m_configuration.m_displayMapperOperation; - //desc.m_ldrGradingLutEnabled = m_configuration.m_ldrColorGradingLutEnabled; - //desc.m_ldrColorGradingLut = m_configuration.m_ldrColorGradingLut; - //desc.m_acesParameterOverrides = m_configuration.m_acesParameterOverrides; - //fp->RegisterDisplayMapperConfiguration(desc); + m_featureProcessor->SetQualityLevel(m_configuration.m_qualityLevel); } } // namespace Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.h index 8700e1ffb5..81da772129 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseGlobalIlluminationComponentController.h @@ -14,12 +14,9 @@ #include #include - +#include #include -//#include -//#include - namespace AZ { namespace Render @@ -49,7 +46,7 @@ namespace AZ void OnConfigChanged(); DiffuseGlobalIlluminationComponentConfig m_configuration; - EntityId m_entityId; + DiffuseGlobalIlluminationFeatureProcessorInterface* m_featureProcessor = nullptr; }; } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.h index ef606d2170..51a17cb2cf 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridComponentController.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include From 3d1abdc4e3934888ad253d0563f614b094496418 Mon Sep 17 00:00:00 2001 From: igarri Date: Fri, 4 Jun 2021 12:16:32 +0100 Subject: [PATCH 506/811] Pull request corrections, namespaces, style, etc --- .../Entries/RootAssetBrowserEntry.cpp | 2 +- .../AssetBrowser/Search/Filter.h | 1 + .../AssetBrowser/Views/EntryDelegate.cpp | 8 +-- .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 61 +++++++++---------- 4 files changed, 36 insertions(+), 36 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp index 2ccc2cd6bf..e626f31b62 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp @@ -287,7 +287,7 @@ namespace AzToolsFramework product->m_assetType.ToString(product->m_assetTypeString); AZ::Data::AssetCatalogRequestBus::BroadcastResult(product->m_relativePath, &AZ::Data::AssetCatalogRequests::GetAssetPathById, assetId); QString displayPath = QString::fromUtf8(product->m_relativePath.c_str()); - displayPath.remove(QString("/" + QString::fromUtf8(product->m_name.c_str()))); + displayPath.remove(QString(AZ_CORRECT_DATABASE_SEPARATOR + QString::fromUtf8(product->m_name.c_str()))); product->m_displayPath = displayPath; EntryCache::GetInstance()->m_productAssetIdMap[assetId] = product; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h index 135dd00925..b67b699862 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.h @@ -110,6 +110,7 @@ namespace AzToolsFramework ~StringFilter() override = default; void SetFilterString(const QString& filterString); + protected: QString GetNameInternal() const override; bool MatchInternal(const AssetBrowserEntry* entry) const override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp index c73c00981b..d0ac05020d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/EntryDelegate.cpp @@ -95,13 +95,13 @@ namespace AzToolsFramework remainingRect.adjust(thumbX, 0, 0, 0); // bump it to the right by the size of the thumbnail remainingRect.adjust(ENTRY_SPACING_LEFT_PIXELS, 0, 0, 0); // bump it to the right by the spacing. } - QString displayString = qvariant_cast(index.data(index.column())); + QString displayString = index.column() == aznumeric_cast(AssetBrowserEntry::Column::Name) + ? qvariant_cast(entry->data(aznumeric_cast(AssetBrowserEntry::Column::Name))) + : qvariant_cast(entry->data(aznumeric_cast(AssetBrowserEntry::Column::Path))); style->drawItemText( painter, remainingRect, option.displayAlignment, actualPalette, isEnabled, - index.column() == aznumeric_cast(AssetBrowserEntry::Column::Name) - ? qvariant_cast(entry->data(aznumeric_cast(AssetBrowserEntry::Column::Name))) - : qvariant_cast(entry->data(aznumeric_cast(AssetBrowserEntry::Column::Path))), + displayString, isSelected ? QPalette::HighlightedText : QPalette::Text); } } diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 481cc35635..60ff6f9549 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -74,9 +74,9 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->setupUi(this); m_ui->m_searchWidget->Setup(true, true); - namespace AB = AzToolsFramework::AssetBrowser; + namespace AzAssetBrowser = AzToolsFramework::AssetBrowser; - AB::AssetBrowserComponentRequestBus::BroadcastResult(m_assetBrowserModel, &AB::AssetBrowserComponentRequests::GetAssetBrowserModel); + AzAssetBrowser::AssetBrowserComponentRequestBus::BroadcastResult(m_assetBrowserModel, &AzAssetBrowser::AssetBrowserComponentRequests::GetAssetBrowserModel); AZ_Assert(m_assetBrowserModel, "Failed to get filebrowser model"); m_filterModel->setSourceModel(m_assetBrowserModel); m_filterModel->SetFilter(m_ui->m_searchWidget->GetFilter()); @@ -90,34 +90,34 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_tableModel->setSourceModel(m_filterModel.data()); m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); connect( - m_filterModel.data(), &AB::AssetBrowserFilterModel::filterChanged, m_tableModel.data(), - &AB::AssetBrowserTableModel::UpdateTableModelMaps); + m_filterModel.data(), &AzAssetBrowser::AssetBrowserFilterModel::filterChanged, m_tableModel.data(), + &AzAssetBrowser::AssetBrowserTableModel::UpdateTableModelMaps); connect( - m_ui->m_assetBrowserTableViewWidget, &AB::AssetBrowserTableView::selectionChangedSignal, this, + m_ui->m_assetBrowserTableViewWidget, &AzAssetBrowser::AssetBrowserTableView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); connect( m_ui->m_assetBrowserTableViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItemTableModel); connect( - m_ui->m_assetBrowserTableViewWidget, &AB::AssetBrowserTableView::ClearStringFilter, m_ui->m_searchWidget, - &AB::SearchWidget::ClearStringFilter); + m_ui->m_assetBrowserTableViewWidget, &AzAssetBrowser::AssetBrowserTableView::ClearStringFilter, m_ui->m_searchWidget, + &AzAssetBrowser::SearchWidget::ClearStringFilter); connect( - m_ui->m_assetBrowserTableViewWidget, &AB::AssetBrowserTableView::ClearTypeFilter, m_ui->m_searchWidget, - &AB::SearchWidget::ClearTypeFilter); + m_ui->m_assetBrowserTableViewWidget, &AzAssetBrowser::AssetBrowserTableView::ClearTypeFilter, m_ui->m_searchWidget, + &AzAssetBrowser::SearchWidget::ClearTypeFilter); m_ui->m_assetBrowserTableViewWidget->SetName("AssetBrowserTableView_main"); - connect(m_filterModel.data(), &AB::AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); + connect(m_filterModel.data(), &AzAssetBrowser::AssetBrowserFilterModel::stringFilterPopulated, this, &AzAssetBrowserWindow::SwitchDisplayView); connect(m_ui->m_viewSwitcherCheckBox, &QCheckBox::stateChanged, this, &AzAssetBrowserWindow::LockToDefaultView); } m_ui->m_assetBrowserTreeViewWidget->setModel(m_filterModel.data()); connect( - m_ui->m_searchWidget->GetFilter().data(), &AB::AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), - &AB::AssetBrowserFilterModel::filterUpdatedSlot); + m_ui->m_searchWidget->GetFilter().data(), &AzAssetBrowser::AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), + &AzAssetBrowser::AssetBrowserFilterModel::filterUpdatedSlot); connect( - m_filterModel.data(), &AB::AssetBrowserFilterModel::filterChanged, this, + m_filterModel.data(), &AzAssetBrowser::AssetBrowserFilterModel::filterChanged, this, [this]() { const bool hasFilter = !m_ui->m_searchWidget->GetFilterString().isEmpty(); @@ -126,17 +126,17 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) }); connect( - m_ui->m_assetBrowserTreeViewWidget, &AB::AssetBrowserTreeView::selectionChangedSignal, this, + m_ui->m_assetBrowserTreeViewWidget, &AzAssetBrowser::AssetBrowserTreeView::selectionChangedSignal, this, &AzAssetBrowserWindow::SelectionChangedSlot); connect(m_ui->m_assetBrowserTreeViewWidget, &QAbstractItemView::doubleClicked, this, &AzAssetBrowserWindow::DoubleClickedItem); connect( - m_ui->m_assetBrowserTreeViewWidget, &AB::AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, - &AB::SearchWidget::ClearStringFilter); + m_ui->m_assetBrowserTreeViewWidget, &AzAssetBrowser::AssetBrowserTreeView::ClearStringFilter, m_ui->m_searchWidget, + &AzAssetBrowser::SearchWidget::ClearStringFilter); connect( - m_ui->m_assetBrowserTreeViewWidget, &AB::AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, - &AB::SearchWidget::ClearTypeFilter); + m_ui->m_assetBrowserTreeViewWidget, &AzAssetBrowser::AssetBrowserTreeView::ClearTypeFilter, m_ui->m_searchWidget, + &AzAssetBrowser::SearchWidget::ClearTypeFilter); m_ui->m_assetBrowserTreeViewWidget->SetName("AssetBrowserTreeView_main"); } @@ -232,21 +232,21 @@ void AzAssetBrowserWindow::SelectionChangedSlot(const QItemSelection& /*selected // just becuase on some OS clicking once is activation. void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& element) { - namespace AB = AzToolsFramework::AssetBrowser; + namespace AzAssetBrowser = AzToolsFramework::AssetBrowser; // assumption: Double clicking an item selects it before telling us we double clicked it. const auto& selectedAssets = m_ui->m_assetBrowserTreeViewWidget->GetSelectedAssets(); - for (const AB::AssetBrowserEntry* entry : selectedAssets) + for (const AzAssetBrowser::AssetBrowserEntry* entry : selectedAssets) { AZ::Data::AssetId assetIdToOpen; AZStd::string fullFilePath; - if (const AB::ProductAssetBrowserEntry* productEntry = azrtti_cast(entry)) + if (const AzAssetBrowser::ProductAssetBrowserEntry* productEntry = azrtti_cast(entry)) { assetIdToOpen = productEntry->GetAssetId(); fullFilePath = entry->GetFullPath(); } - else if (const AB::SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry)) + else if (const AzAssetBrowser::SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry)) { // manufacture an empty AssetID with the source's UUID assetIdToOpen = AZ::Data::AssetId(sourceEntry->GetSourceUuid(), 0); @@ -256,8 +256,8 @@ void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& bool handledBySomeone = false; if (assetIdToOpen.IsValid()) { - AB::AssetBrowserInteractionNotificationBus::Broadcast( - &AB::AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); + AzAssetBrowser::AssetBrowserInteractionNotificationBus::Broadcast( + &AzAssetBrowser::AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); } if (!handledBySomeone && !fullFilePath.empty()) @@ -269,20 +269,19 @@ void AzAssetBrowserWindow::DoubleClickedItem([[maybe_unused]] const QModelIndex& void AzAssetBrowserWindow::DoubleClickedItemTableModel([[maybe_unused]] const QModelIndex& element) { - namespace AB = AzToolsFramework::AssetBrowser; - // assumption: Double clicking an item selects it before telling us we double clicked it. + namespace AzAssetBrowser = AzToolsFramework::AssetBrowser; const auto& selectedAssets = m_ui->m_assetBrowserTableViewWidget->GetSelectedAssets(); - for (const AB::AssetBrowserEntry* entry : selectedAssets) + for (const AzAssetBrowser::AssetBrowserEntry* entry : selectedAssets) { AZ::Data::AssetId assetIdToOpen; AZStd::string fullFilePath; - if (const AB::ProductAssetBrowserEntry* productEntry = azrtti_cast(entry)) + if (const AzAssetBrowser::ProductAssetBrowserEntry* productEntry = azrtti_cast(entry)) { assetIdToOpen = productEntry->GetAssetId(); fullFilePath = entry->GetFullPath(); } - else if (const AB::SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry)) + else if (const AzAssetBrowser::SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry)) { // manufacture an empty AssetID with the source's UUID assetIdToOpen = AZ::Data::AssetId(sourceEntry->GetSourceUuid(), 0); @@ -292,8 +291,8 @@ void AzAssetBrowserWindow::DoubleClickedItemTableModel([[maybe_unused]] const QM bool handledBySomeone = false; if (assetIdToOpen.IsValid()) { - AB::AssetBrowserInteractionNotificationBus::Broadcast( - &AB::AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); + AzAssetBrowser::AssetBrowserInteractionNotificationBus::Broadcast( + &AzAssetBrowser::AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, assetIdToOpen, handledBySomeone); } if (!handledBySomeone && !fullFilePath.empty()) From 05e20803a89253bd8f7ba6ef507242e08d833d72 Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Fri, 4 Jun 2021 14:32:06 +0100 Subject: [PATCH 507/811] First pass for getting things ready for grid snap button (#1118) * first pass of change to simplify snapping for snap-to-grid button and fix snapping bug caused by non-uniform scale --- .../AzManipulatorTestFrameworkUtils.h | 25 ++-- .../AzManipulatorTestFrameworkUtils.cpp | 58 +++++---- .../Tests/GridSnappingTest.cpp | 120 +++++++++++++----- .../Manipulators/BaseManipulator.cpp | 5 + .../Manipulators/EditorVertexSelection.cpp | 27 ++-- .../Manipulators/LinearManipulator.cpp | 70 ++++------ .../Manipulators/LinearManipulator.h | 12 +- .../Manipulators/ManipulatorSnapping.cpp | 36 ++++-- .../Manipulators/ManipulatorSnapping.h | 22 ++-- .../Manipulators/MultiLinearManipulator.cpp | 28 ++-- .../Manipulators/MultiLinearManipulator.h | 2 - .../Manipulators/PlanarManipulator.cpp | 50 +++----- .../Manipulators/PlanarManipulator.h | 13 +- .../EditorNonUniformScaleComponentMode.cpp | 48 ++++--- .../EditorTransformComponentSelection.cpp | 39 ++---- 15 files changed, 295 insertions(+), 260 deletions(-) diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h index dcddf1e5a5..f1c32e4d8d 100644 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h +++ b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h @@ -12,17 +12,22 @@ #pragma once -#include -#include #include +#include +#include +#include namespace AzManipulatorTestFramework { - //! Create a linear manipulator with a unit sphere bounds. + //! Create a linear manipulator with a unit sphere bound. AZStd::shared_ptr CreateLinearManipulator( - const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, - const AZ::Vector3& position = AZ::Vector3::CreateZero(), - const float radius = 1.0f); + const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, const AZ::Vector3& position = AZ::Vector3::CreateZero(), + float radius = 1.0f); + + //! Create a planar manipulator with a unit sphere bound. + AZStd::shared_ptr CreatePlanarManipulator( + const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, const AZ::Vector3& position = AZ::Vector3::CreateZero(), + float radius = 1.0f); //! Create a mouse pick from the specified ray and screen point. AzToolsFramework::ViewportInteraction::MousePick CreateMousePick( @@ -34,14 +39,12 @@ namespace AzManipulatorTestFramework //! Create a mouse interaction from the specified pick, buttons, interaction id and keyboard modifiers. AzToolsFramework::ViewportInteraction::MouseInteraction CreateMouseInteraction( - const AzToolsFramework::ViewportInteraction::MousePick& mousePick, - AzToolsFramework::ViewportInteraction::MouseButtons buttons, + const AzToolsFramework::ViewportInteraction::MousePick& mousePick, AzToolsFramework::ViewportInteraction::MouseButtons buttons, AzToolsFramework::ViewportInteraction::InteractionId interactionId, AzToolsFramework::ViewportInteraction::KeyboardModifiers modifiers); //! Create a mouse buttons from the specified mouse button. - AzToolsFramework::ViewportInteraction::MouseButtons CreateMouseButtons( - AzToolsFramework::ViewportInteraction::MouseButton button); + AzToolsFramework::ViewportInteraction::MouseButtons CreateMouseButtons(AzToolsFramework::ViewportInteraction::MouseButton button); //! Create a mouse interaction event from the specified interaction and event. AzToolsFramework::ViewportInteraction::MouseInteractionEvent CreateMouseInteractionEvent( @@ -61,5 +64,5 @@ namespace AzManipulatorTestFramework AzFramework::ScreenPoint GetCameraStateViewportCenter(const AzFramework::CameraState& cameraState); //! Default viewport size (1080p) in 16:9 aspect ratio. - const auto DefaultViewportSize = AZ::Vector2(1920.0f, 1080.0f); + inline const auto DefaultViewportSize = AZ::Vector2(1920.0f, 1080.0f); } // namespace AzManipulatorTestFramework diff --git a/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp b/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp index b255fcae73..985c21cf8e 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp @@ -14,7 +14,6 @@ #include #include #include -#include #include namespace AzManipulatorTestFramework @@ -28,22 +27,21 @@ namespace AzManipulatorTestFramework using MouseEvent = AzToolsFramework::ViewportInteraction::MouseEvent; using MousePick = AzToolsFramework::ViewportInteraction::MousePick; - AZStd::shared_ptr CreateLinearManipulator( - const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, - const AZ::Vector3& position, - const float radius) + // create a default sphere view for a manipulator for simple intersection + template + void SetupManipulatorView( + AZStd::shared_ptr manipulator, const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, + const AZ::Vector3& position, const float radius) { - auto manipulator = AzToolsFramework::LinearManipulator::MakeShared(AZ::Transform::CreateIdentity()); - manipulator->SetLocalPosition(position); - // unit sphere view auto sphereView = AzToolsFramework::CreateManipulatorViewSphere( AZ::Colors::Red, radius, - [](const MouseInteraction& /*mouseInteraction*/, const bool /*mouseOver*/, - const AZ::Color& defaultColor) - { - return defaultColor; - }, true); + []([[maybe_unused]] const MouseInteraction& mouseInteraction, [[maybe_unused]] const bool mouseOver, + const AZ::Color& defaultColor) + { + return defaultColor; + }, + true); // unit sphere bound AzToolsFramework::Picking::BoundShapeSphere sphereBound; @@ -62,6 +60,26 @@ namespace AzManipulatorTestFramework // this would occur internally when the manipulator is drawn but we must do manually here to ensure that the // bounds will always be valid upon instantiation view->RefreshBound(manipulatorManagerId, manipulator->GetManipulatorId(), sphereBound); + } + + AZStd::shared_ptr CreateLinearManipulator( + const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, const AZ::Vector3& position, const float radius) + { + auto manipulator = AzToolsFramework::LinearManipulator::MakeShared(AZ::Transform::CreateIdentity()); + manipulator->SetLocalPosition(position); + + SetupManipulatorView(manipulator, manipulatorManagerId, position, radius); + + return manipulator; + } + + AZStd::shared_ptr CreatePlanarManipulator( + const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, const AZ::Vector3& position, const float radius) + { + auto manipulator = AzToolsFramework::PlanarManipulator::MakeShared(AZ::Transform::CreateIdentity()); + manipulator->SetLocalPosition(position); + + SetupManipulatorView(manipulator, manipulatorManagerId, position, radius); return manipulator; } @@ -104,8 +122,7 @@ namespace AzManipulatorTestFramework return buttons; } - MouseInteractionEvent CreateMouseInteractionEvent( - const MouseInteraction& mouseInteraction, MouseEvent event) + MouseInteractionEvent CreateMouseInteractionEvent(const MouseInteraction& mouseInteraction, MouseEvent event) { return MouseInteractionEvent(mouseInteraction, event); } @@ -114,8 +131,7 @@ namespace AzManipulatorTestFramework { AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Event( AzToolsFramework::GetEntityContextId(), - &AzToolsFramework::ViewportInteraction::InternalMouseViewportRequests::InternalHandleAllMouseInteractions, - event); + &AzToolsFramework::ViewportInteraction::InternalMouseViewportRequests::InternalHandleAllMouseInteractions, event); } AzFramework::CameraState SetCameraStatePosition(const AZ::Vector3& position, AzFramework::CameraState& cameraState) @@ -133,9 +149,7 @@ namespace AzManipulatorTestFramework AzFramework::ScreenPoint GetCameraStateViewportCenter(const AzFramework::CameraState& cameraState) { - return { - aznumeric_cast(cameraState.m_viewportSize.GetX() / 2.f), - aznumeric_cast(cameraState.m_viewportSize.GetY() / 2.f) - }; + return { aznumeric_cast(cameraState.m_viewportSize.GetX() / 2.f), + aznumeric_cast(cameraState.m_viewportSize.GetY() / 2.f) }; } -} // namespace UnitTest +} // namespace AzManipulatorTestFramework diff --git a/Code/Framework/AzManipulatorTestFramework/Tests/GridSnappingTest.cpp b/Code/Framework/AzManipulatorTestFramework/Tests/GridSnappingTest.cpp index e6468c1ebb..d6006ba74f 100644 --- a/Code/Framework/AzManipulatorTestFramework/Tests/GridSnappingTest.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Tests/GridSnappingTest.cpp @@ -10,52 +10,55 @@ * */ +#include "AzManipulatorTestFrameworkTestFixtures.h" + #include #include #include -#include "AzManipulatorTestFrameworkTestFixtures.h" -#include -#include -#include #include +#include +#include +#include +#include +#include #include +#include namespace UnitTest { - class GridSnappingFixture - : public ToolsApplicationFixture + class GridSnappingFixture : public ToolsApplicationFixture { public: GridSnappingFixture() : m_viewportManipulatorInteraction(AZStd::make_unique()) - , m_actionDispatcher(AZStd::make_unique(*m_viewportManipulatorInteraction)) - , m_linearManipulator( - AzManipulatorTestFramework::CreateLinearManipulator( - m_viewportManipulatorInteraction->GetManipulatorManager().GetId(), - /*position=*/AZ::Vector3(0.0f, 50.0f, 0.0f), - /*radius=*/m_boundsRadius)) - {} + , m_actionDispatcher( + AZStd::make_unique(*m_viewportManipulatorInteraction)) + { + } protected: void SetUpEditorFixtureImpl() override { - m_cameraState = AzFramework::CreateIdentityDefaultCamera( - AZ::Vector3::CreateZero(), AzManipulatorTestFramework::DefaultViewportSize); + m_cameraState = + AzFramework::CreateIdentityDefaultCamera(AZ::Vector3::CreateZero(), AzManipulatorTestFramework::DefaultViewportSize); } public: - const float m_boundsRadius = 1.0f; AZStd::unique_ptr m_viewportManipulatorInteraction; AZStd::unique_ptr m_actionDispatcher; - AZStd::shared_ptr m_linearManipulator; AzFramework::CameraState m_cameraState; }; TEST_F(GridSnappingFixture, MouseDownWithSnappingEnabledSnapsToClosestGridSize) { + AZStd::shared_ptr linearManipulator(AzManipulatorTestFramework::CreateLinearManipulator( + m_viewportManipulatorInteraction->GetManipulatorManager().GetId(), + /*position=*/AZ::Vector3(0.0f, 50.0f, 0.0f), + /*radius=*/m_boundsRadius)); + // the initial starting position of the manipulator (in front of the camera) - const auto initialPositionWorld = m_linearManipulator->GetLocalPosition(); + const auto initialPositionWorld = linearManipulator->GetLocalPosition(); // where the manipulator should end up (in front and to the left of the camera) const auto finalPositionWorld = AZ::Vector3(-10.0f, 50.0f, 0.0f); // perspective scale factor for manipulator distance to camera @@ -66,21 +69,18 @@ namespace UnitTest // adjusted final world position taking into account the manipulator position relative to the camera const auto finalPositionWorldAdjusted = finalPositionWorld - (vectorToInitialPositionWorld * scaledRadiusBound); // calculate the position in screen space of the initial position of the manipulator - const auto initialPositionScreen = - AzFramework::WorldToScreen(initialPositionWorld, m_cameraState); + const auto initialPositionScreen = AzFramework::WorldToScreen(initialPositionWorld, m_cameraState); // calculate the position in screen space of the final position of the manipulator const auto finalPositionScreen = AzFramework::WorldToScreen(finalPositionWorldAdjusted, m_cameraState); // callback to update the manipulator's current position - m_linearManipulator->InstallMouseMoveCallback( - [this](const AzToolsFramework::LinearManipulator::Action& action) - { - auto pos = action.LocalPosition(); - m_linearManipulator->SetLocalPosition(pos); - }); + linearManipulator->InstallMouseMoveCallback( + [this, linearManipulator](const AzToolsFramework::LinearManipulator::Action& action) + { + linearManipulator->SetLocalPosition(action.LocalPosition()); + }); - m_actionDispatcher - ->EnableSnapToGrid() + m_actionDispatcher->EnableSnapToGrid() ->GridSize(5.0f) ->CameraState(m_cameraState) ->MousePosition(initialPositionScreen) @@ -89,7 +89,67 @@ namespace UnitTest ->MousePosition(finalPositionScreen) ->MouseLButtonUp() ->ExpectManipulatorNotBeingInteracted() - ->ExpectTrue(m_linearManipulator->GetLocalPosition().IsClose(finalPositionWorld, 0.01f)) - ; + ->ExpectTrue(linearManipulator->GetLocalPosition().IsClose(finalPositionWorld, 0.01f)); + } + + template + void ValidateManipulatorSnappingBehavior( + AZStd::shared_ptr manipulator, AzManipulatorTestFramework::ImmediateModeActionDispatcher* actionDispatcher, + const AzFramework::CameraState& cameraState) + { + manipulator->SetLocalOrientation(AZ::Quaternion::CreateFromEulerAnglesDegrees(AZ::Vector3(180.0f, 0.0f, 135.0f))); + + // the initial starting position of the manipulator (in front of the camera) + const auto initialPositionWorld = manipulator->GetLocalPosition() + AZ::Vector3::CreateAxisX(0.15f); + // where the manipulator should end up (unmoved) + const auto finalPositionWorld = manipulator->GetLocalPosition(); + // where we should move the mouse to + const auto attemptPositionWorld = manipulator->GetLocalPosition() + AZ::Vector3::CreateAxisX(0.35f); + // calculate the position in screen space of the initial position of the manipulator + const auto initialPositionScreen = AzFramework::WorldToScreen(initialPositionWorld, cameraState); + // calculate the position in screen space of the final position of the manipulator + const auto attemptPositionScreen = AzFramework::WorldToScreen(attemptPositionWorld, cameraState); + + // callback to update the manipulator's current position + manipulator->InstallMouseMoveCallback( + [manipulator](const typename Manipulator::Action& action) + { + manipulator->SetLocalPosition(action.LocalPosition()); + }); + + actionDispatcher->EnableSnapToGrid() + ->GridSize(1.0f) + ->CameraState(cameraState) + ->MousePosition(initialPositionScreen) + ->MouseLButtonDown() + ->ExpectManipulatorBeingInteracted() + ->MousePosition(attemptPositionScreen) + ->MouseLButtonUp() + ->ExpectManipulatorNotBeingInteracted() + ->ExpectThat(manipulator->GetLocalPosition(), IsCloseTolerance(finalPositionWorld, 0.01f)); + } + + TEST_F(GridSnappingFixture, MouseDownAndMoveLinearManipulatorDoesNotSnapWithMovementSmallerThanHalfGridSize) + { + AZStd::shared_ptr linearManipulator(AzManipulatorTestFramework::CreateLinearManipulator( + m_viewportManipulatorInteraction->GetManipulatorManager().GetId(), + /*position=*/AZ::Vector3(0.0f, 10.0f, 0.0f), + /*radius=*/m_boundsRadius)); + + linearManipulator->SetAxis(AZ::Vector3::CreateAxisY()); + + ValidateManipulatorSnappingBehavior(linearManipulator, m_actionDispatcher.get(), m_cameraState); + } + + TEST_F(GridSnappingFixture, MouseDownAndMovePlanarManipulatorDoesNotSnapWithMovementSmallerThanHalfGridSize) + { + AZStd::shared_ptr planarManipulator(AzManipulatorTestFramework::CreatePlanarManipulator( + m_viewportManipulatorInteraction->GetManipulatorManager().GetId(), + /*position=*/AZ::Vector3(0.0f, 10.0f, 0.0f), + /*radius=*/m_boundsRadius)); + + planarManipulator->SetAxes(AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ()); + + ValidateManipulatorSnappingBehavior(planarManipulator, m_actionDispatcher.get(), m_cameraState); } } // namespace UnitTest diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp index e7235f0f82..955d10d3bd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp @@ -433,6 +433,11 @@ namespace AzToolsFramework return m_manipulatorSpaceWithLocalTransform.GetSpace(); } + const AZ::Vector3& Manipulators::GetNonUniformScale() const + { + return m_manipulatorSpaceWithLocalTransform.GetNonUniformScale(); + } + void Manipulators::SetSpace(const AZ::Transform& worldFromLocal) { m_manipulatorSpaceWithLocalTransform.SetSpace(worldFromLocal); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp index 4d10a4c171..55a8464ba6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp @@ -192,8 +192,7 @@ namespace AzToolsFramework /// for each vertex associated with the translation manipulator to use with offset calculations when updating. template void InitializeVertexLookup( - IndexedTranslationManipulator& translationManipulator, - const AZ::EntityId entityId, const AZ::Vector3& snapOffset) + IndexedTranslationManipulator& translationManipulator, const AZ::EntityId entityId) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -202,7 +201,7 @@ namespace AzToolsFramework AZ::FixedVerticesRequestBus::Bind(fixedVertices, entityId); translationManipulator.Process( - [snapOffset, fixedVertices] + [fixedVertices] (typename IndexedTranslationManipulator::VertexLookup& vertexLookup) { Vertex vertex; @@ -213,7 +212,7 @@ namespace AzToolsFramework if (found) { - vertexLookup.m_start = vertex + AZ::AdaptVertexIn(snapOffset); + vertexLookup.m_start = vertex; vertexLookup.m_offset = Vertex::CreateZero(); } }); @@ -250,10 +249,10 @@ namespace AzToolsFramework // linear manipulator callbacks m_translationManipulator->m_manipulator.InstallLinearManipulatorMouseDownCallback( - [this](const LinearManipulator::Action& action) + [this]([[maybe_unused]] const LinearManipulator::Action& action) { BeginBatchMovement(); - InitializeVertexLookup(*m_translationManipulator, GetEntityId(), action.m_start.m_positionSnapOffset); + InitializeVertexLookup(*m_translationManipulator, GetEntityId()); }); m_translationManipulator->m_manipulator.InstallLinearManipulatorMouseMoveCallback( @@ -264,17 +263,17 @@ namespace AzToolsFramework }); m_translationManipulator->m_manipulator.InstallLinearManipulatorMouseUpCallback( - [this](const LinearManipulator::Action& /*action*/) + [this]([[maybe_unused]] const LinearManipulator::Action& action) { EndBatchMovement(); }); // planar manipulator callbacks m_translationManipulator->m_manipulator.InstallPlanarManipulatorMouseDownCallback( - [this](const PlanarManipulator::Action& action) + [this]([[maybe_unused]] const PlanarManipulator::Action& action) { BeginBatchMovement(); - InitializeVertexLookup(*m_translationManipulator, GetEntityId(), action.m_start.m_snapOffset); + InitializeVertexLookup(*m_translationManipulator, GetEntityId()); }); m_translationManipulator->m_manipulator.InstallPlanarManipulatorMouseMoveCallback( @@ -285,17 +284,17 @@ namespace AzToolsFramework }); m_translationManipulator->m_manipulator.InstallPlanarManipulatorMouseUpCallback( - [this](const PlanarManipulator::Action& /*action*/) + [this]([[maybe_unused]] const PlanarManipulator::Action& action) { EndBatchMovement(); }); // surface manipulator callbacks m_translationManipulator->m_manipulator.InstallSurfaceManipulatorMouseDownCallback( - [this](const SurfaceManipulator::Action& action) + [this]([[maybe_unused]] const SurfaceManipulator::Action& action) { BeginBatchMovement(); - InitializeVertexLookup(*m_translationManipulator, GetEntityId(), action.m_start.m_snapOffset); + InitializeVertexLookup(*m_translationManipulator, GetEntityId()); }); m_translationManipulator->m_manipulator.InstallSurfaceManipulatorMouseMoveCallback( @@ -306,7 +305,7 @@ namespace AzToolsFramework }); m_translationManipulator->m_manipulator.InstallSurfaceManipulatorMouseUpCallback( - [this](const SurfaceManipulator::Action& /*action*/) + [this]([[maybe_unused]] const SurfaceManipulator::Action& action) { EndBatchMovement(); }); @@ -893,7 +892,7 @@ namespace AzToolsFramework { BeginBatchMovement(); - InitializeVertexLookup(*m_translationManipulator, GetEntityId(), AZ::Vector3::CreateZero()); + InitializeVertexLookup(*m_translationManipulator, GetEntityId()); // note: AdaptVertexIn/Out is to ensure we clamp the vertex local Z position to 0 if // dealing with Vector2s when setting the position of the manipulator. const AZ::Vector3 localOffset = diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp index aa84fc5752..34ae28bd13 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp @@ -23,8 +23,8 @@ namespace AzToolsFramework { LinearManipulator::Starter CalculateLinearManipulationDataStart( const LinearManipulator::Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction, const ViewportInteraction::MouseInteraction& interaction, - const float intersectionDistance, const AzFramework::CameraState& cameraState) + const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, const float intersectionDistance, + const AzFramework::CameraState& cameraState) { const ManipulatorInteraction manipulatorInteraction = BuildManipulatorInteraction( @@ -50,28 +50,9 @@ namespace AzToolsFramework manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection, localIntersectionPoint, startTransition.m_localNormal, start.m_localHitPosition); - const float gridSize = gridSnapAction.m_gridSnapParams.m_gridSize; - const bool snapping = gridSnapAction.m_gridSnapParams.m_gridSnap; - const float scaleRecip = manipulatorInteraction.m_scaleReciprocal; - - // calculate position amount to snap, to align with grid - const AZ::Vector3 positionSnapOffset = snapping && !gridSnapAction.m_localSnapping - ? CalculateSnappedOffset(localTransform.GetTranslation(), axis, gridSize * scaleRecip) - : AZ::Vector3::CreateZero(); - - const AZ::Vector3 localScale = AZ::Vector3(localTransform.GetUniformScale()); - const AZ::Quaternion localRotation = QuaternionFromTransformNoScaling(localTransform); - // calculate scale amount to snap, to align to round scale value - const AZ::Vector3 scaleSnapOffset = snapping && !gridSnapAction.m_localSnapping - ? localRotation.GetInverseFull().TransformVector(CalculateSnappedOffset( - localRotation.TransformVector(localScale), axis, gridSize * scaleRecip)) - : AZ::Vector3::CreateZero(); - start.m_screenPosition = interaction.m_mousePick.m_screenCoordinates; - start.m_positionSnapOffset = positionSnapOffset; - start.m_scaleSnapOffset = scaleSnapOffset; - start.m_localPosition = localTransform.GetTranslation() + positionSnapOffset; - start.m_localScale = localScale + scaleSnapOffset; + start.m_localPosition = localTransform.GetTranslation(); + start.m_localScale = AZ::Vector3(localTransform.GetUniformScale());; start.m_localAxis = axis; // sign to determine which side of the linear axis we pressed // (useful to know when the visual axis flips to face the camera) @@ -87,7 +68,7 @@ namespace AzToolsFramework LinearManipulator::Action CalculateLinearManipulationDataAction( const LinearManipulator::Fixed& fixed, const LinearManipulator::Starter& starter, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, - const GridSnapAction& gridSnapAction, const ViewportInteraction::MouseInteraction& interaction) + const GridSnapParameters& gridSnapParams, const ViewportInteraction::MouseInteraction& interaction) { const ManipulatorInteraction manipulatorInteraction = BuildManipulatorInteraction( @@ -108,31 +89,34 @@ namespace AzToolsFramework GetCameraState(interaction.m_interactionId.m_viewportId)); const AZ::Vector3 axis = TransformDirectionNoScaling(localTransform, fixed.m_axis); - // The local positions have been transformed to the reference frame of the object being manipulated. But they appear in the world - // with non-uniform scale applied, and the object being manipulated will want to work with unscaled deltas, so we need to divide by - // the non-uniform scale here. + // the local positions have been transformed to the reference frame of the object being manipulated, but they appear in the world + // with non-uniform scale applied, the object being manipulated will want to work with unscaled deltas, so we need to divide by + // the non-uniform scale here const AZ::Vector3 hitDelta = (localHitPosition - start.m_localHitPosition) / nonUniformScale; const AZ::Vector3 unsnappedOffset = axis * axis.Dot(hitDelta); - const float scaleRecip = manipulatorInteraction.m_scaleReciprocal * axis.Dot(manipulatorInteraction.m_nonUniformScaleReciprocal); - const float gridSize = gridSnapAction.m_gridSnapParams.m_gridSize; - const bool snapping = gridSnapAction.m_gridSnapParams.m_gridSnap; + const float scaleRecip = + manipulatorInteraction.m_scaleReciprocal * fixed.m_axis.Dot(manipulatorInteraction.m_nonUniformScaleReciprocal); + const float gridSize = gridSnapParams.m_gridSize; + const bool snapping = gridSnapParams.m_gridSnap; LinearManipulator::Action action; action.m_fixed = fixed; action.m_start = start; action.m_current.m_localPositionOffset = snapping - ? unsnappedOffset + CalculateSnappedOffset(unsnappedOffset, axis, gridSize * scaleRecip) + ? CalculateSnappedAmount(unsnappedOffset, axis, gridSize * scaleRecip) : unsnappedOffset; action.m_current.m_screenPosition = interaction.m_mousePick.m_screenCoordinates; action.m_viewportId = interaction.m_interactionId.m_viewportId; const AZ::Quaternion localRotation = QuaternionFromTransformNoScaling(localTransform); - const AZ::Vector3 scaledUnsnappedOffset = unsnappedOffset * startTransition.m_screenToWorldScale * NonUniformScaleReciprocal(nonUniformScale); + const AZ::Vector3 scaledUnsnappedOffset = + unsnappedOffset * startTransition.m_screenToWorldScale * NonUniformScaleReciprocal(nonUniformScale); + // how much to adjust the scale based on movement const AZ::Quaternion invLocalRotation = localRotation.GetInverseFull(); action.m_current.m_localScaleOffset = snapping - ? invLocalRotation.TransformVector((scaledUnsnappedOffset + CalculateSnappedOffset(scaledUnsnappedOffset, axis, gridSize * scaleRecip))) + ? invLocalRotation.TransformVector(CalculateSnappedAmount(scaledUnsnappedOffset, axis, gridSize * scaleRecip)) : invLocalRotation.TransformVector(scaledUnsnappedOffset); // record what modifier keys are held during this action @@ -171,19 +155,18 @@ namespace AzToolsFramework const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance) { const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace()); - const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); // note: m_localTransform must not be made uniform as it may contain a local scale we want to snap m_starter = CalculateLinearManipulationDataStart( - m_fixed, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), - GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction, rayIntersectionDistance, + m_fixed, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), interaction, rayIntersectionDistance, GetCameraState(interaction.m_interactionId.m_viewportId)); if (m_onLeftMouseDownCallback) { + const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); + m_onLeftMouseDownCallback(CalculateLinearManipulationDataAction( - m_fixed, m_starter, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), - GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction)); + m_fixed, m_starter, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), gridSnapParams, interaction)); } } @@ -195,8 +178,8 @@ namespace AzToolsFramework // note: m_localTransform must not be made uniform as it may contain a local scale we want to snap m_onMouseMoveCallback(CalculateLinearManipulationDataAction( - m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), - GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction)); + m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), gridSnapParams, + interaction)); } } @@ -208,8 +191,7 @@ namespace AzToolsFramework // note: m_localTransform must not be made uniform as it may contain a local scale we want to snap m_onLeftMouseUpCallback(CalculateLinearManipulationDataAction( - m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), - GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction)); + m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), gridSnapParams, interaction)); } } @@ -232,8 +214,8 @@ namespace AzToolsFramework GridSnapSettings(mouseInteraction.m_interactionId.m_viewportId); const auto action = CalculateLinearManipulationDataAction( - m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), - GridSnapAction(gridSnapParams, mouseInteraction.m_keyboardModifiers.Alt()), mouseInteraction); + m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), gridSnapParams, + mouseInteraction); // display the exact hit (ray intersection) of the mouse pick on the manipulator DrawTransformAxes( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.h index 576c543dce..c3d43a2535 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.h @@ -20,7 +20,7 @@ namespace AzToolsFramework { - struct GridSnapAction; + struct GridSnapParameters; /// LinearManipulator serves as a visual tool for users to modify values /// in one dimension on an axis defined in 3D space. @@ -68,8 +68,6 @@ namespace AzToolsFramework AZ::Vector3 m_localScale; ///< The current scale of the manipulator in local space. AZ::Vector3 m_localHitPosition; ///< The intersection point in local space between the ray and the manipulator when the mouse down event happens. AZ::Vector3 m_localAxis; ///< The axis in the local space of the manipulator itself. - AZ::Vector3 m_positionSnapOffset; ///< The snap offset amount to ensure manipulator is aligned to the grid. - AZ::Vector3 m_scaleSnapOffset; ///< The snap offset amount to ensure manipulator is aligned to round scale increments. float m_sign; ///< Used to determine which side of the axis we clicked on in case it's flipped to face the camera. AzFramework::ScreenPoint m_screenPosition; ///< The initial position in screen space of the manipulator. }; @@ -91,7 +89,7 @@ namespace AzToolsFramework ViewportInteraction::KeyboardModifiers m_modifiers; int m_viewportId; ///< The id of the viewport this manipulator is being used in. AZ::Vector3 LocalScale() const { return m_start.m_localScale + m_current.m_localScaleOffset; } - AZ::Vector3 LocalScaleOffset() const { return m_start.m_scaleSnapOffset + m_current.m_localScaleOffset; } + AZ::Vector3 LocalScaleOffset() const { return m_current.m_localScaleOffset; } AZ::Vector3 LocalPosition() const { return m_start.m_localPosition + m_current.m_localPositionOffset; } AZ::Vector3 LocalPositionOffset() const { return m_current.m_localPositionOffset; } AZ::Vector2 ScreenOffset() const @@ -162,11 +160,11 @@ namespace AzToolsFramework LinearManipulator::Starter CalculateLinearManipulationDataStart( const LinearManipulator::Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction, const ViewportInteraction::MouseInteraction& interaction, - float intersectionDistance, const AzFramework::CameraState& cameraState); + const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, float intersectionDistance, + const AzFramework::CameraState& cameraState); LinearManipulator::Action CalculateLinearManipulationDataAction( const LinearManipulator::Fixed& fixed, const LinearManipulator::Starter& starter, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, - const GridSnapAction& gridSnapAction, const ViewportInteraction::MouseInteraction& interaction); + const GridSnapParameters& gridSnapParams, const ViewportInteraction::MouseInteraction& interaction); } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.cpp index 015ea8a3e3..8a6398d025 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.cpp @@ -42,12 +42,6 @@ namespace AzToolsFramework { } - GridSnapAction::GridSnapAction(const GridSnapParameters& gridSnapParameters, const bool localSnapping) - : m_gridSnapParams(gridSnapParameters) - , m_localSnapping(localSnapping) - { - } - ManipulatorInteraction BuildManipulatorInteraction( const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Vector3& worldRayOrigin, const AZ::Vector3& worldRayDirection) @@ -57,19 +51,39 @@ namespace AzToolsFramework return {localFromWorldUniform.TransformPoint(worldRayOrigin), TransformDirectionNoScaling(localFromWorldUniform, worldRayDirection), - ScaleReciprocal(worldFromLocalUniform), - NonUniformScaleReciprocal(nonUniformScale)}; + NonUniformScaleReciprocal(nonUniformScale), + ScaleReciprocal(worldFromLocalUniform)}; } - AZ::Vector3 CalculateSnappedOffset( - const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, const float size) + struct SnapAdjustment + { + float m_existingSnapDistance; //!< How far to snap up or down to align to the grid. + float m_nextSnapDistance; //!< The snap increment (will return full signed value (grid size) when distance + //!< moved is greater than half of the grid size in either direction). + }; + + static SnapAdjustment CalculateSnapDistance(const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, const float size) { // calculate total distance along axis const float axisDistance = axis.Dot(unsnappedPosition); // round to nearest step size const float snappedAxisDistance = floorf((axisDistance / size) + 0.5f) * size; + + return { axisDistance, snappedAxisDistance }; + } + + AZ::Vector3 CalculateSnappedOffset(const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, const float size) + { + const auto snapAdjustment = CalculateSnapDistance(unsnappedPosition, axis, size); // return offset along axis to snap to step size - return axis * (snappedAxisDistance - axisDistance); + return axis * (snapAdjustment.m_nextSnapDistance - snapAdjustment.m_existingSnapDistance); + } + + AZ::Vector3 CalculateSnappedAmount(const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, const float size) + { + const auto snapAdjustment = CalculateSnapDistance(unsnappedPosition, axis, size); + // return offset along axis to snap to step size + return axis * snapAdjustment.m_nextSnapDistance; } AZ::Vector3 CalculateSnappedTerrainPosition( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h index e6c70079df..11860780c7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h @@ -31,24 +31,15 @@ namespace AzToolsFramework float m_gridSize; }; - /// Structure to encapsulate the current grid snapping state. - struct GridSnapAction - { - GridSnapAction(const GridSnapParameters& gridSnapParameters, bool localSnapping); - - GridSnapParameters m_gridSnapParams; - bool m_localSnapping; - }; - /// Structure to hold transformed incoming viewport interaction from world space to manipulator space. struct ManipulatorInteraction { AZ::Vector3 m_localRayOrigin; ///< The ray origin (start) in the reference from of the manipulator. AZ::Vector3 m_localRayDirection; ///< The ray direction in the reference from of the manipulator. - float m_scaleReciprocal; ///< The scale reciprocal (1.0 / scale) of the transform used to move the - ///< ray from world space to local space. AZ::Vector3 m_nonUniformScaleReciprocal; ///< Handles inverting any non-uniform scale which was applied ///< separately from the transform. + float m_scaleReciprocal; ///< The scale reciprocal (1.0 / scale) of the transform used to move the + ///< ray from world space to local space. }; /// Build a ManipulatorInteraction structure from the incoming viewport interaction. @@ -56,11 +47,16 @@ namespace AzToolsFramework const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Vector3& worldRayOrigin, const AZ::Vector3& worldRayDirection); - /// Calculate the offset along an axis to adjust a position - /// to stay snapped to a given grid size. + /// Calculate the offset along an axis to adjust a position to stay snapped to a given grid size. + /// @note This is snap up or down to the nearest grid segment (e.g. 0.2 snaps to 0.0 -> delta 0.2, + /// 0.7 snaps to 1.0 -> delta 0.3). AZ::Vector3 CalculateSnappedOffset( const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, float size); + /// Return the amount to snap from the starting position given the current grid size. + /// @note A movement of more than half size (in either direction) will cause a snap by size. + AZ::Vector3 CalculateSnappedAmount(const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, float size); + /// For a given point on the terrain, calculate the closest xy position snapped to the grid /// (z position is aligned to terrain height, not snapped to z grid) AZ::Vector3 CalculateSnappedTerrainPosition( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp index 566de9a8a6..83c4c28e9a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp @@ -59,17 +59,16 @@ namespace AzToolsFramework const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, const AZStd::vector& fixedAxes, - const AZStd::vector& starterStates, const GridSnapAction& gridSnapAction) + const AZStd::vector& starterStates, const GridSnapParameters& gridSnapParams) { MultiLinearManipulator::Action action; action.m_viewportId = interaction.m_interactionId.m_viewportId; // build up action state for each axis for (size_t fixedIndex = 0; fixedIndex < fixedAxes.size(); ++fixedIndex) { - action.m_actions.push_back( - CalculateLinearManipulationDataAction( - fixedAxes[fixedIndex], starterStates[fixedIndex], worldFromLocal, nonUniformScale, localTransform, - gridSnapAction, interaction)); + action.m_actions.push_back(CalculateLinearManipulationDataAction( + fixedAxes[fixedIndex], starterStates[fixedIndex], worldFromLocal, nonUniformScale, localTransform, gridSnapParams, + interaction)); } return action; @@ -79,8 +78,6 @@ namespace AzToolsFramework const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance) { const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace()); - - const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); const AzFramework::CameraState cameraState = GetCameraState(interaction.m_interactionId.m_viewportId); // build up initial start state for each axis @@ -88,20 +85,19 @@ namespace AzToolsFramework { // note: m_localTransform must not be made uniform as it may contain a local scale we want to snap const auto linearStart = CalculateLinearManipulationDataStart( - fixed, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), - GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction, - rayIntersectionDistance, cameraState); + fixed, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), interaction, rayIntersectionDistance, + cameraState); m_starters.push_back(linearStart); } if (m_onLeftMouseDownCallback) { - const GridSnapAction gridSnapAction = GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()); + const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); // pass action containing all linear actions for each axis to handler m_onLeftMouseDownCallback(BuildMultiLinearManipulatorAction( worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), - interaction, m_fixedAxes, m_starters, gridSnapAction)); + interaction, m_fixedAxes, m_starters, gridSnapParams)); } } @@ -111,11 +107,9 @@ namespace AzToolsFramework { const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace()); const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); - const GridSnapAction gridSnapAction = GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()); - m_onMouseMoveCallback(BuildMultiLinearManipulatorAction( worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), - interaction, m_fixedAxes, m_starters, gridSnapAction)); + interaction, m_fixedAxes, m_starters, gridSnapParams)); } } @@ -125,11 +119,9 @@ namespace AzToolsFramework { const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace()); const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); - const GridSnapAction gridSnapAction = GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()); - m_onLeftMouseUpCallback(BuildMultiLinearManipulatorAction( worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), - interaction, m_fixedAxes, m_starters, gridSnapAction)); + interaction, m_fixedAxes, m_starters, gridSnapParams)); m_starters.clear(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.h index 4a99435008..8e31e02605 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.h @@ -20,8 +20,6 @@ namespace AzToolsFramework { - struct GridSnapAction; - //! MultiLinearManipulator serves as a visual tool for users to modify values //! in one or more dimensions on axes defined in 3D space. class MultiLinearManipulator diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.cpp index abd5414ce3..6eb96f081c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.cpp @@ -22,8 +22,7 @@ namespace AzToolsFramework { PlanarManipulator::StartInternal PlanarManipulator::CalculateManipulationDataStart( - const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction, + const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, const float intersectionDistance) { const ManipulatorInteraction manipulatorInteraction = @@ -31,8 +30,6 @@ namespace AzToolsFramework worldFromLocal, nonUniformScale, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection); const AZ::Vector3 normal = TransformDirectionNoScaling(localTransform, fixed.m_normal); - const AZ::Vector3 axis1 = TransformDirectionNoScaling(localTransform, fixed.m_axis1); - const AZ::Vector3 axis2 = TransformDirectionNoScaling(localTransform, fixed.m_axis2); // initial intersect point const AZ::Vector3 localIntersectionPoint = @@ -43,25 +40,14 @@ namespace AzToolsFramework manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection, localIntersectionPoint, normal, startInternal.m_localHitPosition); - const float scaleRecip = manipulatorInteraction.m_scaleReciprocal; - const float gridSize = gridSnapAction.m_gridSnapParams.m_gridSize; - const bool snapping = gridSnapAction.m_gridSnapParams.m_gridSnap; - - // calculate amount to snap to align with grid - const AZ::Vector3 snapOffset = snapping && !gridSnapAction.m_localSnapping - ? CalculateSnappedOffset(localTransform.GetTranslation(), axis1, gridSize * scaleRecip) + - CalculateSnappedOffset(localTransform.GetTranslation(), axis2, gridSize * scaleRecip) - : AZ::Vector3::CreateZero(); - - startInternal.m_snapOffset = snapOffset; - startInternal.m_localPosition = localTransform.GetTranslation() + snapOffset; + startInternal.m_localPosition = localTransform.GetTranslation(); return startInternal; } PlanarManipulator::Action PlanarManipulator::CalculateManipulationDataAction( - const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal, - const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction, + const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, const GridSnapParameters& gridSnapParams, const ViewportInteraction::MouseInteraction& interaction) { const ManipulatorInteraction manipulatorInteraction = @@ -88,20 +74,18 @@ namespace AzToolsFramework const AZ::Vector3 hitDelta = (localHitPosition - startInternal.m_localHitPosition) / nonUniformScale; const AZ::Vector3 unsnappedOffset = axis1.Dot(hitDelta) * axis1 + axis2.Dot(hitDelta) * axis2; - const float scaleRecip = manipulatorInteraction.m_scaleReciprocal; const AZ::Vector3 nonUniformScaleRecip = manipulatorInteraction.m_nonUniformScaleReciprocal; - const float gridSize = gridSnapAction.m_gridSnapParams.m_gridSize; - const bool snapping = gridSnapAction.m_gridSnapParams.m_gridSnap; + const float scaleRecip = manipulatorInteraction.m_scaleReciprocal; + const float gridSize = gridSnapParams.m_gridSize; + const bool snapping = gridSnapParams.m_gridSnap; Action action; action.m_fixed = fixed; action.m_start.m_localPosition = startInternal.m_localPosition; - action.m_start.m_snapOffset = startInternal.m_snapOffset; action.m_start.m_localHitPosition = startInternal.m_localHitPosition; action.m_current.m_localOffset = snapping - ? unsnappedOffset + - CalculateSnappedOffset(unsnappedOffset, axis1, gridSize * scaleRecip * nonUniformScaleRecip.Dot(axis1)) + - CalculateSnappedOffset(unsnappedOffset, axis2, gridSize * scaleRecip * nonUniformScaleRecip.Dot(axis2)) + ? CalculateSnappedAmount(unsnappedOffset, axis1, gridSize * scaleRecip * nonUniformScaleRecip.Dot(fixed.m_axis1)) + + CalculateSnappedAmount(unsnappedOffset, axis2, gridSize * scaleRecip * nonUniformScaleRecip.Dot(fixed.m_axis2)) : unsnappedOffset; // record what modifier keys are held during this action @@ -141,18 +125,17 @@ namespace AzToolsFramework { const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace()); - const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); - m_startInternal = CalculateManipulationDataStart( m_fixed, worldFromLocalUniformScale, GetNonUniformScale(), TransformNormalizedScale(GetLocalTransform()), - GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction, rayIntersectionDistance); if (m_onLeftMouseDownCallback) { + const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); + m_onLeftMouseDownCallback(CalculateManipulationDataAction( m_fixed, m_startInternal, worldFromLocalUniformScale, GetNonUniformScale(), TransformNormalizedScale(GetLocalTransform()), - GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction)); + gridSnapParams, interaction)); } } @@ -164,8 +147,7 @@ namespace AzToolsFramework m_onMouseMoveCallback(CalculateManipulationDataAction( m_fixed, m_startInternal, TransformUniformScale(GetSpace()), GetNonUniformScale(), - TransformNormalizedScale(GetLocalTransform()), - GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction)); + TransformNormalizedScale(GetLocalTransform()), gridSnapParams, interaction)); } } @@ -177,8 +159,7 @@ namespace AzToolsFramework m_onLeftMouseUpCallback(CalculateManipulationDataAction( m_fixed, m_startInternal, TransformUniformScale(GetSpace()), GetNonUniformScale(), - TransformNormalizedScale(GetLocalTransform()), - GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction)); + TransformNormalizedScale(GetLocalTransform()), gridSnapParams, interaction)); } } @@ -195,8 +176,7 @@ namespace AzToolsFramework const GridSnapParameters gridSnapParams = GridSnapSettings(mouseInteraction.m_interactionId.m_viewportId); const auto action = CalculateManipulationDataAction( m_fixed, m_startInternal, TransformUniformScale(GetSpace()), GetNonUniformScale(), - TransformNormalizedScale(GetLocalTransform()), - GridSnapAction(gridSnapParams, mouseInteraction.m_keyboardModifiers.Alt()), mouseInteraction); + TransformNormalizedScale(GetLocalTransform()), gridSnapParams, mouseInteraction); // display the exact hit (ray intersection) of the mouse pick on the manipulator DrawTransformAxes( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.h index 7a3b2a18a9..154ed4c7d6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.h @@ -21,7 +21,7 @@ namespace AzToolsFramework { class ManipulatorView; - struct GridSnapAction; + struct GridSnapParameters; /// PlanarManipulator serves as a visual tool for users to modify values /// in two dimension in a plane defined two non-collinear axes in 3D space. @@ -58,7 +58,6 @@ namespace AzToolsFramework { AZ::Vector3 m_localPosition; ///< The current position of the manipulator in local space. AZ::Vector3 m_localHitPosition; ///< The intersection point in local space between the ray and the manipulator when the mouse down event happens. - AZ::Vector3 m_snapOffset; ///< The snap offset amount to ensure manipulator is aligned to the grid. }; /// The state of the manipulator during an interaction. @@ -120,7 +119,6 @@ namespace AzToolsFramework { AZ::Vector3 m_localPosition; ///< The starting position of the manipulator in local space. AZ::Vector3 m_localHitPosition; ///< The intersection point in world space between the ray and the manipulator when the mouse down event happens. - AZ::Vector3 m_snapOffset; ///< The snap offset amount to ensure manipulator is aligned to the grid. }; Fixed m_fixed; @@ -134,12 +132,11 @@ namespace AzToolsFramework static StartInternal CalculateManipulationDataStart( const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction, - const ViewportInteraction::MouseInteraction& interaction, float intersectionDistance); + const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, float intersectionDistance); static Action CalculateManipulationDataAction( - const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal, - const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, - const GridSnapAction& gridSnapAction, const ViewportInteraction::MouseInteraction& interaction); + const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, const GridSnapParameters& gridSnapParams, + const ViewportInteraction::MouseInteraction& interaction); }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponentMode.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponentMode.cpp index 497bcf15d7..51c5406812 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponentMode.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponentMode.cpp @@ -37,13 +37,13 @@ namespace AzToolsFramework axisLength, AzFramework::ViewportColors::XAxisColor, AzFramework::ViewportColors::YAxisColor, AzFramework::ViewportColors::ZAxisColor); - auto mouseDownCallback = [this](const LinearManipulator::Action& action) { + auto mouseDownCallback = [this]([[maybe_unused]] const LinearManipulator::Action& action) + { AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); - AZ::NonUniformScaleRequestBus::EventResult( nonUniformScale, m_entityComponentIdPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); - m_initialScale = nonUniformScale + action.m_start.m_scaleSnapOffset; + m_initialScale = nonUniformScale; AZ::NonUniformScaleRequestBus::Event( m_entityComponentIdPair.GetEntityId(), &AZ::NonUniformScaleRequests::SetScale, m_initialScale); @@ -51,29 +51,37 @@ namespace AzToolsFramework m_manipulators->InstallAxisLeftMouseDownCallback(mouseDownCallback); - m_manipulators->InstallAxisMouseMoveCallback([this](const LinearManipulator::Action& action) { - const AZ::Vector3 scaleMultiplier = - (AZ::Vector3::CreateOne() + ((action.LocalScaleOffset() * action.m_start.m_sign) / m_initialScale)); + m_manipulators->InstallAxisMouseMoveCallback( + [this](const LinearManipulator::Action& action) + { + const AZ::Vector3 scaleMultiplier = + (AZ::Vector3::CreateOne() + ((action.LocalScaleOffset() * action.m_start.m_sign) / m_initialScale)); - AZ::NonUniformScaleRequestBus::Event( - m_entityComponentIdPair.GetEntityId(), &AZ::NonUniformScaleRequests::SetScale, - (scaleMultiplier * m_initialScale).GetClamp(AZ::Vector3(AZ::MinTransformScale), AZ::Vector3(AZ::MaxTransformScale))); - }); + AZ::NonUniformScaleRequestBus::Event( + m_entityComponentIdPair.GetEntityId(), &AZ::NonUniformScaleRequests::SetScale, + (scaleMultiplier * m_initialScale) + .GetClamp(AZ::Vector3(AZ::MinTransformScale), AZ::Vector3(AZ::MaxTransformScale))); + }); m_manipulators->InstallUniformLeftMouseDownCallback(mouseDownCallback); - m_manipulators->InstallUniformMouseMoveCallback([this](const LinearManipulator::Action& action) { - const auto sumVectorElements = [](const AZ::Vector3& vec) { return vec.GetX() + vec.GetY() + vec.GetZ(); }; + m_manipulators->InstallUniformMouseMoveCallback( + [this](const LinearManipulator::Action& action) + { + const auto sumVectorElements = [](const AZ::Vector3& vec) + { + return vec.GetX() + vec.GetY() + vec.GetZ(); + }; - const float minScaleMultiplier = AZ::MinTransformScale / m_initialScale.GetMinElement(); - const float maxScaleMultiplier = AZ::MaxTransformScale / m_initialScale.GetMaxElement(); - const float scaleMultiplier = AZ::GetClamp( - 1.0f + sumVectorElements(action.m_start.m_sign * action.LocalScaleOffset() / m_initialScale), minScaleMultiplier, - maxScaleMultiplier); + const float minScaleMultiplier = AZ::MinTransformScale / m_initialScale.GetMinElement(); + const float maxScaleMultiplier = AZ::MaxTransformScale / m_initialScale.GetMaxElement(); + const float scaleMultiplier = AZ::GetClamp( + 1.0f + sumVectorElements(action.m_start.m_sign * action.LocalScaleOffset() / m_initialScale), minScaleMultiplier, + maxScaleMultiplier); - AZ::NonUniformScaleRequestBus::Event( - m_entityComponentIdPair.GetEntityId(), &AZ::NonUniformScaleRequests::SetScale, scaleMultiplier * m_initialScale); - }); + AZ::NonUniformScaleRequestBus::Event( + m_entityComponentIdPair.GetEntityId(), &AZ::NonUniformScaleRequests::SetScale, scaleMultiplier * m_initialScale); + }); } NonUniformScaleComponentMode::~NonUniformScaleComponentMode() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index 5acfa5df59..db321d6818 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -423,15 +423,14 @@ namespace AzToolsFramework } } - static void InitializeTranslationLookup( - EntityIdManipulators& entityIdManipulators, const AZ::Vector3& snapOffset) + static void InitializeTranslationLookup(EntityIdManipulators& entityIdManipulators) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); for (auto& entityIdLookup : entityIdManipulators.m_lookups) { entityIdLookup.second.m_initial = - AZ::Transform::CreateTranslation(GetWorldTranslation(entityIdLookup.first) + snapOffset); + AZ::Transform::CreateTranslation(GetWorldTranslation(entityIdLookup.first)); } } @@ -820,7 +819,7 @@ namespace AzToolsFramework // moving with ctrl - setting override pivotOverrideFrame.m_translationOverride = entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); - InitializeTranslationLookup(entityIdManipulators, -action.LocalPositionOffset()); + InitializeTranslationLookup(entityIdManipulators); } else { @@ -1277,12 +1276,12 @@ namespace AzToolsFramework // linear translationManipulators->InstallLinearManipulatorMouseDownCallback( - [this, manipulatorEntityIds](const LinearManipulator::Action& action) mutable + [this, manipulatorEntityIds]([[maybe_unused]] const LinearManipulator::Action& action) mutable { // important to sort entityIds based on hierarchy order when updating transforms BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds->m_entityIds); - InitializeTranslationLookup(m_entityIdManipulators, action.m_start.m_positionSnapOffset); + InitializeTranslationLookup(m_entityIdManipulators); m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); m_axisPreview.m_orientation = QuaternionFromTransformNoScaling( @@ -1302,19 +1301,19 @@ namespace AzToolsFramework }); translationManipulators->InstallLinearManipulatorMouseUpCallback( - [this](const LinearManipulator::Action& /*action*/) mutable + [this]([[maybe_unused]] const LinearManipulator::Action& action) mutable { EndRecordManipulatorCommand(); }); // planar translationManipulators->InstallPlanarManipulatorMouseDownCallback( - [this, manipulatorEntityIds](const PlanarManipulator::Action& action) + [this, manipulatorEntityIds]([[maybe_unused]] const PlanarManipulator::Action& action) { // important to sort entityIds based on hierarchy order when updating transforms BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds->m_entityIds); - InitializeTranslationLookup(m_entityIdManipulators, action.m_start.m_snapOffset); + InitializeTranslationLookup(m_entityIdManipulators); m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); m_axisPreview.m_orientation = QuaternionFromTransformNoScaling( @@ -1340,11 +1339,11 @@ namespace AzToolsFramework // surface translationManipulators->InstallSurfaceManipulatorMouseDownCallback( - [this, manipulatorEntityIds](const SurfaceManipulator::Action& action) + [this, manipulatorEntityIds]([[maybe_unused]] const SurfaceManipulator::Action& action) { BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds->m_entityIds); - InitializeTranslationLookup(m_entityIdManipulators, action.m_start.m_snapOffset); + InitializeTranslationLookup(m_entityIdManipulators); m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); m_axisPreview.m_orientation = QuaternionFromTransformNoScaling( @@ -3326,26 +3325,16 @@ namespace AzToolsFramework } static void DrawManipulatorGrid( - AzFramework::DebugDisplayRequests& debugDisplay, const EntityIdManipulators& entityIdManipulators, - const float gridSize, const float localSnapping) + AzFramework::DebugDisplayRequests& debugDisplay, const EntityIdManipulators& entityIdManipulators, const float gridSize) { const AZ::Matrix3x3 orientation = AZ::Matrix3x3::CreateFromTransform(entityIdManipulators.m_manipulators->GetLocalTransform()); - const AZ::Vector3 unsnappedTranslation = + const AZ::Vector3 translation = entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); - // calculate the offset to snap by to align the manipulator to the grid - // note: only perform this if we are not snapping in local space - const AZ::Vector3 snappedOffset = !localSnapping - ? CalculateSnappedOffset(unsnappedTranslation, orientation.GetBasisX(), gridSize) + - CalculateSnappedOffset(unsnappedTranslation, orientation.GetBasisY(), gridSize) - : AZ::Vector3::CreateZero(); - - const AZ::Vector3 snappedTranslation = unsnappedTranslation + snappedOffset; - DrawSnappingGrid( - debugDisplay, AZ::Transform::CreateFromMatrix3x3AndTranslation(orientation, snappedTranslation), + debugDisplay, AZ::Transform::CreateFromMatrix3x3AndTranslation(orientation, translation), gridSize); } @@ -3484,7 +3473,7 @@ namespace AzToolsFramework const GridSnapParameters gridSnapParams = GridSnapSettings(viewportInfo.m_viewportId); if (gridSnapParams.m_gridSnap && m_entityIdManipulators.m_manipulators) { - DrawManipulatorGrid(debugDisplay, m_entityIdManipulators, gridSnapParams.m_gridSize, modifiers.Alt()); + DrawManipulatorGrid(debugDisplay, m_entityIdManipulators, gridSnapParams.m_gridSize); } } } From b73de269ee5e271b0854b6ce30b54d2c839b1433 Mon Sep 17 00:00:00 2001 From: Aaron Ruiz Mora Date: Fri, 4 Jun 2021 15:24:22 +0100 Subject: [PATCH 508/811] Use '' instead of 'Default' in Material Selection widget. (#1140) --- Gems/PhysX/Code/Editor/MaterialIdWidget.cpp | 28 +++++++++++---------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/Gems/PhysX/Code/Editor/MaterialIdWidget.cpp b/Gems/PhysX/Code/Editor/MaterialIdWidget.cpp index 9ec438101a..44787ddd20 100644 --- a/Gems/PhysX/Code/Editor/MaterialIdWidget.cpp +++ b/Gems/PhysX/Code/Editor/MaterialIdWidget.cpp @@ -19,6 +19,8 @@ namespace PhysX { namespace Editor { + static const char* const DefaultPhysicsMaterialLabel = ""; + AZ::u32 MaterialIdWidget::GetHandlerName() const { return Physics::Edit::MaterialIdSelector; @@ -72,8 +74,7 @@ namespace PhysX auto lockToDefault = [gui]() { - static const char* defaultLabel = "Default"; - gui->addItem(defaultLabel); + gui->addItem(DefaultPhysicsMaterialLabel); gui->setCurrentIndex(0); return false; }; @@ -83,30 +84,31 @@ namespace PhysX return lockToDefault(); } - auto materialAsset = AZ::Data::AssetManager::Instance().GetAsset(m_materialLibraryId, AZ::Data::AssetLoadBehavior::Default); - materialAsset.BlockUntilLoadComplete(); + auto materialLibraryAsset = AZ::Data::AssetManager::Instance().GetAsset(m_materialLibraryId, AZ::Data::AssetLoadBehavior::Default); + materialLibraryAsset.BlockUntilLoadComplete(); - if (materialAsset.Get() == nullptr) + if (materialLibraryAsset.Get() == nullptr) { return lockToDefault(); } - const auto& materialsData = materialAsset.Get()->GetMaterialsData(); + const auto& materials = materialLibraryAsset.Get()->GetMaterialsData(); - if (materialsData.size() == 0) + if (materials.empty()) { return lockToDefault(); } - m_libraryIds.reserve(materialsData.size()); + m_libraryIds.reserve(materials.size() + 1); // Plus one to reserve the first element for default physics material + // Add default physics material first m_libraryIds.push_back(Physics::MaterialId()); - gui->addItem("Default"); + gui->addItem(DefaultPhysicsMaterialLabel); - for (const auto& materialData : materialAsset.Get()->GetMaterialsData()) + for (const auto& material : materials) { - gui->addItem(materialData.m_configuration.m_surfaceType.c_str()); - m_libraryIds.push_back(materialData.m_id); + gui->addItem(material.m_configuration.m_surfaceType.c_str()); + m_libraryIds.push_back(material.m_id); } gui->setCurrentIndex(GetIndexForId(instance)); @@ -116,7 +118,7 @@ namespace PhysX Physics::MaterialId MaterialIdWidget::GetIdForIndex(size_t index) { - if (m_libraryIds.size() <= index) + if (index >= m_libraryIds.size()) { return Physics::MaterialId(); } From 0f90ccc0b4e78b57a07001a94f8ef219dac3fb7e Mon Sep 17 00:00:00 2001 From: antonmic Date: Fri, 4 Jun 2021 09:38:28 -0700 Subject: [PATCH 509/811] initial changes compiling --- .../DisplayMapperFullScreenPass.h | 2 +- .../Feature/DisplayMapper/DisplayMapperPass.h | 2 +- .../Atom/Feature/LuxCore/LuxCoreTexturePass.h | 2 +- .../Atom/Feature/LuxCore/RenderTexturePass.h | 2 +- .../CheckerboardColorResolvePass.cpp | 6 +- .../CheckerboardColorResolvePass.h | 2 +- .../Source/Checkerboard/CheckerboardPass.cpp | 4 +- .../Source/Checkerboard/CheckerboardPass.h | 2 +- .../CoreLights/CascadedShadowmapsPass.cpp | 8 +- .../CoreLights/CascadedShadowmapsPass.h | 2 +- .../DirectionalLightFeatureProcessor.cpp | 2 +- .../Source/CoreLights/LightCullingPass.cpp | 3 +- .../Code/Source/CoreLights/LightCullingPass.h | 3 +- .../Source/CoreLights/LightCullingRemap.cpp | 2 +- .../Source/CoreLights/LightCullingRemap.h | 2 +- .../LightCullingTilePreparePass.cpp | 25 ++-- .../CoreLights/LightCullingTilePreparePass.h | 3 +- .../CoreLights/ProjectedShadowmapsPass.cpp | 6 +- .../CoreLights/ProjectedShadowmapsPass.h | 2 +- .../Code/Source/CoreLights/ShadowmapPass.cpp | 4 +- .../Code/Source/CoreLights/ShadowmapPass.h | 2 +- .../DisplayMapperFullScreenPass.cpp | 2 +- .../DisplayMapper/DisplayMapperPass.cpp | 6 +- .../Common/Code/Source/ImGui/ImGuiPass.cpp | 4 +- .../Common/Code/Source/ImGui/ImGuiPass.h | 2 +- .../Source/LuxCore/LuxCoreTexturePass.cpp | 6 +- .../Code/Source/LuxCore/RenderTexturePass.cpp | 6 +- .../MorphTargets/MorphTargetComputePass.cpp | 2 +- .../MorphTargets/MorphTargetComputePass.h | 2 +- .../Source/PostProcessing/BloomBlurPass.cpp | 4 +- .../Source/PostProcessing/BloomBlurPass.h | 2 +- .../PostProcessing/BloomCompositePass.cpp | 4 +- .../PostProcessing/BloomCompositePass.h | 2 +- .../PostProcessing/BloomDownsamplePass.cpp | 4 +- .../PostProcessing/BloomDownsamplePass.h | 2 +- .../DepthOfFieldCopyFocusDepthToCpuPass.cpp | 2 +- .../DepthOfFieldCopyFocusDepthToCpuPass.h | 2 +- ...DepthOfFieldWriteFocusDepthFromGpuPass.cpp | 4 +- .../DepthOfFieldWriteFocusDepthFromGpuPass.h | 2 +- .../PostProcessing/EyeAdaptationPass.cpp | 2 +- .../Source/PostProcessing/EyeAdaptationPass.h | 2 +- .../LookModificationTransformPass.cpp | 4 +- .../LookModificationTransformPass.h | 2 +- .../LuminanceHistogramGeneratorPass.cpp | 2 +- .../LuminanceHistogramGeneratorPass.h | 2 +- .../Code/Source/PostProcessing/SsaoPasses.cpp | 4 +- .../Code/Source/PostProcessing/SsaoPasses.h | 2 +- .../RayTracingAccelerationStructurePass.cpp | 2 +- .../RayTracingAccelerationStructurePass.h | 2 +- .../ReflectionCopyFrameBufferPass.cpp | 4 +- .../ReflectionCopyFrameBufferPass.h | 2 +- .../ReflectionScreenSpaceBlurPass.cpp | 6 +- .../ReflectionScreenSpaceBlurPass.h | 2 +- .../ProjectedShadowFeatureProcessor.cpp | 2 +- .../Include/Atom/RPI.Public/Pass/CopyPass.h | 2 +- .../Atom/RPI.Public/Pass/MSAAResolvePass.h | 2 +- .../Include/Atom/RPI.Public/Pass/ParentPass.h | 5 +- .../Code/Include/Atom/RPI.Public/Pass/Pass.h | 50 ++++---- .../Atom/RPI.Public/Pass/PassDefines.h | 25 ++++ .../Include/Atom/RPI.Public/Pass/PassSystem.h | 21 ++-- .../RPI.Public/Pass/PassSystemInterface.h | 24 +++- .../Include/Atom/RPI.Public/Pass/RenderPass.h | 2 +- .../Pass/Specific/DownsampleMipChainPass.h | 2 +- .../Pass/Specific/EnvironmentCubeMapPass.h | 2 +- .../Pass/Specific/RenderToTexturePass.h | 2 +- .../RPI.Public/Pass/Specific/SelectorPass.h | 2 +- .../RPI.Public/Pass/Specific/SwapChainPass.h | 2 +- .../Code/Source/RPI.Public/Pass/CopyPass.cpp | 2 +- .../RPI.Public/Pass/MSAAResolvePass.cpp | 2 +- .../Source/RPI.Public/Pass/ParentPass.cpp | 25 ++-- .../RPI/Code/Source/RPI.Public/Pass/Pass.cpp | 107 +++++++++++------- .../Source/RPI.Public/Pass/PassSystem.cpp | 89 +++++++++++---- .../Source/RPI.Public/Pass/RenderPass.cpp | 2 +- .../Pass/Specific/DownsampleMipChainPass.cpp | 4 +- .../Pass/Specific/EnvironmentCubeMapPass.cpp | 6 +- .../Pass/Specific/RenderToTexturePass.cpp | 6 +- .../RPI.Public/Pass/Specific/SelectorPass.cpp | 6 +- .../Pass/Specific/SwapChainPass.cpp | 8 +- .../Code/Source/RPI.Public/RenderPipeline.cpp | 3 +- Gems/Atom/RPI/Code/Tests/Pass/PassTests.cpp | 14 +-- 80 files changed, 361 insertions(+), 238 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperFullScreenPass.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperFullScreenPass.h index 94e52d41b0..23c4cd1a0a 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperFullScreenPass.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperFullScreenPass.h @@ -42,7 +42,7 @@ namespace AZ void SetInputReferenceAttachmentName(const Name& attachmentName); // Pass behavior overrides - virtual void BuildAttachmentsInternal() override; + virtual void BuildInternal() override; protected: explicit DisplayMapperFullScreenPass(const RPI::PassDescriptor& descriptor); diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperPass.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperPass.h index 67d9eae9ae..15ada4dd94 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperPass.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperPass.h @@ -76,7 +76,7 @@ namespace AZ DisplayMapperPass(const RPI::PassDescriptor& descriptor); // Pass behavior overrides - void BuildAttachmentsInternal() final; + void BuildInternal() final; void FrameBeginInternal(FramePrepareParams params) final; void FrameEndInternal() final; void CreateChildPassesInternal() final; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/LuxCore/LuxCoreTexturePass.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/LuxCore/LuxCoreTexturePass.h index 23e9c220b2..2ad2af3efd 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/LuxCore/LuxCoreTexturePass.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/LuxCore/LuxCoreTexturePass.h @@ -42,7 +42,7 @@ namespace AZ protected: // Pass behavior overrides void CreateChildPassesInternal() final; - void BuildAttachmentsInternal() final; + void BuildInternal() final; void FrameBeginInternal(FramePrepareParams params) final; private: diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/LuxCore/RenderTexturePass.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/LuxCore/RenderTexturePass.h index 5ae5008a92..cd148d3452 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/LuxCore/RenderTexturePass.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/LuxCore/RenderTexturePass.h @@ -46,7 +46,7 @@ namespace AZ private: - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; void UpdataAttachment(); diff --git a/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardColorResolvePass.cpp b/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardColorResolvePass.cpp index 3ebb6b370c..a6c440cf39 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardColorResolvePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardColorResolvePass.cpp @@ -60,7 +60,7 @@ namespace AZ Base::FrameBeginInternal(params); } - void CheckerboardColorResolvePass::BuildAttachmentsInternal() + void CheckerboardColorResolvePass::BuildInternal() { // For each bound attachments they are the inputs from current frame. // We use them to get their owner CheckerboardPass then find the render targets from last frame @@ -99,7 +99,7 @@ namespace AZ // reset frame offset to 0 since attachments are rebuilt m_frameOffset = 0; - Base::BuildAttachmentsInternal(); + Base::BuildInternal(); } void CheckerboardColorResolvePass::CompileResources(const RHI::FrameGraphCompileContext& context) @@ -135,7 +135,7 @@ namespace AZ void CheckerboardColorResolvePass::FrameEndInternal() { // For the input slots for current frame, they always get updated when CheckerboardPass updates the render targets - // But for the input slots for previous frame, we need to manually update them since they were manually attached in BuildAttachmentsInternal() + // But for the input slots for previous frame, we need to manually update them since they were manually attached in BuildInternal() // // When pass attachment was built, CheckerboardPass creates two resources for each render target. // For example, diffuse_0 and diffuse_1 which diffuse_0 is for even frame and diffuse_1 is for odd frame. diff --git a/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardColorResolvePass.h b/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardColorResolvePass.h index 8cb15d5f49..93930e2bbc 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardColorResolvePass.h +++ b/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardColorResolvePass.h @@ -52,7 +52,7 @@ namespace AZ protected: // Pass overrides... void FrameBeginInternal(FramePrepareParams params) override; - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameEndInternal() override; // Scope producer functions... diff --git a/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardPass.cpp b/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardPass.cpp index 09c69dfe18..a781c460f5 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardPass.cpp @@ -50,7 +50,7 @@ namespace AZ Base::FrameBeginInternal(params); } - void CheckerboardPass::BuildAttachmentsInternal() + void CheckerboardPass::BuildInternal() { Data::Instance pool = RPI::ImageSystemInterface::Get()->GetSystemAttachmentPool(); @@ -101,7 +101,7 @@ namespace AZ // reset frame offset to 0 since attachments are rebuilt m_frameOffset = 0; - Base::BuildAttachmentsInternal(); + Base::BuildInternal(); } diff --git a/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardPass.h b/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardPass.h index 3b905cc3db..02429bb837 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/Checkerboard/CheckerboardPass.h @@ -40,7 +40,7 @@ namespace AZ protected: // Pass overrides... void FrameBeginInternal(FramePrepareParams params); - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameEndInternal() override; private: diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.cpp index d83201533c..4c7e69f2ae 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.cpp @@ -100,7 +100,7 @@ namespace AZ m_arraySize = arraySize; m_updateChildren = true; - QueueForBuildAttachments(); + QueueForBuild(); m_atlas.Initialize(); for (size_t cascadeIndex = 0; cascadeIndex < m_arraySize; ++cascadeIndex) @@ -149,7 +149,7 @@ namespace AZ return m_atlas; } - void CascadedShadowmapsPass::BuildAttachmentsInternal() + void CascadedShadowmapsPass::BuildInternal() { UpdateChildren(); @@ -159,7 +159,7 @@ namespace AZ } UpdateShadowmapImageSize(); - Base::BuildAttachmentsInternal(); + Base::BuildInternal(); } void CascadedShadowmapsPass::GetPipelineViewTags(RPI::SortedPipelineViewTags& outTags) const @@ -215,7 +215,7 @@ namespace AZ AZ_RPI_PASS_WARNING(child, "CascadedShadowmapsPass child Pass creation failed for %d", cascadeIndex); if (child) { - child->QueueForBuildAttachments(); + child->QueueForBuild(); AddChild(child); } } diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.h index aa95e0af44..772be9466d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.h @@ -53,7 +53,7 @@ namespace AZ explicit CascadedShadowmapsPass(const RPI::PassDescriptor& descriptor); // RPI::Pass overrides... - void BuildAttachmentsInternal() override; + void BuildInternal() override; void GetPipelineViewTags(RPI::SortedPipelineViewTags& outTags) const override; void GetViewDrawListInfo(RHI::DrawListMask& outDrawListMask, RPI::PassesByDrawList& outPassesByDrawList, const RPI::PipelineViewTag& viewTag) const override; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp index 9b40097716..cdbe431949 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp @@ -1106,7 +1106,7 @@ namespace AZ { for (EsmShadowmapsPass* pass : it.second) { - pass->QueueForBuildAttachments(); + pass->QueueForBuild(); } } } diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp index 987ed299b3..88a063b499 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp @@ -163,7 +163,6 @@ namespace AZ void LightCullingPass::ResetInternal() { - m_initialized = false; m_tileDataIndex = -1; m_constantDataIndex.Reset(); @@ -260,7 +259,7 @@ namespace AZ return gridPixelSize; } - void LightCullingPass::BuildAttachmentsInternal() + void LightCullingPass::BuildInternal() { m_tileDataIndex = FindInputBinding(AZ::Name("TileLightData")); CreateLightList(); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.h index d8699ea0c7..8080379716 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.h @@ -50,7 +50,7 @@ namespace AZ // Pass behavior overrides... void ResetInternal()override; - void BuildAttachmentsInternal() override; + void BuildInternal() override; // Scope producer functions... void CompileResources(const RHI::FrameGraphCompileContext& context) override; @@ -96,7 +96,6 @@ namespace AZ AZ::RHI::ShaderInputNameIndex m_constantDataIndex = "m_constantData"; - bool m_initialized = false; Data::Instance m_lightList; uint32_t m_tileDataIndex = -1; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp index 42882cec6e..a12ba48751 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp @@ -108,7 +108,7 @@ namespace AZ return -1; } - void LightCullingRemap::BuildAttachmentsInternal() + void LightCullingRemap::BuildInternal() { m_tileDataIndex = FindInputOutputBinding(AZ::Name("TileLightData")); m_tileDim = GetTileDataBufferResolution(); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.h index 0738acd459..6d60f93a64 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.h @@ -55,7 +55,7 @@ namespace AZ // Pass behavior overrides... void ResetInternal()override; - void BuildAttachmentsInternal() override; + void BuildInternal() override; // RHI::ScopeProducer overrides... void SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) override; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.cpp index 816ef25bc6..c144525cec 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.cpp @@ -167,37 +167,36 @@ namespace AZ AZ_Assert(setOk, "LightCullingTilePreparePass::SetConstantData() - could not set constant data"); } - void LightCullingTilePreparePass::BuildAttachmentsInternal() + void LightCullingTilePreparePass::BuildInternal() { ChooseShaderVariant(); } - void LightCullingTilePreparePass::OnShaderReinitialized(const AZ::RPI::Shader&) + void LightCullingTilePreparePass::OnShaderReloaded() { LoadShader(); - if (!m_flags.m_queuedForBuildAttachment && !m_flags.m_isBuildingAttachments) + AZ_Assert(GetPassState() != RPI::PassState::Rendering, "LightCullingTilePreparePass: Trying to reload shader during rendering"); + if (GetPassState() == RPI::PassState::Initialized) { ChooseShaderVariant(); } } + + void LightCullingTilePreparePass::OnShaderReinitialized(const AZ::RPI::Shader&) + { + OnShaderReloaded(); + } + void LightCullingTilePreparePass::OnShaderAssetReinitialized(const Data::Asset&) { - LoadShader(); - if (!m_flags.m_queuedForBuildAttachment && !m_flags.m_isBuildingAttachments) - { - ChooseShaderVariant(); - } + OnShaderReloaded(); } void LightCullingTilePreparePass::OnShaderVariantReinitialized( const AZ::RPI::Shader&, const AZ::RPI::ShaderVariantId&, AZ::RPI::ShaderVariantStableId) { - LoadShader(); - if (!m_flags.m_queuedForBuildAttachment && !m_flags.m_isBuildingAttachments) - { - ChooseShaderVariant(); - } + OnShaderReloaded(); } } // namespace Render diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.h index efba105912..0febb66e3d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.h @@ -50,7 +50,7 @@ namespace AZ LightCullingTilePreparePass(const RPI::PassDescriptor& descriptor); // Pass behavior overrides... - void BuildAttachmentsInternal() override; + void BuildInternal() override; /////////////////////////////////////////////////////////////////// // ShaderReloadNotificationBus overrides... @@ -73,6 +73,7 @@ namespace AZ const AZ::RPI::ShaderVariant& CreateShaderVariant(); void CreatePipelineStateFromShaderVariant(const RPI::ShaderVariant& shaderVariant); void SetConstantData(); + void OnShaderReloaded(); AZ::RHI::ShaderInputNameIndex m_constantDataIndex = "m_constantData"; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.cpp index d77419fe8f..87cacbb345 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.cpp @@ -73,7 +73,7 @@ namespace AZ { m_sizes = sizes; m_updateChildren = true; - QueueForBuildAttachments(); + QueueForBuild(); m_atlas.Initialize(); for (const auto& it : m_sizes) @@ -156,7 +156,7 @@ namespace AZ return m_atlas; } - void ProjectedShadowmapsPass::BuildAttachmentsInternal() + void ProjectedShadowmapsPass::BuildInternal() { UpdateChildren(); @@ -177,7 +177,7 @@ namespace AZ imageDescriptor.m_size = RHI::Size(shadowmapWidth, shadowmapWidth, 1); imageDescriptor.m_arraySize = m_atlas.GetArraySliceCount(); - Base::BuildAttachmentsInternal(); + Base::BuildInternal(); } void ProjectedShadowmapsPass::GetPipelineViewTags(RPI::SortedPipelineViewTags& outTags) const diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.h index 63640d22c6..f1963cc885 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.h @@ -71,7 +71,7 @@ namespace AZ explicit ProjectedShadowmapsPass(const RPI::PassDescriptor& descriptor); // RPI::Pass overrides... - void BuildAttachmentsInternal() override; + void BuildInternal() override; void GetPipelineViewTags(RPI::SortedPipelineViewTags& outTags) const override; void GetViewDrawListInfo(RHI::DrawListMask& outDrawListMask, RPI::PassesByDrawList& outPassesByDrawList, const RPI::PipelineViewTag& viewTag) const override; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapPass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapPass.cpp index 087a73a94d..d31947da5a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapPass.cpp @@ -107,7 +107,7 @@ namespace AZ m_scissorState = scissor; } - void ShadowmapPass::BuildAttachmentsInternal() + void ShadowmapPass::BuildInternal() { RPI::Ptr parentPass = GetParent(); if (!parentPass) @@ -135,7 +135,7 @@ namespace AZ action.m_loadAction = m_clearEnabled ? RHI::AttachmentLoadAction::Clear : RHI::AttachmentLoadAction::DontCare; binding.m_unifiedScopeDesc = RHI::UnifiedScopeAttachmentDescriptor(attachmentId, imageViewDescriptor, action); - Base::BuildAttachmentsInternal(); + Base::BuildInternal(); } } // namespace Render diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapPass.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapPass.h index 9c308dc4df..2814761a69 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapPass.h @@ -58,7 +58,7 @@ namespace AZ explicit ShadowmapPass(const RPI::PassDescriptor& descriptor); // RHI::Pass overrides... - void BuildAttachmentsInternal() override; + void BuildInternal() override; uint16_t m_arraySlice = 0; bool m_clearEnabled = true; diff --git a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperFullScreenPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperFullScreenPass.cpp index ba83fabed3..096179d5b6 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperFullScreenPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperFullScreenPass.cpp @@ -34,7 +34,7 @@ namespace AZ { } - void DisplayMapperFullScreenPass::BuildAttachmentsInternal() + void DisplayMapperFullScreenPass::BuildInternal() { RPI::PassConnection inConnection; inConnection.m_localSlot = InputAttachmentName; diff --git a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp index 8ae790e12c..be3e05163a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp @@ -46,8 +46,6 @@ namespace AZ DisplayMapperPass::DisplayMapperPass(const RPI::PassDescriptor& descriptor) : RPI::ParentPass(descriptor) { - m_flags.m_alreadyCreated = false; - AzFramework::NativeWindowHandle windowHandle = nullptr; AzFramework::WindowSystemRequestBus::BroadcastResult( windowHandle, @@ -137,7 +135,7 @@ namespace AZ } } - void DisplayMapperPass::BuildAttachmentsInternal() + void DisplayMapperPass::BuildInternal() { const Name outputName = Name{ "Output" }; Name inputPass = Name{ "Parent" }; @@ -187,7 +185,7 @@ namespace AZ m_swapChainAttachmentBinding = FindAttachmentBinding(Name("SwapChainOutput")); - ParentPass::BuildAttachmentsInternal(); + ParentPass::BuildInternal(); } void DisplayMapperPass::FrameBeginInternal(FramePrepareParams params) diff --git a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp index a29354f723..fe5d9a16fe 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp @@ -519,13 +519,13 @@ namespace AZ io.Fonts->TexID = reinterpret_cast(m_fontAtlas.get()); } - void ImGuiPass::OnBuildAttachmentsFinishedInternal() + void ImGuiPass::OnBuildFinishedInternal() { // Set output format and finalize pipeline state m_pipelineState->SetOutputFromPass(this); m_pipelineState->Finalize(); - Base::OnBuildAttachmentsFinishedInternal(); + Base::OnBuildFinishedInternal(); } void ImGuiPass::SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) diff --git a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h index c8be0d7ee6..30449820bb 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h @@ -94,7 +94,7 @@ namespace AZ explicit ImGuiPass(const RPI::PassDescriptor& descriptor); // Pass Behaviour Overrides... - void OnBuildAttachmentsFinishedInternal() override; + void OnBuildFinishedInternal() override; void FrameBeginInternal(FramePrepareParams params) override; // Scope producer functions diff --git a/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp b/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp index 9a921205ab..3c7233e747 100644 --- a/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp @@ -28,8 +28,6 @@ namespace AZ LuxCoreTexturePass::LuxCoreTexturePass(const RPI::PassDescriptor& descriptor) : ParentPass(descriptor) { - m_flags.m_alreadyCreated = false; - RPI::PassSystemInterface* passSystem = RPI::PassSystemInterface::Get(); // Create render target pass @@ -61,9 +59,9 @@ namespace AZ AddChild(m_renderTargetPass); } - void LuxCoreTexturePass::BuildAttachmentsInternal() + void LuxCoreTexturePass::BuildInternal() { - ParentPass::BuildAttachmentsInternal(); + ParentPass::BuildInternal(); } void LuxCoreTexturePass::FrameBeginInternal(FramePrepareParams params) diff --git a/Gems/Atom/Feature/Common/Code/Source/LuxCore/RenderTexturePass.cpp b/Gems/Atom/Feature/Common/Code/Source/LuxCore/RenderTexturePass.cpp index 0782e12278..aa991e270a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/LuxCore/RenderTexturePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/LuxCore/RenderTexturePass.cpp @@ -38,13 +38,13 @@ namespace AZ m_attachmentSize = image->GetRHIImage()->GetDescriptor().m_size; m_attachmentFormat = format; m_shaderResourceGroup->SetImage(m_textureIndex, image); - QueueForBuildAttachments(); + QueueForBuild(); } - void RenderTexturePass::BuildAttachmentsInternal() + void RenderTexturePass::BuildInternal() { UpdataAttachment(); - FullscreenTrianglePass::BuildAttachmentsInternal(); + FullscreenTrianglePass::BuildInternal(); } void RenderTexturePass::FrameBeginInternal(FramePrepareParams params) diff --git a/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetComputePass.cpp b/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetComputePass.cpp index 1bb537ecef..42acd5c447 100644 --- a/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetComputePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetComputePass.cpp @@ -44,7 +44,7 @@ namespace AZ m_skinnedMeshFeatureProcessor = skinnedMeshFeatureProcessor; } - void MorphTargetComputePass::BuildAttachmentsInternal() + void MorphTargetComputePass::BuildInternal() { // The same buffer that skinning writes to is used to manage the computed vertex deltas that are passed from the // morph target pass to the skinning pass. This simplifies things by only requiring one class to manage the memory diff --git a/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetComputePass.h b/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetComputePass.h index 61fa485fbc..d346edd908 100644 --- a/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetComputePass.h +++ b/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetComputePass.h @@ -37,7 +37,7 @@ namespace AZ void SetFeatureProcessor(SkinnedMeshFeatureProcessor* m_skinnedMeshFeatureProcessor); private: - void BuildAttachmentsInternal() override; + void BuildInternal() override; void BuildCommandListInternal(const RHI::FrameGraphExecuteContext& context) override; SkinnedMeshFeatureProcessor* m_skinnedMeshFeatureProcessor = nullptr; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.cpp index 1427adeb08..af95a76718 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.cpp @@ -252,10 +252,10 @@ namespace AZ } } - void BloomBlurPass::BuildAttachmentsInternal() + void BloomBlurPass::BuildInternal() { BuildChildPasses(); - ParentPass::BuildAttachmentsInternal(); + ParentPass::BuildInternal(); } void BloomBlurPass::FrameBeginInternal(FramePrepareParams params) diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.h index e87d831382..4c65368506 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.h @@ -47,7 +47,7 @@ namespace AZ BloomBlurPass(const RPI::PassDescriptor& descriptor); // Pass behaviour overrides... - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; void GetInputInfo(); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.cpp index fbb020cbf3..810353aab1 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.cpp @@ -56,10 +56,10 @@ namespace AZ m_passData = *passData; } - void BloomCompositePass::BuildAttachmentsInternal() + void BloomCompositePass::BuildInternal() { BuildChildPasses(); - ParentPass::BuildAttachmentsInternal(); + ParentPass::BuildInternal(); } void BloomCompositePass::FrameBeginInternal(FramePrepareParams params) diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.h index 86d897ae7d..a19947e1d0 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.h @@ -44,7 +44,7 @@ namespace AZ BloomCompositePass(const RPI::PassDescriptor& descriptor); // Pass behaviour overrides... - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; void GetAttachmentInfo(); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.cpp index 647177a1ce..63779beb16 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.cpp @@ -74,10 +74,10 @@ namespace AZ AddAttachmentBinding(outBinding); } - ComputePass::BuildAttachmentsInternal(); + ComputePass::BuildInternal(); } - void BloomDownsamplePass::BuildAttachmentsInternal() + void BloomDownsamplePass::BuildInternal() { BuildOutAttachmentBinding(); } diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.h index 824f703417..3eb0ac8740 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.h @@ -37,7 +37,7 @@ namespace AZ BloomDownsamplePass(const RPI::PassDescriptor& descriptor); // Pass Behaviour Overrides... - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; void BuildOutAttachmentBinding(); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldCopyFocusDepthToCpuPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldCopyFocusDepthToCpuPass.cpp index d64bba1957..00d5ad93c3 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldCopyFocusDepthToCpuPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldCopyFocusDepthToCpuPass.cpp @@ -52,7 +52,7 @@ namespace AZ return depth; } - void DepthOfFieldCopyFocusDepthToCpuPass::BuildAttachmentsInternal() + void DepthOfFieldCopyFocusDepthToCpuPass::BuildInternal() { SetScopeId(RHI::ScopeId(GetPathName())); } diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldCopyFocusDepthToCpuPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldCopyFocusDepthToCpuPass.h index 64301b6e0c..7e8d041e96 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldCopyFocusDepthToCpuPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldCopyFocusDepthToCpuPass.h @@ -48,7 +48,7 @@ namespace AZ void BuildCommandList(const RHI::FrameGraphExecuteContext& context) override; // Pass overrides - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; RPI::Ptr m_bufferRef; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldWriteFocusDepthFromGpuPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldWriteFocusDepthFromGpuPass.cpp index e7ac891198..4aaf936426 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldWriteFocusDepthFromGpuPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldWriteFocusDepthFromGpuPass.cpp @@ -62,9 +62,9 @@ namespace AZ m_bufferRef = bufferRef; } - void DepthOfFieldWriteFocusDepthFromGpuPass::BuildAttachmentsInternal() + void DepthOfFieldWriteFocusDepthFromGpuPass::BuildInternal() { - AZ_Assert(m_bufferRef != nullptr, "%s has a null buffer when calling BuildAttachmentsInternal.", GetPathName().GetCStr()); + AZ_Assert(m_bufferRef != nullptr, "%s has a null buffer when calling BuildInternal.", GetPathName().GetCStr()); AttachBufferToSlot(Name("DofDepthInputOutput"), m_bufferRef); } diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldWriteFocusDepthFromGpuPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldWriteFocusDepthFromGpuPass.h index 592ab64c01..881ef9df94 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldWriteFocusDepthFromGpuPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldWriteFocusDepthFromGpuPass.h @@ -51,7 +51,7 @@ namespace AZ void CompileResources(const RHI::FrameGraphCompileContext& context) override; // Pass overrides - void BuildAttachmentsInternal() override; + void BuildInternal() override; }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.cpp index e7d4c47f02..879abf6418 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.cpp @@ -62,7 +62,7 @@ namespace AZ m_buffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); } - void EyeAdaptationPass::BuildAttachmentsInternal() + void EyeAdaptationPass::BuildInternal() { if (!m_buffer) { diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.h index cef168a122..d53569a9f9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.h @@ -58,7 +58,7 @@ namespace AZ float m_exposureValue = 1.0f; }; - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.cpp index 98c842042b..9f792370fc 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.cpp @@ -36,10 +36,10 @@ namespace AZ &AzFramework::WindowSystemRequestBus::Events::GetDefaultWindowHandle); } - void LookModificationPass::BuildAttachmentsInternal() + void LookModificationPass::BuildInternal() { m_swapChainAttachmentBinding = FindAttachmentBinding(Name("SwapChainOutput")); - ParentPass::BuildAttachmentsInternal(); + ParentPass::BuildInternal(); } void LookModificationPass::FrameBeginInternal([[maybe_unused]] FramePrepareParams params) diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.h index 5102015e82..8203530918 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.h @@ -52,7 +52,7 @@ namespace AZ //! Pass overrides ... void FrameBeginInternal(FramePrepareParams params) override; - void BuildAttachmentsInternal() override; + void BuildInternal() override; private: const RPI::PassAttachmentBinding* m_swapChainAttachmentBinding = nullptr; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp index 758c21bc4e..2fe8b01089 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp @@ -86,7 +86,7 @@ namespace AZ return colorBuffer->m_descriptor.m_image.m_size; } - void LuminanceHistogramGeneratorPass::BuildAttachmentsInternal() + void LuminanceHistogramGeneratorPass::BuildInternal() { CreateHistogramBuffer(); AttachHistogramBuffer(); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.h index ee8a10fe16..9691daab6f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.h @@ -42,7 +42,7 @@ namespace AZ protected: LuminanceHistogramGeneratorPass(const RPI::PassDescriptor& descriptor); - virtual void BuildAttachmentsInternal() override; + virtual void BuildInternal() override; void CreateHistogramBuffer(); void AttachHistogramBuffer(); AZ::RHI::Size GetColorBufferResolution(); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.cpp index 68472115ce..1aa16a4417 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.cpp @@ -41,9 +41,9 @@ namespace AZ return ParentPass::IsEnabled(); } - void SsaoParentPass::OnBuildAttachmentsFinishedInternal() + void SsaoParentPass::OnBuildFinishedInternal() { - ParentPass::OnBuildAttachmentsFinishedInternal(); + ParentPass::OnBuildFinishedInternal(); m_blurParentPass = FindChildPass(Name("SsaoBlur"))->AsParent(); AZ_Assert(m_blurParentPass, "[SsaoParentPass] Could not retrieve parent blur pass."); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.h index 9abd04e306..20aa554414 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.h @@ -36,7 +36,7 @@ namespace AZ protected: // Behavior functions override... - void OnBuildAttachmentsFinishedInternal() override; + void OnBuildFinishedInternal() override; void FrameBeginInternal(FramePrepareParams params) override; private: diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.cpp index 92cd41b4e8..f1fcd2de35 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.cpp @@ -42,7 +42,7 @@ namespace AZ } } - void RayTracingAccelerationStructurePass::BuildAttachmentsInternal() + void RayTracingAccelerationStructurePass::BuildInternal() { SetScopeId(RHI::ScopeId(GetPathName())); } diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.h b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.h index 6d90d752e3..127669301e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.h +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingAccelerationStructurePass.h @@ -44,7 +44,7 @@ namespace AZ void BuildCommandList(const RHI::FrameGraphExecuteContext& context) override; // Pass overrides - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; // buffer view descriptor for the TLAS diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.cpp index 5137b66bf9..9a9064bdf7 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.cpp @@ -30,7 +30,7 @@ namespace AZ { } - void ReflectionCopyFrameBufferPass::BuildAttachmentsInternal() + void ReflectionCopyFrameBufferPass::BuildInternal() { RPI::PassHierarchyFilter passFilter(AZ::Name("ReflectionScreenSpaceBlurPass")); const AZStd::vector& passes = RPI::PassSystemInterface::Get()->FindPasses(passFilter); @@ -43,7 +43,7 @@ namespace AZ AttachImageToSlot(outputBinding.m_name, frameBufferAttachment); } - FullscreenTrianglePass::BuildAttachmentsInternal(); + FullscreenTrianglePass::BuildInternal(); } } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.h index 2a2fecea40..f0b8c80d72 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.h @@ -37,7 +37,7 @@ namespace AZ explicit ReflectionCopyFrameBufferPass(const RPI::PassDescriptor& descriptor); // Pass Overrides... - void BuildAttachmentsInternal() override; + void BuildInternal() override; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp index 883686ac5b..680d117b98 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp @@ -113,7 +113,7 @@ namespace AZ } } - void ReflectionScreenSpaceBlurPass::BuildAttachmentsInternal() + void ReflectionScreenSpaceBlurPass::BuildInternal() { RemoveChildren(); @@ -166,9 +166,9 @@ namespace AZ // create child passes, one vertical and one horizontal blur per mip level CreateChildPasses(mipLevels - 1); - // call ParentPass::BuildAttachmentsInternal() first to configure the slots and auto-add the empty bindings, + // call ParentPass::BuildInternal() first to configure the slots and auto-add the empty bindings, // then we will assign attachments to the bindings - ParentPass::BuildAttachmentsInternal(); + ParentPass::BuildInternal(); // setup attachment bindings on vertical blur child passes uint32_t attachmentIndex = 0; diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h index 53f4026aef..f344fc8e9b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h @@ -44,7 +44,7 @@ namespace AZ // Pass Overrides... void ResetInternal() override; - void BuildAttachmentsInternal() override; + void BuildInternal() override; AZStd::vector> m_verticalBlurChildPasses; AZStd::vector> m_horizontalBlurChildPasses; diff --git a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp index 216a126953..8484fdddc2 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp @@ -526,7 +526,7 @@ namespace AZ::Render for (EsmShadowmapsPass* esmPass : m_esmShadowmapsPasses) { - esmPass->QueueForBuildAttachments(); + esmPass->QueueForBuild(); } for (ProjectedShadowmapsPass* shadowPass : m_projectedShadowmapsPasses) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/CopyPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/CopyPass.h index ede14564cd..fd5cdabc83 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/CopyPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/CopyPass.h @@ -49,7 +49,7 @@ namespace AZ void CopyImageToBuffer(const RHI::FrameGraphCompileContext& context); // Pass behavior overrides - void BuildAttachmentsInternal() override; + void BuildInternal() override; // Scope producer functions... void SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) override; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/MSAAResolvePass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/MSAAResolvePass.h index 91ae1536c3..71776982b3 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/MSAAResolvePass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/MSAAResolvePass.h @@ -40,7 +40,7 @@ namespace AZ MSAAResolvePass(const PassDescriptor& descriptor); // Pass behavior overrides... - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; private: diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h index b4f63a7099..0e1e12e620 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h @@ -109,8 +109,9 @@ namespace AZ // --- Pass Behaviour Overrides --- void ResetInternal() override; - void BuildAttachmentsInternal() override; - void OnBuildAttachmentsFinishedInternal() override; + void BuildInternal() override; + void OnBuildFinishedInternal() override; + void InitializeInternal() override; void FrameBeginInternal(FramePrepareParams params) override; void FrameEndInternal() override; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h index 1cba71ae7e..ee7f850d27 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h @@ -80,7 +80,7 @@ namespace AZ //! ending with 'Internal' to define the behavior of your passes. These virtual are recursively //! called in Preorder order throughout the pass tree. Only FramePrepare and FrameEnd are //! guaranteed to be called per frame. The other override-able functions are called as needed - //! when scheduled with the PassSystem. See QueueForBuildAttachments and QueueForRemoval. + //! when scheduled with the PassSystem. See QueueForBuild and QueueForRemoval. //! //! Passes are created by the PassFactory. They can be created using either Pass Name, //! a PassTemplate, or a PassRequest. To register your pass class with the PassFactory, @@ -153,11 +153,14 @@ namespace AZ // --- Utility functions --- - //! Queues the pass to have BuildAttachments() called by the PassSystem on frame update - void QueueForBuildAttachments(); + //! Queues the pass to have Build() called by the PassSystem on frame update + void QueueForBuild(); //! Queues the pass to have RemoveFromParent() called by the PassSystem on frame update - void QueueForRemoval(bool needsDeletion = false); + void QueueForRemoval(); + + //! Queues the pass to have Initialize() called by the PassSystem on frame update + void QueueForInitialization(); //! Adds an attachment binding to the list of this Pass' attachment bindings void AddAttachmentBinding(PassAttachmentBinding attachmentBinding); @@ -173,8 +176,8 @@ namespace AZ //! Attach an external buffer resource as attachment to specified slot //! The buffer will be added as a pass attachment then attach to the pass slot - //! Note: the pass attachment and binding will be removed after the general BuildAttachments call. - //! you can add this call in pass' BuildAttachmentsInternal so it will be added whenever attachments get rebuilt + //! Note: the pass attachment and binding will be removed after the general Build call. + //! you can add this call in pass' BuildInternal so it will be added whenever attachments get rebuilt void AttachBufferToSlot(AZStd::string_view slot, Data::Instance buffer); void AttachBufferToSlot(const Name& slot, Data::Instance buffer); void AttachImageToSlot(const Name& slot, Data::Instance image); @@ -256,6 +259,8 @@ namespace AZ //! Returns pointer to the parent pass ParentPass* GetParent() const; + PassState GetPassState() const; + protected: explicit Pass(const PassDescriptor& descriptor); @@ -309,18 +314,23 @@ namespace AZ // customize it's behavior, hence why these functions are called the pass behavior functions. // Resets everything in the pass (like Attachments). - // Called from PassSystem when pass is QueueForBuildAttachments. + // Called from PassSystem when pass is QueueForBuild. void Reset(); virtual void ResetInternal() { } // Builds and sets up any attachments and input/output connections the pass needs. - // Called from PassSystem when pass is QueueForBuildAttachments. - void BuildAttachments(); - virtual void BuildAttachmentsInternal() { } + // Called from PassSystem when pass is QueueForBuild. + void Build(); + virtual void BuildInternal() { } // Called after the pass build phase has finished. Allows passes to reset build flags. - void OnBuildAttachmentsFinished(); - virtual void OnBuildAttachmentsFinishedInternal() { }; + void OnBuildFinished(); + virtual void OnBuildFinishedInternal() { }; + + // Allows for additional pass initialization between building and rendering + // Can be queued independently of Build so as to only invoke Initialize without Build + void Initialize(); + virtual void InitializeInternal() { }; // The Pass's 'Render' function. Called every frame, here the pass sets up it's rendering logic with // the FrameGraphBuilder. This is where your derived pass needs to call ImportScopeProducer on @@ -379,20 +389,16 @@ namespace AZ struct { uint64_t m_createdByPassRequest : 1; - uint64_t m_initialized : 1; uint64_t m_enabled : 1; uint64_t m_parentEnabled : 1; - uint64_t m_alreadyCreated : 1; - uint64_t m_alreadyReset : 1; - uint64_t m_alreadyPrepared : 1; + + uint64_t m_initialized : 1; + uint64_t m_partOfHierarchy : 1; uint64_t m_hasDrawListTag : 1; uint64_t m_hasPipelineViewTag : 1; - uint64_t m_queuedForBuildAttachment : 1; uint64_t m_timestampQueryEnabled : 1; uint64_t m_pipelineStatisticsQueryEnabled : 1; - uint64_t m_isBuildingAttachments : 1; - uint64_t m_isRendering : 1; }; uint64_t m_allFlags = 0; }; @@ -510,6 +516,12 @@ namespace AZ // Depth of the tree hierarchy this pass is at. // Example: Root would be depth 0, Root.Ssao.Downsample depth 2 uint32_t m_treeDepth = 0; + + // Used to track what phase of build/execution the pass is in + PassState m_state = PassState::Uninitialized; + + // Used to track what phases of build/initialization the pass is queued for + PassQueueState m_queueState = PassQueueState::NoQueue; }; //! Struct used to return results from Pass hierarchy validation diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassDefines.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassDefines.h index d536104768..7c55944603 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassDefines.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassDefines.h @@ -21,3 +21,28 @@ // Set this to 1 locally on your machine to facilitate pass debugging and get extra information // about passes in the output window. DO NOT SUBMIT with value set to 1 #define AZ_RPI_ENABLE_PASS_DEBUGGING 0 + +namespace AZ +{ + namespace RPI + { + enum class PassState : u8 + { + Uninitialized, + Queued, + Resetting, + Building, + Initializing, + Initialized, + Rendering + }; + + enum class PassQueueState : u8 + { + NoQueue, + QueuedForRemoval, + QueuedForBuild, + QueuedForInitialization, + }; + } +} diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h index fd30f4f406..534bf211dd 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h @@ -73,12 +73,12 @@ namespace AZ bool LoadPassTemplateMappings(const AZStd::string& templateMappingPath) override; void WriteTemplateToFile(const PassTemplate& passTemplate, AZStd::string_view assetFilePath) override; void DebugPrintPassHierarchy() override; - bool IsBuilding() const override; bool IsHotReloading() const override; void SetHotReloading(bool hotReloading) override; void SetTargetedPassDebuggingName(const AZ::Name& targetPassName) override; const AZ::Name& GetTargetedPassDebuggingName() const override; void ConnectEvent(OnReadyLoadTemplatesEvent::Handler& handler) override; + PassSystemState GetState() const override; // PassSystemInterface factory related functions... void AddPassCreator(Name className, PassCreator createFunction) override; @@ -103,8 +103,11 @@ namespace AZ // Returns the root of the pass tree hierarchy const Ptr& GetRootPass() override; - // Calls BuildAttachments() on passes queued in m_buildAttachmentsList - void BuildPassAttachments(); + // Calls Build() on passes queued in m_buildPassList + void BuildPasses(); + + // Calls Initialize() on passes queued in m_initializePassList + void InitializePasses(); // Validates Pass Hierarchy after building void Validate(); @@ -113,13 +116,15 @@ namespace AZ void RemovePasses(); // Functions for queuing passes in the lists below - void QueueForBuildAttachments(Pass* pass) override; + void QueueForBuild(Pass* pass) override; void QueueForRemoval(Pass* pass) override; + void QueueForInitialization(Pass* pass) override; // Lists for queuing passes for various function calls // Name of the list reflects the pass function it will call - AZStd::vector< Ptr > m_buildAttachmentsList; + AZStd::vector< Ptr > m_buildPassList; AZStd::vector< Ptr > m_removePassList; + AZStd::vector< Ptr > m_initializePassList; // Library of pass descriptors that can be instantiated through data driven pass requests PassLibrary m_passLibrary; @@ -133,9 +138,6 @@ namespace AZ // Whether the Pass Hierarchy changed bool m_passHierarchyChanged = true; - // Whether the Pass System is currently in it's building phase - bool m_isBuilding = false; - // Whether the Pass System is currently hot reloading passes bool m_isHotReloading = false; @@ -147,6 +149,9 @@ namespace AZ // Events OnReadyLoadTemplatesEvent m_loadTemplatesEvent; + + // Used to track what phase of execution the pass system is in + PassSystemState m_state = PassSystemState::Unitialized; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h index 1224bf9545..788d00c8eb 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h @@ -40,6 +40,18 @@ namespace AZ using PassCreator = AZStd::function(const PassDescriptor& descriptor)>; + enum class PassSystemState : u32 + { + Unitialized, + Idle, + RemovingPasses, + Building, + Initializing, + Validating, + Rendering, + FrameEnd, + }; + class PassSystemInterface { friend class Pass; @@ -77,9 +89,6 @@ namespace AZ //! Prints the entire pass hierarchy from the root virtual void DebugPrintPassHierarchy() = 0; - //! Returns whether the Pass System is currently in it's build phase - virtual bool IsBuilding() const = 0; - //! Returns whether the Pass System is currently hot reloading virtual bool IsHotReloading() const = 0; @@ -157,15 +166,20 @@ namespace AZ //! The handler can add new pass templates or load pass template mappings from assets virtual void ConnectEvent(OnReadyLoadTemplatesEvent::Handler& handler) = 0; + virtual PassSystemState GetState() const = 0; + private: // These functions are only meant to be used by the Pass class - // Schedules a pass to have it's BuildAttachments() function called during frame update - virtual void QueueForBuildAttachments(Pass* pass) = 0; + // Schedules a pass to have it's Build() function called during frame update + virtual void QueueForBuild(Pass* pass) = 0; // Schedules a pass to be deleted during frame update virtual void QueueForRemoval(Pass* pass) = 0; + // Schedules a pass to be initialized during frame update + virtual void QueueForInitialization(Pass* pass) = 0; + //! Registers the pass with the pass library. Called in the Pass constructor. virtual void RegisterPass(Pass* pass) = 0; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RenderPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RenderPass.h index 5cd917e841..5f222d8bba 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RenderPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RenderPass.h @@ -96,7 +96,7 @@ namespace AZ void BindPassSrg(const RHI::FrameGraphCompileContext& context, Data::Instance& shaderResourceGroup); // Pass behavior overrides... - void OnBuildAttachmentsFinishedInternal() override; + void OnBuildFinishedInternal() override; void FrameBeginInternal(FramePrepareParams params) override; void FrameEndInternal() override; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/DownsampleMipChainPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/DownsampleMipChainPass.h index 71c1fe4c49..eb4c4ed0aa 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/DownsampleMipChainPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/DownsampleMipChainPass.h @@ -46,7 +46,7 @@ namespace AZ // Pass Behaviour Overrides... void ResetInternal() override; - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; private: diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.h index 293a750f38..235871df83 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.h @@ -61,7 +61,7 @@ namespace AZ // Pass overrides void CreateChildPassesInternal() override; - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; void FrameEndInternal() override; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/RenderToTexturePass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/RenderToTexturePass.h index c8daab8ef8..c86203b79b 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/RenderToTexturePass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/RenderToTexturePass.h @@ -47,7 +47,7 @@ namespace AZ protected: // Pass behavior overrides - void BuildAttachmentsInternal() override; + void BuildInternal() override; void FrameBeginInternal(FramePrepareParams params) override; // Function to be called when output size changed diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/SelectorPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/SelectorPass.h index fe0ce231eb..2d876c6040 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/SelectorPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/SelectorPass.h @@ -49,7 +49,7 @@ namespace AZ SelectorPass(const PassDescriptor& descriptor); // Pass behavior overrides - void BuildAttachmentsInternal() final; + void BuildInternal() final; // the input slot index each output slot connect to AZStd::vector m_connections; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/SwapChainPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/SwapChainPass.h index 9aa00c99c2..7eac0d366d 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/SwapChainPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Specific/SwapChainPass.h @@ -64,7 +64,7 @@ namespace AZ protected: // Pass behavior overrides void CreateChildPassesInternal() override final; - void BuildAttachmentsInternal() override final; + void BuildInternal() override final; void FrameBeginInternal(FramePrepareParams params) override final; // WindowNotificationBus::Handler overrides ... diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/CopyPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/CopyPass.cpp index 4a6c883584..9648a47fd6 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/CopyPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/CopyPass.cpp @@ -74,7 +74,7 @@ namespace AZ // --- Pass behavior overrides --- - void CopyPass::BuildAttachmentsInternal() + void CopyPass::BuildInternal() { AZ_Assert(GetInputCount() == 1 && GetOutputCount() == 1, "CopyPass has %d inputs and %d outputs. It should have exactly one of each.", diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/MSAAResolvePass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/MSAAResolvePass.cpp index c889f367b7..e457cb4992 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/MSAAResolvePass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/MSAAResolvePass.cpp @@ -38,7 +38,7 @@ namespace AZ { } - void MSAAResolvePass::BuildAttachmentsInternal() + void MSAAResolvePass::BuildInternal() { AZ_Assert(GetOutputCount() != 0, "MSAAResolvePass %s has no outputs to render to.", GetPathName().GetCStr()); } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp index 106ef82bf1..7244510fbd 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp @@ -59,7 +59,7 @@ namespace AZ child->m_parent = this; child->OnHierarchyChange(); - QueueForBuildAttachments(); + QueueForBuild(); // Notify pipeline if (m_pipeline) @@ -248,13 +248,6 @@ namespace AZ void ParentPass::CreateChildPasses() { - // Flag prevents the function from executing multiple times a frame. Can happen - // as pass system has a list of passes for which it needs to call this function. - if (m_flags.m_alreadyCreated) - { - return; - } - m_flags.m_alreadyCreated = true; RemoveChildren(); CreatePassesFromTemplate(); CreateChildPassesInternal(); @@ -277,19 +270,27 @@ namespace AZ } } - void ParentPass::BuildAttachmentsInternal() + void ParentPass::BuildInternal() { for (const Ptr& child : m_children) { - child->BuildAttachments(); + child->Build(); } } - void ParentPass::OnBuildAttachmentsFinishedInternal() + void ParentPass::OnBuildFinishedInternal() { for (const Ptr& child : m_children) { - child->OnBuildAttachmentsFinished(); + child->OnBuildFinished(); + } + } + + void ParentPass::InitializeInternal() + { + for (const Ptr& child : m_children) + { + child->Initialize(); } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp index 8d613eb2bb..da9022b655 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp @@ -71,7 +71,7 @@ namespace AZ } PassSystemInterface::Get()->RegisterPass(this); - QueueForBuildAttachments(); + QueueForBuild(); } Pass::~Pass() @@ -162,6 +162,11 @@ namespace AZ // --- Getters & Setters --- + PassState Pass::GetPassState() const + { + return m_state; + } + ParentPass* Pass::GetParent() const { return m_parent; @@ -350,28 +355,49 @@ namespace AZ // --- Queuing functions with PassSystem --- - void Pass::QueueForBuildAttachments() + void Pass::QueueForBuild() { // Don't queue if we're in building phase - if (!PassSystemInterface::Get()->IsBuilding()) + if (PassSystemInterface::Get()->GetState() != PassSystemState::Building && + (m_queueState == PassQueueState::NoQueue || m_queueState == PassQueueState::QueuedForInitialization)) { - // m_queuedForBuildAttachment makes sure the pass only be queue for once - if (!m_flags.m_queuedForBuildAttachment) - { - PassSystemInterface::Get()->QueueForBuildAttachments(this); - m_flags.m_queuedForBuildAttachment = true; + PassSystemInterface::Get()->QueueForBuild(this); + m_queueState = PassQueueState::QueuedForBuild; - // Set these two flags to false since when queue build attachments request, they should all be already be false except one use - // case that the pass system processed all queued requests when active a scene. - m_flags.m_alreadyPrepared = false; - m_flags.m_alreadyReset = false; + if (m_state != PassState::Rendering) + { + m_state = PassState::Queued; } } } - void Pass::QueueForRemoval([[maybe_unused]] bool needsDeletion) + void Pass::QueueForInitialization() { - PassSystemInterface::Get()->QueueForRemoval(this); + // Don't queue if we're in initialization phase + if (PassSystemInterface::Get()->GetState() != PassSystemState::Initializing && m_queueState == PassQueueState::NoQueue) + { + PassSystemInterface::Get()->QueueForInitialization(this); + m_queueState = PassQueueState::QueuedForInitialization; + + if(m_state != PassState::Rendering) + { + m_state = PassState::Queued; + } + } + } + + void Pass::QueueForRemoval() + { + if (m_queueState != PassQueueState::QueuedForRemoval) + { + PassSystemInterface::Get()->QueueForRemoval(this); + m_queueState = PassQueueState::QueuedForRemoval; + + if (m_state != PassState::Rendering) + { + m_state = PassState::Queued; + } + } } // --- PassTemplate related functions --- @@ -990,7 +1016,7 @@ namespace AZ { Ptr targetAttachment = nullptr; - if (!m_flags.m_isBuildingAttachments && !IsEnabled() && binding.m_slotType == PassSlotType::Output && binding.m_fallbackBinding) + if (m_state != PassState::Building && !IsEnabled() && binding.m_slotType == PassSlotType::Output && binding.m_fallbackBinding) { targetAttachment = binding.m_fallbackBinding->m_attachment; } @@ -1037,13 +1063,11 @@ namespace AZ void Pass::Reset() { - // Flag prevents the function from executing multiple times a frame. Can happen - // as pass system has a list of passes for which it needs to call this function. - if (m_flags.m_alreadyReset) + if (m_queueState != PassQueueState::QueuedForBuild || m_state != PassState::Queued) { return; } - m_flags.m_alreadyReset = true; + m_state = PassState::Resetting; // Store references to imported attachments to underlying images and buffers aren't deleted during attachment building StoreImportedAttachmentReferences(); @@ -1060,18 +1084,13 @@ namespace AZ ResetInternal(); } - void Pass::BuildAttachments() + void Pass::Build() { - m_flags.m_queuedForBuildAttachment = false; - - // Flag prevents the function from executing multiple times a frame. Can happen - // as pass system has a list of passes for which it needs to call this function. - if (m_flags.m_alreadyPrepared) + if (m_queueState != PassQueueState::QueuedForBuild || m_state != PassState::Resetting) { return; } - m_flags.m_alreadyPrepared = true; - m_flags.m_isBuildingAttachments = true; + m_state = PassState::Building; AZ_RPI_BREAK_ON_TARGET_PASS; @@ -1084,7 +1103,7 @@ namespace AZ SetupInputsFromTemplate(); // Custom pass behavior - BuildAttachmentsInternal(); + BuildInternal(); // Outputs SetupOutputsFromTemplate(); @@ -1095,21 +1114,29 @@ namespace AZ UpdateOwnedAttachments(); UpdateAttachmentUsageIndices(); - m_flags.m_isBuildingAttachments = false; + // Queue for Initialization + m_queueState = PassQueueState::NoQueue; + QueueForInitialization(); } - void Pass::OnBuildAttachmentsFinished() + void Pass::OnBuildFinished() { AZ_RPI_BREAK_ON_TARGET_PASS; - // These flags are to prevent a pass from being built multiple times. - // We reset them after each build phase. - m_flags.m_alreadyCreated = false; - m_flags.m_alreadyPrepared = false; - m_flags.m_alreadyReset = false; - m_flags.m_queuedForBuildAttachment = false; m_importedAttachmentStore.clear(); - OnBuildAttachmentsFinishedInternal(); + OnBuildFinishedInternal(); + } + + void Pass::Initialize() + { + if (m_queueState != PassQueueState::QueuedForInitialization || m_state != PassState::Queued) + { + return; + } + + m_state = PassState::Initializing; + InitializeInternal(); + m_state = PassState::Initialized; } void Pass::Validate(PassValidationResults& validationResults) @@ -1165,7 +1192,7 @@ namespace AZ UpdateConnectedBindings(); return; } - m_flags.m_isRendering = true; + m_state = PassState::Rendering; UpdateConnectedBindings(); UpdateOwnedAttachments(); @@ -1180,10 +1207,10 @@ namespace AZ void Pass::FrameEnd() { - if (m_flags.m_isRendering) + if (m_state == PassState::Rendering) { FrameEndInternal(); - m_flags.m_isRendering = false; + m_state = (m_queueState == PassQueueState::NoQueue) ? PassState::Initialized : PassState::Queued; } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp index 448c28f202..3dabd88fff 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -93,11 +93,15 @@ namespace AZ void PassSystem::Init() { + m_state = PassSystemState::Initializing; + Interface::Register(this); m_passLibrary.Init(); m_passFactory.Init(&m_passLibrary); m_rootPass = CreatePass(Name{"Root"}); m_rootPass->m_flags.m_partOfHierarchy = true; + + m_state = PassSystemState::Idle; } void PassSystem::InitPassTemplates() @@ -118,10 +122,10 @@ namespace AZ JsonSerializationUtils::SaveObjectToFile(&passAsset, assetFilePath); } - void PassSystem::QueueForBuildAttachments(Pass* pass) + void PassSystem::QueueForBuild(Pass* pass) { - AZ_Assert(pass != nullptr, "Queuing nullptr pass in PassSystem::QueueForBuildAttachments"); - m_buildAttachmentsList.push_back(pass); + AZ_Assert(pass != nullptr, "Queuing nullptr pass in PassSystem::QueueForBuild"); + m_buildPassList.push_back(pass); } void PassSystem::QueueForRemoval(Pass* pass) @@ -130,6 +134,12 @@ namespace AZ m_removePassList.push_back(pass); } + void PassSystem::QueueForInitialization(Pass* pass) + { + AZ_Assert(pass != nullptr, "Queuing nullptr pass in PassSystem::QueueForInitialization"); + m_initializePassList.push_back(pass); + } + // Sort so passes with less depth (closer to the root) are first. Used when changes // in the parent passes can affect the child passes, like with attachment building. void SortPassListAscending(AZStd::vector< Ptr >& passList) @@ -155,6 +165,7 @@ namespace AZ void PassSystem::RemovePasses() { + m_state = PassSystemState::RemovingPasses; AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: RemovePasses"); if (!m_removePassList.empty()) @@ -168,24 +179,25 @@ namespace AZ m_removePassList.clear(); } + + m_state = PassSystemState::Idle; } - void PassSystem::BuildPassAttachments() + void PassSystem::BuildPasses() { + m_state = PassSystemState::Building; AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: BuildPassAttachments"); - m_isBuilding = true; + m_passHierarchyChanged = !m_buildPassList.empty(); - m_passHierarchyChanged = !m_buildAttachmentsList.empty(); - - // While loop is for the event in which passes being built add more pass to m_buildAttachmentsList - while(!m_buildAttachmentsList.empty()) + // While loop is for the event in which passes being built add more pass to m_buildPassList + while(!m_buildPassList.empty()) { AZ_Assert(m_removePassList.empty(), "Passes shouldn't be queued removal during build attachment process"); - AZStd::vector< Ptr > buildListCopy = m_buildAttachmentsList; - m_buildAttachmentsList.clear(); + AZStd::vector< Ptr > buildListCopy = m_buildPassList; + m_buildPassList.clear(); // Erase passes which were removed from pass tree already (which parent is empty) auto unused = AZStd::remove_if(buildListCopy.begin(), buildListCopy.end(), @@ -203,15 +215,15 @@ namespace AZ } for (const Ptr& pass : buildListCopy) { - pass->BuildAttachments(); + pass->Build(); } - - // Signal all passes that we have finished building - m_rootPass->OnBuildAttachmentsFinished(); } if (m_passHierarchyChanged) { + // Signal all passes that we have finished building + m_rootPass->OnBuildFinished(); + #if AZ_RPI_ENABLE_PASS_DEBUGGING if (!m_isHotReloading) { @@ -221,11 +233,39 @@ namespace AZ #endif } - m_isBuilding = false; + m_state = PassSystemState::Idle; + } + + void PassSystem::InitializePasses() + { + m_state = PassSystemState::Initializing; + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: BuildPassAttachments"); + + if(!m_initializePassList.empty()) + { + // Erase passes which were removed from pass tree already (which parent is empty) + auto unused = AZStd::remove_if(m_initializePassList.begin(), m_initializePassList.end(), + [](const RHI::Ptr& currentPass) + { + return !currentPass->m_flags.m_partOfHierarchy; + }); + m_initializePassList.erase(unused, m_initializePassList.end()); + + SortPassListAscending(m_initializePassList); + + for (const Ptr& pass : m_initializePassList) + { + pass->Initialize(); + } + } + + m_state = PassSystemState::Idle; } void PassSystem::Validate() { + m_state = PassSystemState::Validating; AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: Validate"); if (PassValidation::IsEnabled()) @@ -241,12 +281,15 @@ namespace AZ m_rootPass->Validate(validationResults); validationResults.PrintValidationIfError(); } + + m_state = PassSystemState::Idle; } void PassSystem::ProcessQueuedChanges() { RemovePasses(); - BuildPassAttachments(); + BuildPasses(); + InitializePasses(); Validate(); } @@ -256,6 +299,8 @@ namespace AZ AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: FrameUpdate"); ProcessQueuedChanges(); + + m_state = PassSystemState::Rendering; Pass::FramePrepareParams params{ &frameGraphBuilder }; m_rootPass->FrameBegin(params); } @@ -264,6 +309,8 @@ namespace AZ { AZ_ATOM_PROFILE_FUNCTION("RHI", "PassSystem: FrameEnd"); + m_state = PassSystemState::FrameEnd; + m_rootPass->FrameEnd(); // remove any pipelines that are marked as ExecuteOnce @@ -278,12 +325,14 @@ namespace AZ } m_passHierarchyChanged = false; + + m_state = PassSystemState::Idle; } void PassSystem::Shutdown() { RemovePasses(); - m_buildAttachmentsList.clear(); + m_buildPassList.clear(); m_rootPass = nullptr; m_passFactory.Shutdown(); m_passLibrary.Shutdown(); @@ -296,9 +345,9 @@ namespace AZ return m_rootPass; } - bool PassSystem::IsBuilding() const + PassSystemState PassSystem::GetState() const { - return m_isBuilding; + return m_state; } bool PassSystem::IsHotReloading() const diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp index 3a2a556429..12989fb873 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp @@ -128,7 +128,7 @@ namespace AZ } - void RenderPass::OnBuildAttachmentsFinishedInternal() + void RenderPass::OnBuildFinishedInternal() { if (m_shaderResourceGroup != nullptr) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/DownsampleMipChainPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/DownsampleMipChainPass.cpp index 0e0ebf445e..329247d4eb 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/DownsampleMipChainPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/DownsampleMipChainPass.cpp @@ -181,12 +181,12 @@ namespace AZ // Pass behavior functions... - void DownsampleMipChainPass::BuildAttachmentsInternal() + void DownsampleMipChainPass::BuildInternal() { GetInputInfo(); BuildChildPasses(); UpdateChildren(); - ParentPass::BuildAttachmentsInternal(); + ParentPass::BuildInternal(); } void DownsampleMipChainPass::FrameBeginInternal(FramePrepareParams params) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp index c72712bce5..672e5509ee 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp @@ -37,8 +37,6 @@ namespace AZ EnvironmentCubeMapPass::EnvironmentCubeMapPass(const PassDescriptor& passDescriptor) : ParentPass(passDescriptor) { - m_flags.m_alreadyCreated = false; - // load pass data const EnvironmentCubeMapPassData* passData = PassUtils::GetPassData(passDescriptor); if (passData == nullptr) @@ -113,7 +111,7 @@ namespace AZ AddChild(m_childPass); } - void EnvironmentCubeMapPass::BuildAttachmentsInternal() + void EnvironmentCubeMapPass::BuildInternal() { // create output image descriptor m_outputImageDesc = RHI::ImageDescriptor::Create2D(RHI::ImageBindFlags::Color | RHI::ImageBindFlags::CopyRead, CubeMapFaceSize, CubeMapFaceSize, RHI::Format::R16G16B16A16_FLOAT); @@ -135,7 +133,7 @@ namespace AZ m_attachmentBindings.push_back(outputAttachment); - ParentPass::BuildAttachmentsInternal(); + ParentPass::BuildInternal(); } void EnvironmentCubeMapPass::FrameBeginInternal(FramePrepareParams params) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/RenderToTexturePass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/RenderToTexturePass.cpp index 4356a56622..c0a4785365 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/RenderToTexturePass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/RenderToTexturePass.cpp @@ -50,7 +50,7 @@ namespace AZ { } - void RenderToTexturePass::BuildAttachmentsInternal() + void RenderToTexturePass::BuildInternal() { m_outputAttachment = aznew PassAttachment(); m_outputAttachment->m_name = "RenderTarget"; @@ -73,7 +73,7 @@ namespace AZ m_attachmentBindings.push_back(outputBinding); - Base::BuildAttachmentsInternal(); + Base::BuildInternal(); } void RenderToTexturePass::FrameBeginInternal(FramePrepareParams params) @@ -100,7 +100,7 @@ namespace AZ m_passData.m_width = width; m_passData.m_height = height; OnUpdateOutputSize(); - QueueForBuildAttachments(); + QueueForBuild(); } void RenderToTexturePass::OnUpdateOutputSize() diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SelectorPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SelectorPass.cpp index 8e8c67393d..90390b78d7 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SelectorPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SelectorPass.cpp @@ -44,7 +44,7 @@ namespace AZ } } - void SelectorPass::BuildAttachmentsInternal() + void SelectorPass::BuildInternal() { // Update output connections based on m_connections // This need to be done after BuildAttachment is finished @@ -72,7 +72,7 @@ namespace AZ m_connections[outputSlotIndex] = inputSlotIndex; // Queue to rebuild attachment connections - QueueForBuildAttachments(); + QueueForBuild(); } void SelectorPass::Connect(const AZ::Name& inputSlot, const AZ::Name& outputSlot) @@ -113,7 +113,7 @@ namespace AZ m_connections[outputIdx] = inputIdx; // Queue to rebuild attachment connections - QueueForBuildAttachments(); + QueueForBuild(); } } // namespace RPI diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp index 5bcec87df0..e6f65e997c 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp @@ -26,8 +26,6 @@ namespace AZ , m_windowContext(windowContext) , m_childTemplateName(childTemplateName) { - m_flags.m_alreadyCreated = false; - PassSystemInterface* passSystem = PassSystemInterface::Get(); // Create child pass @@ -112,7 +110,7 @@ namespace AZ AddChild(m_childPass); } - void SwapChainPass::BuildAttachmentsInternal() + void SwapChainPass::BuildInternal() { if (m_windowContext->GetSwapChain() == nullptr) { @@ -124,7 +122,7 @@ namespace AZ SetupSwapChainAttachment(); - ParentPass::BuildAttachmentsInternal(); + ParentPass::BuildInternal(); } void SwapChainPass::FrameBeginInternal(FramePrepareParams params) @@ -154,7 +152,7 @@ namespace AZ void SwapChainPass::OnWindowResized([[maybe_unused]] uint32_t width, [[maybe_unused]] uint32_t height) { - QueueForBuildAttachments(); + QueueForBuild(); } void SwapChainPass::ReadbackSwapChain(AZStd::shared_ptr readback) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp index cc0cefd082..86d76287bb 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp @@ -329,9 +329,8 @@ namespace AZ if (validation.IsValid()) { // Remove old pass - bool deletePass = true; m_rootPass->SetRenderPipeline(nullptr); - m_rootPass->QueueForRemoval(deletePass); + m_rootPass->QueueForRemoval(); // Set new root m_rootPass = newRoot; diff --git a/Gems/Atom/RPI/Code/Tests/Pass/PassTests.cpp b/Gems/Atom/RPI/Code/Tests/Pass/PassTests.cpp index 96a21f8c9b..f9a2bc4493 100644 --- a/Gems/Atom/RPI/Code/Tests/Pass/PassTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Pass/PassTests.cpp @@ -329,7 +329,7 @@ namespace UnitTest Ptr parentPass = m_passSystem->CreatePassFromTemplate(Name("ParentPass"), Name("ParentPass")); parentPass->Reset(); - parentPass->BuildAttachments(); + parentPass->Build(); PassValidationResults validationResults; parentPass->Validate(validationResults); @@ -351,7 +351,7 @@ namespace UnitTest Ptr parentPass = m_passSystem->CreatePassFromTemplate(Name("ParentPass"), Name("ParentPass")); parentPass->Reset(); - parentPass->BuildAttachments(); + parentPass->Build(); PassValidationResults validationResults; parentPass->Validate(validationResults); @@ -373,7 +373,7 @@ namespace UnitTest Ptr parentPass = m_passSystem->CreatePassFromTemplate(Name("ParentPass"), Name("ParentPass")); parentPass->Reset(); - parentPass->BuildAttachments(); + parentPass->Build(); PassValidationResults validationResults; parentPass->Validate(validationResults); @@ -397,7 +397,7 @@ namespace UnitTest parentPass->m_flags.m_partOfHierarchy = true; parentPass->OnHierarchyChange(); parentPass->Reset(); - parentPass->BuildAttachments(); + parentPass->Build(); PassValidationResults validationResults; parentPass->Validate(validationResults); @@ -421,7 +421,7 @@ namespace UnitTest parentPass->m_flags.m_partOfHierarchy = true; parentPass->OnHierarchyChange(); parentPass->Reset(); - parentPass->BuildAttachments(); + parentPass->Build(); PassValidationResults validationResults; parentPass->Validate(validationResults); @@ -445,7 +445,7 @@ namespace UnitTest parentPass->m_flags.m_partOfHierarchy = true; parentPass->OnHierarchyChange(); parentPass->Reset(); - parentPass->BuildAttachments(); + parentPass->Build(); PassValidationResults validationResults; parentPass->Validate(validationResults); @@ -469,7 +469,7 @@ namespace UnitTest parentPass->m_flags.m_partOfHierarchy = true; parentPass->OnHierarchyChange(); parentPass->Reset(); - parentPass->BuildAttachments(); + parentPass->Build(); PassValidationResults validationResults; parentPass->Validate(validationResults); From 5d4226df16a404708b69cb5a46e8aa297adb1767 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Fri, 4 Jun 2021 17:28:43 +0000 Subject: [PATCH 510/811] Get a mesh's morph targets based on the scene graph hierarchy, instead of mesh name (#1128) When building a mesh's morph targets, the exporter has to identify the base mesh in addition to each morph target mesh. Previously this was done by searching the entire scene graph for nodes * of type IBlendShapeData * whose parent's name matches the name of the Atom model This is problematic for a few reasons. The first is that the Atom model's name may have been based on the optimized mesh node. When this happens, the `OptimizedMeshSuffix` that is used in the Scene Graph node's name is stripped off of the Atom model's name. The result is that the *unoptimized* mesh is used as the base mesh for the blend shapes, instead of the optimized blend shape. This of course results in disaster, since the optimizer reorders the vertices, and the base mesh will not match the optimized one. The second is that it is not really necessary to do the search based on the node name at all. All of a mesh's blend shapes are child nodes of the base IMeshData node. With this change, the base mesh is located based on the node data pointer, and all of its child IBlendShapeData nodes are added to the set of blend shapes to process. This way, the Atom model's name isn't involved in the lookup. --- .../Model/MorphTargetExporter.cpp | 83 ++++++++----------- .../RPI.Builders/Model/MorphTargetExporter.h | 5 +- 2 files changed, 36 insertions(+), 52 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp index 3d0cbca8e6..f14d73a9cf 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp @@ -14,9 +14,11 @@ #include #include #include +#include #include #include #include +#include #include #include @@ -27,62 +29,42 @@ namespace AZ::RPI AZStd::unordered_map MorphTargetExporter::GetBlendShapeInfos( const Containers::Scene& scene, - const AZStd::optional& filterMeshName) const + const MeshData* meshData) const { const Containers::SceneGraph& sceneGraph = scene.GetGraph(); - const auto contentStorage = sceneGraph.GetContentStorage(); - const auto nameStorage = sceneGraph.GetNameStorage(); + + const auto foundBaseMeshIter = AZStd::find_if(sceneGraph.GetContentStorage().cbegin(), sceneGraph.GetContentStorage().cend(), [meshData](const auto& nodeData) + { + return nodeData.get() == meshData; + }); + if (foundBaseMeshIter == sceneGraph.GetContentStorage().cend()) + { + return {}; + } + + const auto baseMeshNodeIndex = sceneGraph.ConvertToNodeIndex(foundBaseMeshIter); + + const auto childBlendShapeDatas = Containers::MakeDerivedFilterView( + Containers::Views::MakeSceneGraphChildView(sceneGraph, baseMeshNodeIndex, sceneGraph.GetContentStorage().cbegin(), true) + ); AZStd::unordered_map result; - - const auto keyValueView = Containers::Views::MakePairView(nameStorage, contentStorage); - const auto filteredView = Containers::Views::MakeFilterView(keyValueView, Containers::DerivedTypeFilter()); - for (const auto& [name, object] : filteredView) + for (auto it = childBlendShapeDatas.cbegin(); it != childBlendShapeDatas.cend(); ++it) { - const Containers::SceneGraph::NodeIndex sceneNodeIndex = sceneGraph.Find(name.GetPath()); + const Containers::SceneGraph::NodeIndex blendShapeNodeIndex = sceneGraph.ConvertToNodeIndex(it.GetBaseIterator().GetBaseIterator().GetHierarchyIterator()); AZStd::set types; - Events::GraphMetaInfoBus::Broadcast(&Events::GraphMetaInfo::GetVirtualTypes, types, scene, sceneNodeIndex); - if (types.find(Events::GraphMetaInfo::GetIgnoreVirtualType()) == types.end()) + Events::GraphMetaInfoBus::Broadcast(&Events::GraphMetaInfo::GetVirtualTypes, types, scene, blendShapeNodeIndex); + if (!types.contains(Events::GraphMetaInfo::GetIgnoreVirtualType())) { - const char* sceneNodePath = name.GetPath(); - const Containers::SceneGraph::NodeIndex nodeIndex = sceneGraph.Find(sceneNodePath); - if (nodeIndex.IsValid()) - { - const AZStd::string meshNodeName = SourceBlendShapeInfo::GetMeshNodeName(sceneGraph, nodeIndex); - if (!filterMeshName.has_value() || - (filterMeshName.has_value() && filterMeshName.value() == meshNodeName)) - { - const AZStd::string blendShapeName = sceneGraph.GetNodeName(nodeIndex).GetName(); - SourceBlendShapeInfo& blendShapeInfo = result[blendShapeName]; - blendShapeInfo.m_sceneNodeIndices.push_back(nodeIndex); - } - } - else - { - AZ_Warning(ModelAssetBuilderComponent::s_builderName, false, "Cannot retrieve scene graph index for blend shape node with path %s.", sceneNodePath); - } + const AZStd::string blendShapeName{sceneGraph.GetNodeName(blendShapeNodeIndex).GetName(), sceneGraph.GetNodeName(blendShapeNodeIndex).GetNameLength()}; + result[blendShapeName].m_sceneNodeIndices.emplace_back(blendShapeNodeIndex); } } return result; } - AZStd::string MorphTargetExporter::SourceBlendShapeInfo::GetMeshNodeName(const Containers::SceneGraph& sceneGraph, - const Containers::SceneGraph::NodeIndex& sceneNodeIndex) - { - const auto* blendShapeData = - azrtti_cast(sceneGraph.GetNodeContent(sceneNodeIndex).get()); - AZ_Assert(blendShapeData, "Cannot get mesh node name from scene node. Node is expected to be a blend shape."); - if (blendShapeData) - { - Containers::SceneGraph::NodeIndex morphMeshParentIndex = sceneGraph.GetNodeParent(sceneNodeIndex); - return sceneGraph.GetNodeName(morphMeshParentIndex).GetName(); - } - - return {}; - } - void MorphTargetExporter::ProduceMorphTargets(const Containers::Scene& scene, uint32_t vertexOffset, const ModelAssetBuilderComponent::SourceMeshContent& sourceMesh, @@ -92,9 +74,14 @@ namespace AZ::RPI { const Containers::SceneGraph& sceneGraph = scene.GetGraph(); +#if defined(AZ_ENABLE_TRACING) + const auto baseMeshIt = AZStd::find(sceneGraph.GetContentStorage().cbegin(), sceneGraph.GetContentStorage().cend(), sourceMesh.m_meshData); + const Containers::SceneGraph::NodeIndex baseMeshIndex = sceneGraph.ConvertToNodeIndex(baseMeshIt); + const AZStd::string_view baseMeshName{sceneGraph.GetNodeName(baseMeshIndex).GetName(), sceneGraph.GetNodeName(baseMeshIndex).GetNameLength()}; +#endif + // Get the blend shapes for the given mesh - const AZStd::string_view meshName = sourceMesh.m_name.GetStringView(); - AZStd::unordered_map blendShapeInfos = GetBlendShapeInfos(scene, meshName); + AZStd::unordered_map blendShapeInfos = GetBlendShapeInfos(scene, sourceMesh.m_meshData.get()); for (const auto& iter : blendShapeInfos) { @@ -109,12 +96,12 @@ namespace AZ::RPI { #if defined(AZ_ENABLE_TRACING) const Containers::SceneGraph::NodeIndex morphMeshParentIndex = sceneGraph.GetNodeParent(sceneNodeIndex); - const char* meshNodeName = sceneGraph.GetNodeName(morphMeshParentIndex).GetName(); + const AZStd::string_view sourceMeshName{sceneGraph.GetNodeName(morphMeshParentIndex).GetName(), sceneGraph.GetNodeName(morphMeshParentIndex).GetNameLength()}; #endif - AZ_Assert(AZ::StringFunc::Equal(sourceMesh.m_name.GetCStr(), meshNodeName, /*bCaseSensitive=*/true), - "Scene graph mesh node (%s) has a different name than the product mesh (%s).", - meshNodeName, sourceMesh.m_name.GetCStr()); + AZ_Assert(AZ::StringFunc::Equal(baseMeshName, sourceMeshName, /*bCaseSensitive=*/true), + "Scene graph mesh node (%.*s) has a different name than the product mesh (%.*s).", + AZ_STRING_ARG(sourceMeshName), AZ_STRING_ARG(baseMeshName)); const DataTypes::MatrixType globalTransform = Utilities::BuildWorldTransform(sceneGraph, sceneNodeIndex); BuildMorphTargetMesh(vertexOffset, sourceMesh, productMesh, metaAssetCreator, blendShapeName, blendShapeData, globalTransform, coordSysConverter, scene.GetSourceFilename()); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.h b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.h index 4845d7d1da..32f9e2e508 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.h +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.h @@ -39,12 +39,9 @@ namespace AZ struct SourceBlendShapeInfo { AZStd::vector m_sceneNodeIndices; - - static AZStd::string GetMeshNodeName(const AZ::SceneAPI::Containers::SceneGraph& sceneGraph, - const AZ::SceneAPI::Containers::SceneGraph::NodeIndex& sceneNodeIndex); }; //! Retrieve all scene graph nodes per blend shape for all available blend shapes. - AZStd::unordered_map GetBlendShapeInfos(const AZ::SceneAPI::Containers::Scene& scene, const AZStd::optional& filterMeshName = AZStd::nullopt) const; + AZStd::unordered_map GetBlendShapeInfos(const AZ::SceneAPI::Containers::Scene& scene, const MeshData* meshData) const; //! Calculate position delta tolerance that is used to indicate whether a given vertex is part of the sparse set of morphed vertices //! or if it will be skipped and optimized out due to a hardly visible or no movement at all. From dcdd63966ed43ec80f56aca75c4ba9a80fcc201a Mon Sep 17 00:00:00 2001 From: Qing Tao <55564570+VickyAtAZ@users.noreply.github.com> Date: Fri, 4 Jun 2021 10:28:56 -0700 Subject: [PATCH 511/811] ATOM-15658 Better option of CreateCommonBuffer requires unique buffer name (#1133) * ATOM-15658 Better option of CreateCommonBuffer requires unique buffer name - Change the CreateCommonBuffer function to not require an unique name by default. - Remove the code for generating unique buffer names. - Add buffer name to BufferAsset so it can be used for device object name instead of using asset file name. - Change RPI::Buffer to use BufferName_AssetUuid as attachment id. --- .../Source/CoreLights/LightCullingPass.cpp | 7 +--- .../Source/CoreLights/LightCullingRemap.cpp | 7 +--- .../Common/Code/Source/Math/MathFilter.cpp | 1 + .../ExposureControlSettings.cpp | 11 +----- .../ExposureControl/ExposureControlSettings.h | 4 +- .../DepthOfFieldReadBackFocusDepthPass.cpp | 3 +- .../ExposureControlRenderProxy.cpp | 1 + .../PostProcessing/EyeAdaptationPass.cpp | 6 +-- .../LuminanceHistogramGeneratorPass.cpp | 7 +--- .../RayTracing/RayTracingFeatureProcessor.cpp | 8 +--- .../Source/SkyBox/SkyBoxFeatureProcessor.cpp | 2 +- .../TransformServiceFeatureProcessor.cpp | 6 +-- .../Code/Source/Utils/GpuBufferHandler.cpp | 4 +- .../Include/Atom/RPI.Public/Buffer/Buffer.h | 2 + .../Atom/RPI.Public/Buffer/BufferSystem.h | 2 +- .../RPI.Public/Buffer/BufferSystemInterface.h | 5 ++- .../Atom/RPI.Reflect/Buffer/BufferAsset.h | 4 ++ .../Model/ModelAssetBuilderComponent.cpp | 2 +- .../Code/Source/RPI.Public/Buffer/Buffer.cpp | 17 ++++++--- .../Source/RPI.Public/Buffer/BufferSystem.cpp | 27 ++++++++----- .../DynamicDraw/DynamicBufferAllocator.cpp | 2 +- .../Source/RPI.Reflect/Buffer/BufferAsset.cpp | 8 +++- .../RPI.Reflect/Buffer/BufferAssetCreator.cpp | 5 ++- .../RPI/Code/Tests/Buffer/BufferTests.cpp | 38 +++++++++++++++---- .../EMotionFXAtom/Code/Source/ActorAsset.cpp | 2 +- 25 files changed, 104 insertions(+), 77 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp index 987ed299b3..a9b43ef1e7 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp @@ -311,14 +311,9 @@ namespace AZ { auto tileBufferResolution = GetTileDataBufferResolution(); - // generate a UUID for the buffer name to keep it unique when there are multiple render pipelines - AZ::Uuid uuid = AZ::Uuid::CreateRandom(); - AZStd::string uuidString; - uuid.ToString(uuidString); - RPI::CommonBufferDescriptor desc; desc.m_poolType = RPI::CommonBufferPoolType::ReadWrite; - desc.m_bufferName = AZStd::string::format("LightList_%s", uuidString.c_str()); + desc.m_bufferName = "LightList"; desc.m_elementSize = sizeof(uint32_t); desc.m_byteCount = tileBufferResolution.m_width * tileBufferResolution.m_height * 256 * sizeof(uint32_t); m_lightList = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp index 42882cec6e..26e4ed9f6e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp @@ -118,14 +118,9 @@ namespace AZ void LightCullingRemap::CreateRemappedLightListBuffer() { - // generate a UUID for the buffer name to keep it unique when there are multiple render pipelines - AZ::Uuid uuid = AZ::Uuid::CreateRandom(); - AZStd::string uuidString; - uuid.ToString(uuidString); - RPI::CommonBufferDescriptor desc; desc.m_poolType = RPI::CommonBufferPoolType::ReadWrite; - desc.m_bufferName = AZStd::string::format("LightListRemapped_%s", uuidString.c_str()); + desc.m_bufferName = "LightListRemapped"; desc.m_elementSize = RHI::GetFormatSize(LightListRemappedFormat); desc.m_byteCount = m_tileDim.m_width * m_tileDim.m_height * NumBins * MaxLightsPerTile * desc.m_elementSize; m_lightListRemapped = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); diff --git a/Gems/Atom/Feature/Common/Code/Source/Math/MathFilter.cpp b/Gems/Atom/Feature/Common/Code/Source/Math/MathFilter.cpp index 8190c3af98..cb6f3e3522 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Math/MathFilter.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Math/MathFilter.cpp @@ -74,6 +74,7 @@ namespace AZ desc.m_elementFormat = filters.front()->GetElementFormat(); desc.m_byteCount = totalElementCount * elementSize; desc.m_bufferData = data.data(); + desc.m_isUniqueName = true; auto buffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcess/ExposureControl/ExposureControlSettings.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcess/ExposureControl/ExposureControlSettings.cpp index 056f7b7da4..288dd54e2b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcess/ExposureControl/ExposureControlSettings.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcess/ExposureControl/ExposureControlSettings.cpp @@ -100,16 +100,9 @@ namespace AZ bool ExposureControlSettings::InitCommonBuffer() { - // generate a UUID for the buffer name to keep it unique - AZ::Uuid uuid = AZ::Uuid::CreateRandom(); - AZStd::string uuidString; - uuid.ToString(uuidString); - - AZStd::string bufferName = AZStd::string::format("%s_%s", ExposureControlBufferBaseName, uuidString.c_str()); - RPI::CommonBufferDescriptor desc; desc.m_poolType = RPI::CommonBufferPoolType::Constant; - desc.m_bufferName = bufferName; + desc.m_bufferName = ExposureControlBufferName; desc.m_byteCount = sizeof(ShaderParameters); desc.m_elementSize = sizeof(ShaderParameters); @@ -117,7 +110,7 @@ namespace AZ if (!m_buffer) { - AZ_Assert(false, "Failed to create the RPI::Buffer[%s] which is used for the exposure control feature.", bufferName.c_str()); + AZ_Assert(false, "Failed to create the RPI::Buffer[%s] which is used for the exposure control feature.", desc.m_bufferName.c_str()); return false; } diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcess/ExposureControl/ExposureControlSettings.h b/Gems/Atom/Feature/Common/Code/Source/PostProcess/ExposureControl/ExposureControlSettings.h index 8344d6aa09..bfb4237b96 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcess/ExposureControl/ExposureControlSettings.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcess/ExposureControl/ExposureControlSettings.h @@ -28,8 +28,8 @@ namespace AZ { class PostProcessSettings; - // Base name of the buffer used for the exposure control feature. Usually distinct identifier will be added to this name for each exposure control settings. - static const char* const ExposureControlBufferBaseName = "ExposureControlBuffer"; + // Name of the buffer used for the exposure control feature + static const char* const ExposureControlBufferName = "ExposureControlBuffer"; // The post process sub-settings class for the exposure control feature class ExposureControlSettings final diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.cpp index abd916fcc9..c355b7c8a7 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.cpp @@ -47,9 +47,8 @@ namespace AZ m_getDepthPass = static_cast(pass.get()); // Create buffer for read back focus depth. We append static counter to avoid name conflicts. - AZStd::string bufferName = AZStd::string::format("DepthOfFieldReadBackAutoFocusDepthBuffer_%d", s_bufferInstance++); RPI::CommonBufferDescriptor desc; - desc.m_bufferName = bufferName; + desc.m_bufferName = "DepthOfFieldReadBackAutoFocusDepthBuffer"; desc.m_poolType = RPI::CommonBufferPoolType::ReadWrite; desc.m_byteCount = sizeof(float); desc.m_elementSize = aznumeric_cast(desc.m_byteCount); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/ExposureControlRenderProxy.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/ExposureControlRenderProxy.cpp index eb7a3b527f..c70d56aa90 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/ExposureControlRenderProxy.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/ExposureControlRenderProxy.cpp @@ -71,6 +71,7 @@ namespace AZ desc.m_bufferName = bufferName; desc.m_byteCount = sizeof(ShaderParameters); desc.m_elementSize = sizeof(ShaderParameters); + desc.m_isUniqueName = true; m_buffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); } diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.cpp index e7d4c47f02..bf293fd3d2 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/EyeAdaptationPass.cpp @@ -34,7 +34,7 @@ namespace AZ { namespace Render { - static const char* const EyeAdaptationBufferBaseName = "EyeAdaptationBuffer"; + static const char* const EyeAdaptationBufferName = "EyeAdaptationBuffer"; RPI::Ptr EyeAdaptationPass::Create(const RPI::PassDescriptor& descriptor) { @@ -49,12 +49,10 @@ namespace AZ void EyeAdaptationPass::InitBuffer() { - AZStd::string bufferName = AZStd::string::format("%s_%p", EyeAdaptationBufferBaseName, this); - ExposureCalculationData defaultData; RPI::CommonBufferDescriptor desc; desc.m_poolType = RPI::CommonBufferPoolType::ReadWrite; - desc.m_bufferName = bufferName; + desc.m_bufferName = EyeAdaptationBufferName; desc.m_byteCount = sizeof(ExposureCalculationData); desc.m_elementSize = aznumeric_cast(desc.m_byteCount); desc.m_bufferData = &defaultData; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp index 758c21bc4e..715ebf2945 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LuminanceHistogramGeneratorPass.cpp @@ -62,14 +62,9 @@ namespace AZ void LuminanceHistogramGeneratorPass::CreateHistogramBuffer() { - // generate a UUID for the buffer name to keep it unique when there are multiple render pipelines - AZ::Uuid uuid = AZ::Uuid::CreateRandom(); - AZStd::string uuidString; - uuid.ToString(uuidString); - RPI::CommonBufferDescriptor desc; desc.m_poolType = RPI::CommonBufferPoolType::ReadWrite; - desc.m_bufferName = AZStd::string::format("LuminanceHistogramBuffer_%s", uuidString.c_str()); + desc.m_bufferName = "LuminanceHistogramBuffer"; desc.m_elementSize = sizeof(uint32_t); desc.m_byteCount = NumHistogramBins * sizeof(uint32_t); desc.m_elementFormat = RHI::Format::R32_UINT; diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp index 10c7c2d378..2db396e36d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp @@ -210,12 +210,10 @@ namespace AZ if (m_meshInfoBuffer == nullptr) { - AZStd::string uuidString = AZ::Uuid::CreateRandom().ToString(); - // allocate the MeshInfo structured buffer RPI::CommonBufferDescriptor desc; desc.m_poolType = RPI::CommonBufferPoolType::ReadOnly; - desc.m_bufferName = AZStd::string::format("RayTracingMeshInfo_%s", uuidString.c_str()); + desc.m_bufferName = "RayTracingMeshInfo"; desc.m_byteCount = newMeshByteCount; desc.m_elementSize = sizeof(MeshInfo); m_meshInfoBuffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); @@ -283,12 +281,10 @@ namespace AZ if (m_materialInfoBuffer == nullptr) { - AZStd::string uuidString = AZ::Uuid::CreateRandom().ToString(); - // allocate the MaterialInfo structured buffer RPI::CommonBufferDescriptor desc; desc.m_poolType = RPI::CommonBufferPoolType::ReadOnly; - desc.m_bufferName = AZStd::string::format("RayTracingMaterialInfo_%s", uuidString.c_str()); + desc.m_bufferName = "RayTracingMaterialInfo"; desc.m_byteCount = newMaterialByteCount; desc.m_elementSize = sizeof(MaterialInfo); m_materialInfoBuffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); diff --git a/Gems/Atom/Feature/Common/Code/Source/SkyBox/SkyBoxFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/SkyBox/SkyBoxFeatureProcessor.cpp index 058e243fb7..4a3586a799 100644 --- a/Gems/Atom/Feature/Common/Code/Source/SkyBox/SkyBoxFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/SkyBox/SkyBoxFeatureProcessor.cpp @@ -193,7 +193,7 @@ namespace AZ RPI::CommonBufferDescriptor desc; desc.m_poolType = RPI::CommonBufferPoolType::Constant; - desc.m_bufferName = AZStd::string::format("SkyboxBuffer_%p", this); + desc.m_bufferName = "SkyboxBuffer"; desc.m_byteCount = byteCount; desc.m_elementSize = byteCount; desc.m_bufferData = &m_physicalSkyData; diff --git a/Gems/Atom/Feature/Common/Code/Source/TransformService/TransformServiceFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/TransformService/TransformServiceFeatureProcessor.cpp index fb73d0f416..074b09e35d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/TransformService/TransformServiceFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/TransformService/TransformServiceFeatureProcessor.cpp @@ -89,13 +89,13 @@ namespace AZ // Create the transform buffer, grow by powers of two RPI::CommonBufferDescriptor desc2; desc2.m_poolType = RPI::CommonBufferPoolType::ReadOnly; - desc2.m_bufferName = AZStd::string::format("'m_objectToWorldBuffer_%" PRIXPTR, reinterpret_cast(this)); + desc2.m_bufferName = "m_objectToWorldBuffer"; desc2.m_byteCount = byteCount; desc2.m_elementSize = elementSize; m_objectToWorldBuffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc2); - desc2.m_bufferName = AZStd::string::format("'m_objectToWorldHistoryBuffer_%p", this); + desc2.m_bufferName = "m_objectToWorldHistoryBuffer"; m_objectToWorldHistoryBuffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc2); } else @@ -119,7 +119,7 @@ namespace AZ // Create the normal buffer, grow by powers of two RPI::CommonBufferDescriptor desc2; desc2.m_poolType = RPI::CommonBufferPoolType::ReadOnly; - desc2.m_bufferName = AZStd::string::format("'m_objectToWorldInverseTransposeBuffer_%" PRIXPTR, reinterpret_cast(this)); + desc2.m_bufferName = "m_objectToWorldInverseTransposeBuffer"; desc2.m_byteCount = byteCount; desc2.m_elementSize = elementSize; diff --git a/Gems/Atom/Feature/Common/Code/Source/Utils/GpuBufferHandler.cpp b/Gems/Atom/Feature/Common/Code/Source/Utils/GpuBufferHandler.cpp index 13a151f8ac..db78247251 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Utils/GpuBufferHandler.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Utils/GpuBufferHandler.cpp @@ -40,13 +40,11 @@ namespace AZ if (m_bufferIndex.IsValid()) { - AZStd::string bufferName = AZStd::string::format("%s_%" PRIXPTR, descriptor.m_bufferName.c_str(), reinterpret_cast(this)); - uint32_t byteCount = RHI::NextPowerOfTwo(GetMax(BufferMinSize, m_elementCount * m_elementSize)); RPI::CommonBufferDescriptor desc; desc.m_poolType = RPI::CommonBufferPoolType::ReadOnly; - desc.m_bufferName = bufferName; + desc.m_bufferName = descriptor.m_bufferName; desc.m_byteCount = byteCount; desc.m_elementSize = descriptor.m_elementSize; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/Buffer.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/Buffer.h index 3fef502e92..df24c7591b 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/Buffer.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/Buffer.h @@ -112,6 +112,8 @@ namespace AZ AZStd::mutex m_pendingUploadMutex; RHI::BufferViewDescriptor m_bufferViewDescriptor; + + RHI::AttachmentId m_attachmentId; }; template diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystem.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystem.h index c4b6aa74b4..9f5b150752 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystem.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystem.h @@ -35,7 +35,7 @@ namespace AZ // BufferSystemInterface overrides... RHI::Ptr GetCommonBufferPool(CommonBufferPoolType poolType) override; Data::Instance CreateBufferFromCommonPool(const CommonBufferDescriptor& descriptor) override; - Data::Instance FindCommonBuffer(AZStd::string_view bufferName) override; + Data::Instance FindCommonBuffer(AZStd::string_view uniqueBufferName) override; void Init(); void Shutdown(); diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystemInterface.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystemInterface.h index 1469eed060..39b4b09691 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystemInterface.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystemInterface.h @@ -53,6 +53,9 @@ namespace AZ RHI::Format m_elementFormat = RHI::Format::Unknown; // CreateBufferFromCommonPool(const CommonBufferDescriptor& descriptor) = 0; //! Find a buffer by name. The buffer has to be created by CreateBufferFromCommonPool function - virtual Data::Instance FindCommonBuffer(AZStd::string_view bufferName) = 0; + virtual Data::Instance FindCommonBuffer(AZStd::string_view uniqueBufferName) = 0; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Buffer/BufferAsset.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Buffer/BufferAsset.h index d8a6fbb44d..4776933de6 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Buffer/BufferAsset.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Buffer/BufferAsset.h @@ -60,11 +60,15 @@ namespace AZ const Data::Asset& GetPoolAsset() const; CommonBufferPoolType GetCommonPoolType() const; + + const AZStd::string& GetName() const; private: // Called by asset creators to assign the asset to a ready state. void SetReady(); + AZStd::string m_name; + AZStd::vector m_buffer; RHI::BufferDescriptor m_bufferDescriptor; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp index ea2bdd0d83..f559a0aba6 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp @@ -114,7 +114,7 @@ namespace AZ if (auto* serialize = azrtti_cast(context)) { serialize->Class() - ->Version(26); // [ATOM-14992] + ->Version(27); // [ATOM-15658] } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp index 470b66c28e..81f02b7435 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp @@ -32,10 +32,6 @@ namespace AZ auto buffer = Data::InstanceDatabase::Instance().FindOrCreate( Data::InstanceId::CreateFromAssetId(bufferAsset.GetId()), bufferAsset); - if (buffer && buffer->m_rhiBuffer) - { - buffer->m_rhiBuffer->SetName(Name(bufferAsset.GetHint())); - } return buffer; } @@ -170,6 +166,16 @@ namespace AZ return resultCode; } } + + m_rhiBuffer->SetName(Name(bufferAsset.GetName())); + + // Only generate buffer's attachment id if the buffer is writable + if (RHI::CheckBitsAny(m_rhiBuffer->GetDescriptor().m_bindFlags, + RHI::BufferBindFlags::ShaderWrite | RHI::BufferBindFlags::CopyWrite | RHI::BufferBindFlags::DynamicInputAssembly)) + { + // attachment id = bufferName_bufferInstanceId + m_attachmentId = Name(bufferAsset.GetName() + "_" + bufferAsset.GetId().m_guid.ToString(false, false)); + } return RHI::ResultCode::Success; } @@ -312,7 +318,8 @@ namespace AZ const RHI::AttachmentId& Buffer::GetAttachmentId() const { - return m_rhiBuffer->GetName(); + AZ_Assert(!m_attachmentId.GetStringView().empty(), "Read-only buffer doesn't need attachment id"); + return m_attachmentId; } const RHI::BufferViewDescriptor& Buffer::GetBufferViewDescriptor() const diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp index 9a9254b0d6..c4b4b28d44 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp @@ -152,15 +152,22 @@ namespace AZ } Data::Instance BufferSystem::CreateBufferFromCommonPool(const CommonBufferDescriptor& descriptor) - { - Uuid bufferId = Uuid::CreateName(descriptor.m_bufferName.c_str()); - - // Report error if there is a buffer with same name. - // Note: this shouldn't return the existing buffer because users are expecting a newly created buffer. - if (Data::InstanceDatabase::Instance().Find(Data::InstanceId(bufferId))) + { + Uuid bufferId; + if (descriptor.m_isUniqueName) { - AZ_Error("BufferSystem", false, "Buffer with same name '%s' already exist", descriptor.m_bufferName.c_str()); - return nullptr; + bufferId = Uuid::CreateName(descriptor.m_bufferName.c_str()); + // Report error if there is a buffer with same name. + // Note: this shouldn't return the existing buffer because users are expecting a newly created buffer. + if (Data::InstanceDatabase::Instance().Find(Data::InstanceId(bufferId))) + { + AZ_Error("BufferSystem", false, "Buffer with same name '%s' already exist", descriptor.m_bufferName.c_str()); + return nullptr; + } + } + else + { + bufferId = Uuid::CreateRandom(); } RHI::Ptr bufferPool = GetCommonBufferPool(descriptor.m_poolType); @@ -207,9 +214,9 @@ namespace AZ return nullptr; } - Data::Instance BufferSystem::FindCommonBuffer(AZStd::string_view bufferName) + Data::Instance BufferSystem::FindCommonBuffer(AZStd::string_view uniqueBufferName) { - Uuid bufferId = Uuid::CreateName(bufferName.data()); + Uuid bufferId = Uuid::CreateName(uniqueBufferName.data()); return Data::InstanceDatabase::Instance().Find(Data::InstanceId(bufferId)); } } // namespace RPI diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicBufferAllocator.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicBufferAllocator.cpp index e79aa2e1bb..627b1e9912 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicBufferAllocator.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicBufferAllocator.cpp @@ -30,7 +30,7 @@ namespace AZ // Create the ring buffer from common pool RPI::CommonBufferDescriptor desc; desc.m_poolType = RPI::CommonBufferPoolType::DynamicInputAssembly; - desc.m_bufferName = AZStd::string::format("DyanmicBufferRing_%p", this); + desc.m_bufferName = "DyanmicBufferRing"; desc.m_elementSize = 1; desc.m_byteCount = ringBufferSize; m_ringBuffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Buffer/BufferAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Buffer/BufferAsset.cpp index 6f9d3a9d64..69444ae466 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Buffer/BufferAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Buffer/BufferAsset.cpp @@ -30,7 +30,8 @@ namespace AZ if (auto* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(1) + ->Version(2) + ->Field("Name", &BufferAsset::m_name) ->Field("Buffer", &BufferAsset::m_buffer) ->Field("BufferDescriptor", &BufferAsset::m_bufferDescriptor) ->Field("BufferViewDescriptor", &BufferAsset::m_bufferViewDescriptor) @@ -80,5 +81,10 @@ namespace AZ { return m_poolType; } + + const AZStd::string& BufferAsset::GetName() const + { + return m_name; + } } //namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Buffer/BufferAssetCreator.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Buffer/BufferAssetCreator.cpp index 486be9860e..4bd1b53f57 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Buffer/BufferAssetCreator.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Buffer/BufferAssetCreator.cpp @@ -152,7 +152,10 @@ namespace AZ void BufferAssetCreator::SetBufferName(AZStd::string_view name) { - m_asset.SetHint(name); + if (ValidateIsReady()) + { + m_asset->m_name = name; + } } bool BufferAssetCreator::Clone(const Data::Asset& sourceAsset, Data::Asset& clonedResult, Data::AssetId& inOutLastCreatedAssetId) diff --git a/Gems/Atom/RPI/Code/Tests/Buffer/BufferTests.cpp b/Gems/Atom/RPI/Code/Tests/Buffer/BufferTests.cpp index df3af5f0d2..261b57a568 100644 --- a/Gems/Atom/RPI/Code/Tests/Buffer/BufferTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Buffer/BufferTests.cpp @@ -474,6 +474,7 @@ namespace UnitTest desc.m_poolType = RPI::CommonBufferPoolType::ReadOnly; desc.m_bufferName = "Buffer1"; desc.m_byteCount = bufferInfo.m_bufferDescriptor.m_byteCount; + desc.m_isUniqueName = true; Data::Instance bufferInst = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); // buffer created @@ -488,8 +489,33 @@ namespace UnitTest EXPECT_EQ(bufferFound2.get(), nullptr); } - // Failed if creates a buffer with duplicated name with existing buffer - TEST_F(BufferTests, BufferSystem_CreateDuplicatedNamedBuffer_Fail) + // Failed if creates a buffe which has a same name with existing buffer + // and has m_isUniqueName is enabled + TEST_F(BufferTests, BufferSystem_CreateDuplicatedNamedBufferEnableUniqueName_Fail) + { + using namespace AZ; + + ExpectedBuffer bufferInfo = CreateValidBuffer(); + + RPI::CommonBufferDescriptor desc; + desc.m_poolType = RPI::CommonBufferPoolType::ReadOnly; + desc.m_bufferName = "Buffer1"; + desc.m_byteCount = bufferInfo.m_bufferDescriptor.m_byteCount; + desc.m_isUniqueName = true; + + Data::Instance bufferInst = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); + // buffer created + EXPECT_NE(bufferInst.get(), nullptr); + + AZ_TEST_START_ASSERTTEST; + Data::Instance bufferInst2 = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); + AZ_TEST_STOP_ASSERTTEST(1); + // buffer NOT created + EXPECT_EQ(bufferInst2.get(), nullptr); + } + + // create a buffer which has a same name with existing buffer + TEST_F(BufferTests, BufferSystem_CreateDuplicatedNamedBuffers_Success) { using namespace AZ; @@ -503,12 +529,10 @@ namespace UnitTest Data::Instance bufferInst = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); // buffer created EXPECT_NE(bufferInst.get(), nullptr); - - AZ_TEST_START_ASSERTTEST; + Data::Instance bufferInst2 = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); - AZ_TEST_STOP_ASSERTTEST(1); - // buffer NOT created - EXPECT_EQ(bufferInst2.get(), nullptr); + // buffer created + EXPECT_NE(bufferInst2.get(), nullptr); } // Buffer instance creation unit tests diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp index 8dc7f9387c..9f68a7d12c 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp @@ -595,7 +595,7 @@ namespace AZ // Create a buffer and populate it with the transforms RPI::CommonBufferDescriptor descriptor; descriptor.m_bufferData = boneTransforms.data(); - descriptor.m_bufferName = AZStd::string::format("BoneTransformBuffer_%s_%s", actorInstance->GetActor()->GetName(), Uuid::CreateRandom().ToString().c_str()); + descriptor.m_bufferName = AZStd::string::format("BoneTransformBuffer_%s", actorInstance->GetActor()->GetName()); descriptor.m_byteCount = boneTransforms.size() * sizeof(float); descriptor.m_elementSize = floatsPerBone * sizeof(float); descriptor.m_poolType = RPI::CommonBufferPoolType::ReadOnly; From 76a6df341b0b05eafb53f4977cd706a80a3b2b3d Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 4 Jun 2021 10:51:47 -0700 Subject: [PATCH 512/811] SPEC-2513 Fixes to enable w4457 --- .../UdpTransport/UdpFragmentQueue.cpp | 4 +- Code/Sandbox/Editor/CVarMenu.cpp | 14 ++-- .../Editor/TrackView/TrackViewAnimNode.cpp | 4 +- .../Editor/TrackView/TrackViewTrack.cpp | 6 +- .../Vulkan/Code/Source/RHI/DescriptorSet.cpp | 4 +- .../Window/ShaderManagementConsoleWindow.cpp | 4 +- .../Source/Editor/QATLControlsTreeModel.cpp | 8 +- .../EMotionFX/Rendering/Common/RenderUtil.cpp | 12 +-- .../EMotionFX/Source/MultiThreadScheduler.cpp | 4 +- .../PropertyWidgets/MotionDataHandler.cpp | 6 +- .../StaticLib/GraphCanvas/Styling/Parser.cpp | 80 +++++++++---------- .../GraphCanvas/Utils/GraphUtils.cpp | 6 +- Gems/GraphModel/Code/Source/Model/Graph.cpp | 4 +- .../Editor/Animation/UiAnimViewAnimNode.cpp | 12 +-- .../Code/Editor/Animation/UiAnimViewTrack.cpp | 6 +- .../MicrophoneSystemComponent_Windows.cpp | 22 ++--- .../NetworkEntity/NetworkEntityManager.cpp | 4 +- .../Widgets/NodePalette/NodePaletteModel.cpp | 12 +-- .../View/Windows/ScriptCanvasContextMenus.cpp | 4 +- .../Grammar/AbstractCodeModel.cpp | 10 +-- .../Internal/Nodes/ExpressionNodeBase.cpp | 6 +- .../Code/Source/Core/WhiteBoxToolApi.cpp | 16 ++-- .../Common/MSVC/Configurations_msvc.cmake | 1 - 23 files changed, 124 insertions(+), 125 deletions(-) diff --git a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpFragmentQueue.cpp b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpFragmentQueue.cpp index 2a90509187..042f19aa70 100644 --- a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpFragmentQueue.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpFragmentQueue.cpp @@ -139,7 +139,7 @@ namespace AzNetworking NetworkOutputSerializer networkSerializer(buffer.GetBuffer(), buffer.GetSize()); { - ISerializer& serializer = networkSerializer; // To get the default typeinfo parameters in ISerializer + ISerializer& networkISerializer = networkSerializer; // To get the default typeinfo parameters in ISerializer // First, serialize out the header if (!header.SerializePacketFlags(networkSerializer)) @@ -148,7 +148,7 @@ namespace AzNetworking return false; } - if (!serializer.Serialize(header, "Header")) + if (!networkISerializer.Serialize(header, "Header")) { AZLOG(NET_FragmentQueue, "Reconstructed fragmented packet failed header serialization"); return false; diff --git a/Code/Sandbox/Editor/CVarMenu.cpp b/Code/Sandbox/Editor/CVarMenu.cpp index f3dd4cf065..bbce0c63fc 100644 --- a/Code/Sandbox/Editor/CVarMenu.cpp +++ b/Code/Sandbox/Editor/CVarMenu.cpp @@ -118,10 +118,10 @@ void CVarMenu::AddUniqueCVarsItem(QString displayName, // Otherwise we could have just used the action's currently checked // state and updated the CVar's value only bool cVarOn = (cVar->GetFVal() == availableCVar.m_onValue); - bool checked = !cVarOn; - SetCVar(cVar, checked ? availableCVar.m_onValue : availableCVar.m_offValue); - action->setChecked(checked); - if (checked) + bool cVarChecked = !cVarOn; + SetCVar(cVar, cVarChecked ? availableCVar.m_onValue : availableCVar.m_offValue); + action->setChecked(cVarChecked); + if (cVarChecked) { // Set the rest of the CVars in the group to their off values SetCVarsToOffValue(availableCVars, availableCVar); @@ -132,9 +132,9 @@ void CVarMenu::AddUniqueCVarsItem(QString displayName, // Initialize the action's checked state based on its associated CVar's current value ICVar* cVar = gEnv->pConsole->GetCVar(availableCVar.m_cVarName.toUtf8().data()); - bool checked = (cVar && cVar->GetFVal() == availableCVar.m_onValue); - action->setChecked(checked); - if (checked) + bool cVarChecked = (cVar && cVar->GetFVal() == availableCVar.m_onValue); + action->setChecked(cVarChecked); + if (cVarChecked) { // Set the rest of the CVars in the group to their off values SetCVarsToOffValue(availableCVars, availableCVar); diff --git a/Code/Sandbox/Editor/TrackView/TrackViewAnimNode.cpp b/Code/Sandbox/Editor/TrackView/TrackViewAnimNode.cpp index 35306b9535..2b4622f5ec 100644 --- a/Code/Sandbox/Editor/TrackView/TrackViewAnimNode.cpp +++ b/Code/Sandbox/Editor/TrackView/TrackViewAnimNode.cpp @@ -205,10 +205,10 @@ CTrackViewAnimNode::CTrackViewAnimNode(IAnimSequence* pSequence, IAnimNode* anim for (int i = 0; i < nodeCount; ++i) { IAnimNode* node = pSequence->GetNode(i); - IAnimNode* pParentNode = node->GetParent(); + IAnimNode* pNodeParentNode = node->GetParent(); // If our node is the parent, then the current node is a child of it - if (animNode == pParentNode) + if (animNode == pNodeParentNode) { CTrackViewAnimNodeFactory animNodeFactory; CTrackViewAnimNode* pNewTVAnimNode = animNodeFactory.BuildAnimNode(pSequence, node, this); diff --git a/Code/Sandbox/Editor/TrackView/TrackViewTrack.cpp b/Code/Sandbox/Editor/TrackView/TrackViewTrack.cpp index 94559921c3..76a836f86c 100644 --- a/Code/Sandbox/Editor/TrackView/TrackViewTrack.cpp +++ b/Code/Sandbox/Editor/TrackView/TrackViewTrack.cpp @@ -68,12 +68,12 @@ CTrackViewTrack::CTrackViewTrack(IAnimTrack* pTrack, CTrackViewAnimNode* pTrackA { // Search for child tracks const unsigned int subTrackCount = m_pAnimTrack->GetSubTrackCount(); - for (unsigned int subTrackIndex = 0; subTrackIndex < subTrackCount; ++subTrackIndex) + for (unsigned int subTrackI = 0; subTrackI < subTrackCount; ++subTrackI) { - IAnimTrack* pSubTrack = m_pAnimTrack->GetSubTrack(subTrackIndex); + IAnimTrack* pSubTrack = m_pAnimTrack->GetSubTrack(subTrackI); CTrackViewTrackFactory trackFactory; - CTrackViewTrack* pNewTVTrack = trackFactory.BuildTrack(pSubTrack, pTrackAnimNode, this, true, subTrackIndex); + CTrackViewTrack* pNewTVTrack = trackFactory.BuildTrack(pSubTrack, pTrackAnimNode, this, true, subTrackI); m_childNodes.push_back(std::unique_ptr(pNewTVTrack)); } diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp index 634f5a51ac..37f1e31542 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp @@ -261,8 +261,8 @@ namespace AZ if (vulkanDescriptor.m_constantDataPool && constantDataSize) { m_constantDataBuffer = Buffer::Create(); - const RHI::BufferDescriptor descriptor(RHI::BufferBindFlags::Constant, constantDataSize); - RHI::BufferInitRequest request(*m_constantDataBuffer, descriptor); + const RHI::BufferDescriptor bufferDescriptor(RHI::BufferBindFlags::Constant, constantDataSize); + RHI::BufferInitRequest request(*m_constantDataBuffer, bufferDescriptor); RHI::ResultCode rhiResult = vulkanDescriptor.m_constantDataPool->InitBuffer(request); if (rhiResult != RHI::ResultCode::Success) { diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index 6ab297bfc5..08d406884f 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -510,9 +510,9 @@ namespace ShaderManagementConsole AZStd::vector documentIdsToClose; documentIdsToClose.reserve(m_tabWidget->count()); const AZ::Uuid documentIdToKeepOpen = GetDocumentIdFromTab(tabIndex); - for (int tabIndex = 0; tabIndex < m_tabWidget->count(); ++tabIndex) + for (int tabI = 0; tabI < m_tabWidget->count(); ++tabI) { - const AZ::Uuid documentId = GetDocumentIdFromTab(tabIndex); + const AZ::Uuid documentId = GetDocumentIdFromTab(tabI); if (documentId != documentIdToKeepOpen) { documentIdsToClose.push_back(documentId); diff --git a/Gems/AudioSystem/Code/Source/Editor/QATLControlsTreeModel.cpp b/Gems/AudioSystem/Code/Source/Editor/QATLControlsTreeModel.cpp index d05f7830a4..32446237a3 100644 --- a/Gems/AudioSystem/Code/Source/Editor/QATLControlsTreeModel.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/QATLControlsTreeModel.cpp @@ -287,9 +287,9 @@ namespace AudioControls QDataStream stream(&encoded, QIODevice::ReadOnly); while (!stream.atEnd()) { - int row, col; + int streamRow, streamCol; QMap roleDataMap; - stream >> row >> col >> roleDataMap; + stream >> streamRow >> streamCol >> roleDataMap; if (!roleDataMap.isEmpty()) { // If dropping a folder, make sure that folder name doesn't already exist where it is being dropped @@ -341,9 +341,9 @@ namespace AudioControls { QByteArray data = mimeData->data(format); QDataStream stream(&data, QIODevice::ReadOnly); - int row, col; + int streamRow, streamCol; QMap roleDataMap; - stream >> row >> col >> roleDataMap; + stream >> streamRow >> streamCol >> roleDataMap; if (!roleDataMap.isEmpty() && roleDataMap[eDR_TYPE] != eIT_FOLDER) { return false; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp index b2389a3086..90752c7604 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp @@ -1628,18 +1628,18 @@ namespace MCommon } else { - const float screenWidth = static_cast(camera->GetScreenWidth()); - const float screenHeight = static_cast(camera->GetScreenHeight()); + const float cameraScreenWidth = static_cast(camera->GetScreenWidth()); + const float cameraScreenHeight = static_cast(camera->GetScreenHeight()); // find the 4 corners of the frustum AZ::Vector3 corners[4]; const AZ::Matrix4x4 inversedProjectionMatrix = MCore::InvertProjectionMatrix(camera->GetProjectionMatrix()); const AZ::Matrix4x4 inversedViewMatrix = MCore::InvertProjectionMatrix(camera->GetViewMatrix()); - corners[0] = MCore::Unproject(0.0f, 0.0f, screenWidth, screenHeight, camera->GetFarClipDistance(), inversedProjectionMatrix, inversedViewMatrix); - corners[1] = MCore::Unproject(screenWidth, 0.0f, screenWidth, screenHeight, camera->GetFarClipDistance(), inversedProjectionMatrix, inversedViewMatrix); - corners[2] = MCore::Unproject(screenWidth, screenHeight, screenWidth, screenHeight, camera->GetFarClipDistance(), inversedProjectionMatrix, inversedViewMatrix); - corners[3] = MCore::Unproject(0.0f, screenHeight, screenWidth, screenHeight, camera->GetFarClipDistance(), inversedProjectionMatrix, inversedViewMatrix); + corners[0] = MCore::Unproject(0.0f, 0.0f, cameraScreenWidth, cameraScreenHeight, camera->GetFarClipDistance(), inversedProjectionMatrix, inversedViewMatrix); + corners[1] = MCore::Unproject(cameraScreenWidth, 0.0f, cameraScreenWidth, cameraScreenHeight, camera->GetFarClipDistance(), inversedProjectionMatrix, inversedViewMatrix); + corners[2] = MCore::Unproject(cameraScreenWidth, cameraScreenHeight, cameraScreenWidth, cameraScreenHeight, camera->GetFarClipDistance(), inversedProjectionMatrix, inversedViewMatrix); + corners[3] = MCore::Unproject(0.0f, cameraScreenHeight, cameraScreenWidth, cameraScreenHeight, camera->GetFarClipDistance(), inversedProjectionMatrix, inversedViewMatrix); // calculate the intersection points with the ground plane and create an AABB around those // if there is no intersection point then use the ray target as point, which is the projection onto the far plane basically diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp index 327f9d27ae..1094ad72a3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp @@ -319,9 +319,9 @@ namespace EMotionFX step.mDependencies.Clear(false); // calculate the new dependencies for this step - for (ActorInstance* actorInstance : step.mActorInstances) + for (ActorInstance* stepActorInstance : step.mActorInstances) { - AddDependenciesToStep(actorInstance, &step); + AddDependenciesToStep(stepActorInstance, &step); } // assume that there is only one of the same actor instance in the whole schedule diff --git a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/MotionDataHandler.cpp b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/MotionDataHandler.cpp index 7597cb888d..6060a81bd0 100644 --- a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/MotionDataHandler.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/MotionDataHandler.cpp @@ -91,10 +91,10 @@ namespace EMotionFX } else { - AZ::Outcome index = factory.FindRegisteredIndexByTypeId(instance); - if (index.IsSuccess()) + AZ::Outcome motionIndex = factory.FindRegisteredIndexByTypeId(instance); + if (motionIndex.IsSuccess()) { - GUI->setCurrentIndex(static_cast(index.GetValue() + 1)); // +1 because we inserted an 'Automatic' one as first entry. + GUI->setCurrentIndex(static_cast(motionIndex.GetValue() + 1)); // +1 because we inserted an 'Automatic' one as first entry. } else { diff --git a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/Parser.cpp b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/Parser.cpp index db07c3ca8e..23d28857e1 100644 --- a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/Parser.cpp +++ b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/Parser.cpp @@ -725,23 +725,23 @@ namespace GraphCanvas case Attribute::LineColor: case Attribute::StripeColor: { - QString value(member->value.GetString()); + QString valueStr(member->value.GetString()); - if (IsColorValid(value)) + if (IsColorValid(valueStr)) { - style->SetAttribute(attribute, ParseColor(value)); + style->SetAttribute(attribute, ParseColor(valueStr)); } break; } case Attribute::BackgroundImage: { - QString value(member->value.GetString()); + QString valueStr(member->value.GetString()); - if (value.startsWith(QStringLiteral(":/"))) + if (valueStr.startsWith(QStringLiteral(":/"))) { - value = QString("qrc%1").arg(value); + valueStr = QString("qrc%1").arg(valueStr); } - QUrl url(value); + QUrl url(valueStr); if (url.isValid()) { style->SetAttribute(attribute, url); @@ -844,103 +844,103 @@ namespace GraphCanvas case Attribute::BorderStyle: case Attribute::LineStyle: { - QString value(member->value.GetString()); + QString valueStr(member->value.GetString()); - if (IsLineStyleValid(value)) + if (IsLineStyleValid(valueStr)) { - style->SetAttribute(attribute, QVariant::fromValue(ParseLineStyle(value))); + style->SetAttribute(attribute, QVariant::fromValue(ParseLineStyle(valueStr))); } break; } case Attribute::LineCurve: { - QString value(member->value.GetString()); + QString valueStr(member->value.GetString()); - if (IsLineCurveValid(value)) + if (IsLineCurveValid(valueStr)) { - style->SetAttribute(attribute, QVariant::fromValue(ParseLineCurve(value))); + style->SetAttribute(attribute, QVariant::fromValue(ParseLineCurve(valueStr))); } break; } case Attribute::CapStyle: { - QString value(member->value.GetString()); + QString valueStr(member->value.GetString()); - if (IsCapStyleValid(value)) + if (IsCapStyleValid(valueStr)) { - style->SetAttribute(attribute, QVariant::fromValue(ParseCapStyle(value))); + style->SetAttribute(attribute, QVariant::fromValue(ParseCapStyle(valueStr))); } break; } case Attribute::FontFamily: { - QString value(member->value.GetString()); + QString valueStr(member->value.GetString()); - if (QString::compare(value, QLatin1String("default"), Qt::CaseInsensitive) == 0) + if (QString::compare(valueStr, QLatin1String("default"), Qt::CaseInsensitive) == 0) { - value = defaultFontInfo.family(); + valueStr = defaultFontInfo.family(); } else { - QFont font(value); + QFont font(valueStr); QFontInfo info(font); if (!info.exactMatch()) { - qWarning() << "Invalid font-family:" << value; + qWarning() << "Invalid font-family:" << valueStr; } } - style->SetAttribute(attribute, value); + style->SetAttribute(attribute, valueStr); } case Attribute::FontStyle: { - QString value(member->value.GetString()); + QString valueStr(member->value.GetString()); - if (QString::compare(value, QLatin1String("default"), Qt::CaseInsensitive) == 0) + if (QString::compare(valueStr, QLatin1String("default"), Qt::CaseInsensitive) == 0) { style->SetAttribute(attribute, defaultFontInfo.style()); } else { - if (IsFontStyleValid(value)) + if (IsFontStyleValid(valueStr)) { - style->SetAttribute(attribute, ParseFontStyle(value)); + style->SetAttribute(attribute, ParseFontStyle(valueStr)); } } break; } case Attribute::FontWeight: { - QString value(member->value.GetString()); + QString valueStr(member->value.GetString()); - if (QString::compare(value, QLatin1String("default"), Qt::CaseInsensitive) == 0) + if (QString::compare(valueStr, QLatin1String("default"), Qt::CaseInsensitive) == 0) { style->SetAttribute(attribute, defaultFontInfo.weight()); } else { - if (IsFontWeightValid(value)) + if (IsFontWeightValid(valueStr)) { - style->SetAttribute(attribute, ParseFontWeight(value)); + style->SetAttribute(attribute, ParseFontWeight(valueStr)); } } break; } case Attribute::FontVariant: { - QString value(member->value.GetString()); + QString valueStr(member->value.GetString()); - if (QString::compare(value, QLatin1String("default"), Qt::CaseInsensitive) == 0) + if (QString::compare(valueStr, QLatin1String("default"), Qt::CaseInsensitive) == 0) { style->SetAttribute(attribute, defaultFont.capitalization()); } else { - if (IsFontVariantValid(value)) + if (IsFontVariantValid(valueStr)) { - style->SetAttribute(attribute, value); + style->SetAttribute(attribute, valueStr); } } break; @@ -965,23 +965,23 @@ namespace GraphCanvas break; case Attribute::PaletteStyle: { - QString value(member->value.GetString()); - style->SetAttribute(attribute, QVariant::fromValue(ParsePaletteStyle(value))); + QString valueStr(member->value.GetString()); + style->SetAttribute(attribute, QVariant::fromValue(ParsePaletteStyle(valueStr))); break; } case Attribute::PatternTemplate: case Attribute::PatternPalettes: { - QString value(member->value.GetString()); - style->SetAttribute(attribute, value); + QString valueStr(member->value.GetString()); + style->SetAttribute(attribute, valueStr); break; } case Attribute::Steps: { QList stepList; - QString value(member->value.GetString()); + QString valueStr(member->value.GetString()); - QStringList splitValues = value.split("|"); + QStringList splitValues = valueStr.split("|"); for (QString currentString : splitValues) { diff --git a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Utils/GraphUtils.cpp b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Utils/GraphUtils.cpp index c2574a69f6..16bc3dd86a 100644 --- a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Utils/GraphUtils.cpp +++ b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Utils/GraphUtils.cpp @@ -1325,12 +1325,12 @@ namespace GraphCanvas AZStd::vector< Endpoint > endpoints; SlotRequestBus::EventResult(endpoints, currentEndpoint.GetSlotId(), &SlotRequests::GetRemappedModelEndpoints); - for (const Endpoint& endpoint : endpoints) + for (const Endpoint& e : endpoints) { // If we haven't already processed the node, add it to our explore set so we can recurse. - if (retVal.count(endpoint) == 0) + if (retVal.count(e) == 0) { - exploreSet.insert(endpoint); + exploreSet.insert(e); } } } diff --git a/Gems/GraphModel/Code/Source/Model/Graph.cpp b/Gems/GraphModel/Code/Source/Model/Graph.cpp index 25ad61db2c..809679e9f6 100644 --- a/Gems/GraphModel/Code/Source/Model/Graph.cpp +++ b/Gems/GraphModel/Code/Source/Model/Graph.cpp @@ -279,8 +279,8 @@ namespace GraphModel m_connections.erase(iter); #if defined(AZ_ENABLE_TRACING) - auto iter = AZStd::find(m_connections.begin(), m_connections.end(), connection); - AZ_Assert(iter == m_connections.end(), "Graph is broken. The same connection object was found multiple times."); + auto iterConnection = AZStd::find(m_connections.begin(), m_connections.end(), connection); + AZ_Assert(iterConnection == m_connections.end(), "Graph is broken. The same connection object was found multiple times."); #endif return true; diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp index f99eea5fa2..37629fac37 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp @@ -110,10 +110,10 @@ CUiAnimViewAnimNode::CUiAnimViewAnimNode(IUiAnimSequence* pSequence, IUiAnimNode for (int i = 0; i < nodeCount; ++i) { IUiAnimNode* pNode = pSequence->GetNode(i); - IUiAnimNode* pParentNode = pNode->GetParent(); + IUiAnimNode* pNodeParentNode = pNode->GetParent(); // If our node is the parent, then the current node is a child of it - if (pAnimNode == pParentNode) + if (pAnimNode == pNodeParentNode) { CUiAnimViewAnimNodeFactory animNodeFactory; CUiAnimViewAnimNode* pNewUiAVAnimNode = animNodeFactory.BuildAnimNode(pSequence, pNode, this); @@ -510,20 +510,20 @@ bool CUiAnimViewAnimNode::BaseClassPropertyPotentiallyChanged( { for (const AZ::SerializeContext::ClassElement& baseElement : baseClassData->m_elements) { - size_t offset = baseClassOffset + baseElement.m_offset; + size_t baseOffset = baseClassOffset + baseElement.m_offset; if (baseElement.m_flags & AZ::SerializeContext::ClassElement::FLG_BASE_CLASS) { - if (BaseClassPropertyPotentiallyChanged(context, dstComponent, srcComponent, baseElement, offset)) + if (BaseClassPropertyPotentiallyChanged(context, dstComponent, srcComponent, baseElement, baseOffset)) { valueChanged = true; } } else { - if (HasComponentParamValueAzChanged(dstComponent, srcComponent, baseElement, offset)) + if (HasComponentParamValueAzChanged(dstComponent, srcComponent, baseElement, baseOffset)) { valueChanged = true; - AzEntityPropertyChanged(srcComponent, dstComponent, baseElement, offset); + AzEntityPropertyChanged(srcComponent, dstComponent, baseElement, baseOffset); } } } diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewTrack.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewTrack.cpp index 797154a50b..fc77a370d3 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewTrack.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewTrack.cpp @@ -59,12 +59,12 @@ CUiAnimViewTrack::CUiAnimViewTrack(IUiAnimTrack* pTrack, CUiAnimViewAnimNode* pT { // Search for child tracks const unsigned int subTrackCount = m_pAnimTrack->GetSubTrackCount(); - for (unsigned int subTrackIndex = 0; subTrackIndex < subTrackCount; ++subTrackIndex) + for (unsigned int subTrackI = 0; subTrackI < subTrackCount; ++subTrackI) { - IUiAnimTrack* pSubTrack = m_pAnimTrack->GetSubTrack(subTrackIndex); + IUiAnimTrack* pSubTrack = m_pAnimTrack->GetSubTrack(subTrackI); CUiAnimViewTrackFactory trackFactory; - CUiAnimViewTrack* pNewUiAVTrack = trackFactory.BuildTrack(pSubTrack, pTrackAnimNode, this, true, subTrackIndex); + CUiAnimViewTrack* pNewUiAVTrack = trackFactory.BuildTrack(pSubTrack, pTrackAnimNode, this, true, subTrackI); m_childNodes.push_back(std::unique_ptr(pNewUiAVTrack)); } diff --git a/Gems/Microphone/Code/Source/Platform/Windows/MicrophoneSystemComponent_Windows.cpp b/Gems/Microphone/Code/Source/Platform/Windows/MicrophoneSystemComponent_Windows.cpp index 2eb840b253..5a080084e1 100644 --- a/Gems/Microphone/Code/Source/Platform/Windows/MicrophoneSystemComponent_Windows.cpp +++ b/Gems/Microphone/Code/Source/Platform/Windows/MicrophoneSystemComponent_Windows.cpp @@ -422,12 +422,12 @@ namespace Audio if (stereoToMono) { // Samples are interleaved now, copy only left channel to the output - float* inputData = reinterpret_cast(m_conversionBufferIn.m_data); - float* outputData = reinterpret_cast(m_conversionBufferOut.m_data); + float* bufferInputData = reinterpret_cast(m_conversionBufferIn.m_data); + float* bufferOutputData = reinterpret_cast(m_conversionBufferOut.m_data); for (AZ::u32 frame = 0; frame < numFrames; ++frame) { - outputData[frame] = *inputData++; - ++inputData; + bufferOutputData[frame] = *bufferInputData++; + ++bufferInputData; } } else // monoToStereo @@ -435,21 +435,21 @@ namespace Audio // Split single samples to both left and right channels if (shouldDeinterleave) { - float* inputData = reinterpret_cast(m_conversionBufferIn.m_data); - float** outputData = reinterpret_cast(m_conversionBufferOut.m_data); + float* bufferInputData = reinterpret_cast(m_conversionBufferIn.m_data); + float** bufferOutputData = reinterpret_cast(m_conversionBufferOut.m_data); for (AZ::u32 frame = 0; frame < numFrames; ++frame) { - outputData[0][frame] = outputData[1][frame] = inputData[frame]; + bufferOutputData[0][frame] = bufferOutputData[1][frame] = bufferInputData[frame]; } } else { - float* inputData = reinterpret_cast(m_conversionBufferIn.m_data); - float* outputData = reinterpret_cast(m_conversionBufferOut.m_data); + float* bufferInputData = reinterpret_cast(m_conversionBufferIn.m_data); + float* bufferOutputData = reinterpret_cast(m_conversionBufferOut.m_data); for (AZ::u32 frame = 0; frame < numFrames; ++frame) { - *outputData++ = inputData[frame]; - *outputData++ = inputData[frame]; + *bufferOutputData++ = bufferInputData[frame]; + *bufferOutputData++ = bufferInputData[frame]; } } } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index eaf89f3489..b0f1b221e8 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -263,9 +263,9 @@ namespace Multiplayer // Validate that we aren't already planning to remove this entity if (safeToExit) { - for (auto entityId : m_removeList) + for (auto remoteEntityId : m_removeList) { - if (entityId == entityId) + if (remoteEntityId == remoteEntityId) { safeToExit = false; } diff --git a/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp b/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp index 8b00b5b71b..a5c0287cfd 100644 --- a/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp +++ b/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp @@ -340,31 +340,31 @@ namespace } // Pass in the associated class data so we can do more intensive lookups? - const AZ::SerializeContext::ClassData* classData = serializeContext.FindClassData(node.first); + const AZ::SerializeContext::ClassData* nodeClassData = serializeContext.FindClassData(node.first); - if (classData == nullptr) + if (nodeClassData == nullptr) { continue; } // Detect primitive types os we avoid making nodes out of them. // Or anything that is 'pure data' and should be populated through a different mechanism. - if (classData->m_azRtti && classData->m_azRtti->IsTypeOf()) + if (nodeClassData->m_azRtti && nodeClassData->m_azRtti->IsTypeOf()) { continue; } // Skip over some of our more dynamic nodes that we want to populate using different means - else if (classData->m_azRtti && classData->m_azRtti->IsTypeOf()) + else if (nodeClassData->m_azRtti && nodeClassData->m_azRtti->IsTypeOf()) { continue; } - else if (classData->m_azRtti && classData->m_azRtti->IsTypeOf()) + else if (nodeClassData->m_azRtti && nodeClassData->m_azRtti->IsTypeOf()) { continue; } else { - nodePaletteModel.RegisterCustomNode(categoryPath, node.first, node.second, classData); + nodePaletteModel.RegisterCustomNode(categoryPath, node.first, node.second, nodeClassData); } } diff --git a/Gems/ScriptCanvas/Code/Editor/View/Windows/ScriptCanvasContextMenus.cpp b/Gems/ScriptCanvas/Code/Editor/View/Windows/ScriptCanvasContextMenus.cpp index 428f5eb290..3c21701fb0 100644 --- a/Gems/ScriptCanvas/Code/Editor/View/Windows/ScriptCanvasContextMenus.cpp +++ b/Gems/ScriptCanvas/Code/Editor/View/Windows/ScriptCanvasContextMenus.cpp @@ -563,13 +563,13 @@ namespace ScriptCanvasEditor else if (slotType == GraphCanvas::SlotTypes::DataSlot) { const AZ::EntityId& slotId2 = GetTargetId(); - const GraphCanvas::GraphId& graphId = GetGraphId(); + const GraphCanvas::GraphId& graphId2 = GetGraphId(); GraphCanvas::Endpoint endpoint; GraphCanvas::SlotRequestBus::EventResult(endpoint, slotId2, &GraphCanvas::SlotRequests::GetEndpoint); bool promotedElement = false; - GraphCanvas::GraphModelRequestBus::EventResult(promotedElement, graphId, &GraphCanvas::GraphModelRequests::PromoteToVariableAction, endpoint); + GraphCanvas::GraphModelRequestBus::EventResult(promotedElement, graphId2, &GraphCanvas::GraphModelRequests::PromoteToVariableAction, endpoint); if (promotedElement) { diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp index db45f6bfe3..2a485c9501 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp @@ -4090,23 +4090,23 @@ namespace ScriptCanvas auto userFunctionIter = m_userInsThatRequireTopology.find(nodeling); if (userFunctionIter != m_userInsThatRequireTopology.end()) { - auto& node = *userFunctionIter->first; - auto outSlots = node.GetSlotsByType(CombinedSlotType::ExecutionOut); + auto& userFunctionNode = *userFunctionIter->first; + auto outSlots = userFunctionNode.GetSlotsByType(CombinedSlotType::ExecutionOut); if (outSlots.empty() || !outSlots.front()) { - AddError(node.GetEntityId(), nullptr, ScriptCanvas::ParseErrors::NoOutSlotInFunctionDefinitionStart); + AddError(userFunctionNode.GetEntityId(), nullptr, ScriptCanvas::ParseErrors::NoOutSlotInFunctionDefinitionStart); return; } - if (!ExecutionContainsCyclesCheck(node, *outSlots.front())) + if (!ExecutionContainsCyclesCheck(userFunctionNode, *outSlots.front())) { auto definition = userFunctionIter->second; auto entrySlot = definition->GetId().m_slot; AZ_Assert(entrySlot, "Bad accounting in user function definition node"); AZStd::vector returnValues; UserOutCallCollector userOutCallCollector; - TraverseExecutionConnections(node, *entrySlot, userOutCallCollector); + TraverseExecutionConnections(userFunctionNode, *entrySlot, userOutCallCollector); const AZStd::unordered_set& uniqueNodelingsOut = userOutCallCollector.GetOutCalls(); for (const auto& returnCall : uniqueNodelingsOut) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodes/ExpressionNodeBase.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodes/ExpressionNodeBase.cpp index e7edcce002..8c0f5760a8 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodes/ExpressionNodeBase.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodes/ExpressionNodeBase.cpp @@ -121,13 +121,13 @@ namespace ScriptCanvas { if (slotId == ExpressionNodeBaseProperty::GetInSlotId(this)) { - for (const SlotId& slotId : m_dirtyInputs) + for (const SlotId& dirtySlotId : m_dirtyInputs) { - auto variableIter = m_slotToVariableMap.find(slotId); + auto variableIter = m_slotToVariableMap.find(dirtySlotId); if (variableIter != m_slotToVariableMap.end()) { - PushVariable(variableIter->second, (*FindDatum(slotId))); + PushVariable(variableIter->second, (*FindDatum(dirtySlotId))); } } diff --git a/Gems/WhiteBox/Code/Source/Core/WhiteBoxToolApi.cpp b/Gems/WhiteBox/Code/Source/Core/WhiteBoxToolApi.cpp index 5803f066ae..a6b9456f98 100644 --- a/Gems/WhiteBox/Code/Source/Core/WhiteBoxToolApi.cpp +++ b/Gems/WhiteBox/Code/Source/Core/WhiteBoxToolApi.cpp @@ -2060,23 +2060,23 @@ namespace WhiteBox polygonHandle.m_faceHandles.push_back(faceHandleToVisit); // for all halfedges - for (const auto halfedgeHandle : faceHalfedges) + for (const auto faceHalfedgeHandle : faceHalfedges) { - const EdgeHandle edgeHandle = HalfedgeEdgeHandle(whiteBox, halfedgeHandle); + const EdgeHandle edgeHandle = HalfedgeEdgeHandle(whiteBox, faceHalfedgeHandle); // if we haven't seen this halfedge before and we want to track it, // store it in visited halfedges - if (halfedgeHandle != oppositeHalfedgeHandle + if (faceHalfedgeHandle != oppositeHalfedgeHandle // ignore border halfedges (not inside the polygon) - && AZStd::find(borderHalfedgeHandles.cbegin(), borderHalfedgeHandles.cend(), halfedgeHandle) == + && AZStd::find(borderHalfedgeHandles.cbegin(), borderHalfedgeHandles.cend(), faceHalfedgeHandle) == borderHalfedgeHandles.cend() // ensure we do not visit the same halfedge again - && AZStd::find(visitedHalfedges.cbegin(), visitedHalfedges.cend(), halfedgeHandle) == + && AZStd::find(visitedHalfedges.cbegin(), visitedHalfedges.cend(), faceHalfedgeHandle) == visitedHalfedges.cend() // ignore the halfedge if we've already tracked it in our 'building' list && AZStd::find(buildingEdgeHandles.cbegin(), buildingEdgeHandles.cend(), edgeHandle) == buildingEdgeHandles.cend()) { - halfedgesToVisit.push_back(HalfedgeOppositeHalfedgeHandle(whiteBox, halfedgeHandle)); + halfedgesToVisit.push_back(HalfedgeOppositeHalfedgeHandle(whiteBox, faceHalfedgeHandle)); } } } @@ -3198,10 +3198,10 @@ namespace WhiteBox // - add bottom faces if mesh was 2d previously (reverse winding order) FaceHandles allFacesToRemove = polygonHandle.m_faceHandles; - for (const auto& polygonHandle : polygonHandlesToRemove) + for (const auto& polygonHandleToRemove : polygonHandlesToRemove) { allFacesToRemove.insert( - allFacesToRemove.end(), polygonHandle.m_faceHandles.cbegin(), polygonHandle.m_faceHandles.cend()); + allFacesToRemove.end(), polygonHandleToRemove.m_faceHandles.cbegin(), polygonHandleToRemove.m_faceHandles.cend()); } // remove all faces that were already there diff --git a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake index f53b8aa769..357d578c44 100644 --- a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake +++ b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake @@ -73,7 +73,6 @@ ly_append_configurations_options( /wd4389 # comparison, signed/unsigned mismatch /wd4436 # the result of unary operator may be unaligned /wd4450 # declaration hides global declaration - /wd4457 # declaration hides function parameter # Enabling warnings that are disabled by default from /W4 # https://docs.microsoft.com/en-us/cpp/preprocessor/compiler-warnings-that-are-off-by-default?view=vs-2019 From 1f48985a0e325164af62561f6983ebac4a620e0c Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Fri, 4 Jun 2021 18:09:26 +0000 Subject: [PATCH 513/811] Update Blast to the latest version, eb169fe (#1076) --- cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index fa1326b63d..1a2cfa4049 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -30,11 +30,11 @@ ly_associate_package(PACKAGE_NAME azslc-1.7.21-rev1-multiplatform ly_associate_package(PACKAGE_NAME glad-2.0.0-beta-rev2-multiplatform TARGETS glad PACKAGE_HASH ff97ee9664e97d0854b52a3734c2289329d9f2b4cd69478df6d0ca1f1c9392ee) ly_associate_package(PACKAGE_NAME lux_core-2.2-rev5-multiplatform TARGETS lux_core PACKAGE_HASH c8c13cf7bc351643e1abd294d0841b24dee60e51647dff13db7aec396ad1e0b5) ly_associate_package(PACKAGE_NAME xxhash-0.7.4-rev1-multiplatform TARGETS xxhash PACKAGE_HASH e81f3e6c4065975833996dd1fcffe46c3cf0f9e3a4207ec5f4a1b564ba75861e) -ly_associate_package(PACKAGE_NAME Blast-1.1.7-rev1-multiplatform TARGETS Blast PACKAGE_HASH 36b8f393bcd25d0f85cfc7a831ebbdac881e6054c4f0735649966aa6aa86e6f0) ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform TARGETS PVRTexTool PACKAGE_HASH d0d6da61c7557de0d2c71fc35ba56c3be49555b703f0e853d4c58225537acf1e) # platform-specific: ly_associate_package(PACKAGE_NAME AWSGameLiftServerSDK-3.4.1-rev1-windows TARGETS AWSGameLiftServerSDK PACKAGE_HASH a0586b006e4def65cc25f388de17dc475e417dc1e6f9d96749777c88aa8271b0) +ly_associate_package(PACKAGE_NAME Blast-v1.1.7_rc2-9-geb169fe-rev1-windows TARGETS Blast PACKAGE_HASH 216df71f4ffaf4a6ea3f2e77e5f27d68f2325e717fbd1626b00c785b82cd1b67) ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev2-windows TARGETS DirectXShaderCompilerDxc PACKAGE_HASH decc53e97c7ddda9c7f853a30af7808a7b652a912f59ad2cd4bca5d308aae2c4) ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-windows TARGETS SPIRVCross PACKAGE_HASH 7d601ea9d625b1d509d38bd132a1f433d7e895b16adab76bac6103567a7a6817) ly_associate_package(PACKAGE_NAME freetype-2.10.4.14-windows TARGETS freetype PACKAGE_HASH 88dedc86ccb8c92f14c2c033e51ee7d828fa08eafd6475c6aa963938a99f4bf3) From febf53671eacbe0f67a60feb5317ef93d70f43f5 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Fri, 4 Jun 2021 11:09:44 -0700 Subject: [PATCH 514/811] Addressed PR feedback. --- .../AzCore/AzCore/Serialization/IdUtils.h | 2 +- .../Spawnable/SpawnableEntitiesInterface.h | 34 +++++++++---------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/IdUtils.h b/Code/Framework/AzCore/AzCore/Serialization/IdUtils.h index 98959fe4bd..15ce299000 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/IdUtils.h +++ b/Code/Framework/AzCore/AzCore/Serialization/IdUtils.h @@ -29,7 +29,7 @@ namespace AZ namespace IdUtils { /** - * \param AllowDuplicates - If true allows the same id to be registered multiple time, + * \param AllowDuplicates - If true allows the same id to be registered multiple times, with the newer value overwriting the stored value. If false, duplicates are not allowed and the first stored value is kept.The default is false. */ diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index 2ad1db60a4..d2a5872fc8 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -177,8 +177,8 @@ namespace AzFramework //! Callback that's called after instances of entities have been created, but before they're spawned into the world. This //! gives the opportunity to modify the entities if needed such as injecting additional components or modifying components. EntityPreInsertionCallback m_preInsertionCallback; - //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that - //! made the function call. The returned list of entities contains all the newly created entities. + //! Callback that's called when spawning entities has completed. This can be triggered from a different thread than the one that + //! made the function call to spawn. The returned list of entities contains all the newly created entities. EntitySpawnCallback m_completionCallback; //! The Serialize Context used to clone entities with. If this is not provided the global Serialize Contetx will be used. AZ::SerializeContext* m_serializeContext { nullptr }; @@ -191,8 +191,8 @@ namespace AzFramework //! Callback that's called after instances of entities have been created, but before they're spawned into the world. This //! gives the opportunity to modify the entities if needed such as injecting additional components or modifying components. EntityPreInsertionCallback m_preInsertionCallback; - //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that - //! made the function call. The returned list of entities contains all the newly created entities. + //! Callback that's called when spawning entities has completed. This can be triggered from a different thread than the one that + //! made the function call to spawn. The returned list of entities contains all the newly created entities. EntitySpawnCallback m_completionCallback; //! The Serialize Context used to clone entities with. If this is not provided the global Serialize Contetx will be used. AZ::SerializeContext* m_serializeContext{ nullptr }; @@ -207,8 +207,8 @@ namespace AzFramework struct DespawnAllEntitiesOptionalArgs final { - //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that - //! made the function call. The returned list of entities contains all the newly created entities. + //! Callback that's called when despawning entities has completed. This can be triggered from a different thread than the one that + //! made the function call to despawn. The returned list of entities contains all the newly created entities. EntityDespawnCallback m_completionCallback; //! The priority at which this call will be executed. SpawnablePriority m_priority { SpawnablePriority_Default }; @@ -216,10 +216,10 @@ namespace AzFramework struct ReloadSpawnableOptionalArgs final { - //! Callback that's called when spawning entities has completed. This can be called from a different thread than the one that - //! made the function call. The returned list of entities contains all the newly created entities. + //! Callback that's called when respawning entities has completed. This can be triggered from a different thread than the one that + //! made the function call to respawn. The returned list of entities contains all the newly created entities. ReloadSpawnableCallback m_completionCallback; - //! The Serialize Context used to clone entities with. If this is not provided the global Serialize Contetx will be used. + //! The Serialize Context used to clone entities with. If this is not provided the global Serialize Context will be used. AZ::SerializeContext* m_serializeContext { nullptr }; //! The priority at which this call will be executed. SpawnablePriority m_priority { SpawnablePriority_Default }; @@ -268,32 +268,32 @@ namespace AzFramework //! Spawn instances of all entities in the spawnable. //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. - //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs + //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs. virtual void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnAllEntitiesOptionalArgs optionalArgs = {}) = 0; //! Spawn instances of some entities in the spawnable. //! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them. //! @param priority The priority at which this call will be executed. //! @param entityIndices The indices into the template entities stored in the spawnable that will be used to spawn entities from. - //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs + //! @param optionalArgs Optional additional arguments, see SpawnEntitiesOptionalArgs. virtual void SpawnEntities( EntitySpawnTicket& ticket, AZStd::vector entityIndices, SpawnEntitiesOptionalArgs optionalArgs = {}) = 0; //! Removes all entities in the provided list from the environment. //! @param ticket The ticket previously used to spawn entities with. //! @param priority The priority at which this call will be executed. - //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs + //! @param optionalArgs Optional additional arguments, see DespawnAllEntitiesOptionalArgs. virtual void DespawnAllEntities(EntitySpawnTicket& ticket, DespawnAllEntitiesOptionalArgs optionalArgs = {}) = 0; //! Removes all entities in the provided list from the environment and reconstructs the entities from the provided spawnable. //! @param ticket Holds the information on the entities to reload. //! @param priority The priority at which this call will be executed. //! @param spawnable The spawnable that will replace the existing spawnable. Both need to have the same asset id. - //! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs + //! @param optionalArgs Optional additional arguments, see ReloadSpawnableOptionalArgs. virtual void ReloadSpawnable( EntitySpawnTicket& ticket, AZ::Data::Asset spawnable, ReloadSpawnableOptionalArgs optionalArgs = {}) = 0; //! List all entities that are spawned using this ticket. //! @param ticket Only the entities associated with this ticket will be listed. - //! @param priority The priority at which this call will be executed. //! @param listCallback Required callback that will be called to list the entities on. + //! @param optionalArgs Optional additional arguments, see ListEntitiesOptionalArgs. virtual void ListEntities( EntitySpawnTicket& ticket, ListEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs = {}) = 0; //! List all entities that are spawned using this ticket with their spawnable index. @@ -303,23 +303,23 @@ namespace AzFramework //! the same index may appear multiple times as there are no restriction on how many instance of a specific entity can be //! created. //! @param ticket Only the entities associated with this ticket will be listed. - //! @param priority The priority at which this call will be executed. //! @param listCallback Required callback that will be called to list the entities and indices on. + //! @param optionalArgs Optional additional arguments, see ListEntitiesOptionalArgs. virtual void ListIndicesAndEntities( EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs = {}) = 0; //! Claim all entities that are spawned using this ticket. Ownership of the entities is transferred from the ticket to the //! caller through the callback. After this call the ticket will have no entities associated with it. The caller of //! this function will need to manage the entities after this call. //! @param ticket Only the entities associated with this ticket will be released. - //! @param priority The priority at which this call will be executed. //! @param listCallback Required callback that will be called to transfer the entities through. + //! @param optionalArgs Optional additional arguments, see ClaimEntitiesOptionalArgs. virtual void ClaimEntities( EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback, ClaimEntitiesOptionalArgs optionalArgs = {}) = 0; //! Blocks until all operations made on the provided ticket before the barrier call have completed. //! @param ticket The ticket to monitor. - //! @param priority The priority at which this call will be executed. //! @param completionCallback Required callback that will be called as soon as the barrier has been reached. + //! @param optionalArgs Optional additional arguments, see BarrierOptionalArgs. virtual void Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback, BarrierOptionalArgs optionalArgs = {}) = 0; //! Register a handler for OnSpawned events. From b10ed227c0d7a59d51b6397a4f25a4b395293ae8 Mon Sep 17 00:00:00 2001 From: guthadam Date: Fri, 4 Jun 2021 13:54:45 -0500 Subject: [PATCH 515/811] Added version handling for removed fields --- .../Code/Source/Material/EditorMaterialComponentSlot.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp index bdc82acda6..65fa7bc286 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp @@ -70,6 +70,12 @@ namespace AZ } } + if (classElement.GetVersion() < 5) + { + classElement.RemoveElementByName(AZ_CRC_CE("matModUvOverrides")); + classElement.RemoveElementByName(AZ_CRC_CE("propertyOverrides")); + } + return true; } From c586ff1ca6c8970bc168a98aa5762514a9ca421d Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Fri, 4 Jun 2021 12:12:02 -0700 Subject: [PATCH 516/811] Allow script canvas user to listen for RPC events --- .../Source/AutoGen/AutoComponent_Source.jinja | 32 +++++++++++++++++-- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 259f469020..12ff01468e 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -373,21 +373,21 @@ void {{ ClassName }}::Signal{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.jo AZ::Entity* entity = AZ::Interface::Get()->FindEntity(id); if (!entity) { - AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }} failed. The entity with id %s doesn't exist, please provide a valid entity id.", id.ToString().c_str()) + AZ_Warning("Network Property", false, "{{ ClassName }} {{ UpperFirst(Property.attrib['Name']) }}ByEntity failed. The entity with id %s doesn't exist, please provide a valid entity id.", id.ToString().c_str()) return; } {{ ClassName }}* networkComponent = entity->FindComponent<{{ ClassName }}>(); if (!networkComponent) { - AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }} failed. Entity '%s' (id: %s) is missing {{ ClassName }}, be sure to add {{ ClassName }} to this entity.", entity->GetName().c_str(), id.ToString().c_str()) + AZ_Warning("Network Property", false, "{{ ClassName }} {{ UpperFirst(Property.attrib['Name']) }}ByEntity failed. Entity '%s' (id: %s) is missing {{ ClassName }}, be sure to add {{ ClassName }} to this entity.", entity->GetName().c_str(), id.ToString().c_str()) return; } {{ ClassName }}Controller* controller = static_cast<{{ ClassName }}Controller*>(networkComponent->GetController()); if (!controller) { - AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }} method failed. Entity '%s' (id: %s) {{ ClassName }} is missing the network controller. This RemoteProcedure can only be invoked from {{InvokeFrom}} network entities, because this entity doesn't have a controller, it must not be a {{InvokeFrom}} entity. Please check your network context before attempting to call {{ UpperFirst(Property.attrib['Name']) }}.", entity->GetName().c_str(), id.ToString().c_str()) + AZ_Warning("Network Property", false, "{{ ClassName }} {{ UpperFirst(Property.attrib['Name']) }}ByEntity method failed. Entity '%s' (id: %s) {{ ClassName }} is missing the network controller. This RemoteProcedure can only be invoked from {{InvokeFrom}} network entities, because this entity doesn't have a controller, it must not be a {{InvokeFrom}} entity. Please check your network context before attempting to call {{ UpperFirst(Property.attrib['Name']) }}.", entity->GetName().c_str(), id.ToString().c_str()) return; } @@ -429,6 +429,32 @@ void {{ ClassName }}::Signal{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.jo ->Method("Get{{ UpperFirst(Property.attrib['Name']) }}Event", [](const {{ ClassName }}* self) -> AZ::Event<{{ ', '.join(paramTypes) }}>& { return self->m_controller->Get{{ UpperFirst(Property.attrib['Name']) }}Event(); + }) + ->Attribute(AZ::Script::Attributes::AzEventDescription, {{ LowerFirst(Property.attrib['Name']) }}EventDesc) + ->Method("Get{{ UpperFirst(Property.attrib['Name']) }}EventByEntity", [](AZ::EntityId id) -> AZ::Event<{{ ', '.join(paramTypes) }}>* + { + AZ::Entity* entity = AZ::Interface::Get()->FindEntity(id); + if (!entity) + { + AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }}EventByEntity failed. The entity with id %s doesn't exist, please provide a valid entity id.", id.ToString().c_str()) + return nullptr; + } + + {{ ClassName }}* networkComponent = entity->FindComponent<{{ ClassName }}>(); + if (!networkComponent) + { + AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }}EventByEntity failed. Entity '%s' (id: %s) is missing {{ ClassName }}, be sure to add {{ ClassName }} to this entity.", entity->GetName().c_str(), id.ToString().c_str()) + return nullptr; + } + + {{ ClassName }}Controller* controller = static_cast<{{ ClassName }}Controller*>(networkComponent->GetController()); + if (!controller) + { + AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }}EventByEntity method failed. Entity '%s' (id: %s) {{ ClassName }} is missing the network controller. This RemoteProcedure can only be received by {{InvokeTo}} network entities, because this entity doesn't have a controller, it must not be a {{InvokeTo}} entity. Please check your network context before attempting to Get{{ UpperFirst(Property.attrib['Name']) }}Event.", entity->GetName().c_str(), id.ToString().c_str()) + return nullptr; + } + + return &controller->Get{{ UpperFirst(Property.attrib['Name']) }}Event(); }) ->Attribute(AZ::Script::Attributes::AzEventDescription, AZStd::move({{ LowerFirst(Property.attrib['Name']) }}EventDesc)) {% endif %} From 758f62a5531b3a28c10d8e410645a022868976cd Mon Sep 17 00:00:00 2001 From: amzn-sj Date: Fri, 4 Jun 2021 12:34:50 -0700 Subject: [PATCH 517/811] Fix Editor crash in Mac --- Registry/Platform/Mac/streamer.editor.setreg | 28 ++++++++++++++++++++ Registry/Platform/Mac/streamer.test.setreg | 24 +++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 Registry/Platform/Mac/streamer.editor.setreg create mode 100644 Registry/Platform/Mac/streamer.test.setreg diff --git a/Registry/Platform/Mac/streamer.editor.setreg b/Registry/Platform/Mac/streamer.editor.setreg new file mode 100644 index 0000000000..85360d128e --- /dev/null +++ b/Registry/Platform/Mac/streamer.editor.setreg @@ -0,0 +1,28 @@ +{ + "Amazon": + { + "AzCore": + { + "Streamer": + { + "Profiles": + { + "Generic": + { + "Stack": + [ + { + "$type": "AZ::IO::StorageDriveConfig", + // The maximum number of file handles that the drive will cache. + // On Mac the default limit for the number of file handles an application + // can have open is set to 256. So we need to set this to a lower value than on PC. + // This limit is set by "launchctl limit maxfiles" + "MaxFileHandles": 65 + } + ] + } + } + } + } + } +} \ No newline at end of file diff --git a/Registry/Platform/Mac/streamer.test.setreg b/Registry/Platform/Mac/streamer.test.setreg new file mode 100644 index 0000000000..df41b7a350 --- /dev/null +++ b/Registry/Platform/Mac/streamer.test.setreg @@ -0,0 +1,24 @@ +{ + "Amazon": + { + "AzCore": + { + "Streamer": + { + "Profiles": + { + "Generic": + { + "Stack": + [ + { + "$type": "AZ::IO::StorageDriveConfig", + "MaxFileHandles": 65 + } + ] + } + } + } + } + } +} \ No newline at end of file From 16eb3bd82c9fa842b6f654115607e50bf7a5a65e Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 4 Jun 2021 15:25:49 -0500 Subject: [PATCH 518/811] Adding newline to streamer.editor.setreg --- Registry/Platform/Mac/streamer.editor.setreg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Registry/Platform/Mac/streamer.editor.setreg b/Registry/Platform/Mac/streamer.editor.setreg index 85360d128e..2fc8197c5f 100644 --- a/Registry/Platform/Mac/streamer.editor.setreg +++ b/Registry/Platform/Mac/streamer.editor.setreg @@ -25,4 +25,4 @@ } } } -} \ No newline at end of file +} From f7caa988081eca13d0680eb89eed5af5a795224f Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 4 Jun 2021 15:26:16 -0500 Subject: [PATCH 520/811] Adding newline to streamer.test.setreg --- Registry/Platform/Mac/streamer.test.setreg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Registry/Platform/Mac/streamer.test.setreg b/Registry/Platform/Mac/streamer.test.setreg index df41b7a350..2b053a497e 100644 --- a/Registry/Platform/Mac/streamer.test.setreg +++ b/Registry/Platform/Mac/streamer.test.setreg @@ -21,4 +21,4 @@ } } } -} \ No newline at end of file +} From 40d90c49a378bb82c1632fb1e29fbc6b7bd76774 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Fri, 4 Jun 2021 13:42:25 -0700 Subject: [PATCH 521/811] Disabled writing UserSettings.xml in Spawnable tests. --- .../Tests/Spawnable/SpawnableEntitiesManagerTests.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp index 484b7f46d7..8bb39449f1 100644 --- a/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp +++ b/Code/Framework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp @@ -11,6 +11,7 @@ */ #include +#include #include #include #include @@ -40,6 +41,10 @@ namespace UnitTest m_application = new TestApplication(); AZ::ComponentApplication::Descriptor descriptor; m_application->Start(descriptor); + // Without this, the user settings component would attempt to save on finalize/shutdown. Since the file is + // shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash + // in the unit tests. + AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize); m_spawnable = aznew AzFramework::Spawnable( AZ::Data::AssetId::CreateString("{EB2E8A2B-F253-4A90-BBF4-55F2EED786B8}:0"), AZ::Data::AssetData::AssetStatus::Ready); From 55a46806590d04c45b3203fa27b5216536677100 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Fri, 4 Jun 2021 14:10:30 -0700 Subject: [PATCH 522/811] Fixed Multiplayer unit tests. The multiplayer unit tests created a SpawnableSystemComponent without an application to provide the Serialize Context. This caused an assert which failed the unit tests. Since the entity spawning system doesn't seem to be directly used the component was removed. --- Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp b/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp index 6ace4db592..7b09b65de4 100644 --- a/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp +++ b/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp @@ -30,7 +30,6 @@ namespace UnitTest { SetupAllocator(); AZ::NameDictionary::Create(); - m_spawnableComponent = new AzFramework::SpawnableSystemComponent(); m_netComponent = new AzNetworking::NetworkingSystemComponent(); m_mpComponent = new Multiplayer::MultiplayerSystemComponent(); @@ -46,7 +45,6 @@ namespace UnitTest { delete m_mpComponent; delete m_netComponent; - delete m_spawnableComponent; AZ::NameDictionary::Destroy(); TeardownAllocator(); } @@ -76,7 +74,6 @@ namespace UnitTest AzNetworking::NetworkingSystemComponent* m_netComponent = nullptr; Multiplayer::MultiplayerSystemComponent* m_mpComponent = nullptr; - AzFramework::SpawnableSystemComponent* m_spawnableComponent = nullptr; }; TEST_F(MultiplayerSystemTests, TestInitEvent) From a10e1d9a8753757c12c261bea035c52403391197 Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Fri, 4 Jun 2021 14:10:34 -0700 Subject: [PATCH 523/811] Script Canvas node palette search will ignore whitespace --- .../Model/NodePaletteSortFilterProxyModel.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/Model/NodePaletteSortFilterProxyModel.cpp b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/Model/NodePaletteSortFilterProxyModel.cpp index ca5e962685..9e1e0688b4 100644 --- a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/Model/NodePaletteSortFilterProxyModel.cpp +++ b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/Model/NodePaletteSortFilterProxyModel.cpp @@ -147,8 +147,9 @@ namespace GraphCanvas return true; } - QString test = model->data(index).toString(); - + // Ignore whitespace when filtering node names + QString test = model->data(index).toString().simplified().replace(" ", ""); + bool showRow = false; int regexIndex = test.lastIndexOf(m_filterRegex); @@ -283,7 +284,10 @@ namespace GraphCanvas void NodePaletteSortFilterProxyModel::SetFilter(const QString& filter) { - m_filter = QRegExp::escape(filter); + // Remove whitespace and escape() so every regexp special character is escaped with a backslash + // Removing the whitespace will allow us to find nodes even if the node is written with or without spaces. + // Example: "OnGraphStart" or "On Graph Start" + m_filter = QRegExp::escape(filter.simplified().replace(" ", "")); m_filterRegex = QRegExp(m_filter, Qt::CaseInsensitive); } From 50d6e36ccd17c9214f057e749dc73db5a2c148b8 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 4 Jun 2021 14:36:46 -0700 Subject: [PATCH 524/811] Bug and improvements to Editor/AP debugging settings (#1146) --- Code/Sandbox/Editor/CMakeLists.txt | 4 ++-- Code/Tools/AssetProcessor/CMakeLists.txt | 4 ++-- cmake/Projects.cmake | 12 +++++++++--- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/Code/Sandbox/Editor/CMakeLists.txt b/Code/Sandbox/Editor/CMakeLists.txt index 01b58e3f77..58d5e86a2f 100644 --- a/Code/Sandbox/Editor/CMakeLists.txt +++ b/Code/Sandbox/Editor/CMakeLists.txt @@ -191,8 +191,8 @@ ly_add_translations( ) ly_add_dependencies(Editor AssetProcessor) -if(LY_FIRST_PROJECT_PATH) - set_property(TARGET Editor APPEND PROPERTY VS_DEBUGGER_COMMAND_ARGUMENTS "--project-path=\"${LY_FIRST_PROJECT_PATH}\"") +if(LY_DEFAULT_PROJECT_PATH) + set_property(TARGET Editor APPEND PROPERTY VS_DEBUGGER_COMMAND_ARGUMENTS "--project-path=\"${LY_DEFAULT_PROJECT_PATH}\"") endif() ################################################################################ diff --git a/Code/Tools/AssetProcessor/CMakeLists.txt b/Code/Tools/AssetProcessor/CMakeLists.txt index 6c12ab6024..2db888218b 100644 --- a/Code/Tools/AssetProcessor/CMakeLists.txt +++ b/Code/Tools/AssetProcessor/CMakeLists.txt @@ -125,8 +125,8 @@ ly_add_target( AZ::AssetProcessorBatch.Static ) -if(LY_FIRST_PROJECT_PATH) - set_property(TARGET AssetProcessor AssetProcessorBatch APPEND PROPERTY VS_DEBUGGER_COMMAND_ARGUMENTS "--project-path=\"${LY_FIRST_PROJECT_PATH}\"") +if(LY_DEFAULT_PROJECT_PATH) + set_property(TARGET AssetProcessor AssetProcessorBatch APPEND PROPERTY VS_DEBUGGER_COMMAND_ARGUMENTS "--project-path=\"${LY_DEFAULT_PROJECT_PATH}\"") endif() # Adds the AssetProcessorBatch target as a C preprocessor define so that it can be used as a Settings Registry diff --git a/cmake/Projects.cmake b/cmake/Projects.cmake index adaf7ee15f..eadfa79c1b 100644 --- a/cmake/Projects.cmake +++ b/cmake/Projects.cmake @@ -167,9 +167,6 @@ endfunction() # Add the projects here so the above function is found foreach(project ${LY_PROJECTS}) file(REAL_PATH ${project} full_directory_path BASE_DIRECTORY ${CMAKE_SOURCE_DIR}) - if(NOT LY_FIRST_PROJECT) - ly_set(LY_FIRST_PROJECT_PATH ${full_directory_path}) - endif() string(SHA256 full_directory_hash ${full_directory_path}) # Truncate the full_directory_hash down to 8 characters to avoid hitting the Windows 260 character path limit @@ -182,4 +179,13 @@ foreach(project ${LY_PROJECTS}) ly_generate_project_build_path_setreg(${full_directory_path}) add_project_json_external_subdirectories(${full_directory_path}) endforeach() + +# If just one project is defined we pass it as a parameter to the applications +list(LENGTH LY_PROJECTS projects_length) +if(projects_length EQUAL "1") + list(GET LY_PROJECTS 0 project) + file(REAL_PATH ${project} full_directory_path BASE_DIRECTORY ${CMAKE_SOURCE_DIR}) + ly_set(LY_DEFAULT_PROJECT_PATH ${full_directory_path}) +endif() + ly_set(LY_PROJECTS_FOLDER_NAME ${LY_PROJECTS_FOLDER_NAME}) From 52b306eb3ef53ea01080c9670985d893d8ef73d1 Mon Sep 17 00:00:00 2001 From: antonmic Date: Fri, 4 Jun 2021 14:59:27 -0700 Subject: [PATCH 525/811] Pass changes now building and working --- .../Code/Source/DisplayMapper/DisplayMapperPass.cpp | 2 ++ .../Code/Source/LuxCore/LuxCoreTexturePass.cpp | 2 ++ .../RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h | 1 + .../RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp | 6 ++++++ Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp | 11 +++++++---- .../RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp | 13 ++++++++----- .../Pass/Specific/EnvironmentCubeMapPass.cpp | 2 ++ .../RPI.Public/Pass/Specific/SwapChainPass.cpp | 2 ++ 8 files changed, 30 insertions(+), 9 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp index be3e05163a..b6fa0b5c41 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp @@ -46,6 +46,8 @@ namespace AZ DisplayMapperPass::DisplayMapperPass(const RPI::PassDescriptor& descriptor) : RPI::ParentPass(descriptor) { + m_flags.m_alreadyCreated = false; + AzFramework::NativeWindowHandle windowHandle = nullptr; AzFramework::WindowSystemRequestBus::BroadcastResult( windowHandle, diff --git a/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp b/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp index 3c7233e747..7708605e29 100644 --- a/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp @@ -28,6 +28,8 @@ namespace AZ LuxCoreTexturePass::LuxCoreTexturePass(const RPI::PassDescriptor& descriptor) : ParentPass(descriptor) { + m_flags.m_alreadyCreated = false; + RPI::PassSystemInterface* passSystem = RPI::PassSystemInterface::Get(); // Create render target pass diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h index ee7f850d27..b71016f30a 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h @@ -393,6 +393,7 @@ namespace AZ uint64_t m_parentEnabled : 1; uint64_t m_initialized : 1; + uint64_t m_alreadyCreated : 1; uint64_t m_partOfHierarchy : 1; uint64_t m_hasDrawListTag : 1; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp index 7244510fbd..ebdfa7cf55 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp @@ -248,6 +248,12 @@ namespace AZ void ParentPass::CreateChildPasses() { + if (m_flags.m_alreadyCreated) + { + return; + } + m_flags.m_alreadyCreated = true; + RemoveChildren(); CreatePassesFromTemplate(); CreateChildPassesInternal(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp index da9022b655..726d702a72 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp @@ -151,6 +151,7 @@ namespace AZ { AZ_RPI_PASS_ASSERT(m_parent != nullptr, "Trying to remove pass from parent but pointer to the parent pass is null."); m_parent->RemoveChild(Ptr(this)); + m_queueState = PassQueueState::NoQueue; } void Pass::OnOrphan() @@ -358,7 +359,7 @@ namespace AZ void Pass::QueueForBuild() { // Don't queue if we're in building phase - if (PassSystemInterface::Get()->GetState() != PassSystemState::Building && + if (m_state != PassState::Building && (m_queueState == PassQueueState::NoQueue || m_queueState == PassQueueState::QueuedForInitialization)) { PassSystemInterface::Get()->QueueForBuild(this); @@ -374,7 +375,7 @@ namespace AZ void Pass::QueueForInitialization() { // Don't queue if we're in initialization phase - if (PassSystemInterface::Get()->GetState() != PassSystemState::Initializing && m_queueState == PassQueueState::NoQueue) + if (m_queueState == PassQueueState::NoQueue) { PassSystemInterface::Get()->QueueForInitialization(this); m_queueState = PassQueueState::QueuedForInitialization; @@ -1086,11 +1087,12 @@ namespace AZ void Pass::Build() { - if (m_queueState != PassQueueState::QueuedForBuild || m_state != PassState::Resetting) + if (m_queueState != PassQueueState::QueuedForBuild || (m_state != PassState::Queued && m_state != PassState::Resetting)) { return; } m_state = PassState::Building; + m_queueState = PassQueueState::NoQueue; AZ_RPI_BREAK_ON_TARGET_PASS; @@ -1115,7 +1117,6 @@ namespace AZ UpdateAttachmentUsageIndices(); // Queue for Initialization - m_queueState = PassQueueState::NoQueue; QueueForInitialization(); } @@ -1123,6 +1124,7 @@ namespace AZ { AZ_RPI_BREAK_ON_TARGET_PASS; + m_flags.m_alreadyCreated = false; m_importedAttachmentStore.clear(); OnBuildFinishedInternal(); } @@ -1133,6 +1135,7 @@ namespace AZ { return; } + m_queueState = PassQueueState::NoQueue; m_state = PassState::Initializing; InitializeInternal(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp index 3dabd88fff..0c38b228f5 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -242,19 +242,22 @@ namespace AZ AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: BuildPassAttachments"); - if(!m_initializePassList.empty()) + while (!m_initializePassList.empty()) { + AZStd::vector< Ptr > initListCopy = m_initializePassList; + m_initializePassList.clear(); + // Erase passes which were removed from pass tree already (which parent is empty) - auto unused = AZStd::remove_if(m_initializePassList.begin(), m_initializePassList.end(), + auto unused = AZStd::remove_if(initListCopy.begin(), initListCopy.end(), [](const RHI::Ptr& currentPass) { return !currentPass->m_flags.m_partOfHierarchy; }); - m_initializePassList.erase(unused, m_initializePassList.end()); + initListCopy.erase(unused, initListCopy.end()); - SortPassListAscending(m_initializePassList); + SortPassListAscending(initListCopy); - for (const Ptr& pass : m_initializePassList) + for (const Ptr& pass : initListCopy) { pass->Initialize(); } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp index 672e5509ee..be06343ab9 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp @@ -37,6 +37,8 @@ namespace AZ EnvironmentCubeMapPass::EnvironmentCubeMapPass(const PassDescriptor& passDescriptor) : ParentPass(passDescriptor) { + m_flags.m_alreadyCreated = false; + // load pass data const EnvironmentCubeMapPassData* passData = PassUtils::GetPassData(passDescriptor); if (passData == nullptr) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp index e6f65e997c..45fb890e91 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp @@ -26,6 +26,8 @@ namespace AZ , m_windowContext(windowContext) , m_childTemplateName(childTemplateName) { + m_flags.m_alreadyCreated = false; + PassSystemInterface* passSystem = PassSystemInterface::Get(); // Create child pass From 8a079da914ceadb07846d66230dd031a3b8cccc6 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Sat, 5 Jun 2021 00:04:26 +0200 Subject: [PATCH 526/811] GemCatalog: Gem cart widget and overlay window * [LYN-4174] Added icons for gem catalog summary cart * [LYN-4174] Gem Catalog: Text eliding for too long gem names and creators * [LYN-4174] Gem catalog: Resetting filters when re-initializing for another project * [LYN-4174] Gem Catalog: Fixed a bug with filters being applied/remembered after leaving gem catalog and coming back editing another project * [LYN-4174] GemCatalog: Gem cart widget and overlay window * Added cart button with dynamic label to display the number of gems to be enabled/disabled and a arrow down button to indicate some sort of pop-up/overlay window will appear on click. * Overlay gem tags update dynamically while the dialog is open based on the gem model. * Moved some styling from C++ to the style sheet. --- .../Resources/CarrotArrowDown.svg | 3 + .../Resources/ProjectManager.qrc | 3 + .../Resources/ProjectManager.qss | 40 ++- .../ProjectManager/Resources/Summary.svg | 3 + .../ProjectManager/Resources/WindowClose.svg | 4 + .../GemCatalog/GemCatalogHeaderWidget.cpp | 235 +++++++++++++++++- .../GemCatalog/GemCatalogHeaderWidget.h | 64 ++++- .../Source/GemCatalog/GemCatalogScreen.cpp | 8 +- .../Source/GemCatalog/GemCatalogScreen.h | 2 + .../Source/GemCatalog/GemItemDelegate.cpp | 8 +- .../GemCatalog/GemSortFilterProxyModel.cpp | 11 + .../GemCatalog/GemSortFilterProxyModel.h | 1 + 12 files changed, 350 insertions(+), 32 deletions(-) create mode 100644 Code/Tools/ProjectManager/Resources/CarrotArrowDown.svg create mode 100644 Code/Tools/ProjectManager/Resources/Summary.svg create mode 100644 Code/Tools/ProjectManager/Resources/WindowClose.svg diff --git a/Code/Tools/ProjectManager/Resources/CarrotArrowDown.svg b/Code/Tools/ProjectManager/Resources/CarrotArrowDown.svg new file mode 100644 index 0000000000..73545968d5 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/CarrotArrowDown.svg @@ -0,0 +1,3 @@ + + + diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qrc b/Code/Tools/ProjectManager/Resources/ProjectManager.qrc index 04d5e98a10..62b7d23e9c 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qrc +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qrc @@ -26,5 +26,8 @@ Backgrounds/FirstTimeBackgroundImage.jpg ArrowDownLine.svg ArrowUpLine.svg + CarrotArrowDown.svg + Summary.svg + WindowClose.svg
diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qss b/Code/Tools/ProjectManager/Resources/ProjectManager.qss index 224574f522..6fd4086c58 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qss +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qss @@ -115,7 +115,7 @@ QTabBar::tab:pressed /************** General (Modal windows) **************/ #header { - background-color:#111111; + background-color:#111111; min-height:80px; max-height:80px; } @@ -172,8 +172,8 @@ QTabBar::tab:pressed #footer > QPushButton { qproperty-flat: true; - background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, - stop: 0 #0095f2, stop: 1.0 #1e70eb); + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #0095f2, stop: 1.0 #1e70eb); border-radius: 3px; min-height: 28px; max-height: 28px; @@ -181,26 +181,26 @@ QTabBar::tab:pressed margin-right:30px; } #footer > QPushButton:hover { - background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, - stop: 0 #10A5f2, stop: 1.0 #2e80eb); + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #10A5f2, stop: 1.0 #2e80eb); } #footer > QPushButton:pressed { - background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, - stop: 0 #0085e2, stop: 1.0 #0e60db); + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #0085e2, stop: 1.0 #0e60db); } #footer > QPushButton[secondary="true"] { margin-right: 10px; - background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, - stop: 0 #888888, stop: 1.0 #555555); + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #888888, stop: 1.0 #555555); } #footer > QPushButton[secondary="true"]:hover { - background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, - stop: 0 #999999, stop: 1.0 #666666); + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #999999, stop: 1.0 #666666); } #footer > QPushButton[secondary="true"]:pressed { - background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, - stop: 0 #555555, stop: 1.0 #777777); + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #555555, stop: 1.0 #777777); } /************** Project Settings **************/ @@ -356,6 +356,20 @@ QTabBar::tab:pressed font-size: 18px; } +#GemCatalogCart { + background-color: #555555; +} + +#GemCatalogCartCountLabel { + font-size: 12px; + background-color: #4285F4; + border-radius: 3px; +} + +#GemCatalogCartOverlaySectionLabel { + font-weight: 600; +} + /************** Gem Catalog (Inspector) **************/ #GemCatalogInspector { diff --git a/Code/Tools/ProjectManager/Resources/Summary.svg b/Code/Tools/ProjectManager/Resources/Summary.svg new file mode 100644 index 0000000000..fe26718aff --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/Summary.svg @@ -0,0 +1,3 @@ + + + diff --git a/Code/Tools/ProjectManager/Resources/WindowClose.svg b/Code/Tools/ProjectManager/Resources/WindowClose.svg new file mode 100644 index 0000000000..0485ff95cd --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/WindowClose.svg @@ -0,0 +1,4 @@ + + + + diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp index 6402121e4a..a98135d3e6 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp @@ -10,24 +10,229 @@ * */ -#include #include #include +#include #include +#include +#include namespace O3DE::ProjectManager { - GemCatalogHeaderWidget::GemCatalogHeaderWidget(GemSortFilterProxyModel* filterProxyModel, QWidget* parent) + CartOverlayWidget::CartOverlayWidget(GemModel* gemModel, QWidget* parent) + : QWidget(parent) + , m_gemModel(gemModel) + { + setObjectName("GemCatalogCart"); + + m_layout = new QVBoxLayout(); + m_layout->setSpacing(0); + m_layout->setMargin(0); + m_layout->setAlignment(Qt::AlignTop); + setLayout(m_layout); + + QHBoxLayout* hLayout = new QHBoxLayout(); + + QPushButton* closeButton = new QPushButton(); + closeButton->setFlat(true); + closeButton->setFocusPolicy(Qt::NoFocus); + closeButton->setIcon(QIcon(":/WindowClose.svg")); + connect(closeButton, &QPushButton::clicked, this, [=] + { + deleteLater(); + }); + hLayout->addSpacerItem(new QSpacerItem(10, 0, QSizePolicy::Expanding)); + hLayout->addWidget(closeButton); + m_layout->addLayout(hLayout); + + // enabled + { + m_enabledWidget = new QWidget(); + m_enabledWidget->setFixedWidth(s_width); + m_layout->addWidget(m_enabledWidget); + + QVBoxLayout* layout = new QVBoxLayout(); + layout->setAlignment(Qt::AlignTop); + m_enabledWidget->setLayout(layout); + + m_enabledLabel = new QLabel(); + m_enabledLabel->setObjectName("GemCatalogCartOverlaySectionLabel"); + layout->addWidget(m_enabledLabel); + m_enabledTagContainer = new TagContainerWidget(); + layout->addWidget(m_enabledTagContainer); + } + + // disabled + { + m_disabledWidget = new QWidget(); + m_disabledWidget->setFixedWidth(s_width); + m_layout->addWidget(m_disabledWidget); + + QVBoxLayout* layout = new QVBoxLayout(); + layout->setAlignment(Qt::AlignTop); + m_disabledWidget->setLayout(layout); + + m_disabledLabel = new QLabel(); + m_disabledLabel->setObjectName("GemCatalogCartOverlaySectionLabel"); + layout->addWidget(m_disabledLabel); + m_disabledTagContainer = new TagContainerWidget(); + layout->addWidget(m_disabledTagContainer); + } + + setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog); + + Update(); + connect(gemModel, &GemModel::dataChanged, this, [=] + { + Update(); + }); + } + + void CartOverlayWidget::Update() + { + const QVector toBeAdded = m_gemModel->GatherGemsToBeAdded(); + if (toBeAdded.isEmpty()) + { + m_enabledWidget->hide(); + } + else + { + m_enabledTagContainer->Update(ConvertFromModelIndices(toBeAdded)); + m_enabledLabel->setText(QString("%1 %2").arg(QString::number(toBeAdded.size()), tr("Gems to be enabled"))); + m_enabledWidget->show(); + } + + const QVector toBeRemoved = m_gemModel->GatherGemsToBeRemoved(); + if (toBeRemoved.isEmpty()) + { + m_disabledWidget->hide(); + } + else + { + m_disabledTagContainer->Update(ConvertFromModelIndices(toBeRemoved)); + m_disabledLabel->setText(QString("%1 %2").arg(QString::number(toBeRemoved.size()), tr("Gems to be disabled"))); + m_disabledWidget->show(); + } + } + + QStringList CartOverlayWidget::ConvertFromModelIndices(const QVector& gems) const + { + QStringList gemNames; + gemNames.reserve(gems.size()); + for (const QModelIndex& modelIndex : gems) + { + gemNames.push_back(GemModel::GetName(modelIndex)); + } + return gemNames; + } + + CartButton::CartButton(GemModel* gemModel, QWidget* parent) + : QWidget(parent) + , m_gemModel(gemModel) + { + m_layout = new QHBoxLayout(); + m_layout->setMargin(0); + setLayout(m_layout); + + QPushButton* iconButton = new QPushButton(); + iconButton->setFlat(true); + iconButton->setFocusPolicy(Qt::NoFocus); + iconButton->setIcon(QIcon(":/Summary.svg")); + iconButton->setFixedSize(s_iconSize, s_iconSize); + connect(iconButton, &QPushButton::clicked, this, &CartButton::ShowOverlay); + m_layout->addWidget(iconButton); + + m_countLabel = new QLabel(); + m_countLabel->setObjectName("GemCatalogCartCountLabel"); + m_countLabel->setFixedHeight(s_iconSize - 1); // Compensate for the empty icon space by using a slightly smaller label height. + m_layout->addWidget(m_countLabel); + + m_dropDownButton = new QPushButton(); + m_dropDownButton->setFlat(true); + m_dropDownButton->setFocusPolicy(Qt::NoFocus); + m_dropDownButton->setIcon(QIcon(":/CarrotArrowDown.svg")); + m_dropDownButton->setFixedSize(s_arrowDownIconSize, s_arrowDownIconSize); + connect(m_dropDownButton, &QPushButton::clicked, this, &CartButton::ShowOverlay); + m_layout->addWidget(m_dropDownButton); + + // Adjust the label text whenever the model gets updated. + connect(gemModel, &GemModel::dataChanged, [=] + { + const QVector toBeAdded = m_gemModel->GatherGemsToBeAdded(); + const QVector toBeRemoved = m_gemModel->GatherGemsToBeRemoved(); + + const int count = toBeAdded.size() + toBeRemoved.size(); + m_countLabel->setText(QString::number(count)); + + m_dropDownButton->setVisible(!toBeAdded.isEmpty() || !toBeRemoved.isEmpty()); + + // Automatically close the overlay window in case there are no gems to be enabled or disabled anymore. + if (m_cartOverlay && toBeAdded.isEmpty() && toBeRemoved.isEmpty()) + { + m_cartOverlay->deleteLater(); + m_cartOverlay = nullptr; + } + }); + } + + void CartButton::mousePressEvent([[maybe_unused]] QMouseEvent* event) + { + ShowOverlay(); + } + + void CartButton::ShowOverlay() + { + const QVector toBeAdded = m_gemModel->GatherGemsToBeAdded(); + const QVector toBeRemoved = m_gemModel->GatherGemsToBeRemoved(); + if (toBeAdded.isEmpty() && toBeRemoved.isEmpty()) + { + return; + } + + if (m_cartOverlay) + { + // Directly delete the former overlay before creating the new one. + // Don't use deleteLater() here. This might overwrite the new overlay pointer + // depending on the event queue. + delete m_cartOverlay; + } + + m_cartOverlay = new CartOverlayWidget(m_gemModel, this); + connect(m_cartOverlay, &QWidget::destroyed, this, [=] + { + // Reset the overlay pointer on destruction to prevent dangling pointers. + m_cartOverlay = nullptr; + }); + m_cartOverlay->show(); + + const QPoint parentPos = m_dropDownButton->mapToParent(m_dropDownButton->pos()); + const QPoint globalPos = m_dropDownButton->mapToGlobal(m_dropDownButton->pos()); + const QPoint offset(-4, 10); + m_cartOverlay->setGeometry(globalPos.x() - parentPos.x() - m_cartOverlay->width() + width() + offset.x(), + globalPos.y() + offset.y(), + m_cartOverlay->width(), + m_cartOverlay->height()); + } + + CartButton::~CartButton() + { + // Make sure the overlay window is automatically closed in case the gem catalog is destroyed. + if (m_cartOverlay) + { + m_cartOverlay->deleteLater(); + } + } + + GemCatalogHeaderWidget::GemCatalogHeaderWidget(GemModel* gemModel, GemSortFilterProxyModel* filterProxyModel, QWidget* parent) : QFrame(parent) { QHBoxLayout* hLayout = new QHBoxLayout(); hLayout->setAlignment(Qt::AlignLeft); - hLayout->setMargin(0); + hLayout->setContentsMargins(10, 7, 10, 7); setLayout(hLayout); setObjectName("GemCatalogHeaderWidget"); - - hLayout->addSpacing(7); + setFixedHeight(s_height); QLabel* titleLabel = new QLabel(tr("Gem Catalog")); titleLabel->setObjectName("GemCatalogTitle"); @@ -35,17 +240,23 @@ namespace O3DE::ProjectManager hLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding)); - AzQtComponents::SearchLineEdit* filterLineEdit = new AzQtComponents::SearchLineEdit(); - filterLineEdit->setStyleSheet("background-color: #DDDDDD;"); - connect(filterLineEdit, &QLineEdit::textChanged, this, [=](const QString& text) + m_filterLineEdit = new AzQtComponents::SearchLineEdit(); + m_filterLineEdit->setStyleSheet("background-color: #DDDDDD;"); + connect(m_filterLineEdit, &QLineEdit::textChanged, this, [=](const QString& text) { filterProxyModel->SetSearchString(text); }); - hLayout->addWidget(filterLineEdit); + hLayout->addWidget(m_filterLineEdit); hLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding)); - hLayout->addSpacerItem(new QSpacerItem(140, 0, QSizePolicy::Fixed)); - - setFixedHeight(60); + hLayout->addSpacerItem(new QSpacerItem(75, 0, QSizePolicy::Fixed)); + + CartButton* cartButton = new CartButton(gemModel); + hLayout->addWidget(cartButton); + } + + void GemCatalogHeaderWidget::ReinitForProject() + { + m_filterLineEdit->setText({}); } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.h index 3e065edd8f..bef7555618 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.h @@ -13,19 +13,81 @@ #pragma once #if !defined(Q_MOC_RUN) +#include +#include #include +#include #include +#include +#include +#include +#include #endif namespace O3DE::ProjectManager { + class CartOverlayWidget + : public QWidget + { + Q_OBJECT // AUTOMOC + + public: + CartOverlayWidget(GemModel* gemModel, QWidget* parent = nullptr); + void Update(); + + private: + QStringList ConvertFromModelIndices(const QVector& gems) const; + + QVBoxLayout* m_layout = nullptr; + GemModel* m_gemModel = nullptr; + + QWidget* m_enabledWidget = nullptr; + QLabel* m_enabledLabel = nullptr; + TagContainerWidget* m_enabledTagContainer = nullptr; + + QWidget* m_disabledWidget = nullptr; + QLabel* m_disabledLabel = nullptr; + TagContainerWidget* m_disabledTagContainer = nullptr; + + inline constexpr static int s_width = 240; + }; + + class CartButton + : public QWidget + { + Q_OBJECT // AUTOMOC + + public: + CartButton(GemModel* gemModel, QWidget* parent = nullptr); + ~CartButton(); + void ShowOverlay(); + + private: + void mousePressEvent(QMouseEvent* event) override; + + GemModel* m_gemModel = nullptr; + QHBoxLayout* m_layout = nullptr; + QLabel* m_countLabel = nullptr; + QPushButton* m_dropDownButton = nullptr; + CartOverlayWidget* m_cartOverlay = nullptr; + + inline constexpr static int s_iconSize = 24; + inline constexpr static int s_arrowDownIconSize = 8; + }; + class GemCatalogHeaderWidget : public QFrame { Q_OBJECT // AUTOMOC public: - explicit GemCatalogHeaderWidget(GemSortFilterProxyModel* filterProxyModel, QWidget* parent = nullptr); + explicit GemCatalogHeaderWidget(GemModel* gemModel, GemSortFilterProxyModel* filterProxyModel, QWidget* parent = nullptr); ~GemCatalogHeaderWidget() = default; + + void ReinitForProject(); + + private: + AzQtComponents::SearchLineEdit* m_filterLineEdit = nullptr; + inline constexpr static int s_height = 60; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp index aa36c1b0ab..4424767c0b 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp @@ -12,7 +12,6 @@ #include #include -#include #include #include #include @@ -35,8 +34,8 @@ namespace O3DE::ProjectManager vLayout->setSpacing(0); setLayout(vLayout); - GemCatalogHeaderWidget* headerWidget = new GemCatalogHeaderWidget(m_proxModel); - vLayout->addWidget(headerWidget); + m_headerWidget = new GemCatalogHeaderWidget(m_gemModel, m_proxModel); + vLayout->addWidget(m_headerWidget); QHBoxLayout* hLayout = new QHBoxLayout(); hLayout->setMargin(0); @@ -77,10 +76,11 @@ namespace O3DE::ProjectManager m_filterWidget->deleteLater(); } + m_proxModel->ResetFilters(); m_filterWidget = new GemFilterWidget(m_proxModel); m_filterWidgetLayout->addWidget(m_filterWidget); - m_proxModel->InvalidateFilter(); + m_headerWidget->ReinitForProject(); // Select the first entry after everything got correctly sized QTimer::singleShot(200, [=]{ diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h index 0847d9b74e..f5092e837a 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h @@ -14,6 +14,7 @@ #if !defined(Q_MOC_RUN) #include +#include #include #include #include @@ -40,6 +41,7 @@ namespace O3DE::ProjectManager GemListView* m_gemListView = nullptr; GemInspector* m_gemInspector = nullptr; GemModel* m_gemModel = nullptr; + GemCatalogHeaderWidget* m_headerWidget = nullptr; GemSortFilterProxyModel* m_proxModel = nullptr; QVBoxLayout* m_filterWidgetLayout = nullptr; GemFilterWidget* m_filterWidget = nullptr; diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp index 0fc0d89fcb..8aa68fb7a2 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp @@ -53,6 +53,7 @@ namespace O3DE::ProjectManager QFont standardFont(options.font); standardFont.setPixelSize(s_fontSize); + QFontMetrics standardFontMetrics(standardFont); painter->save(); painter->setClipping(true); @@ -78,8 +79,10 @@ namespace O3DE::ProjectManager } // Gem name - const QString gemName = GemModel::GetName(modelIndex); + QString gemName = GemModel::GetName(modelIndex); QFont gemNameFont(options.font); + const int firstColumnMaxTextWidth = s_summaryStartX - 30; + gemName = QFontMetrics(gemNameFont).elidedText(gemName, Qt::TextElideMode::ElideRight, firstColumnMaxTextWidth); gemNameFont.setPixelSize(s_gemNameFontSize); gemNameFont.setBold(true); QRect gemNameRect = GetTextRect(gemNameFont, gemName, s_gemNameFontSize); @@ -90,7 +93,8 @@ namespace O3DE::ProjectManager painter->drawText(gemNameRect, Qt::TextSingleLine, gemName); // Gem creator - const QString gemCreator = GemModel::GetCreator(modelIndex); + QString gemCreator = GemModel::GetCreator(modelIndex); + gemCreator = standardFontMetrics.elidedText(gemCreator, Qt::TextElideMode::ElideRight, firstColumnMaxTextWidth); QRect gemCreatorRect = GetTextRect(standardFont, gemCreator, s_fontSize); gemCreatorRect.moveTo(contentRect.left(), contentRect.top() + gemNameRect.height()); diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.cpp index 33936f417e..d8f41c077e 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.cpp @@ -130,4 +130,15 @@ namespace O3DE::ProjectManager invalidate(); emit OnInvalidated(); } + + void GemSortFilterProxyModel::ResetFilters() + { + m_searchString.clear(); + m_gemOriginFilter = {}; + m_platformFilter = {}; + m_typeFilter = {}; + m_featureFilter = {}; + + InvalidateFilter(); + } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.h index e5554c020c..f24a724ecf 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.h @@ -51,6 +51,7 @@ namespace O3DE::ProjectManager void SetFeatures(const QSet& features) { m_featureFilter = features; InvalidateFilter(); } void InvalidateFilter(); + void ResetFilters(); signals: void OnInvalidated(); From dbdf97069003a3db5cbded1f6b4b0cd4509aa230 Mon Sep 17 00:00:00 2001 From: gallowj Date: Fri, 4 Jun 2021 17:09:44 -0500 Subject: [PATCH 527/811] Atom15729 Fixed broken materials --- .../Assets/Materials/baseboards.material | 3 -- .../Lighthead_lightfacingemissive.material | 9 ---- .../PlayfulTeapot_playfulteapot.material | 12 ----- .../Assets/Materials/Copper/copper.material | 5 --- .../Assets/Materials/Plaster/plaster.material | 11 ----- .../Materials/Plastic_01/plastic_01.material | 11 ----- .../objects/sponza_mat_ceiling.material | 44 +++---------------- .../Assets/objects/sponza_mat_chain.material | 27 +++--------- .../Assets/objects/sponza_mat_leaf.material | 19 -------- .../Assets/objects/sponza_mat_lion.material | 35 +++------------ .../objects/sponza_mat_vaseplant.material | 18 -------- 11 files changed, 18 insertions(+), 176 deletions(-) diff --git a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/baseboards.material b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/baseboards.material index f75490c2ad..dee6ded191 100644 --- a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/baseboards.material +++ b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Materials/baseboards.material @@ -37,9 +37,6 @@ "factor": 0.4343433976173401, "textureMap": "Materials/Bricks038_8K/Bricks038_8K_Roughness.png", "useTexture": false - }, - "subsurfaceScattering": { - "useThicknessMap": false } } } diff --git a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Objects/Lighthead_lightfacingemissive.material b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Objects/Lighthead_lightfacingemissive.material index 21cb12a82c..ddc298a08b 100644 --- a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Objects/Lighthead_lightfacingemissive.material +++ b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Objects/Lighthead_lightfacingemissive.material @@ -18,15 +18,6 @@ }, "opacity": { "factor": 1.0 - }, - "subsurfaceScattering": { - "enableSubsurfaceScattering": true, - "quality": 1.0, - "scatterDistance": 2.626262664794922, - "subsurfaceScatterFactor": 1.0, - "thickness": 0.1414141058921814, - "transmissionMode": "ThinObject", - "transmissionScale": 1.8181817531585694 } } } diff --git a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Objects/PlayfulTeapot_playfulteapot.material b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Objects/PlayfulTeapot_playfulteapot.material index b46dd709b1..27540c587e 100644 --- a/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Objects/PlayfulTeapot_playfulteapot.material +++ b/Gems/AtomContent/LookDevelopmentStudioPixar/Assets/Objects/PlayfulTeapot_playfulteapot.material @@ -31,18 +31,6 @@ }, "roughness": { "factor": 0.0 - }, - "subsurfaceScattering": { - "enableSubsurfaceScattering": true, - "quality": 1.0, - "scatterColor": [ - 0.045288778841495517, - 0.24347294867038728, - 0.2060578316450119, - 1.0 - ], - "scatterDistance": 4.040403842926025, - "subsurfaceScatterFactor": 0.5 } } } diff --git a/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Copper/copper.material b/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Copper/copper.material index 4489e12c4d..80b7ea29f3 100644 --- a/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Copper/copper.material +++ b/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Copper/copper.material @@ -20,11 +20,6 @@ }, "roughness": { "factor": 0.20202019810676576 - }, - "subsurfaceScattering": { - "quality": 0.329292893409729, - "scatterDistance": 6.666666507720947, - "subsurfaceScatterFactor": 0.9595959782600403 } } } diff --git a/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Plaster/plaster.material b/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Plaster/plaster.material index 3121fdac24..cdf76f612d 100644 --- a/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Plaster/plaster.material +++ b/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Plaster/plaster.material @@ -28,17 +28,6 @@ }, "specularF0": { "factor": 1.0 - }, - "subsurfaceScattering": { - "quality": 0.9838383793830872, - "scatterColor": [ - 0.143602654337883, - 0.012634470127522946, - 0.0005798428319394589, - 1.0 - ], - "scatterDistance": 18.383838653564454, - "subsurfaceScatterFactor": 0.1414141058921814 } } } diff --git a/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Plastic_01/plastic_01.material b/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Plastic_01/plastic_01.material index e953d04238..227017e1ab 100644 --- a/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Plastic_01/plastic_01.material +++ b/Gems/AtomContent/ReferenceMaterials/Assets/Materials/Plastic_01/plastic_01.material @@ -25,17 +25,6 @@ }, "specularF0": { "factor": 1.0 - }, - "subsurfaceScattering": { - "quality": 0.9838383793830872, - "scatterColor": [ - 0.143602654337883, - 0.012634470127522946, - 0.0005798428319394589, - 1.0 - ], - "scatterDistance": 18.383838653564454, - "subsurfaceScatterFactor": 0.1414141058921814 } } } diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_ceiling.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_ceiling.material index 95d08d398b..88730c9556 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_ceiling.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_ceiling.material @@ -4,20 +4,15 @@ "parentMaterial": "", "propertyLayoutVersion": 3, "properties": { - "occlusion": { - "diffuseTextureMap": "Textures/ceiling_1k_ao.png" - }, "baseColor": { - "textureBlendMode": "Lerp", + "color": [ + 0.800000011920929, + 0.800000011920929, + 0.800000011920929, + 1.0 + ], "textureMap": "Textures/ceiling_1k_basecolor.png" }, - "clearCoat": { - "enable": true, - "factor": 0.5, - "influenceMap": "Textures/ceiling_1k_ao.png", - "normalMap": "Textures/ceiling_1k_normal.png", - "roughness": 0.30000001192092898 - }, "emissive": { "color": [ 0.0, @@ -26,33 +21,8 @@ 1.0 ] }, - "general": { - "applySpecularAA": true - }, - "irradiance": { - "color": [ - 1.0, - 0.7591058015823364, - 0.43776607513427737, - 1.0 - ] - }, - "normal": { - "textureMap": "Textures/ceiling_1k_normal.png" - }, "opacity": { "factor": 1.0 - }, - "parallax": { - "algorithm": "ContactRefinement", - "factor": 0.019999999552965165, - "pdo": true, - "quality": "Medium", - "textureMap": "Textures/ceiling_1k_height.png", - "useTexture": false - }, - "roughness": { - "textureMap": "Textures/ceiling_1k_roughness.png" } } -} +} \ No newline at end of file diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_chain.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_chain.material index 223bd0a24f..1ed442a9e0 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_chain.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_chain.material @@ -13,31 +13,16 @@ ], "textureMap": "Textures/chain_basecolor.png" }, - "general": { - "applySpecularAA": true - }, - "irradiance": { + "emissive": { "color": [ - 0.4891279339790344, - 0.7931944727897644, - 1.0, + 0.0, + 0.0, + 0.0, 1.0 ] }, - "metallic": { - "textureMap": "Textures/chain_alpha.png" - }, - "normal": { - "textureMap": "Textures/chain_normal.jpg" - }, "opacity": { - "alphaSource": "Split", - "factor": 0.30000001192092898, - "mode": "Cutout", - "textureMap": "Textures/chain_alpha.png" - }, - "roughness": { - "factor": 0.4000000059604645 + "factor": 1.0 } } -} +} \ No newline at end of file diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_leaf.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_leaf.material index ac326ae935..c95d0a662b 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_leaf.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_leaf.material @@ -47,25 +47,6 @@ }, "roughness": { "textureMap": "Textures/thorn_roughness.png" - }, - "subsurfaceScattering": { - "enableSubsurfaceScattering": true, - "quality": 1.0, - "scatterColor": [ - 0.28143739700317385, - 1.0, - 0.13000686466693879, - 1.0 - ], - "scatterDistance": 1.0, - "thickness": 0.10000000149011612, - "transmissionMode": "ThinObject", - "transmissionTint": [ - 0.07225146889686585, - 0.16981765627861024, - 0.04444953054189682, - 1.0 - ] } } } diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_lion.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_lion.material index b1f78aa33f..08eb920607 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_lion.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_lion.material @@ -4,9 +4,6 @@ "parentMaterial": "", "propertyLayoutVersion": 3, "properties": { - "occlusion": { - "diffuseTextureMap": "Textures/lion_1k_ao.png" - }, "baseColor": { "color": [ 0.800000011920929, @@ -16,38 +13,16 @@ ], "textureMap": "Textures/lion_1k_basecolor.png" }, - "general": { - "applySpecularAA": true - }, - "irradiance": { + "emissive": { "color": [ - 1.0, - 0.7364919781684876, - 0.3672388792037964, + 0.0, + 0.0, + 0.0, 1.0 ] }, - "metallic": { - "textureMap": "Textures/lion_1k_metallic.png" - }, - "normal": { - "textureMap": "Textures/lion_1k_normal.jpg" - }, "opacity": { "factor": 1.0 - }, - "parallax": { - "algorithm": "ContactRefinement", - "factor": 0.009999999776482582, - "pdo": true, - "quality": "Ultra", - "textureMap": "Textures/lion_1k_height.png" - }, - "roughness": { - "textureMap": "Textures/lion_1k_roughness.png" - }, - "specularF0": { - "enableMultiScatterCompensation": true } } -} +} \ No newline at end of file diff --git a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vaseplant.material b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vaseplant.material index 37d9e2c01c..290ddc81a6 100644 --- a/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vaseplant.material +++ b/Gems/AtomContent/Sponza/Assets/objects/sponza_mat_vaseplant.material @@ -28,24 +28,6 @@ "doubleSided": true, "factor": 0.28999999165534975, "mode": "Cutout" - }, - "subsurfaceScattering": { - "enableSubsurfaceScattering": true, - "quality": 1.0, - "scatterColor": [ - 0.07421988248825073, - 0.10223544389009476, - 0.0, - 1.0 - ], - "subsurfaceScatterFactor": 0.0, - "transmissionMode": "ThinObject", - "transmissionTint": [ - 0.33716335892677309, - 0.4620737135410309, - 0.0, - 1.0 - ] } } } From e71a4656bc1a3a304ee124c426d0936dafc22a38 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 4 Jun 2021 15:10:20 -0700 Subject: [PATCH 528/811] SPEC-2513 Fixes to enable w4450 (#1145) * Fix for w4457 * Nothing to fix, seems we deleted all the code that was causing this offense --- cmake/Platform/Common/MSVC/Configurations_msvc.cmake | 1 - 1 file changed, 1 deletion(-) diff --git a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake index 357d578c44..d0e4d9ed73 100644 --- a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake +++ b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake @@ -72,7 +72,6 @@ ly_append_configurations_options( /wd4366 # the result of unary operator may be unaligned /wd4389 # comparison, signed/unsigned mismatch /wd4436 # the result of unary operator may be unaligned - /wd4450 # declaration hides global declaration # Enabling warnings that are disabled by default from /W4 # https://docs.microsoft.com/en-us/cpp/preprocessor/compiler-warnings-that-are-off-by-default?view=vs-2019 From cf35585bc0d50e6e09c6e712bdb66351cf40fc94 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 4 Jun 2021 15:25:57 -0700 Subject: [PATCH 529/811] Making incremental linking off by default (#1154) --- cmake/Platform/Common/MSVC/Configurations_msvc.cmake | 2 +- scripts/build/Platform/Windows/build_config.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake index d0e4d9ed73..8c22677f91 100644 --- a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake +++ b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake @@ -126,7 +126,7 @@ ly_append_configurations_options( /INCREMENTAL:NO ) -set(LY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG TRUE CACHE BOOL "Indicates if incremental linking is used in debug configurations (default = TRUE)") +set(LY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG FALSE CACHE BOOL "Indicates if incremental linking is used in debug configurations (default = FALSE)") if(LY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG) ly_append_configurations_options( COMPILATION_DEBUG diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index fc4668de0a..552ef2c6fd 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -87,7 +87,7 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG=FALSE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" @@ -101,7 +101,7 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG=FALSE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_smoke TEST_SUITE_main", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", From 1396110f6d0edc8795ae7a439945b399b3684e5a Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 4 Jun 2021 15:46:19 -0700 Subject: [PATCH 530/811] Preventing builds from cleaning on each step (#1151) --- scripts/build/Jenkins/Jenkinsfile | 14 +++++++------- scripts/build/Platform/Linux/build_linux.sh | 1 - scripts/build/Platform/Mac/build_mac.sh | 1 - scripts/build/Platform/Windows/build_windows.cmd | 1 - 4 files changed, 7 insertions(+), 10 deletions(-) diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile index 2f6be2b060..3cf7d92ba6 100644 --- a/scripts/build/Jenkins/Jenkinsfile +++ b/scripts/build/Jenkins/Jenkinsfile @@ -313,13 +313,13 @@ def PreBuildCommonSteps(Map pipelineConfig, String repositoryName, String projec script: 'python/get_python.bat' } - if(env.CLEAN_OUTPUT_DIRECTORY?.toBoolean() || env.CLEAN_ASSETS?.toBoolean()) { - def command = "${pipelineConfig.PYTHON_DIR}/python" - if(env.IS_UNIX) command += '.sh' - else command += '.cmd' - command += " -u ${pipelineConfig.BUILD_ENTRY_POINT} --platform ${platform} --type clean" - palSh(command, "Running ${platform} clean") - } + // Always run the clean step, the scripts detect what variables were set, but it also cleans if + // the NODE_LABEL has changed + def command = "${pipelineConfig.PYTHON_DIR}/python" + if(env.IS_UNIX) command += '.sh' + else command += '.cmd' + command += " -u ${pipelineConfig.BUILD_ENTRY_POINT} --platform ${platform} --type clean" + palSh(command, "Running ${platform} clean") } } diff --git a/scripts/build/Platform/Linux/build_linux.sh b/scripts/build/Platform/Linux/build_linux.sh index ef1b1dcb96..f88d3ab116 100755 --- a/scripts/build/Platform/Linux/build_linux.sh +++ b/scripts/build/Platform/Linux/build_linux.sh @@ -14,7 +14,6 @@ set -o errexit # exit on the first failure encountered BASEDIR=$(dirname "$0") source $BASEDIR/env_linux.sh -source $BASEDIR/clean_linux.sh mkdir -p ${OUTPUT_DIRECTORY} SOURCE_DIRECTORY=${PWD} diff --git a/scripts/build/Platform/Mac/build_mac.sh b/scripts/build/Platform/Mac/build_mac.sh index 4a61f97fe4..473a968d98 100755 --- a/scripts/build/Platform/Mac/build_mac.sh +++ b/scripts/build/Platform/Mac/build_mac.sh @@ -14,7 +14,6 @@ set -o errexit # exit on the first failure encountered BASEDIR=$(dirname "$0") source $BASEDIR/env_mac.sh -source $BASEDIR/clean_mac.sh mkdir -p ${OUTPUT_DIRECTORY} SOURCE_DIRECTORY=${PWD} diff --git a/scripts/build/Platform/Windows/build_windows.cmd b/scripts/build/Platform/Windows/build_windows.cmd index 474c1720df..4dcd12d008 100644 --- a/scripts/build/Platform/Windows/build_windows.cmd +++ b/scripts/build/Platform/Windows/build_windows.cmd @@ -13,7 +13,6 @@ REM SETLOCAL EnableDelayedExpansion CALL %~dp0env_windows.cmd -CALL %~dp0clean_windows.cmd IF NOT EXIST "%OUTPUT_DIRECTORY%" ( MKDIR %OUTPUT_DIRECTORY%. From 74f474aae2084c0489fd9dfa8b5025970b197e03 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Fri, 4 Jun 2021 18:02:09 -0500 Subject: [PATCH 531/811] Add unit tests for the ViewportScreen ndc <-> worldspace utility functions (#1149) Add ScreenNdcToWorld function to enable round trip testing. --- .../AzFramework/Viewport/ViewportScreen.cpp | 17 +++- .../AzFramework/Viewport/ViewportScreen.h | 8 +- .../Tests/Viewport/ViewportScreenTests.cpp | 87 ++++++++++++++++++- 3 files changed, 104 insertions(+), 8 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp index 5d2d02a398..8283e0b1f2 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp @@ -128,12 +128,12 @@ namespace AzFramework worldPosition, CameraView(cameraState), CameraProjection(cameraState), cameraState.m_viewportSize); } - AZ::Vector3 ScreenToWorld( - const ScreenPoint& screenPosition, const AZ::Matrix4x4& inverseCameraView, - const AZ::Matrix4x4& inverseCameraProjection, const AZ::Vector2& viewportSize) + AZ::Vector3 ScreenNDCToWorld( + const AZ::Vector2& normalizedScreenPosition, const AZ::Matrix4x4& inverseCameraView, + const AZ::Matrix4x4& inverseCameraProjection) { // convert screen space coordinates from <0, 1> to <-1,1> range - const auto ndcPosition = NDCFromScreenPoint(screenPosition, viewportSize) * 2.0f - AZ::Vector2::CreateOne(); + const auto ndcPosition = normalizedScreenPosition * 2.0f - AZ::Vector2::CreateOne(); // transform ndc space position to clip space const auto clipSpacePosition = inverseCameraProjection * Vector2ToVector4(ndcPosition, -1.0f, 1.0f); @@ -145,6 +145,15 @@ namespace AzFramework return worldPosition; } + AZ::Vector3 ScreenToWorld( + const ScreenPoint& screenPosition, const AZ::Matrix4x4& inverseCameraView, + const AZ::Matrix4x4& inverseCameraProjection, const AZ::Vector2& viewportSize) + { + const auto normalizedScreenPosition = NDCFromScreenPoint(screenPosition, viewportSize); + + return ScreenNDCToWorld(normalizedScreenPosition, inverseCameraView, inverseCameraProjection); + } + AZ::Vector3 ScreenToWorld(const ScreenPoint& screenPosition, const CameraState& cameraState) { return ScreenToWorld( diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.h b/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.h index a2c650465f..844f52b565 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.h @@ -42,7 +42,7 @@ namespace AzFramework const AZ::Vector3& worldPosition, const AZ::Matrix4x4& cameraView, const AZ::Matrix4x4& cameraProjection, const AZ::Vector2& viewportSize); - //! Unprojects a position in screen space to world space. + //! Unprojects a position in screen space pixel coordinates to world space. //! Note: The position returned will be on the near clip plane of the camera in world space. AZ::Vector3 ScreenToWorld(const ScreenPoint& screenPosition, const CameraState& cameraState); @@ -52,6 +52,12 @@ namespace AzFramework const ScreenPoint& screenPosition, const AZ::Matrix4x4& inverseCameraView, const AZ::Matrix4x4& inverseCameraProjection, const AZ::Vector2& viewportSize); + //! Unprojects a position in screen space normalized device coordinates to world space. + //! Note: The position returned will be on the near clip plane of the camera in world space. + AZ::Vector3 ScreenNDCToWorld( + const AZ::Vector2& ndcPosition, const AZ::Matrix4x4& inverseCameraView, + const AZ::Matrix4x4& inverseCameraProjection); + //! Returns the camera projection for the current camera state. AZ::Matrix4x4 CameraProjection(const CameraState& cameraState); diff --git a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp index 18462bc97b..d82c7ec425 100644 --- a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -23,6 +24,15 @@ namespace UnitTest { + // transform a point from normalized device coordinates to world space, and then from world space back to normalized device coordinates + AZ::Vector2 ScreenNDCToWorldToScreenNDC( + const AZ::Vector2& ndcPoint, const AzFramework::CameraState& cameraState) + { + const auto worldResult = AzFramework::ScreenNDCToWorld(ndcPoint, InverseCameraView(cameraState), InverseCameraProjection(cameraState)); + const auto ndcResult = AzFramework::WorldToScreenNDC(worldResult, CameraView(cameraState), CameraProjection(cameraState)); + return AZ::Vector3ToVector2(ndcResult); + } + // transform a point from screen space to world space, and then from world space back to screen space AzFramework::ScreenPoint ScreenToWorldToScreen( const AzFramework::ScreenPoint& screenPoint, const AzFramework::CameraState& cameraState) @@ -30,7 +40,8 @@ namespace UnitTest const auto worldResult = AzFramework::ScreenToWorld(screenPoint, cameraState); return AzFramework::WorldToScreen(worldResult, cameraState); } - + //////////////////////////////////////////////////////////////////////////////////////////////////////// + // ScreenPoint tests TEST(ViewportScreen, WorldToScreenAndScreenToWorldReturnsTheSameValueIdentityCameraOffsetFromOrigin) { using AzFramework::ScreenPoint; @@ -38,8 +49,6 @@ namespace UnitTest const auto screenDimensions = AZ::Vector2(800.0f, 600.0f); const auto cameraPosition = AZ::Vector3::CreateAxisY(-10.0f); - // note: nearClip is 0.1 - the world space value returned will be aligned to the near clip - // plane of the camera so use that to confirm the mapping to/from is correct const auto cameraState = AzFramework::CreateIdentityDefaultCamera(cameraPosition, screenDimensions); { const auto expectedScreenPoint = ScreenPoint{600, 450}; @@ -81,6 +90,8 @@ namespace UnitTest EXPECT_EQ(resultScreenPoint, expectedScreenPoint); } + // note: nearClip is 0.1 - the world space value returned will be aligned to the near clip + // plane of the camera so use that to confirm the mapping to/from is correct TEST(ViewportScreen, ScreenToWorldReturnsPositionOnNearClipPlaneInWorldSpace) { using AzFramework::ScreenPoint; @@ -94,7 +105,75 @@ namespace UnitTest const auto worldResult = AzFramework::ScreenToWorld(ScreenPoint{400, 300}, cameraState); EXPECT_THAT(worldResult, IsClose(AZ::Vector3(10.1f, 0.0f, 0.0f))); } + + //////////////////////////////////////////////////////////////////////////////////////////////////////// + // NDC tests + TEST(ViewportScreen, WorldToScreenNDCAndScreenNDCToWorldReturnsTheSameValueIdentityCameraOffsetFromOrigin) + { + using NdcPoint = AZ::Vector2; + + const auto screenDimensions = AZ::Vector2(800.0f, 600.0f); + const auto cameraPosition = AZ::Vector3::CreateAxisY(-10.0f); + const auto cameraState = AzFramework::CreateIdentityDefaultCamera(cameraPosition, screenDimensions); + { + const auto expectedNdcPoint = NdcPoint{0.75f, 0.75f}; + const auto resultNdcPoint = ScreenNDCToWorldToScreenNDC(expectedNdcPoint, cameraState); + EXPECT_THAT(resultNdcPoint, IsClose(expectedNdcPoint)); + } + + { + const auto expectedNdcPoint = NdcPoint{0.5f, 0.5f}; + const auto resultNdcPoint = ScreenNDCToWorldToScreenNDC(expectedNdcPoint, cameraState); + EXPECT_THAT(resultNdcPoint, IsClose(expectedNdcPoint)); + } + + { + const auto expectedNdcPoint = NdcPoint{0.0f, 0.0f}; + const auto resultNdcPoint = ScreenNDCToWorldToScreenNDC(expectedNdcPoint, cameraState); + EXPECT_THAT(resultNdcPoint, IsClose(expectedNdcPoint)); + } + + { + const auto expectedNdcPoint = NdcPoint{1.0f, 1.0f}; + const auto resultNdcPoint = ScreenNDCToWorldToScreenNDC(expectedNdcPoint, cameraState); + EXPECT_THAT(resultNdcPoint, IsClose(expectedNdcPoint)); + } + } + + TEST(ViewportScreen, WorldToScreenNDCAndScreenNDCToWorldReturnsTheSameValueOrientatedCamera) + { + using NdcPoint = AZ::Vector2; + + const auto screenDimensions = AZ::Vector2(800.0f, 600.0f); + const auto cameraTransform = + AZ::Transform::CreateRotationX(AZ::DegToRad(45.0f)) * AZ::Transform::CreateRotationZ(AZ::DegToRad(90.0f)); + + const auto cameraState = AzFramework::CreateDefaultCamera(cameraTransform, screenDimensions); + + const auto expectedNdcPoint = NdcPoint{0.25f, 0.5f}; + const auto resultNdcPoint = ScreenNDCToWorldToScreenNDC(expectedNdcPoint, cameraState); + EXPECT_THAT(resultNdcPoint, IsClose(expectedNdcPoint)); + } + + // note: nearClip is 0.1 - the world space value returned will be aligned to the near clip + // plane of the camera so use that to confirm the mapping to/from is correct + TEST(ViewportScreen, ScreenNDCToWorldReturnsPositionOnNearClipPlaneInWorldSpace) + { + using NdcPoint = AZ::Vector2; + + const auto screenDimensions = AZ::Vector2(800.0f, 600.0f); + const auto cameraTransform = AZ::Transform::CreateTranslation(AZ::Vector3(10.0f, 0.0f, 0.0f)) * + AZ::Transform::CreateRotationZ(AZ::DegToRad(-90.0f)); + + const auto cameraState = AzFramework::CreateDefaultCamera(cameraTransform, screenDimensions); + + const auto worldResult = AzFramework::ScreenNDCToWorld(NdcPoint{0.5f, 0.5f}, InverseCameraView(cameraState), InverseCameraProjection(cameraState)); + EXPECT_THAT(worldResult, IsClose(AZ::Vector3(10.1f, 0.0f, 0.0f))); + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////// + // ScreenVector tests TEST(ViewportScreen, SubstractingScreenPointGivesScreenVector) { using AzFramework::ScreenPoint; @@ -220,6 +299,8 @@ namespace UnitTest EXPECT_NEAR(AzFramework::ScreenVectorLength(ScreenVector(12, 15)), 19.20937f, 0.001f); } + //////////////////////////////////////////////////////////////////////////////////////////////////////// + // Other tests TEST(ViewportScreen, CanGetCameraTransformFromCameraViewAndBack) { const auto screenDimensions = AZ::Vector2(1024.0f, 768.0f); From 6ee58b7b641ea9b7bd8727217920e0f9477bc664 Mon Sep 17 00:00:00 2001 From: amzn-sj Date: Fri, 4 Jun 2021 16:09:37 -0700 Subject: [PATCH 532/811] Fix overrides for array in editor setreg. Remove the test overrides. --- Registry/Platform/Mac/streamer.editor.setreg | 5 ++++ Registry/Platform/Mac/streamer.test.setreg | 24 -------------------- 2 files changed, 5 insertions(+), 24 deletions(-) delete mode 100644 Registry/Platform/Mac/streamer.test.setreg diff --git a/Registry/Platform/Mac/streamer.editor.setreg b/Registry/Platform/Mac/streamer.editor.setreg index 85360d128e..dafcfdc9d9 100644 --- a/Registry/Platform/Mac/streamer.editor.setreg +++ b/Registry/Platform/Mac/streamer.editor.setreg @@ -18,6 +18,11 @@ // can have open is set to 256. So we need to set this to a lower value than on PC. // This limit is set by "launchctl limit maxfiles" "MaxFileHandles": 65 + }, + { + "$type": "AzFramework::RemoteStorageDriveConfig", + // The maximum number of file handles that the drive will cache. + "MaxFileHandles": 1024 } ] } diff --git a/Registry/Platform/Mac/streamer.test.setreg b/Registry/Platform/Mac/streamer.test.setreg deleted file mode 100644 index df41b7a350..0000000000 --- a/Registry/Platform/Mac/streamer.test.setreg +++ /dev/null @@ -1,24 +0,0 @@ -{ - "Amazon": - { - "AzCore": - { - "Streamer": - { - "Profiles": - { - "Generic": - { - "Stack": - [ - { - "$type": "AZ::IO::StorageDriveConfig", - "MaxFileHandles": 65 - } - ] - } - } - } - } - } -} \ No newline at end of file From 9b1775427895177c6d0125dd6d6ed6bc95d6c823 Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Fri, 4 Jun 2021 16:14:25 -0700 Subject: [PATCH 533/811] Project Template details and preview changes --- .../Resources/ArrowBack_Hover.svg | 3 + .../Resources/DefaultTemplate.png | 3 + .../Resources/ProjectManager.qrc | 2 + .../Resources/ProjectManager.qss | 67 ++++++- .../Source/CreateProjectCtrl.cpp | 183 ++++++++++++------ .../ProjectManager/Source/CreateProjectCtrl.h | 36 +++- .../Source/NewProjectSettingsScreen.cpp | 127 ++++++++++-- .../Source/NewProjectSettingsScreen.h | 14 ++ .../Source/ProjectTemplateInfo.h | 1 + .../ProjectManager/Source/PythonBindings.cpp | 9 +- .../Source/TemplateButtonWidget.cpp | 65 +++++++ .../Source/TemplateButtonWidget.h | 37 ++++ .../project_manager_files.cmake | 2 + Templates/DefaultProject/template.json | 5 +- 14 files changed, 464 insertions(+), 90 deletions(-) create mode 100644 Code/Tools/ProjectManager/Resources/ArrowBack_Hover.svg create mode 100644 Code/Tools/ProjectManager/Resources/DefaultTemplate.png create mode 100644 Code/Tools/ProjectManager/Source/TemplateButtonWidget.cpp create mode 100644 Code/Tools/ProjectManager/Source/TemplateButtonWidget.h diff --git a/Code/Tools/ProjectManager/Resources/ArrowBack_Hover.svg b/Code/Tools/ProjectManager/Resources/ArrowBack_Hover.svg new file mode 100644 index 0000000000..5b3b14f09a --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/ArrowBack_Hover.svg @@ -0,0 +1,3 @@ + + + diff --git a/Code/Tools/ProjectManager/Resources/DefaultTemplate.png b/Code/Tools/ProjectManager/Resources/DefaultTemplate.png new file mode 100644 index 0000000000..2634c383fc --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/DefaultTemplate.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8358f4dad9878c662b9819b2b346622af691eb45f8eddc28fff79a50650ae6cf +size 2503 diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qrc b/Code/Tools/ProjectManager/Resources/ProjectManager.qrc index 62b7d23e9c..33acfa9e1b 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qrc +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qrc @@ -7,6 +7,7 @@ AddOffset.svg AddOffset_Hover.svg ArrowBack.svg + ArrowBack_Hover.svg build.svg FolderOffset.svg FolderOffset_Hover.svg @@ -18,6 +19,7 @@ Linux.svg macOS.svg DefaultProjectImage.png + DefaultTemplate.png ArrowDownLine.svg ArrowUpLine.svg o3de.svg diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qss b/Code/Tools/ProjectManager/Resources/ProjectManager.qss index 6fd4086c58..8b7470051c 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qss +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qss @@ -136,11 +136,9 @@ QTabBar::tab:pressed #header QPushButton:focus { border:none; } -#header QPushButton:hover { - background:#333333 url(:/ArrowBack.svg) no-repeat center; -} +#header QPushButton:hover, #header QPushButton:pressed { - background:#222222 url(:/ArrowBack.svg) no-repeat center; + background:transparent url(:/ArrowBack_Hover.svg) no-repeat center; } #headerTitle { @@ -210,9 +208,6 @@ QTabBar::tab:pressed #projectTemplate { margin: 55px 0 0 50px; - max-width: 780px; - min-height:200px; - max-height:200px; } #projectTemplateLabel { font-size:16px; @@ -227,11 +222,67 @@ QTabBar::tab:pressed #projectTemplateDetails { background-color:#444444; - max-width:240px; + max-width:20%; min-width:240px; margin-left:30px; } +#projectTemplateDetails #displayName, +#projectTemplateDetails #includedGemsTitle { + font-size:18px; +} + +#projectTemplateDetails #moreGems { + font-size:14px; + margin-top:20px; +} + +#projectTemplateDetails #includedGemsTitle { + margin-top:5px; + margin-bottom:5px; +} + +#projectTemplateDetails #summary { + padding-bottom:0px; + border-bottom:2px solid #555555; + min-height:80px; + qproperty-alignment: AlignTop; +} + +#projectTemplateDetails #browseCatalog { + margin:5px 0px 15px 0px; +} + +#projectTemplate QPushButton { + qproperty-flat: true; + min-width: 96px; + max-width: 96px; + min-height: 160px; + max-height: 160px; +} +#projectTemplate #templateLabel { + qproperty-alignment: AlignCenter; +} +#projectTemplate QPushButton #templateImage { + border:3px solid transparent; + border-radius: 4px; +} +#projectTemplate QPushButton[Checked="true"] #templateImage { + border:3px solid #1e70eb; +} +#projectTemplate QPushButton[Checked="true"] #templateLabel { + font-weight:bold; +} +#projectTemplate QPushButton:hover { + background-color: #444444; +} +#projectTemplate QPushButton:focus { + outline: none; + border:none; +} + + + #projectSettingsTab::tab-bar { left: 60px; } diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp index 85e34aeced..4498a6bc82 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -41,24 +42,33 @@ namespace O3DE::ProjectManager m_stack = new QStackedWidget(this); m_stack->setObjectName("body"); - m_stack->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding)); - m_stack->addWidget(new NewProjectSettingsScreen()); - m_gemCatalog = new GemCatalogScreen(); - m_stack->addWidget(m_gemCatalog); + m_stack->setSizePolicy(QSizePolicy(QSizePolicy::Preferred,QSizePolicy::Expanding)); + + m_newProjectSettingsScreen = new NewProjectSettingsScreen(this); + m_stack->addWidget(m_newProjectSettingsScreen); + + m_gemCatalogScreen = new GemCatalogScreen(this); + m_stack->addWidget(m_gemCatalogScreen); vLayout->addWidget(m_stack); - QDialogButtonBox* backNextButtons = new QDialogButtonBox(); - backNextButtons->setObjectName("footer"); - vLayout->addWidget(backNextButtons); + QDialogButtonBox* buttons = new QDialogButtonBox(); + buttons->setObjectName("footer"); + vLayout->addWidget(buttons); - m_backButton = backNextButtons->addButton(tr("Back"), QDialogButtonBox::RejectRole); - m_backButton->setProperty("secondary", true); - m_nextButton = backNextButtons->addButton(tr("Next"), QDialogButtonBox::ApplyRole); +#ifdef TEMPLATE_GEM_CONFIGURATION_ENABLED + connect(m_newProjectSettingsScreen, &ScreenWidget::ChangeScreenRequest, this, &CreateProjectCtrl::OnChangeScreenRequest); - connect(m_backButton, &QPushButton::clicked, this, &CreateProjectCtrl::HandleBackButton); - connect(m_nextButton, &QPushButton::clicked, this, &CreateProjectCtrl::HandleNextButton); + m_secondaryButton = buttons->addButton(tr("Back"), QDialogButtonBox::RejectRole); + m_secondaryButton->setProperty("secondary", true); + m_secondaryButton->setVisible(false); + connect(m_secondaryButton, &QPushButton::clicked, this, &CreateProjectCtrl::HandleSecondaryButton); Update(); +#endif // TEMPLATE_GEM_CONFIGURATION_ENABLED + + m_primaryButton = buttons->addButton(tr("Create Project"), QDialogButtonBox::ApplyRole); + connect(m_primaryButton, &QPushButton::clicked, this, &CreateProjectCtrl::HandlePrimaryButton); + setLayout(vLayout); } @@ -80,8 +90,10 @@ namespace O3DE::ProjectManager { if (m_stack->currentIndex() > 0) { - m_stack->setCurrentIndex(m_stack->currentIndex() - 1); - Update(); +#ifdef TEMPLATE_GEM_CONFIGURATION_ENABLED + PreviousScreen(); +#endif // TEMPLATE_GEM_CONFIGURATION_ENABLED + } else { @@ -89,70 +101,121 @@ namespace O3DE::ProjectManager } } - void CreateProjectCtrl::HandleNextButton() +#ifdef TEMPLATE_GEM_CONFIGURATION_ENABLED + void CreateProjectCtrl::HandleSecondaryButton() { - ScreenWidget* currentScreen = reinterpret_cast(m_stack->currentWidget()); - ProjectManagerScreen screenEnum = currentScreen->GetScreenEnum(); - - if (screenEnum == ProjectManagerScreen::NewProjectSettings) + if (m_stack->currentIndex() > 0) { - auto newProjectScreen = reinterpret_cast(currentScreen); - if (newProjectScreen) - { - if (!newProjectScreen->Validate()) - { - QMessageBox::critical(this, tr("Invalid project settings"), tr("Invalid project settings")); - return; - } - - m_projectInfo = newProjectScreen->GetProjectInfo(); - m_projectTemplatePath = newProjectScreen->GetProjectTemplatePath(); - - // The next page is the gem catalog. Gather the available gems that will be shown in the gem catalog. - m_gemCatalog->ReinitForProject(m_projectInfo.m_path, /*isNewProject=*/true); - } - } - - if (m_stack->currentIndex() != m_stack->count() - 1) - { - m_stack->setCurrentIndex(m_stack->currentIndex() + 1); - Update(); + // return to Project Settings page + PreviousScreen(); } else { - auto result = PythonBindingsInterface::Get()->CreateProject(m_projectTemplatePath, m_projectInfo); + // Configure Gems + NextScreen(); + } + } + + void CreateProjectCtrl::Update() + { + if (m_stack->currentWidget() == m_gemCatalogScreen) + { + m_header->setSubTitle(tr("Configure project with Gems")); + m_secondaryButton->setVisible(false); + } + else + { + m_header->setSubTitle(tr("Enter Project Details")); + m_secondaryButton->setVisible(true); + m_secondaryButton->setText(tr("Configure Gems")); + } + } + + void CreateProjectCtrl::OnChangeScreenRequest(ProjectManagerScreen screen) + { + if (screen == ProjectManagerScreen::GemCatalog) + { + HandleSecondaryButton(); + } + else + { + emit ChangeScreenRequest(screen); + } + } + + void CreateProjectCtrl::NextScreen() + { + if (m_stack->currentIndex() < m_stack->count()) + { + if(CurrentScreenIsValid()) + { + m_stack->setCurrentIndex(m_stack->currentIndex() + 1); + + QString projectTemplatePath = m_newProjectSettingsScreen->GetProjectTemplatePath(); + m_gemCatalogScreen->ReinitForProject(projectTemplatePath + "/Template", /*isNewProject=*/true); + + Update(); + } + else + { + QMessageBox::warning(this, tr("Invalid project settings"), tr("Please correct the indicated project settings and try again.")); + } + } + } + + void CreateProjectCtrl::PreviousScreen() + { + // we don't require the current screen to be valid when moving back + if (m_stack->currentIndex() > 0) + { + m_stack->setCurrentIndex(m_stack->currentIndex() - 1); + Update(); + } + } +#endif // TEMPLATE_GEM_CONFIGURATION_ENABLED + + void CreateProjectCtrl::HandlePrimaryButton() + { + CreateProject(); + } + + bool CreateProjectCtrl::CurrentScreenIsValid() + { + if (m_stack->currentWidget() == m_newProjectSettingsScreen) + { + return m_newProjectSettingsScreen->Validate(); + } + + return true; + } + + void CreateProjectCtrl::CreateProject() + { + if (m_newProjectSettingsScreen->Validate()) + { + ProjectInfo projectInfo = m_newProjectSettingsScreen->GetProjectInfo(); + QString projectTemplatePath = m_newProjectSettingsScreen->GetProjectTemplatePath(); + + auto result = PythonBindingsInterface::Get()->CreateProject(projectTemplatePath, projectInfo); if (result.IsSuccess()) { // automatically register the project - PythonBindingsInterface::Get()->AddProject(m_projectInfo.m_path); + PythonBindingsInterface::Get()->AddProject(projectInfo.m_path); + +#ifdef TEMPLATE_GEM_CONFIGURATION_ENABLED + m_gemCatalogScreen->EnableDisableGemsForProject(projectInfo.m_path); +#endif // TEMPLATE_GEM_CONFIGURATION_ENABLED - // adding gems is not implemented yet because we don't know what targets to add or how to add them emit ChangeScreenRequest(ProjectManagerScreen::Projects); } else { QMessageBox::critical(this, tr("Project creation failed"), tr("Failed to create project.")); } - - // Enable/disable gems for the newly created project. - m_gemCatalog->EnableDisableGemsForProject(m_projectInfo.m_path); - } - } - - void CreateProjectCtrl::Update() - { - ScreenWidget* currentScreen = reinterpret_cast(m_stack->currentWidget()); - if (currentScreen && currentScreen->GetScreenEnum() == ProjectManagerScreen::GemCatalog) - { - m_header->setTitle(tr("Create Project")); - m_header->setSubTitle(tr("Configure project with Gems")); - m_nextButton->setText(tr("Create Project")); } else { - m_header->setTitle(tr("Create Project")); - m_header->setSubTitle(tr("Enter Project Details")); - m_nextButton->setText(tr("Next")); + QMessageBox::warning(this, tr("Invalid project settings"), tr("Please correct the indicated project settings and try again.")); } } diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h index 89d18a9ebc..e802b6845a 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.h @@ -14,9 +14,11 @@ #if !defined(Q_MOC_RUN) #include #include -#include #endif +// due to current limitations, customizing template Gems is disabled +#define TEMPLATE_GEM_CONFIGURATION_ENABLED + QT_FORWARD_DECLARE_CLASS(QStackedWidget) QT_FORWARD_DECLARE_CLASS(QPushButton) QT_FORWARD_DECLARE_CLASS(QLabel) @@ -24,6 +26,8 @@ QT_FORWARD_DECLARE_CLASS(QLabel) namespace O3DE::ProjectManager { QT_FORWARD_DECLARE_CLASS(ScreenHeader) + QT_FORWARD_DECLARE_CLASS(NewProjectSettingsScreen) + QT_FORWARD_DECLARE_CLASS(GemCatalogScreen) class CreateProjectCtrl : public ScreenWidget @@ -36,21 +40,37 @@ namespace O3DE::ProjectManager protected slots: void HandleBackButton(); - void HandleNextButton(); + void HandlePrimaryButton(); + +#ifdef TEMPLATE_GEM_CONFIGURATION_ENABLED + void OnChangeScreenRequest(ProjectManagerScreen screen); + void HandleSecondaryButton(); +#endif // TEMPLATE_GEM_CONFIGURATION_ENABLED private: +#ifdef TEMPLATE_GEM_CONFIGURATION_ENABLED void Update(); + void NextScreen(); + void PreviousScreen(); +#endif // TEMPLATE_GEM_CONFIGURATION_ENABLED - QStackedWidget* m_stack; - ScreenHeader* m_header; + bool CurrentScreenIsValid(); + void CreateProject(); - QPushButton* m_backButton; - QPushButton* m_nextButton; + QStackedWidget* m_stack = nullptr; + ScreenHeader* m_header = nullptr; + + QPushButton* m_primaryButton = nullptr; + +#ifdef TEMPLATE_GEM_CONFIGURATION_ENABLED + QPushButton* m_secondaryButton = nullptr; +#endif // TEMPLATE_GEM_CONFIGURATION_ENABLED QString m_projectTemplatePath; ProjectInfo m_projectInfo; - - GemCatalogScreen* m_gemCatalog = nullptr; + + NewProjectSettingsScreen* m_newProjectSettingsScreen = nullptr; + GemCatalogScreen* m_gemCatalogScreen = nullptr; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp index c8dc8451ae..5faa6cb8bd 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp @@ -14,8 +14,12 @@ #include #include #include +#include #include #include +#include +#include +#include #include #include @@ -28,10 +32,12 @@ #include #include #include +#include +#include namespace O3DE::ProjectManager { - constexpr const char* k_pathProperty = "Path"; + constexpr const char* k_templateIndexProperty = "TemplateIndex"; NewProjectSettingsScreen::NewProjectSettingsScreen(QWidget* parent) : ProjectSettingsScreen(parent) @@ -59,30 +65,69 @@ namespace O3DE::ProjectManager projectTemplateDetailsLabel->setObjectName("projectTemplateDetailsLabel"); containerLayout->addWidget(projectTemplateDetailsLabel); - QHBoxLayout* templateLayout = new QHBoxLayout(this); - containerLayout->addItem(templateLayout); + + // we might have enough templates that we need to scroll + QScrollArea* templatesScrollArea = new QScrollArea(this); + QWidget* scrollWidget = new QWidget(); + + FlowLayout* flowLayout = new FlowLayout(0, s_spacerSize, s_spacerSize); + scrollWidget->setLayout(flowLayout); + + templatesScrollArea->setWidget(scrollWidget); + templatesScrollArea->setWidgetResizable(true); m_projectTemplateButtonGroup = new QButtonGroup(this); m_projectTemplateButtonGroup->setObjectName("templateButtonGroup"); + + // QButtonGroup has overloaded buttonClicked methods so we need the QOverload + connect( + m_projectTemplateButtonGroup, QOverload::of(&QButtonGroup::buttonClicked), this, + [=](QAbstractButton* button) + { + if (button && button->property(k_templateIndexProperty).isValid()) + { + int projectIndex = button->property(k_templateIndexProperty).toInt(); + UpdateTemplateDetails(m_templates.at(projectIndex)); + } + }); + auto templatesResult = PythonBindingsInterface::Get()->GetProjectTemplates(); if (templatesResult.IsSuccess() && !templatesResult.GetValue().isEmpty()) { - for (const ProjectTemplateInfo& projectTemplate : templatesResult.GetValue()) - { - QRadioButton* radioButton = new QRadioButton(projectTemplate.m_name, this); - radioButton->setProperty(k_pathProperty, projectTemplate.m_path); - m_projectTemplateButtonGroup->addButton(radioButton); + m_templates = templatesResult.GetValue(); - containerLayout->addWidget(radioButton); + // sort alphabetically by display name because they could be in any order + std::sort(m_templates.begin(), m_templates.end(), [](const ProjectTemplateInfo& arg1, const ProjectTemplateInfo& arg2) + { + return arg1.m_displayName.toLower() < arg2.m_displayName.toLower(); + }); + + for (int index = 0; index < m_templates.size(); ++index) + { + ProjectTemplateInfo projectTemplate = m_templates.at(index); + QString projectPreviewPath = projectTemplate.m_path + "/Template/preview.png"; + QFileInfo doesPreviewExist(projectPreviewPath); + if (!doesPreviewExist.exists() || !doesPreviewExist.isFile()) + { + projectPreviewPath = ":/DefaultTemplate.png"; + } + TemplateButton* templateButton = new TemplateButton(projectPreviewPath, projectTemplate.m_displayName, this); + templateButton->setCheckable(true); + templateButton->setProperty(k_templateIndexProperty, index); + + m_projectTemplateButtonGroup->addButton(templateButton); + + flowLayout->addWidget(templateButton); } m_projectTemplateButtonGroup->buttons().first()->setChecked(true); } + containerLayout->addWidget(templatesScrollArea); } projectTemplateWidget->setLayout(containerLayout); m_verticalLayout->addWidget(projectTemplateWidget); - QWidget* projectTemplateDetails = new QWidget(this); + QFrame* projectTemplateDetails = CreateTemplateDetails(s_templateDetailsContentMargin); projectTemplateDetails->setObjectName("projectTemplateDetails"); m_horizontalLayout->addWidget(projectTemplateDetails); } @@ -109,11 +154,71 @@ namespace O3DE::ProjectManager void NewProjectSettingsScreen::NotifyCurrentScreen() { + if (!m_templates.isEmpty()) + { + UpdateTemplateDetails(m_templates.first()); + } + Validate(); } QString NewProjectSettingsScreen::GetProjectTemplatePath() { - return m_projectTemplateButtonGroup->checkedButton()->property(k_pathProperty).toString(); + const int templateIndex = m_projectTemplateButtonGroup->checkedButton()->property(k_templateIndexProperty).toInt(); + return m_templates.at(templateIndex).m_path; + } + + QFrame* NewProjectSettingsScreen::CreateTemplateDetails(int margin) + { + QFrame* projectTemplateDetails = new QFrame(this); + projectTemplateDetails->setObjectName("projectTemplateDetails"); + QVBoxLayout* templateDetailsLayout = new QVBoxLayout(); + templateDetailsLayout->setContentsMargins(margin, margin, margin, margin); + templateDetailsLayout->setAlignment(Qt::AlignTop); + { + m_templateDisplayName = new QLabel(this); + m_templateDisplayName->setObjectName("displayName"); + templateDetailsLayout->addWidget(m_templateDisplayName); + + m_templateSummary = new QLabel(this); + m_templateSummary->setObjectName("summary"); + m_templateSummary->setWordWrap(true); + templateDetailsLayout->addWidget(m_templateSummary); + + QLabel* includedGemsTitle = new QLabel(tr("Included Gems"), this); + includedGemsTitle->setObjectName("includedGemsTitle"); + templateDetailsLayout->addWidget(includedGemsTitle); + + m_templateIncludedGems = new TagContainerWidget(this); + m_templateIncludedGems->setObjectName("includedGems"); + templateDetailsLayout->addWidget(m_templateIncludedGems); + +#ifdef TEMPLATE_GEM_CONFIGURATION_ENABLED + QLabel* moreGemsLabel = new QLabel(tr("Looking for more Gems?"), this); + moreGemsLabel->setObjectName("moreGems"); + templateDetailsLayout->addWidget(moreGemsLabel); + + QLabel* browseCatalogLabel = new QLabel(tr("Browse the Gems Catalog to further customize your project."), this); + browseCatalogLabel->setObjectName("browseCatalog"); + browseCatalogLabel->setWordWrap(true); + templateDetailsLayout->addWidget(browseCatalogLabel); + + QPushButton* configureGemsButton = new QPushButton(tr("Configure with more Gems"), this); + connect(configureGemsButton, &QPushButton::clicked, this, [=]() + { + emit ChangeScreenRequest(ProjectManagerScreen::GemCatalog); + }); + templateDetailsLayout->addWidget(configureGemsButton); +#endif // TEMPLATE_GEM_CONFIGURATION_ENABLED + } + projectTemplateDetails->setLayout(templateDetailsLayout); + return projectTemplateDetails; + } + + void NewProjectSettingsScreen::UpdateTemplateDetails(const ProjectTemplateInfo& templateInfo) + { + m_templateDisplayName->setText(templateInfo.m_displayName); + m_templateSummary->setText(templateInfo.m_summary); + m_templateIncludedGems->Update(templateInfo.m_includedGems); } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h index 6a4b6ec57d..ce77915404 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h +++ b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h @@ -13,12 +13,17 @@ #if !defined(Q_MOC_RUN) #include +#include +#include #endif QT_FORWARD_DECLARE_CLASS(QButtonGroup) +QT_FORWARD_DECLARE_CLASS(QLabel) +QT_FORWARD_DECLARE_CLASS(QFrame) namespace O3DE::ProjectManager { + QT_FORWARD_DECLARE_CLASS(TagContainerWidget) class NewProjectSettingsScreen : public ProjectSettingsScreen { @@ -33,8 +38,17 @@ namespace O3DE::ProjectManager private: QString GetDefaultProjectPath(); + QFrame* CreateTemplateDetails(int margin); + void UpdateTemplateDetails(const ProjectTemplateInfo& templateInfo); QButtonGroup* m_projectTemplateButtonGroup; + QLabel* m_templateDisplayName; + QLabel* m_templateSummary; + TagContainerWidget* m_templateIncludedGems; + QVector m_templates; + + inline constexpr static int s_spacerSize = 20; + inline constexpr static int s_templateDetailsContentMargin = 20; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectTemplateInfo.h b/Code/Tools/ProjectManager/Source/ProjectTemplateInfo.h index 0477968050..e75c64ec90 100644 --- a/Code/Tools/ProjectManager/Source/ProjectTemplateInfo.h +++ b/Code/Tools/ProjectManager/Source/ProjectTemplateInfo.h @@ -31,6 +31,7 @@ namespace O3DE::ProjectManager QString m_name; QString m_path; QString m_summary; + QStringList m_includedGems; QStringList m_canonicalTags; QStringList m_userTags; }; diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 37e636caef..3263505f9e 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -754,7 +754,7 @@ namespace O3DE::ProjectManager ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path) { ProjectTemplateInfo templateInfo; - templateInfo.m_path = Py_To_String(path); + templateInfo.m_path = Py_To_String(pybind11::str(path)); auto data = m_manifest.attr("get_template_json_data")(pybind11::none(), path); if (pybind11::isinstance(data)) @@ -781,6 +781,13 @@ namespace O3DE::ProjectManager templateInfo.m_canonicalTags.push_back(Py_To_String(tag)); } } + if (data.contains("included_gems")) + { + for (auto gem : data["included_gems"]) + { + templateInfo.m_includedGems.push_back(Py_To_String(gem)); + } + } } catch ([[maybe_unused]] const std::exception& e) { diff --git a/Code/Tools/ProjectManager/Source/TemplateButtonWidget.cpp b/Code/Tools/ProjectManager/Source/TemplateButtonWidget.cpp new file mode 100644 index 0000000000..41b5e51c99 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/TemplateButtonWidget.cpp @@ -0,0 +1,65 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include + +#include +#include +#include +#include +#include +#include + +namespace O3DE::ProjectManager +{ + + TemplateButton::TemplateButton(const QString& imagePath, const QString& labelText, QWidget* parent) + : QPushButton(parent) + { + setAutoExclusive(true); + + setObjectName("templateButton"); + + QVBoxLayout* vLayout = new QVBoxLayout(); + vLayout->setSpacing(0); + vLayout->setContentsMargins(0, 0, 0, 0); + setLayout(vLayout); + + QLabel* image = new QLabel(this); + image->setObjectName("templateImage"); + image->setPixmap( + QPixmap(imagePath).scaled(QSize(s_templateImageWidth,s_templateImageHeight) , Qt::KeepAspectRatio, Qt::SmoothTransformation)); + vLayout->addWidget(image); + + QLabel* label = new QLabel(labelText, this); + label->setObjectName("templateLabel"); + vLayout->addWidget(label); + + connect(this, &QAbstractButton::toggled, this, &TemplateButton::onToggled); + } + + void TemplateButton::onToggled() + { + setProperty("Checked", isChecked()); + + // we must unpolish/polish every child after changing a property + // or else they won't use the correct stylesheet selector + for (auto child : findChildren()) + { + child->style()->unpolish(child); + child->style()->polish(child); + } + + style()->unpolish(this); + style()->polish(this); + } +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/TemplateButtonWidget.h b/Code/Tools/ProjectManager/Source/TemplateButtonWidget.h new file mode 100644 index 0000000000..db0f5f39c8 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/TemplateButtonWidget.h @@ -0,0 +1,37 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#endif + +namespace O3DE::ProjectManager +{ + class TemplateButton + : public QPushButton + { + Q_OBJECT // AUTOMOC + + public: + explicit TemplateButton(const QString& imagePath, const QString& labelText, QWidget* parent = nullptr); + ~TemplateButton() = default; + + protected slots: + void onToggled(); + + private: + inline constexpr static int s_templateImageWidth = 92; + inline constexpr static int s_templateImageHeight = 122; + }; +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index a7a36f26ab..40f450ab6f 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -60,6 +60,8 @@ set(FILES Source/LinkWidget.cpp Source/TagWidget.h Source/TagWidget.cpp + Source/TemplateButtonWidget.h + Source/TemplateButtonWidget.cpp Source/GemCatalog/GemCatalogHeaderWidget.h Source/GemCatalog/GemCatalogHeaderWidget.cpp Source/GemCatalog/GemCatalogScreen.h diff --git a/Templates/DefaultProject/template.json b/Templates/DefaultProject/template.json index 26b868d315..6f74fb6b26 100644 --- a/Templates/DefaultProject/template.json +++ b/Templates/DefaultProject/template.json @@ -4,8 +4,9 @@ "restricted_platform_relative_path": "Templates", "origin": "The primary repo for DefaultProject goes here: i.e. http://www.mydomain.com", "license": "What license DefaultProject uses goes here: i.e. https://opensource.org/licenses/MIT", - "display_name": "DefaultProject", + "display_name": "Default", "summary": "A short description of DefaultProject.", + "included_gems": ["Atom","Camera","EMotionFX","UI","Maestro","Input","ImGui"], "canonical_tags": [], "user_tags": [ "DefaultProject" @@ -651,4 +652,4 @@ "origin": "Shaders" } ] -} \ No newline at end of file +} From 08db0584762545b87d09a48c897a8787852bcdbd Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 4 Jun 2021 16:41:24 -0700 Subject: [PATCH 534/811] SPEC-2513 Fixes to enable w4436 and w4366 (#1157) * Fix for w4457 * Nothing to fix, seems we deleted all the code that was causing this offense * removing warning * another warning that doesnt trigger --- cmake/Platform/Common/MSVC/Configurations_msvc.cmake | 2 -- 1 file changed, 2 deletions(-) diff --git a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake index 8c22677f91..bcff2adeb7 100644 --- a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake +++ b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake @@ -69,9 +69,7 @@ ly_append_configurations_options( /wd4267 # conversion, possible loss of data /wd4310 # cast truncates constant value /wd4324 # structure was padded due to alignment specifier - /wd4366 # the result of unary operator may be unaligned /wd4389 # comparison, signed/unsigned mismatch - /wd4436 # the result of unary operator may be unaligned # Enabling warnings that are disabled by default from /W4 # https://docs.microsoft.com/en-us/cpp/preprocessor/compiler-warnings-that-are-off-by-default?view=vs-2019 From accd473ff5cd03a9e003dee4476c7c2581f4f125 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Fri, 4 Jun 2021 20:19:38 -0400 Subject: [PATCH 535/811] Adding python bindings for modifying project properties --- .../ProjectManager/Source/PythonBindings.cpp | 18 ++++++++++++++++++ .../ProjectManager/Source/PythonBindings.h | 6 ++++++ .../Source/PythonBindingsInterface.h | 19 +++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 37e636caef..0acbf8ffaf 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -289,6 +289,7 @@ namespace O3DE::ProjectManager m_engineTemplate = pybind11::module::import("o3de.engine_template"); m_enableGemProject = pybind11::module::import("o3de.enable_gem"); m_disableGemProject = pybind11::module::import("o3de.disable_gem"); + m_editProjectProperties = pybind11::module::import("o3de.project_properties"); // make sure the engine is registered RegisterThisEngine(); @@ -686,6 +687,23 @@ namespace O3DE::ProjectManager return projectInfo; } + AZ::Outcome PythonBindings::ModifyProjectProperties(const QString& path, const QString& origin, const QString& displayName, + const QString& summary, const QString& icon, const QString& addTag, const QString& removeTag) + { + return ExecuteWithLockErrorHandling([&] + { + m_editProjectProperties.attr("edit_project_props")( + pybind11::str(path.toStdString()), //proj_path + pybind11::none(), //proj_name not used + origin.isNull() ? pybind11::none() : pybind11::str(origin.toStdString()), //new_origin + displayName.isNull() ? pybind11::none() : pybind11::str(displayName.toStdString()), //new_display + summary.isNull() ? pybind11::none() : pybind11::str(summary.toStdString()), //new_summary + icon.isNull() ? pybind11::none() : pybind11::str(icon.toStdString()), //new_icon + addTag.isNull() ? pybind11::none() : pybind11::str(addTag.toStdString()), //new_tag + removeTag.isNull() ? pybind11::none() : pybind11::str(removeTag.toStdString())); //remove_tag + }); + } + AZ::Outcome> PythonBindings::GetProjects() { QVector projects; diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h index 278aa2d5d7..5f03d0ab28 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.h +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -53,6 +53,11 @@ namespace O3DE::ProjectManager bool UpdateProject(const ProjectInfo& projectInfo) override; AZ::Outcome AddGemToProject(const QString& gemPath, const QString& projectPath) override; AZ::Outcome RemoveGemFromProject(const QString& gemPath, const QString& projectPath) override; + AZ::Outcome ModifyProjectProperties( + const QString& path, + const QString& origin = 0, + const QString& displayName = 0, + const QString& summary = 0, const QString& icon = 0, const QString& addTag = 0, const QString& removeTag = 0) override; // ProjectTemplate AZ::Outcome> GetProjectTemplates() override; @@ -78,5 +83,6 @@ namespace O3DE::ProjectManager pybind11::handle m_manifest; pybind11::handle m_enableGemProject; pybind11::handle m_disableGemProject; + pybind11::handle m_editProjectProperties; }; } diff --git a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h index 09d9187dbd..edc9510236 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h +++ b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h @@ -132,6 +132,25 @@ namespace O3DE::ProjectManager */ virtual AZ::Outcome AddGemToProject(const QString& gemPath, const QString& projectPath) = 0; + /** + * Change property in project json file + * @param path the absolute path to the gem + * @param origin the description or url for project origin (such as project host, repository, owner...etc) + * @param displayName the project display name + * @param summary short description of the project + * @param icon image used to represent the project + * @param addTag user tag to be added + * @param removeTag user tag to be removed + */ + virtual AZ::Outcome ModifyProjectProperties( + const QString& path, + const QString& origin = 0, + const QString& displayName = 0, + const QString& summary = 0, + const QString& icon = 0, + const QString& addTag = 0, + const QString& removeTag = 0) = 0; + /** * Remove gem to a project * @param gemPath the absolute path to the gem From d9b57bce678d11ef9a2f73cf45c3bd37422c8f0b Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 4 Jun 2021 19:34:22 -0500 Subject: [PATCH 536/811] Fixed configuring of cmake when a project resides on a different drive than the engine (#1153) --- cmake/Platform/Common/Install_common.cmake | 38 ++++++++++++++++++---- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 016c0d623d..4aeaf21e95 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -182,8 +182,20 @@ set_property(TARGET ${TARGET_NAME} endif() endif() - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/${NAME_PLACEHOLDER}_$.cmake" + if(IS_ABSOLUTE ${target_source_dir}) + # This normally applies the target_source_dir is outside of the engine root + # such as when invoking ly_setup_subdirectory from the project + # Therefore the final directory component of the target source directory is used first 8 characters + # of a SHA256 hash + string(SHA256 target_source_hash ${target_source_dir}) + string(SUBSTRING ${target_source_hash} 0 8 target_source_hash) + get_filename_component(target_source_folder_name ${target_source_dir} NAME) + set(target_source_dir "${target_source_folder_name}-${target_source_hash}") + endif() + + set(target_install_source_dir ${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}) + file(GENERATE OUTPUT "${target_install_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") + install(FILES "${target_install_source_dir}/${NAME_PLACEHOLDER}_$.cmake" DESTINATION ${target_source_dir} COMPONENT ${install_component} ) @@ -235,18 +247,32 @@ function(ly_setup_subdirectory absolute_target_source_dir) endforeach() file(READ ${LY_ROOT_FOLDER}/cmake/install/Copyright.in cmake_copyright_comment) - # Write out all the agreegated ly_add_target function calls and the final ly_create_alias() calls to the target CMakeList.txt - file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/CMakeLists.txt + + if(IS_ABSOLUTE ${target_source_dir}) + # This normally applies the target_source_dir is outside of the engine root + # such as when invoking ly_setup_subdirectory from the project + # Therefore the final directory component of the target source directory is used first 8 characters + # of a SHA256 hash + string(SHA256 target_source_hash ${target_source_dir}) + string(SUBSTRING ${target_source_hash} 0 8 target_source_hash) + get_filename_component(target_source_folder_name ${target_source_dir} NAME) + set(target_source_dir "${target_source_folder_name}-${target_source_hash}") + endif() + + # Initialize the target install source directory to path underneath the current binary directory + set(target_install_source_dir ${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}) + # Write out all the aggregated ly_add_target function calls and the final ly_create_alias() calls to the target CMakeLists.txt + file(WRITE ${target_install_source_dir}/CMakeLists.txt "${cmake_copyright_comment}" "${all_configured_targets}" "\n" "${CREATE_ALIASES_PLACEHOLDER}" ) - # get the component ID. if the property isn't set for the directory, it will auto fallback to use CMAKE_INSTALL_DEFAULT_COMPONENT_NAME + # get the component ID. if the property isn't set for the directory, it will auto fallback to use CMAKE_INSTALL_DEFAULT_COMPONENT_NAME get_property(install_component DIRECTORY ${absolute_target_source_dir} PROPERTY INSTALL_COMPONENT) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${target_source_dir}/CMakeLists.txt" + install(FILES "${target_install_source_dir}/CMakeLists.txt" DESTINATION ${target_source_dir} COMPONENT ${install_component} ) From 77f0d983c8475f24c874ccdd634a51c1ae8942ef Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 4 Jun 2021 19:34:28 -0500 Subject: [PATCH 537/811] Mac SystemFile_Apple.h build fix (#1159) --- .../AzCore/Platform/Common/Apple/AzCore/IO/SystemFile_Apple.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Framework/AzCore/Platform/Common/Apple/AzCore/IO/SystemFile_Apple.h b/Code/Framework/AzCore/Platform/Common/Apple/AzCore/IO/SystemFile_Apple.h index 3967cafc90..2ebb79634a 100644 --- a/Code/Framework/AzCore/Platform/Common/Apple/AzCore/IO/SystemFile_Apple.h +++ b/Code/Framework/AzCore/Platform/Common/Apple/AzCore/IO/SystemFile_Apple.h @@ -14,6 +14,9 @@ #include #include #include +#include + +#include namespace AZ { From 74e5090f26f957adf75f141d70cc7d3da9c0bfdd Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 4 Jun 2021 18:08:52 -0700 Subject: [PATCH 538/811] Adding ExternalWarningLevel to the Directory.Build.props to get the default warning level for external headers to match the one we define through compile options (#1160) --- cmake/Platform/Common/Directory.Build.props | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/cmake/Platform/Common/Directory.Build.props b/cmake/Platform/Common/Directory.Build.props index b74fa48471..951d3c6605 100644 --- a/cmake/Platform/Common/Directory.Build.props +++ b/cmake/Platform/Common/Directory.Build.props @@ -15,4 +15,9 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. true true + + + TurnOffAllWarnings + + \ No newline at end of file From 90fd676748fd92c356c89fe037379e54e087c1d0 Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Fri, 4 Jun 2021 18:19:35 -0700 Subject: [PATCH 539/811] update to let regex ingore whitespace instead of removing whitespace by hand in order to preserve the original node name and lets us accurately highlight the matching part of the node name --- .../Model/NodePaletteSortFilterProxyModel.cpp | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/Model/NodePaletteSortFilterProxyModel.cpp b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/Model/NodePaletteSortFilterProxyModel.cpp index 9e1e0688b4..2917642d66 100644 --- a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/Model/NodePaletteSortFilterProxyModel.cpp +++ b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/Model/NodePaletteSortFilterProxyModel.cpp @@ -147,17 +147,17 @@ namespace GraphCanvas return true; } - // Ignore whitespace when filtering node names - QString test = model->data(index).toString().simplified().replace(" ", ""); + + QString test = model->data(index).toString(); bool showRow = false; - int regexIndex = test.lastIndexOf(m_filterRegex); + int regexIndex = m_filterRegex.indexIn(test); if (regexIndex >= 0) { showRow = true; - - AZStd::pair highlight(regexIndex, m_filter.size()); + + AZStd::pair highlight(regexIndex, m_filterRegex.matchedLength()); currentItem->SetHighlight(highlight); } else @@ -285,10 +285,19 @@ namespace GraphCanvas void NodePaletteSortFilterProxyModel::SetFilter(const QString& filter) { // Remove whitespace and escape() so every regexp special character is escaped with a backslash - // Removing the whitespace will allow us to find nodes even if the node is written with or without spaces. + // Then ignore all whitespace by adding \s* (regex optional whitespace match) in between every other character. + // We use \s* instead of simply removing all whitespace from the filter and node-names in order to preserve the node-name and accurately highlight the matching portion. // Example: "OnGraphStart" or "On Graph Start" m_filter = QRegExp::escape(filter.simplified().replace(" ", "")); - m_filterRegex = QRegExp(m_filter, Qt::CaseInsensitive); + + QString regExIgnoreWhitespace(m_filter[0]); + for (int i = 1; i < m_filter.size(); ++i) + { + regExIgnoreWhitespace.append("\\s*"); + regExIgnoreWhitespace.append(m_filter[i]); + } + + m_filterRegex = QRegExp(regExIgnoreWhitespace, Qt::CaseInsensitive); } void NodePaletteSortFilterProxyModel::ClearFilter() From 3b60bcc0f1ab6707017d5698f55aa471e9ff598b Mon Sep 17 00:00:00 2001 From: AMZN-nggieber <52797929+AMZN-nggieber@users.noreply.github.com> Date: Fri, 4 Jun 2021 18:41:30 -0700 Subject: [PATCH 540/811] Project Manager Build Project from Projects Page (#1142) * Added loading bar mode to project button * Added ProjectBuilder files * commmit current progress for project building * Push current project building work * Full build commands built out and message boxes for lots of situation * Replaced defaultProjectImage placeholder * Added installed cmake path to builder process env PATH --- .../Resources/DefaultProjectImage.png | 4 +- .../Resources/ProjectManager.qss | 13 + .../Source/CreateProjectCtrl.cpp | 2 + .../ProjectManager/Source/ProjectBuilder.cpp | 250 ++++++++++++ .../ProjectManager/Source/ProjectBuilder.h | 73 ++++ .../Source/ProjectButtonWidget.cpp | 109 +++++- .../Source/ProjectButtonWidget.h | 19 +- .../ProjectManager/Source/ProjectInfo.cpp | 4 +- .../Tools/ProjectManager/Source/ProjectInfo.h | 4 +- .../ProjectManager/Source/ProjectUtils.cpp | 48 ++- .../ProjectManager/Source/ProjectUtils.h | 3 + .../ProjectManager/Source/ProjectsScreen.cpp | 363 ++++++++++++++---- .../ProjectManager/Source/ProjectsScreen.h | 35 +- .../ProjectManager/Source/PythonBindings.cpp | 2 +- .../ProjectManager/Source/ScreenWidget.h | 2 + .../ProjectManager/Source/ScreensCtrl.cpp | 1 + .../Tools/ProjectManager/Source/ScreensCtrl.h | 2 + .../Source/UpdateProjectCtrl.cpp | 14 +- .../project_manager_files.cmake | 2 + 19 files changed, 835 insertions(+), 115 deletions(-) create mode 100644 Code/Tools/ProjectManager/Source/ProjectBuilder.cpp create mode 100644 Code/Tools/ProjectManager/Source/ProjectBuilder.h diff --git a/Code/Tools/ProjectManager/Resources/DefaultProjectImage.png b/Code/Tools/ProjectManager/Resources/DefaultProjectImage.png index cc1eda5bb8..a3e13481c9 100644 --- a/Code/Tools/ProjectManager/Resources/DefaultProjectImage.png +++ b/Code/Tools/ProjectManager/Resources/DefaultProjectImage.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f82f22df64b93d4bec91e56b60efa3d5ce2915ce388a2dc627f1ab720678e3d5 -size 334987 +oid sha256:4a5881b8d6cfbc4ceefb14ab96844484fe19407ee030824768f9fcce2f729d35 +size 2949 diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qss b/Code/Tools/ProjectManager/Resources/ProjectManager.qss index 8b7470051c..c18d61fc24 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qss +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qss @@ -362,6 +362,7 @@ QTabBar::tab:pressed #projectButton > #labelButton { border:1px solid white; } + #projectButton > #labelButton:hover, #projectButton > #labelButton:pressed { border:1px solid #1e70eb; @@ -401,6 +402,18 @@ QTabBar::tab:pressed max-height:278px; } +QProgressBar { + border: none; + background-color: transparent; + padding: 0px; + min-height: 14px; + font-size: 2px; +} + +QProgressBar::chunk { + background-color: #1E70EB; +} + /************** Gem Catalog **************/ #GemCatalogTitle { diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp index 4498a6bc82..c8ed3954ac 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp @@ -206,6 +206,8 @@ namespace O3DE::ProjectManager m_gemCatalogScreen->EnableDisableGemsForProject(projectInfo.m_path); #endif // TEMPLATE_GEM_CONFIGURATION_ENABLED + projectInfo.m_needsBuild = true; + emit NotifyBuildProject(projectInfo); emit ChangeScreenRequest(ProjectManagerScreen::Projects); } else diff --git a/Code/Tools/ProjectManager/Source/ProjectBuilder.cpp b/Code/Tools/ProjectManager/Source/ProjectBuilder.cpp new file mode 100644 index 0000000000..8cdab93c6a --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ProjectBuilder.cpp @@ -0,0 +1,250 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + + +//#define MOCK_BUILD_PROJECT true + +namespace O3DE::ProjectManager +{ + // 10 Minutes + constexpr int MaxBuildTimeMSecs = 600000; + static const QString BuildPathPostfix = "windows_vs2019"; + static const QString ErrorLogPathPostfix = "CMakeFiles/CMakeProjectBuildError.log"; + + ProjectBuilderWorker::ProjectBuilderWorker(const ProjectInfo& projectInfo) + : QObject() + , m_projectInfo(projectInfo) + { + } + + void ProjectBuilderWorker::BuildProject() + { +#ifdef MOCK_BUILD_PROJECT + for (int i = 0; i < 10; ++i) + { + QThread::sleep(1); + UpdateProgress(i * 10); + } + Done(m_projectPath); +#else + EngineInfo engineInfo; + + AZ::Outcome engineInfoResult = PythonBindingsInterface::Get()->GetEngineInfo(); + if (engineInfoResult.IsSuccess()) + { + engineInfo = engineInfoResult.GetValue(); + } + else + { + emit Done(tr("Failed to get engine info.")); + return; + } + + // Show some kind of progress with very approximate estimates + UpdateProgress(1); + + QProcessEnvironment currentEnvironment(QProcessEnvironment::systemEnvironment()); + // Append cmake path to PATH incase it is missing + QDir cmakePath(engineInfo.m_path); + cmakePath.cd("cmake/runtime/bin"); + QString pathValue = currentEnvironment.value("PATH"); + pathValue += ";" + cmakePath.path(); + currentEnvironment.insert("PATH", pathValue); + + QProcess configProjectProcess; + configProjectProcess.setProcessChannelMode(QProcess::MergedChannels); + configProjectProcess.setWorkingDirectory(m_projectInfo.m_path); + configProjectProcess.setProcessEnvironment(currentEnvironment); + + configProjectProcess.start( + "cmake", + QStringList + { + "-B", + QDir(m_projectInfo.m_path).filePath(BuildPathPostfix), + "-S", + m_projectInfo.m_path, + "-G", + "Visual Studio 16", + "-DLY_3RDPARTY_PATH=" + engineInfo.m_thirdPartyPath + }); + + if (!configProjectProcess.waitForStarted()) + { + emit Done(tr("Configuring project failed to start.")); + return; + } + if (!configProjectProcess.waitForFinished(MaxBuildTimeMSecs)) + { + WriteErrorLog(configProjectProcess.readAllStandardOutput()); + emit Done(tr("Configuring project timed out. See log for details")); + return; + } + + QString configProjectOutput(configProjectProcess.readAllStandardOutput()); + if (configProjectProcess.exitCode() != 0 || !configProjectOutput.contains("Generating done")) + { + WriteErrorLog(configProjectOutput); + emit Done(tr("Configuring project failed. See log for details.")); + return; + } + + UpdateProgress(20); + + QProcess buildProjectProcess; + buildProjectProcess.setProcessChannelMode(QProcess::MergedChannels); + buildProjectProcess.setWorkingDirectory(m_projectInfo.m_path); + buildProjectProcess.setProcessEnvironment(currentEnvironment); + + buildProjectProcess.start( + "cmake", + QStringList + { + "--build", + QDir(m_projectInfo.m_path).filePath(BuildPathPostfix), + "--target", + m_projectInfo.m_projectName + ".GameLauncher", + "Editor", + "--config", + "profile" + }); + + if (!buildProjectProcess.waitForStarted()) + { + emit Done(tr("Building project failed to start.")); + return; + } + if (!buildProjectProcess.waitForFinished(MaxBuildTimeMSecs)) + { + WriteErrorLog(configProjectProcess.readAllStandardOutput()); + emit Done(tr("Building project timed out. See log for details")); + return; + } + + QString buildProjectOutput(buildProjectProcess.readAllStandardOutput()); + if (configProjectProcess.exitCode() != 0) + { + WriteErrorLog(buildProjectOutput); + emit Done(tr("Building project failed. See log for details.")); + } + else + { + emit Done(""); + } +#endif + } + + QString ProjectBuilderWorker::LogFilePath() const + { + QDir logFilePath(m_projectInfo.m_path); + logFilePath.cd(BuildPathPostfix); + return logFilePath.filePath(ErrorLogPathPostfix); + } + + void ProjectBuilderWorker::WriteErrorLog(const QString& log) + { + QFile logFile(LogFilePath()); + // Overwrite file with truncate + if (logFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) + { + QTextStream output(&logFile); + output << log; + logFile.close(); + } + } + + ProjectBuilderController::ProjectBuilderController(const ProjectInfo& projectInfo, ProjectButton* projectButton, QWidget* parent) + : QObject() + , m_projectInfo(projectInfo) + , m_projectButton(projectButton) + , m_parent(parent) + { + m_worker = new ProjectBuilderWorker(m_projectInfo); + m_worker->moveToThread(&m_workerThread); + + connect(&m_workerThread, &QThread::finished, m_worker, &ProjectBuilderWorker::deleteLater); + connect(&m_workerThread, &QThread::started, m_worker, &ProjectBuilderWorker::BuildProject); + connect(m_worker, &ProjectBuilderWorker::Done, this, &ProjectBuilderController::HandleResults); + connect(m_worker, &ProjectBuilderWorker::UpdateProgress, this, &ProjectBuilderController::UpdateUIProgress); + } + + ProjectBuilderController::~ProjectBuilderController() + { + m_workerThread.quit(); + m_workerThread.wait(); + } + + void ProjectBuilderController::Start() + { + m_workerThread.start(); + UpdateUIProgress(0); + } + + void ProjectBuilderController::SetProjectButton(ProjectButton* projectButton) + { + m_projectButton = projectButton; + } + + QString ProjectBuilderController::GetProjectPath() const + { + return m_projectInfo.m_path; + } + + void ProjectBuilderController::UpdateUIProgress(int progress) + { + if (m_projectButton) + { + m_projectButton->SetButtonOverlayText(QString("%1 (%2%)\n\n").arg(tr("Building Project..."), QString::number(progress))); + m_projectButton->SetProgressBarValue(progress); + } + } + + void ProjectBuilderController::HandleResults(const QString& result) + { + if (!result.isEmpty()) + { + if (result.contains(tr("log"))) + { + QMessageBox::StandardButton openLog = QMessageBox::critical( + m_parent, + tr("Project Failed to Build!"), + result + tr("\n\nWould you like to view log?"), + QMessageBox::No | QMessageBox::Yes); + + if (openLog == QMessageBox::Yes) + { + // Open application assigned to this file type + QDesktopServices::openUrl(QUrl("file:///" + m_worker->LogFilePath())); + } + } + else + { + QMessageBox::critical(m_parent, tr("Project Failed to Build!"), result); + } + } + + emit Done(); + } +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectBuilder.h b/Code/Tools/ProjectManager/Source/ProjectBuilder.h new file mode 100644 index 0000000000..de84a351ee --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ProjectBuilder.h @@ -0,0 +1,73 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ +#pragma once + +#if !defined(Q_MOC_RUN) +#include + +#include +#endif + +namespace O3DE::ProjectManager +{ + QT_FORWARD_DECLARE_CLASS(ProjectButton) + + class ProjectBuilderWorker : public QObject + { + Q_OBJECT + + public: + explicit ProjectBuilderWorker(const ProjectInfo& projectInfo); + ~ProjectBuilderWorker() = default; + + QString LogFilePath() const; + + public slots: + void BuildProject(); + + signals: + void UpdateProgress(int progress); + void Done(QString result); + + private: + void WriteErrorLog(const QString& log); + + ProjectInfo m_projectInfo; + }; + + class ProjectBuilderController : public QObject + { + Q_OBJECT + + public: + explicit ProjectBuilderController(const ProjectInfo& projectInfo, ProjectButton* projectButton, QWidget* parent = nullptr); + ~ProjectBuilderController(); + + void SetProjectButton(ProjectButton* projectButton); + QString GetProjectPath() const; + + public slots: + void Start(); + void UpdateUIProgress(int progress); + void HandleResults(const QString& result); + + signals: + void Done(); + + private: + ProjectInfo m_projectInfo; + ProjectBuilderWorker* m_worker; + QThread m_workerThread; + ProjectButton* m_projectButton; + QWidget* m_parent; + }; +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp index ee4d48fe7f..db1b1a4850 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp @@ -21,6 +21,7 @@ #include #include #include +#include namespace O3DE::ProjectManager { @@ -31,11 +32,26 @@ namespace O3DE::ProjectManager : QLabel(parent) { setObjectName("labelButton"); + + QVBoxLayout* vLayout = new QVBoxLayout(this); + vLayout->setContentsMargins(0, 0, 0, 0); + vLayout->setSpacing(5); + + setLayout(vLayout); m_overlayLabel = new QLabel("", this); m_overlayLabel->setObjectName("labelButtonOverlay"); m_overlayLabel->setWordWrap(true); m_overlayLabel->setAlignment(Qt::AlignCenter); m_overlayLabel->setVisible(false); + vLayout->addWidget(m_overlayLabel); + + m_buildButton = new QPushButton(tr("Build Project"), this); + m_buildButton->setVisible(false); + + m_progressBar = new QProgressBar(this); + m_progressBar->setObjectName("labelButtonProgressBar"); + m_progressBar->setVisible(false); + vLayout->addWidget(m_progressBar); } void LabelButton::mousePressEvent([[maybe_unused]] QMouseEvent* event) @@ -57,7 +73,22 @@ namespace O3DE::ProjectManager m_overlayLabel->setText(text); } - ProjectButton::ProjectButton(const ProjectInfo& projectInfo, QWidget* parent) + QLabel* LabelButton::GetOverlayLabel() + { + return m_overlayLabel; + } + + QProgressBar* LabelButton::GetProgressBar() + { + return m_progressBar; + } + + QPushButton* LabelButton::GetBuildButton() + { + return m_buildButton; + } + + ProjectButton::ProjectButton(const ProjectInfo& projectInfo, QWidget* parent, bool processing) : QFrame(parent) , m_projectInfo(projectInfo) { @@ -66,10 +97,18 @@ namespace O3DE::ProjectManager m_projectInfo.m_imagePath = ":/DefaultProjectImage.png"; } - Setup(); + BaseSetup(); + if (processing) + { + ProcessingSetup(); + } + else + { + ReadySetup(); + } } - void ProjectButton::Setup() + void ProjectButton::BaseSetup() { setObjectName("projectButton"); @@ -87,8 +126,37 @@ namespace O3DE::ProjectManager m_projectImageLabel->setPixmap( QPixmap(m_projectInfo.m_imagePath).scaled(m_projectImageLabel->size(), Qt::KeepAspectRatioByExpanding)); + m_projectFooter = new QFrame(this); + QHBoxLayout* hLayout = new QHBoxLayout(); + hLayout->setContentsMargins(0, 0, 0, 0); + m_projectFooter->setLayout(hLayout); + { + QLabel* projectNameLabel = new QLabel(m_projectInfo.m_displayName, this); + hLayout->addWidget(projectNameLabel); + } + + vLayout->addWidget(m_projectFooter); + } + + void ProjectButton::ProcessingSetup() + { + m_projectImageLabel->GetOverlayLabel()->setAlignment(Qt::AlignHCenter | Qt::AlignBottom); + m_projectImageLabel->SetEnabled(false); + m_projectImageLabel->SetOverlayText(tr("Processing...\n\n")); + + QProgressBar* progressBar = m_projectImageLabel->GetProgressBar(); + progressBar->setVisible(true); + progressBar->setValue(0); + } + + void ProjectButton::ReadySetup() + { + connect(m_projectImageLabel, &LabelButton::triggered, [this]() { emit OpenProject(m_projectInfo.m_path); }); + connect(m_projectImageLabel->GetBuildButton(), &QPushButton::clicked, [this](){ emit BuildProject(m_projectInfo); }); + QMenu* menu = new QMenu(this); menu->addAction(tr("Edit Project Settings..."), this, [this]() { emit EditProject(m_projectInfo.m_path); }); + menu->addAction(tr("Build"), this, [this]() { emit BuildProject(m_projectInfo); }); menu->addSeparator(); menu->addAction(tr("Open Project folder..."), this, [this]() { @@ -100,30 +168,33 @@ namespace O3DE::ProjectManager menu->addAction(tr("Remove from O3DE"), this, [this]() { emit RemoveProject(m_projectInfo.m_path); }); menu->addAction(tr("Delete this Project"), this, [this]() { emit DeleteProject(m_projectInfo.m_path); }); - QFrame* footer = new QFrame(this); - QHBoxLayout* hLayout = new QHBoxLayout(); - hLayout->setContentsMargins(0, 0, 0, 0); - footer->setLayout(hLayout); - { - QLabel* projectNameLabel = new QLabel(m_projectInfo.m_displayName, this); - hLayout->addWidget(projectNameLabel); - - QPushButton* projectMenuButton = new QPushButton(this); - projectMenuButton->setObjectName("projectMenuButton"); - projectMenuButton->setMenu(menu); - hLayout->addWidget(projectMenuButton); - } - - vLayout->addWidget(footer); + QPushButton* projectMenuButton = new QPushButton(this); + projectMenuButton->setObjectName("projectMenuButton"); + projectMenuButton->setMenu(menu); + m_projectFooter->layout()->addWidget(projectMenuButton); } - void ProjectButton::SetButtonEnabled(bool enabled) + void ProjectButton::SetLaunchButtonEnabled(bool enabled) { m_projectImageLabel->SetEnabled(enabled); } + void ProjectButton::ShowBuildButton(bool show) + { + QSpacerItem* buttonSpacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Expanding); + + m_projectImageLabel->layout()->addItem(buttonSpacer); + m_projectImageLabel->layout()->addWidget(m_projectImageLabel->GetBuildButton()); + m_projectImageLabel->GetBuildButton()->setVisible(show); + } + void ProjectButton::SetButtonOverlayText(const QString& text) { m_projectImageLabel->SetOverlayText(text); } + + void ProjectButton::SetProgressBarValue(int progress) + { + m_projectImageLabel->GetProgressBar()->setValue(progress); + } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h index bb61f7354b..1178c8ea76 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h @@ -21,6 +21,7 @@ QT_FORWARD_DECLARE_CLASS(QPixmap) QT_FORWARD_DECLARE_CLASS(QPushButton) QT_FORWARD_DECLARE_CLASS(QAction) +QT_FORWARD_DECLARE_CLASS(QProgressBar) namespace O3DE::ProjectManager { @@ -36,6 +37,10 @@ namespace O3DE::ProjectManager void SetEnabled(bool enabled); void SetOverlayText(const QString& text); + QLabel* GetOverlayLabel(); + QProgressBar* GetProgressBar(); + QPushButton* GetBuildButton(); + signals: void triggered(); @@ -44,6 +49,8 @@ namespace O3DE::ProjectManager private: QLabel* m_overlayLabel; + QProgressBar* m_progressBar; + QPushButton* m_buildButton; bool m_enabled = true; }; @@ -53,11 +60,13 @@ namespace O3DE::ProjectManager Q_OBJECT // AUTOMOC public: - explicit ProjectButton(const ProjectInfo& m_projectInfo, QWidget* parent = nullptr); + explicit ProjectButton(const ProjectInfo& m_projectInfo, QWidget* parent = nullptr, bool processing = false); ~ProjectButton() = default; - void SetButtonEnabled(bool enabled); + void SetLaunchButtonEnabled(bool enabled); + void ShowBuildButton(bool show); void SetButtonOverlayText(const QString& text); + void SetProgressBarValue(int progress); signals: void OpenProject(const QString& projectName); @@ -65,11 +74,15 @@ namespace O3DE::ProjectManager void CopyProject(const QString& projectName); void RemoveProject(const QString& projectName); void DeleteProject(const QString& projectName); + void BuildProject(const ProjectInfo& projectInfo); private: - void Setup(); + void BaseSetup(); + void ProcessingSetup(); + void ReadySetup(); ProjectInfo m_projectInfo; LabelButton* m_projectImageLabel; + QFrame* m_projectFooter; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp index f0dc05cc62..da0b4ebd61 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp @@ -15,13 +15,13 @@ namespace O3DE::ProjectManager { ProjectInfo::ProjectInfo(const QString& path, const QString& projectName, const QString& displayName, - const QString& imagePath, const QString& backgroundImagePath, bool isNew) + const QString& imagePath, const QString& backgroundImagePath, bool needsBuild) : m_path(path) , m_projectName(projectName) , m_displayName(displayName) , m_imagePath(imagePath) , m_backgroundImagePath(backgroundImagePath) - , m_isNew(isNew) + , m_needsBuild(needsBuild) { } diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.h b/Code/Tools/ProjectManager/Source/ProjectInfo.h index 71fa12b344..857e6ea4d5 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.h +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.h @@ -24,7 +24,7 @@ namespace O3DE::ProjectManager public: ProjectInfo() = default; ProjectInfo(const QString& path, const QString& projectName, const QString& displayName, - const QString& imagePath, const QString& backgroundImagePath, bool isNew); + const QString& imagePath, const QString& backgroundImagePath, bool needsBuild); bool operator==(const ProjectInfo& rhs); bool operator!=(const ProjectInfo& rhs); @@ -42,6 +42,6 @@ namespace O3DE::ProjectManager QString m_backgroundImagePath; // Used in project creation - bool m_isNew = false; //! Is this a new project or existing + bool m_needsBuild = false; //! Does this project need to be built }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectUtils.cpp b/Code/Tools/ProjectManager/Source/ProjectUtils.cpp index 58e4c5c60f..3e2b3c13e1 100644 --- a/Code/Tools/ProjectManager/Source/ProjectUtils.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectUtils.cpp @@ -16,7 +16,9 @@ #include #include #include -#include +#include +#include +#include namespace O3DE::ProjectManager { @@ -192,6 +194,49 @@ namespace O3DE::ProjectManager return true; } + static bool IsVS2019Installed_internal() + { + QProcessEnvironment environment = QProcessEnvironment::systemEnvironment(); + QString programFilesPath = environment.value("ProgramFiles(x86)"); + QString vsWherePath = programFilesPath + "\\Microsoft Visual Studio\\Installer\\vswhere.exe"; + + QFileInfo vsWhereFile(vsWherePath); + if (vsWhereFile.exists() && vsWhereFile.isFile()) + { + QProcess vsWhereProcess; + vsWhereProcess.setProcessChannelMode(QProcess::MergedChannels); + + vsWhereProcess.start( + vsWherePath, + QStringList{ "-version", "16.0", "-latest", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", + "-property", "isComplete" }); + + if (!vsWhereProcess.waitForStarted()) + { + return false; + } + + while (vsWhereProcess.waitForReadyRead()) + { + } + + QString vsWhereOutput(vsWhereProcess.readAllStandardOutput()); + if (vsWhereOutput.startsWith("1")) + { + return true; + } + } + + return false; + } + + bool IsVS2019Installed() + { + static bool vs2019Installed = IsVS2019Installed_internal(); + + return vs2019Installed; + } + ProjectManagerScreen GetProjectManagerScreen(const QString& screen) { auto iter = s_ProjectManagerStringNames.find(screen); @@ -202,6 +247,5 @@ namespace O3DE::ProjectManager return ProjectManagerScreen::Invalid; } - } // namespace ProjectUtils } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectUtils.h b/Code/Tools/ProjectManager/Source/ProjectUtils.h index d556d682f2..9c711ad187 100644 --- a/Code/Tools/ProjectManager/Source/ProjectUtils.h +++ b/Code/Tools/ProjectManager/Source/ProjectUtils.h @@ -25,6 +25,9 @@ namespace O3DE::ProjectManager bool CopyProject(const QString& origPath, const QString& newPath); bool DeleteProjectFiles(const QString& path, bool force = false); bool MoveProject(const QString& origPath, const QString& newPath, QWidget* parent = nullptr); + + bool IsVS2019Installed(); + ProjectManagerScreen GetProjectManagerScreen(const QString& screen); } // namespace ProjectUtils } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp index 425aa8514d..8e41e52643 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp @@ -15,6 +15,8 @@ #include #include #include +#include +#include #include #include @@ -42,6 +44,8 @@ #include #include #include +#include +#include //#define DISPLAY_PROJECT_DEV_DATA true @@ -66,6 +70,14 @@ namespace O3DE::ProjectManager m_stack->addWidget(m_projectsContent); vLayout->addWidget(m_stack); + + connect(reinterpret_cast(parent), &ScreensCtrl::NotifyBuildProject, this, &ProjectsScreen::SuggestBuildProject); + } + + ProjectsScreen::~ProjectsScreen() + + { + delete m_currentBuilder; } QFrame* ProjectsScreen::CreateFirstTimeContent() @@ -110,7 +122,7 @@ namespace O3DE::ProjectManager return frame; } - QFrame* ProjectsScreen::CreateProjectsContent() + QFrame* ProjectsScreen::CreateProjectsContent(QString buildProjectPath, ProjectButton** projectButton) { QFrame* frame = new QFrame(this); frame->setObjectName("projectsContent"); @@ -158,30 +170,43 @@ namespace O3DE::ProjectManager projectsScrollArea->setWidgetResizable(true); #ifndef DISPLAY_PROJECT_DEV_DATA + // Iterate once to insert building project first + if (!buildProjectPath.isEmpty()) + { + buildProjectPath = QDir::fromNativeSeparators(buildProjectPath); + for (auto project : projectsResult.GetValue()) + { + if (QDir::fromNativeSeparators(project.m_path) == buildProjectPath) + { + ProjectButton* buildingProjectButton = CreateProjectButton(project, flowLayout, true); + + if (projectButton) + { + *projectButton = buildingProjectButton; + } + + break; + } + } + } + for (auto project : projectsResult.GetValue()) #else ProjectInfo project = projectsResult.GetValue().at(0); for (int i = 0; i < 15; i++) #endif { - ProjectButton* projectButton; - - QString projectPreviewPath = project.m_path + m_projectPreviewImagePath; - QFileInfo doesPreviewExist(projectPreviewPath); - if (doesPreviewExist.exists() && doesPreviewExist.isFile()) + // Add all other projects skipping building project + // Safe if no building project because it is just an empty string + if (project.m_path != buildProjectPath) { - project.m_imagePath = projectPreviewPath; + ProjectButton* projectButtonWidget = CreateProjectButton(project, flowLayout); + + if (RequiresBuildProjectIterator(project.m_path) != m_requiresBuild.end()) + { + projectButtonWidget->ShowBuildButton(true); + } } - - projectButton = new ProjectButton(project, this); - - flowLayout->addWidget(projectButton); - - connect(projectButton, &ProjectButton::OpenProject, this, &ProjectsScreen::HandleOpenProject); - connect(projectButton, &ProjectButton::EditProject, this, &ProjectsScreen::HandleEditProject); - connect(projectButton, &ProjectButton::CopyProject, this, &ProjectsScreen::HandleCopyProject); - connect(projectButton, &ProjectButton::RemoveProject, this, &ProjectsScreen::HandleRemoveProject); - connect(projectButton, &ProjectButton::DeleteProject, this, &ProjectsScreen::HandleDeleteProject); } layout->addWidget(projectsScrollArea); @@ -191,6 +216,60 @@ namespace O3DE::ProjectManager return frame; } + ProjectButton* ProjectsScreen::CreateProjectButton(ProjectInfo& project, QLayout* flowLayout, bool processing) + { + ProjectButton* projectButton; + + QString projectPreviewPath = project.m_path + m_projectPreviewImagePath; + QFileInfo doesPreviewExist(projectPreviewPath); + if (doesPreviewExist.exists() && doesPreviewExist.isFile()) + { + project.m_imagePath = projectPreviewPath; + } + + projectButton = new ProjectButton(project, this, processing); + + flowLayout->addWidget(projectButton); + + if (!processing) + { + connect(projectButton, &ProjectButton::OpenProject, this, &ProjectsScreen::HandleOpenProject); + connect(projectButton, &ProjectButton::EditProject, this, &ProjectsScreen::HandleEditProject); + connect(projectButton, &ProjectButton::CopyProject, this, &ProjectsScreen::HandleCopyProject); + connect(projectButton, &ProjectButton::RemoveProject, this, &ProjectsScreen::HandleRemoveProject); + connect(projectButton, &ProjectButton::DeleteProject, this, &ProjectsScreen::HandleDeleteProject); + } + connect(projectButton, &ProjectButton::BuildProject, this, &ProjectsScreen::QueueBuildProject); + + return projectButton; + } + + void ProjectsScreen::ResetProjectsContent() + { + // refresh the projects content by re-creating it for now + if (m_projectsContent) + { + m_stack->removeWidget(m_projectsContent); + m_projectsContent->deleteLater(); + } + + // Make sure to update builder with latest Project Button + if (m_currentBuilder) + { + ProjectButton* projectButtonPtr; + + m_projectsContent = CreateProjectsContent(m_currentBuilder->GetProjectPath(), &projectButtonPtr); + m_currentBuilder->SetProjectButton(projectButtonPtr); + } + else + { + m_projectsContent = CreateProjectsContent(); + } + + m_stack->addWidget(m_projectsContent); + m_stack->setCurrentWidget(m_projectsContent); + } + ProjectManagerScreen ProjectsScreen::GetScreenEnum() { return ProjectManagerScreen::Projects; @@ -237,7 +316,7 @@ namespace O3DE::ProjectManager { if (ProjectUtils::AddProjectDialog(this)) { - emit ResetScreenRequest(ProjectManagerScreen::Projects); + ResetProjectsContent(); emit ChangeScreenRequest(ProjectManagerScreen::Projects); } } @@ -245,38 +324,47 @@ namespace O3DE::ProjectManager { if (!projectPath.isEmpty()) { - AZ::IO::FixedMaxPath executableDirectory = AZ::Utils::GetExecutableDirectory(); - AZStd::string executableFilename = "Editor"; - AZ::IO::FixedMaxPath editorExecutablePath = executableDirectory / (executableFilename + AZ_TRAIT_OS_EXECUTABLE_EXTENSION); - auto cmdPath = AZ::IO::FixedMaxPathString::format("%s -regset=\"/Amazon/AzCore/Bootstrap/project_path=%s\"", editorExecutablePath.c_str(), projectPath.toStdString().c_str()); + if (!WarnIfInBuildQueue(projectPath)) + { + AZ::IO::FixedMaxPath executableDirectory = AZ::Utils::GetExecutableDirectory(); + AZStd::string executableFilename = "Editor"; + AZ::IO::FixedMaxPath editorExecutablePath = executableDirectory / (executableFilename + AZ_TRAIT_OS_EXECUTABLE_EXTENSION); + auto cmdPath = AZ::IO::FixedMaxPathString::format( + "%s -regset=\"/Amazon/AzCore/Bootstrap/project_path=%s\"", editorExecutablePath.c_str(), + projectPath.toStdString().c_str()); - AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; - processLaunchInfo.m_commandlineParameters = cmdPath; - bool launchSucceeded = AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo); - if (!launchSucceeded) - { - AZ_Error("ProjectManager", false, "Failed to launch editor"); - QMessageBox::critical( this, tr("Error"), tr("Failed to launch the Editor, please verify the project settings are valid.")); - } - else - { - // prevent the user from accidentally pressing the button while the editor is launching - // and let them know what's happening - ProjectButton* button = qobject_cast(sender()); - if (button) + AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; + processLaunchInfo.m_commandlineParameters = cmdPath; + bool launchSucceeded = AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo); + if (!launchSucceeded) { - button->SetButtonEnabled(false); - button->SetButtonOverlayText(tr("Opening Editor...")); + AZ_Error("ProjectManager", false, "Failed to launch editor"); + QMessageBox::critical( + this, tr("Error"), tr("Failed to launch the Editor, please verify the project settings are valid.")); } + else + { + // prevent the user from accidentally pressing the button while the editor is launching + // and let them know what's happening + ProjectButton* button = qobject_cast(sender()); + if (button) + { + button->SetLaunchButtonEnabled(false); + button->SetButtonOverlayText(tr("Opening Editor...")); + } - // enable the button after 3 seconds - constexpr int waitTimeInMs = 3000; - QTimer::singleShot(waitTimeInMs, this, [this, button] { - if (button) + // enable the button after 3 seconds + constexpr int waitTimeInMs = 3000; + QTimer::singleShot( + waitTimeInMs, this, + [this, button] { - button->SetButtonEnabled(true); - } - }); + if (button) + { + button->SetLaunchButtonEnabled(true); + } + }); + } } } else @@ -288,38 +376,90 @@ namespace O3DE::ProjectManager } void ProjectsScreen::HandleEditProject(const QString& projectPath) { - emit NotifyCurrentProject(projectPath); - emit ChangeScreenRequest(ProjectManagerScreen::UpdateProject); + if (!WarnIfInBuildQueue(projectPath)) + { + emit NotifyCurrentProject(projectPath); + emit ChangeScreenRequest(ProjectManagerScreen::UpdateProject); + } } void ProjectsScreen::HandleCopyProject(const QString& projectPath) { - // Open file dialog and choose location for copied project then register copy with O3DE - if (ProjectUtils::CopyProjectDialog(projectPath, this)) + if (!WarnIfInBuildQueue(projectPath)) { - emit ResetScreenRequest(ProjectManagerScreen::Projects); - emit ChangeScreenRequest(ProjectManagerScreen::Projects); + // Open file dialog and choose location for copied project then register copy with O3DE + if (ProjectUtils::CopyProjectDialog(projectPath, this)) + { + ResetProjectsContent(); + emit ChangeScreenRequest(ProjectManagerScreen::Projects); + } } } void ProjectsScreen::HandleRemoveProject(const QString& projectPath) { - // Unregister Project from O3DE and reload projects - if (ProjectUtils::UnregisterProject(projectPath)) + if (!WarnIfInBuildQueue(projectPath)) { - emit ResetScreenRequest(ProjectManagerScreen::Projects); - emit ChangeScreenRequest(ProjectManagerScreen::Projects); + // Unregister Project from O3DE and reload projects + if (ProjectUtils::UnregisterProject(projectPath)) + { + ResetProjectsContent(); + emit ChangeScreenRequest(ProjectManagerScreen::Projects); + } } } void ProjectsScreen::HandleDeleteProject(const QString& projectPath) { - QMessageBox::StandardButton warningResult = QMessageBox::warning( - this, tr("Delete Project"), tr("Are you sure?\nProject will be removed from O3DE and directory will be deleted!"), - QMessageBox::No | QMessageBox::Yes); - - if (warningResult == QMessageBox::Yes) + if (!WarnIfInBuildQueue(projectPath)) { - // Remove project from O3DE and delete from disk - HandleRemoveProject(projectPath); - ProjectUtils::DeleteProjectFiles(projectPath); + QMessageBox::StandardButton warningResult = QMessageBox::warning(this, + tr("Delete Project"), + tr("Are you sure?\nProject will be unregistered from O3DE and project directory will be deleted from your disk."), + QMessageBox::No | QMessageBox::Yes); + + if (warningResult == QMessageBox::Yes) + { + // Remove project from O3DE and delete from disk + HandleRemoveProject(projectPath); + ProjectUtils::DeleteProjectFiles(projectPath); + } + } + } + + void ProjectsScreen::SuggestBuildProject(const ProjectInfo& projectInfo) + { + if (projectInfo.m_needsBuild) + { + if (RequiresBuildProjectIterator(projectInfo.m_path) == m_requiresBuild.end()) + { + m_requiresBuild.append(projectInfo); + } + ResetProjectsContent(); + } + else + { + QMessageBox::information(this, + tr("Project Should be rebuilt."), + projectInfo.m_projectName + tr(" project likely needs to be rebuilt.")); + } + } + + void ProjectsScreen::QueueBuildProject(const ProjectInfo& projectInfo) + { + auto requiredIter = RequiresBuildProjectIterator(projectInfo.m_path); + if (requiredIter != m_requiresBuild.end()) + { + m_requiresBuild.erase(requiredIter); + } + + if (!BuildQueueContainsProject(projectInfo.m_path)) + { + if (m_buildQueue.empty() && !m_currentBuilder) + { + StartProjectBuild(projectInfo); + } + else + { + m_buildQueue.append(projectInfo); + } } } @@ -331,17 +471,7 @@ namespace O3DE::ProjectManager } else { - // refresh the projects content by re-creating it for now - if (m_projectsContent) - { - m_stack->removeWidget(m_projectsContent); - m_projectsContent->deleteLater(); - } - - m_projectsContent = CreateProjectsContent(); - - m_stack->addWidget(m_projectsContent); - m_stack->setCurrentWidget(m_projectsContent); + ResetProjectsContent(); } } @@ -363,4 +493,89 @@ namespace O3DE::ProjectManager return displayFirstTimeContent; } + void ProjectsScreen::StartProjectBuild(const ProjectInfo& projectInfo) + { + if (ProjectUtils::IsVS2019Installed()) + { + QMessageBox::StandardButton buildProject = QMessageBox::information( + this, + tr("Building \"%1\"").arg(projectInfo.m_projectName), + tr("Ready to build \"%1\"?").arg(projectInfo.m_projectName), + QMessageBox::No | QMessageBox::Yes); + + if (buildProject == QMessageBox::Yes) + { + m_currentBuilder = new ProjectBuilderController(projectInfo, nullptr, this); + ResetProjectsContent(); + connect(m_currentBuilder, &ProjectBuilderController::Done, this, &ProjectsScreen::ProjectBuildDone); + + m_currentBuilder->Start(); + } + else + { + ProjectBuildDone(); + } + } + } + + void ProjectsScreen::ProjectBuildDone() + { + delete m_currentBuilder; + m_currentBuilder = nullptr; + + if (!m_buildQueue.empty()) + { + StartProjectBuild(m_buildQueue.front()); + m_buildQueue.pop_front(); + } + else + { + ResetProjectsContent(); + } + } + + QList::iterator ProjectsScreen::RequiresBuildProjectIterator(const QString& projectPath) + { + QString nativeProjPath(QDir::toNativeSeparators(projectPath)); + auto projectIter = m_requiresBuild.begin(); + for (; projectIter != m_requiresBuild.end(); ++projectIter) + { + if (QDir::toNativeSeparators(projectIter->m_path) == nativeProjPath) + { + break; + } + } + + return projectIter; + } + + bool ProjectsScreen::BuildQueueContainsProject(const QString& projectPath) + { + QString nativeProjPath(QDir::toNativeSeparators(projectPath)); + for (const ProjectInfo& project : m_buildQueue) + { + if (QDir::toNativeSeparators(project.m_path) == nativeProjPath) + { + return true; + } + } + + return false; + } + + bool ProjectsScreen::WarnIfInBuildQueue(const QString& projectPath) + { + if (BuildQueueContainsProject(projectPath)) + { + QMessageBox::warning( + this, + tr("Action Temporarily Disabled!"), + tr("Action not allowed on projects in build queue.")); + + return true; + } + + return false; + } + } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.h b/Code/Tools/ProjectManager/Source/ProjectsScreen.h index e02b34525b..bc28d4ef30 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsScreen.h +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.h @@ -13,21 +13,28 @@ #if !defined(Q_MOC_RUN) #include +#include + +#include #endif QT_FORWARD_DECLARE_CLASS(QPaintEvent) QT_FORWARD_DECLARE_CLASS(QFrame) QT_FORWARD_DECLARE_CLASS(QStackedWidget) +QT_FORWARD_DECLARE_CLASS(QLayout) namespace O3DE::ProjectManager { + QT_FORWARD_DECLARE_CLASS(ProjectBuilderController); + QT_FORWARD_DECLARE_CLASS(ProjectButton); + class ProjectsScreen : public ScreenWidget { public: explicit ProjectsScreen(QWidget* parent = nullptr); - ~ProjectsScreen() = default; + ~ProjectsScreen(); ProjectManagerScreen GetScreenEnum() override; QString GetTabText() override; @@ -35,6 +42,7 @@ namespace O3DE::ProjectManager protected: void NotifyCurrentScreen() override; + void ProjectBuildDone(); protected slots: void HandleNewProjectButton(); @@ -45,19 +53,32 @@ namespace O3DE::ProjectManager void HandleRemoveProject(const QString& projectPath); void HandleDeleteProject(const QString& projectPath); + void SuggestBuildProject(const ProjectInfo& projectInfo); + void QueueBuildProject(const ProjectInfo& projectInfo); + void paintEvent(QPaintEvent* event) override; private: QFrame* CreateFirstTimeContent(); - QFrame* CreateProjectsContent(); + QFrame* CreateProjectsContent(QString buildProjectPath = "", ProjectButton** projectButton = nullptr); + ProjectButton* CreateProjectButton(ProjectInfo& project, QLayout* flowLayout, bool processing = false); + void ResetProjectsContent(); bool ShouldDisplayFirstTimeContent(); - QAction* m_createNewProjectAction; - QAction* m_addExistingProjectAction; + void StartProjectBuild(const ProjectInfo& projectInfo); + QList::iterator RequiresBuildProjectIterator(const QString& projectPath); + bool BuildQueueContainsProject(const QString& projectPath); + bool WarnIfInBuildQueue(const QString& projectPath); + + QAction* m_createNewProjectAction = nullptr; + QAction* m_addExistingProjectAction = nullptr; QPixmap m_background; - QFrame* m_firstTimeContent; - QFrame* m_projectsContent; - QStackedWidget* m_stack; + QFrame* m_firstTimeContent = nullptr; + QFrame* m_projectsContent = nullptr; + QStackedWidget* m_stack = nullptr; + QList m_requiresBuild; + QQueue m_buildQueue; + ProjectBuilderController* m_currentBuilder = nullptr; const QString m_projectPreviewImagePath = "/preview.png"; diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 3263505f9e..5f4bb833d8 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -667,7 +667,7 @@ namespace O3DE::ProjectManager { ProjectInfo projectInfo; projectInfo.m_path = Py_To_String(path); - projectInfo.m_isNew = false; + projectInfo.m_needsBuild = false; auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path); if (pybind11::isinstance(projectData)) diff --git a/Code/Tools/ProjectManager/Source/ScreenWidget.h b/Code/Tools/ProjectManager/Source/ScreenWidget.h index 2ad6d30201..47baed261c 100644 --- a/Code/Tools/ProjectManager/Source/ScreenWidget.h +++ b/Code/Tools/ProjectManager/Source/ScreenWidget.h @@ -13,6 +13,7 @@ #if !defined(Q_MOC_RUN) #include +#include #include #include @@ -61,6 +62,7 @@ namespace O3DE::ProjectManager void GotoPreviousScreenRequest(); void ResetScreenRequest(ProjectManagerScreen screen); void NotifyCurrentProject(const QString& projectPath); + void NotifyBuildProject(const ProjectInfo& projectInfo); }; diff --git a/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp b/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp index 52fcbf354a..646f66a557 100644 --- a/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp @@ -177,6 +177,7 @@ namespace O3DE::ProjectManager connect(newScreen, &ScreenWidget::GotoPreviousScreenRequest, this, &ScreensCtrl::GotoPreviousScreen); connect(newScreen, &ScreenWidget::ResetScreenRequest, this, &ScreensCtrl::ResetScreen); connect(newScreen, &ScreenWidget::NotifyCurrentProject, this, &ScreensCtrl::NotifyCurrentProject); + connect(newScreen, &ScreenWidget::NotifyBuildProject, this, &ScreensCtrl::NotifyBuildProject); } void ScreensCtrl::ResetAllScreens() diff --git a/Code/Tools/ProjectManager/Source/ScreensCtrl.h b/Code/Tools/ProjectManager/Source/ScreensCtrl.h index 3b51ed529a..841108dff7 100644 --- a/Code/Tools/ProjectManager/Source/ScreensCtrl.h +++ b/Code/Tools/ProjectManager/Source/ScreensCtrl.h @@ -13,6 +13,7 @@ #if !defined(Q_MOC_RUN) #include +#include #include #include @@ -39,6 +40,7 @@ namespace O3DE::ProjectManager signals: void NotifyCurrentProject(const QString& projectPath); + void NotifyBuildProject(const ProjectInfo& projectInfo); public slots: bool ChangeToScreen(ProjectManagerScreen screen); diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp index a383a0f93b..6fcb1b1c71 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp @@ -119,7 +119,9 @@ namespace O3DE::ProjectManager void UpdateProjectCtrl::HandleNextButton() { - if (m_stack->currentIndex() == ScreenOrder::Settings) + bool shouldRebuild = false; + + if (m_stack->currentIndex() == ScreenOrder::Settings && m_updateSettingsScreen) { if (m_updateSettingsScreen) { @@ -155,11 +157,17 @@ namespace O3DE::ProjectManager m_projectInfo = newProjectSettings; } } - - if (m_stack->currentIndex() == ScreenOrder::Gems && m_gemCatalogScreen) + else if (m_stack->currentIndex() == ScreenOrder::Gems && m_gemCatalogScreen) { // Enable or disable the gems that got adjusted in the gem catalog and apply them to the given project. m_gemCatalogScreen->EnableDisableGemsForProject(m_projectInfo.m_path); + + shouldRebuild = true; + } + + if (shouldRebuild) + { + emit NotifyBuildProject(m_projectInfo); } emit ChangeScreenRequest(ProjectManagerScreen::Projects); diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index 40f450ab6f..eb9cd1145e 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -38,6 +38,8 @@ set(FILES Source/ProjectInfo.cpp Source/ProjectUtils.h Source/ProjectUtils.cpp + Source/ProjectBuilder.h + Source/ProjectBuilder.cpp Source/UpdateProjectSettingsScreen.h Source/UpdateProjectSettingsScreen.cpp Source/NewProjectSettingsScreen.h From 9df995dd264516dfd821ca5c51c84400f14f957c Mon Sep 17 00:00:00 2001 From: Ken Pruiksma Date: Fri, 4 Jun 2021 20:57:44 -0500 Subject: [PATCH 541/811] Temporal anti-aliasing and constrast adaptive sharpening (#1161) First version of temporal antialiasing and contrast adaptive sharpening for GA. Works well in most cases but still has a few issues that will need additional time. This is only the passes and shaders with no exposure to the editor. TAA and CAS can be turned on by enabling their respective passes in the pipeline. All of the code has been previously reviewed in smaller PRs into the taa_staging branch: aws-lumberyard-dev#29 aws-lumberyard-dev#53 aws-lumberyard-dev#73 aws-lumberyard-dev#79 aws-lumberyard-dev#84 Main issues: - Bloom doesn't play nice with TAA and seems to greatly amplify any flickering - AuxGeom jitters with the camera, so TAA doesn't currently work well in editor - Transparencies don't have correct motion vectors. History rectification keeps this from looking too bad, but could still be improved - There is still more that could be done to inhibit flickering, usually from specular aliasing - Motion vectors aren't correct on POM unless PDO is turned on, which can result in some blurring during motion. - SSAO can contribute to flickering in its default half res configuration. Changing this to full res mitigates the problem. Squashed merge of the following: * [ATOM-13987] Initial checkin of Taa pass. * TAA pass setup WIP. (does not work yet due to pass configuration issues). * Taa WIP - Camera motion vectors fixed and hooked up. TAA does simple reprojection and rejection based on depth. * Small update to use lerp and add some comments. * Fix issue with attachments not being set up on bindings at initialization. Fixing issue with half-pixel offsets in TAA shader * - Motion vector passes now use the same output with mesh motion vectors overwriting camera motion vectors. - Taa pass now works with multiple pipelines. - Cleaned up TAA shader a bit. * Fixes from PR review. * Adding check for multiple attachments of the same name with different resources in Pass::ImportAttachments(). * Adding camera jitter with configurable position count. Updated TAA to blend in tonemapped space. * Fixes from PR review. Fixing camera motion vectors for background (infinite distance) * Updates to taa shader from PR review * Adding a rcp input color size. * Fix comment on PassAttachment::Update() * Updates for PR review. * Fixing missing const on the FrameAttachment* in Pass's call to FindAttachment() * Taa WIP - Adding filtering to both the current pixel and history. Adding rectification based on variance clipping. Adding some basic anti-flickering. Removing rejection based on depth. * Updates from PR code review. Mostly better commenting and naming. * Adding contrast adaptive sharpening based on AMD FidelityFX CAS to help with the softness added by TAA. * Changing to using luminance for sharpening instead of just green. Added some comments. * Moving Taa's NaN check to a better location. Disabling TAA and sharpening in prep for check in. * Updates from PR feedback. --- .../Passes/ContrastAdaptiveSharpening.pass | 75 +++++ .../Common/Assets/Passes/MainPipeline.pass | 7 + .../Assets/Passes/MeshMotionVector.pass | 39 +-- .../Assets/Passes/MotionVectorParent.pass | 20 ++ .../Assets/Passes/PassTemplates.azasset | 8 + .../Assets/Passes/PostProcessParent.pass | 52 +++- .../Passes/SMAA1xApplyLinearHDRColor.pass | 6 + .../Feature/Common/Assets/Passes/Taa.pass | 113 ++++++++ .../MotionVector/CameraMotionVector.azsl | 21 +- .../MotionVector/MeshMotionVectorCommon.azsli | 4 + .../ContrastAdaptiveSharpening.azsl | 85 ++++++ .../ContrastAdaptiveSharpening.shader | 11 + .../Assets/Shaders/PostProcessing/Taa.azsl | 271 ++++++++++++++++++ .../Assets/Shaders/PostProcessing/Taa.shader | 11 + .../atom_feature_common_asset_files.cmake | 2 + .../Code/Source/CommonSystemComponent.cpp | 5 + .../Code/Source/PostProcessing/TaaPass.cpp | 247 ++++++++++++++++ .../Code/Source/PostProcessing/TaaPass.h | 105 +++++++ .../Code/atom_feature_common_files.cmake | 2 + .../Atom/RHI/FrameGraphAttachmentInterface.h | 6 + .../Code/Include/Atom/RPI.Public/Pass/Pass.h | 4 +- .../Atom/RPI.Public/Pass/PassAttachment.h | 3 +- .../RPI/Code/Include/Atom/RPI.Public/View.h | 16 +- .../RPI/Code/Source/RPI.Public/Pass/Pass.cpp | 29 +- .../Source/RPI.Public/Pass/PassAttachment.cpp | 4 +- Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp | 85 +++--- 26 files changed, 1139 insertions(+), 92 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Assets/Passes/ContrastAdaptiveSharpening.pass create mode 100644 Gems/Atom/Feature/Common/Assets/Passes/Taa.pass create mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ContrastAdaptiveSharpening.azsl create mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ContrastAdaptiveSharpening.shader create mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/Taa.azsl create mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/Taa.shader create mode 100644 Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp create mode 100644 Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.h diff --git a/Gems/Atom/Feature/Common/Assets/Passes/ContrastAdaptiveSharpening.pass b/Gems/Atom/Feature/Common/Assets/Passes/ContrastAdaptiveSharpening.pass new file mode 100644 index 0000000000..44ab6f4a52 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Passes/ContrastAdaptiveSharpening.pass @@ -0,0 +1,75 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "PassAsset", + "ClassData": { + "PassTemplate": { + "Name": "ContrastAdaptiveSharpeningTemplate", + "PassClass": "ComputePass", + "Slots": [ + { + "Name": "InputColor", + "SlotType": "Input", + "ShaderInputName": "m_inputColor", + "ScopeAttachmentUsage": "Shader" + }, + { + "Name": "OutputColor", + "SlotType": "Output", + "ShaderInputName": "m_outputColor", + "ScopeAttachmentUsage": "Shader" + } + ], + "ImageAttachments": [ + { + "Name": "Output", + "FormatSource": { + "Pass": "This", + "Attachment": "InputColor" + }, + "SizeSource": { + "Source": { + "Pass": "This", + "Attachment": "InputColor" + } + }, + "ImageDescriptor": { + "Format": "R16G16B16A16_FLOAT", + "BindFlags": "3", + "SharedQueueMask": "1" + } + } + ], + "Connections": [ + { + "LocalSlot": "OutputColor", + "AttachmentRef": { + "Pass": "This", + "Attachment": "Output" + } + } + ], + "FallbackConnections": [ + { + "Input": "InputColor", + "Output": "OutputColor" + } + ], + "PassData": { + "$type": "ComputePassData", + "ShaderAsset": { + "FilePath": "Shaders/Postprocessing/ContrastAdaptiveSharpening.shader" + }, + "Make Fullscreen Pass": true, + "ShaderDataMappings": { + "FloatMappings": [ + { + "Name": "m_strength", + "Value": 0.25 + } + ] + } + } + } + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Passes/MainPipeline.pass b/Gems/Atom/Feature/Common/Assets/Passes/MainPipeline.pass index af7408b48c..b2e0cf088e 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/MainPipeline.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/MainPipeline.pass @@ -341,6 +341,13 @@ "Attachment": "Depth" } }, + { + "LocalSlot": "MotionVectors", + "AttachmentRef": { + "Pass": "MotionVectorPass", + "Attachment": "MotionVectorOutput" + } + }, { "LocalSlot": "SwapChainOutput", "AttachmentRef": { diff --git a/Gems/Atom/Feature/Common/Assets/Passes/MeshMotionVector.pass b/Gems/Atom/Feature/Common/Assets/Passes/MeshMotionVector.pass index 57600440b4..4c14fd9b3f 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/MeshMotionVector.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/MeshMotionVector.pass @@ -13,22 +13,11 @@ "SlotType": "Input", "ScopeAttachmentUsage": "InputAssembly" }, - // Outputs... + // Input/Output... { - "Name": "Output", - "SlotType": "Output", - "ScopeAttachmentUsage": "RenderTarget", - "LoadStoreAction": { - "ClearValue": { - "Value": [ - 0.0, - 0.0, - 0.0, - {} - ] - }, - "LoadAction": "Clear" - } + "Name": "MotionInputOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "RenderTarget" }, { "Name": "OutputDepthStencil", @@ -46,19 +35,6 @@ } ], "ImageAttachments": [ - { - "Name": "MotionBuffer", - "SizeSource": { - "Source": { - "Pass": "Parent", - "Attachment": "SwapChainOutput" - } - }, - "ImageDescriptor": { - "Format": "R16G16_FLOAT", - "SharedQueueMask": "Graphics" - } - }, { "Name": "DepthStencil", "SizeSource": { @@ -74,13 +50,6 @@ } ], "Connections": [ - { - "LocalSlot": "Output", - "AttachmentRef": { - "Pass": "This", - "Attachment": "MotionBuffer" - } - }, { "LocalSlot": "OutputDepthStencil", "AttachmentRef": { diff --git a/Gems/Atom/Feature/Common/Assets/Passes/MotionVectorParent.pass b/Gems/Atom/Feature/Common/Assets/Passes/MotionVectorParent.pass index a8369e4618..d7f4894706 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/MotionVectorParent.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/MotionVectorParent.pass @@ -20,6 +20,19 @@ { "Name": "SwapChainOutput", "SlotType": "InputOutput" + }, + { + "Name": "MotionVectorOutput", + "SlotType": "Output" + } + ], + "Connections": [ + { + "LocalSlot": "MotionVectorOutput", + "AttachmentRef": { + "Pass": "MeshMotionVectorPass", + "Attachment": "MotionInputOutput" + } } ], "PassRequests": [ @@ -50,6 +63,13 @@ "Pass": "Parent", "Attachment": "SkinnedMeshes" } + }, + { + "LocalSlot": "MotionInputOutput", + "AttachmentRef": { + "Pass": "CameraMotionVectorPass", + "Attachment": "Output" + } } ], "PassData": { diff --git a/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset b/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset index c56e8932b1..702ac8fe72 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset +++ b/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset @@ -284,6 +284,14 @@ "Name": "SMAA1xApplyPerceptualColorTemplate", "Path": "Passes/SMAA1xApplyPerceptualColor.pass" }, + { + "Name": "TaaTemplate", + "Path": "Passes/Taa.pass" + }, + { + "Name": "ContrastAdaptiveSharpeningTemplate", + "Path": "Passes/ContrastAdaptiveSharpening.pass" + }, { "Name": "SsaoParentTemplate", "Path": "Passes/SsaoParent.pass" diff --git a/Gems/Atom/Feature/Common/Assets/Passes/PostProcessParent.pass b/Gems/Atom/Feature/Common/Assets/Passes/PostProcessParent.pass index 36f7f1e985..fb27770da3 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/PostProcessParent.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/PostProcessParent.pass @@ -16,6 +16,10 @@ "Name": "Depth", "SlotType": "Input" }, + { + "Name": "MotionVectors", + "SlotType": "Input" + }, // SwapChain here is only used to reference the frame height and format { "Name": "SwapChainOutput", @@ -40,8 +44,8 @@ { "LocalSlot": "Output", "AttachmentRef": { - "Pass": "LightAdaptation", - "Attachment": "Output" + "Pass": "ContrastAdaptiveSharpeningPass", + "Attachment": "OutputColor" } }, { @@ -80,6 +84,34 @@ } ] }, + { + "Name": "TaaPass", + "TemplateName": "TaaTemplate", + "Enabled": false, + "Connections": [ + { + "LocalSlot": "InputColor", + "AttachmentRef": { + "Pass": "SMAA1xApplyLinearHDRColorPass", + "Attachment": "OutputColor" + } + }, + { + "LocalSlot": "InputDepth", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "Depth" + } + }, + { + "LocalSlot": "MotionVectors", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "MotionVectors" + } + } + ] + }, { "Name": "DepthOfFieldPass", "TemplateName": "DepthOfFieldTemplate", @@ -88,7 +120,7 @@ { "LocalSlot": "DoFColorInput", "AttachmentRef": { - "Pass": "SMAA1xApplyLinearHDRColorPass", + "Pass": "TaaPass", "Attachment": "OutputColor" } }, @@ -134,6 +166,20 @@ } } ] + }, + { + "Name": "ContrastAdaptiveSharpeningPass", + "TemplateName": "ContrastAdaptiveSharpeningTemplate", + "Enabled": false, + "Connections": [ + { + "LocalSlot": "InputColor", + "AttachmentRef": { + "Pass": "LightAdaptation", + "Attachment": "Output" + } + } + ] } ] } diff --git a/Gems/Atom/Feature/Common/Assets/Passes/SMAA1xApplyLinearHDRColor.pass b/Gems/Atom/Feature/Common/Assets/Passes/SMAA1xApplyLinearHDRColor.pass index 98700d5f0c..70604fba25 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/SMAA1xApplyLinearHDRColor.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/SMAA1xApplyLinearHDRColor.pass @@ -40,6 +40,12 @@ } } ], + "FallbackConnections": [ + { + "Input": "InputColor", + "Output": "OutputColor" + } + ], "PassRequests": [ { "Name": "SMAAConvertToPerceptualColor", diff --git a/Gems/Atom/Feature/Common/Assets/Passes/Taa.pass b/Gems/Atom/Feature/Common/Assets/Passes/Taa.pass new file mode 100644 index 0000000000..f1ba156007 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Passes/Taa.pass @@ -0,0 +1,113 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "PassAsset", + "ClassData": { + "PassTemplate": { + "Name": "TaaTemplate", + "PassClass": "TaaPass", + "Slots": [ + { + "Name": "InputColor", + "SlotType": "Input", + "ShaderInputName": "m_inputColor", + "ScopeAttachmentUsage": "Shader" + }, + { + "Name": "InputDepth", + "SlotType": "Input", + "ShaderInputName": "m_inputDepth", + "ScopeAttachmentUsage": "Shader" + }, + { + "Name": "MotionVectors", + "SlotType": "Input", + "ShaderInputName": "m_motionVectors", + "ScopeAttachmentUsage": "Shader" + }, + { + "Name": "LastFrameAccumulation", + "SlotType": "Input", + "ShaderInputName": "m_lastFrameAccumulation", + "ScopeAttachmentUsage": "Shader" + }, + { + "Name": "OutputColor", + "SlotType": "Output", + "ShaderInputName": "m_outputColor", + "ScopeAttachmentUsage": "Shader" + } + ], + "ImageAttachments": [ + { + "Name": "Accumulation1", + "Lifetime": "Imported", + "FormatSource": { + "Pass": "This", + "Attachment": "InputColor" + }, + "SizeSource": { + "Source": { + "Pass": "This", + "Attachment": "InputColor" + } + }, + "ImageDescriptor": { + "Format": "R16G16B16A16_FLOAT", + "BindFlags": "3", + "SharedQueueMask": "1" + } + }, + { + "Name": "Accumulation2", + "Lifetime": "Imported", + "FormatSource": { + "Pass": "This", + "Attachment": "InputColor" + }, + "SizeSource": { + "Source": { + "Pass": "This", + "Attachment": "InputColor" + } + }, + "ImageDescriptor": { + "Format": "R16G16B16A16_FLOAT", + "BindFlags": "3", + "SharedQueueMask": "1" + } + } + ], + "FallbackConnections": [ + { + "Input": "InputColor", + "Output": "OutputColor" + } + ], + "PassData": { + "$type": "TaaPassData", + "ShaderAsset": { + "FilePath": "Shaders/Postprocessing/Taa.shader" + }, + "Make Fullscreen Pass": true, + "ShaderDataMappings": { + "FloatMappings": [ + { + "Name": "m_currentFrameContribution", + "Value": 0.1 + }, + { + "Name": "m_clampGamma", + "Value": 1.0 + }, + { + "Name": "m_maxDeviationBeforeDampening", + "Value": 0.5 + } + ] + }, + "NumJitterPositions": 16 + } + } + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/MotionVector/CameraMotionVector.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/MotionVector/CameraMotionVector.azsl index a073f42f03..c83e5138e6 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/MotionVector/CameraMotionVector.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/MotionVector/CameraMotionVector.azsl @@ -39,10 +39,27 @@ PSOutput MainPS(VSOutput IN) PSOutput OUT; float depth = PassSrg::m_depthStencil.Sample(PassSrg::LinearSampler, IN.m_texCoord).r; + + // If depth is 0, that means depth is on the far plane. This should be treated as being infinitely far + // away, not actually on the far plane, because the infinitely far background shouldn't move as a result + // of camera translation. Tweaking the depth to -near/far distance makes that happen. Keep in mind near + // and far are inverted, so this normally a very small value. + if (depth == 0.0) + { + depth = -ViewSrg::GetFarZ() / ViewSrg::GetNearZ(); + } + float2 clipPos = float2(mad(IN.m_texCoord.x, 2.0, -1.0), mad(IN.m_texCoord.y, -2.0, 1.0)); float4 worldPos = mul(ViewSrg::m_viewProjectionInverseMatrix, float4(clipPos, depth, 1.0)); + float4 clipPosPrev = mul(ViewSrg::m_viewProjectionPrevMatrix, float4((worldPos / worldPos.w).xyz, 1.0)); - - OUT.m_motion = (clipPos - (clipPosPrev / clipPosPrev.w).xy) * 0.5; + clipPosPrev = (clipPosPrev / clipPosPrev.w); + + // Clip space is from -1.0 to 1.0, so the motion vectors are 2x as big as they should be + OUT.m_motion = (clipPos - clipPosPrev.xy) * 0.5; + + // Flip y to line up with uv coordinates + OUT.m_motion.y = -OUT.m_motion.y; + return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/MotionVector/MeshMotionVectorCommon.azsli b/Gems/Atom/Feature/Common/Assets/Shaders/MotionVector/MeshMotionVectorCommon.azsli index c11e9d9e0e..ff2758af87 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/MotionVector/MeshMotionVectorCommon.azsli +++ b/Gems/Atom/Feature/Common/Assets/Shaders/MotionVector/MeshMotionVectorCommon.azsli @@ -41,5 +41,9 @@ PSOutput MainPS(VSOutput IN) float2 motion = (clipPos.xy / clipPos.w - clipPosPrev.xy / clipPosPrev.w) * 0.5; OUT.m_motion = motion; + + // Flip y to line up with uv coordinates + OUT.m_motion.y = -OUT.m_motion.y; + return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ContrastAdaptiveSharpening.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ContrastAdaptiveSharpening.azsl new file mode 100644 index 0000000000..14fa942a7d --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ContrastAdaptiveSharpening.azsl @@ -0,0 +1,85 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include + +#define TILE_DIM_X 16 +#define TILE_DIM_Y 16 + +ShaderResourceGroup PassSrg : SRG_PerPass +{ + Texture2D m_inputColor; + RWTexture2D m_outputColor; + + float m_strength; // Strength of the sharpening effect. Range from 0 to 1. +} + + +// Constrast Adaptive Sharpening, based on AMD FidelityFX CAS - https://gpuopen.com/fidelityfx-cas/ + +// This shader sharpens the input based on the contrast of the local neighborhood +// so that only areas that need sharpening are sharpened, while high constast areas +// are mostly left alone. + +[numthreads(TILE_DIM_X, TILE_DIM_Y, 1)] +void MainCS( + uint3 dispatchThreadID : SV_DispatchThreadID, + uint3 groupID : SV_GroupID, + uint groupIndex : SV_GroupIndex) +{ + uint2 pixelCoord = dispatchThreadID.xy; + + // Fetch local neighborhood to determin sharpening weight. + // a + // b c d + // e + + float3 sampleA = PassSrg::m_inputColor[pixelCoord + int2( 0, -1)].rgb; + float3 sampleB = PassSrg::m_inputColor[pixelCoord + int2(-1, 0)].rgb; + float3 sampleC = PassSrg::m_inputColor[pixelCoord + int2( 0, 0)].rgb; + float3 sampleD = PassSrg::m_inputColor[pixelCoord + int2( 1, 0)].rgb; + float3 sampleE = PassSrg::m_inputColor[pixelCoord + int2( 0, 1)].rgb; + + float lumA = GetLuminance(sampleA); + float lumB = GetLuminance(sampleB); + float lumC = GetLuminance(sampleC); + float lumD = GetLuminance(sampleD); + float lumE = GetLuminance(sampleE); + + // Get the min and max. Just use the green channel for luminance. + float minLum = min(min(lumA, lumB), min(lumC, min(lumD, lumE))); + float maxLum = max(max(lumA, lumB), max(lumC, max(lumD, lumE))); + + float dMinLum = minLum; // Distance from 0 to minimum + float dMaxLum = 1.0 - maxLum; // Distance from 1 to the maximum + + // baseSharpening is higher when local contrast is lower to avoid over-sharpening. + float baseSharpening = min(dMinLum, dMaxLum) / max(maxLum, 0.0001); + baseSharpening = sqrt(baseSharpening); // bias towards more sharpening + + // Negative weights for sharpening effect, center pixel is always weighted 1. + float developerMaximum = lerp(-0.125, -0.2, PassSrg::m_strength); + float weight = baseSharpening * developerMaximum; + float totalWeight = weight * 4 + 1.0; + + float3 output = + ( + sampleA * weight + + sampleB * weight + + sampleC + + sampleD * weight + + sampleE * weight + ) / totalWeight; + + PassSrg::m_outputColor[pixelCoord] = float4(output, 1.0); +} diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ContrastAdaptiveSharpening.shader b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ContrastAdaptiveSharpening.shader new file mode 100644 index 0000000000..756ce0ec7a --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ContrastAdaptiveSharpening.shader @@ -0,0 +1,11 @@ +{ + "Source": "ContrastAdaptiveSharpening", + "ProgramSettings": { + "EntryPoints": [ + { + "name": "MainCS", + "type": "Compute" + } + ] + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/Taa.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/Taa.azsl new file mode 100644 index 0000000000..94944df9de --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/Taa.azsl @@ -0,0 +1,271 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include + +#define TILE_DIM_X 16 +#define TILE_DIM_Y 16 + +ShaderResourceGroup PassSrg : SRG_PerPass +{ + Texture2D m_inputColor; + Texture2D m_inputDepth; + Texture2D m_motionVectors; + Texture2D m_lastFrameAccumulation; + + RWTexture2D m_outputColor; + + Sampler LinearSampler + { + MinFilter = Linear; + MagFilter = Linear; + MipFilter = Linear; + AddressU = Clamp; + AddressV = Clamp; + AddressW = Clamp; + }; + + // Current frame's default contribution to the history. + float m_currentFrameContribution; + + // Increase this value for weaker clamping, decrease for stronger clamping, default 1.0. + float m_clampGamma; + + // Default 0.5, used for flicker reduction. Any sample further than this many standard deviations outside the neighborhood + // will have its weight decreased. The further outside the max deviation, the more its weight is reduced. + float m_maxDeviationBeforeDampening; + + struct Constants + { + uint2 m_inputColorSize; + float2 m_inputColorRcpSize; + + // 3x3 filter weights + // 8 2 6 + // 3 0 1 + // 7 4 5 + float4 m_weights1; // 0 1 2 3 + float4 m_weights2; // 4 5 6 7 + float4 m_weights3; // 8 x x x + }; + Constants m_constantData; +} + +static const int2 offsets[9] = +{ + // Center + int2(0, 0), + // Cross + int2( 1, 0), + int2( 0,-1), + int2(-1, 0), + int2( 0, 1), + // Diagonals + int2( 1,-1), + int2( 1, 1), + int2(-1,-1), + int2(-1, 1), +}; + +float3 RgbToYCoCg(float3 rgb) +{ + const float3x3 conversionMatrix = + { + 0.25, 0.50, 0.25, + 0.50, 0.00, -0.50, + -0.25, 0.50, -0.25 + }; + return mul(conversionMatrix, rgb); +} + +float3 YCoCgToRgb(float3 yCoCg) +{ + const float3x3 conversionMatrix = + { + 1.0, 1.0, -1.0, + 1.0, 0.0, 1.0, + 1.0, -1.0, -1.0 + }; + return mul(conversionMatrix, yCoCg); +} + +// Sample a texture with a 5 tap Catmull-Rom. Consider ripping this out and putting in a more general location. +// This function samples a 4x4 neighborhood around the uv. By taking advantage of bilinear filtering this can be +// done with only 9 taps on the edges between pixels. The cost is further reduced by dropping the 4 diagonal +// samples as their influence is negligible. +float4 SampleCatmullRom5Tap(Texture2D texture, SamplerState linearSampler, float2 uv, float2 textureSize, float2 rcpTextureSize, float sharpness) +{ + // Think of sample locations in the 4x4 neighborhood as having a top left coordinate of 0,0 and + // a bottom right coordinate of 3,3. + + // Find the position in texture space then round it to get the center of the 1,1 pixel (tc1) + float2 texelPos = uv * textureSize; + float2 tc1= floor(texelPos - 0.5) + 0.5; + + // Offset from center position to texel + float2 f = texelPos - tc1; + + // Compute Catmull-Rom weights based on the offset and sharpness + float c = sharpness; + float2 w0 = f * (-c + f * (2.0 * c - c * f)); + float2 w1 = 1.0 + f * f * (c -3.0 + (2.0 - c) * f); + float2 w2 = f * (c + f * ((3.0 - 2.0 * c) - (2.0 - c) * f)); + float2 w3 = f * f * (c * f - c); + + float2 w12 = w1 + w2; + + // Compute uv coordinates for sampling the texture + float2 tc0 = (tc1 - 1.0f) * rcpTextureSize; + float2 tc3 = (tc1 + 2.0f) * rcpTextureSize; + float2 tc12 = (tc1 + w2 / w12) * rcpTextureSize; + + // Compute sample weights + float sw0 = w12.x * w0.y; + float sw1 = w0.x * w12.y; + float sw2 = w12.x * w12.y; + float sw3 = w3.x * w12.y; + float sw4 = w12.x * w3.y; + + // total weight of samples to normalize result. + float totalWeight = sw0 + sw1 + sw2 + sw3 + sw4; + + float4 result = 0.0f; + result += texture.SampleLevel(linearSampler, float2(tc12.x, tc0.y), 0.0) * sw0; + result += texture.SampleLevel(linearSampler, float2( tc0.x, tc12.y), 0.0) * sw1; + result += texture.SampleLevel(linearSampler, float2(tc12.x, tc12.y), 0.0) * sw2; + result += texture.SampleLevel(linearSampler, float2( tc3.x, tc12.y), 0.0) * sw3; + result += texture.SampleLevel(linearSampler, float2(tc12.x, tc3.y), 0.0) * sw4; + + return result / totalWeight; +} + +[numthreads(TILE_DIM_X, TILE_DIM_Y, 1)] +void MainCS( + uint3 dispatchThreadID : SV_DispatchThreadID, + uint3 groupID : SV_GroupID, + uint groupIndex : SV_GroupIndex) +{ + uint2 pixelCoord = dispatchThreadID.xy; + + const float filterWeights[9] = + { + PassSrg::m_constantData.m_weights1.x, + PassSrg::m_constantData.m_weights1.y, + PassSrg::m_constantData.m_weights1.z, + PassSrg::m_constantData.m_weights1.w, + PassSrg::m_constantData.m_weights2.x, + PassSrg::m_constantData.m_weights2.y, + PassSrg::m_constantData.m_weights2.z, + PassSrg::m_constantData.m_weights2.w, + PassSrg::m_constantData.m_weights3.x, + }; + + float3 sum = 0.0; + float3 sumOfSquares = 0.0; + float nearestDepth = 1.0; + uint2 nearestDepthPixelCoord; + + float3 thisFrameColor = float3(0.0, 0.0, 0.0); + + // Sample the neighborhood to filter the current pixel, gather statistics about + // its neighbors, and find the closest neighbor to choose a motion vector. + [unroll] for (int i = 0; i < 9; ++i) + { + uint2 neighborhoodPixelCoord = pixelCoord + offsets[i]; + float3 neighborhoodColor = PassSrg::m_inputColor[neighborhoodPixelCoord].rgb; + + // Convert to YCoCg space for better clipping. + neighborhoodColor = RgbToYCoCg(neighborhoodColor); + + sum += neighborhoodColor; + sumOfSquares += neighborhoodColor * neighborhoodColor; + thisFrameColor += neighborhoodColor * filterWeights[i]; + + // Find the coordinate of the nearest depth + float neighborhoodDepth = PassSrg::m_inputDepth[neighborhoodPixelCoord].r; + if (neighborhoodDepth < nearestDepth) + { + nearestDepth = neighborhoodDepth; + nearestDepthPixelCoord = neighborhoodPixelCoord; + } + } + + // Variance clipping, see http://developer.download.nvidia.com/gameworks/events/GDC2016/msalvi_temporal_supersampling.pdf + float3 mean = sum / 9.0; + float3 standardDeviation = max(0.0, sqrt(sumOfSquares / 9.0 - mean * mean)); + standardDeviation *= PassSrg::m_clampGamma; + + // Grab the motion vector from the closest pixel in the 3x3 neighborhood. This is done so that motion vectors correctly + // track edges. For instance, if a pixel lies on the edge of a moving object, where the color is a blend of the + // forground and background, it's possible for the pixel center to hit the (not moving) background. However, the correct + // history for this pixel will be the location this edge was the previous frame. By choosing the motion of the nearest + // pixel in the neighborhood that edge will be correctly tracked. + + // Motion vectors store the direction of movement, so to look up where things were in the previous frame, it's negated. + float2 previousPositionOffset = -PassSrg::m_motionVectors[nearestDepthPixelCoord]; + + // Get the uv coordinate for the previous frame. + float2 rcpSize = PassSrg::m_constantData.m_inputColorRcpSize; + float2 uvCoord = (pixelCoord + 0.5f) * rcpSize; + float2 uvOld = uvCoord + previousPositionOffset; + float2 previousPositionOffsetInPixels = float2(PassSrg::m_constantData.m_inputColorSize) * previousPositionOffset; + + // Sample the last frame using a 5-tap Catmull-Rom + float3 lastFrameColor = SampleCatmullRom5Tap(PassSrg::m_lastFrameAccumulation, PassSrg::LinearSampler, uvOld, PassSrg::m_constantData.m_inputColorSize, PassSrg::m_constantData.m_inputColorRcpSize, 0.5).rgb; + lastFrameColor = RgbToYCoCg(lastFrameColor); + + // Last frame color relative to mean + float3 centerColorOffset = lastFrameColor - mean; + float3 colorOffsetStandardDeviationRatio = abs(standardDeviation / centerColorOffset); + + // Clamp the color by the aabb of the standardDeviation. Can never be greater than 1, so will always be inside or on the bounds of the aabb. + float clampedColorLength = min(min(min(1, colorOffsetStandardDeviationRatio.x), colorOffsetStandardDeviationRatio.y), colorOffsetStandardDeviationRatio.z); + + // Calculate the true clamped color by offsetting it back from the mean. + float3 lastFrameClampedColor = mean + centerColorOffset * clampedColorLength; + + // Anti-flickering - Reduce current frame weight the more it deviates from the history based on the standard deviation of the neighborhood. + // Start reducing weight at differences greater than m_maxDeviationBeforeDampening standard deviations in luminance. + float standardDeviationWeight = standardDeviation.r * PassSrg::m_maxDeviationBeforeDampening; + float3 sdFromLastFrame = standardDeviationWeight / abs(lastFrameClampedColor.r - thisFrameColor.r); + + float currentFrameWeight = PassSrg::m_currentFrameContribution; + currentFrameWeight *= saturate(sdFromLastFrame * sdFromLastFrame); + + // Back to Rgb space + thisFrameColor = YCoCgToRgb(thisFrameColor); + lastFrameClampedColor = YCoCgToRgb(lastFrameClampedColor); + + // Out of bounds protection. + if (any(uvOld > 1.0) || any(uvOld < 0.0)) + { + currentFrameWeight = 1.0f; + } + + // Blend should be in perceptual space, so tonemap first + float luminance = GetLuminance(thisFrameColor); + thisFrameColor = thisFrameColor / (1 + luminance); + lastFrameClampedColor = lastFrameClampedColor / (1 + luminance); + + // Blend color with history + float3 color = lerp(lastFrameClampedColor, thisFrameColor, currentFrameWeight); + + // Un-tonemap color + color = color * (1.0 + luminance); + + // NaN protection (without this NaNs could get in the history buffer and quickly consume the frame) + color = max(0.0, color); + + PassSrg::m_outputColor[pixelCoord].rgb = color; + +} diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/Taa.shader b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/Taa.shader new file mode 100644 index 0000000000..f30ff92f20 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/Taa.shader @@ -0,0 +1,11 @@ +{ + "Source": "Taa", + "ProgramSettings": { + "EntryPoints": [ + { + "name": "MainCS", + "type": "Compute" + } + ] + } +} diff --git a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake index a9ba765329..3dfabc586a 100644 --- a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake +++ b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake @@ -89,6 +89,7 @@ set(FILES Passes/CascadedShadowmaps.pass Passes/CheckerboardResolveColor.pass Passes/CheckerboardResolveDepth.pass + Passes/ContrastAdaptiveSharpening.pass Passes/ConvertToAcescg.pass Passes/DebugOverlayParent.pass Passes/DeferredFog.pass @@ -207,6 +208,7 @@ set(FILES Passes/SsaoHalfRes.pass Passes/SsaoParent.pass Passes/SubsurfaceScattering.pass + Passes/Taa.pass Passes/Transparent.pass Passes/TransparentParent.pass Passes/UI.pass diff --git a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp index d38db1b08e..af28624357 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp @@ -64,6 +64,7 @@ #include #include #include +#include #include #include #include @@ -133,6 +134,7 @@ namespace AZ PostProcessFeatureProcessor::Reflect(context); ImGuiPassData::Reflect(context); RayTracingPassData::Reflect(context); + TaaPassData::Reflect(context); LightingPreset::Reflect(context); ModelPreset::Reflect(context); @@ -230,6 +232,9 @@ namespace AZ // Add Depth Downsample/Upsample passes passSystem->AddPassCreator(Name("DepthUpsamplePass"), &DepthUpsamplePass::Create); + + // Add Taa Pass + passSystem->AddPassCreator(Name("TaaPass"), &TaaPass::Create); // Add DepthOfField pass passSystem->AddPassCreator(Name("DepthOfFieldCompositePass"), &DepthOfFieldCompositePass::Create); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp new file mode 100644 index 0000000000..9f885ede70 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp @@ -0,0 +1,247 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace AZ::Render +{ + + RPI::Ptr TaaPass::Create(const RPI::PassDescriptor& descriptor) + { + RPI::Ptr pass = aznew TaaPass(descriptor); + return pass; + } + + TaaPass::TaaPass(const RPI::PassDescriptor& descriptor) + : Base(descriptor) + { + uint32_t numJitterPositions = 8; + + const TaaPassData* taaPassData = RPI::PassUtils::GetPassData(descriptor); + if (taaPassData) + { + numJitterPositions = taaPassData->m_numJitterPositions; + } + + // The coprimes 2, 3 are commonly used for halton sequences because they have an even distribution even for + // few samples. With larger primes you need to offset by some amount between each prime to have the same + // effect. We could allow this to be configurable in the future. + SetupSubPixelOffsets(2, 3, numJitterPositions); + } + + void TaaPass::CompileResources(const RHI::FrameGraphCompileContext& context) + { + struct TaaConstants + { + AZStd::array m_size = { 1, 1 }; + AZStd::array m_rcpSize = { 0.0, 0.0 }; + + AZStd::array m_weights1 = { 0.0 }; + AZStd::array m_weights2 = { 0.0 }; + AZStd::array m_weights3 = { 0.0 }; + }; + + TaaConstants cb; + RHI::Size inputSize = m_lastFrameAccumulationBinding->m_attachment->m_descriptor.m_image.m_size; + cb.m_size[0] = inputSize.m_width; + cb.m_size[1] = inputSize.m_height; + cb.m_rcpSize[0] = 1.0f / inputSize.m_width; + cb.m_rcpSize[1] = 1.0f / inputSize.m_height; + + Offset jitterOffset = m_subPixelOffsets.at(m_offsetIndex); + GenerateFilterWeights(Vector2(jitterOffset.m_xOffset, jitterOffset.m_yOffset)); + cb.m_weights1 = { m_filterWeights[0], m_filterWeights[1], m_filterWeights[2], m_filterWeights[3] }; + cb.m_weights2 = { m_filterWeights[4], m_filterWeights[5], m_filterWeights[6], m_filterWeights[7] }; + cb.m_weights3 = { m_filterWeights[8], 0.0f, 0.0f, 0.0f }; + + m_shaderResourceGroup->SetConstant(m_constantDataIndex, cb); + + + Base::CompileResources(context); + } + + void TaaPass::FrameBeginInternal(FramePrepareParams params) + { + RHI::Size inputSize = m_inputColorBinding->m_attachment->m_descriptor.m_image.m_size; + Vector2 rcpInputSize = Vector2(1.0 / inputSize.m_width, 1.0 / inputSize.m_height); + + RPI::ViewPtr view = GetRenderPipeline()->GetDefaultView(); + m_offsetIndex = (m_offsetIndex + 1) % m_subPixelOffsets.size(); + Offset offset = m_subPixelOffsets.at(m_offsetIndex); + view->SetClipSpaceOffset(offset.m_xOffset * rcpInputSize.GetX(), offset.m_yOffset * rcpInputSize.GetY()); + + m_lastFrameAccumulationBinding->SetAttachment(m_accumulationAttachments[m_accumulationOuptutIndex]); + m_accumulationOuptutIndex ^= 1; // swap which attachment is the output and last frame + + UpdateAttachmentImage(m_accumulationAttachments[m_accumulationOuptutIndex]); + m_outputColorBinding->SetAttachment(m_accumulationAttachments[m_accumulationOuptutIndex]); + + Base::FrameBeginInternal(params); + } + + void TaaPass::ResetInternal() + { + m_accumulationAttachments[0].reset(); + m_accumulationAttachments[1].reset(); + + m_inputColorBinding = nullptr; + m_lastFrameAccumulationBinding = nullptr; + m_outputColorBinding = nullptr; + + Base::ResetInternal(); + } + + void TaaPass::BuildAttachmentsInternal() + { + m_accumulationAttachments[0] = FindAttachment(Name("Accumulation1")); + m_accumulationAttachments[1] = FindAttachment(Name("Accumulation2")); + + bool hasAttachments = m_accumulationAttachments[0] || m_accumulationAttachments[1]; + AZ_Error("TaaPass", hasAttachments, "TaaPass must have Accumulation1 and Accumulation2 ImageAttachments defined."); + + if (hasAttachments) + { + // Make sure the attachments have images when the pass first loads. + for (auto i : { 0, 1 }) + { + if (!m_accumulationAttachments[i]->m_importedResource) + { + UpdateAttachmentImage(m_accumulationAttachments[i]); + } + } + } + + m_inputColorBinding = FindAttachmentBinding(Name("InputColor")); + AZ_Error("TaaPass", m_inputColorBinding, "TaaPass requires a slot for InputColor."); + m_lastFrameAccumulationBinding = FindAttachmentBinding(Name("LastFrameAccumulation")); + AZ_Error("TaaPass", m_lastFrameAccumulationBinding, "TaaPass requires a slot for LastFrameAccumulation."); + m_outputColorBinding = FindAttachmentBinding(Name("OutputColor")); + AZ_Error("TaaPass", m_outputColorBinding, "TaaPass requires a slot for OutputColor."); + + // Set up the attachment for last frame accumulation and output color if it's never been done to + // ensure SRG indices are set up correctly by the pass system. + if (m_lastFrameAccumulationBinding->m_attachment == nullptr) + { + m_lastFrameAccumulationBinding->SetAttachment(m_accumulationAttachments[0]); + m_outputColorBinding->SetAttachment(m_accumulationAttachments[1]); + } + + Base::BuildAttachmentsInternal(); + } + + void TaaPass::UpdateAttachmentImage(RPI::Ptr& attachment) + { + if (!attachment) + { + return; + } + + // update the image attachment descriptor to sync up size and format + attachment->Update(true); + RHI::ImageDescriptor& imageDesc = attachment->m_descriptor.m_image; + RPI::AttachmentImage* currentImage = azrtti_cast(attachment->m_importedResource.get()); + + if (attachment->m_importedResource && imageDesc.m_size == currentImage->GetDescriptor().m_size) + { + // If there's a resource already and the size didn't change, just keep using the old AttachmentImage. + return; + } + + Data::Instance pool = RPI::ImageSystemInterface::Get()->GetSystemAttachmentPool(); + + // set the bind flags + imageDesc.m_bindFlags |= RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderReadWrite; + + // The ImageViewDescriptor must be specified to make sure the frame graph compiler doesn't treat this as a transient image. + RHI::ImageViewDescriptor viewDesc = RHI::ImageViewDescriptor::Create(imageDesc.m_format, 0, 0); + viewDesc.m_aspectFlags = RHI::ImageAspectFlags::Color; + viewDesc.m_overrideBindFlags = RHI::ImageBindFlags::ShaderReadWrite; + + // The full path name is needed for the attachment image so it's not deduplicated from accumulation images in different pipelines. + AZStd::string imageName = RPI::ConcatPassString(GetPathName(), attachment->m_path); + auto attachmentImage = RPI::AttachmentImage::Create(*pool.get(), imageDesc, Name(imageName), nullptr, &viewDesc); + + attachment->m_path = attachmentImage->GetAttachmentId(); + attachment->m_importedResource = attachmentImage; + } + + void TaaPass::SetupSubPixelOffsets(uint32_t haltonX, uint32_t haltonY, uint32_t length) + { + m_subPixelOffsets.resize(length); + HaltonSequence<2> sequence = HaltonSequence<2>({haltonX, haltonY}); + sequence.FillHaltonSequence(m_subPixelOffsets.begin(), m_subPixelOffsets.end()); + + // Adjust to the -1.0 to 1.0 range. This is done because the view needs offsets in clip + // space and is one less calculation that would need to be done in FrameBeginInternal() + AZStd::for_each(m_subPixelOffsets.begin(), m_subPixelOffsets.end(), + [](Offset& offset) + { + offset.m_xOffset = 2.0f * offset.m_xOffset - 1.0f; + offset.m_yOffset = 2.0f * offset.m_yOffset - 1.0f; + } + ); + } + + // Approximation of a Blackman Harris window function of width 3.3. + // https://en.wikipedia.org/wiki/Window_function#Blackman%E2%80%93Harris_window + static float BlackmanHarris(AZ::Vector2 uv) + { + return expf(-2.29f * (uv.GetX() * uv.GetX() + uv.GetY() * uv.GetY())); + } + + // Generates filter weights for the 3x3 neighborhood of a pixel. Since jitter positions are the + // same for every pixel we can calculate this once here and upload to the SRG. + // Jitter weights are based on a window function centered at the pixel center (we use Blackman-Harris). + // As the jitter position moves around, some neighborhood locations decrease in weight, and others + // increase in weight based on their distance from the center of the pixel. + void TaaPass::GenerateFilterWeights(AZ::Vector2 jitterOffset) + { + static const AZStd::array pixelOffsets = + { + // Center + Vector2(0.0f, 0.0f), + // Cross + Vector2( 1.0f, 0.0f), + Vector2( 0.0f, 1.0f), + Vector2(-1.0f, 0.0f), + Vector2( 0.0f, -1.0f), + // Diagonals + Vector2( 1.0f, 1.0f), + Vector2( 1.0f, -1.0f), + Vector2(-1.0f, 1.0f), + Vector2(-1.0f, -1.0f), + }; + + float sum = 0.0f; + for (uint32_t i = 0; i < 9; ++i) + { + m_filterWeights[i] = BlackmanHarris(pixelOffsets[i] + jitterOffset); + sum += m_filterWeights[i]; + } + + // Normalize the weight so the sum of all weights is 1.0. + float normalization = 1.0f / sum; + for (uint32_t i = 0; i < 9; ++i) + { + m_filterWeights[i] *= normalization; + } + } + +} // namespace AZ::Render diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.h new file mode 100644 index 0000000000..6133720691 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.h @@ -0,0 +1,105 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include +#include + +namespace AZ::Render +{ + //! Custom data for the Taa Pass. + struct TaaPassData + : public RPI::ComputePassData + { + AZ_RTTI(TaaPassData, "{BCDF5C7D-7A78-4C69-A460-FA6899C3B960}", ComputePassData); + AZ_CLASS_ALLOCATOR(TaaPassData, SystemAllocator, 0); + + TaaPassData() = default; + virtual ~TaaPassData() = default; + + static void Reflect(ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("NumJitterPositions", &TaaPassData::m_numJitterPositions) + ; + } + } + + uint32_t m_numJitterPositions = 8; + }; + + class TaaPass : public RPI::ComputePass + { + using Base = RPI::ComputePass; + AZ_RPI_PASS(TaaPass); + + public: + AZ_RTTI(AZ::Render::TaaPass, "{AB3BD4EA-33D7-477F-82B4-21DDFB517499}", Base); + AZ_CLASS_ALLOCATOR(TaaPass, SystemAllocator, 0); + virtual ~TaaPass() = default; + + /// Creates a TaaPass + static RPI::Ptr Create(const RPI::PassDescriptor& descriptor); + + private: + + TaaPass(const RPI::PassDescriptor& descriptor); + + // Scope producer functions... + void CompileResources(const RHI::FrameGraphCompileContext& context) override; + + // Pass behavior overrides... + void FrameBeginInternal(FramePrepareParams params) override; + void ResetInternal() override; + void BuildAttachmentsInternal() override; + + void UpdateAttachmentImage(RPI::Ptr& attachment); + + void SetupSubPixelOffsets(uint32_t haltonX, uint32_t haltonY, uint32_t length); + void GenerateFilterWeights(AZ::Vector2 jitterOffset); + + RHI::ShaderInputNameIndex m_outputIndex = "m_output"; + RHI::ShaderInputNameIndex m_lastFrameAccumulationIndex = "m_lastFrameAccumulation"; + RHI::ShaderInputNameIndex m_constantDataIndex = "m_constantData"; + + Data::Instance m_accumulationAttachments[2]; + + RPI::PassAttachmentBinding* m_inputColorBinding = nullptr; + RPI::PassAttachmentBinding* m_lastFrameAccumulationBinding = nullptr; + RPI::PassAttachmentBinding* m_outputColorBinding = nullptr; + + struct Offset + { + Offset() = default; + + // Constructor for implicit conversion from array output by HaltonSequence. + Offset(AZStd::array offsets) + : m_xOffset(offsets[0]) + , m_yOffset(offsets[1]) + {}; + + float m_xOffset = 0.0f; + float m_yOffset = 0.0f; + }; + + AZStd::array m_filterWeights = { 0.0f }; + + AZStd::vector m_subPixelOffsets; + uint32_t m_offsetIndex = 0; + + uint8_t m_accumulationOuptutIndex = 0; + + }; +} // namespace AZ::Render diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake index a108fc82f5..a759de77fa 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -252,6 +252,8 @@ set(FILES Source/PostProcessing/SsaoPasses.h Source/PostProcessing/SubsurfaceScatteringPass.cpp Source/PostProcessing/SubsurfaceScatteringPass.h + Source/PostProcessing/TaaPass.h + Source/PostProcessing/TaaPass.cpp Source/RayTracing/RayTracingFeatureProcessor.h Source/RayTracing/RayTracingFeatureProcessor.cpp Source/RayTracing/RayTracingAccelerationStructurePass.cpp diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/FrameGraphAttachmentInterface.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/FrameGraphAttachmentInterface.h index c3194efbb6..af29079a97 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/FrameGraphAttachmentInterface.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/FrameGraphAttachmentInterface.h @@ -89,6 +89,12 @@ namespace AZ return m_attachmentDatabase.IsAttachmentValid(attachmentId); } + //! Returns the FrameAttachment for a given AttachmentId, or nullptr if not found. + const FrameAttachment* FindAttachment(const AttachmentId& attachmentId) const + { + return m_attachmentDatabase.FindAttachment(attachmentId); + } + //! Resolves an attachment id to a buffer descriptor. This is useful when accessing buffer information for //! an attachment that was declared in a different scope. //! \param attachmentId The attachment id used to lookup the descriptors. diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h index 1cba71ae7e..3d0a8cd3a8 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h @@ -184,8 +184,8 @@ namespace AZ //! Collect all different view tags from this pass virtual void GetPipelineViewTags(SortedPipelineViewTags& outTags) const; - //! Adds this pass' DrawListTags to the outDrawListMask. - virtual void GetViewDrawListInfo(RHI::DrawListMask& outDrawListMask, PassesByDrawList& outPassesByDrawList, const PipelineViewTag& viewTag) const; + //! Adds this pass' DrawListTags to the outDrawListMask. + virtual void GetViewDrawListInfo(RHI::DrawListMask& outDrawListMask, PassesByDrawList& outPassesByDrawList, const PipelineViewTag& viewTag) const; //! Check if the pass has a DrawListTag. Pass' DrawListTag can be used to filter draw items. virtual RHI::DrawListTag GetDrawListTag() const; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassAttachment.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassAttachment.h index 5509398f55..fd2a49a941 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassAttachment.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassAttachment.h @@ -52,7 +52,8 @@ namespace AZ const RHI::TransientBufferDescriptor GetTransientBufferDescriptor() const; //! Updates the size and format of this attachment using the sources below if specified - void Update(); + //! @param updateImportedAttachments - Imported attchments will only update if this is true. + void Update(bool updateImportedAttachments = false); //! Sets all formats to nearest device supported formats and warns if changes where made void ValidateDeviceFormats(const AZStd::vector& formatFallbacks, RHI::FormatCapabilities capabilities = RHI::FormatCapabilities::None); diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h index e611ecf0d6..fabec8d896 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h @@ -88,6 +88,9 @@ namespace AZ //! Sets the viewToClip matrix and recalculates the other matrices void SetViewToClipMatrix(const AZ::Matrix4x4& viewToClip); + //! Sets a pixel offset on the view, usually used for jittering the camera for anti-aliasing techniques. + void SetClipSpaceOffset(float xOffset, float yOffset); + const AZ::Matrix4x4& GetWorldToViewMatrix() const; //! Use GetViewToWorldMatrix().GetTranslation() to get the camera's position. const AZ::Matrix4x4& GetViewToWorldMatrix() const; @@ -173,7 +176,6 @@ namespace AZ Matrix4x4 m_worldToViewMatrix; Matrix4x4 m_viewToWorldMatrix; Matrix4x4 m_viewToClipMatrix; - Matrix4x4 m_clipToViewMatrix; Matrix4x4 m_clipToWorldMatrix; // View's position in world space @@ -188,17 +190,15 @@ namespace AZ // Cached matrix to transform from world space to clip space Matrix4x4 m_worldToClipMatrix; - Matrix4x4 m_worldToClipPrevMatrix; + Matrix4x4 m_worldToViewPrevMatrix; + Matrix4x4 m_viewToClipPrevMatrix; + + // Clip space offset for camera jitter with taa + Vector2 m_clipSpaceOffset = Vector2(0.0f, 0.0f); // Flags whether view matrices are dirty which requires rebuild srg bool m_needBuildSrg = true; - // Following two bools form a delay circuit to update history of next frame - // if vp matrix is changed during current frame, this is required because - // view class doesn't contain subroutines called at the end of each frame - bool m_worldToClipMatrixChanged = true; - bool m_worldToClipPrevMatrixNeedsUpdate = false; - MatrixChangedEvent m_onWorldToClipMatrixChange; MatrixChangedEvent m_onWorldToViewMatrixChange; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp index 8d613eb2bb..1e230a7fc0 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp @@ -914,23 +914,40 @@ namespace AZ { // make sure to only import the resource one time RHI::AttachmentId attachmentId = attachment->GetAttachmentId(); - if (!attachmentDatabase.IsAttachmentValid(attachmentId)) + const RHI::FrameAttachment* currentAttachment = attachmentDatabase.FindAttachment(attachmentId); + + if (azrtti_istypeof(attachment->m_importedResource.get())) { - if (azrtti_istypeof(attachment->m_importedResource.get())) + Image* image = static_cast(attachment->m_importedResource.get()); + if (currentAttachment == nullptr) { - Image* image = static_cast(attachment->m_importedResource.get()); attachmentDatabase.ImportImage(attachmentId, image->GetRHIImage()); } - else if (azrtti_istypeof(attachment->m_importedResource.get())) + else + { + AZ_Assert(currentAttachment->GetResource() == image->GetRHIImage(), + "Importing image attachment named \"%s\" but a different attachment with the " + "same name already exists in the database.\n", attachmentId.GetCStr()); + } + } + else if (azrtti_istypeof(attachment->m_importedResource.get())) + { + Buffer* buffer = static_cast(attachment->m_importedResource.get()); + if (currentAttachment == nullptr) { - Buffer* buffer = static_cast(attachment->m_importedResource.get()); attachmentDatabase.ImportBuffer(attachmentId, buffer->GetRHIBuffer()); } else { - AZ_RPI_PASS_ERROR(false, "Can't import unknown resource type"); + AZ_Assert(currentAttachment->GetResource() == buffer->GetRHIBuffer(), + "Importing buffer attachment named \"%s\" but a different attachment with the " + "same name already exists in the database.\n", attachmentId.GetCStr()); } } + else + { + AZ_RPI_PASS_ERROR(false, "Can't import unknown resource type"); + } } } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassAttachment.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassAttachment.cpp index a5082c5ee6..3bd26a5906 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassAttachment.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassAttachment.cpp @@ -114,9 +114,9 @@ namespace AZ return RHI::TransientBufferDescriptor(GetAttachmentId(), m_descriptor.m_buffer); } - void PassAttachment::Update() + void PassAttachment::Update(bool updateImportedAttachments) { - if (m_descriptor.m_type == RHI::AttachmentType::Image && m_lifetime == RHI::AttachmentLifetimeType::Transient) + if (m_descriptor.m_type == RHI::AttachmentType::Image && (m_lifetime == RHI::AttachmentLifetimeType::Transient || updateImportedAttachments == true)) { if (m_settingFlags.m_getFormatFromPipeline && m_renderPipelineSource) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index bd0e15fb2e..24dfcb7097 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -127,7 +127,6 @@ namespace AZ m_worldToViewMatrix = worldToView; m_worldToClipMatrix = m_viewToClipMatrix * m_worldToViewMatrix; - m_worldToClipMatrixChanged = true; m_onWorldToViewMatrixChange.Signal(m_worldToViewMatrix); m_onWorldToClipMatrixChange.Signal(m_worldToClipMatrix); @@ -166,8 +165,6 @@ namespace AZ m_worldToViewMatrix = m_viewToWorldMatrix.GetInverseFast(); m_worldToClipMatrix = m_viewToClipMatrix * m_worldToViewMatrix; - m_clipToWorldMatrix = m_viewToWorldMatrix * m_clipToViewMatrix; - m_worldToClipMatrixChanged = true; m_onWorldToViewMatrixChange.Signal(m_worldToViewMatrix); m_onWorldToClipMatrixChange.Signal(m_worldToClipMatrix); @@ -178,12 +175,8 @@ namespace AZ void View::SetViewToClipMatrix(const AZ::Matrix4x4& viewToClip) { m_viewToClipMatrix = viewToClip; - m_clipToViewMatrix = viewToClip.GetInverseFull(); m_worldToClipMatrix = m_viewToClipMatrix * m_worldToViewMatrix; - m_worldToClipMatrixChanged = true; - - m_clipToWorldMatrix = m_viewToWorldMatrix * m_clipToViewMatrix; // Update z depth constant simultaneously // zNear -> n, zFar -> f @@ -210,6 +203,12 @@ namespace AZ InvalidateSrg(); } + + void View::SetClipSpaceOffset(float xOffset, float yOffset) + { + m_clipSpaceOffset.Set(xOffset, yOffset); + InvalidateSrg(); + } const AZ::Matrix4x4& View::GetWorldToViewMatrix() const { @@ -368,36 +367,56 @@ namespace AZ void View::UpdateSrg() { - if (m_worldToClipPrevMatrixNeedsUpdate) + if (m_needBuildSrg) { - m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, m_worldToClipPrevMatrix); - m_worldToClipPrevMatrixNeedsUpdate = false; + if (m_clipSpaceOffset.IsZero()) + { + Matrix4x4 worldToClipPrevMatrix = m_viewToClipPrevMatrix * m_worldToViewPrevMatrix; + m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, worldToClipPrevMatrix); + m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, m_worldToClipMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, m_viewToClipMatrix); + m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, m_clipToWorldMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, m_viewToClipMatrix.GetInverseFull()); + } + else + { + // Offset the current and previous frame clip matricies + Matrix4x4 offsetViewToClipMatrix = m_viewToClipMatrix; + offsetViewToClipMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX()); + offsetViewToClipMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY()); + + Matrix4x4 offsetViewToClipPrevMatrix = m_viewToClipPrevMatrix; + offsetViewToClipPrevMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX()); + offsetViewToClipPrevMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY()); + + // Build other matricies dependent on the view to clip matricies + Matrix4x4 offsetWorldToClipMatrix = offsetViewToClipMatrix * m_worldToViewMatrix; + Matrix4x4 offsetWorldToClipPrevMatrix = offsetViewToClipPrevMatrix * m_worldToViewPrevMatrix; + + Matrix4x4 offsetClipToViewMatrix = offsetViewToClipMatrix.GetInverseFull(); + Matrix4x4 offsetClipToWorldMatrix = m_viewToWorldMatrix * offsetClipToViewMatrix; + + m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, offsetWorldToClipPrevMatrix); + m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, offsetWorldToClipMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, offsetViewToClipMatrix); + m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, offsetClipToWorldMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, offsetViewToClipMatrix.GetInverseFull()); + } + + m_shaderResourceGroup->SetConstant(m_worldPositionConstantIndex, m_position); + m_shaderResourceGroup->SetConstant(m_viewMatrixConstantIndex, m_worldToViewMatrix); + m_shaderResourceGroup->SetConstant(m_viewMatrixInverseConstantIndex, m_worldToViewMatrix.GetInverseFull()); + m_shaderResourceGroup->SetConstant(m_zConstantsConstantIndex, m_nearZ_farZ_farZTimesNearZ_farZMinusNearZ); + m_shaderResourceGroup->SetConstant(m_unprojectionConstantsIndex, m_unprojectionConstants); + + m_shaderResourceGroup->Compile(); + m_needBuildSrg = false; } - if (m_worldToClipMatrixChanged) - { - m_worldToClipPrevMatrix = m_worldToClipMatrix; - m_worldToClipPrevMatrixNeedsUpdate = true; - m_worldToClipMatrixChanged = false; - } + m_viewToClipPrevMatrix = m_viewToClipMatrix; + m_worldToViewPrevMatrix = m_worldToViewMatrix; - if (!m_needBuildSrg) - { - return; - } - - m_shaderResourceGroup->SetConstant(m_worldPositionConstantIndex, m_position); - m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, m_worldToClipMatrix); - m_shaderResourceGroup->SetConstant(m_viewMatrixConstantIndex, m_worldToViewMatrix); - m_shaderResourceGroup->SetConstant(m_viewMatrixInverseConstantIndex, m_worldToViewMatrix.GetInverseFull()); - m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, m_viewToClipMatrix); - m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, m_viewToClipMatrix.GetInverseFull()); - m_shaderResourceGroup->SetConstant(m_zConstantsConstantIndex, m_nearZ_farZ_farZTimesNearZ_farZMinusNearZ); - m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, m_clipToWorldMatrix); - m_shaderResourceGroup->SetConstant(m_unprojectionConstantsIndex, m_unprojectionConstants); - - m_shaderResourceGroup->Compile(); - m_needBuildSrg = false; + m_clipSpaceOffset.Set(0); } void View::BeginCulling() From 7984f82e481b2ddac0a8ebb7f2b28b4aa9d8f9d8 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Fri, 4 Jun 2021 23:03:17 -0400 Subject: [PATCH 542/811] Bing project_properties CLI to updateProject method. Update project info struct. Update project properties cli to support lists for tags. Minor adjustments to support changes. --- .../ProjectManager/Source/ProjectInfo.cpp | 7 ++- .../Tools/ProjectManager/Source/ProjectInfo.h | 13 ++++-- .../ProjectManager/Source/PythonBindings.cpp | 45 +++++++++++-------- .../ProjectManager/Source/PythonBindings.h | 7 +-- .../Source/PythonBindingsInterface.h | 21 +-------- .../Source/UpdateProjectCtrl.cpp | 6 +-- scripts/o3de/o3de/project_properties.py | 22 ++++----- 7 files changed, 59 insertions(+), 62 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp index f0dc05cc62..f470841f09 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp @@ -15,14 +15,19 @@ namespace O3DE::ProjectManager { ProjectInfo::ProjectInfo(const QString& path, const QString& projectName, const QString& displayName, - const QString& imagePath, const QString& backgroundImagePath, bool isNew) + const QString& origin, const QString& summary, const QString& imagePath, const QString& backgroundImagePath, + bool isNew) : m_path(path) , m_projectName(projectName) , m_displayName(displayName) + , m_origin(origin) + , m_summary(summary) , m_imagePath(imagePath) , m_backgroundImagePath(backgroundImagePath) , m_isNew(isNew) { + m_userTags = QStringList(); + m_userTagsForRemoval = QStringList(); } bool ProjectInfo::operator==(const ProjectInfo& rhs) diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.h b/Code/Tools/ProjectManager/Source/ProjectInfo.h index 71fa12b344..699d0997c6 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.h +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.h @@ -15,6 +15,7 @@ #if !defined(Q_MOC_RUN) #include #include +#include #endif namespace O3DE::ProjectManager @@ -23,8 +24,8 @@ namespace O3DE::ProjectManager { public: ProjectInfo() = default; - ProjectInfo(const QString& path, const QString& projectName, const QString& displayName, - const QString& imagePath, const QString& backgroundImagePath, bool isNew); + ProjectInfo(const QString& path, const QString& projectName, const QString& displayName, const QString& origin, + const QString& summary, const QString& imagePath, const QString& backgroundImagePath, bool isNew); bool operator==(const ProjectInfo& rhs); bool operator!=(const ProjectInfo& rhs); @@ -36,12 +37,18 @@ namespace O3DE::ProjectManager // From project.json QString m_projectName; QString m_displayName; + QString m_origin; + QString m_summary; + QStringList m_userTags; // Used on projects home screen QString m_imagePath; - QString m_backgroundImagePath; + QStringList m_backgroundImagePath; // Used in project creation bool m_isNew = false; //! Is this a new project or existing + + // Used to flag tags for removal + QStringList m_userTagsForRemoval; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 0acbf8ffaf..16bcd6e122 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #pragma pop_macro("slots") #include @@ -687,23 +688,6 @@ namespace O3DE::ProjectManager return projectInfo; } - AZ::Outcome PythonBindings::ModifyProjectProperties(const QString& path, const QString& origin, const QString& displayName, - const QString& summary, const QString& icon, const QString& addTag, const QString& removeTag) - { - return ExecuteWithLockErrorHandling([&] - { - m_editProjectProperties.attr("edit_project_props")( - pybind11::str(path.toStdString()), //proj_path - pybind11::none(), //proj_name not used - origin.isNull() ? pybind11::none() : pybind11::str(origin.toStdString()), //new_origin - displayName.isNull() ? pybind11::none() : pybind11::str(displayName.toStdString()), //new_display - summary.isNull() ? pybind11::none() : pybind11::str(summary.toStdString()), //new_summary - icon.isNull() ? pybind11::none() : pybind11::str(icon.toStdString()), //new_icon - addTag.isNull() ? pybind11::none() : pybind11::str(addTag.toStdString()), //new_tag - removeTag.isNull() ? pybind11::none() : pybind11::str(removeTag.toStdString())); //remove_tag - }); - } - AZ::Outcome> PythonBindings::GetProjects() { QVector projects; @@ -764,9 +748,32 @@ namespace O3DE::ProjectManager }); } - bool PythonBindings::UpdateProject([[maybe_unused]] const ProjectInfo& projectInfo) + AZ::Outcome PythonBindings::UpdateProject(const ProjectInfo& projectInfo) { - return false; + return ExecuteWithLockErrorHandling([&] + { + std::list newTags; + for (auto& i : projectInfo.m_userTags) + { + newTags.push_back(i.toStdString()); + } + + std::list removedTags; + for (auto& i : projectInfo.m_userTagsForRemoval) + { + removedTags.push_back(i.toStdString()); + } + + m_editProjectProperties.attr("edit_project_props")( + pybind11::str(projectInfo.m_path.toStdString()), // proj_path + pybind11::none(), // proj_name not used + pybind11::str(projectInfo.m_origin.toStdString()), // new_origin + pybind11::str(projectInfo.m_displayName.toStdString()), // new_display + pybind11::str(projectInfo.m_summary.toStdString()), // new_summary + pybind11::str(projectInfo.m_imagePath.toStdString()), // new_icon + pybind11::list(pybind11::cast(newTags)), // new_tag + pybind11::list(pybind11::cast(removedTags))); // remove_tag + }); } ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h index 5f03d0ab28..707595b6fd 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.h +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -50,14 +50,9 @@ namespace O3DE::ProjectManager AZ::Outcome> GetProjects() override; bool AddProject(const QString& path) override; bool RemoveProject(const QString& path) override; - bool UpdateProject(const ProjectInfo& projectInfo) override; + AZ::Outcome UpdateProject(const ProjectInfo& projectInfo) override; AZ::Outcome AddGemToProject(const QString& gemPath, const QString& projectPath) override; AZ::Outcome RemoveGemFromProject(const QString& gemPath, const QString& projectPath) override; - AZ::Outcome ModifyProjectProperties( - const QString& path, - const QString& origin = 0, - const QString& displayName = 0, - const QString& summary = 0, const QString& icon = 0, const QString& addTag = 0, const QString& removeTag = 0) override; // ProjectTemplate AZ::Outcome> GetProjectTemplates() override; diff --git a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h index edc9510236..fd94a4e964 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h +++ b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h @@ -122,7 +122,7 @@ namespace O3DE::ProjectManager * @param projectInfo the info to use to update the project * @return true on success, false on failure */ - virtual bool UpdateProject(const ProjectInfo& projectInfo) = 0; + virtual AZ::Outcome UpdateProject(const ProjectInfo& projectInfo) = 0; /** * Add a gem to a project @@ -132,25 +132,6 @@ namespace O3DE::ProjectManager */ virtual AZ::Outcome AddGemToProject(const QString& gemPath, const QString& projectPath) = 0; - /** - * Change property in project json file - * @param path the absolute path to the gem - * @param origin the description or url for project origin (such as project host, repository, owner...etc) - * @param displayName the project display name - * @param summary short description of the project - * @param icon image used to represent the project - * @param addTag user tag to be added - * @param removeTag user tag to be removed - */ - virtual AZ::Outcome ModifyProjectProperties( - const QString& path, - const QString& origin = 0, - const QString& displayName = 0, - const QString& summary = 0, - const QString& icon = 0, - const QString& addTag = 0, - const QString& removeTag = 0) = 0; - /** * Remove gem to a project * @param gemPath the absolute path to the gem diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp index a383a0f93b..19078f65ea 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp @@ -134,10 +134,10 @@ namespace O3DE::ProjectManager // Update project if settings changed if (m_projectInfo != newProjectSettings) { - bool result = PythonBindingsInterface::Get()->UpdateProject(newProjectSettings); - if (!result) + auto result = PythonBindingsInterface::Get()->UpdateProject(newProjectSettings); + if (!result.IsSuccess()) { - QMessageBox::critical(this, tr("Project update failed"), tr("Failed to update project.")); + QMessageBox::critical(this, tr("Project update failed"), tr(result.GetError().c_str())); return; } } diff --git a/scripts/o3de/o3de/project_properties.py b/scripts/o3de/o3de/project_properties.py index 69bd1b9406..83e76fc18f 100644 --- a/scripts/o3de/o3de/project_properties.py +++ b/scripts/o3de/o3de/project_properties.py @@ -45,15 +45,17 @@ def edit_project_props(proj_path, proj_name, new_origin, new_display, if new_icon: proj_json['icon_path'] = new_icon if new_tag: - proj_json.setdefault('user_tags', []).append(new_tag) + for tag in new_tag: + proj_json.setdefault('user_tags', []).append(tag) if remove_tag: if 'user_tags' in proj_json: - if remove_tag in proj_json['user_tags']: - proj_json['user_tags'].remove(remove_tag) - else: - logger.warn(f'{remove_tag} not found in user_tags for removal.') + for del_tag in remove_tag: + if del_tag in proj_json['user_tags']: + proj_json['user_tags'].remove(del_tag) + else: + logger.warn(f'{del_tag} not found in user_tags for removal.') else: - logger.warn(f'user_tags property not found for removal of tag {remove_tag}.') + logger.warn(f'user_tags property not found for removal of {remove_tag}.') manifest.save_o3de_manifest(proj_json, pathlib.Path(proj_path) / 'project.json') return 0 @@ -83,10 +85,10 @@ def add_parser_args(parser): help='Sets the summary description of the project.') group.add_argument('-pi', '--project-icon', type=str, required=False, help='Sets the path to the projects icon resource.') - group.add_argument('-pt', '--project-tag', type=str, required=False, - help='Adds a tag to user_tags property. These tags are intended for documentation and filtering.') - group.add_argument('-rt', '--remove-tag', type=str, required=False, - help='Removes a tag from the user_tags property.') + group.add_argument('-pt', '--project-tag', type=default, required=False, + help='Adds tag(s) to user_tags property. These tags are intended for documentation and filtering.') + group.add_argument('-rt', '--remove-tag', type=default, required=False, + help='Removes tag(s) from the user_tags property.') parser.set_defaults(func=_edit_project_props) def add_args(subparsers) -> None: From 155271a0ee164610e70cb93726f14b67103859e8 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Fri, 4 Jun 2021 23:07:36 -0400 Subject: [PATCH 543/811] Fixed data type changed by mistake for project info image path --- Code/Tools/ProjectManager/Source/ProjectInfo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.h b/Code/Tools/ProjectManager/Source/ProjectInfo.h index 699d0997c6..63f509af18 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.h +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.h @@ -43,7 +43,7 @@ namespace O3DE::ProjectManager // Used on projects home screen QString m_imagePath; - QStringList m_backgroundImagePath; + QString m_backgroundImagePath; // Used in project creation bool m_isNew = false; //! Is this a new project or existing From d2f8e4903719dfb97ec08795432106ce45ebbf13 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Fri, 4 Jun 2021 23:16:25 -0400 Subject: [PATCH 544/811] resolving merge conflict due to variable name change from main --- Code/Tools/ProjectManager/Source/ProjectInfo.cpp | 4 ++-- Code/Tools/ProjectManager/Source/ProjectInfo.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp index f470841f09..85716fccfa 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp @@ -16,7 +16,7 @@ namespace O3DE::ProjectManager { ProjectInfo::ProjectInfo(const QString& path, const QString& projectName, const QString& displayName, const QString& origin, const QString& summary, const QString& imagePath, const QString& backgroundImagePath, - bool isNew) + bool needsBuild) : m_path(path) , m_projectName(projectName) , m_displayName(displayName) @@ -24,7 +24,7 @@ namespace O3DE::ProjectManager , m_summary(summary) , m_imagePath(imagePath) , m_backgroundImagePath(backgroundImagePath) - , m_isNew(isNew) + , m_needsBuild(needsBuild) { m_userTags = QStringList(); m_userTagsForRemoval = QStringList(); diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.h b/Code/Tools/ProjectManager/Source/ProjectInfo.h index 63f509af18..99ab8ebf31 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.h +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.h @@ -25,7 +25,7 @@ namespace O3DE::ProjectManager public: ProjectInfo() = default; ProjectInfo(const QString& path, const QString& projectName, const QString& displayName, const QString& origin, - const QString& summary, const QString& imagePath, const QString& backgroundImagePath, bool isNew); + const QString& summary, const QString& imagePath, const QString& backgroundImagePath, bool needsBuild); bool operator==(const ProjectInfo& rhs); bool operator!=(const ProjectInfo& rhs); @@ -46,7 +46,7 @@ namespace O3DE::ProjectManager QString m_backgroundImagePath; // Used in project creation - bool m_isNew = false; //! Is this a new project or existing + bool m_needsBuild = false; //! Is this a new project or existing // Used to flag tags for removal QStringList m_userTagsForRemoval; From 0334aa1b1c1f4fc13495537e7b272263a16ef772 Mon Sep 17 00:00:00 2001 From: Peng Date: Fri, 4 Jun 2021 20:17:32 -0700 Subject: [PATCH 545/811] ATOM-15723 [RHI][Vulkan] Set unbounded array support based on physical device indexing features JIRA: https://jira.agscollab.com/browse/ATOM-15723 --- Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp index 76662ebc6e..04f2465e78 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp @@ -720,7 +720,7 @@ namespace AZ StringList deviceExtensions = physicalDevice.GetDeviceExtensionNames(); StringList::iterator itRayTracingExtension = AZStd::find(deviceExtensions.begin(), deviceExtensions.end(), VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME); m_features.m_rayTracing = (itRayTracingExtension != deviceExtensions.end()); - m_features.m_unboundedArrays = true; + m_features.m_unboundedArrays = physicalDevice.GetPhysicalDeviceDescriptorIndexingFeatures().shaderStorageTexelBufferArrayNonUniformIndexing; const auto& deviceLimits = physicalDevice.GetDeviceLimits(); m_limits.m_maxImageDimension1D = deviceLimits.maxImageDimension1D; From bf29b27937f4f1ff0828a6b49859e7e0570b685e Mon Sep 17 00:00:00 2001 From: amzn-hdoke <61443753+hdoke@users.noreply.github.com> Date: Fri, 4 Jun 2021 20:48:35 -0700 Subject: [PATCH 546/811] Add AWSAttribution feature (#1164) * LYN-3601: Provide skeleton classes for AWS Attribution (#31) Provide skeleton classes for AWS Attribution, along with some basic unit tests * Add AWS Attribution UI and settings (#56) * Adding AWS Attributions UX and corresponding editor preference s setting * Fix serialized field description * Fixed update frequency to be a day * Handling editor startup with default values for AWSAttribution * Add missing header and remove AWSCoreSystemComponentMock fron test * Generate and post AWSAttribution metric (#69) * Adding AWS Attribution Api service job * Adding support for config endpoint override * Update Api endpoint formatting, fix default region * Remove extra header * Fixes for link issues * Fix Unittest namespace * Instantiating AWSAttributionSystemComponent in AWS.Editor module * Update AttributionMetric with engine version and AWS enabled gems (#77) * Update AttributionMetric with engine version and AWS enabled gems * Fix warnings * Undoing accidental change * Saving level PrefabLevel_OpensLevelWithEntities * Remove overriding editorprefrences.setreg * Revert "Saving level PrefabLevel_OpensLevelWithEntities" This reverts commit 529af70c55ece70fc6bc29ceb83bef60413713a3. * Move AWS preferences to its own temp settings file * Undo accidental file add * Add missing string params in warning messages Co-authored-by: Pip Potter <61438964+lmbr-pip@users.noreply.github.com> --- .../Editor/EditorPreferencesDialog.cpp | 2 + .../Editor/EditorPreferencesPageAWS.cpp | 151 +++++++ .../Sandbox/Editor/EditorPreferencesPageAWS.h | 60 +++ Code/Sandbox/Editor/MainWindow.qrc | 1 + Code/Sandbox/Editor/PreferencesStdPages.cpp | 8 + Code/Sandbox/Editor/editor_lib_files.cmake | 2 + .../Editor/res/AWS_preferences_icon.svg | 3 + Gems/AWSCore/Code/CMakeLists.txt | 4 +- .../Include/Private/AWSCoreEditorModule.h | 2 +- .../Attribution/AWSAttributionServiceApi.h | 71 +++ .../Attribution/AWSCoreAttributionConstant.h | 25 ++ .../Attribution/AWSCoreAttributionManager.h | 53 +++ .../Attribution/AWSCoreAttributionMetric.h | 62 +++ .../AWSCoreAttributionSystemComponent.h | 50 +++ .../Public/Framework/ServiceClientJobConfig.h | 6 + .../Code/Source/AWSCoreEditorModule.cpp | 5 +- .../Attribution/AWSAttributionServiceApi.cpp | 45 ++ .../Attribution/AWSCoreAttributionManager.cpp | 275 ++++++++++++ .../Attribution/AWSCoreAttributionMetric.cpp | 106 +++++ .../AWSCoreAttributionSystemComponent.cpp | 81 ++++ .../AWSAttributionServiceApiTest.cpp | 85 ++++ .../AWSCoreAttributionManagerTest.cpp | 414 ++++++++++++++++++ .../AWSCoreAttributionMetricTest.cpp | 50 +++ .../AWSCoreAttributionSystemComponentTest.cpp | 132 ++++++ .../Code/Tests/TestFramework/AWSCoreFixture.h | 31 +- Gems/AWSCore/Code/awscore_editor_files.cmake | 9 + .../Code/awscore_editor_tests_files.cmake | 4 + 27 files changed, 1732 insertions(+), 5 deletions(-) create mode 100644 Code/Sandbox/Editor/EditorPreferencesPageAWS.cpp create mode 100644 Code/Sandbox/Editor/EditorPreferencesPageAWS.h create mode 100644 Code/Sandbox/Editor/res/AWS_preferences_icon.svg create mode 100644 Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSAttributionServiceApi.h create mode 100644 Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionConstant.h create mode 100644 Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionManager.h create mode 100644 Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionMetric.h create mode 100644 Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionSystemComponent.h create mode 100644 Gems/AWSCore/Code/Source/Editor/Attribution/AWSAttributionServiceApi.cpp create mode 100644 Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp create mode 100644 Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionMetric.cpp create mode 100644 Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionSystemComponent.cpp create mode 100644 Gems/AWSCore/Code/Tests/Editor/Attribution/AWSAttributionServiceApiTest.cpp create mode 100644 Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionManagerTest.cpp create mode 100644 Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionMetricTest.cpp create mode 100644 Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionSystemComponentTest.cpp diff --git a/Code/Sandbox/Editor/EditorPreferencesDialog.cpp b/Code/Sandbox/Editor/EditorPreferencesDialog.cpp index e5bcfd6bad..679c73e7df 100644 --- a/Code/Sandbox/Editor/EditorPreferencesDialog.cpp +++ b/Code/Sandbox/Editor/EditorPreferencesDialog.cpp @@ -35,6 +35,7 @@ #include "EditorPreferencesPageViewportMovement.h" #include "EditorPreferencesPageViewportDebug.h" #include "EditorPreferencesPageExperimentalLighting.h" +#include "EditorPreferencesPageAWS.h" #include "LyViewPaneNames.h" AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING @@ -72,6 +73,7 @@ EditorPreferencesDialog::EditorPreferencesDialog(QWidget* pParent) CEditorPreferencesPage_ViewportMovement::Reflect(*serializeContext); CEditorPreferencesPage_ViewportDebug::Reflect(*serializeContext); CEditorPreferencesPage_ExperimentalLighting::Reflect(*serializeContext); + CEditorPreferencesPage_AWS::Reflect(*serializeContext); } } diff --git a/Code/Sandbox/Editor/EditorPreferencesPageAWS.cpp b/Code/Sandbox/Editor/EditorPreferencesPageAWS.cpp new file mode 100644 index 0000000000..edaf813cd8 --- /dev/null +++ b/Code/Sandbox/Editor/EditorPreferencesPageAWS.cpp @@ -0,0 +1,151 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#include "EditorDefs.h" + +#include "EditorPreferencesPageAWS.h" + +// AzCore +#include +#include +#include + +void CEditorPreferencesPage_AWS::Reflect(AZ::SerializeContext& serialize) +{ + serialize.Class() + ->Version(1) + ->Field("AWSAttributionEnabled", &UsageOptions::m_awsAttributionEnabled); + + serialize.Class() + ->Version(1) + ->Field("UsageOptions", &CEditorPreferencesPage_AWS::m_usageOptions); + + AZ::EditContext* editContext = serialize.GetEditContext(); + if (editContext) + { + editContext->Class("Options", "") + ->DataElement(AZ::Edit::UIHandlers::CheckBox, &UsageOptions::m_awsAttributionEnabled, "Send Metrics usage to AWS", + "Reports Gem usage to AWS on Editor launch"); + + editContext->Class("AWS Preferences", "AWS Preferences") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20)) + ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_AWS::m_usageOptions, "AWS Usage Data", "AWS Usage Options"); + } +} + + +CEditorPreferencesPage_AWS::CEditorPreferencesPage_AWS() +{ + m_settingsRegistry = AZStd::make_unique(); + InitializeSettings(); + + // TODO Update with AWS svg. + m_icon = QIcon(":/res/AWS_preferences_icon.svg"); +} + +CEditorPreferencesPage_AWS::~CEditorPreferencesPage_AWS() +{ + m_settingsRegistry.reset(); +} + +const char* CEditorPreferencesPage_AWS::GetTitle() +{ + return "AWS"; +} + +QIcon& CEditorPreferencesPage_AWS::GetIcon() +{ + return m_icon; +} + +void CEditorPreferencesPage_AWS::OnApply() +{ + m_settingsRegistry->Set(AWSAttributionEnabledKey, m_usageOptions.m_awsAttributionEnabled); + SaveSettingsRegistryFile(); +} + +const CEditorPreferencesPage_AWS::UsageOptions& CEditorPreferencesPage_AWS::GetUsageOptions() +{ + return m_usageOptions; +} + +void CEditorPreferencesPage_AWS::SaveSettingsRegistryFile() +{ + AZ::Job* job = AZ::CreateJobFunction( + [this]() + { + AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); + AZ_Assert(fileIO, "File IO is not initialized."); + + // Resolve path to editor_aws_preferences.setreg + AZStd::string editorPreferencesFilePath = + AZStd::string::format("@user@/%s/%s", AZ::SettingsRegistryInterface::RegistryFolder, EditorAWSPreferencesFileName); + AZStd::array resolvedPath{}; + fileIO->ResolvePath(editorPreferencesFilePath.c_str(), resolvedPath.data(), resolvedPath.size()); + + AZ::SettingsRegistryMergeUtils::DumperSettings dumperSettings; + dumperSettings.m_prettifyOutput = true; + dumperSettings.m_jsonPointerPrefix = AWSAttributionSettingsPrefixKey; + + AZStd::string stringBuffer; + AZ::IO::ByteContainerStream stringStream(&stringBuffer); + if (!AZ::SettingsRegistryMergeUtils::DumpSettingsRegistryToStream( + *m_settingsRegistry, AWSAttributionSettingsPrefixKey, stringStream, dumperSettings)) + { + AZ_Warning( + "AWSAttributionManager", false, R"(Unable to save changes to the Editor AWS Preferences registry file at "%s"\n)", + resolvedPath.data()); + return; + } + + bool saved{}; + constexpr auto configurationMode = + AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY; + if (AZ::IO::SystemFile outputFile; outputFile.Open(resolvedPath.data(), configurationMode)) + { + saved = outputFile.Write(stringBuffer.data(), stringBuffer.size()) == stringBuffer.size(); + } + + AZ_Warning( + "AWSAttributionManager", saved, R"(Unable to save Editor AWS Preferences registry file to path "%s"\n)", + editorPreferencesFilePath.c_str()); + }, + true); + job->Start(); +} + +void CEditorPreferencesPage_AWS::InitializeSettings() +{ + AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); + AZ_Assert(fileIO, "File IO is not initialized."); + + // Resolve path to editor_aws_preferences.setreg + AZStd::string editorAWSPreferencesFilePath = + AZStd::string::format("@user@/%s/%s", AZ::SettingsRegistryInterface::RegistryFolder, EditorAWSPreferencesFileName); + AZStd::array resolvedPathAWSPreference{}; + if (!fileIO->ResolvePath(editorAWSPreferencesFilePath.c_str(), resolvedPathAWSPreference.data(), resolvedPathAWSPreference.size())) + { + AZ_Warning("AWSAttributionManager", false, "Error resolving path %s", resolvedPathAWSPreference.data()); + return; + } + + if (fileIO->Exists(resolvedPathAWSPreference.data())) + { + m_settingsRegistry->MergeSettingsFile(resolvedPathAWSPreference.data(), AZ::SettingsRegistryInterface::Format::JsonMergePatch, ""); + } + + if (!m_settingsRegistry->Get(m_usageOptions.m_awsAttributionEnabled, AWSAttributionEnabledKey)) + { + // If key is missing default to on. + m_usageOptions.m_awsAttributionEnabled = true; + } +} diff --git a/Code/Sandbox/Editor/EditorPreferencesPageAWS.h b/Code/Sandbox/Editor/EditorPreferencesPageAWS.h new file mode 100644 index 0000000000..b0dc7ee740 --- /dev/null +++ b/Code/Sandbox/Editor/EditorPreferencesPageAWS.h @@ -0,0 +1,60 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include "Include/IPreferencesPage.h" +#include +#include +#include +#include + +class CEditorPreferencesPage_AWS + : public IPreferencesPage +{ +public: + AZ_RTTI(CEditorPreferencesPage_AWS, "{51FB9557-ABA3-4FD7-803A-1784F5B06F5F}", IPreferencesPage) + + static void Reflect(AZ::SerializeContext& serialize); + + CEditorPreferencesPage_AWS(); + virtual ~CEditorPreferencesPage_AWS(); + + // IPreferencesPage interface methods. + virtual const char* GetCategory() override { return "AWS"; } + virtual const char* GetTitle() override; + virtual QIcon& GetIcon() override; + virtual void OnApply() override; + virtual void OnCancel() override {} + virtual bool OnQueryCancel() override { return true; } + +protected: + struct UsageOptions + { + AZ_TYPE_INFO(UsageOptions, "{2B7D9B19-D13B-4E54-B724-B2FD8D0828B3}") + + bool m_awsAttributionEnabled; + }; + + const UsageOptions& GetUsageOptions(); + +private: + void InitializeSettings(); + void SaveSettingsRegistryFile(); + UsageOptions m_usageOptions; + QIcon m_icon; + AZStd::unique_ptr m_settingsRegistry; + + static constexpr char AWSAttributionEnabledKey[] = "/Amazon/AWS/Preferences/AWSAttributionEnabled"; + static constexpr char EditorPreferencesFileName[] = "editorpreferences.setreg"; + static constexpr char EditorAWSPreferencesFileName[] = "editor_aws_preferences.setreg"; + static constexpr char AWSAttributionSettingsPrefixKey[] = "/Amazon/AWS/Preferences"; +}; diff --git a/Code/Sandbox/Editor/MainWindow.qrc b/Code/Sandbox/Editor/MainWindow.qrc index 476159fbfd..fd207ebe13 100644 --- a/Code/Sandbox/Editor/MainWindow.qrc +++ b/Code/Sandbox/Editor/MainWindow.qrc @@ -143,6 +143,7 @@ res/Camera.svg res/Debug.svg res/Experimental.svg + res/AWS_preferences_icon.svg res/Files.svg res/Gizmos.svg res/Global.svg diff --git a/Code/Sandbox/Editor/PreferencesStdPages.cpp b/Code/Sandbox/Editor/PreferencesStdPages.cpp index 032b01e353..3a66d6e3f4 100644 --- a/Code/Sandbox/Editor/PreferencesStdPages.cpp +++ b/Code/Sandbox/Editor/PreferencesStdPages.cpp @@ -15,6 +15,8 @@ #include "PreferencesStdPages.h" +#include + // Editor #include "EditorPreferencesPageGeneral.h" #include "EditorPreferencesPageFiles.h" @@ -23,6 +25,7 @@ #include "EditorPreferencesPageViewportMovement.h" #include "EditorPreferencesPageViewportDebug.h" #include "EditorPreferencesPageExperimentalLighting.h" +#include "EditorPreferencesPageAWS.h" ////////////////////////////////////////////////////////////////////////// @@ -42,6 +45,11 @@ CStdPreferencesClassDesc::CStdPreferencesClassDesc() }; m_pageCreators.push_back([]() { return new CEditorPreferencesPage_ExperimentalLighting(); }); + + if (AzToolsFramework::IsComponentWithServiceRegistered(AZ_CRC_CE("AWSCoreEditorService"))) + { + m_pageCreators.push_back([]() { return new CEditorPreferencesPage_AWS(); }); + } } HRESULT CStdPreferencesClassDesc::QueryInterface(const IID& riid, void** ppvObj) diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index e1cf18df55..ebd7f89cfb 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -586,6 +586,8 @@ set(FILES EditorPreferencesPageViewportDebug.cpp EditorPreferencesPageExperimentalLighting.h EditorPreferencesPageExperimentalLighting.cpp + EditorPreferencesPageAWS.h + EditorPreferencesPageAWS.cpp EditorPreferencesDialog.h EditorPreferencesDialog.cpp EditorPreferencesDialog.ui diff --git a/Code/Sandbox/Editor/res/AWS_preferences_icon.svg b/Code/Sandbox/Editor/res/AWS_preferences_icon.svg new file mode 100644 index 0000000000..e2a86cf162 --- /dev/null +++ b/Code/Sandbox/Editor/res/AWS_preferences_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/Gems/AWSCore/Code/CMakeLists.txt b/Gems/AWSCore/Code/CMakeLists.txt index 7edb22124f..d6cd57355f 100644 --- a/Gems/AWSCore/Code/CMakeLists.txt +++ b/Gems/AWSCore/Code/CMakeLists.txt @@ -64,11 +64,13 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Include/Public BUILD_DEPENDENCIES PRIVATE + AZ::AzQtComponents 3rdParty::Qt::Core 3rdParty::Qt::Widgets - AZ::AzQtComponents + Gem::AWSCore.Static PUBLIC AZ::AzToolsFramework + 3rdParty::AWSNativeSDK::AWSCore ) ly_add_target( diff --git a/Gems/AWSCore/Code/Include/Private/AWSCoreEditorModule.h b/Gems/AWSCore/Code/Include/Private/AWSCoreEditorModule.h index 45a2c1f9f7..144976f355 100644 --- a/Gems/AWSCore/Code/Include/Private/AWSCoreEditorModule.h +++ b/Gems/AWSCore/Code/Include/Private/AWSCoreEditorModule.h @@ -16,7 +16,7 @@ namespace AWSCore { class AWSCoreEditorModule - :public AZ::Module + : public AZ::Module { public: AZ_RTTI(AWSCoreEditorModule, "{C1C9B898-848B-4C2F-A7AA-69642D12BCB5}", AZ::Module); diff --git a/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSAttributionServiceApi.h b/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSAttributionServiceApi.h new file mode 100644 index 0000000000..d14e51589c --- /dev/null +++ b/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSAttributionServiceApi.h @@ -0,0 +1,71 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include + +namespace AWSCore +{ + namespace ServiceAPI + { + //! Struct for storing the success response. + struct AWSAtrributionSuccessResponse + { + //! Identify the expected property type and provide a location where the property value can be stored. + //! @param key Name of the property. + //! @param reader JSON reader to read the property. + bool OnJsonKey(const char* key, AWSCore::JsonReader& reader); + + AZStd::string result; //!< Processing result for the input record. + }; + + // Service RequestJobs + AWS_FEATURE_GEM_SERVICE(AWSAttribution); + + //! POST request to send attribution metric to the backend. + //! The path for this service API is "/prod/metrics". + class AWSAttributionRequest + : public AWSCore::ServiceRequest + { + public: + SERVICE_REQUEST(AWSAttribution, HttpMethod::HTTP_POST, "/metrics"); + + bool UseAWSCredentials() + { + return false; + } + + //! Request body for the service API request. + struct Parameters + { + //! Build the service API request. + //! @request Builder for generating the request. + //! @return Whether the request is built successfully. + bool BuildRequest(AWSCore::RequestBuilder& request); + + //! Write to the service API request body. + //! @param writer JSON writer for the serialization. + //! @return Whether the serialization is successful. + bool WriteJson(AWSCore::JsonWriter& writer) const; + + AttributionMetric metric; + }; + + AWSAtrributionSuccessResponse result; + Parameters parameters; //! Request parameter. + }; + + using AWSAttributionRequestJob = AWSCore::ServiceRequestJob; + } // ServiceAPI +} // AWSMetrics diff --git a/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionConstant.h b/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionConstant.h new file mode 100644 index 0000000000..503abfb9cf --- /dev/null +++ b/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionConstant.h @@ -0,0 +1,25 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#pragma once + +namespace AWSCore +{ + //! Default metrics attribute keys + static constexpr char AwsAttributionAttributeKeyVersion[] = "version"; + static constexpr char AwsAttributionAttributeKeyO3DEVersion[] = "o3de_version"; + static constexpr char AwsAttributionAttributeKeyPlatform[] = "platform"; + static constexpr char AwsAttributionAttributeKeyPlatformVersion[] = "platform_version"; + static constexpr char AwsAttributionAttributeKeyActiveAWSGems[] = "aws_gems"; + static constexpr char AwsAttributionAttributeKeyTimestamp[] = "timestamp"; + +} // namespace AWSCOre diff --git a/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionManager.h b/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionManager.h new file mode 100644 index 0000000000..ad3b8c72c9 --- /dev/null +++ b/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionManager.h @@ -0,0 +1,53 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#pragma once +#include +#include + +#include +#include + +namespace AWSCore +{ + //! Manages operational metrics for AWS gems + class AWSAttributionManager + { + public: + AWSAttributionManager(); + virtual ~AWSAttributionManager(); + + //! Perform initialization + void Init(); + + //! Run metric check + void MetricCheck(); + + protected: + virtual void SubmitMetric(AttributionMetric& metric); + virtual void UpdateMetric(AttributionMetric& metric); + void UpdateLastSend(); + void SetApiEndpointAndRegion(ServiceAPI::AWSAttributionRequestJob::Config* config); + + private: + bool ShouldGenerateMetric() const; + + AZStd::string GetEngineVersion() const; + AZStd::string GetPlatform() const; + void GetActiveAWSGems(AZStd::vector& gemNames); + + void SaveSettingsRegistryFile(); + + AZStd::unique_ptr m_settingsRegistry; + }; + +} // namespace AWSCore diff --git a/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionMetric.h b/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionMetric.h new file mode 100644 index 0000000000..42518b8df5 --- /dev/null +++ b/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionMetric.h @@ -0,0 +1,62 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates, or + * a third party where indicated. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#pragma once + +#include + +#include +#include +#include +#include + +namespace AWSCore +{ + //! Defines the operational metric sent periodically + class AttributionMetric + { + public: + AZ_TYPE_INFO(MetricsAttribute, "{6483F481-0C18-4171-8B59-A44F2F28EAE5}") + + AttributionMetric(); + AttributionMetric(const AZStd::string& timestamp); + ~AttributionMetric() = default; + + void SetO3DEVersion(const AZStd::string& version); + void SetPlatform(const AZStd::string& platform, const AZStd::string& platformVersion); + void AddActiveGem(const AZStd::string& gemName); + + //! Serialize the metrics object queue to a string. + //! @return Serialized string. + AZStd::string SerializeToJson(); + + //! Serialize the metrics object to JSON for the sending requests. + //! @param writer JSON writer for the serialization. + //! @return Whether the metrics event is serialized successfully. + bool SerializeToJson(AWSCore::JsonWriter& writer) const; + + //! Read from a JSON value to the metrics event. + //! @param metricsObjVal JSON value to read from. + //! @return Whether the metrics event is created successfully. + bool ReadFromJson(rapidjson::Value& metricsObjVal); + + //! Generates a UTC 8601 formatted timestamp + static AZStd::string GenerateTimeStamp(); + private: + AZStd::string m_version; //!< Schema version in use + AZStd::string m_o3deVersion; //!< O3DE editor version in use + AZStd::string m_platform; //!< OS type + AZStd::string m_platformVersion; //!< OS subtype + AZStd::string m_timestamp; //!< Metric generation time + AZStd::vector m_activeAWSGems; //!< Active AWS Gems in project + }; +} // namespace AWSCore diff --git a/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionSystemComponent.h b/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionSystemComponent.h new file mode 100644 index 0000000000..476b7ba842 --- /dev/null +++ b/Gems/AWSCore/Code/Include/Private/Editor/Attribution/AWSCoreAttributionSystemComponent.h @@ -0,0 +1,50 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#pragma once + +#include +#include + +namespace AWSCore +{ + class AWSAttributionManager; + + //! Attribution System Component. Responsible for instantiating and managing AWS Attribution Manager + class AWSAttributionSystemComponent: + public AZ::Component + { + public: + AZ_COMPONENT(AWSAttributionSystemComponent, "{366861EC-8337-4180-A202-4E4DF082A3A8}"); + + AWSAttributionSystemComponent(); + ~AWSAttributionSystemComponent() = default; + + static void Reflect(AZ::ReflectContext* context);\ + + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); + + protected: + //////////////////////////////////////////////////////////////////////// + // AZ::Component interface implementation + void Init() override; + void Activate() override; + void Deactivate() override; + //////////////////////////////////////////////////////////////////////// + + private: + AZStd::unique_ptr m_manager; //!< pointer to the attribution manager which handles operational metrics + }; +} // namespace AWSCore diff --git a/Gems/AWSCore/Code/Include/Public/Framework/ServiceClientJobConfig.h b/Gems/AWSCore/Code/Include/Public/Framework/ServiceClientJobConfig.h index 722fc098a0..709e786adc 100644 --- a/Gems/AWSCore/Code/Include/Public/Framework/ServiceClientJobConfig.h +++ b/Gems/AWSCore/Code/Include/Public/Framework/ServiceClientJobConfig.h @@ -113,7 +113,13 @@ namespace AWSCore /// needed. See it's use in ServiceRequestJobConfig. const AZStd::string GetServiceUrl() override { + if (endpointOverride.has_value()) + { + return endpointOverride.value().c_str(); + } + AZStd::string serviceUrl; + if (!ServiceTraitsType::RESTApiIdKeyName && !ServiceTraitsType::RESTApiStageKeyName) { AWSResourceMappingRequestBus::BroadcastResult( diff --git a/Gems/AWSCore/Code/Source/AWSCoreEditorModule.cpp b/Gems/AWSCore/Code/Source/AWSCoreEditorModule.cpp index 69e45bfd68..2f4519c960 100644 --- a/Gems/AWSCore/Code/Source/AWSCoreEditorModule.cpp +++ b/Gems/AWSCore/Code/Source/AWSCoreEditorModule.cpp @@ -11,6 +11,7 @@ #include #include +#include namespace AWSCore { @@ -19,6 +20,7 @@ namespace AWSCore // Push results of [MyComponent]::CreateDescriptor() into m_descriptors here. m_descriptors.insert(m_descriptors.end(), { AWSCoreEditorSystemComponent::CreateDescriptor(), + AWSAttributionSystemComponent::CreateDescriptor() }); } @@ -28,7 +30,8 @@ namespace AWSCore AZ::ComponentTypeList AWSCoreEditorModule::GetRequiredSystemComponents() const { return AZ::ComponentTypeList{ - azrtti_typeid() + azrtti_typeid(), + azrtti_typeid() }; } diff --git a/Gems/AWSCore/Code/Source/Editor/Attribution/AWSAttributionServiceApi.cpp b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSAttributionServiceApi.cpp new file mode 100644 index 0000000000..3c82ec98f9 --- /dev/null +++ b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSAttributionServiceApi.cpp @@ -0,0 +1,45 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include + +namespace AWSCore +{ + namespace ServiceAPI + { + constexpr char AwsAttributionServiceResultResponseKey[] = "statusCode"; + + bool AWSAtrributionSuccessResponse::OnJsonKey(const char* key, AWSCore::JsonReader& reader) + { + if (strcmp(key, AwsAttributionServiceResultResponseKey) == 0) + { + return reader.Accept(result); + } + return reader.Ignore(); + } + + bool AWSAttributionRequest::Parameters::BuildRequest(AWSCore::RequestBuilder& request) + { + bool ok = true; + ok = ok && request.WriteJsonBodyParameter(*this); + return ok; + } + + bool AWSAttributionRequest::Parameters::WriteJson(AWSCore::JsonWriter& writer) const + { + bool ok = true; + ok = ok && metric.SerializeToJson(writer); + return ok; + } + } +} diff --git a/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp new file mode 100644 index 0000000000..e7a6828903 --- /dev/null +++ b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp @@ -0,0 +1,275 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +namespace AWSCore +{ + static constexpr const char* EngineVersionJsonKey = "O3DEVersion"; + + constexpr char EditorAWSPreferencesFileName[] = "editor_aws_preferences.setreg"; + constexpr char AWSAttributionSettingsPrefixKey[] = "/Amazon/AWS/Preferences"; + constexpr char AWSAttributionEnabledKey[] = "/Amazon/AWS/Preferences/AWSAttributionEnabled"; + constexpr char AWSAttributionDelaySecondsKey[] = "/Amazon/AWS/Preferences/AWSAttributionDelaySeconds"; + constexpr char AWSAttributionLastTimeStampKey[] = "/Amazon/AWS/Preferences/AWSAttributionLastTimeStamp"; + constexpr char AWSAttributionApiId[] = "xbzx78kvbk"; + constexpr char AWSAttributionChinaApiId[] = ""; + constexpr char AWSAttributionApiStage[] = "prod"; + + AWSAttributionManager::AWSAttributionManager() + { + m_settingsRegistry = AZStd::make_unique(); + } + + AWSAttributionManager::~AWSAttributionManager() + { + m_settingsRegistry.reset(); + } + + void AWSAttributionManager::Init() + { + } + + void AWSAttributionManager::MetricCheck() + { + if (ShouldGenerateMetric()) + { + // 1. Gather metadata and assemble metric + AttributionMetric metric; + UpdateMetric(metric); + // 2. Identify region and chose attribution endpoint + + // 3. Post metric + SubmitMetric(metric); + } + } + + bool AWSAttributionManager::ShouldGenerateMetric() const + { + AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); + AZ_Assert(fileIO, "File IO is not initialized."); + + // Resolve path to editor_aws_preferences.setreg + AZStd::string editorAWSPreferencesFilePath = + AZStd::string::format("@user@/%s/%s", AZ::SettingsRegistryInterface::RegistryFolder, EditorAWSPreferencesFileName); + AZStd::array resolvedPathAWSPreference{}; + if (!fileIO->ResolvePath(editorAWSPreferencesFilePath.c_str(), resolvedPathAWSPreference.data(), resolvedPathAWSPreference.size())) + { + AZ_Warning("AWSAttributionManager", false, "Error resolving path %s", resolvedPathAWSPreference.data()); + return false; + } + + if (fileIO->Exists(resolvedPathAWSPreference.data())) + { + m_settingsRegistry->MergeSettingsFile(resolvedPathAWSPreference.data(), AZ::SettingsRegistryInterface::Format::JsonMergePatch, ""); + } + + bool awsAttributionEnabled = false; + if (!m_settingsRegistry->Get(awsAttributionEnabled, AWSAttributionEnabledKey)) + { + // If not found default to sending the metric. + awsAttributionEnabled = true; + } + + if (!awsAttributionEnabled) + { + return false; + } + + // If delayInSeconds is not found, set default to a day + AZ::u64 delayInSeconds = 0; + if (!m_settingsRegistry->Get(delayInSeconds, AWSAttributionDelaySecondsKey)) + { + AZ_Warning("AWSAttributionManager", false, "AWSAttribution delay key not found. Defaulting to delay to day"); + delayInSeconds = 86400; + m_settingsRegistry->Set(AWSAttributionDelaySecondsKey, delayInSeconds); + } + + AZ::u64 lastSendTimeStampSeconds = 0; + if (!m_settingsRegistry->Get(lastSendTimeStampSeconds, AWSAttributionLastTimeStampKey)) + { + // If last time stamp not found, assume this is the first attempt at sending. + return true; + } + + AZStd::chrono::seconds lastSendTimeStamp = AZStd::chrono::seconds(lastSendTimeStampSeconds); + AZStd::chrono::seconds secondsSinceLastSend = + AZStd::chrono::duration_cast(AZStd::chrono::system_clock::now().time_since_epoch()) - lastSendTimeStamp; + if (secondsSinceLastSend.count() >= delayInSeconds) + { + return true; + } + + return false; + } + + void AWSAttributionManager::SaveSettingsRegistryFile() + { + AZ::Job* job = AZ::CreateJobFunction( + [this]() + { + AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); + AZ_Assert(fileIO, "File IO is not initialized."); + + // Resolve path to editor_aws_preferences.setreg + AZStd::string editorPreferencesFilePath = AZStd::string::format("@user@/%s/%s", AZ::SettingsRegistryInterface::RegistryFolder, EditorAWSPreferencesFileName); + AZStd::array resolvedPath {}; + fileIO->ResolvePath(editorPreferencesFilePath.c_str(), resolvedPath.data(), resolvedPath.size()); + + AZ::SettingsRegistryMergeUtils::DumperSettings dumperSettings; + dumperSettings.m_prettifyOutput = true; + dumperSettings.m_jsonPointerPrefix = AWSAttributionSettingsPrefixKey; + + AZStd::string stringBuffer; + AZ::IO::ByteContainerStream stringStream(&stringBuffer); + if (!AZ::SettingsRegistryMergeUtils::DumpSettingsRegistryToStream( + *m_settingsRegistry, AWSAttributionSettingsPrefixKey, stringStream, dumperSettings)) + { + AZ_Warning( + "AWSAttributionManager", false, R"(Unable to save changes to the Editor AWS Preferences registry file at "%s"\n)", + resolvedPath.data()); + return; + } + + bool saved {}; + constexpr auto configurationMode = + AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY; + if (AZ::IO::SystemFile outputFile; outputFile.Open(resolvedPath.data(), configurationMode)) + { + saved = outputFile.Write(stringBuffer.data(), stringBuffer.size()) == stringBuffer.size(); + } + + AZ_Warning( + "AWSAttributionManager", saved, R"(Unable to save Editor AWS Preferences registry file to path "%s"\n)", + editorPreferencesFilePath.c_str()); + }, + true); + job->Start(); + + } + + void AWSAttributionManager::UpdateLastSend() + { + if (!m_settingsRegistry->Set(AWSAttributionLastTimeStampKey, + AZStd::chrono::duration_cast(AZStd::chrono::system_clock::now().time_since_epoch()).count())) + { + AZ_Warning("AWSAttributionManager", true, "Failed to set AWSAttributionLastTimeStamp"); + return; + } + SaveSettingsRegistryFile(); + } + + void AWSAttributionManager::SetApiEndpointAndRegion(AWSCore::ServiceAPI::AWSAttributionRequestJob::Config* config) + { + // Get default config for the process to check the region. + // Assumption to determine China region is the default profile is set to China region. + auto profile_name = Aws::Auth::GetConfigProfileName(); + Aws::Client::ClientConfiguration clientConfig(profile_name.c_str()); + AZStd::string apiId = AWSAttributionApiId; + + if (clientConfig.region == Aws::Region::CN_NORTH_1 || clientConfig.region == Aws::Region::CN_NORTHWEST_1) + { + config->region = Aws::Region::CN_NORTH_1; + apiId = AWSAttributionChinaApiId; + } + + config->region = Aws::Region::US_WEST_2; + config->endpointOverride = + AWSResourceMappingUtils::FormatRESTApiUrl(apiId, config->region.value().c_str(), AWSAttributionApiStage).c_str(); + } + + AZStd::string AWSAttributionManager::GetEngineVersion() const + { + AZStd::string engineVersion; + auto engineSettingsPath = AZ::IO::FixedMaxPath{ AZ::Utils::GetEnginePath() } / "engine.json"; + if (AZ::IO::SystemFile::Exists(engineSettingsPath.c_str())) + { + AZ::SettingsRegistryImpl settingsRegistry; + if (settingsRegistry.MergeSettingsFile( + engineSettingsPath.Native(), AZ::SettingsRegistryInterface::Format::JsonMergePatch, AZ::SettingsRegistryMergeUtils::EngineSettingsRootKey)) + { + settingsRegistry.Get(engineVersion, AZ::SettingsRegistryInterface::FixedValueString(AZ::SettingsRegistryMergeUtils::EngineSettingsRootKey) + "/" + EngineVersionJsonKey); + } + } + return engineVersion; + } + + AZStd::string AWSAttributionManager::GetPlatform() const + { + return AZ::GetPlatformName(AZ::g_currentPlatform); + } + + void AWSAttributionManager::GetActiveAWSGems(AZStd::vector& gems) + { + AZ::ModuleManagerRequestBus::Broadcast( + &AZ::ModuleManagerRequestBus::Events::EnumerateModules, + [this, &gems](const AZ::ModuleData& moduleData) + { + AZ::Entity* moduleEntity = moduleData.GetEntity(); + auto moduleEntityName = moduleEntity->GetName(); + if (moduleEntityName.contains("AWS")) + gems.push_back(moduleEntityName.substr(0, moduleEntityName.find_last_of("."))); + return true; + }); + } + + void AWSAttributionManager::UpdateMetric(AttributionMetric& metric) + { + AZStd::string engineVersion = this->GetEngineVersion(); + metric.SetO3DEVersion(engineVersion); + + AZStd::string platform = this->GetPlatform(); + metric.SetPlatform(platform, ""); + + AZStd::vector gemNames; + GetActiveAWSGems(gemNames); + for (AZStd::string& gemName : gemNames) + { + metric.AddActiveGem(gemName); + } + } + + void AWSAttributionManager::SubmitMetric(AttributionMetric& metric) + { + AWSCore::ServiceAPI::AWSAttributionRequestJob::Config* config = ServiceAPI::AWSAttributionRequestJob::GetDefaultConfig(); + SetApiEndpointAndRegion(config); + + ServiceAPI::AWSAttributionRequestJob* requestJob = ServiceAPI::AWSAttributionRequestJob::Create( + [this](ServiceAPI::AWSAttributionRequestJob* successJob) + { + AZ_UNUSED(successJob); + + UpdateLastSend(); + AZ_Printf("AWSAttributionManager", "AWSAttribution metric submit success"); + + }, {}, config); + + requestJob->parameters.metric = metric; + requestJob->Start(); + } + +} // namespace AWSCore diff --git a/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionMetric.cpp b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionMetric.cpp new file mode 100644 index 0000000000..6ad322995e --- /dev/null +++ b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionMetric.cpp @@ -0,0 +1,106 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include +#include +#include +#include + +#pragma warning(disable : 4996) + +namespace AWSCore +{ + AttributionMetric::AttributionMetric(const AZStd::string& timestamp) + : m_version("1.1") + , m_timestamp(timestamp) + { + } + + AttributionMetric::AttributionMetric() + : m_version("1.1") + { + m_timestamp = AttributionMetric::GenerateTimeStamp(); + } + + void AttributionMetric::SetO3DEVersion(const AZStd::string& version) + { + m_o3deVersion = version; + } + + void AttributionMetric::SetPlatform(const AZStd::string& platform, const AZStd::string& platformVersion) + { + m_platform = platform; + m_platformVersion = platformVersion; + } + + void AttributionMetric::AddActiveGem(const AZStd::string& gemName) + { + m_activeAWSGems.push_back(gemName); + } + + AZStd::string AttributionMetric::SerializeToJson() + { + std::stringstream stringStream; + AWSCore::JsonOutputStream jsonStream{stringStream}; + AWSCore::JsonWriter writer{jsonStream}; + + SerializeToJson(writer); + + return stringStream.str().c_str(); + } + + bool AttributionMetric::SerializeToJson(AWSCore::JsonWriter& writer) const + { + bool ok = true; + ok = ok && writer.StartObject(); + + writer.Write(AwsAttributionAttributeKeyVersion, m_version.c_str()); + writer.Write(AwsAttributionAttributeKeyO3DEVersion, m_o3deVersion.c_str()); + writer.Write(AwsAttributionAttributeKeyPlatform, m_platform.c_str()); + writer.Write(AwsAttributionAttributeKeyPlatformVersion, m_platformVersion.c_str()); + + if (m_activeAWSGems.size() > 0) + { + writer.Key(AwsAttributionAttributeKeyActiveAWSGems); + writer.StartArray(); // to store Array of objects + for (auto& iter : m_activeAWSGems) + { + writer.String(iter.c_str()); + } + writer.EndArray(); + } + + writer.Write(AwsAttributionAttributeKeyTimestamp, m_timestamp.c_str()); + + ok = ok && writer.EndObject(); + return ok; + } + + bool AttributionMetric::ReadFromJson(rapidjson::Value& metricsObjVal) + { + AZ_UNUSED(metricsObjVal); + return false; + } + + AZStd::string AttributionMetric::GenerateTimeStamp() + { + // Timestamp format is using the UTC ISO8601 format + // TODO: Move to a general util as Metrics has similar requirement + time_t now; + time(&now); + char buffer[50]; + strftime(buffer, sizeof(buffer), "%FT%TZ", gmtime(&now)); + + return buffer; + } + +} // namespace AWSCore diff --git a/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionSystemComponent.cpp b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionSystemComponent.cpp new file mode 100644 index 0000000000..ea388972d3 --- /dev/null +++ b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionSystemComponent.cpp @@ -0,0 +1,81 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace AWSCore +{ + + AWSAttributionSystemComponent::AWSAttributionSystemComponent() + : m_manager(AZStd::make_unique()) + { + } + + void AWSAttributionSystemComponent::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serialize = azrtti_cast(context)) + { + serialize->Class()->Version(0); + if (AZ::EditContext* ec = serialize->GetEditContext()) + { + ec->Class("AWSCoreAttributions", "Generates operation metrics for AWSCore gem") + ->ClassElement(AZ::Edit::ClassElements::EditorData, ""); + } + } + } + + void AWSAttributionSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC_CE("AWSCoreAttributionService")); + } + + void AWSAttributionSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("AWSCoreAttributionService")); + } + + void AWSAttributionSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + required.push_back(AZ_CRC_CE("AWSCoreService")); + } + + void AWSAttributionSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + AZ_UNUSED(dependent); + } + + void AWSAttributionSystemComponent::Init() + { + // load config if required - ie check if attributions should be generated and pass to manager + m_manager->Init(); + } + + void AWSAttributionSystemComponent::Activate() + { + m_manager->MetricCheck(); + } + + void AWSAttributionSystemComponent::Deactivate() + { + m_manager.reset(); + } + +} // namespace AWSCore + diff --git a/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSAttributionServiceApiTest.cpp b/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSAttributionServiceApiTest.cpp new file mode 100644 index 0000000000..affa1ad69c --- /dev/null +++ b/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSAttributionServiceApiTest.cpp @@ -0,0 +1,85 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include +#include + +#include + +using namespace AWSCore; + +namespace AWSCoreUnitTest +{ + class JsonReaderMock + : public AWSCore::JsonReader + { + public: + MOCK_METHOD0(Ignore, bool()); + MOCK_METHOD1(Accept, bool(bool& target)); + MOCK_METHOD1(Accept, bool(AZStd::string& target)); + MOCK_METHOD1(Accept, bool(int& target)); + MOCK_METHOD1(Accept, bool(unsigned& target)); + MOCK_METHOD1(Accept, bool(int64_t& target)); + MOCK_METHOD1(Accept, bool(uint64_t& target)); + MOCK_METHOD1(Accept, bool(double& target)); + MOCK_METHOD1(Accept, bool(AWSCore::JsonKeyHandler keyHandler)); + MOCK_METHOD1(Accept, bool(AWSCore::JsonArrayHandler arrayHandler)); + }; + + class AWSAttributionServiceApiTest + : public UnitTest::ScopedAllocatorSetupFixture + { + public: + testing::NiceMock JsonReader; + }; + + TEST_F(AWSAttributionServiceApiTest, AWSAtrributionSuccessResponse_Serialization) + { + ServiceAPI::AWSAtrributionSuccessResponse response; + response.result = "ok"; + + EXPECT_CALL(JsonReader, Accept(response.result)).Times(1); + EXPECT_CALL(JsonReader, Ignore()).Times(0); + + response.OnJsonKey("statusCode", JsonReader); + } + + TEST_F(AWSAttributionServiceApiTest, AWSAtrributionSuccessResponse_Serialization_Ignore) + { + ServiceAPI::AWSAtrributionSuccessResponse response; + response.result = "ok"; + + EXPECT_CALL(JsonReader, Accept(response.result)).Times(0); + EXPECT_CALL(JsonReader, Ignore()).Times(1); + + response.OnJsonKey("", JsonReader); + } + + TEST_F(AWSAttributionServiceApiTest, BuildRequestBody_PostProducerEventsRequest_SerializedMetricsQueue) + { + ServiceAPI::AWSAttributionRequest request; + request.parameters.metric = AttributionMetric(); + + AWSCore::RequestBuilder requestBuilder{}; + EXPECT_TRUE(request.parameters.BuildRequest(requestBuilder)); + std::shared_ptr bodyContent = requestBuilder.GetBodyContent(); + EXPECT_TRUE(bodyContent != nullptr); + + AZStd::string bodyString; + std::istreambuf_iterator eos; + bodyString = AZStd::string{ std::istreambuf_iterator(*bodyContent), eos }; + AZ_Printf("AWSAttributionServiceApiTest", bodyString.c_str()); + EXPECT_TRUE(bodyString.find(AZStd::string::format("{\"%s\":\"1.1\"", AwsAttributionAttributeKeyVersion)) != AZStd::string::npos); + } +} diff --git a/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionManagerTest.cpp b/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionManagerTest.cpp new file mode 100644 index 0000000000..298c250086 --- /dev/null +++ b/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionManagerTest.cpp @@ -0,0 +1,414 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + + +using namespace AWSCore; + +namespace AWSAttributionUnitTest +{ + class ModuleDataMock: + public AZ::ModuleData + { + public: + AZStd::shared_ptr m_entity; + ModuleDataMock(AZStd::string name) + { + m_entity = AZStd::make_shared(); + m_entity->SetName(name); + } + virtual ~ModuleDataMock() + { + m_entity.reset(); + } + + AZ::DynamicModuleHandle* GetDynamicModuleHandle() const override + { + return nullptr; + } + /// Get the handle to the module class + AZ::Module* GetModule() const override + { + return nullptr; + } + /// Get the entity this module uses as a System Entity + AZ::Entity* GetEntity() const override + { + return m_entity.get(); + } + /// Get the debug name of the module + const char* GetDebugName() const override + { + return m_entity->GetName().c_str(); + } + }; + + class ModuleManagerRequestBusMock + : public AZ::ModuleManagerRequestBus::Handler + { + public: + + void EnumerateModulesMock(AZ::ModuleManagerRequests::EnumerateModulesCallback perModuleCallback) + { + auto data = ModuleDataMock("AWSCore.Editor.dll"); + perModuleCallback(data); + data = ModuleDataMock("AWSClientAuth.so"); + perModuleCallback(data); + } + + ModuleManagerRequestBusMock() + { + AZ::ModuleManagerRequestBus::Handler::BusConnect(); + ON_CALL(*this, EnumerateModules(testing::_)).WillByDefault(testing::Invoke(this, &ModuleManagerRequestBusMock::EnumerateModulesMock)); + } + + ~ModuleManagerRequestBusMock() + { + AZ::ModuleManagerRequestBus::Handler::BusDisconnect(); + } + + MOCK_METHOD1(EnumerateModules, void(AZ::ModuleManagerRequests::EnumerateModulesCallback perModuleCallback)); + MOCK_METHOD3(LoadDynamicModule, AZ::ModuleManagerRequests::LoadModuleOutcome(const char* modulePath, AZ::ModuleInitializationSteps lastStepToPerform, bool maintainReference)); + MOCK_METHOD3(LoadDynamicModules, AZ::ModuleManagerRequests::LoadModulesResult(const AZ::ModuleDescriptorList& modules, AZ::ModuleInitializationSteps lastStepToPerform, bool maintainReferences)); + MOCK_METHOD2(LoadStaticModules, AZ::ModuleManagerRequests::LoadModulesResult(AZ::CreateStaticModulesCallback staticModulesCb, AZ::ModuleInitializationSteps lastStepToPerform)); + MOCK_METHOD1(IsModuleLoaded, bool(const char* modulePath)); + }; + + class AWSAttributionManagerMock + : public AWSAttributionManager + { + public: + using AWSAttributionManager::SubmitMetric; + using AWSAttributionManager::UpdateMetric; + using AWSAttributionManager::SetApiEndpointAndRegion; + + + AWSAttributionManagerMock() + { + ON_CALL(*this, SubmitMetric(testing::_)).WillByDefault(testing::Invoke(this, &AWSAttributionManagerMock::SubmitMetricMock)); + } + + MOCK_METHOD1(SubmitMetric, void(AttributionMetric& metric)); + + void SubmitMetricMock(AttributionMetric& metric) + { + AZ_UNUSED(metric); + UpdateLastSend(); + } + }; + + class AttributionManagerTest + : public AWSCoreFixture + { + public: + + virtual ~AttributionManagerTest() = default; + + protected: + AZStd::shared_ptr m_serializeContext; + AZStd::unique_ptr m_registrationContext; + AZStd::shared_ptr m_settingsRegistry; + AZStd::unique_ptr m_jobContext; + AZStd::unique_ptr m_jobCancelGroup; + AZStd::unique_ptr m_jobManager; + AZStd::array m_resolvedSettingsPath; + ModuleManagerRequestBusMock m_moduleManagerRequestBusMock; + + void SetUp() override + { + AWSCoreFixture::SetUp(); + + char rootPath[AZ_MAX_PATH_LEN]; + AZ::Utils::GetExecutableDirectory(rootPath, AZ_MAX_PATH_LEN); + m_localFileIO->SetAlias("@user@", AZ_TRAIT_TEST_ROOT_FOLDER); + + m_localFileIO->ResolvePath("@user@/Registry/", m_resolvedSettingsPath.data(), m_resolvedSettingsPath.size()); + AZ::IO::SystemFile::CreateDir(m_resolvedSettingsPath.data()); + + m_localFileIO->ResolvePath("@user@/Registry/editor_aws_preferences.setreg", m_resolvedSettingsPath.data(), m_resolvedSettingsPath.size()); + + m_serializeContext = AZStd::make_unique(); + + AZ::JsonSystemComponent::Reflect(m_registrationContext.get()); + + m_settingsRegistry = AZStd::make_unique(); + + m_settingsRegistry->SetContext(m_serializeContext.get()); + m_settingsRegistry->SetContext(m_registrationContext.get()); + + AZ::SettingsRegistry::Register(m_settingsRegistry.get()); + + AZ::JobManagerDesc jobManagerDesc; + AZ::JobManagerThreadDesc threadDesc; + + m_jobManager.reset(aznew AZ::JobManager(jobManagerDesc)); + m_jobCancelGroup.reset(aznew AZ::JobCancelGroup()); + jobManagerDesc.m_workerThreads.push_back(threadDesc); + m_jobContext.reset(aznew AZ::JobContext(*m_jobManager, *m_jobCancelGroup)); + AZ::JobContext::SetGlobalContext(m_jobContext.get()); + } + + void TearDown() override + { + AZ::JobContext::SetGlobalContext(nullptr); + m_jobContext.reset(); + m_jobCancelGroup.reset(); + m_jobManager.reset(); + + AZ::SettingsRegistry::Unregister(m_settingsRegistry.get()); + + m_settingsRegistry.reset(); + m_serializeContext.reset(); + m_registrationContext.reset(); + + m_localFileIO->ResolvePath("@user@/Registry/", m_resolvedSettingsPath.data(), m_resolvedSettingsPath.size()); + AZ::IO::SystemFile::DeleteDir(m_resolvedSettingsPath.data()); + + delete AZ::IO::FileIOBase::GetInstance(); + AZ::IO::FileIOBase::SetInstance(nullptr); + + AWSCoreFixture::TearDown(); + } + }; + + TEST_F(AttributionManagerTest, MetricsSettings_AttributionDisabled_SkipsSend) + { + // GIVEN + AWSAttributionManagerMock manager; + manager.Init(); + + CreateFile(m_resolvedSettingsPath.data(), R"({ + "Amazon": { + "AWS": { + "Preferences": { + "AWSAttributionEnabled": false, + "AWSAttributionDelaySeconds": 30 + } + } + } + })"); + + EXPECT_CALL(manager, SubmitMetric(testing::_)).Times(0); + EXPECT_CALL(m_moduleManagerRequestBusMock, EnumerateModules(testing::_)).Times(0); + + // WHEN + manager.MetricCheck(); + + // THEN + m_settingsRegistry->MergeSettingsFile(m_resolvedSettingsPath.data(), AZ::SettingsRegistryInterface::Format::JsonMergePatch, ""); + AZ::u64 timeStamp = 0; + m_settingsRegistry->Get(timeStamp, "/Amazon/AWS/Preferences/AWSAttributionLastTimeStamp"); + ASSERT_TRUE(timeStamp == 0); + + RemoveFile(m_resolvedSettingsPath.data()); + } + + TEST_F(AttributionManagerTest, AttributionEnabled_NoPreviousTimeStamp_SendSuccess) + { + // GIVEN + AWSAttributionManagerMock manager; + manager.Init(); + + CreateFile(m_resolvedSettingsPath.data(), R"({ + "Amazon": { + "AWS": { + "Preferences": { + "AWSAttributionEnabled": true, + "AWSAttributionDelaySeconds": 30, + } + } + } + })"); + + EXPECT_CALL(manager, SubmitMetric(testing::_)).Times(1); + EXPECT_CALL(m_moduleManagerRequestBusMock, EnumerateModules(testing::_)).Times(1); + + // WHEN + manager.MetricCheck(); + + // THEN + m_settingsRegistry->MergeSettingsFile(m_resolvedSettingsPath.data(), AZ::SettingsRegistryInterface::Format::JsonMergePatch, ""); + AZ::u64 timeStamp = 0; + m_settingsRegistry->Get(timeStamp, "/Amazon/AWS/Preferences/AWSAttributionLastTimeStamp"); + ASSERT_TRUE(timeStamp > 0); + + + RemoveFile(m_resolvedSettingsPath.data()); + } + + TEST_F(AttributionManagerTest, AttributionEnabled_ValidPreviousTimeStamp_SendSuccess) + { + // GIVEN + AWSAttributionManagerMock manager; + manager.Init(); + + CreateFile(m_resolvedSettingsPath.data(), R"({ + "Amazon": { + "AWS": { + "Preferences": { + "AWSAttributionEnabled": true, + "AWSAttributionDelaySeconds": 30, + "AWSAttributionLastTimeStamp": 629400 + } + } + } + })"); + + EXPECT_CALL(manager, SubmitMetric(testing::_)).Times(1); + EXPECT_CALL(m_moduleManagerRequestBusMock, EnumerateModules(testing::_)).Times(1); + + // WHEN + manager.MetricCheck(); + + // THEN + m_settingsRegistry->MergeSettingsFile(m_resolvedSettingsPath.data(), AZ::SettingsRegistryInterface::Format::JsonMergePatch, ""); + AZ::u64 timeStamp = 0; + m_settingsRegistry->Get(timeStamp, "/Amazon/AWS/Preferences/AWSAttributionLastTimeStamp"); + ASSERT_TRUE(timeStamp > 0); + + RemoveFile(m_resolvedSettingsPath.data()); + } + + TEST_F(AttributionManagerTest, AttributionEnabled_DelayNotSatisfied_SendFail) + { + // GIVEN + AWSAttributionManagerMock manager; + manager.Init(); + + + CreateFile(m_resolvedSettingsPath.data(), R"({ + "Amazon": { + "AWS": { + "Preferences": { + "AWSAttributionEnabled": true, + "AWSAttributionDelaySeconds": 300, + "AWSAttributionLastTimeStamp": 0 + } + } + } + })"); + + AZ::u64 delayInSeconds = AZStd::chrono::duration_cast(AZStd::chrono::system_clock::now().time_since_epoch()).count(); + ASSERT_TRUE(m_settingsRegistry->Set("/Amazon/AWS/Preferences/AWSAttributionLastTimeStamp", delayInSeconds)); + + EXPECT_CALL(manager, SubmitMetric(testing::_)).Times(1); + EXPECT_CALL(m_moduleManagerRequestBusMock, EnumerateModules(testing::_)).Times(1); + + // WHEN + manager.MetricCheck(); + + // THEN + m_settingsRegistry->MergeSettingsFile(m_resolvedSettingsPath.data(), AZ::SettingsRegistryInterface::Format::JsonMergePatch, ""); + AZ::u64 timeStamp = 0; + m_settingsRegistry->Get(timeStamp, "/Amazon/AWS/Preferences/AWSAttributionLastTimeStamp"); + ASSERT_TRUE(timeStamp == delayInSeconds); + + RemoveFile(m_resolvedSettingsPath.data()); + } + + TEST_F(AttributionManagerTest, AttributionEnabledNotFound_SendSuccess) + { + // GIVEN + AWSAttributionManagerMock manager; + manager.Init(); + + CreateFile(m_resolvedSettingsPath.data(), R"({ + "Amazon": { + "AWS": { + "Preferences": { + } + } + } + })"); + + EXPECT_CALL(manager, SubmitMetric(testing::_)).Times(1); + EXPECT_CALL(m_moduleManagerRequestBusMock, EnumerateModules(testing::_)).Times(1); + + // WHEN + manager.MetricCheck(); + + // THEN + m_settingsRegistry->MergeSettingsFile(m_resolvedSettingsPath.data(), AZ::SettingsRegistryInterface::Format::JsonMergePatch, ""); + AZ::u64 timeStamp = 0; + m_settingsRegistry->Get(timeStamp, "/Amazon/AWS/Preferences/AWSAttributionLastTimeStamp"); + ASSERT_TRUE(timeStamp != 0); + + RemoveFile(m_resolvedSettingsPath.data()); + } + + TEST_F(AttributionManagerTest, SetApiEndpointAndRegion_Success) + { + // GIVEN + AWSAttributionManagerMock manager; + AWSCore::ServiceAPI::AWSAttributionRequestJob::Config* config = aznew AWSCore::ServiceAPI::AWSAttributionRequestJob::Config(); + + // WHEN + manager.SetApiEndpointAndRegion(config); + + // THEN + ASSERT_TRUE(config->region == Aws::Region::US_WEST_2); + ASSERT_TRUE(config->endpointOverride->find("execute-api.us-west-2.amazonaws.com") != Aws::String::npos); + + delete config; + } + + TEST_F(AttributionManagerTest, UpdateMetric_Success) + { + // GIVEN + AWSAttributionManagerMock manager; + AttributionMetric metric; + + AZStd::array engineJsonPath; + m_localFileIO->ResolvePath("@user@/Registry/engine.json", engineJsonPath.data(), engineJsonPath.size()); + CreateFile(engineJsonPath.data(), R"({"O3DEVersion": "1.0.0.0"})"); + + m_localFileIO->ResolvePath("@user@/Registry/", engineJsonPath.data(), engineJsonPath.size()); + m_settingsRegistry->Set(AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder, engineJsonPath.data()); + + EXPECT_CALL(m_moduleManagerRequestBusMock, EnumerateModules(testing::_)).Times(1); + + // WHEN + manager.UpdateMetric(metric); + + // THEN + AZStd::string serializedMetricValue = metric.SerializeToJson(); + ASSERT_TRUE(serializedMetricValue.find("\"o3de_version\":\"1.0.0.0\"") != AZStd::string::npos); + ASSERT_TRUE(serializedMetricValue.find(AZ::GetPlatformName(AZ::g_currentPlatform)) != AZStd::string::npos); + ASSERT_TRUE(serializedMetricValue.find("AWSCore.Editor") != AZStd::string::npos); + ASSERT_TRUE(serializedMetricValue.find("AWSClientAuth") != AZStd::string::npos); + + RemoveFile(engineJsonPath.data()); + } + +} // namespace AWSCoreUnitTest diff --git a/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionMetricTest.cpp b/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionMetricTest.cpp new file mode 100644 index 0000000000..c93b8bb08e --- /dev/null +++ b/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionMetricTest.cpp @@ -0,0 +1,50 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include + +#include + +namespace AWSCore +{ + using AttributionMetricTest = UnitTest::ScopedAllocatorSetupFixture; + + TEST_F(AttributionMetricTest, Contruction_Test) + { + AZStd::string timestamp = AttributionMetric::GenerateTimeStamp(); + AttributionMetric metric(timestamp); + + AZStd::string serializedMetric = AZStd::string::format( + "{\"version\":\"1.1\",\"o3de_version\":\"\",\"platform\":\"\",\"platform_version\":\"\",\"timestamp\":\"%s\"}", timestamp.c_str()); + ASSERT_EQ(metric.SerializeToJson(), serializedMetric); + } + + TEST_F(AttributionMetricTest, AddActiveGems) + { + AZStd::string timestamp = AttributionMetric::GenerateTimeStamp(); + AttributionMetric metric(timestamp); + + AZStd::string gem1 = "AWSGem1"; + AZStd::string gem2 = "AWSGem2"; + + metric.AddActiveGem(gem1); + metric.AddActiveGem(gem2); + + AZStd::string serializedMetric = AZStd::string::format( + "{\"version\":\"1.1\",\"o3de_version\":\"\",\"platform\":\"\",\"platform_version\":\"\",\"aws_gems\":[\"%s\",\"%s\"],\"timestamp\":\"%s\"}", + gem1.c_str(), gem2.c_str(), timestamp.c_str()); + + AZStd::string actualValue = metric.SerializeToJson(); + ASSERT_EQ(actualValue, serializedMetric); + } + +} // namespace AWSCore diff --git a/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionSystemComponentTest.cpp b/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionSystemComponentTest.cpp new file mode 100644 index 0000000000..4419c78467 --- /dev/null +++ b/Gems/AWSCore/Code/Tests/Editor/Attribution/AWSCoreAttributionSystemComponentTest.cpp @@ -0,0 +1,132 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace AWSCore; + +namespace AWSCoreUnitTest +{ + class AWSCoreSystemComponentMock : public AZ::Component + { + public: + AZ_COMPONENT(AWSCoreSystemComponentMock, "{5F48030D-EB59-4820-BC65-69EC7CC6C119}"); + + static void Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serialize = azrtti_cast(context)) + { + serialize->Class()->Version(0); + + if (AZ::EditContext* ec = serialize->GetEditContext()) + { + ec->Class("AWSCoreMock", "Adds core support for working with AWS") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System")) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true); + } + } + } + + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC_CE("AWSCoreService")); + } + + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + AZ_UNUSED(incompatible); + } + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + AZ_UNUSED(required); + } + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + AZ_UNUSED(dependent); + } + + ~AWSCoreSystemComponentMock() = default; + + MOCK_METHOD0(Init, void()); + MOCK_METHOD0(Activate, void()); + MOCK_METHOD0(Deactivate, void()); + }; + + class AWSAttributionSystemComponentTest : public AWSCoreFixture + { + void SetUp() override + { + AWSCoreFixture::SetUp(); + m_serializeContext = AZStd::make_unique(); + m_serializeContext->CreateEditContext(); + m_behaviorContext = AZStd::make_unique(); + + m_awsCoreComponentDescriptor.reset(AWSCoreSystemComponentMock::CreateDescriptor()); + m_awsCoreComponentDescriptor->Reflect(m_serializeContext.get()); + m_awsCoreComponentDescriptor->Reflect(m_behaviorContext.get()); + + m_componentDescriptor.reset(AWSAttributionSystemComponent::CreateDescriptor()); + m_componentDescriptor->Reflect(m_serializeContext.get()); + m_componentDescriptor->Reflect(m_behaviorContext.get()); + + m_entity = aznew AZ::Entity(); + m_awsCoreSystemComponentMock = aznew testing::NiceMock(); + m_entity->AddComponent(m_awsCoreSystemComponentMock); + m_attributionSystemsComponent.reset(m_entity->CreateComponent()); + } + + void TearDown() override + { + m_entity->Deactivate(); + m_entity->RemoveComponent(m_attributionSystemsComponent.get()); + m_entity->RemoveComponent(m_awsCoreSystemComponentMock); + delete m_entity; + m_entity = nullptr; + + m_attributionSystemsComponent.reset(); + delete m_awsCoreSystemComponentMock; + m_awsCoreComponentDescriptor.reset(); + m_componentDescriptor.reset(); + m_behaviorContext.reset(); + m_serializeContext.reset(); + AWSCoreFixture::TearDown(); + } + + public: + AZStd::unique_ptr m_attributionSystemsComponent; + testing::NiceMock* m_awsCoreSystemComponentMock; + AZ::Entity* m_entity; + + private: + AZStd::unique_ptr m_serializeContext; + AZStd::unique_ptr m_behaviorContext; + AZStd::unique_ptr m_componentDescriptor; + AZStd::unique_ptr m_awsCoreComponentDescriptor; + }; + + TEST_F(AWSAttributionSystemComponentTest, SystemComponentInitActivate_Success) + { + m_entity->Init(); + m_entity->Activate(); + } +} + + diff --git a/Gems/AWSCore/Code/Tests/TestFramework/AWSCoreFixture.h b/Gems/AWSCore/Code/Tests/TestFramework/AWSCoreFixture.h index 1810af9c82..d921ffaf07 100644 --- a/Gems/AWSCore/Code/Tests/TestFramework/AWSCoreFixture.h +++ b/Gems/AWSCore/Code/Tests/TestFramework/AWSCoreFixture.h @@ -127,13 +127,40 @@ public: void TearDown() override { AZ::IO::FileIOBase::SetInstance(nullptr); - delete m_localFileIO; - AZ::IO::FileIOBase::SetInstance(m_otherFileIO); + + if (m_otherFileIO) + { + delete m_localFileIO; + AZ::IO::FileIOBase::SetInstance(m_otherFileIO); + } AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); } + bool CreateFile(const AZStd::string& filePath, const AZStd::string& content) + { + AZ::IO::HandleType fileHandle; + if (!m_localFileIO->Open(filePath.c_str(), AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeText, fileHandle)) + { + return false; + } + + m_localFileIO->Write(fileHandle, content.c_str(), content.size()); + m_localFileIO->Close(fileHandle); + return true; + } + + bool RemoveFile(const AZStd::string& filePath) + { + if (m_localFileIO->Exists(filePath.c_str())) + { + return m_localFileIO->Remove(filePath.c_str()); + } + + return true; + } + AZ::IO::FileIOBase* m_localFileIO = nullptr; private: diff --git a/Gems/AWSCore/Code/awscore_editor_files.cmake b/Gems/AWSCore/Code/awscore_editor_files.cmake index 13bfbb6102..6e16fc7d27 100644 --- a/Gems/AWSCore/Code/awscore_editor_files.cmake +++ b/Gems/AWSCore/Code/awscore_editor_files.cmake @@ -11,6 +11,11 @@ set(FILES Include/Private/AWSCoreEditorSystemComponent.h + Include/Private/Editor/Attribution/AWSCoreAttributionConstant.h + Include/Private/Editor/Attribution/AWSCoreAttributionMetric.h + Include/Private/Editor/Attribution/AWSCoreAttributionManager.h + Include/Private/Editor/Attribution/AWSCoreAttributionSystemComponent.h + Include/Private/Editor/Attribution/AWSAttributionServiceApi.h Include/Private/Editor/AWSCoreEditorManager.h Include/Private/Editor/Constants/AWSCoreEditorMenuLinks.h Include/Private/Editor/Constants/AWSCoreEditorMenuNames.h @@ -18,6 +23,10 @@ set(FILES Include/Private/Editor/UI/AWSCoreResourceMappingToolAction.h Source/AWSCoreEditorSystemComponent.cpp Source/Editor/AWSCoreEditorManager.cpp + Source/Editor/Attribution/AWSCoreAttributionMetric.cpp + Source/Editor/Attribution/AWSCoreAttributionManager.cpp + Source/Editor/Attribution/AWSCoreAttributionSystemComponent.cpp + Source/Editor/Attribution/AWSAttributionServiceApi.cpp Source/Editor/UI/AWSCoreEditorMenu.cpp Source/Editor/UI/AWSCoreResourceMappingToolAction.cpp ) diff --git a/Gems/AWSCore/Code/awscore_editor_tests_files.cmake b/Gems/AWSCore/Code/awscore_editor_tests_files.cmake index ff89b6b5bd..bba830d5d1 100644 --- a/Gems/AWSCore/Code/awscore_editor_tests_files.cmake +++ b/Gems/AWSCore/Code/awscore_editor_tests_files.cmake @@ -11,6 +11,10 @@ set(FILES Tests/AWSCoreEditorSystemComponentTest.cpp + Tests/Editor/Attribution/AWSCoreAttributionManagerTest.cpp + Tests/Editor/Attribution/AWSCoreAttributionMetricTest.cpp + Tests/Editor/Attribution/AWSCoreAttributionSystemComponentTest.cpp + Tests/Editor/Attribution/AWSAttributionServiceApiTest.cpp Tests/Editor/UI/AWSCoreEditorMenuTest.cpp Tests/Editor/UI/AWSCoreEditorUIFixture.h Tests/Editor/UI/AWSCoreResourceMappingToolActionTest.cpp From aeaf1bcdbe6768ba0f4ef3e7afd603a899d3474c Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Fri, 4 Jun 2021 21:29:36 -0700 Subject: [PATCH 547/811] Fix engine settings not populating or saving * Allow multiple settings to be registered at once * Old manifests versions may not have default_third_party_folder --- .../ProjectManager/Source/PythonBindings.cpp | 4 +- scripts/o3de/o3de/register.py | 50 +++++++++---------- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 5f4bb833d8..d7d0414c1f 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -384,7 +384,9 @@ namespace O3DE::ProjectManager engineInfo.m_defaultProjectsFolder = Py_To_String(o3deData["default_projects_folder"]); engineInfo.m_defaultRestrictedFolder = Py_To_String(o3deData["default_restricted_folder"]); engineInfo.m_defaultTemplatesFolder = Py_To_String(o3deData["default_templates_folder"]); - engineInfo.m_thirdPartyPath = Py_To_String(o3deData["default_third_party_folder"]); + + pybind11::str defaultThirdPartyFolder = m_manifest.attr("get_o3de_third_party_folder")(); + engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData,"default_third_party_folder", Py_To_String(defaultThirdPartyFolder)); } auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath); diff --git a/scripts/o3de/o3de/register.py b/scripts/o3de/o3de/register.py index 4e73edca7f..b3a6a1e44c 100644 --- a/scripts/o3de/o3de/register.py +++ b/scripts/o3de/o3de/register.py @@ -580,65 +580,65 @@ def register(engine_path: str or pathlib.Path = None, if not project_path: logger.error(f'Project path cannot be empty.') return 1 - result = register_project_path(json_data, project_path, remove, engine_path) + result = result or register_project_path(json_data, project_path, remove, engine_path) - elif isinstance(gem_path, str) or isinstance(gem_path, pathlib.PurePath): + if isinstance(gem_path, str) or isinstance(gem_path, pathlib.PurePath): if not gem_path: logger.error(f'Gem path cannot be empty.') return 1 - result = register_gem_path(json_data, gem_path, remove, + result = result or register_gem_path(json_data, gem_path, remove, external_subdir_engine_path, external_subdir_project_path) - elif isinstance(external_subdir_path, str) or isinstance(external_subdir_path, pathlib.PurePath): + if isinstance(external_subdir_path, str) or isinstance(external_subdir_path, pathlib.PurePath): if not external_subdir_path: logger.error(f'External Subdirectory path is None.') return 1 - result = register_external_subdirectory(json_data, external_subdir_path, remove, + result = result or register_external_subdirectory(json_data, external_subdir_path, remove, external_subdir_engine_path, external_subdir_project_path) - elif isinstance(template_path, str) or isinstance(template_path, pathlib.PurePath): + if isinstance(template_path, str) or isinstance(template_path, pathlib.PurePath): if not template_path: logger.error(f'Template path cannot be empty.') return 1 - result = register_template_path(json_data, template_path, remove, engine_path) + result = result or register_template_path(json_data, template_path, remove, engine_path) - elif isinstance(restricted_path, str) or isinstance(restricted_path, pathlib.PurePath): + if isinstance(restricted_path, str) or isinstance(restricted_path, pathlib.PurePath): if not restricted_path: logger.error(f'Restricted path cannot be empty.') return 1 - result = register_restricted_path(json_data, restricted_path, remove, engine_path) + result = result or register_restricted_path(json_data, restricted_path, remove, engine_path) - elif isinstance(repo_uri, str) or isinstance(repo_uri, pathlib.PurePath): + if isinstance(repo_uri, str) or isinstance(repo_uri, pathlib.PurePath): if not repo_uri: logger.error(f'Repo URI cannot be empty.') return 1 - result = register_repo(json_data, repo_uri, remove) + result = result or register_repo(json_data, repo_uri, remove) - elif isinstance(default_engines_folder, str) or isinstance(default_engines_folder, pathlib.PurePath): - result = register_default_engines_folder(json_data, default_engines_folder, remove) + if isinstance(default_engines_folder, str) or isinstance(default_engines_folder, pathlib.PurePath): + result = result or register_default_engines_folder(json_data, default_engines_folder, remove) - elif isinstance(default_projects_folder, str) or isinstance(default_projects_folder, pathlib.PurePath): - result = register_default_projects_folder(json_data, default_projects_folder, remove) + if isinstance(default_projects_folder, str) or isinstance(default_projects_folder, pathlib.PurePath): + result = result or register_default_projects_folder(json_data, default_projects_folder, remove) - elif isinstance(default_gems_folder, str) or isinstance(default_gems_folder, pathlib.PurePath): - result = register_default_gems_folder(json_data, default_gems_folder, remove) + if isinstance(default_gems_folder, str) or isinstance(default_gems_folder, pathlib.PurePath): + result = result or register_default_gems_folder(json_data, default_gems_folder, remove) - elif isinstance(default_templates_folder, str) or isinstance(default_templates_folder, pathlib.PurePath): - result = register_default_templates_folder(json_data, default_templates_folder, remove) + if isinstance(default_templates_folder, str) or isinstance(default_templates_folder, pathlib.PurePath): + result = result or register_default_templates_folder(json_data, default_templates_folder, remove) - elif isinstance(default_restricted_folder, str) or isinstance(default_restricted_folder, pathlib.PurePath): - result = register_default_restricted_folder(json_data, default_restricted_folder, remove) + if isinstance(default_restricted_folder, str) or isinstance(default_restricted_folder, pathlib.PurePath): + result = result or register_default_restricted_folder(json_data, default_restricted_folder, remove) - elif default_third_party_folder: - result = register_default_third_party_folder(json_data, default_third_party_folder, remove) + if isinstance(default_third_party_folder, str) or isinstance(default_third_party_folder, pathlib.PurePath): + result = result or register_default_third_party_folder(json_data, default_third_party_folder, remove) # engine is done LAST # Now that everything that could have an engine context is done, if the engine is supplied that means this is # registering the engine itself - elif isinstance(engine_path, str) or isinstance(engine_path, pathlib.PurePath): + if isinstance(engine_path, str) or isinstance(engine_path, pathlib.PurePath): if not engine_path: logger.error(f'Engine path cannot be empty.') return 1 - result = register_engine_path(json_data, engine_path, remove, force) + result = result or register_engine_path(json_data, engine_path, remove, force) if not result: manifest.save_o3de_manifest(json_data) From ed759612dd198ae463c6af0b8b6b92ba2c51c563 Mon Sep 17 00:00:00 2001 From: antonmic Date: Sat, 5 Jun 2021 19:12:45 -0700 Subject: [PATCH 548/811] Atom Pass changes WIP: ASV screenshot tests passing now --- .../Common/Code/Source/ImGui/ImGuiPass.cpp | 4 +- .../Common/Code/Source/ImGui/ImGuiPass.h | 2 +- .../Code/Source/PostProcessing/SsaoPasses.cpp | 4 +- .../Code/Source/PostProcessing/SsaoPasses.h | 2 +- .../Atom/RPI.Public/Pass/AttachmentReadback.h | 2 +- .../Include/Atom/RPI.Public/Pass/ParentPass.h | 2 +- .../Code/Include/Atom/RPI.Public/Pass/Pass.h | 12 +- .../Atom/RPI.Public/Pass/PassDefines.h | 5 +- .../Include/Atom/RPI.Public/Pass/RenderPass.h | 2 +- .../RPI.Public/Pass/AttachmentReadback.cpp | 15 +- .../Source/RPI.Public/Pass/ParentPass.cpp | 12 +- .../RPI/Code/Source/RPI.Public/Pass/Pass.cpp | 228 ++++++++++++------ .../Source/RPI.Public/Pass/PassSystem.cpp | 28 ++- .../Source/RPI.Public/Pass/RenderPass.cpp | 2 +- 14 files changed, 208 insertions(+), 112 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp index fe5d9a16fe..750402ada8 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp @@ -519,13 +519,13 @@ namespace AZ io.Fonts->TexID = reinterpret_cast(m_fontAtlas.get()); } - void ImGuiPass::OnBuildFinishedInternal() + void ImGuiPass::InitializeInternal() { // Set output format and finalize pipeline state m_pipelineState->SetOutputFromPass(this); m_pipelineState->Finalize(); - Base::OnBuildFinishedInternal(); + Base::InitializeInternal(); } void ImGuiPass::SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) diff --git a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h index 30449820bb..f63b515536 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h @@ -94,7 +94,7 @@ namespace AZ explicit ImGuiPass(const RPI::PassDescriptor& descriptor); // Pass Behaviour Overrides... - void OnBuildFinishedInternal() override; + void InitializeInternal() override; void FrameBeginInternal(FramePrepareParams params) override; // Scope producer functions diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.cpp index 1aa16a4417..8954584886 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.cpp @@ -41,9 +41,9 @@ namespace AZ return ParentPass::IsEnabled(); } - void SsaoParentPass::OnBuildFinishedInternal() + void SsaoParentPass::InitializeInternal() { - ParentPass::OnBuildFinishedInternal(); + ParentPass::InitializeInternal(); m_blurParentPass = FindChildPass(Name("SsaoBlur"))->AsParent(); AZ_Assert(m_blurParentPass, "[SsaoParentPass] Could not retrieve parent blur pass."); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.h index 20aa554414..9fc5448f65 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SsaoPasses.h @@ -36,7 +36,7 @@ namespace AZ protected: // Behavior functions override... - void OnBuildFinishedInternal() override; + void InitializeInternal() override; void FrameBeginInternal(FramePrepareParams params) override; private: diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/AttachmentReadback.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/AttachmentReadback.h index 539e1a5398..3c00ce4e4c 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/AttachmentReadback.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/AttachmentReadback.h @@ -99,7 +99,7 @@ namespace AZ void DecomposeExecute(const RHI::FrameGraphExecuteContext& context); // copy data from the read back buffer (m_readbackBuffer) to the data buffer (m_dataBuffer) - void CopyBufferData(uint32_t readbackBufferIndex); + bool CopyBufferData(uint32_t readbackBufferIndex); // Get read back data in a structure ReadbackResult GetReadbackResult() const; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h index 0e1e12e620..ca7baf1a0f 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h @@ -110,7 +110,7 @@ namespace AZ void ResetInternal() override; void BuildInternal() override; - void OnBuildFinishedInternal() override; + void OnInitializationFinishedInternal() override; void InitializeInternal() override; void FrameBeginInternal(FramePrepareParams params) override; void FrameEndInternal() override; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h index b71016f30a..3cab5b36e4 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h @@ -320,12 +320,12 @@ namespace AZ // Builds and sets up any attachments and input/output connections the pass needs. // Called from PassSystem when pass is QueueForBuild. - void Build(); + void Build(bool calledFromPassSystem = false); virtual void BuildInternal() { } // Called after the pass build phase has finished. Allows passes to reset build flags. - void OnBuildFinished(); - virtual void OnBuildFinishedInternal() { }; + void OnInitializationFinished(); + virtual void OnInitializationFinishedInternal() { }; // Allows for additional pass initialization between building and rendering // Can be queued independently of Build so as to only invoke Initialize without Build @@ -395,6 +395,12 @@ namespace AZ uint64_t m_initialized : 1; uint64_t m_alreadyCreated : 1; + // OLD SCHOOL + uint64_t m_alreadyReset : 1; + uint64_t m_alreadyPrepared : 1; + uint64_t m_queuedForBuildAttachment : 1; + + uint64_t m_partOfHierarchy : 1; uint64_t m_hasDrawListTag : 1; uint64_t m_hasPipelineViewTag : 1; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassDefines.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassDefines.h index 7c55944603..7ba7f1be4e 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassDefines.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassDefines.h @@ -20,7 +20,7 @@ // Enables debugging of the pass system // Set this to 1 locally on your machine to facilitate pass debugging and get extra information // about passes in the output window. DO NOT SUBMIT with value set to 1 -#define AZ_RPI_ENABLE_PASS_DEBUGGING 0 +#define AZ_RPI_ENABLE_PASS_DEBUGGING 1 namespace AZ { @@ -31,9 +31,12 @@ namespace AZ Uninitialized, Queued, Resetting, + Reset, Building, + Built, Initializing, Initialized, + Idle, Rendering }; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RenderPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RenderPass.h index 5f222d8bba..8f8267393e 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RenderPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RenderPass.h @@ -96,7 +96,7 @@ namespace AZ void BindPassSrg(const RHI::FrameGraphCompileContext& context, Data::Instance& shaderResourceGroup); // Pass behavior overrides... - void OnBuildFinishedInternal() override; + void InitializeInternal() override; void FrameBeginInternal(FramePrepareParams params) override; void FrameEndInternal() override; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/AttachmentReadback.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/AttachmentReadback.cpp index 6435ae9570..88d3eb27fd 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/AttachmentReadback.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/AttachmentReadback.cpp @@ -320,8 +320,14 @@ namespace AZ { if (m_state == ReadbackState::Reading) { - CopyBufferData(readbackBufferCurrentIndex); - m_state = ReadbackState::Success; + if (CopyBufferData(readbackBufferCurrentIndex)) + { + m_state = ReadbackState::Success; + } + else + { + m_state = ReadbackState::Failed; + } } if (m_callback) { @@ -498,13 +504,13 @@ namespace AZ return result; } - void AttachmentReadback::CopyBufferData(uint32_t readbackBufferIndex) + bool AttachmentReadback::CopyBufferData(uint32_t readbackBufferIndex) { Data::Instance readbackBufferCurrent = m_readbackBufferArray[readbackBufferIndex]; if (!readbackBufferCurrent) { - return; + return false; } auto bufferSize = readbackBufferCurrent->GetBufferSize(); @@ -537,6 +543,7 @@ namespace AZ } m_isReadbackComplete[readbackBufferIndex] = true; + return true; } } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp index ebdfa7cf55..ad361bdf42 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp @@ -270,10 +270,10 @@ namespace AZ void ParentPass::ResetInternal() { - for (const Ptr& child : m_children) - { - child->Reset(); - } + //for (const Ptr& child : m_children) + //{ + // child->Reset(); + //} } void ParentPass::BuildInternal() @@ -284,11 +284,11 @@ namespace AZ } } - void ParentPass::OnBuildFinishedInternal() + void ParentPass::OnInitializationFinishedInternal() { for (const Ptr& child : m_children) { - child->OnBuildFinished(); + child->OnInitializationFinished(); } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp index 726d702a72..790a1e767f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp @@ -37,10 +37,13 @@ #include #include + namespace AZ { namespace RPI { +#pragma optimize("", off) + // --- Constructors --- Pass::Pass(const PassDescriptor& descriptor) @@ -152,6 +155,7 @@ namespace AZ AZ_RPI_PASS_ASSERT(m_parent != nullptr, "Trying to remove pass from parent but pointer to the parent pass is null."); m_parent->RemoveChild(Ptr(this)); m_queueState = PassQueueState::NoQueue; + m_state = PassState::Idle; } void Pass::OnOrphan() @@ -354,53 +358,6 @@ namespace AZ return nullptr; } - // --- Queuing functions with PassSystem --- - - void Pass::QueueForBuild() - { - // Don't queue if we're in building phase - if (m_state != PassState::Building && - (m_queueState == PassQueueState::NoQueue || m_queueState == PassQueueState::QueuedForInitialization)) - { - PassSystemInterface::Get()->QueueForBuild(this); - m_queueState = PassQueueState::QueuedForBuild; - - if (m_state != PassState::Rendering) - { - m_state = PassState::Queued; - } - } - } - - void Pass::QueueForInitialization() - { - // Don't queue if we're in initialization phase - if (m_queueState == PassQueueState::NoQueue) - { - PassSystemInterface::Get()->QueueForInitialization(this); - m_queueState = PassQueueState::QueuedForInitialization; - - if(m_state != PassState::Rendering) - { - m_state = PassState::Queued; - } - } - } - - void Pass::QueueForRemoval() - { - if (m_queueState != PassQueueState::QueuedForRemoval) - { - PassSystemInterface::Get()->QueueForRemoval(this); - m_queueState = PassQueueState::QueuedForRemoval; - - if (m_state != PassState::Rendering) - { - m_state = PassState::Queued; - } - } - } - // --- PassTemplate related functions --- void Pass::CreateBindingsFromTemplate() @@ -430,7 +387,7 @@ namespace AZ PassAttachmentBinding* localBinding = FindAttachmentBinding(slot); if (!localBinding) { - AZ_RPI_PASS_ERROR(false, "Pass::AttachBufferToSlot - Pass %s failed to find slot %s.", + AZ_RPI_PASS_ERROR(false, "Pass::AttachBufferToSlot - Pass [%s] failed to find slot [%s].", m_path.GetCStr(), slot.GetCStr()); return; } @@ -440,7 +397,7 @@ namespace AZ // handle the connected bindings if (localBinding->m_attachment) { - AZ_RPI_PASS_ERROR(false, "Pass::AttachBufferToSlot - Slot %s already has attachment %s.", + AZ_RPI_PASS_ERROR(false, "Pass::AttachBufferToSlot - Slot [%s] already has attachment [%s].", slot.GetCStr(), localBinding->m_attachment->m_name.GetCStr()); return; } @@ -462,7 +419,7 @@ namespace AZ PassAttachmentBinding* localBinding = FindAttachmentBinding(slot); if (!localBinding) { - AZ_RPI_PASS_ERROR(false, "Pass::AttachImageToSlot - Pass %s failed to find slot %s.", + AZ_RPI_PASS_ERROR(false, "Pass::AttachImageToSlot - Pass [%s] failed to find slot [%s].", m_path.GetCStr(), slot.GetCStr()); return; } @@ -472,7 +429,7 @@ namespace AZ // handle the connected bindings if (localBinding->m_attachment) { - AZ_RPI_PASS_ERROR(false, "Pass::AttachImageToSlot - Slot %s already has attachment %s.", + AZ_RPI_PASS_ERROR(false, "Pass::AttachImageToSlot - Slot [%s] already has attachment [%s].", slot.GetCStr(), localBinding->m_attachment->m_name.GetCStr()); return; } @@ -495,7 +452,7 @@ namespace AZ PassAttachmentBinding* localBinding = FindAttachmentBinding(connection.m_localSlot); if (!localBinding) { - AZ_RPI_PASS_ERROR(false, "Pass::ProcessConnection - Pass %s failed to find slot %s.", + AZ_RPI_PASS_ERROR(false, "Pass::ProcessConnection - Pass [%s] failed to find slot [%s].", m_path.GetCStr(), connection.m_localSlot.GetCStr()); return; @@ -517,7 +474,7 @@ namespace AZ { foundPass = true; const Ptr attachment = FindOwnedAttachment(connectedSlotName); - AZ_RPI_PASS_ERROR(attachment, "Pass::ProcessConnection - Pass %s doesn't own an attachment named %s.", + AZ_RPI_PASS_ERROR(attachment, "Pass::ProcessConnection - Pass [%s] doesn't own an attachment named [%s].", m_path.GetCStr(), connectedSlotName.GetCStr()); localBinding->SetAttachment(attachment); @@ -628,10 +585,10 @@ namespace AZ if (!outputBinding || !inputBinding) { - AZ_RPI_PASS_ERROR(inputBinding, "Pass::ProcessFallbackConnection - Pass %s failed to find input slot %s.", + AZ_RPI_PASS_ERROR(inputBinding, "Pass::ProcessFallbackConnection - Pass [%s] failed to find input slot [%s].", m_path.GetCStr(), connection.m_inputSlotName.GetCStr()); - AZ_RPI_PASS_ERROR(outputBinding, "Pass::ProcessFallbackConnection - Pass %s failed to find output slot %s.", + AZ_RPI_PASS_ERROR(outputBinding, "Pass::ProcessFallbackConnection - Pass [%s] failed to find output slot [%s].", m_path.GetCStr(), connection.m_outputSlotName.GetCStr()); return; @@ -641,10 +598,10 @@ namespace AZ if (!typesAreValid) { - AZ_RPI_PASS_ERROR(inputBinding->m_slotType == PassSlotType::Input, "Pass::ProcessFallbackConnection - Pass %s specifies fallback connection input %s, which is not an input.", + AZ_RPI_PASS_ERROR(inputBinding->m_slotType == PassSlotType::Input, "Pass::ProcessFallbackConnection - Pass [%s] specifies fallback connection input [%s], which is not an input.", m_path.GetCStr(), connection.m_inputSlotName.GetCStr()); - AZ_RPI_PASS_ERROR(outputBinding->m_slotType == PassSlotType::Output, "Pass::ProcessFallbackConnection - Pass %s specifies fallback connection output %s, which is not an output.", + AZ_RPI_PASS_ERROR(outputBinding->m_slotType == PassSlotType::Output, "Pass::ProcessFallbackConnection - Pass [%s] specifies fallback connection output [%s], which is not an output.", m_path.GetCStr(), connection.m_inputSlotName.GetCStr()); return; @@ -1038,7 +995,7 @@ namespace AZ // Check whether the template's slot allows this attachment if (m_template && !m_template->AttachmentFitsSlot(targetAttachment->m_descriptor, binding.m_name)) { - AZ_RPI_PASS_ERROR(false, "Pass::UpdateConnectedBinding - Attachment %s did not match the filters of input slot %s on pass %s.", + AZ_RPI_PASS_ERROR(false, "Pass::UpdateConnectedBinding - Attachment [%s] did not match the filters of input slot [%s] on pass [%s].", targetAttachment->m_name.GetCStr(), binding.m_name.GetCStr(), m_path.GetCStr()); @@ -1060,14 +1017,86 @@ namespace AZ } } + // --- Queuing functions with PassSystem --- + +#define OLD_SCHOOL 1 + + void Pass::QueueForBuild() + { +#if OLD_SCHOOL + // Don't queue if we're in building phase + //if (PassSystemInterface::Get()->GetState() != RPI::PassSystemState::Building) + { + if (!m_flags.m_queuedForBuildAttachment) + { + PassSystemInterface::Get()->QueueForBuild(this); + m_flags.m_queuedForBuildAttachment = true; + + // Set these two flags to false since when queue build attachments request, they should all be already be false except one use + // case that the pass system processed all queued requests when active a scene. + // m_flags.m_alreadyPrepared = false; + + m_queueState = PassQueueState::QueuedForBuild; + + if (m_state != PassState::Rendering) + { + m_state = PassState::Queued; + } + + } + } +#else + // Don't queue if we're in building phase + if (m_state != PassState::Building && + (m_queueState == PassQueueState::NoQueue || m_queueState == PassQueueState::QueuedForInitialization)) + { + //if (PassSystemInterface::Get()->GetState() != RPI::PassSystemState::Building) + { + PassSystemInterface::Get()->QueueForBuild(this); + } + m_queueState = PassQueueState::QueuedForBuild; + + if (m_state != PassState::Rendering) + { + m_state = PassState::Queued; + } + } +#endif + } + + void Pass::QueueForInitialization() + { + // Only queue if the pass is not in any other queue + if (m_queueState == PassQueueState::NoQueue) + { + PassSystemInterface::Get()->QueueForInitialization(this); + m_queueState = PassQueueState::QueuedForInitialization; + + if (m_state != PassState::Rendering && m_state != PassState::Built) + { + m_state = PassState::Queued; + } + } + } + + void Pass::QueueForRemoval() + { + if (m_queueState != PassQueueState::QueuedForRemoval) + { + PassSystemInterface::Get()->QueueForRemoval(this); + m_queueState = PassQueueState::QueuedForRemoval; + + if (m_state != PassState::Rendering) + { + m_state = PassState::Queued; + } + } + } + // --- Pass behavior functions --- void Pass::Reset() { - if (m_queueState != PassQueueState::QueuedForBuild || m_state != PassState::Queued) - { - return; - } m_state = PassState::Resetting; // Store references to imported attachments to underlying images and buffers aren't deleted during attachment building @@ -1083,19 +1112,37 @@ namespace AZ m_executeBeforePasses.clear(); ResetInternal(); + + m_state = PassState::Reset; } - void Pass::Build() + void Pass::Build(bool calledFromPassSystem) { - if (m_queueState != PassQueueState::QueuedForBuild || (m_state != PassState::Queued && m_state != PassState::Resetting)) + AZ_RPI_BREAK_ON_TARGET_PASS; + + bool execute = (m_state == PassState::Idle); + execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForBuild); + execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForInitialization); + +#if OLD_SCHOOL + AZ_Assert(!execute == m_flags.m_alreadyPrepared, "ANTON - EARLY OUT FLAGS do not match for pass BUILD!!"); + if (m_flags.m_alreadyPrepared) { return; } + m_flags.m_alreadyPrepared = true; +#else + if (!execute) + { + return; + } +#endif + + Reset(); + m_state = PassState::Building; m_queueState = PassQueueState::NoQueue; - AZ_RPI_BREAK_ON_TARGET_PASS; - // Bindings, inputs and attachments CreateBindingsFromTemplate(); SetupInputsFromRequest(); @@ -1116,32 +1163,51 @@ namespace AZ UpdateOwnedAttachments(); UpdateAttachmentUsageIndices(); - // Queue for Initialization - QueueForInitialization(); - } + m_state = PassState::Built; - void Pass::OnBuildFinished() - { - AZ_RPI_BREAK_ON_TARGET_PASS; - - m_flags.m_alreadyCreated = false; - m_importedAttachmentStore.clear(); - OnBuildFinishedInternal(); + // If this pass's Build() wasn't called from the Pass System, then it was called by it's parent pass + // In which case we don't need to queue for initialization because the parent will already be queued + if (calledFromPassSystem) + { + // Queue for Initialization + QueueForInitialization(); + } } void Pass::Initialize() { - if (m_queueState != PassQueueState::QueuedForInitialization || m_state != PassState::Queued) + AZ_RPI_BREAK_ON_TARGET_PASS; + + bool execute = (m_state == PassState::Idle || m_state == PassState::Built); + execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForInitialization); + + if (!execute) { return; } - m_queueState = PassQueueState::NoQueue; m_state = PassState::Initializing; + m_queueState = PassQueueState::NoQueue; + InitializeInternal(); + m_state = PassState::Initialized; } + void Pass::OnInitializationFinished() + { + AZ_RPI_BREAK_ON_TARGET_PASS; + + m_flags.m_alreadyPrepared = false; + m_flags.m_queuedForBuildAttachment = false; + + m_flags.m_alreadyCreated = false; + m_importedAttachmentStore.clear(); + OnInitializationFinishedInternal(); + + m_state = PassState::Idle; + } + void Pass::Validate(PassValidationResults& validationResults) { if (PassValidation::IsEnabled()) @@ -1195,6 +1261,8 @@ namespace AZ UpdateConnectedBindings(); return; } + + AZ_Assert(m_state == PassState::Idle, "Pass::FrameBegin - Pass [%s] is attempting to render, but is not in the Idle state.", m_path.GetCStr()); m_state = PassState::Rendering; UpdateConnectedBindings(); @@ -1213,7 +1281,7 @@ namespace AZ if (m_state == PassState::Rendering) { FrameEndInternal(); - m_state = (m_queueState == PassQueueState::NoQueue) ? PassState::Initialized : PassState::Queued; + m_state = (m_queueState == PassQueueState::NoQueue) ? PassState::Idle : PassState::Queued; } } @@ -1578,6 +1646,8 @@ namespace AZ } } +#pragma optimize("", on) + } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp index 0c38b228f5..abcaa181d8 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -50,6 +50,8 @@ namespace AZ { namespace RPI { +#pragma optimize("", off) + PassSystemInterface* PassSystemInterface::Get() { return Interface::Get(); @@ -101,6 +103,8 @@ namespace AZ m_rootPass = CreatePass(Name{"Root"}); m_rootPass->m_flags.m_partOfHierarchy = true; + //m_targetedPassDebugName = "RPISamplePipeline"; + m_state = PassSystemState::Idle; } @@ -189,7 +193,8 @@ namespace AZ AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: BuildPassAttachments"); - m_passHierarchyChanged = !m_buildPassList.empty(); + m_passHierarchyChanged = m_passHierarchyChanged || !m_buildPassList.empty(); + u32 loopCounter = 0; // While loop is for the event in which passes being built add more pass to m_buildPassList while(!m_buildPassList.empty()) @@ -211,19 +216,13 @@ namespace AZ for (const Ptr& pass : buildListCopy) { - pass->Reset(); - } - for (const Ptr& pass : buildListCopy) - { - pass->Build(); + pass->Build(true); } + loopCounter++; } if (m_passHierarchyChanged) { - // Signal all passes that we have finished building - m_rootPass->OnBuildFinished(); - #if AZ_RPI_ENABLE_PASS_DEBUGGING if (!m_isHotReloading) { @@ -242,6 +241,9 @@ namespace AZ AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: BuildPassAttachments"); + m_passHierarchyChanged = m_passHierarchyChanged || !m_initializePassList.empty(); + u32 loopCounter = 0; + while (!m_initializePassList.empty()) { AZStd::vector< Ptr > initListCopy = m_initializePassList; @@ -261,6 +263,13 @@ namespace AZ { pass->Initialize(); } + loopCounter++; + } + + if (m_passHierarchyChanged) + { + // Signal all passes that we have finished initialization + m_rootPass->OnInitializationFinished(); } m_state = PassSystemState::Idle; @@ -474,5 +483,6 @@ namespace AZ return nullptr; } +#pragma optimize("", on) } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp index 12989fb873..3e52130f6f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp @@ -128,7 +128,7 @@ namespace AZ } - void RenderPass::OnBuildFinishedInternal() + void RenderPass::InitializeInternal() { if (m_shaderResourceGroup != nullptr) { From c6d0887210c367f58b086d90f5f20759887d5e72 Mon Sep 17 00:00:00 2001 From: moudgils Date: Sun, 6 Jun 2021 10:24:42 -0700 Subject: [PATCH 549/811] Minor method name changes --- Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp | 8 ++++---- Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp index 1e2edc6520..5d6c275184 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp @@ -422,12 +422,12 @@ namespace AZ { if(RHI::CheckBitsAny(visMaskIt->second, RHI::ShaderStageMask::Compute)) { - ApplyUseResourceToCompute(commandEncoder, it.second, resourcesToMakeResidentCompute); + CollectResourcesForCompute(commandEncoder, it.second, resourcesToMakeResidentCompute); } else { AZ_Assert(RHI::CheckBitsAny(visMaskIt->second, RHI::ShaderStageMask::Vertex) || RHI::CheckBitsAny(visMaskIt->second, RHI::ShaderStageMask::Fragment), "The visibility mask %i is not set for Vertex or fragment stage", visMaskIt->second); - ApplyUseResourceToGraphic(commandEncoder, visMaskIt->second, it.second, resourcesToMakeResidentGraphics); + CollectResourcesForGraphics(commandEncoder, visMaskIt->second, it.second, resourcesToMakeResidentGraphics); } } } @@ -450,7 +450,7 @@ namespace AZ } } - void ArgumentBuffer::ApplyUseResourceToCompute(id encoder, const ResourceBindingsSet& resourceBindingDataSet, ComputeResourcesToMakeResidentMap& resourcesToMakeResidentMap) const + void ArgumentBuffer::CollectResourcesForCompute(id encoder, const ResourceBindingsSet& resourceBindingDataSet, ComputeResourcesToMakeResidentMap& resourcesToMakeResidentMap) const { for (const auto& resourceBindingData : resourceBindingDataSet) { @@ -477,7 +477,7 @@ namespace AZ } } - void ArgumentBuffer::ApplyUseResourceToGraphic(id encoder, RHI::ShaderStageMask visShaderMask, const ResourceBindingsSet& resourceBindingDataSet, GraphicsResourcesToMakeResidentMap& resourcesToMakeResidentMap) const + void ArgumentBuffer::CollectResourcesForGraphics(id encoder, RHI::ShaderStageMask visShaderMask, const ResourceBindingsSet& resourceBindingDataSet, GraphicsResourcesToMakeResidentMap& resourcesToMakeResidentMap) const { MTLRenderStages mtlRenderStages = GetRenderStages(visShaderMask); diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h index 2434b8312d..06380162b6 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h @@ -128,8 +128,8 @@ namespace AZ using ComputeResourcesToMakeResidentMap = AZStd::unordered_map; using GraphicsResourcesToMakeResidentMap = AZStd::unordered_map, MetalResourceArray>; - void ApplyUseResourceToCompute(id encoder, const ResourceBindingsSet& resourceBindingData, ComputeResourcesToMakeResidentMap& resourcesToMakeResidentMap) const; - void ApplyUseResourceToGraphic(id encoder, RHI::ShaderStageMask visShaderMask, const ResourceBindingsSet& resourceBindingDataSet, GraphicsResourcesToMakeResidentMap& resourcesToMakeResidentMap) const; + void CollectResourcesForCompute(id encoder, const ResourceBindingsSet& resourceBindingData, ComputeResourcesToMakeResidentMap& resourcesToMakeResidentMap) const; + void CollectResourcesForGraphics(id encoder, RHI::ShaderStageMask visShaderMask, const ResourceBindingsSet& resourceBindingDataSet, GraphicsResourcesToMakeResidentMap& resourcesToMakeResidentMap) const; //! Use visibility information to call UseResource on all resources for this Argument Buffer void ApplyUseResource(id encoder, const ResourceBindingsMap& resourceMap, From 9d7119a7f84a8f19db2d60da6ba3ea174e8c6461 Mon Sep 17 00:00:00 2001 From: antonmic Date: Sun, 6 Jun 2021 21:51:49 -0700 Subject: [PATCH 550/811] Pass Changes WIP: fixed bloom pass --- .../Code/Include/Atom/RPI.Public/Pass/Pass.h | 2 +- .../Source/RPI.Public/Pass/ParentPass.cpp | 8 ++--- .../RPI/Code/Source/RPI.Public/Pass/Pass.cpp | 33 +++++++++++++++++-- .../Source/RPI.Public/Pass/PassSystem.cpp | 4 +++ 4 files changed, 40 insertions(+), 7 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h index 3cab5b36e4..64daf1006d 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h @@ -396,8 +396,8 @@ namespace AZ uint64_t m_alreadyCreated : 1; // OLD SCHOOL - uint64_t m_alreadyReset : 1; uint64_t m_alreadyPrepared : 1; + uint64_t m_alreadyReset : 1; uint64_t m_queuedForBuildAttachment : 1; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp index ad361bdf42..6b95a6e17a 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp @@ -270,10 +270,10 @@ namespace AZ void ParentPass::ResetInternal() { - //for (const Ptr& child : m_children) - //{ - // child->Reset(); - //} + for (const Ptr& child : m_children) + { + child->Reset(); + } } void ParentPass::BuildInternal() diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp index 790a1e767f..391db8361d 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp @@ -75,6 +75,10 @@ namespace AZ PassSystemInterface::Get()->RegisterPass(this); QueueForBuild(); + + // Skip reset since the pass just got created + m_state = PassState::Reset; + m_flags.m_alreadyReset = true; } Pass::~Pass() @@ -1034,6 +1038,7 @@ namespace AZ // Set these two flags to false since when queue build attachments request, they should all be already be false except one use // case that the pass system processed all queued requests when active a scene. + // m_flags.m_alreadyReset = false; // m_flags.m_alreadyPrepared = false; m_queueState = PassQueueState::QueuedForBuild; @@ -1097,6 +1102,24 @@ namespace AZ void Pass::Reset() { + bool execute = (m_state == PassState::Idle); + execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForBuild); + execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForInitialization); + +#if OLD_SCHOOL + AZ_Assert(!execute == m_flags.m_alreadyReset, "ANTON - EARLY OUT FLAGS do not match for pass BUILD!!"); + if (m_flags.m_alreadyReset) + { + return; + } + m_flags.m_alreadyReset = true; +#else + if (!execute) + { + return; + } +#endif + m_state = PassState::Resetting; // Store references to imported attachments to underlying images and buffers aren't deleted during attachment building @@ -1120,7 +1143,7 @@ namespace AZ { AZ_RPI_BREAK_ON_TARGET_PASS; - bool execute = (m_state == PassState::Idle); + bool execute = (m_state == PassState::Idle || m_state == PassState::Reset); execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForBuild); execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForInitialization); @@ -1138,7 +1161,7 @@ namespace AZ } #endif - Reset(); + //Reset(); m_state = PassState::Building; m_queueState = PassQueueState::NoQueue; @@ -1189,6 +1212,11 @@ namespace AZ m_state = PassState::Initializing; m_queueState = PassQueueState::NoQueue; + // Update +// UpdateConnectedBindings(); +// UpdateOwnedAttachments(); +// UpdateAttachmentUsageIndices(); + InitializeInternal(); m_state = PassState::Initialized; @@ -1198,6 +1226,7 @@ namespace AZ { AZ_RPI_BREAK_ON_TARGET_PASS; + m_flags.m_alreadyReset = false; m_flags.m_alreadyPrepared = false; m_flags.m_queuedForBuildAttachment = false; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp index abcaa181d8..bbd9ac7df8 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -214,6 +214,10 @@ namespace AZ SortPassListAscending(buildListCopy); + for (const Ptr& pass : buildListCopy) + { + pass->Reset(); + } for (const Ptr& pass : buildListCopy) { pass->Build(true); From 1ffcfa07e6126c60e035a65f77bb7107d21b86dc Mon Sep 17 00:00:00 2001 From: Ibtehaj Nadeem <81370835+ibtehajn@users.noreply.github.com> Date: Mon, 7 Jun 2021 12:53:07 +0100 Subject: [PATCH 551/811] Remove Jenkins failure notifications (#958) Remove Jenkins failure notifications --- scripts/build/Jenkins/Jenkinsfile | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile index 3cf7d92ba6..1bce2988bf 100644 --- a/scripts/build/Jenkins/Jenkinsfile +++ b/scripts/build/Jenkins/Jenkinsfile @@ -578,14 +578,12 @@ finally { ) } node('controller') { - emailRecipients = [[$class: 'RequesterRecipientProvider']] - if (env.WATCHED_BRANCHES.tokenize(',').contains(branchName)) { - emailRecipients.add([$class: 'CulpritsRecipientProvider']) - } step([ - $class: 'Mailer', - notifyEveryUnstableBuild: true, - recipients: emailextrecipients(emailRecipients) + $class: 'Mailer', + notifyEveryUnstableBuild: true, + recipients: emailextrecipients([ + [$class: 'RequesterRecipientProvider'] + ]) ]) } } catch(Exception e) { From 5b940e8ed671034fa1ffb5e6950e752d88542ef2 Mon Sep 17 00:00:00 2001 From: Hasareej <82398396+Hasareej@users.noreply.github.com> Date: Mon, 7 Jun 2021 13:32:13 +0100 Subject: [PATCH 552/811] Viewport Ui Cluster Locked State Overlay (#1139) * Viewport Ui Cluster Locked State Overlay * PR feedback changes. --- .../img/UI20/toolbar/Locked_Status.svg | 12 ++++ .../AzQtComponents/Components/resources.qrc | 3 +- .../EditorTransformComponentSelection.cpp | 3 + .../ViewportUi/ViewportUiCluster.cpp | 55 +++++++++++++++++++ .../ViewportUi/ViewportUiCluster.h | 4 ++ .../ViewportUi/ViewportUiDisplay.cpp | 8 +++ .../ViewportUi/ViewportUiDisplay.h | 1 + .../ViewportUi/ViewportUiManager.cpp | 10 ++++ .../ViewportUi/ViewportUiManager.h | 1 + .../ViewportUi/ViewportUiRequestBus.h | 2 + 10 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Locked_Status.svg diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Locked_Status.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Locked_Status.svg new file mode 100644 index 0000000000..2612059dce --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Locked_Status.svg @@ -0,0 +1,12 @@ + + + Icon / Locked Status + + + + + + + + + \ No newline at end of file diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc index 00fa95d094..7070bd372b 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc @@ -356,7 +356,8 @@ img/UI20/toolbar/Load.svg img/UI20/toolbar/Local.svg img/UI20/toolbar/Locked.svg - img/UI20/toolbar/LUA.svg + img/UI20/toolbar/Locked_Status.svg + img/UI20/toolbar/LUA.svg img/UI20/toolbar/Material.svg img/UI20/toolbar/Measure.svg img/UI20/toolbar/Move.svg diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index db321d6818..5603c1a0f7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -2646,6 +2646,9 @@ namespace AzToolsFramework m_spaceCluster.m_spaceLock = ReferenceFrame::World; } } + ViewportUi::ViewportUiRequestBus::Event( + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::SetClusterButtonLocked, + m_spaceCluster.m_spaceClusterId, buttonId, m_spaceCluster.m_spaceLock.has_value()); }; m_spaceCluster.m_spaceSelectionHandler = AZ::Event::Handler(onButtonClicked); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.cpp index 79744f1dbf..d452d47508 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.cpp @@ -108,6 +108,61 @@ namespace AzToolsFramework::ViewportUi::Internal m_widgetCallbacks.Update(); } + void ViewportUiCluster::SetButtonLocked(const ButtonId buttonId, const bool isLocked) + { + const auto& buttons = m_buttonGroup->GetButtons(); + + // unlocked previously locked button + if (m_lockedButtonId.has_value() && isLocked) + { + // find the button to extract the old icon (without overlay) + auto findLocked = [this](const Button* button) { return (button->m_buttonId == m_lockedButtonId); }; + if (auto lockedButtonIt = AZStd::find_if(buttons.begin(), buttons.end(), findLocked); lockedButtonIt != buttons.end()) + { + // get the action corresponding to the lockedButtonId + if (auto actionEntry = m_buttonActionMap.find(m_lockedButtonId.value()); actionEntry != m_buttonActionMap.end()) + { + // remove the overlay + auto action = actionEntry->second; + action->setIcon(QIcon(QString((*lockedButtonIt)->m_icon.c_str()))); + } + } + } + + auto found = [buttonId](Button* button) { return (button->m_buttonId == buttonId); }; + if (auto buttonIt = AZStd::find_if(buttons.begin(), buttons.end(), found); buttonIt != buttons.end()) + { + QIcon newIcon; + + if (isLocked) + { + // overlay the locked icon ontop of the button's icon + QPixmap comboPixmap(24, 24); + comboPixmap.fill(Qt::transparent); + QPixmap firstImage(QString((*buttonIt)->m_icon.c_str())); + QPixmap secondImage(QString(":/stylesheet/img/UI20/toolbar/Locked_Status.svg")); + + QPainter painter(&comboPixmap); + painter.drawPixmap(0, 0, firstImage); + painter.drawPixmap(0, 0, secondImage); + newIcon.addPixmap(comboPixmap); + m_lockedButtonId = buttonId; + } + else + { + // remove the overlay + newIcon = QIcon(QString((*buttonIt)->m_icon.c_str())); + m_lockedButtonId = AZStd::nullopt; + } + + if (auto actionEntry = m_buttonActionMap.find(buttonId); actionEntry != m_buttonActionMap.end()) + { + auto action = actionEntry->second; + action->setIcon(newIcon); + } + } + } + ViewportUiWidgetCallbacks ViewportUiCluster::GetWidgetCallbacks() { return m_widgetCallbacks; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.h index 4f738177ea..027a201a9c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.h @@ -17,6 +17,7 @@ #include #include #include +#include namespace AzToolsFramework::ViewportUi::Internal { @@ -38,6 +39,8 @@ namespace AzToolsFramework::ViewportUi::Internal void RemoveButton(ButtonId buttonId); //! Updates all registered actions. void Update(); + //! Adds a locked overlay to the button's icon. + void SetButtonLocked(ButtonId buttonId, bool isLocked); //! Returns the widget manager. ViewportUiWidgetCallbacks GetWidgetCallbacks(); @@ -52,5 +55,6 @@ namespace AzToolsFramework::ViewportUi::Internal AZStd::shared_ptr m_buttonGroup; //!< Data structure which the cluster will be displaying to the Viewport UI. AZStd::unordered_map> m_buttonActionMap; //!< Map for buttons to their corresponding actions. ViewportUiWidgetCallbacks m_widgetCallbacks; //!< Registers actions and manages updates. + AZStd::optional m_lockedButtonId = AZStd::nullopt; //!< Used to track the last button locked. }; } // namespace AzToolsFramework::ViewportUi::Internal diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp index e9e7dcc1cc..3565d33174 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp @@ -100,6 +100,14 @@ namespace AzToolsFramework::ViewportUi::Internal } } + void ViewportUiDisplay::SetClusterButtonLocked(const ViewportUiElementId clusterId, const ButtonId buttonId, const bool isLocked) + { + if (auto viewportUiCluster = qobject_cast(GetViewportUiElement(clusterId).get())) + { + viewportUiCluster->SetButtonLocked(buttonId, isLocked); + } + } + void ViewportUiDisplay::RemoveClusterButton(ViewportUiElementId clusterId, ButtonId buttonId) { if (auto cluster = qobject_cast(GetViewportUiElement(clusterId).get())) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h index d46e01c978..19d04e63ff 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h @@ -58,6 +58,7 @@ namespace AzToolsFramework::ViewportUi::Internal void AddCluster(AZStd::shared_ptr buttonGroup, Alignment align); void AddClusterButton(ViewportUiElementId clusterId, Button* button); + void SetClusterButtonLocked(ViewportUiElementId clusterId, ButtonId buttonId, bool isLocked); void RemoveClusterButton(ViewportUiElementId clusterId, ButtonId buttonId); void UpdateCluster(const ViewportUiElementId clusterId); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp index 12c3b5c9bb..0668af383b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp @@ -67,6 +67,16 @@ namespace AzToolsFramework::ViewportUi } } + void ViewportUiManager::SetClusterButtonLocked(const ClusterId clusterId, const ButtonId buttonId, const bool isLocked) + { + if (auto clusterIt = m_clusterButtonGroups.find(clusterId); clusterIt != m_clusterButtonGroups.end()) + { + auto cluster = clusterIt->second; + m_viewportUi->SetClusterButtonLocked(cluster->GetViewportUiElementId(), buttonId, isLocked); + UpdateButtonGroupUi(cluster.get()); + } + } + void ViewportUiManager::RegisterClusterEventHandler(const ClusterId clusterId, AZ::Event::Handler& handler) { if (auto clusterIt = m_clusterButtonGroups.find(clusterId); clusterIt != m_clusterButtonGroups.end()) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h index 04a58cef65..14609ccc14 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h @@ -35,6 +35,7 @@ namespace AzToolsFramework::ViewportUi const SwitcherId CreateSwitcher(Alignment align) override; void SetClusterActiveButton(ClusterId clusterId, ButtonId buttonId) override; void SetSwitcherActiveButton(SwitcherId switcherId, ButtonId buttonId) override; + void SetClusterButtonLocked(ClusterId clusterId, ButtonId buttonId, bool isLocked) override; const ButtonId CreateClusterButton(ClusterId clusterId, const AZStd::string& icon) override; const ButtonId CreateSwitcherButton( SwitcherId switcherId, const AZStd::string& icon, const AZStd::string& name = AZStd::string()) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h index 3879817ccb..a068ffe9ee 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h @@ -65,6 +65,8 @@ namespace AzToolsFramework::ViewportUi virtual void SetClusterActiveButton(ClusterId clusterId, ButtonId buttonId) = 0; //! Sets the active button of the switcher. This is the button which has a text label. virtual void SetSwitcherActiveButton(SwitcherId clusterId, ButtonId buttonId) = 0; + //! Adds a locked overlay to the cluster button's icon. + virtual void SetClusterButtonLocked(ClusterId clusterId, ButtonId buttonId, bool isLocked) = 0; //! Registers a new button onto a cluster. virtual const ButtonId CreateClusterButton(const ClusterId clusterId, const AZStd::string& icon) = 0; //! Registers a new button onto a switcher. From c751cda73d0831e87beeca09832ff134219f8a25 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 7 Jun 2021 13:07:17 +0000 Subject: [PATCH 553/811] Fix for variable that is only used in the debug config (#1166) --- .../Code/Source/Integration/Components/ActorComponent.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp index f41ef165c8..b0065708fb 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp @@ -299,8 +299,7 @@ namespace EMotionFX void ActorComponent::OnAssetReady(AZ::Data::Asset asset) { m_configuration.m_actorAsset = asset; - Actor* actor = m_configuration.m_actorAsset->GetActor(); - AZ_Assert(m_configuration.m_actorAsset.IsReady() && actor, "Actor asset should be loaded and actor valid."); + AZ_Assert(m_configuration.m_actorAsset.IsReady() && m_configuration.m_actorAsset->GetActor(), "Actor asset should be loaded and actor valid."); CheckActorCreation(); } From cf8a6761bf91a0e098643a54dbe2882ed3cc21de Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Mon, 7 Jun 2021 14:50:49 +0100 Subject: [PATCH 554/811] Formatting-only change - Update Manipulator and Viewport AzToolsFramework files (#1143) * formatting changes to AzToolsFramework viewport related types + API comment style updates * minor format change - include ordering * improve formatting by moving comment * fix compile error and switch to use AZ_Printf * small polish changes after review feedback --- Code/Framework/AzCore/AzCore/std/math.h | 3 + .../AzFramework/Viewport/CameraInput.cpp | 36 +- .../ActionDispatcher.h | 2 +- .../AzManipulatorTestFrameworkUtils.h | 9 +- .../ImmediateModeActionDispatcher.h | 10 +- .../AzManipulatorTestFrameworkUtils.cpp | 6 +- .../DirectManipulatorViewportInteraction.cpp | 42 +- .../Source/ImmediateModeActionDispatcher.cpp | 14 +- .../Tests/BusCallTest.cpp | 35 +- .../Tests/DirectCallTest.cpp | 21 +- .../Tests/GridSnappingTest.cpp | 5 +- .../Tests/ViewportInteractionTest.cpp | 6 +- .../Tests/WorldSpaceBuilderTest.cpp | 83 +- .../Manipulators/AngularManipulator.cpp | 96 +- .../Manipulators/AngularManipulator.h | 115 +- .../Manipulators/BaseManipulator.cpp | 125 +- .../Manipulators/BaseManipulator.h | 323 ++-- .../Manipulators/BoxManipulatorRequestBus.h | 49 +- .../Manipulators/EditorVertexSelection.cpp | 834 ++++----- .../Manipulators/EditorVertexSelection.h | 296 +-- .../Manipulators/HoverSelection.h | 64 +- .../Manipulators/LineHoverSelection.cpp | 53 +- .../Manipulators/LineHoverSelection.h | 35 +- .../LineSegmentSelectionManipulator.cpp | 50 +- .../LineSegmentSelectionManipulator.h | 71 +- .../Manipulators/LinearManipulator.cpp | 97 +- .../Manipulators/LinearManipulator.h | 132 +- .../Manipulators/ManipulatorBus.h | 79 +- .../Manipulators/ManipulatorManager.cpp | 67 +- .../Manipulators/ManipulatorManager.h | 83 +- .../Manipulators/ManipulatorSnapping.cpp | 108 +- .../Manipulators/ManipulatorSnapping.h | 114 +- .../Manipulators/ManipulatorSpace.h | 22 +- .../Manipulators/ManipulatorView.cpp | 449 ++--- .../Manipulators/ManipulatorView.h | 319 ++-- .../Manipulators/MultiLinearManipulator.cpp | 58 +- .../Manipulators/MultiLinearManipulator.h | 29 +- .../Manipulators/PlanarManipulator.cpp | 82 +- .../Manipulators/PlanarManipulator.h | 108 +- .../Manipulators/RotationManipulators.cpp | 57 +- .../Manipulators/RotationManipulators.h | 35 +- .../Manipulators/ScaleManipulators.cpp | 71 +- .../Manipulators/ScaleManipulators.h | 40 +- .../Manipulators/SelectionManipulator.cpp | 35 +- .../Manipulators/SelectionManipulator.h | 69 +- .../Manipulators/SplineHoverSelection.cpp | 37 +- .../Manipulators/SplineHoverSelection.h | 34 +- .../SplineSelectionManipulator.cpp | 45 +- .../Manipulators/SplineSelectionManipulator.h | 57 +- .../Manipulators/SurfaceManipulator.cpp | 84 +- .../Manipulators/SurfaceManipulator.h | 89 +- .../Manipulators/TranslationManipulators.cpp | 103 +- .../Manipulators/TranslationManipulators.h | 75 +- .../AzToolsFramework/Picking/BoundInterface.h | 87 +- .../Picking/ContextBoundAPI.h | 64 +- .../Manipulators/ManipulatorBoundManager.cpp | 41 +- .../Manipulators/ManipulatorBoundManager.h | 38 +- .../Manipulators/ManipulatorBounds.cpp | 64 +- .../Picking/Manipulators/ManipulatorBounds.h | 125 +- .../Viewport/EditorContextMenu.cpp | 41 +- .../Viewport/EditorContextMenu.h | 30 +- .../Viewport/VertexContainerDisplay.cpp | 39 +- .../Viewport/VertexContainerDisplay.h | 29 +- .../Viewport/ViewportMessages.h | 222 +-- .../Viewport/ViewportTypes.cpp | 62 +- .../AzToolsFramework/Viewport/ViewportTypes.h | 252 ++- .../EditorDefaultSelection.cpp | 163 +- .../EditorDefaultSelection.h | 93 +- .../ViewportSelection/EditorHelpers.cpp | 97 +- .../ViewportSelection/EditorHelpers.h | 54 +- .../EditorInteractionSystemComponent.cpp | 44 +- .../EditorInteractionSystemComponent.h | 50 +- ...ractionSystemViewportSelectionRequestBus.h | 60 +- .../EditorPickEntitySelection.cpp | 52 +- .../EditorPickEntitySelection.h | 40 +- .../ViewportSelection/EditorSelectionUtil.cpp | 96 +- .../ViewportSelection/EditorSelectionUtil.h | 65 +- .../EditorTransformComponentSelection.cpp | 1649 ++++++++--------- ...rTransformComponentSelectionRequestBus.cpp | 104 +- ...torTransformComponentSelectionRequestBus.h | 80 +- .../EditorVisibleEntityDataCache.cpp | 100 +- .../EditorVisibleEntityDataCache.h | 31 +- .../Tests/ComponentModeTests.cpp | 131 +- 83 files changed, 4455 insertions(+), 4509 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/std/math.h b/Code/Framework/AzCore/AzCore/std/math.h index 9e9be7944a..f5e2ac7ea7 100644 --- a/Code/Framework/AzCore/AzCore/std/math.h +++ b/Code/Framework/AzCore/AzCore/std/math.h @@ -21,11 +21,14 @@ namespace AZStd using std::asin; using std::atan; using std::atan2; + using std::ceil; using std::cos; using std::exp2; + using std::floor; using std::fmod; using std::round; using std::sin; using std::sqrt; using std::tan; + using std::trunc; } // namespace AZStd diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 559f7ce460..674e10812b 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -22,7 +22,11 @@ namespace AzFramework { AZ_CVAR( - float, ed_cameraSystemDefaultPlaneHeight, 34.0f, nullptr, AZ::ConsoleFunctorFlags::Null, + float, + ed_cameraSystemDefaultPlaneHeight, + 34.0f, + nullptr, + AZ::ConsoleFunctorFlags::Null, "The default height of the ground plane to do intersection tests against when orbiting"); AZ_CVAR(float, ed_cameraSystemBoostMultiplier, 3.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemTranslateSpeed, 10.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); @@ -41,7 +45,11 @@ namespace AzFramework AZ_CVAR( AZ::CVarFixedString, ed_cameraSystemTranslateForwardKey, "keyboard_key_alphanumeric_W", nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR( - AZ::CVarFixedString, ed_cameraSystemTranslateBackwardKey, "keyboard_key_alphanumeric_S", nullptr, AZ::ConsoleFunctorFlags::Null, + AZ::CVarFixedString, + ed_cameraSystemTranslateBackwardKey, + "keyboard_key_alphanumeric_S", + nullptr, + AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR( AZ::CVarFixedString, ed_cameraSystemTranslateLeftKey, "keyboard_key_alphanumeric_A", nullptr, AZ::ConsoleFunctorFlags::Null, ""); @@ -326,7 +334,9 @@ namespace AzFramework } Camera RotateCameraInput::StepCamera( - const Camera& targetCamera, const ScreenVector& cursorDelta, [[maybe_unused]] const float scrollDelta, + const Camera& targetCamera, + const ScreenVector& cursorDelta, + [[maybe_unused]] const float scrollDelta, [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; @@ -374,7 +384,9 @@ namespace AzFramework } Camera PanCameraInput::StepCamera( - const Camera& targetCamera, const ScreenVector& cursorDelta, [[maybe_unused]] const float scrollDelta, + const Camera& targetCamera, + const ScreenVector& cursorDelta, + [[maybe_unused]] const float scrollDelta, [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; @@ -473,7 +485,9 @@ namespace AzFramework } Camera TranslateCameraInput::StepCamera( - const Camera& targetCamera, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] const float scrollDelta, + const Camera& targetCamera, + [[maybe_unused]] const ScreenVector& cursorDelta, + [[maybe_unused]] const float scrollDelta, const float deltaTime) { Camera nextCamera = targetCamera; @@ -630,7 +644,9 @@ namespace AzFramework } Camera OrbitDollyScrollCameraInput::StepCamera( - const Camera& targetCamera, [[maybe_unused]] const ScreenVector& cursorDelta, const float scrollDelta, + const Camera& targetCamera, + [[maybe_unused]] const ScreenVector& cursorDelta, + const float scrollDelta, [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; @@ -666,7 +682,9 @@ namespace AzFramework } Camera OrbitDollyCursorMoveCameraInput::StepCamera( - const Camera& targetCamera, const ScreenVector& cursorDelta, [[maybe_unused]] const float scrollDelta, + const Camera& targetCamera, + const ScreenVector& cursorDelta, + [[maybe_unused]] const float scrollDelta, [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; @@ -686,7 +704,9 @@ namespace AzFramework } Camera ScrollTranslationCameraInput::StepCamera( - const Camera& targetCamera, [[maybe_unused]] const ScreenVector& cursorDelta, const float scrollDelta, + const Camera& targetCamera, + [[maybe_unused]] const ScreenVector& cursorDelta, + const float scrollDelta, [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ActionDispatcher.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ActionDispatcher.h index c9211e9f26..1eba4f3799 100644 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ActionDispatcher.h +++ b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ActionDispatcher.h @@ -97,7 +97,7 @@ namespace AzManipulatorTestFramework if (m_logging) { AZStd::string message = AZStd::string::format(format, args...); - std::cout << "[ActionDispatcher] " << message.c_str() << "\n"; + AZ_Printf("[ActionDispatcher] %s", message.c_str()); } } diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h index f1c32e4d8d..9d380003e2 100644 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h +++ b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h @@ -21,12 +21,14 @@ namespace AzManipulatorTestFramework { //! Create a linear manipulator with a unit sphere bound. AZStd::shared_ptr CreateLinearManipulator( - const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, const AZ::Vector3& position = AZ::Vector3::CreateZero(), + const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, + const AZ::Vector3& position = AZ::Vector3::CreateZero(), float radius = 1.0f); //! Create a planar manipulator with a unit sphere bound. AZStd::shared_ptr CreatePlanarManipulator( - const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, const AZ::Vector3& position = AZ::Vector3::CreateZero(), + const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, + const AZ::Vector3& position = AZ::Vector3::CreateZero(), float radius = 1.0f); //! Create a mouse pick from the specified ray and screen point. @@ -39,7 +41,8 @@ namespace AzManipulatorTestFramework //! Create a mouse interaction from the specified pick, buttons, interaction id and keyboard modifiers. AzToolsFramework::ViewportInteraction::MouseInteraction CreateMouseInteraction( - const AzToolsFramework::ViewportInteraction::MousePick& mousePick, AzToolsFramework::ViewportInteraction::MouseButtons buttons, + const AzToolsFramework::ViewportInteraction::MousePick& mousePick, + AzToolsFramework::ViewportInteraction::MouseButtons buttons, AzToolsFramework::ViewportInteraction::InteractionId interactionId, AzToolsFramework::ViewportInteraction::KeyboardModifiers modifiers); diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ImmediateModeActionDispatcher.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ImmediateModeActionDispatcher.h index 6759c2255f..1faf4eff65 100644 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ImmediateModeActionDispatcher.h +++ b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ImmediateModeActionDispatcher.h @@ -12,14 +12,13 @@ #pragma once -#include #include +#include namespace AzManipulatorTestFramework { //! Dispatches actions immediately to the manipulators. - class ImmediateModeActionDispatcher - : public ActionDispatcher + class ImmediateModeActionDispatcher : public ActionDispatcher { using KeyboardModifier = AzToolsFramework::ViewportInteraction::KeyboardModifier; using KeyboardModifiers = AzToolsFramework::ViewportInteraction::KeyboardModifiers; @@ -62,7 +61,7 @@ namespace AzManipulatorTestFramework void MouseLButtonUpImpl() override; void MousePositionImpl(const AzFramework::ScreenPoint& position) override; void KeyboardModifierDownImpl(const KeyboardModifier& keyModifier) override; - void KeyboardModifierUpImpl(const KeyboardModifier& keyModifier) override; + void KeyboardModifierUpImpl(const KeyboardModifier& keyModifier) override; void ExpectManipulatorBeingInteractedImpl() override; void ExpectManipulatorNotBeingInteractedImpl() override; void SetEntityWorldTransformImpl(AZ::EntityId entityId, const AZ::Transform& transform) override; @@ -97,8 +96,7 @@ namespace AzManipulatorTestFramework return this; } - inline ImmediateModeActionDispatcher* ImmediateModeActionDispatcher::GetKeyboardModifiers( - KeyboardModifiers& keyboardModifiers) + inline ImmediateModeActionDispatcher* ImmediateModeActionDispatcher::GetKeyboardModifiers(KeyboardModifiers& keyboardModifiers) { keyboardModifiers = GetKeyboardModifiers(); return this; diff --git a/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp b/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp index 985c21cf8e..83746c9490 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp @@ -30,8 +30,10 @@ namespace AzManipulatorTestFramework // create a default sphere view for a manipulator for simple intersection template void SetupManipulatorView( - AZStd::shared_ptr manipulator, const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, - const AZ::Vector3& position, const float radius) + AZStd::shared_ptr manipulator, + const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, + const AZ::Vector3& position, + const float radius) { // unit sphere view auto sphereView = AzToolsFramework::CreateManipulatorViewSphere( diff --git a/Code/Framework/AzManipulatorTestFramework/Source/DirectManipulatorViewportInteraction.cpp b/Code/Framework/AzManipulatorTestFramework/Source/DirectManipulatorViewportInteraction.cpp index 5c5f77629c..192202cee2 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/DirectManipulatorViewportInteraction.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/DirectManipulatorViewportInteraction.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include #include @@ -19,10 +19,10 @@ namespace AzManipulatorTestFramework using MouseInteraction = AzToolsFramework::ViewportInteraction::MouseInteraction; using MouseInteractionEvent = AzToolsFramework::ViewportInteraction::MouseInteractionEvent; - class CustomManipulatorManager - : public AzToolsFramework::ManipulatorManager + class CustomManipulatorManager : public AzToolsFramework::ManipulatorManager { using ManagerBase = AzToolsFramework::ManipulatorManager; + public: using ManagerBase::ManagerBase; @@ -31,18 +31,17 @@ namespace AzManipulatorTestFramework }; //! Implementation of the manipulator interface using direct access to the manipulator manager. - class DirectCallManipulatorManager - : public ManipulatorManagerInterface + class DirectCallManipulatorManager : public ManipulatorManagerInterface { public: DirectCallManipulatorManager( - ViewportInteractionInterface* viewportInteraction, - AZStd::shared_ptr manipulatorManager); - + ViewportInteractionInterface* viewportInteraction, AZStd::shared_ptr manipulatorManager); + // ManipulatorManagerInterface ... void ConsumeMouseInteractionEvent(const MouseInteractionEvent& event); AzToolsFramework::ManipulatorManagerId GetId() const override; bool ManipulatorBeingInteracted() const override; + private: // Trigger the updating of manipulator bounds. void DrawManipulators(const MouseInteraction& mouseInteraction); @@ -61,8 +60,7 @@ namespace AzManipulatorTestFramework } DirectCallManipulatorManager::DirectCallManipulatorManager( - ViewportInteractionInterface* viewportInteraction, - AZStd::shared_ptr manipulatorManager) + ViewportInteractionInterface* viewportInteraction, AZStd::shared_ptr manipulatorManager) : m_viewportInteraction(viewportInteraction) , m_manipulatorManager(AZStd::move(manipulatorManager)) { @@ -126,11 +124,9 @@ namespace AzManipulatorTestFramework DirectCallManipulatorViewportInteraction::DirectCallManipulatorViewportInteraction() : m_customManager( - AZStd::make_unique( - AzToolsFramework::ManipulatorManagerId(AZ::Crc32("TestManipulatorManagerId")))) + AZStd::make_unique(AzToolsFramework::ManipulatorManagerId(AZ::Crc32("TestManipulatorManagerId")))) , m_viewportInteraction(AZStd::make_unique()) - , m_manipulatorManager( - AZStd::make_unique(m_viewportInteraction.get(), m_customManager)) + , m_manipulatorManager(AZStd::make_unique(m_viewportInteraction.get(), m_customManager)) { } diff --git a/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp b/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp index ad59d9578a..356a146125 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp @@ -10,8 +10,8 @@ * */ -#include #include +#include #include #include @@ -33,8 +33,7 @@ namespace AzManipulatorTestFramework using KeyboardModifier = AzToolsFramework::ViewportInteraction::KeyboardModifier; using MouseInteractionEvent = AzToolsFramework::ViewportInteraction::MouseInteractionEvent; - ImmediateModeActionDispatcher::ImmediateModeActionDispatcher( - ManipulatorViewportInteraction& viewportManipulatorInteraction) + ImmediateModeActionDispatcher::ImmediateModeActionDispatcher(ManipulatorViewportInteraction& viewportManipulatorInteraction) : m_viewportManipulatorInteraction(viewportManipulatorInteraction) { } @@ -126,8 +125,7 @@ namespace AzManipulatorTestFramework void ImmediateModeActionDispatcher::EnterComponentModeImpl(const AZ::Uuid& uuid) { using AzToolsFramework::ComponentModeFramework::ComponentModeSystemRequestBus; - ComponentModeSystemRequestBus::Broadcast( - &ComponentModeSystemRequestBus::Events::AddSelectedComponentModesOfType, uuid); + ComponentModeSystemRequestBus::Broadcast(&ComponentModeSystemRequestBus::Events::AddSelectedComponentModesOfType, uuid); } const AzToolsFramework::ViewportInteraction::MouseInteractionEvent* ImmediateModeActionDispatcher::GetMouseInteractionEvent() const @@ -144,8 +142,7 @@ namespace AzManipulatorTestFramework AzToolsFramework::ViewportInteraction::MouseInteractionEvent* ImmediateModeActionDispatcher::GetMouseInteractionEvent() { - return const_cast( - static_cast(this)->GetMouseInteractionEvent()); + return const_cast(static_cast(this)->GetMouseInteractionEvent()); } ImmediateModeActionDispatcher* ImmediateModeActionDispatcher::ExpectTrue(bool result) @@ -162,8 +159,7 @@ namespace AzManipulatorTestFramework return this; } - ImmediateModeActionDispatcher* ImmediateModeActionDispatcher::GetEntityWorldTransform( - AZ::EntityId entityId, AZ::Transform& transform) + ImmediateModeActionDispatcher* ImmediateModeActionDispatcher::GetEntityWorldTransform(AZ::EntityId entityId, AZ::Transform& transform) { Log("Getting entity world transform"); transform = AzToolsFramework::GetWorldTransform(entityId); diff --git a/Code/Framework/AzManipulatorTestFramework/Tests/BusCallTest.cpp b/Code/Framework/AzManipulatorTestFramework/Tests/BusCallTest.cpp index 8cc906f339..b2da9965e6 100644 --- a/Code/Framework/AzManipulatorTestFramework/Tests/BusCallTest.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Tests/BusCallTest.cpp @@ -11,17 +11,18 @@ */ #include "AzManipulatorTestFrameworkTestFixtures.h" -#include #include +#include namespace UnitTest { - class AzManipulatorTestFrameworkBusCallTestFixture - : public LinearManipulatorTestFixture + class AzManipulatorTestFrameworkBusCallTestFixture : public LinearManipulatorTestFixture { protected: AzManipulatorTestFrameworkBusCallTestFixture() - : LinearManipulatorTestFixture(AzToolsFramework::g_mainManipulatorManagerId) {} + : LinearManipulatorTestFixture(AzToolsFramework::g_mainManipulatorManagerId) + { + } bool IsManipulatorInteractingBusCall() const { @@ -37,8 +38,8 @@ namespace UnitTest TEST_F(AzManipulatorTestFrameworkBusCallTestFixture, ConsumeViewportLeftMouseClick) { // given a left mouse down ray in world space - auto event = AzManipulatorTestFramework::CreateMouseInteractionEvent( - m_interaction, AzToolsFramework::ViewportInteraction::MouseEvent::Down); + auto event = + AzManipulatorTestFramework::CreateMouseInteractionEvent(m_interaction, AzToolsFramework::ViewportInteraction::MouseEvent::Down); // consume the mouse down and up events AzManipulatorTestFramework::DispatchMouseInteractionEvent(event); @@ -56,8 +57,8 @@ namespace UnitTest TEST_F(AzManipulatorTestFrameworkBusCallTestFixture, ConsumeViewportMouseMoveHover) { // given a left mouse down ray in world space - const auto event = AzManipulatorTestFramework::CreateMouseInteractionEvent( - m_interaction, AzToolsFramework::ViewportInteraction::MouseEvent::Move); + const auto event = + AzManipulatorTestFramework::CreateMouseInteractionEvent(m_interaction, AzToolsFramework::ViewportInteraction::MouseEvent::Move); // consume the mouse move event AzManipulatorTestFramework::DispatchMouseInteractionEvent(event); @@ -75,8 +76,8 @@ namespace UnitTest TEST_F(AzManipulatorTestFrameworkBusCallTestFixture, ConsumeViewportMouseMoveActive) { // given a left mouse down ray in world space - auto event = AzManipulatorTestFramework::CreateMouseInteractionEvent( - m_interaction, AzToolsFramework::ViewportInteraction::MouseEvent::Down); + auto event = + AzManipulatorTestFramework::CreateMouseInteractionEvent(m_interaction, AzToolsFramework::ViewportInteraction::MouseEvent::Down); // consume the mouse down event AzManipulatorTestFramework::DispatchMouseInteractionEvent(event); @@ -110,14 +111,14 @@ namespace UnitTest const AZ::Vector3 initialManipulatorPosition = m_linearManipulator->GetLocalPosition(); m_linearManipulator->InstallMouseMoveCallback( [&movementAlongAxis, this](const AzToolsFramework::LinearManipulator::Action& action) - { - movementAlongAxis = action.LocalPositionOffset(); - m_linearManipulator->SetLocalPosition(action.LocalPosition()); - }); + { + movementAlongAxis = action.LocalPositionOffset(); + m_linearManipulator->SetLocalPosition(action.LocalPosition()); + }); // given a left mouse down ray in world space - auto event = AzManipulatorTestFramework::CreateMouseInteractionEvent( - m_interaction, AzToolsFramework::ViewportInteraction::MouseEvent::Down); + auto event = + AzManipulatorTestFramework::CreateMouseInteractionEvent(m_interaction, AzToolsFramework::ViewportInteraction::MouseEvent::Down); // consume the mouse down event AzManipulatorTestFramework::DispatchMouseInteractionEvent(event); @@ -134,7 +135,7 @@ namespace UnitTest // consume the mouse up event event.m_mouseEvent = AzToolsFramework::ViewportInteraction::MouseEvent::Up; AzManipulatorTestFramework::DispatchMouseInteractionEvent(event); - + // expect the left mouse down/up sanity flags to be set EXPECT_TRUE(m_receivedLeftMouseDown); EXPECT_TRUE(m_receivedLeftMouseUp); diff --git a/Code/Framework/AzManipulatorTestFramework/Tests/DirectCallTest.cpp b/Code/Framework/AzManipulatorTestFramework/Tests/DirectCallTest.cpp index bec61ce9a8..af810c1dcf 100644 --- a/Code/Framework/AzManipulatorTestFramework/Tests/DirectCallTest.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Tests/DirectCallTest.cpp @@ -14,10 +14,10 @@ namespace UnitTest { - class CustomManipulatorManager - : public AzToolsFramework::ManipulatorManager + class CustomManipulatorManager : public AzToolsFramework::ManipulatorManager { using ManagerBase = AzToolsFramework::ManipulatorManager; + public: using ManagerBase::ManagerBase; @@ -27,17 +27,17 @@ namespace UnitTest } }; - class AzManipulatorTestFrameworkCustomManagerTestFixture - : public LinearManipulatorTestFixture + class AzManipulatorTestFrameworkCustomManagerTestFixture : public LinearManipulatorTestFixture { protected: AzManipulatorTestFrameworkCustomManagerTestFixture() - : LinearManipulatorTestFixture(AzToolsFramework::ManipulatorManagerId(AZ::Crc32("TestManipulatorManagerId"))) {} + : LinearManipulatorTestFixture(AzToolsFramework::ManipulatorManagerId(AZ::Crc32("TestManipulatorManagerId"))) + { + } void SetUpEditorFixtureImpl() override { - m_manipulatorManager = - AZStd::make_shared(m_manipulatorManagerId); + m_manipulatorManager = AZStd::make_shared(m_manipulatorManagerId); LinearManipulatorTestFixture::SetUpEditorFixtureImpl(); } @@ -115,9 +115,9 @@ namespace UnitTest m_linearManipulator->InstallMouseMoveCallback( [&movementAlongAxis](const AzToolsFramework::LinearManipulator::Action& action) - { - movementAlongAxis = action.m_current.m_localPositionOffset; - }); + { + movementAlongAxis = action.m_current.m_localPositionOffset; + }); // consume the mouse down event m_manipulatorManager->ConsumeViewportMousePress(m_interaction); @@ -141,4 +141,3 @@ namespace UnitTest EXPECT_EQ(movementAlongAxis, expectedPositionAfterMovementAlongAxis); } } // namespace UnitTest - diff --git a/Code/Framework/AzManipulatorTestFramework/Tests/GridSnappingTest.cpp b/Code/Framework/AzManipulatorTestFramework/Tests/GridSnappingTest.cpp index d6006ba74f..160a9933d9 100644 --- a/Code/Framework/AzManipulatorTestFramework/Tests/GridSnappingTest.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Tests/GridSnappingTest.cpp @@ -12,6 +12,7 @@ #include "AzManipulatorTestFrameworkTestFixtures.h" +#include #include #include #include @@ -22,7 +23,6 @@ #include #include #include -#include namespace UnitTest { @@ -94,7 +94,8 @@ namespace UnitTest template void ValidateManipulatorSnappingBehavior( - AZStd::shared_ptr manipulator, AzManipulatorTestFramework::ImmediateModeActionDispatcher* actionDispatcher, + AZStd::shared_ptr manipulator, + AzManipulatorTestFramework::ImmediateModeActionDispatcher* actionDispatcher, const AzFramework::CameraState& cameraState) { manipulator->SetLocalOrientation(AZ::Quaternion::CreateFromEulerAnglesDegrees(AZ::Vector3(180.0f, 0.0f, 135.0f))); diff --git a/Code/Framework/AzManipulatorTestFramework/Tests/ViewportInteractionTest.cpp b/Code/Framework/AzManipulatorTestFramework/Tests/ViewportInteractionTest.cpp index 6ba44cc71b..4aad2ea138 100644 --- a/Code/Framework/AzManipulatorTestFramework/Tests/ViewportInteractionTest.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Tests/ViewportInteractionTest.cpp @@ -15,8 +15,7 @@ namespace UnitTest { - class AValidViewportInteraction - : public ToolsApplicationFixture + class AValidViewportInteraction : public ToolsApplicationFixture { public: AValidViewportInteraction() @@ -27,8 +26,7 @@ namespace UnitTest protected: void SetUpEditorFixtureImpl() override { - m_cameraState = - AzFramework::CreateIdentityDefaultCamera(AZ::Vector3::CreateZero(), AZ::Vector2(800.0f, 600.0f)); + m_cameraState = AzFramework::CreateIdentityDefaultCamera(AZ::Vector3::CreateZero(), AZ::Vector2(800.0f, 600.0f)); } public: diff --git a/Code/Framework/AzManipulatorTestFramework/Tests/WorldSpaceBuilderTest.cpp b/Code/Framework/AzManipulatorTestFramework/Tests/WorldSpaceBuilderTest.cpp index a6c58971f6..6168e9cece 100644 --- a/Code/Framework/AzManipulatorTestFramework/Tests/WorldSpaceBuilderTest.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Tests/WorldSpaceBuilderTest.cpp @@ -11,49 +11,48 @@ */ #include -#include #include +#include #include -#include #include -#include +#include #include +#include namespace UnitTest { - class AzManipulatorTestFrameworkWorldSpaceBuilderTestFixture - : public ToolsApplicationFixture + class AzManipulatorTestFrameworkWorldSpaceBuilderTestFixture : public ToolsApplicationFixture { protected: struct State { State(AZStd::unique_ptr viewportManipulatorInteraction) : m_viewportManipulatorInteraction(viewportManipulatorInteraction.release()) - , m_actionDispatcher(AZStd::make_unique(*m_viewportManipulatorInteraction)) - , m_linearManipulator( - AzManipulatorTestFramework::CreateLinearManipulator( - m_viewportManipulatorInteraction->GetManipulatorManager().GetId(), - /*position=*/AZ::Vector3(0.0f, 50.0f, 0.0f), - /*radius=*/m_boundsRadius)) + , m_actionDispatcher( + AZStd::make_unique(*m_viewportManipulatorInteraction)) + , m_linearManipulator(AzManipulatorTestFramework::CreateLinearManipulator( + m_viewportManipulatorInteraction->GetManipulatorManager().GetId(), + /*position=*/AZ::Vector3(0.0f, 50.0f, 0.0f), + /*radius=*/m_boundsRadius)) { // default sanity check call backs m_linearManipulator->InstallLeftMouseDownCallback( [this]([[maybe_unused]] const AzToolsFramework::LinearManipulator::Action& action) - { - m_receivedLeftMouseDown = true; - }); + { + m_receivedLeftMouseDown = true; + }); m_linearManipulator->InstallMouseMoveCallback( [this]([[maybe_unused]] const AzToolsFramework::LinearManipulator::Action& action) - { - m_receivedMouseMove = true; - }); + { + m_receivedMouseMove = true; + }); m_linearManipulator->InstallLeftMouseUpCallback( [this]([[maybe_unused]] const AzToolsFramework::LinearManipulator::Action& action) - { - m_receivedLeftMouseUp = true; - }); + { + m_receivedLeftMouseUp = true; + }); } ~State() = default; @@ -79,13 +78,12 @@ namespace UnitTest protected: void SetUpEditorFixtureImpl() override { - m_directState = AZStd::make_unique( - AZStd::make_unique()); - m_busState = AZStd::make_unique( - AZStd::make_unique()); + m_directState = + AZStd::make_unique(AZStd::make_unique()); + m_busState = + AZStd::make_unique(AZStd::make_unique()); m_cameraState = - AzFramework::CreateIdentityDefaultCamera( - AZ::Vector3::CreateZero(), AzManipulatorTestFramework::DefaultViewportSize); + AzFramework::CreateIdentityDefaultCamera(AZ::Vector3::CreateZero(), AzManipulatorTestFramework::DefaultViewportSize); } void TearDownEditorFixtureImpl() override @@ -105,8 +103,7 @@ namespace UnitTest { // given a left mouse down ray in world space // consume the mouse down and up events - state.m_actionDispatcher - ->CameraState(m_cameraState) + state.m_actionDispatcher->CameraState(m_cameraState) ->MousePosition(AzManipulatorTestFramework::GetCameraStateViewportCenter(m_cameraState)) ->MouseLButtonDown() ->Trace("Expecting left mouse button down") @@ -126,31 +123,27 @@ namespace UnitTest ->ExpectTrue(state.m_receivedLeftMouseUp) ->ExpectTrue(state.m_receivedMouseMove) ->ExpectFalse(state.m_linearManipulator->PerformingAction()) - ->ExpectManipulatorNotBeingInteracted() - ; + ->ExpectManipulatorNotBeingInteracted(); } void AzManipulatorTestFrameworkWorldSpaceBuilderTestFixture::ConsumeViewportMouseMoveHover(State& state) { // given a left mouse down ray in world space // consume the mouse move event - state.m_actionDispatcher - ->CameraState(m_cameraState) + state.m_actionDispatcher->CameraState(m_cameraState) ->MousePosition(AzManipulatorTestFramework::GetCameraStateViewportCenter(m_cameraState)) ->ExpectFalse(state.m_linearManipulator->PerformingAction()) ->ExpectManipulatorNotBeingInteracted() ->ExpectFalse(state.m_receivedLeftMouseDown) ->ExpectFalse(state.m_receivedMouseMove) - ->ExpectFalse(state.m_receivedLeftMouseUp) - ; + ->ExpectFalse(state.m_receivedLeftMouseUp); } void AzManipulatorTestFrameworkWorldSpaceBuilderTestFixture::ConsumeViewportMouseMoveActive(State& state) { // given a left mouse down ray in world space // consume the mouse move event - state.m_actionDispatcher - ->CameraState(m_cameraState) + state.m_actionDispatcher->CameraState(m_cameraState) ->MouseLButtonDown() ->MousePosition(AzManipulatorTestFramework::GetCameraStateViewportCenter(m_cameraState)) ->ExpectTrue(state.m_linearManipulator->PerformingAction()) @@ -158,8 +151,7 @@ namespace UnitTest ->MouseLButtonUp() ->ExpectTrue(state.m_receivedLeftMouseDown) ->ExpectTrue(state.m_receivedMouseMove) - ->ExpectTrue(state.m_receivedLeftMouseUp) - ; + ->ExpectTrue(state.m_receivedLeftMouseUp); } void AzManipulatorTestFrameworkWorldSpaceBuilderTestFixture::MoveManipulatorAlongAxis(State& state) @@ -176,8 +168,7 @@ namespace UnitTest // adjusted final world position taking into account the manipulator position relative to the camera const auto finalPositionWorldAdjusted = finalPositionWorld - (vectorToInitialPositionWorld * scaledRadiusBound); // calculate the position in screen space of the initial position of the manipulator - const auto initialPositionScreen = - AzFramework::WorldToScreen(initialPositionWorld, m_cameraState); + const auto initialPositionScreen = AzFramework::WorldToScreen(initialPositionWorld, m_cameraState); // calculate the position in screen space of the final position of the manipulator const auto finalPositionScreen = AzFramework::WorldToScreen(finalPositionWorldAdjusted, m_cameraState); @@ -185,12 +176,11 @@ namespace UnitTest state.m_linearManipulator->InstallMouseMoveCallback( [&movementAlongAxis](const AzToolsFramework::LinearManipulator::Action& action) - { - movementAlongAxis = action.LocalPosition(); - }); + { + movementAlongAxis = action.LocalPosition(); + }); - state.m_actionDispatcher - ->CameraState(m_cameraState) + state.m_actionDispatcher->CameraState(m_cameraState) ->MousePosition(initialPositionScreen) ->MouseLButtonDown() ->ExpectTrue(state.m_linearManipulator->PerformingAction()) @@ -199,8 +189,7 @@ namespace UnitTest ->MouseLButtonUp() ->ExpectTrue(state.m_receivedLeftMouseDown) ->ExpectTrue(state.m_receivedLeftMouseUp) - ->ExpectTrue(movementAlongAxis.IsClose(finalPositionWorld, 0.01f)) - ; + ->ExpectTrue(movementAlongAxis.IsClose(finalPositionWorld, 0.01f)); } TEST_F(AzManipulatorTestFrameworkWorldSpaceBuilderTestFixture, ConsumeViewportLeftMouseClick) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.cpp index 9a4a952d8f..6141fd9642 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.cpp @@ -1,28 +1,32 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "AngularManipulator.h" #include -#include #include +#include namespace AzToolsFramework { - static const float s_circularRotateThresholdDegrees = 80.0f; + static const float CircularRotateThresholdDegrees = 80.0f; AngularManipulator::ActionInternal AngularManipulator::CalculateManipulationDataStart( - const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Transform& localTransform, - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, const float rayDistance) + const Fixed& fixed, + const AZ::Transform& worldFromLocal, + const AZ::Transform& localTransform, + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, + const float rayDistance) { const AZ::Transform worldFromLocalWithTransform = worldFromLocal * localTransform; const AZ::Vector3 worldAxis = TransformDirectionNoScaling(worldFromLocalWithTransform, fixed.m_axis); @@ -35,7 +39,7 @@ namespace AzToolsFramework // if angular manipulator axis is at right angles to us, use initial ray direction // as plane normal and use hit position on manipulator as plane point const float pickAngle = AZ::RadToDeg(AZ::Acos(AZ::Abs(rayDirection.Dot(worldAxis)))); - if (pickAngle > s_circularRotateThresholdDegrees) + if (pickAngle > CircularRotateThresholdDegrees) { actionInternal.m_start.m_planeNormal = -rayDirection; actionInternal.m_start.m_planePoint = rayOrigin + rayDirection * rayDistance; @@ -43,8 +47,8 @@ namespace AzToolsFramework // store initial world hit position Internal::CalculateRayPlaneIntersectingPoint( - rayOrigin, rayDirection, actionInternal.m_start.m_planePoint, - actionInternal.m_start.m_planeNormal, actionInternal.m_current.m_worldHitPosition); + rayOrigin, rayDirection, actionInternal.m_start.m_planePoint, actionInternal.m_start.m_planeNormal, + actionInternal.m_current.m_worldHitPosition); // store entity transform (to go from local to world space) // and store our own starting local transform @@ -56,31 +60,33 @@ namespace AzToolsFramework } AngularManipulator::Action AngularManipulator::CalculateManipulationDataAction( - const Fixed& fixed, ActionInternal& actionInternal, const AZ::Transform& worldFromLocal, - const AZ::Transform& localTransform, const bool snapping, const float angleStepDegrees, - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, + const Fixed& fixed, + ActionInternal& actionInternal, + const AZ::Transform& worldFromLocal, + const AZ::Transform& localTransform, + const bool snapping, + const float angleStepDegrees, + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, const ViewportInteraction::KeyboardModifiers keyboardModifiers) { const AZ::Transform worldFromLocalWithTransform = worldFromLocal * localTransform; const AZ::Vector3 worldAxis = TransformDirectionNoScaling(worldFromLocalWithTransform, fixed.m_axis); AZ::Vector3 worldHitPosition = AZ::Vector3::CreateZero(); - Internal::CalculateRayPlaneIntersectingPoint(rayOrigin, rayDirection, - actionInternal.m_start.m_planePoint, actionInternal.m_start.m_planeNormal, - worldHitPosition); + Internal::CalculateRayPlaneIntersectingPoint( + rayOrigin, rayDirection, actionInternal.m_start.m_planePoint, actionInternal.m_start.m_planeNormal, worldHitPosition); // get vector from center of rotation for current and previous frame const AZ::Vector3 center = worldFromLocalWithTransform.GetTranslation(); const AZ::Vector3 currentWorldHitVector = (worldHitPosition - center).GetNormalizedSafe(); - const AZ::Vector3 previousWorldHitVector = - (actionInternal.m_current.m_worldHitPosition - center).GetNormalizedSafe(); + const AZ::Vector3 previousWorldHitVector = (actionInternal.m_current.m_worldHitPosition - center).GetNormalizedSafe(); // calculate which direction we rotated const AZ::Vector3 worldAxisRight = worldAxis.Cross(previousWorldHitVector); const float rotateSign = Sign(currentWorldHitVector.Dot(worldAxisRight)); // how far did we rotate this frame - const float rotationAngleRad = AZ::Acos(AZ::GetMin( - 1.0f, currentWorldHitVector.Dot(previousWorldHitVector))); + const float rotationAngleRad = AZ::Acos(AZ::GetMin(1.0f, currentWorldHitVector.Dot(previousWorldHitVector))); actionInternal.m_current.m_worldHitPosition = worldHitPosition; // if we're snapping, only increment current radians when we know @@ -148,16 +154,13 @@ namespace AzToolsFramework // calculate initial state when mouse press first happens m_actionInternal = CalculateManipulationDataStart( m_fixed, TransformNormalizedScale(GetSpace()), TransformNormalizedScale(GetLocalTransform()), - interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection, - rayIntersectionDistance); + interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection, rayIntersectionDistance); if (m_onLeftMouseDownCallback) { m_onLeftMouseDownCallback(CalculateManipulationDataAction( - m_fixed, m_actionInternal, m_actionInternal.m_start.m_worldFromLocal, - m_actionInternal.m_start.m_localTransform, snapping, angleStep, - interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection, - interaction.m_keyboardModifiers)); + m_fixed, m_actionInternal, m_actionInternal.m_start.m_worldFromLocal, m_actionInternal.m_start.m_localTransform, snapping, + angleStep, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection, interaction.m_keyboardModifiers)); } } @@ -167,12 +170,9 @@ namespace AzToolsFramework { // calculate delta rotation m_onMouseMoveCallback(CalculateManipulationDataAction( - m_fixed, m_actionInternal, m_actionInternal.m_start.m_worldFromLocal, - m_actionInternal.m_start.m_localTransform, - AngleSnapping(interaction.m_interactionId.m_viewportId), - AngleStep(interaction.m_interactionId.m_viewportId), - interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection, - interaction.m_keyboardModifiers)); + m_fixed, m_actionInternal, m_actionInternal.m_start.m_worldFromLocal, m_actionInternal.m_start.m_localTransform, + AngleSnapping(interaction.m_interactionId.m_viewportId), AngleStep(interaction.m_interactionId.m_viewportId), + interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection, interaction.m_keyboardModifiers)); } } @@ -181,12 +181,9 @@ namespace AzToolsFramework if (m_onLeftMouseUpCallback) { m_onLeftMouseUpCallback(CalculateManipulationDataAction( - m_fixed, m_actionInternal, m_actionInternal.m_start.m_worldFromLocal, - m_actionInternal.m_start.m_localTransform, - AngleSnapping(interaction.m_interactionId.m_viewportId), - AngleStep(interaction.m_interactionId.m_viewportId), - interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection, - interaction.m_keyboardModifiers)); + m_fixed, m_actionInternal, m_actionInternal.m_start.m_worldFromLocal, m_actionInternal.m_start.m_localTransform, + AngleSnapping(interaction.m_interactionId.m_viewportId), AngleStep(interaction.m_interactionId.m_viewportId), + interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection, interaction.m_keyboardModifiers)); } } @@ -197,12 +194,9 @@ namespace AzToolsFramework const ViewportInteraction::MouseInteraction& mouseInteraction) { m_manipulatorView->Draw( - GetManipulatorManagerId(), managerState, - GetManipulatorId(), { - ApplySpace(GetLocalTransform()), GetNonUniformScale(), - AZ::Vector3::CreateZero(), MouseOver() - }, - debugDisplay, cameraState, mouseInteraction); + GetManipulatorManagerId(), managerState, GetManipulatorId(), + { ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay, cameraState, + mouseInteraction); } void AngularManipulator::SetAxis(const AZ::Vector3& axis) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.h index e2f95fce5e..8e0468aa90 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -22,14 +22,14 @@ namespace AzToolsFramework { class ManipulatorView; - /// AngularManipulator serves as a visual tool for users to change a component's property based on rotation - /// around an axis. The rotation angle increases if the rotation goes counter clock-wise when looking - /// in the opposite direction the rotation axis points to. + //! AngularManipulator serves as a visual tool for users to change a component's property based on rotation + //! around an axis. The rotation angle increases if the rotation goes counter clock-wise when looking + //! in the opposite direction the rotation axis points to. class AngularManipulator : public BaseManipulator , public ManipulatorSpaceWithLocalTransform { - /// Private constructor. + //! Private constructor. explicit AngularManipulator(const AZ::Transform& worldFromLocal); public: @@ -42,33 +42,36 @@ namespace AzToolsFramework ~AngularManipulator() = default; - /// A Manipulator must only be created and managed through a shared_ptr. + //! A Manipulator must only be created and managed through a shared_ptr. static AZStd::shared_ptr MakeShared(const AZ::Transform& worldFromLocal); - /// The state of the manipulator at the start of an interaction. + //! The state of the manipulator at the start of an interaction. struct Start { - AZ::Quaternion m_space; ///< Starting orientation space of manipulator. - AZ::Quaternion m_rotation; ///< Starting local rotation of the manipulator. + AZ::Quaternion m_space; //!< Starting orientation space of manipulator. + AZ::Quaternion m_rotation; //!< Starting local rotation of the manipulator. }; - /// The state of the manipulator during an interaction. + //! The state of the manipulator during an interaction. struct Current { - AZ::Quaternion m_delta; ///< Amount of rotation to apply to manipulator during action. + AZ::Quaternion m_delta; //!< Amount of rotation to apply to manipulator during action. }; - /// Mouse action data used by MouseActionCallback (wraps Start and Current manipulator state). + //! Mouse action data used by MouseActionCallback (wraps Start and Current manipulator state). struct Action { Start m_start; Current m_current; ViewportInteraction::KeyboardModifiers m_modifiers; - AZ::Quaternion LocalOrientation() const { return m_start.m_rotation * m_current.m_delta; } + AZ::Quaternion LocalOrientation() const + { + return m_start.m_rotation * m_current.m_delta; + } }; - /// This is the function signature of callbacks that will be invoked whenever a manipulator - /// is clicked on or dragged. + //! This is the function signature of callbacks that will be invoked whenever a manipulator + //! is clicked on or dragged. using MouseActionCallback = AZStd::function; void InstallLeftMouseDownCallback(const MouseActionCallback& onMouseDownCallback); @@ -82,46 +85,49 @@ namespace AzToolsFramework const ViewportInteraction::MouseInteraction& mouseInteraction) override; void SetAxis(const AZ::Vector3& axis); - const AZ::Vector3& GetAxis() const { return m_fixed.m_axis; } + const AZ::Vector3& GetAxis() const + { + return m_fixed.m_axis; + } void SetView(AZStd::unique_ptr&& view); - ManipulatorView* GetView() const { return m_manipulatorView.get(); } + ManipulatorView* GetView() const + { + return m_manipulatorView.get(); + } private: - void OnLeftMouseDownImpl( - const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; - void OnLeftMouseUpImpl( - const ViewportInteraction::MouseInteraction& interaction) override; - void OnMouseMoveImpl( - const ViewportInteraction::MouseInteraction& interaction) override; + void OnLeftMouseDownImpl(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; + void OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction) override; + void OnMouseMoveImpl(const ViewportInteraction::MouseInteraction& interaction) override; void SetBoundsDirtyImpl() override; void InvalidateImpl() override; - /// Unchanging data set once for the angular manipulator. + //! Unchanging data set once for the angular manipulator. struct Fixed { - AZ::Vector3 m_axis = AZ::Vector3::CreateAxisX(); ///< Axis for this angular manipulator to rotate around. + AZ::Vector3 m_axis = AZ::Vector3::CreateAxisX(); //!< Axis for this angular manipulator to rotate around. }; - /// Initial data recorded when a press first happens with an angular manipulator. + //! Initial data recorded when a press first happens with an angular manipulator. struct StartInternal { - AZ::Transform m_worldFromLocal; ///< Initial transform when pressed. - AZ::Transform m_localTransform; ///< Additional transform (offset) to apply to manipulator. - AZ::Vector3 m_planePoint; ///< Position on plane to use for ray intersection. - AZ::Vector3 m_planeNormal; ///< Normal of plane to use for ray intersection. + AZ::Transform m_worldFromLocal; //!< Initial transform when pressed. + AZ::Transform m_localTransform; //!< Additional transform (offset) to apply to manipulator. + AZ::Vector3 m_planePoint; //!< Position on plane to use for ray intersection. + AZ::Vector3 m_planeNormal; //!< Normal of plane to use for ray intersection. }; - /// Current data recorded each frame during an interaction with an angular manipulator. + //! Current data recorded each frame during an interaction with an angular manipulator. struct CurrentInternal { - float m_preSnapRadians = 0.0f; ///< Amount of rotation before a snap (snap increment accumulator). - float m_radians = 0.0f; ///< Amount of rotation about the axis for this action. - AZ::Vector3 m_worldHitPosition; ///< Initial world space hit position. + float m_preSnapRadians = 0.0f; //!< Amount of rotation before a snap (snap increment accumulator). + float m_radians = 0.0f; //!< Amount of rotation about the axis for this action. + AZ::Vector3 m_worldHitPosition; //!< Initial world space hit position. }; - /// Wrap start and current internal data during an interaction with an angular manipulator. + //! Wrap start and current internal data during an interaction with an angular manipulator. struct ActionInternal { StartInternal m_start; @@ -135,16 +141,25 @@ namespace AzToolsFramework MouseActionCallback m_onLeftMouseUpCallback = nullptr; MouseActionCallback m_onMouseMoveCallback = nullptr; - AZStd::unique_ptr m_manipulatorView; ///< Look of manipulator. + AZStd::unique_ptr m_manipulatorView; //!< Look of manipulator. static ActionInternal CalculateManipulationDataStart( - const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Transform& localTransform, - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, float rayDistance); + const Fixed& fixed, + const AZ::Transform& worldFromLocal, + const AZ::Transform& localTransform, + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, + float rayDistance); static Action CalculateManipulationDataAction( - const Fixed& fixed, ActionInternal& actionInternal, const AZ::Transform& worldFromLocal, - const AZ::Transform& localTransform, bool snapping, float angleStepDegrees, - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, + const Fixed& fixed, + ActionInternal& actionInternal, + const AZ::Transform& worldFromLocal, + const AZ::Transform& localTransform, + bool snapping, + float angleStepDegrees, + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, ViewportInteraction::KeyboardModifiers keyboardModifiers); }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp index 955d10d3bd..73d0dc72be 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp @@ -1,33 +1,30 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "BaseManipulator.h" #include -#include #include +#include namespace AzToolsFramework { - AZ_CVAR( - bool, cl_manipulatorDrawDebug, false, nullptr, AZ::ConsoleFunctorFlags::Null, - "Enable debug drawing for Manipulators"); + AZ_CVAR(bool, cl_manipulatorDrawDebug, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Enable debug drawing for Manipulators"); const AZ::Color BaseManipulator::s_defaultMouseOverColor = AZ::Color(1.0f, 1.0f, 0.0f, 1.0f); // yellow AZ_CLASS_ALLOCATOR_IMPL(BaseManipulator, AZ::SystemAllocator, 0) - static bool EntityIdAndEntityComponentIdComparison( - const AZ::EntityId entityId, const AZ::EntityComponentIdPair& entityComponentId) + static bool EntityIdAndEntityComponentIdComparison(const AZ::EntityId entityId, const AZ::EntityComponentIdPair& entityComponentId) { return entityId == entityComponentId.GetEntityId(); } @@ -38,8 +35,7 @@ namespace AzToolsFramework EndUndoBatch(); } - bool BaseManipulator::OnLeftMouseDown( - const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance) + bool BaseManipulator::OnLeftMouseDown(const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -57,8 +53,7 @@ namespace AzToolsFramework (*this.*m_onLeftMouseDownImpl)(interaction, rayIntersectionDistance); - ToolsApplicationNotificationBus::Broadcast( - &ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); + ToolsApplicationNotificationBus::Broadcast(&ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); return true; } @@ -66,8 +61,7 @@ namespace AzToolsFramework return false; } - bool BaseManipulator::OnRightMouseDown( - const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance) + bool BaseManipulator::OnRightMouseDown(const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -85,8 +79,7 @@ namespace AzToolsFramework (*this.*m_onRightMouseDownImpl)(interaction, rayIntersectionDistance); - ToolsApplicationNotificationBus::Broadcast( - &ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); + ToolsApplicationNotificationBus::Broadcast(&ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); return true; } @@ -118,8 +111,7 @@ namespace AzToolsFramework EndUndoBatch(); } - bool BaseManipulator::OnMouseOver( - const ManipulatorId manipulatorId, const ViewportInteraction::MouseInteraction& interaction) + bool BaseManipulator::OnMouseOver(const ManipulatorId manipulatorId, const ViewportInteraction::MouseInteraction& interaction) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -132,8 +124,7 @@ namespace AzToolsFramework { OnMouseWheelImpl(interaction); - ToolsApplicationNotificationBus::Broadcast( - &ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); + ToolsApplicationNotificationBus::Broadcast(&ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); } void BaseManipulator::OnMouseMove(const ViewportInteraction::MouseInteraction& interaction) @@ -142,16 +133,13 @@ namespace AzToolsFramework if (!m_performingAction) { - AZ_Warning( - "Manipulators", false, - "MouseMove action received, but this manipulator is not performing an action"); + AZ_Warning("Manipulators", false, "MouseMove action received, but this manipulator is not performing an action"); return; } // ensure property grid (entity inspector) values are refreshed - ToolsApplicationNotificationBus::Broadcast( - &ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); + ToolsApplicationNotificationBus::Broadcast(&ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); OnMouseMoveImpl(interaction); } @@ -170,16 +158,14 @@ namespace AzToolsFramework Unregister(); } - ManipulatorManagerRequestBus::Event(managerId, - &ManipulatorManagerRequestBus::Events::RegisterManipulator, shared_from_this()); + ManipulatorManagerRequestBus::Event(managerId, &ManipulatorManagerRequestBus::Events::RegisterManipulator, shared_from_this()); } void BaseManipulator::Unregister() { // if the manipulator has already been unregistered, the m_manipulatorManagerId // should be invalid which makes the call below a no-op. - ManipulatorManagerRequestBus::Event(m_manipulatorManagerId, - &ManipulatorManagerRequestBus::Events::UnregisterManipulator, this); + ManipulatorManagerRequestBus::Event(m_manipulatorManagerId, &ManipulatorManagerRequestBus::Events::UnregisterManipulator, this); } void BaseManipulator::Invalidate() @@ -197,8 +183,7 @@ namespace AzToolsFramework if (m_performingAction) { AZ_Warning( - "Manipulators", false, - "MouseDown action received, but the manipulator (id: %d) is still performing an action", + "Manipulators", false, "MouseDown action received, but the manipulator (id: %d) is still performing an action", GetManipulatorId()); return; @@ -214,8 +199,7 @@ namespace AzToolsFramework if (!m_performingAction) { AZ_Warning( - "Manipulators", false, - "MouseUp action received, but this manipulator (id: %d) didn't receive MouseDown action before", + "Manipulators", false, "MouseUp action received, but this manipulator (id: %d) didn't receive MouseDown action before", GetManipulatorId()); return; } @@ -263,13 +247,13 @@ namespace AzToolsFramework if (entityComponentIdPair.GetComponentId() != AZ::InvalidComponentId) { PropertyEditorEntityChangeNotificationBus::Event( - entityComponentIdPair.GetEntityId(), - &PropertyEditorEntityChangeNotifications::OnEntityComponentPropertyChanged, + entityComponentIdPair.GetEntityId(), &PropertyEditorEntityChangeNotifications::OnEntityComponentPropertyChanged, entityComponentIdPair.GetComponentId()); } else { - AZ_Warning("Manipulators", false, + AZ_Warning( + "Manipulators", false, "This Manipulator was only registered with an EntityId and not an EntityComponentIdPair. " "Please use AddEntityComponentIdPair() instead of AddEntityId() when registering what this " "Manipulator is changing."); @@ -280,8 +264,7 @@ namespace AzToolsFramework for (const AZ::Component* component : entity->GetComponents()) { PropertyEditorEntityChangeNotificationBus::Event( - entity->GetId(), &PropertyEditorEntityChangeNotifications::OnEntityComponentPropertyChanged, - component->GetId()); + entity->GetId(), &PropertyEditorEntityChangeNotifications::OnEntityComponentPropertyChanged, component->GetId()); } } } @@ -298,9 +281,7 @@ namespace AzToolsFramework { // look for a match (keep looking in case we have several entity ids with different component ids) const auto entityComponentPairId = - m_entityComponentIdPairs.find_as( - entityId, AZStd::hash(), - &EntityIdAndEntityComponentIdComparison); + m_entityComponentIdPairs.find_as(entityId, AZStd::hash(), &EntityIdAndEntityComponentIdComparison); // update the afterErased variable so we can return an iterator // to the correct position in the container. @@ -334,9 +315,8 @@ namespace AzToolsFramework bool BaseManipulator::HasEntityId(const AZ::EntityId entityId) const { - return m_entityComponentIdPairs.find_as( - entityId, AZStd::hash(), - &EntityIdAndEntityComponentIdComparison) != m_entityComponentIdPairs.end(); + return m_entityComponentIdPairs.find_as(entityId, AZStd::hash(), &EntityIdAndEntityComponentIdComparison) != + m_entityComponentIdPairs.end(); } bool BaseManipulator::HasEntityComponentIdPair(const AZ::EntityComponentIdPair& entityComponentIdPair) const @@ -346,7 +326,8 @@ namespace AzToolsFramework void Manipulators::Register(const ManipulatorManagerId manipulatorManagerId) { - ProcessManipulators([manipulatorManagerId](BaseManipulator* manipulator) + ProcessManipulators( + [manipulatorManagerId](BaseManipulator* manipulator) { manipulator->Register(manipulatorManagerId); }); @@ -354,7 +335,8 @@ namespace AzToolsFramework void Manipulators::Unregister() { - ProcessManipulators([](BaseManipulator* manipulator) + ProcessManipulators( + [](BaseManipulator* manipulator) { if (manipulator->Registered()) { @@ -365,7 +347,8 @@ namespace AzToolsFramework void Manipulators::SetBoundsDirty() { - ProcessManipulators([](BaseManipulator* manipulator) + ProcessManipulators( + [](BaseManipulator* manipulator) { manipulator->SetBoundsDirty(); }); @@ -373,7 +356,8 @@ namespace AzToolsFramework void Manipulators::AddEntityComponentIdPair(const AZ::EntityComponentIdPair& entityComponentIdPair) { - ProcessManipulators([&entityComponentIdPair](BaseManipulator* manipulator) + ProcessManipulators( + [&entityComponentIdPair](BaseManipulator* manipulator) { manipulator->AddEntityComponentIdPair(entityComponentIdPair); }); @@ -381,7 +365,8 @@ namespace AzToolsFramework void Manipulators::RemoveEntityComponentIdPair(const AZ::EntityComponentIdPair& entityComponentIdPair) { - ProcessManipulators([&entityComponentIdPair](BaseManipulator* manipulator) + ProcessManipulators( + [&entityComponentIdPair](BaseManipulator* manipulator) { manipulator->RemoveEntityComponentIdPair(entityComponentIdPair); }); @@ -389,7 +374,8 @@ namespace AzToolsFramework void Manipulators::RemoveEntityId(const AZ::EntityId entityId) { - ProcessManipulators([entityId](BaseManipulator* manipulator) + ProcessManipulators( + [entityId](BaseManipulator* manipulator) { manipulator->RemoveEntityId(entityId); }); @@ -398,7 +384,8 @@ namespace AzToolsFramework bool Manipulators::PerformingAction() { bool performingAction = false; - ProcessManipulators([&performingAction](BaseManipulator* manipulator) + ProcessManipulators( + [&performingAction](BaseManipulator* manipulator) { if (manipulator->PerformingAction()) { @@ -412,7 +399,8 @@ namespace AzToolsFramework bool Manipulators::Registered() { bool registered = false; - ProcessManipulators([®istered](BaseManipulator* manipulator) + ProcessManipulators( + [®istered](BaseManipulator* manipulator) { if (manipulator->Registered()) { @@ -470,8 +458,12 @@ namespace AzToolsFramework namespace Internal { - bool CalculateRayPlaneIntersectingPoint(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, - const AZ::Vector3& pointOnPlane, const AZ::Vector3& planeNormal, AZ::Vector3& resultIntersectingPoint) + bool CalculateRayPlaneIntersectingPoint( + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, + const AZ::Vector3& pointOnPlane, + const AZ::Vector3& planeNormal, + AZ::Vector3& resultIntersectingPoint) { float t = 0.0f; if (AZ::Intersect::IntersectRayPlane(rayOrigin, rayDirection, pointOnPlane, planeNormal, t) > 0) @@ -484,11 +476,12 @@ namespace AzToolsFramework } AZ::Vector3 TryConstrainHitPositionToView( - const AZ::Vector3& currentLocalHitPosition, const AZ::Vector3& startLocalHitPosition, - const AZ::Transform& localFromWorld, const AzFramework::CameraState& cameraState) + const AZ::Vector3& currentLocalHitPosition, + const AZ::Vector3& startLocalHitPosition, + const AZ::Transform& localFromWorld, + const AzFramework::CameraState& cameraState) { - if (currentLocalHitPosition.GetDistance(localFromWorld.TransformPoint(cameraState.m_position)) - > cameraState.m_farClip) + if (currentLocalHitPosition.GetDistance(localFromWorld.TransformPoint(cameraState.m_position)) > cameraState.m_farClip) { return startLocalHitPosition; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.h index 2b078f62b7..04f2bc456b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -22,13 +22,13 @@ #include #include #include -#include "ManipulatorSpace.h" +#include namespace AzFramework { struct CameraState; class DebugDisplayRequests; -} +} // namespace AzFramework namespace AzToolsFramework { @@ -46,9 +46,8 @@ namespace AzToolsFramework struct ManipulatorManagerState; - /// The base class for manipulators, providing interfaces for users of manipulators to talk to. - class BaseManipulator - : public AZStd::enable_shared_from_this + //! The base class for manipulators, providing interfaces for users of manipulators to talk to. + class BaseManipulator : public AZStd::enable_shared_from_this { public: AZ_CLASS_ALLOCATOR_DECL @@ -61,139 +60,181 @@ namespace AzToolsFramework using EntityComponentIds = AZStd::unordered_set; - /// Callback for the event when the mouse pointer is over this manipulator and the left mouse button is pressed. - /// @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera through the mouse pointer. - /// @param rayIntersectionDistance The parameter value in the ray's explicit equation that represents the intersecting point on the target manipulator in world space. - /// @return Return true if OnLeftMouseDownImpl was attached and will be used. + //! Callback for the event when the mouse pointer is over this manipulator and the left mouse button is pressed. + //! @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera + //! through the mouse pointer. + //! @param rayIntersectionDistance The parameter value in the ray's explicit equation that represents the intersecting point on the + //! target manipulator in world space. + //! @return Return true if OnLeftMouseDownImpl was attached and will be used. bool OnLeftMouseDown(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance); - /// Callback for the event when this manipulator is active and the left mouse button is released. - /// @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera through the mouse pointer. + //! Callback for the event when this manipulator is active and the left mouse button is released. + //! @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera + //! through the mouse pointer. void OnLeftMouseUp(const ViewportInteraction::MouseInteraction& interaction); - /// Callback for the event when the mouse pointer is over this manipulator and the right mouse button is pressed . - /// @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera through the mouse pointer. - /// @param rayIntersectionDistance The parameter value in the ray's explicit equation that represents the intersecting point on the target manipulator in world space. - /// @return Return true if OnRightMouseDownImpl was attached and will be used. + //! Callback for the event when the mouse pointer is over this manipulator and the right mouse button is pressed . + //! @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera + //! through the mouse pointer. + //! @param rayIntersectionDistance The parameter value in the ray's explicit equation that represents the intersecting point on the + //! target manipulator in world space. + //! @return Return true if OnRightMouseDownImpl was attached and will be used. bool OnRightMouseDown(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance); - /// Callback for the event when this manipulator is active and the right mouse button is released. - /// @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera through the mouse pointer. + //! Callback for the event when this manipulator is active and the right mouse button is released. + //! @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera + //! through the mouse pointer. void OnRightMouseUp(const ViewportInteraction::MouseInteraction& interaction); - /// Callback for the event when this manipulator is active and the mouse is moved. - /// @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera through the mouse pointer. + //! Callback for the event when this manipulator is active and the mouse is moved. + //! @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera + //! through the mouse pointer. void OnMouseMove(const ViewportInteraction::MouseInteraction& interaction); - /// Callback for the event when this manipulator is active and the mouse wheel is scrolled. - /// @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera through the mouse pointer. + //! Callback for the event when this manipulator is active and the mouse wheel is scrolled. + //! @param interaction It contains various mouse states when the event happens, as well as a ray shooting from the viewing camera + //! through the mouse pointer. void OnMouseWheel(const ViewportInteraction::MouseInteraction& interaction); - /// This function changes the state indicating whether the manipulator is under the mouse pointer. - /// It is called in the event of OnMouseMove and OnMouseWheel only when there is no manipulator currently performing actions. + //! This function changes the state indicating whether the manipulator is under the mouse pointer. + //! It is called in the event of OnMouseMove and OnMouseWheel only when there is no manipulator currently performing actions. bool OnMouseOver(ManipulatorId manipulatorId, const ViewportInteraction::MouseInteraction& interaction); - /// Register itself to a manipulator manager so that it can receive various mouse events and perform manipulations. - /// @param managerId The id identifying a unique manipulator manager. + //! Register itself to a manipulator manager so that it can receive various mouse events and perform manipulations. + //! @param managerId The id identifying a unique manipulator manager. void Register(ManipulatorManagerId managerId); - /// Unregister itself from the manipulator manager it was registered with. + //! Unregister itself from the manipulator manager it was registered with. void Unregister(); - /// Bounds will need to be recalculated next time we render. + //! Bounds will need to be recalculated next time we render. void SetBoundsDirty(); - /// Is this manipulator currently registered with a manipulator manager. + //! Is this manipulator currently registered with a manipulator manager. bool Registered() const { - return m_manipulatorId != InvalidManipulatorId && - m_manipulatorManagerId != InvalidManipulatorManagerId; + return m_manipulatorId != InvalidManipulatorId && m_manipulatorManagerId != InvalidManipulatorManagerId; } - /// Is the manipulator in the middle of an action (between mouse down and mouse up). - bool PerformingAction() const { return m_performingAction; } + //! Is the manipulator in the middle of an action (between mouse down and mouse up). + bool PerformingAction() const + { + return m_performingAction; + } - /// Is the mouse currently over the manipulator (intersecting manipulator bound). - bool MouseOver() const { return m_mouseOver; } + //! Is the mouse currently over the manipulator (intersecting manipulator bound). + bool MouseOver() const + { + return m_mouseOver; + } - /// The unique id of this manipulator. - ManipulatorId GetManipulatorId() const { return m_manipulatorId; } + //! The unique id of this manipulator. + ManipulatorId GetManipulatorId() const + { + return m_manipulatorId; + } - /// The unique id of the manager this manipulator was registered with. - ManipulatorManagerId GetManipulatorManagerId() const { return m_manipulatorManagerId; } + //! The unique id of the manager this manipulator was registered with. + ManipulatorManagerId GetManipulatorManagerId() const + { + return m_manipulatorManagerId; + } - /// Returns all EntityComponentIdPairs associated with this manipulator. + //! Returns all EntityComponentIdPairs associated with this manipulator. const EntityComponentIds& EntityComponentIdPairs() const { return m_entityComponentIdPairs; } - /// Add an entity and component the manipulator is responsible for. + //! Add an entity and component the manipulator is responsible for. void AddEntityComponentIdPair(const AZ::EntityComponentIdPair& entityComponentIdPair); - /// Remove an entity from being affected by this manipulator. - /// @note All components on this entity registered with the manipulator will be removed. + //! Remove an entity from being affected by this manipulator. + //! @note All components on this entity registered with the manipulator will be removed. EntityComponentIds::iterator RemoveEntityId(AZ::EntityId entityId); - /// Remove a specific component (via a EntityComponentIdPair) being affected by this manipulator. + //! Remove a specific component (via a EntityComponentIdPair) being affected by this manipulator. EntityComponentIds::iterator RemoveEntityComponentIdPair(const AZ::EntityComponentIdPair& entityComponentIdPair); - /// Is this entity currently being tracked by this manipulator. + //! Is this entity currently being tracked by this manipulator. bool HasEntityId(AZ::EntityId entityId) const; - /// Is this entity component pair currently being tracked by this manipulator. + //! Is this entity component pair currently being tracked by this manipulator. bool HasEntityComponentIdPair(const AZ::EntityComponentIdPair& entityComponentIdPair) const; - /// Forward a mouse over event in a case where we need the manipulator to immediately refresh. - /// @note Only call this when a mouse over event has just happened. + //! Forward a mouse over event in a case where we need the manipulator to immediately refresh. + //! @note Only call this when a mouse over event has just happened. void ForwardMouseOverEvent(const ViewportInteraction::MouseInteraction& interaction); static const AZ::Color s_defaultMouseOverColor; protected: - /// Protected constructor. + //! Protected constructor. BaseManipulator() = default; - /// Called when unregistering - users of manipulators should not call it directly. + //! Called when unregistering - users of manipulators should not call it directly. void Invalidate(); - /// The implementation to override in a derived class for Invalidate. - virtual void InvalidateImpl() {} + //! The implementation to override in a derived class for Invalidate. + virtual void InvalidateImpl() + { + } - /// The implementation to override in a derived class for OnLeftMouseDown. - /// Note: When implementing this function you must also call AttachLeftMouseDownImpl to ensure - /// m_onLeftMouseDownImpl is set to OnLeftMouseDownImpl, otherwise it will not be called - virtual void OnLeftMouseDownImpl( - const ViewportInteraction::MouseInteraction& /*interaction*/, float /*rayIntersectionDistance*/) {} - void AttachLeftMouseDownImpl() { m_onLeftMouseDownImpl = &BaseManipulator::OnLeftMouseDownImpl; } + //! The implementation to override in a derived class for OnLeftMouseDown. + //! Note: When implementing this function you must also call AttachLeftMouseDownImpl to ensure + //! m_onLeftMouseDownImpl is set to OnLeftMouseDownImpl, otherwise it will not be called + virtual void OnLeftMouseDownImpl(const ViewportInteraction::MouseInteraction& /*interaction*/, float /*rayIntersectionDistance*/) + { + } - /// The implementation to override in a derived class for OnRightMouseDown. - /// Note: When implementing this function you must also call AttachRightMouseDownImpl to ensure - /// m_onRightMouseDownImpl is set to OnRightMouseDownImpl, otherwise it will not be called - virtual void OnRightMouseDownImpl( - const ViewportInteraction::MouseInteraction& /*interaction*/, float /*rayIntersectionDistance*/) {} - void AttachRightMouseDownImpl() { m_onRightMouseDownImpl = &BaseManipulator::OnRightMouseDownImpl; } + void AttachLeftMouseDownImpl() + { + m_onLeftMouseDownImpl = &BaseManipulator::OnLeftMouseDownImpl; + } - /// The implementation to override in a derived class for OnLeftMouseUp. - virtual void OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& /*interaction*/) {} + //! The implementation to override in a derived class for OnRightMouseDown. + //! Note: When implementing this function you must also call AttachRightMouseDownImpl to ensure + //! m_onRightMouseDownImpl is set to OnRightMouseDownImpl, otherwise it will not be called + virtual void OnRightMouseDownImpl(const ViewportInteraction::MouseInteraction& /*interaction*/, float /*rayIntersectionDistance*/) + { + } - /// The implementation to override in a derived class for OnRightMouseUp. - virtual void OnRightMouseUpImpl(const ViewportInteraction::MouseInteraction& /*interaction*/) {} + void AttachRightMouseDownImpl() + { + m_onRightMouseDownImpl = &BaseManipulator::OnRightMouseDownImpl; + } - /// The implementation to override in a derived class for OnMouseMove. - virtual void OnMouseMoveImpl(const ViewportInteraction::MouseInteraction& /*interaction*/) {} + //! The implementation to override in a derived class for OnLeftMouseUp. + virtual void OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& /*interaction*/) + { + } - /// The implementation to override in a derived class for OnMouseOver. - virtual void OnMouseOverImpl( - ManipulatorId /*manipulatorId*/, const ViewportInteraction::MouseInteraction& /*interaction*/) {} + //! The implementation to override in a derived class for OnRightMouseUp. + virtual void OnRightMouseUpImpl(const ViewportInteraction::MouseInteraction& /*interaction*/) + { + } - /// The implementation to override in a derived class for OnMouseWheel. - virtual void OnMouseWheelImpl(const ViewportInteraction::MouseInteraction& /*interaction*/) {} + //! The implementation to override in a derived class for OnMouseMove. + virtual void OnMouseMoveImpl(const ViewportInteraction::MouseInteraction& /*interaction*/) + { + } - /// The implementation to override in a derived class for SetBoundsDirty. - virtual void SetBoundsDirtyImpl() {} + //! The implementation to override in a derived class for OnMouseOver. + virtual void OnMouseOverImpl(ManipulatorId /*manipulatorId*/, const ViewportInteraction::MouseInteraction& /*interaction*/) + { + } - /// Rendering for the manipulator - it is recommended drawing be delegated to a ManipulatorView. + //! The implementation to override in a derived class for OnMouseWheel. + virtual void OnMouseWheelImpl(const ViewportInteraction::MouseInteraction& /*interaction*/) + { + } + + //! The implementation to override in a derived class for SetBoundsDirty. + virtual void SetBoundsDirtyImpl() + { + } + + //! Rendering for the manipulator - it is recommended drawing be delegated to a ManipulatorView. virtual void Draw( const ManipulatorManagerState& managerState, AzFramework::DebugDisplayRequests& debugDisplay, @@ -202,39 +243,39 @@ namespace AzToolsFramework private: friend class ManipulatorManager; - AZStd::unordered_set m_entityComponentIdPairs; ///< The entities this manipulator is associated with. + AZStd::unordered_set m_entityComponentIdPairs; //!< The entities this manipulator is associated with. - ManipulatorId m_manipulatorId = InvalidManipulatorId; ///< The unique id of this manipulator. - ManipulatorManagerId m_manipulatorManagerId = InvalidManipulatorManagerId; ///< The manager this manipulator was registered with. - UndoSystem::URSequencePoint* m_undoBatch = nullptr; ///< Undo active while mouse is pressed. - bool m_performingAction = false; ///< After mouse down and before mouse up. - bool m_mouseOver = false; ///< Is the mouse pointer over the manipulator bound. + ManipulatorId m_manipulatorId = InvalidManipulatorId; //!< The unique id of this manipulator. + ManipulatorManagerId m_manipulatorManagerId = InvalidManipulatorManagerId; //!< The manager this manipulator was registered with. + UndoSystem::URSequencePoint* m_undoBatch = nullptr; //!< Undo active while mouse is pressed. + bool m_performingAction = false; //!< After mouse down and before mouse up. + bool m_mouseOver = false; //!< Is the mouse pointer over the manipulator bound. - /// Member function pointers to OnLeftMouseDownImpl and OnRightMouseDownImpl. - /// Set in AttachLeft/RightMouseDownImpl. + //! Member function pointers to OnLeftMouseDownImpl and OnRightMouseDownImpl. + //! Set in AttachLeft/RightMouseDownImpl. void (BaseManipulator::*m_onLeftMouseDownImpl)( const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) = nullptr; void (BaseManipulator::*m_onRightMouseDownImpl)( const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) = nullptr; - /// Update the mouseOver state for this manipulator. + //! Update the mouseOver state for this manipulator. void UpdateMouseOver(ManipulatorId manipulatorId); - /// Manage correctly ending the undo batch. + //! Manage correctly ending the undo batch. void EndUndoBatch(); - /// Record an action as having started. + //! Record an action as having started. void BeginAction(); - /// Record an action as having stopped. + //! Record an action as having stopped. void EndAction(); - /// Let other systems (UI) know that a component property has been modified by a manipulator. + //! Let other systems (UI) know that a component property has been modified by a manipulator. void NotifyEntityComponentPropertyChanged(); }; - /// Base class to be used when composing aggregate manipulator types - wraps some - /// common functionality all manipulators need. + //! Base class to be used when composing aggregate manipulator types - wraps some + //! common functionality all manipulators need. class Manipulators { public: @@ -249,8 +290,10 @@ namespace AzToolsFramework bool PerformingAction(); bool Registered(); - /// Refresh the Manipulator and/or View based on the current view position. - virtual void RefreshView(const AZ::Vector3& /*worldViewPosition*/) {} + //! Refresh the Manipulator and/or View based on the current view position. + virtual void RefreshView(const AZ::Vector3& /*worldViewPosition*/) + { + } const AZ::Transform& GetLocalTransform() const; const AZ::Transform& GetSpace() const; @@ -262,39 +305,59 @@ namespace AzToolsFramework void SetNonUniformScale(const AZ::Vector3& nonUniformScale); protected: - /// Common processing for base manipulator type - Implement for all - /// individual manipulators used in an aggregate manipulator. + //! Common processing for base manipulator type - Implement for all + //! individual manipulators used in an aggregate manipulator. virtual void ProcessManipulators(const AZStd::function&) = 0; - ///@{ - /// Allows implementers to perform additional logic when updating the location of the manipulator group. - virtual void SetSpaceImpl([[maybe_unused]] const AZ::Transform& worldFromLocal) {} - virtual void SetLocalTransformImpl([[maybe_unused]] const AZ::Transform& localTransform) {} - virtual void SetLocalPositionImpl([[maybe_unused]] const AZ::Vector3& localPosition) {} - virtual void SetLocalOrientationImpl([[maybe_unused]] const AZ::Quaternion& localOrientation) {} - virtual void SetNonUniformScaleImpl([[maybe_unused]] const AZ::Vector3& nonUniformScale) {} - ///@} + //!@{ + //! Allows implementers to perform additional logic when updating the location of the manipulator group. + virtual void SetSpaceImpl([[maybe_unused]] const AZ::Transform& worldFromLocal) + { + } - ManipulatorSpaceWithLocalTransform m_manipulatorSpaceWithLocalTransform; ///< The space and local transform for the manipulators. + virtual void SetLocalTransformImpl([[maybe_unused]] const AZ::Transform& localTransform) + { + } + + virtual void SetLocalPositionImpl([[maybe_unused]] const AZ::Vector3& localPosition) + { + } + + virtual void SetLocalOrientationImpl([[maybe_unused]] const AZ::Quaternion& localOrientation) + { + } + + virtual void SetNonUniformScaleImpl([[maybe_unused]] const AZ::Vector3& nonUniformScale) + { + } + //!@} + + ManipulatorSpaceWithLocalTransform m_manipulatorSpaceWithLocalTransform; //!< The space and local transform for the manipulators. }; namespace Internal { - /// This helper function calculates the intersecting point between a ray and a plane. - /// @param rayOrigin The origin of the ray to test. - /// @param rayDirection The direction of the ray to test. - /// @param maxRayLength - /// @param pointOnPlane A point on the plane. - /// @param planeNormal The normal vector of the plane. - /// @param[out] resultIntersectingPoint This stores the result intersecting point. It will be left unchanged - /// if there is no intersection between the ray and the plane. - /// @return Was there an intersection - bool CalculateRayPlaneIntersectingPoint(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, - const AZ::Vector3& pointOnPlane, const AZ::Vector3& planeNormal, AZ::Vector3& resultIntersectingPoint); + //! This helper function calculates the intersecting point between a ray and a plane. + //! @param rayOrigin The origin of the ray to test. + //! @param rayDirection The direction of the ray to test. + //! @param maxRayLength The maximum length of the ray to test. + //! @param pointOnPlane A point on the plane. + //! @param planeNormal The normal vector of the plane. + //! @param[out] resultIntersectingPoint This stores the result intersecting point. It will be left unchanged + //! if there is no intersection between the ray and the plane. + //! @return Was there an intersection + bool CalculateRayPlaneIntersectingPoint( + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, + const AZ::Vector3& pointOnPlane, + const AZ::Vector3& planeNormal, + AZ::Vector3& resultIntersectingPoint); - /// Returns startLocalHitPosition if currentLocalHitPosition is further away than the camera's far clip plane. + //! Returns startLocalHitPosition if currentLocalHitPosition is further away than the camera's far clip plane. AZ::Vector3 TryConstrainHitPositionToView( - const AZ::Vector3& currentLocalHitPosition, const AZ::Vector3& startLocalHitPosition, - const AZ::Transform& localFromWorld, const AzFramework::CameraState& cameraState); - } + const AZ::Vector3& currentLocalHitPosition, + const AZ::Vector3& startLocalHitPosition, + const AZ::Transform& localFromWorld, + const AzFramework::CameraState& cameraState); + } // namespace Internal } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h index 05da73fa20..69920f5f52 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -21,31 +21,30 @@ namespace AZ namespace AzToolsFramework { - /// Interface for handling box manipulator requests. - /// Used by \ref BoxComponentMode. - class BoxManipulatorRequests - : public AZ::EntityComponentBus + //! Interface for handling box manipulator requests. + //! Used by \ref BoxComponentMode. + class BoxManipulatorRequests : public AZ::EntityComponentBus { public: - /// Get the X/Y/Z dimensions of the box shape/collider. + //! Get the X/Y/Z dimensions of the box shape/collider. virtual AZ::Vector3 GetDimensions() = 0; - /// Set the X/Y/Z dimensions of the box shape/collider. + //! Set the X/Y/Z dimensions of the box shape/collider. virtual void SetDimensions(const AZ::Vector3& dimensions) = 0; - /// Get the transform of the box shape/collider. - /// This is used by \ref BoxComponentMode instead of the \ref \AZ::TransformBus - /// because a collider may have an additional translation/orientation offset from - /// the Entity transform. + //! Get the transform of the box shape/collider. + //! This is used by \ref BoxComponentMode instead of the \ref \AZ::TransformBus + //! because a collider may have an additional translation/orientation offset from + //! the Entity transform. virtual AZ::Transform GetCurrentTransform() = 0; - /// Get the scale currently applied to the box. - /// With the Box Shape, the largest x/y/z component is taken - /// so scale is always uniform, with colliders the scale may - /// be different per component. + //! Get the scale currently applied to the box. + //! With the Box Shape, the largest x/y/z component is taken + //! so scale is always uniform, with colliders the scale may + //! be different per component. virtual AZ::Vector3 GetBoxScale() = 0; protected: ~BoxManipulatorRequests() = default; }; - /// Type to inherit to implement BoxManipulatorRequests + //! Type to inherit to implement BoxManipulatorRequests using BoxManipulatorRequestBus = AZ::EBus; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp index 55a8464ba6..c8be488c91 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "EditorVertexSelection.h" @@ -16,10 +16,10 @@ #include #include #include -#include #include -#include #include +#include +#include #include #include #include @@ -37,7 +37,7 @@ using Vertex3LookupReverseIter = namespace std { - template <> + template<> struct iterator_traits { using difference_type = typename Vertex2LookupReverseIter::difference_type; @@ -47,7 +47,7 @@ namespace std using reference = typename Vertex2LookupReverseIter::reference; }; - template <> + template<> struct iterator_traits { using difference_type = typename Vertex3LookupReverseIter::difference_type; @@ -56,7 +56,7 @@ namespace std using pointer = typename Vertex3LookupReverseIter::pointer; using reference = typename Vertex3LookupReverseIter::reference; }; -} +} // namespace std namespace AzToolsFramework { @@ -73,14 +73,11 @@ namespace AzToolsFramework OnEntityComponentPropertyChanged(entityComponentIdPair); // ensure property grid values are refreshed - ToolsApplicationNotificationBus::Broadcast( - &ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, - Refresh_EntireTree); + ToolsApplicationNotificationBus::Broadcast(&ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_EntireTree); } template - bool EditorVertexSelectionBase::HandleMouse( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction) + bool EditorVertexSelectionBase::HandleMouse(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { m_editorBoxSelect.HandleMouseInteraction(mouseInteraction); @@ -115,18 +112,17 @@ namespace AzToolsFramework } template - void EditorVertexSelectionBase::SnapVerticesToTerrain( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction) + void EditorVertexSelectionBase::SnapVerticesToTerrain(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { ScopedUndoBatch surfaceSnapUndo("Snap to Surface"); ScopedUndoBatch::MarkEntityDirty(GetEntityId()); const int viewportId = mouseInteraction.m_mouseInteraction.m_interactionId.m_viewportId; // get unsnapped terrain position (world space) - AZ::Vector3 worldSurfacePosition = AZ::Vector3::CreateZero();; + AZ::Vector3 worldSurfacePosition = AZ::Vector3::CreateZero(); + ; ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( - worldSurfacePosition, viewportId, - &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, + worldSurfacePosition, viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates); AZ::Transform worldFromLocal; @@ -136,8 +132,7 @@ namespace AzToolsFramework // convert to local space - snap if enabled const GridSnapParameters gridSnapParams = GridSnapSettings(viewportId); const AZ::Vector3 localFinalSurfacePosition = gridSnapParams.m_gridSnap - ? CalculateSnappedTerrainPosition( - worldSurfacePosition, worldFromLocal, viewportId, gridSnapParams.m_gridSize) + ? CalculateSnappedTerrainPosition(worldSurfacePosition, worldFromLocal, viewportId, gridSnapParams.m_gridSize) : localFromWorld.TransformPoint(worldSurfacePosition); SetSelectedPosition(localFinalSurfacePosition); @@ -145,17 +140,16 @@ namespace AzToolsFramework OnEntityComponentPropertyChanged(GetEntityComponentIdPair()); // ensure property grid values are refreshed - ToolsApplicationNotificationBus::Broadcast( - &ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, - Refresh_Values); + ToolsApplicationNotificationBus::Broadcast(&ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); } - /// Iterate over all vertices currently associated with the translation manipulator and update their - /// positions by taking their starting positions and modifying them by an offset. + // iterate over all vertices currently associated with the translation manipulator and update their + // positions by taking their starting positions and modifying them by an offset. template void EditorVertexSelectionBase::UpdateManipulatorsAndVerticesFromOffset( IndexedTranslationManipulator& translationManipulator, - const AZ::Vector3& localManipulatorStartPosition, const AZ::Vector3& localManipulatorOffset) + const AZ::Vector3& localManipulatorStartPosition, + const AZ::Vector3& localManipulatorOffset) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -164,22 +158,19 @@ namespace AzToolsFramework AZ::FixedVerticesRequestBus::Bind(fixedVertices, GetEntityId()); translationManipulator.Process( - [this, localManipulatorOffset, fixedVertices] - (typename IndexedTranslationManipulator::VertexLookup& vertex) - { - vertex.m_offset = AZ::AdaptVertexIn(localManipulatorOffset); + [this, localManipulatorOffset, fixedVertices](typename IndexedTranslationManipulator::VertexLookup& vertex) + { + vertex.m_offset = AZ::AdaptVertexIn(localManipulatorOffset); - bool updated = false; - const Vertex vertexPosition = vertex.m_start + vertex.m_offset; - AZ::FixedVerticesRequestBus::EventResult( - updated, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::UpdateVertex, - vertex.m_index, vertexPosition); + bool updated = false; + const Vertex vertexPosition = vertex.m_start + vertex.m_offset; + AZ::FixedVerticesRequestBus::EventResult( + updated, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::UpdateVertex, vertex.m_index, vertexPosition); - m_selectionManipulators[vertex.m_index]->SetLocalPosition(AZ::AdaptVertexOut(vertexPosition)); - }); + m_selectionManipulators[vertex.m_index]->SetLocalPosition(AZ::AdaptVertexOut(vertexPosition)); + }); - m_translationManipulator->m_manipulator.SetLocalPosition( - localManipulatorStartPosition + localManipulatorOffset); + m_translationManipulator->m_manipulator.SetLocalPosition(localManipulatorStartPosition + localManipulatorOffset); // after vertex positions have changed, anything else which relies on their positions may update if (m_onVertexPositionsUpdated) @@ -188,11 +179,10 @@ namespace AzToolsFramework } } - /// In OnMouseDown for various manipulators (linear/planar/surface), ensure we record the vertex starting position - /// for each vertex associated with the translation manipulator to use with offset calculations when updating. + // in OnMouseDown for various manipulators (linear/planar/surface), ensure we record the vertex starting position + // for each vertex associated with the translation manipulator to use with offset calculations when updating. template - void InitializeVertexLookup( - IndexedTranslationManipulator& translationManipulator, const AZ::EntityId entityId) + void InitializeVertexLookup(IndexedTranslationManipulator& translationManipulator, const AZ::EntityId entityId) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -201,29 +191,28 @@ namespace AzToolsFramework AZ::FixedVerticesRequestBus::Bind(fixedVertices, entityId); translationManipulator.Process( - [fixedVertices] - (typename IndexedTranslationManipulator::VertexLookup& vertexLookup) - { - Vertex vertex; - bool found = false; - AZ::FixedVerticesRequestBus::EventResult( - found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, - vertexLookup.m_index, vertex); - - if (found) + [fixedVertices](typename IndexedTranslationManipulator::VertexLookup& vertexLookup) { - vertexLookup.m_start = vertex; - vertexLookup.m_offset = Vertex::CreateZero(); - } - }); + Vertex vertex; + bool found = false; + AZ::FixedVerticesRequestBus::EventResult( + found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, vertexLookup.m_index, vertex); + + if (found) + { + vertexLookup.m_start = vertex; + vertexLookup.m_offset = Vertex::CreateZero(); + } + }); } - /// Create a translation manipulator for a specific vertex and setup its corresponding callbacks etc. + // create a translation manipulator for a specific vertex and setup its corresponding callbacks etc. template void EditorVertexSelectionBase::CreateTranslationManipulator( const AZ::EntityComponentIdPair& entityComponentIdPair, const ManipulatorManagerId managerId, - const Vertex& vertex, size_t vertexIndex) + const Vertex& vertex, + size_t vertexIndex) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -250,65 +239,65 @@ namespace AzToolsFramework // linear manipulator callbacks m_translationManipulator->m_manipulator.InstallLinearManipulatorMouseDownCallback( [this]([[maybe_unused]] const LinearManipulator::Action& action) - { - BeginBatchMovement(); - InitializeVertexLookup(*m_translationManipulator, GetEntityId()); - }); + { + BeginBatchMovement(); + InitializeVertexLookup(*m_translationManipulator, GetEntityId()); + }); m_translationManipulator->m_manipulator.InstallLinearManipulatorMouseMoveCallback( [this](const LinearManipulator::Action& action) - { - UpdateManipulatorsAndVerticesFromOffset( - *m_translationManipulator, action.m_start.m_localPosition, action.LocalPositionOffset()); - }); + { + UpdateManipulatorsAndVerticesFromOffset( + *m_translationManipulator, action.m_start.m_localPosition, action.LocalPositionOffset()); + }); m_translationManipulator->m_manipulator.InstallLinearManipulatorMouseUpCallback( [this]([[maybe_unused]] const LinearManipulator::Action& action) - { - EndBatchMovement(); - }); + { + EndBatchMovement(); + }); // planar manipulator callbacks m_translationManipulator->m_manipulator.InstallPlanarManipulatorMouseDownCallback( [this]([[maybe_unused]] const PlanarManipulator::Action& action) - { - BeginBatchMovement(); - InitializeVertexLookup(*m_translationManipulator, GetEntityId()); - }); + { + BeginBatchMovement(); + InitializeVertexLookup(*m_translationManipulator, GetEntityId()); + }); m_translationManipulator->m_manipulator.InstallPlanarManipulatorMouseMoveCallback( [this](const PlanarManipulator::Action& action) - { - UpdateManipulatorsAndVerticesFromOffset( - *m_translationManipulator, action.m_start.m_localPosition, action.LocalPositionOffset()); - }); + { + UpdateManipulatorsAndVerticesFromOffset( + *m_translationManipulator, action.m_start.m_localPosition, action.LocalPositionOffset()); + }); m_translationManipulator->m_manipulator.InstallPlanarManipulatorMouseUpCallback( [this]([[maybe_unused]] const PlanarManipulator::Action& action) - { - EndBatchMovement(); - }); + { + EndBatchMovement(); + }); // surface manipulator callbacks m_translationManipulator->m_manipulator.InstallSurfaceManipulatorMouseDownCallback( [this]([[maybe_unused]] const SurfaceManipulator::Action& action) - { - BeginBatchMovement(); - InitializeVertexLookup(*m_translationManipulator, GetEntityId()); - }); + { + BeginBatchMovement(); + InitializeVertexLookup(*m_translationManipulator, GetEntityId()); + }); m_translationManipulator->m_manipulator.InstallSurfaceManipulatorMouseMoveCallback( [this](const SurfaceManipulator::Action& action) - { - UpdateManipulatorsAndVerticesFromOffset( - *m_translationManipulator, action.m_start.m_localPosition, action.LocalPositionOffset()); - }); + { + UpdateManipulatorsAndVerticesFromOffset( + *m_translationManipulator, action.m_start.m_localPosition, action.LocalPositionOffset()); + }); m_translationManipulator->m_manipulator.InstallSurfaceManipulatorMouseUpCallback( [this]([[maybe_unused]] const SurfaceManipulator::Action& action) - { - EndBatchMovement(); - }); + { + EndBatchMovement(); + }); // register the m_translation manipulator so it appears where the selection manipulator previously was m_translationManipulator->m_manipulator.Register(managerId); @@ -330,9 +319,9 @@ namespace AzToolsFramework AZStd::transform( vertexLookups.begin(), vertexLookups.end(), AZStd::back_inserter(vertexIndices), [](const typename IndexedTranslationManipulator::VertexLookup& vertexLookup) - { - return vertexLookup.m_index; - }); + { + return vertexLookup.m_index; + }); return vertexIndices; } @@ -348,12 +337,13 @@ namespace AzToolsFramework bool m_additive = true; // is the box select adding or removing things from the selection }; - template void DoBoxSelect( - const AZ::EntityId entityId, BoxSelectData& boxSelectData, + const AZ::EntityId entityId, + BoxSelectData& boxSelectData, const ViewportInteraction::KeyboardModifiers keyboardModifiers, - const int viewportId, const EditorBoxSelect& editorBoxSelect, + const int viewportId, + const EditorBoxSelect& editorBoxSelect, const AZStd::vector>& selectionManipulators) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -384,8 +374,7 @@ namespace AzToolsFramework if (editorBoxSelect.BoxRegion()) { AZ::Transform worldFromLocal; - AZ::TransformBus::EventResult( - worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); // bind FixedVerticesRequestBus for improved performance typename AZ::FixedVerticesRequestBus::BusPtr fixedVertices; @@ -396,8 +385,7 @@ namespace AzToolsFramework Vertex localVertex; bool found = false; AZ::FixedVerticesRequestBus::EventResult( - found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, - vertexIndex, localVertex); + found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, vertexIndex, localVertex); const AZ::Vector3 worldVertex = worldFromLocal.TransformPoint(AZ::AdaptVertexOut(localVertex)); const AzFramework::ScreenPoint screenPosition = GetScreenPosition(viewportId, worldVertex); @@ -406,8 +394,8 @@ namespace AzToolsFramework if (editorBoxSelect.BoxRegion()->contains(ViewportInteraction::QPointFromScreenPoint(screenPosition))) { // see if vertexIndex is in active selection - auto vertexIt = AZStd::find( - boxSelectData.m_activeSelection.begin(), boxSelectData.m_activeSelection.end(), vertexIndex); + auto vertexIt = + AZStd::find(boxSelectData.m_activeSelection.begin(), boxSelectData.m_activeSelection.end(), vertexIndex); if (!keyboardModifiers.Ctrl()) { @@ -437,8 +425,8 @@ namespace AzToolsFramework else { // not in box region - see if vertexIndex is in delta selection - auto vertexItDelta = AZStd::find( - boxSelectData.m_deltaSelection.begin(), boxSelectData.m_deltaSelection.end(), vertexIndex); + auto vertexItDelta = + AZStd::find(boxSelectData.m_deltaSelection.begin(), boxSelectData.m_deltaSelection.end(), vertexIndex); // if we find the vertex in the delta selection if (vertexItDelta != boxSelectData.m_deltaSelection.end()) @@ -451,8 +439,8 @@ namespace AzToolsFramework boxSelectData.m_deltaSelection.erase(vertexItDelta); // remove the vertex from the active selection as well - auto vertexItStart = AZStd::find( - boxSelectData.m_activeSelection.begin(), boxSelectData.m_activeSelection.end(), vertexIndex); + auto vertexItStart = + AZStd::find(boxSelectData.m_activeSelection.begin(), boxSelectData.m_activeSelection.end(), vertexIndex); if (vertexItStart != boxSelectData.m_activeSelection.end()) { @@ -467,8 +455,8 @@ namespace AzToolsFramework boxSelectData.m_deltaSelection.erase(vertexItDelta); // also add it back to the active selection - auto vertexItStart = AZStd::find( - boxSelectData.m_activeSelection.begin(), boxSelectData.m_activeSelection.end(), vertexIndex); + auto vertexItStart = + AZStd::find(boxSelectData.m_activeSelection.begin(), boxSelectData.m_activeSelection.end(), vertexIndex); if (vertexItStart == boxSelectData.m_activeSelection.end()) { @@ -491,7 +479,8 @@ namespace AzToolsFramework template void EditorVertexSelectionBase::Create( - const AZ::EntityComponentIdPair& entityComponentIdPair, const ManipulatorManagerId managerId, + const AZ::EntityComponentIdPair& entityComponentIdPair, + const ManipulatorManagerId managerId, AZStd::unique_ptr hoverSelection, const TranslationManipulators::Dimensions dimensions, const TranslationManipulatorConfiguratorFn translationManipulatorConfigurator) @@ -509,8 +498,7 @@ namespace AzToolsFramework AZ::FixedVerticesRequestBus::Bind(fixedVertices, GetEntityId()); size_t vertexCount = 0; - AZ::FixedVerticesRequestBus::EventResult( - vertexCount, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::Size); + AZ::FixedVerticesRequestBus::EventResult(vertexCount, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::Size); m_selectionManipulators.reserve(vertexCount); // initialize manipulators for all spline vertices @@ -519,12 +507,10 @@ namespace AzToolsFramework Vertex vertex; bool found = false; AZ::FixedVerticesRequestBus::EventResult( - found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, - vertexIndex, vertex); + found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, vertexIndex, vertex); - m_selectionManipulators.push_back(SelectionManipulator::MakeShared( - WorldFromLocalWithUniformScale(GetEntityId()), - GetNonUniformScale(GetEntityId()))); + m_selectionManipulators.push_back( + SelectionManipulator::MakeShared(WorldFromLocalWithUniformScale(GetEntityId()), GetNonUniformScale(GetEntityId()))); const auto& selectionManipulator = m_selectionManipulators.back(); selectionManipulator->Register(managerId); @@ -539,156 +525,153 @@ namespace AzToolsFramework m_editorBoxSelect.InstallLeftMouseDown( [this, vertexBoxSelectData](const ViewportInteraction::MouseInteractionEvent& /*mouseInteraction*/) - { - // grab currently selected entities (the starting selection) - vertexBoxSelectData->m_startSelection = m_translationManipulator - ? MapFromLookupsToIndices(m_translationManipulator->m_vertices) - : AZStd::vector(); + { + // grab currently selected entities (the starting selection) + vertexBoxSelectData->m_startSelection = m_translationManipulator + ? MapFromLookupsToIndices(m_translationManipulator->m_vertices) + : AZStd::vector(); - // active selection is the same as start selection on mouse down - vertexBoxSelectData->m_activeSelection = vertexBoxSelectData->m_startSelection; + // active selection is the same as start selection on mouse down + vertexBoxSelectData->m_activeSelection = vertexBoxSelectData->m_startSelection; - size_t size = 0; - AZ::FixedVerticesRequestBus::EventResult( - size, GetEntityId(), &AZ::FixedVerticesRequestBus::Handler::Size); + size_t size = 0; + AZ::FixedVerticesRequestBus::EventResult(size, GetEntityId(), &AZ::FixedVerticesRequestBus::Handler::Size); - // populate vector of all indices in container to compare against - vertexBoxSelectData->m_all.resize(size); - std::iota(vertexBoxSelectData->m_all.begin(), vertexBoxSelectData->m_all.end(), static_cast(0)); - }); + // populate vector of all indices in container to compare against + vertexBoxSelectData->m_all.resize(size); + std::iota(vertexBoxSelectData->m_all.begin(), vertexBoxSelectData->m_all.end(), static_cast(0)); + }); m_editorBoxSelect.InstallMouseMove( [this, vertexBoxSelectData](const ViewportInteraction::MouseInteractionEvent& mouseInteraction) - { - DoBoxSelect( - GetEntityId(), *vertexBoxSelectData, mouseInteraction.m_mouseInteraction.m_keyboardModifiers, - mouseInteraction.m_mouseInteraction.m_interactionId.m_viewportId, - m_editorBoxSelect, m_selectionManipulators); - }); - - m_editorBoxSelect.InstallLeftMouseUp([this, vertexBoxSelectData]() - { - if (vertexBoxSelectData->m_additive) { - // bind FixedVerticesRequestBus for improved performance - typename AZ::FixedVerticesRequestBus::BusPtr fixedVertices; - AZ::FixedVerticesRequestBus::Bind(fixedVertices, GetEntityId()); + DoBoxSelect( + GetEntityId(), *vertexBoxSelectData, mouseInteraction.m_mouseInteraction.m_keyboardModifiers, + mouseInteraction.m_mouseInteraction.m_interactionId.m_viewportId, m_editorBoxSelect, m_selectionManipulators); + }); - const AZ::EntityComponentIdPair entityComponentIdPair = m_entityComponentIdPair; - for (size_t vertexIndex : vertexBoxSelectData->m_deltaSelection) - { - Vertex vertex; - bool found = false; - AZ::FixedVerticesRequestBus::EventResult( - found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, - vertexIndex, vertex); - - // if we already have a translation manipulator, add additional vertices to it - if (m_translationManipulator) - { - // otherwise add the new selected vertex - m_translationManipulator->m_vertices.push_back( - typename IndexedTranslationManipulator::VertexLookup{ vertex, Vertex::CreateZero(), vertexIndex }); - } - else - { - // create a new translation manipulator if one did not already exist with the first vertex - CreateTranslationManipulator(entityComponentIdPair, m_manipulatorManagerId, vertex, vertexIndex); - // default to ensuring selection manipulators are 'selected' - m_selectionManipulators[vertexIndex]->Select(); - } - } - } - else - { - // removing vertices with an active translation manipulator - if (m_translationManipulator) - { - // iterate through all delta vertices (ones that were either - // added or removed during selection) and remove them - for (size_t vertexIndex : vertexBoxSelectData->m_deltaSelection) - { - auto vertexIt = AZStd::find_if( - m_translationManipulator->m_vertices.begin(), m_translationManipulator->m_vertices.end(), - [vertexIndex](const auto& vertexLookup) - { - return vertexLookup.m_index == vertexIndex; - }); - - // remove vertex from translation manipulator - if (vertexIt != m_translationManipulator->m_vertices.end()) - { - m_translationManipulator->m_vertices.erase(vertexIt); - - // ensure it is registered to receive input and draw - if (!m_selectionManipulators[vertexIndex]->Registered()) - { - m_selectionManipulators[vertexIndex]->Register(m_manipulatorManagerId); - } - } - } - - // if we have no vertices left, clear selection (restore all selection - // manipulators and destroy translation manipulator) - if (m_translationManipulator->m_vertices.empty()) - { - ClearSelected(); - } - } - } - - // with a selection of more than one or zero, we want to ensure all selection - // manipulators are registered (can be clicked on) - if (vertexBoxSelectData->m_activeSelection.size() > 1) - { - for (size_t vertexIndex : vertexBoxSelectData->m_activeSelection) - { - if (!m_selectionManipulators[vertexIndex]->Registered()) - { - m_selectionManipulators[vertexIndex]->Register(m_manipulatorManagerId); - } - } - } - // special case handling for only one vertex - don't want to display it when - // translation manipulator will be in exactly the same location - else if (vertexBoxSelectData->m_activeSelection.size() == 1) + m_editorBoxSelect.InstallLeftMouseUp( + [this, vertexBoxSelectData]() { if (vertexBoxSelectData->m_additive) { - m_selectionManipulators[vertexBoxSelectData->m_activeSelection[0]]->Unregister(); + // bind FixedVerticesRequestBus for improved performance + typename AZ::FixedVerticesRequestBus::BusPtr fixedVertices; + AZ::FixedVerticesRequestBus::Bind(fixedVertices, GetEntityId()); + + const AZ::EntityComponentIdPair entityComponentIdPair = m_entityComponentIdPair; + for (size_t vertexIndex : vertexBoxSelectData->m_deltaSelection) + { + Vertex vertex; + bool found = false; + AZ::FixedVerticesRequestBus::EventResult( + found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, vertexIndex, vertex); + + // if we already have a translation manipulator, add additional vertices to it + if (m_translationManipulator) + { + // otherwise add the new selected vertex + m_translationManipulator->m_vertices.push_back( + typename IndexedTranslationManipulator::VertexLookup{ vertex, Vertex::CreateZero(), vertexIndex }); + } + else + { + // create a new translation manipulator if one did not already exist with the first vertex + CreateTranslationManipulator(entityComponentIdPair, m_manipulatorManagerId, vertex, vertexIndex); + // default to ensuring selection manipulators are 'selected' + m_selectionManipulators[vertexIndex]->Select(); + } + } } else { - m_selectionManipulators[vertexBoxSelectData->m_activeSelection[0]]->Register(m_manipulatorManagerId); + // removing vertices with an active translation manipulator + if (m_translationManipulator) + { + // iterate through all delta vertices (ones that were either + // added or removed during selection) and remove them + for (size_t vertexIndex : vertexBoxSelectData->m_deltaSelection) + { + auto vertexIt = AZStd::find_if( + m_translationManipulator->m_vertices.begin(), m_translationManipulator->m_vertices.end(), + [vertexIndex](const auto& vertexLookup) + { + return vertexLookup.m_index == vertexIndex; + }); + + // remove vertex from translation manipulator + if (vertexIt != m_translationManipulator->m_vertices.end()) + { + m_translationManipulator->m_vertices.erase(vertexIt); + + // ensure it is registered to receive input and draw + if (!m_selectionManipulators[vertexIndex]->Registered()) + { + m_selectionManipulators[vertexIndex]->Register(m_manipulatorManagerId); + } + } + } + + // if we have no vertices left, clear selection (restore all selection + // manipulators and destroy translation manipulator) + if (m_translationManipulator->m_vertices.empty()) + { + ClearSelected(); + } + } } - } - // update manipulator positions (ensure translation manipulator is - // centered on current selection) - RefreshTranslationManipulator(); + // with a selection of more than one or zero, we want to ensure all selection + // manipulators are registered (can be clicked on) + if (vertexBoxSelectData->m_activeSelection.size() > 1) + { + for (size_t vertexIndex : vertexBoxSelectData->m_activeSelection) + { + if (!m_selectionManipulators[vertexIndex]->Registered()) + { + m_selectionManipulators[vertexIndex]->Register(m_manipulatorManagerId); + } + } + } + // special case handling for only one vertex - don't want to display it when + // translation manipulator will be in exactly the same location + else if (vertexBoxSelectData->m_activeSelection.size() == 1) + { + if (vertexBoxSelectData->m_additive) + { + m_selectionManipulators[vertexBoxSelectData->m_activeSelection[0]]->Unregister(); + } + else + { + m_selectionManipulators[vertexBoxSelectData->m_activeSelection[0]]->Register(m_manipulatorManagerId); + } + } - // restore state once box select has completed - vertexBoxSelectData->m_startSelection.clear(); - vertexBoxSelectData->m_deltaSelection.clear(); - vertexBoxSelectData->m_activeSelection.clear(); - vertexBoxSelectData->m_all.clear(); - }); + // update manipulator positions (ensure translation manipulator is + // centered on current selection) + RefreshTranslationManipulator(); - m_editorBoxSelect.InstallDisplayScene( - [this, vertexBoxSelectData] - (const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& /*debugDisplay*/) - { - const auto keyboardModifiers = ViewportInteraction::KeyboardModifiers( - ViewportInteraction::TranslateKeyboardModifiers(QApplication::queryKeyboardModifiers())); + // restore state once box select has completed + vertexBoxSelectData->m_startSelection.clear(); + vertexBoxSelectData->m_deltaSelection.clear(); + vertexBoxSelectData->m_activeSelection.clear(); + vertexBoxSelectData->m_all.clear(); + }); - // when modifiers change ensure we refresh box selection for immediate update - if (keyboardModifiers != m_editorBoxSelect.PreviousModifiers()) - { - DoBoxSelect( - GetEntityId(), *vertexBoxSelectData, keyboardModifiers, - viewportInfo.m_viewportId, m_editorBoxSelect, m_selectionManipulators); - } - }); + m_editorBoxSelect.InstallDisplayScene( + [this, vertexBoxSelectData](const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& /*debugDisplay*/) + { + const auto keyboardModifiers = ViewportInteraction::KeyboardModifiers( + ViewportInteraction::TranslateKeyboardModifiers(QApplication::queryKeyboardModifiers())); + + // when modifiers change ensure we refresh box selection for immediate update + if (keyboardModifiers != m_editorBoxSelect.PreviousModifiers()) + { + DoBoxSelect( + GetEntityId(), *vertexBoxSelectData, keyboardModifiers, viewportInfo.m_viewportId, m_editorBoxSelect, + m_selectionManipulators); + } + }); AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(GetEntityId()); AzFramework::ViewportDebugDisplayEventBus::Handler::BusConnect(GetEntityContextId()); @@ -734,12 +717,12 @@ namespace AzToolsFramework { // re-enable all selection manipulators associated with the translation // manipulator which is now being removed. - m_translationManipulator->Process([this]( - typename IndexedTranslationManipulator::VertexLookup& vertex) - { - m_selectionManipulators[vertex.m_index]->Register(m_manipulatorManagerId); - m_selectionManipulators[vertex.m_index]->Deselect(); - }); + m_translationManipulator->Process( + [this](typename IndexedTranslationManipulator::VertexLookup& vertex) + { + m_selectionManipulators[vertex.m_index]->Register(m_manipulatorManagerId); + m_selectionManipulators[vertex.m_index]->Deselect(); + }); m_translationManipulator->m_manipulator.Unregister(); m_translationManipulator.reset(); @@ -755,8 +738,7 @@ namespace AzToolsFramework template void EditorVertexSelectionBase::DisplayEntityViewport( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -767,8 +749,7 @@ namespace AzToolsFramework template void EditorVertexSelectionBase::DisplayViewport2d( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -777,8 +758,7 @@ namespace AzToolsFramework template template::value>::type*> - void EditorVertexSelectionBase::UpdateManipulatorSpace( - const AzFramework::ViewportInfo& viewportInfo) + void EditorVertexSelectionBase::UpdateManipulatorSpace(const AzFramework::ViewportInfo& viewportInfo) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -789,23 +769,19 @@ namespace AzToolsFramework &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::ShowingWorldSpace); // update the manipulator to be in the correct space if it changed - if ( m_translationManipulator - && !m_translationManipulator->m_manipulator.PerformingAction() - && worldSpace != m_worldSpace) + if (m_translationManipulator && !m_translationManipulator->m_manipulator.PerformingAction() && worldSpace != m_worldSpace) { const AZ::Transform worldFromLocal = WorldFromLocalWithUniformScale(GetEntityId()); - m_translationManipulator->m_manipulator.SetLocalOrientation(worldSpace - ? QuaternionFromTransformNoScaling(worldFromLocal).GetInverseFull() - : AZ::Quaternion::CreateIdentity()); + m_translationManipulator->m_manipulator.SetLocalOrientation( + worldSpace ? QuaternionFromTransformNoScaling(worldFromLocal).GetInverseFull() : AZ::Quaternion::CreateIdentity()); m_worldSpace = worldSpace; } } template template::value>::type*> - void EditorVertexSelectionBase::UpdateManipulatorSpace( - const AzFramework::ViewportInfo& /*viewportInfo*/) const + void EditorVertexSelectionBase::UpdateManipulatorSpace(const AzFramework::ViewportInfo& /*viewportInfo*/) const { } @@ -813,8 +789,7 @@ namespace AzToolsFramework static bool CanDeleteSelection(const AZ::EntityId entityId, const int64_t selectedCount) { size_t vertexCount = 0; - AZ::VariableVerticesRequestBus::EventResult( - vertexCount, entityId, &AZ::VariableVerticesRequestBus::Handler::Size); + AZ::VariableVerticesRequestBus::EventResult(vertexCount, entityId, &AZ::VariableVerticesRequestBus::Handler::Size); // prevent deleting all vertices const int64_t remaining = aznumeric_cast(vertexCount) - selectedCount; @@ -825,9 +800,8 @@ namespace AzToolsFramework void EditorVertexSelectionVariable::ShowVertexDeletionWarning() { QMessageBox::information( - AzToolsFramework::GetActiveWindow(), "Information", - "It is not possible to delete all vertices.", - QMessageBox::Ok, QMessageBox::NoButton); + AzToolsFramework::GetActiveWindow(), "Information", "It is not possible to delete all vertices.", QMessageBox::Ok, + QMessageBox::NoButton); } template @@ -856,19 +830,19 @@ namespace AzToolsFramework EditorVertexSelectionBase::m_translationManipulator; // ensure we remove vertices in reverse order - std::sort(translationManipulator->m_vertices.rbegin(), translationManipulator->m_vertices.rend(), + std::sort( + translationManipulator->m_vertices.rbegin(), translationManipulator->m_vertices.rend(), [](const typename IndexedTranslationManipulator::VertexLookup& lhs, - const typename IndexedTranslationManipulator::VertexLookup& rhs) - { - return lhs.m_index < rhs.m_index; - }); + const typename IndexedTranslationManipulator::VertexLookup& rhs) + { + return lhs.m_index < rhs.m_index; + }); - translationManipulator->Process([this]( - typename IndexedTranslationManipulator::VertexLookup& vertex) - { - SafeRemoveVertex( - EditorVertexSelectionBase::GetEntityComponentIdPair(), vertex.m_index); - }); + translationManipulator->Process( + [this](typename IndexedTranslationManipulator::VertexLookup& vertex) + { + SafeRemoveVertex(EditorVertexSelectionBase::GetEntityComponentIdPair(), vertex.m_index); + }); translationManipulator->m_manipulator.Unregister(); translationManipulator.reset(); @@ -876,8 +850,7 @@ namespace AzToolsFramework if (EditorVertexSelectionBase::m_hoverSelection) { - EditorVertexSelectionBase::m_hoverSelection->Register( - EditorVertexSelectionBase::GetManipulatorManagerId()); + EditorVertexSelectionBase::m_hoverSelection->Register(EditorVertexSelectionBase::GetManipulatorManagerId()); } EditorVertexSelectionBase::SetState(EditorVertexSelectionBase::State::Selecting); @@ -895,11 +868,9 @@ namespace AzToolsFramework InitializeVertexLookup(*m_translationManipulator, GetEntityId()); // note: AdaptVertexIn/Out is to ensure we clamp the vertex local Z position to 0 if // dealing with Vector2s when setting the position of the manipulator. - const AZ::Vector3 localOffset = - localPosition - m_translationManipulator->m_manipulator.GetLocalTransform().GetTranslation(); + const AZ::Vector3 localOffset = localPosition - m_translationManipulator->m_manipulator.GetLocalTransform().GetTranslation(); UpdateManipulatorsAndVerticesFromOffset( - *m_translationManipulator, - AZ::AdaptVertexOut(AZ::AdaptVertexIn(localPosition)), + *m_translationManipulator, AZ::AdaptVertexOut(AZ::AdaptVertexIn(localPosition)), AZ::AdaptVertexOut(AZ::AdaptVertexIn(localOffset))); RefreshTranslationManipulator(); @@ -928,23 +899,20 @@ namespace AzToolsFramework // calculate average position of selected vertices for translation manipulator MidpointCalculator midpointCalculator; m_translationManipulator->Process( - [this, &midpointCalculator, fixedVertices] - (typename IndexedTranslationManipulator::VertexLookup& vertex) - { - Vertex v; - bool found = false; - AZ::FixedVerticesRequestBus::EventResult( - found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, - vertex.m_index, v); - - if (found) + [this, &midpointCalculator, fixedVertices](typename IndexedTranslationManipulator::VertexLookup& vertex) { - midpointCalculator.AddPosition(AZ::AdaptVertexOut(v)); - } - }); + Vertex v; + bool found = false; + AZ::FixedVerticesRequestBus::EventResult( + found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, vertex.m_index, v); - m_translationManipulator->m_manipulator.SetLocalPosition( - AZ::AdaptVertexOut(midpointCalculator.CalculateMidpoint())); + if (found) + { + midpointCalculator.AddPosition(AZ::AdaptVertexOut(v)); + } + }); + + m_translationManipulator->m_manipulator.SetLocalPosition(AZ::AdaptVertexOut(midpointCalculator.CalculateMidpoint())); } } @@ -970,8 +938,7 @@ namespace AzToolsFramework Vertex vertex; bool found = false; AZ::FixedVerticesRequestBus::EventResult( - found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, - manipulatorIndex, vertex); + found, fixedVertices, &AZ::FixedVerticesRequestBus::Handler::GetVertex, manipulatorIndex, vertex); if (found) { @@ -1037,39 +1004,41 @@ namespace AzToolsFramework } } - /// Handle correctly selecting/deselecting vertices in a vertex selection. + // handle correctly selecting/deselecting vertices in a vertex selection. template void EditorVertexSelectionBase::SelectionManipulatorSelectCallback( - const size_t vertexIndex, const ViewportInteraction::MouseInteraction& interaction, - const AZ::EntityComponentIdPair& entityComponentIdPair, const ManipulatorManagerId managerId) + const size_t vertexIndex, + const ViewportInteraction::MouseInteraction& interaction, + const AZ::EntityComponentIdPair& entityComponentIdPair, + const ManipulatorManagerId managerId) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); Vertex vertex; bool found = false; AZ::FixedVerticesRequestBus::EventResult( - found, GetEntityId(), &AZ::FixedVerticesRequestBus::Handler::GetVertex, - vertexIndex, vertex); + found, GetEntityId(), &AZ::FixedVerticesRequestBus::Handler::GetVertex, vertexIndex, vertex); if (m_translationManipulator != nullptr && interaction.m_keyboardModifiers.Ctrl()) { // ensure all selection manipulators are enabled when selecting more than one (the first // will have been disabled when only selecting an individual vertex - m_translationManipulator->Process([this, managerId]( - typename IndexedTranslationManipulator::VertexLookup& vertexLookup) - { - m_selectionManipulators[vertexLookup.m_index]->Register(managerId); - }); + m_translationManipulator->Process( + [this, managerId](typename IndexedTranslationManipulator::VertexLookup& vertexLookup) + { + m_selectionManipulators[vertexLookup.m_index]->Register(managerId); + }); // if selection manipulator was selected, find it in the vector of vertices stored in // the translation manipulator and remove it if (m_selectionManipulators[vertexIndex]->Selected()) { - auto it = AZStd::find_if(m_translationManipulator->m_vertices.begin(), m_translationManipulator->m_vertices.end(), + auto it = AZStd::find_if( + m_translationManipulator->m_vertices.begin(), m_translationManipulator->m_vertices.end(), [vertexIndex](const typename IndexedTranslationManipulator::VertexLookup vertexLookup) - { - return vertexIndex == vertexLookup.m_index; - }); + { + return vertexIndex == vertexLookup.m_index; + }); if (it != m_translationManipulator->m_vertices.end()) { @@ -1099,28 +1068,27 @@ namespace AzToolsFramework { // if one does not already exist, or we're not holding shift, create a new translation // manipulator at this vertex - CreateTranslationManipulator( - entityComponentIdPair, managerId, vertex, vertexIndex); + CreateTranslationManipulator(entityComponentIdPair, managerId, vertex, vertexIndex); } } - /// Configure the selection manipulator for fixed editor selection - this configures the view and action - /// of interacting with the selection manipulator. Vertices can just be selected (create a translation - /// manipulator) but not added or removed. + // configure the selection manipulator for fixed editor selection - this configures the view and action + // of interacting with the selection manipulator. Vertices can just be selected (create a translation + // manipulator) but not added or removed. template void EditorVertexSelectionFixed::SetupSelectionManipulator( const AZStd::shared_ptr& selectionManipulator, const AZ::EntityComponentIdPair& entityComponentIdPair, - const ManipulatorManagerId managerId, const size_t vertexIndex) + const ManipulatorManagerId managerId, + const size_t vertexIndex) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); // setup selection manipulator - const AZStd::shared_ptr selectionView = - AzToolsFramework::CreateManipulatorViewSphere(AZ::Color(1.0f, 0.0f, 0.0f, 1.0f), - g_defaultManipulatorSphereRadius, [&selectionManipulator] - (const ViewportInteraction::MouseInteraction& /*mouseInteraction*/, - const bool mouseOver, const AZ::Color& defaultColor) + const AZStd::shared_ptr selectionView = AzToolsFramework::CreateManipulatorViewSphere( + AZ::Color(1.0f, 0.0f, 0.0f, 1.0f), g_defaultManipulatorSphereRadius, + [&selectionManipulator]( + const ViewportInteraction::MouseInteraction& /*mouseInteraction*/, const bool mouseOver, const AZ::Color& defaultColor) { if (selectionManipulator->Selected()) { @@ -1128,72 +1096,68 @@ namespace AzToolsFramework } const float opacity[2] = { 0.5f, 1.0f }; - return AZ::Color( - defaultColor.GetR(), defaultColor.GetG(), defaultColor.GetB(), opacity[mouseOver]); + return AZ::Color(defaultColor.GetR(), defaultColor.GetG(), defaultColor.GetB(), opacity[mouseOver]); }); - selectionManipulator->SetViews(ManipulatorViews{selectionView}); + selectionManipulator->SetViews(ManipulatorViews{ selectionView }); - selectionManipulator->InstallLeftMouseUpCallback([ - this, entityComponentIdPair, vertexIndex, managerId]( - const ViewportInteraction::MouseInteraction& interaction) - { - EditorVertexSelectionBase::SelectionManipulatorSelectCallback( - vertexIndex, interaction, entityComponentIdPair, managerId); - }); + selectionManipulator->InstallLeftMouseUpCallback( + [this, entityComponentIdPair, vertexIndex, managerId](const ViewportInteraction::MouseInteraction& interaction) + { + EditorVertexSelectionBase::SelectionManipulatorSelectCallback( + vertexIndex, interaction, entityComponentIdPair, managerId); + }); } - /// Configure the selection manipulator for variable editor selection - this configures the view and action - /// of interacting with the selection manipulator. In this case, hovering the mouse with a modifier key held - /// will indicate removal, and clicking with a modifier key will remove the vertex. + // configure the selection manipulator for variable editor selection - this configures the view and action + // of interacting with the selection manipulator. In this case, hovering the mouse with a modifier key held + // will indicate removal, and clicking with a modifier key will remove the vertex. template void EditorVertexSelectionVariable::SetupSelectionManipulator( const AZStd::shared_ptr& selectionManipulator, const AZ::EntityComponentIdPair& entityComponentIdPair, - const ManipulatorManagerId managerId, const size_t vertexIndex) + const ManipulatorManagerId managerId, + const size_t vertexIndex) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); // setup selection manipulator - const AZStd::shared_ptr manipulatorView = - AzToolsFramework::CreateManipulatorViewSphere(AZ::Color(1.0f, 0.0f, 0.0f, 1.0f), - g_defaultManipulatorSphereRadius, [&selectionManipulator] - (const ViewportInteraction::MouseInteraction& mouseInteraction, - const bool mouseOver, const AZ::Color& defaultColor) + const AZStd::shared_ptr manipulatorView = AzToolsFramework::CreateManipulatorViewSphere( + AZ::Color(1.0f, 0.0f, 0.0f, 1.0f), g_defaultManipulatorSphereRadius, + [&selectionManipulator]( + const ViewportInteraction::MouseInteraction& mouseInteraction, const bool mouseOver, const AZ::Color& defaultColor) + { + if (mouseInteraction.m_keyboardModifiers.Alt() && mouseOver) { - if (mouseInteraction.m_keyboardModifiers.Alt() && mouseOver) - { - // indicate removal of manipulator - return AZ::Color(0.5f, 0.5f, 0.5f, 0.5f); - } + // indicate removal of manipulator + return AZ::Color(0.5f, 0.5f, 0.5f, 0.5f); + } - // highlight or not if mouse is over - const float opacity[2] = { 0.5f, 1.0f }; - if (selectionManipulator->Selected()) - { - return AZ::Color(1.0f, 1.0f, 0.0f, opacity[mouseOver]); - } + // highlight or not if mouse is over + const float opacity[2] = { 0.5f, 1.0f }; + if (selectionManipulator->Selected()) + { + return AZ::Color(1.0f, 1.0f, 0.0f, opacity[mouseOver]); + } - return AZ::Color( - defaultColor.GetR(), defaultColor.GetG(), defaultColor.GetB(), opacity[mouseOver]); - }); + return AZ::Color(defaultColor.GetR(), defaultColor.GetG(), defaultColor.GetB(), opacity[mouseOver]); + }); - - selectionManipulator->SetViews(ManipulatorViews{manipulatorView}); + selectionManipulator->SetViews(ManipulatorViews{ manipulatorView }); selectionManipulator->InstallLeftMouseUpCallback( [this, entityComponentIdPair, vertexIndex, managerId](const ViewportInteraction::MouseInteraction& interaction) - { - if (interaction.m_keyboardModifiers.Alt()) { - SafeRemoveVertex(entityComponentIdPair, vertexIndex); - } - else - { - EditorVertexSelectionBase::SelectionManipulatorSelectCallback( - vertexIndex, interaction, entityComponentIdPair, managerId); - } - }); + if (interaction.m_keyboardModifiers.Alt()) + { + SafeRemoveVertex(entityComponentIdPair, vertexIndex); + } + else + { + EditorVertexSelectionBase::SelectionManipulatorSelectCallback( + vertexIndex, interaction, entityComponentIdPair, managerId); + } + }); } template @@ -1240,15 +1204,17 @@ namespace AzToolsFramework template void EditorVertexSelectionFixed::PrepareActions() { - ActionOverride backAction = CreateBackAction("Deselect Vertex", "Deselect current vertex selection", [this]() - { - EditorVertexSelectionBase::ClearSelected(); - }); + ActionOverride backAction = CreateBackAction( + "Deselect Vertex", "Deselect current vertex selection", + [this]() + { + EditorVertexSelectionBase::ClearSelected(); + }); backAction.SetEntityComponentIdPair(EditorVertexSelectionBase::GetEntityComponentIdPair()); - EditorVertexSelectionBase::m_actionOverrides[static_cast( - EditorVertexSelectionBase::State::Translating)] = AZStd::vector { backAction }; + EditorVertexSelectionBase::m_actionOverrides[static_cast(EditorVertexSelectionBase::State::Translating)] = + AZStd::vector{ backAction }; } template @@ -1261,12 +1227,13 @@ namespace AzToolsFramework MidpointCalculator midpointCalculator; // sort in descending order - std::sort(manipulators.rbegin(), manipulators.rend(), + std::sort( + manipulators.rbegin(), manipulators.rend(), [](const typename IndexedTranslationManipulator::VertexLookup& lhs, const typename IndexedTranslationManipulator::VertexLookup& rhs) - { - return lhs.m_index < rhs.m_index; - }); + { + return lhs.m_index < rhs.m_index; + }); // iterate over current selection for (size_t manipulatorIndex = 0; manipulatorIndex < manipulators.size(); ++manipulatorIndex) @@ -1313,8 +1280,7 @@ namespace AzToolsFramework // create translation manipulator for duplicated vertices at new position EditorVertexSelectionBase::CreateTranslationManipulator( - EditorVertexSelectionBase::GetEntityComponentIdPair(), - EditorVertexSelectionBase::GetManipulatorManagerId(), + EditorVertexSelectionBase::GetEntityComponentIdPair(), EditorVertexSelectionBase::GetManipulatorManagerId(), localCenterPosition, vertices[0].m_index); // clear all selection manipulators to default unselected state @@ -1337,47 +1303,46 @@ namespace AzToolsFramework template void EditorVertexSelectionVariable::PrepareActions() { - ActionOverride deleteAction = CreateDeleteAction(s_deleteVerticesTitle, s_duplicateVerticesDesc, [this]() - { - DestroySelected(); - }); + ActionOverride deleteAction = CreateDeleteAction( + s_deleteVerticesTitle, s_duplicateVerticesDesc, + [this]() + { + DestroySelected(); + }); const AZ::EntityComponentIdPair entityComponentIdPair( - EditorVertexSelectionBase::GetEntityId(), - EditorVertexSelectionBase::GetComponentId()); + EditorVertexSelectionBase::GetEntityId(), EditorVertexSelectionBase::GetComponentId()); // note: important to register which entity/component id pair this action is associated with deleteAction.SetEntityComponentIdPair(entityComponentIdPair); - ActionOverride deselectAction = CreateBackAction(s_deselectVerticesTitle, s_deselectVerticesDesc, [this]() - { - EditorVertexSelectionBase::ClearSelected(); - }); + ActionOverride deselectAction = CreateBackAction( + s_deselectVerticesTitle, s_deselectVerticesDesc, + [this]() + { + EditorVertexSelectionBase::ClearSelected(); + }); // note: important to register which entity/component id pair this action is associated with deselectAction.SetEntityComponentIdPair(entityComponentIdPair); EditorVertexSelectionBase::m_actionOverrides[static_cast(EditorVertexSelectionBase::State::Translating)] = - AZStd::vector - { - ActionOverride() - .SetUri(AzToolsFramework::s_duplicateAction) - .SetKeySequence(QKeySequence(Qt::CTRL + Qt::Key_D)) - .SetTitle(s_duplicateVerticesTitle) - .SetTip(s_duplicateVerticesDesc) - .SetCallback([this]() - { - DuplicateSelected(); - }) - .SetEntityComponentIdPair(entityComponentIdPair), - deleteAction, - deselectAction - }; + AZStd::vector{ ActionOverride() + .SetUri(AzToolsFramework::s_duplicateAction) + .SetKeySequence(QKeySequence(Qt::CTRL + Qt::Key_D)) + .SetTitle(s_duplicateVerticesTitle) + .SetTip(s_duplicateVerticesDesc) + .SetCallback( + [this]() + { + DuplicateSelected(); + }) + .SetEntityComponentIdPair(entityComponentIdPair), + deleteAction, deselectAction }; } template - void InsertVertexAfter( - const AZ::EntityComponentIdPair& entityComponentIdPair, const size_t vertexIndex, const Vertex& localPosition) + void InsertVertexAfter(const AZ::EntityComponentIdPair& entityComponentIdPair, const size_t vertexIndex, const Vertex& localPosition) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -1389,15 +1354,13 @@ namespace AzToolsFramework if (insertPosition >= size) { AZ::VariableVerticesRequestBus::Event( - entityComponentIdPair.GetEntityId(), &AZ::VariableVerticesRequestBus::Handler::AddVertex, - localPosition); + entityComponentIdPair.GetEntityId(), &AZ::VariableVerticesRequestBus::Handler::AddVertex, localPosition); } else { bool updated = false; AZ::VariableVerticesRequestBus::EventResult( - updated, entityComponentIdPair.GetEntityId(), - &AZ::VariableVerticesRequestBus::Handler::InsertVertex, + updated, entityComponentIdPair.GetEntityId(), &AZ::VariableVerticesRequestBus::Handler::InsertVertex, insertPosition, localPosition); } @@ -1409,21 +1372,16 @@ namespace AzToolsFramework { bool removed = false; AZ::VariableVerticesRequestBus::EventResult( - removed, entityComponentIdPair.GetEntityId(), - &AZ::VariableVerticesRequestBus::Handler::RemoveVertex, vertexIndex); + removed, entityComponentIdPair.GetEntityId(), &AZ::VariableVerticesRequestBus::Handler::RemoveVertex, vertexIndex); RefreshUiAfterAddRemove(entityComponentIdPair); } // explicit instantiations - template void InsertVertexAfter( - const AZ::EntityComponentIdPair& entityComponentIdPair, size_t, const AZ::Vector2&); - template void InsertVertexAfter( - const AZ::EntityComponentIdPair& entityComponentIdPair, size_t, const AZ::Vector3&); - template void SafeRemoveVertex( - const AZ::EntityComponentIdPair& entityComponentIdPair, size_t vertexIndex); - template void SafeRemoveVertex( - const AZ::EntityComponentIdPair& entityComponentIdPair, size_t vertexIndex); + template void InsertVertexAfter(const AZ::EntityComponentIdPair& entityComponentIdPair, size_t, const AZ::Vector2&); + template void InsertVertexAfter(const AZ::EntityComponentIdPair& entityComponentIdPair, size_t, const AZ::Vector3&); + template void SafeRemoveVertex(const AZ::EntityComponentIdPair& entityComponentIdPair, size_t vertexIndex); + template void SafeRemoveVertex(const AZ::EntityComponentIdPair& entityComponentIdPair, size_t vertexIndex); AZ_CLASS_ALLOCATOR_IMPL_TEMPLATE(EditorVertexSelectionFixed, AZ::SystemAllocator, 0) AZ_CLASS_ALLOCATOR_IMPL_TEMPLATE(EditorVertexSelectionFixed, AZ::SystemAllocator, 0) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.h index 4d1c3ce43f..0036ea42d4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.h @@ -1,22 +1,22 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once #include #include #include -#include #include +#include #include #include #include @@ -24,37 +24,74 @@ namespace AzToolsFramework { - /// Concrete implementation of AZ::VariableVertices backed by an AZ::VertexContainer. + //! Concrete implementation of AZ::VariableVertices backed by an AZ::VertexContainer. template - class VariableVerticesVertexContainer - : public AZ::VariableVertices + class VariableVerticesVertexContainer : public AZ::VariableVertices { public: explicit VariableVerticesVertexContainer(AZ::VertexContainer& vertexContainer) - : m_vertexContainer(vertexContainer) {} + : m_vertexContainer(vertexContainer) + { + } - bool GetVertex(size_t index, Vertex& vertex) const override { return m_vertexContainer.GetVertex(index, vertex); } - bool UpdateVertex(size_t index, const Vertex& vertex) override { return m_vertexContainer.UpdateVertex(index, vertex); }; - void AddVertex(const Vertex& vertex) override { m_vertexContainer.AddVertex(vertex); } - bool InsertVertex(size_t index, const Vertex& vertex) override { return m_vertexContainer.InsertVertex(index, vertex); } - bool RemoveVertex(size_t index) override { return m_vertexContainer.RemoveVertex(index); } - void SetVertices(const AZStd::vector& vertices) override { m_vertexContainer.SetVertices(vertices); }; - void ClearVertices() override { m_vertexContainer.Clear(); } - size_t Size() const override { return m_vertexContainer.Size(); } - bool Empty() const override { return m_vertexContainer.Empty(); } + bool GetVertex(size_t index, Vertex& vertex) const override + { + return m_vertexContainer.GetVertex(index, vertex); + } + + bool UpdateVertex(size_t index, const Vertex& vertex) override + { + return m_vertexContainer.UpdateVertex(index, vertex); + }; + + void AddVertex(const Vertex& vertex) override + { + m_vertexContainer.AddVertex(vertex); + } + + bool InsertVertex(size_t index, const Vertex& vertex) override + { + return m_vertexContainer.InsertVertex(index, vertex); + } + + bool RemoveVertex(size_t index) override + { + return m_vertexContainer.RemoveVertex(index); + } + + void SetVertices(const AZStd::vector& vertices) override + { + m_vertexContainer.SetVertices(vertices); + }; + + void ClearVertices() override + { + m_vertexContainer.Clear(); + } + + size_t Size() const override + { + return m_vertexContainer.Size(); + } + + bool Empty() const override + { + return m_vertexContainer.Empty(); + } private: AZ::VertexContainer& m_vertexContainer; }; - /// Concrete implementation of AZ::FixedVertices backed by an AZStd::array. + //! Concrete implementation of AZ::FixedVertices backed by an AZStd::array. template - class FixedVerticesArray - : public AZ::FixedVertices + class FixedVerticesArray : public AZ::FixedVertices { public: explicit FixedVerticesArray(AZStd::array& array) - : m_array(array) {} + : m_array(array) + { + } bool GetVertex(size_t index, Vertex& vertex) const override { @@ -72,22 +109,26 @@ namespace AzToolsFramework if (index < m_array.size()) { m_array[index] = vertex; - return true;; + return true; + ; } return false; } - size_t Size() const override { return m_array.size(); } + size_t Size() const override + { + return m_array.size(); + } private: AZStd::array& m_array; }; - /// EditorVertexSelection provides an interface for a collection of manipulators to expose - /// editing of vertices in a container/collection. EditorVertexSelection is templated on the - /// type of Vertex (Vector2/Vector3) stored in the container. - /// EditorVertexSelectionBase provides common behavior shared across Fixed and Variable selections. + //! EditorVertexSelection provides an interface for a collection of manipulators to expose + //! editing of vertices in a container/collection. EditorVertexSelection is templated on the + //! type of Vertex (Vector2/Vector3) stored in the container. + //! EditorVertexSelectionBase provides common behavior shared across Fixed and Variable selections. template class EditorVertexSelectionBase : private AzFramework::EntityDebugDisplayEventBus::Handler @@ -99,89 +140,110 @@ namespace AzToolsFramework EditorVertexSelectionBase& operator=(EditorVertexSelectionBase&&) = default; virtual ~EditorVertexSelectionBase() = default; - /// Setup and configure the EditorVertexSelection for operation. + //! Setup and configure the EditorVertexSelection for operation. void Create( - const AZ::EntityComponentIdPair& entityComponentIdPair, ManipulatorManagerId managerId, + const AZ::EntityComponentIdPair& entityComponentIdPair, + ManipulatorManagerId managerId, AZStd::unique_ptr hoverSelection, TranslationManipulators::Dimensions dimensions, TranslationManipulatorConfiguratorFn translationManipulatorConfigurator); - /// Create a translation manipulator for a given vertex. + //! Create a translation manipulator for a given vertex. void CreateTranslationManipulator( - const AZ::EntityComponentIdPair& entityComponentIdPair, - ManipulatorManagerId managerId, const Vertex& vertex, size_t index); + const AZ::EntityComponentIdPair& entityComponentIdPair, ManipulatorManagerId managerId, const Vertex& vertex, size_t index); - /// Destroy all manipulators associated with the vertex selection. + //! Destroy all manipulators associated with the vertex selection. void Destroy(); - /// Set custom callback for when vertex positions are updated. + //! Set custom callback for when vertex positions are updated. void SetVertexPositionsUpdatedCallback(const AZStd::function& callback); - /// Update manipulators based on local changes to vertex positions. + //! Update manipulators based on local changes to vertex positions. void RefreshLocal(); - /// Update the translation manipulator to be correctly positioned based - /// on the current selection (recenter it). + //! Update the translation manipulator to be correctly positioned based + //! on the current selection (recenter it). void RefreshTranslationManipulator(); - /// Update manipulators based on changes to the entity's transform and non-uniform scale. + //! Update manipulators based on changes to the entity's transform and non-uniform scale. void RefreshSpace(const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale = AZ::Vector3::CreateOne()); - /// Set bounds dirty (need recalculating) for all owned manipulators (selection, translation, hover). + //! Set bounds dirty (need recalculating) for all owned manipulators (selection, translation, hover). void SetBoundsDirty(); - /// How should the EditorVertexSelection respond to mouse input. - virtual bool HandleMouse( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction); + //! How should the EditorVertexSelection respond to mouse input. + virtual bool HandleMouse(const ViewportInteraction::MouseInteractionEvent& mouseInteraction); - /// Snap the selected vertices to the terrain. - /// Note: With a multi-selection the manipulator will be translated to the picked - /// terrain position with all verts moved relative to it. - void SnapVerticesToTerrain( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction); + //! Snap the selected vertices to the terrain. + //! Note: With a multi-selection the manipulator will be translated to the picked + //! terrain position with all vertices moved relative to it. + void SnapVerticesToTerrain(const ViewportInteraction::MouseInteractionEvent& mouseInteraction); - /// The Actions provided by the EditorVertexSelection while it is active. - /// e.g. Vertex deletion, duplication etc. + //! The Actions provided by the EditorVertexSelection while it is active. + //! e.g. Vertex deletion, duplication etc. AZStd::vector ActionOverrides() const; - /// Let the EditorVertexSelection know a batch movement is about to begin so it - /// can avoid certain unnecessary updates. + //! Let the EditorVertexSelection know a batch movement is about to begin so it + //! can avoid certain unnecessary updates. void BeginBatchMovement(); - /// Let the EditorVertexSelection know a batch movement has ended so it can return - /// to its normal state. + //! Let the EditorVertexSelection know a batch movement has ended so it can return + //! to its normal state. void EndBatchMovement(); - /// Set the position of the TranslationManipulators (if active). + //! Set the position of the TranslationManipulators (if active). void SetSelectedPosition(const AZ::Vector3& localPosition); - AZ::EntityId GetEntityId() const { return m_entityComponentIdPair.GetEntityId(); } + AZ::EntityId GetEntityId() const + { + return m_entityComponentIdPair.GetEntityId(); + } protected: - /// Internal interface for EditorVertexSelection. + //! Internal interface for EditorVertexSelection. virtual void SetupSelectionManipulator( const AZStd::shared_ptr& selectionManipulator, const AZ::EntityComponentIdPair& entityComponentIdPair, - ManipulatorManagerId managerId, size_t index) = 0; + ManipulatorManagerId managerId, + size_t index) = 0; virtual void PrepareActions() = 0; - /// Default behavior when clicking on a selection manipulator (representing a vertex). + //! Default behavior when clicking on a selection manipulator (representing a vertex). void SelectionManipulatorSelectCallback( - size_t index, const ViewportInteraction::MouseInteraction& interaction, - const AZ::EntityComponentIdPair& entityComponentIdPair, ManipulatorManagerId managerId); + size_t index, + const ViewportInteraction::MouseInteraction& interaction, + const AZ::EntityComponentIdPair& entityComponentIdPair, + ManipulatorManagerId managerId); - /// Destroy the translation manipulator and deselect all vertices. + //! Destroy the translation manipulator and deselect all vertices. void ClearSelected(); - AZ::ComponentId GetComponentId() const { return m_entityComponentIdPair.GetComponentId(); } - const AZ::EntityComponentIdPair& GetEntityComponentIdPair() const { return m_entityComponentIdPair; } - ManipulatorManagerId GetManipulatorManagerId() const { return m_manipulatorManagerId; } + AZ::ComponentId GetComponentId() const + { + return m_entityComponentIdPair.GetComponentId(); + } - /// Is the translation vertex manipulator in 2D or 3D. - TranslationManipulators::Dimensions Dimensions() const { return m_dimensions; } + const AZ::EntityComponentIdPair& GetEntityComponentIdPair() const + { + return m_entityComponentIdPair; + } - /// How to configure the translation manipulator (view and axes). - TranslationManipulatorConfiguratorFn ConfiguratorFn() const { return m_manipulatorConfiguratorFn; } + ManipulatorManagerId GetManipulatorManagerId() const + { + return m_manipulatorManagerId; + } - /// The state we are in when editing vertices. + //! Is the translation vertex manipulator in 2D or 3D. + TranslationManipulators::Dimensions Dimensions() const + { + return m_dimensions; + } + + //! How to configure the translation manipulator (view and axes). + TranslationManipulatorConfiguratorFn ConfiguratorFn() const + { + return m_manipulatorConfiguratorFn; + } + + //! The state we are in when editing vertices. enum class State { Selecting, @@ -190,23 +252,22 @@ namespace AzToolsFramework void SetState(State state); - AZStd::unique_ptr m_hoverSelection = nullptr; ///< Interface to hover selection, representing bounds that can be selected. - AZStd::shared_ptr> m_translationManipulator = nullptr; ///< Manipulator when vertex is selected to translate it. - AZStd::vector> m_selectionManipulators; ///< Manipulators for each vertex when entity is selected. - AZStd::array, 2> m_actionOverrides; ///< Available actions corresponding to each mode. + AZStd::unique_ptr m_hoverSelection = + nullptr; //!< Interface to hover selection, representing bounds that can be selected. + AZStd::shared_ptr> m_translationManipulator = + nullptr; //!< Manipulator when vertex is selected to translate it. + AZStd::vector> + m_selectionManipulators; //!< Manipulators for each vertex when entity is selected. + AZStd::array, 2> m_actionOverrides; //!< Available actions corresponding to each mode. private: // AzFramework::EntityDebugDisplayEventBus - void DisplayEntityViewport( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; + void DisplayEntityViewport(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; // AzFramework::ViewportDebugDisplayEventBus - void DisplayViewport2d( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; + void DisplayViewport2d(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; - /// Set selected manipulator and vertices position from offset from starting position when pressed. + //! Set selected manipulator and vertices position from offset from starting position when pressed. void UpdateManipulatorsAndVerticesFromOffset( IndexedTranslationManipulator& translationManipulator, const AZ::Vector3& localManipulatorStartPosition, @@ -217,23 +278,24 @@ namespace AzToolsFramework template::value>::type* = nullptr> void UpdateManipulatorSpace(const AzFramework::ViewportInfo& viewportInfo) const; - EditorBoxSelect m_editorBoxSelect; ///< Provide box select support for vertex selection. - AZ::EntityComponentIdPair m_entityComponentIdPair; ///< Id of the Entity and Component this editor vertex selection was created on. - ManipulatorManagerId m_manipulatorManagerId; ///< Id of the manager manipulators created from this type will be associated with. - TranslationManipulators::Dimensions m_dimensions = TranslationManipulators::Dimensions::Three; ///< The dimensions this vertex selection was created with. - TranslationManipulatorConfiguratorFn m_manipulatorConfiguratorFn = nullptr; ///< Function pointer set on Create to decide look and functionality of translation manipulator. - AZStd::function m_onVertexPositionsUpdated = nullptr; ///< Callback for when vertex positions are changed. - State m_state = State::Selecting; ///< Different states VertexSelection can be in. - bool m_worldSpace = false; ///< Are the manipulators being used in local or world space. - bool m_batchMovementInProgress = false; ///< If a batch movement operation is in progress we do not want to - ///< refresh the VertexSelection during it for performance reasons. + EditorBoxSelect m_editorBoxSelect; //!< Provide box select support for vertex selection. + AZ::EntityComponentIdPair m_entityComponentIdPair; //!< Id of the Entity and Component this editor vertex selection was created on. + ManipulatorManagerId m_manipulatorManagerId; //!< Id of the manager manipulators created from this type will be associated with. + TranslationManipulators::Dimensions m_dimensions = + TranslationManipulators::Dimensions::Three; //!< The dimensions this vertex selection was created with. + TranslationManipulatorConfiguratorFn m_manipulatorConfiguratorFn = + nullptr; //!< Function pointer set on Create to decide look and functionality of translation manipulator. + AZStd::function m_onVertexPositionsUpdated = nullptr; //!< Callback for when vertex positions are changed. + State m_state = State::Selecting; //!< Different states VertexSelection can be in. + bool m_worldSpace = false; //!< Are the manipulators being used in local or world space. + bool m_batchMovementInProgress = false; //!< If a batch movement operation is in progress we do not want to + //!< refresh the VertexSelection during it for performance reasons. }; - /// EditorVertexSelectionFixed provides selection and editing for a fixed length number of - /// vertices. New vertices cannot be inserted/added or removed. + //! EditorVertexSelectionFixed provides selection and editing for a fixed length number of + //! vertices. New vertices cannot be inserted/added or removed. template - class EditorVertexSelectionFixed - : public EditorVertexSelectionBase + class EditorVertexSelectionFixed : public EditorVertexSelectionBase { public: AZ_CLASS_ALLOCATOR_DECL @@ -247,15 +309,15 @@ namespace AzToolsFramework void SetupSelectionManipulator( const AZStd::shared_ptr& selectionManipulator, const AZ::EntityComponentIdPair& entityComponentIdPair, - ManipulatorManagerId managerId, size_t index) override; + ManipulatorManagerId managerId, + size_t index) override; void PrepareActions() override; }; - /// EditorVertexSelectionVariable provides selection and editing for a variable length number of - /// vertices. New vertices can be inserted/added or removed from the collection. + //! EditorVertexSelectionVariable provides selection and editing for a variable length number of + //! vertices. New vertices can be inserted/added or removed from the collection. template - class EditorVertexSelectionVariable - : public EditorVertexSelectionBase + class EditorVertexSelectionVariable : public EditorVertexSelectionBase { public: AZ_CLASS_ALLOCATOR_DECL @@ -272,7 +334,8 @@ namespace AzToolsFramework void SetupSelectionManipulator( const AZStd::shared_ptr& selectionManipulator, const AZ::EntityComponentIdPair& entityComponentIdPair, - ManipulatorManagerId managerId, size_t vertIndex) override; + ManipulatorManagerId managerId, + size_t vertIndex) override; //! Presents a warning to the user that vertices will not be deleted. //! @note Allow overriding by derived classes to make this a noop if required. @@ -281,21 +344,18 @@ namespace AzToolsFramework private: void PrepareActions() override; - /// @return The center point of the selected vertices. - Vertex InsertSelectedInPlace( - AZStd::vector::VertexLookup>& manipulators); + //! @return The center point of the selected vertices. + Vertex InsertSelectedInPlace(AZStd::vector::VertexLookup>& manipulators); }; - /// Helper for inserting a vertex in a variable vertices container. + //! Helper for inserting a vertex in a variable vertices container. template - void InsertVertexAfter( - const AZ::EntityComponentIdPair& entityComponentIdPair, size_t vertIndex, const Vertex& localPosition); + void InsertVertexAfter(const AZ::EntityComponentIdPair& entityComponentIdPair, size_t vertIndex, const Vertex& localPosition); - /// Helper for removing a vertex in a variable vertices container. - /// Remove a vertex from the container and ensure the associated manipulator is unset and - /// property display values are refreshed. + //! Helper for removing a vertex in a variable vertices container. + //! Remove a vertex from the container and ensure the associated manipulator is unset and + //! property display values are refreshed. template - void SafeRemoveVertex( - const AZ::EntityComponentIdPair& entityComponentIdPair, size_t vertexIndex); + void SafeRemoveVertex(const AZ::EntityComponentIdPair& entityComponentIdPair, size_t vertexIndex); } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/HoverSelection.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/HoverSelection.h index c5f58f0d56..a389237b2b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/HoverSelection.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/HoverSelection.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -16,10 +16,10 @@ namespace AzToolsFramework { - /// HoverSelection provides an interface for manipulator/s offering selection when - /// the mouse is hovered over a particular bound. This interface is used to represent - /// a Spline manipulator bound, and a series of LineSegment manipulator bounds. - /// This generic interface allows EditorVertexSelection to use either Spline or LineSegment selection. + //! HoverSelection provides an interface for manipulator/s offering selection when + //! the mouse is hovered over a particular bound. This interface is used to represent + //! a Spline manipulator bound, and a series of LineSegment manipulator bounds. + //! This generic interface allows EditorVertexSelection to use either Spline or LineSegment selection. class HoverSelection { public: @@ -33,21 +33,37 @@ namespace AzToolsFramework virtual void SetNonUniformScale(const AZ::Vector3& nonUniformScale) = 0; }; - /// NullHoverSelection is used when vertices cannot be inserted. This serves as a no-op - /// and is used to prevent the need for additional null checks in EditorVertexSelection. - class NullHoverSelection - : public HoverSelection + //! NullHoverSelection is used when vertices cannot be inserted. This serves as a no-op + //! and is used to prevent the need for additional null checks in EditorVertexSelection. + class NullHoverSelection : public HoverSelection { public: NullHoverSelection() = default; NullHoverSelection(const NullHoverSelection&) = delete; NullHoverSelection& operator=(const NullHoverSelection&) = delete; - void Register(ManipulatorManagerId /*managerId*/) override {} - void Unregister() override {} - void SetBoundsDirty() override {} - void Refresh() override {} - void SetSpace(const AZ::Transform& /*worldFromLocal*/) override {} - void SetNonUniformScale([[maybe_unused]] const AZ::Vector3& nonUniformScale) override {} + void Register([[maybe_unused]] ManipulatorManagerId managerId) override + { + } + + void Unregister() override + { + } + + void SetBoundsDirty() override + { + } + + void Refresh() override + { + } + + void SetSpace([[maybe_unused]] const AZ::Transform& worldFromLocal) override + { + } + + void SetNonUniformScale([[maybe_unused]] const AZ::Vector3& nonUniformScale) override + { + } }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineHoverSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineHoverSelection.cpp index e26c154be9..12d5f399c3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineHoverSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineHoverSelection.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "LineHoverSelection.h" @@ -22,17 +22,15 @@ namespace AzToolsFramework { - static const AZ::Color s_lineSelectManipulatorColor = AZ::Color(0.0f, 1.0f, 0.0f, 1.0f); + static const AZ::Color LineSelectManipulatorColor = AZ::Color(0.0f, 1.0f, 0.0f, 1.0f); template - static void UpdateLineSegmentPosition( - const size_t vertIndex, const AZ::EntityId entityId, LineSegmentSelectionManipulator& lineSegment) + static void UpdateLineSegmentPosition(const size_t vertIndex, const AZ::EntityId entityId, LineSegmentSelectionManipulator& lineSegment) { Vertex start; bool foundStart = false; AZ::FixedVerticesRequestBus::EventResult( - foundStart, entityId, &AZ::FixedVerticesRequestBus::Handler::GetVertex, - vertIndex, start); + foundStart, entityId, &AZ::FixedVerticesRequestBus::Handler::GetVertex, vertIndex, start); if (foundStart) { @@ -40,14 +38,12 @@ namespace AzToolsFramework } size_t size = 0; - AZ::FixedVerticesRequestBus::EventResult( - size, entityId, &AZ::FixedVerticesRequestBus::Handler::Size); + AZ::FixedVerticesRequestBus::EventResult(size, entityId, &AZ::FixedVerticesRequestBus::Handler::Size); Vertex end; bool foundEnd = false; AZ::FixedVerticesRequestBus::EventResult( - foundEnd, entityId, &AZ::FixedVerticesRequestBus::Handler::GetVertex, - (vertIndex + 1) % size, end); + foundEnd, entityId, &AZ::FixedVerticesRequestBus::Handler::GetVertex, (vertIndex + 1) % size, end); if (foundEnd) { @@ -56,8 +52,7 @@ namespace AzToolsFramework // update the view const float lineWidth = 0.05f; - lineSegment.SetView( - CreateManipulatorViewLineSelect(lineSegment, s_lineSelectManipulatorColor, lineWidth)); + lineSegment.SetView(CreateManipulatorViewLineSelect(lineSegment, LineSelectManipulatorColor, lineWidth)); } template @@ -66,9 +61,8 @@ namespace AzToolsFramework : m_entityId(entityComponentIdPair.GetEntityId()) { // create a line segment manipulator from vertex positions and setup its callback - auto setupLineSegment = [this] ( - const AZ::EntityComponentIdPair& entityComponentIdPair, - const ManipulatorManagerId managerId, const size_t vertIndex) + auto setupLineSegment = + [this](const AZ::EntityComponentIdPair& entityComponentIdPair, const ManipulatorManagerId managerId, const size_t vertIndex) { m_lineSegmentManipulators.push_back(LineSegmentSelectionManipulator::MakeShared()); AZStd::shared_ptr& lineSegmentManipulator = m_lineSegmentManipulators.back(); @@ -81,11 +75,9 @@ namespace AzToolsFramework lineSegmentManipulator->InstallLeftMouseUpCallback( [vertIndex, entityComponentIdPair](const LineSegmentSelectionManipulator::Action& action) - { - InsertVertexAfter( - entityComponentIdPair, vertIndex, - AZ::AdaptVertexIn(action.m_localLineHitPosition)); - }); + { + InsertVertexAfter(entityComponentIdPair, vertIndex, AZ::AdaptVertexIn(action.m_localLineHitPosition)); + }); }; // create all line segment manipulators for the polygon prism (used for selection bounds) @@ -150,8 +142,7 @@ namespace AzToolsFramework void LineSegmentHoverSelection::Refresh() { size_t vertexCount = 0; - AZ::FixedVerticesRequestBus::EventResult( - vertexCount, m_entityId, &AZ::FixedVerticesRequestBus::Handler::Size); + AZ::FixedVerticesRequestBus::EventResult(vertexCount, m_entityId, &AZ::FixedVerticesRequestBus::Handler::Size); // update the start/end positions of all the line segment manipulators to ensure // they stay consistent with the polygon prism shape diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineHoverSelection.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineHoverSelection.h index eb5e3991c5..e14930f9ca 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineHoverSelection.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineHoverSelection.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -25,17 +25,14 @@ namespace AzToolsFramework { class LineSegmentSelectionManipulator; - /// LineSegmentHoverSelection is a concrete implementation of HoverSelection wrapping a collection/container - /// of vertices and a list of LineSegmentManipulators. The underlying manipulators are used to control selection - /// by highlighting where on the line a new vertex will be inserted. + //! LineSegmentHoverSelection is a concrete implementation of HoverSelection wrapping a collection/container + //! of vertices and a list of LineSegmentManipulators. The underlying manipulators are used to control selection + //! by highlighting where on the line a new vertex will be inserted. template - class LineSegmentHoverSelection - : public HoverSelection + class LineSegmentHoverSelection : public HoverSelection { public: - explicit LineSegmentHoverSelection( - const AZ::EntityComponentIdPair& entityComponentIdPair, - ManipulatorManagerId managerId); + explicit LineSegmentHoverSelection(const AZ::EntityComponentIdPair& entityComponentIdPair, ManipulatorManagerId managerId); LineSegmentHoverSelection(const LineSegmentHoverSelection&) = delete; LineSegmentHoverSelection& operator=(const LineSegmentHoverSelection&) = delete; ~LineSegmentHoverSelection(); @@ -49,6 +46,6 @@ namespace AzToolsFramework private: AZ::EntityId m_entityId; - AZStd::vector> m_lineSegmentManipulators; ///< Manipulators for each line. + AZStd::vector> m_lineSegmentManipulators; //!< Manipulators for each line. }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.cpp index 8874e0dcd9..45f2803818 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "LineSegmentSelectionManipulator.h" @@ -20,15 +20,20 @@ namespace AzToolsFramework { LineSegmentSelectionManipulator::Action CalculateManipulationDataAction( - const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Vector3& rayOrigin, - const AZ::Vector3& rayDirection, const float rayLength, const AZ::Vector3& localStart, const AZ::Vector3& localEnd) + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, + const float rayLength, + const AZ::Vector3& localStart, + const AZ::Vector3& localEnd) { AZ::Vector3 worldClosestPositionRay, worldClosestPositionLineSegment; float rayProportion, lineSegmentProportion; AZ::Intersect::ClosestSegmentSegment( - rayOrigin, rayOrigin + rayDirection * rayLength, - worldFromLocal.TransformPoint(nonUniformScale * localStart), worldFromLocal.TransformPoint(nonUniformScale * localEnd), - rayProportion, lineSegmentProportion, worldClosestPositionRay, worldClosestPositionLineSegment); + rayOrigin, rayOrigin + rayDirection * rayLength, worldFromLocal.TransformPoint(nonUniformScale * localStart), + worldFromLocal.TransformPoint(nonUniformScale * localEnd), rayProportion, lineSegmentProportion, worldClosestPositionRay, + worldClosestPositionLineSegment); AZ::Transform worldFromLocalNormalized = worldFromLocal; const AZ::Vector3 scale = worldFromLocalNormalized.ExtractUniformScale() * nonUniformScale; @@ -47,7 +52,9 @@ namespace AzToolsFramework AttachLeftMouseDownImpl(); } - LineSegmentSelectionManipulator::~LineSegmentSelectionManipulator() {} + LineSegmentSelectionManipulator::~LineSegmentSelectionManipulator() + { + } void LineSegmentSelectionManipulator::InstallLeftMouseDownCallback(const MouseActionCallback& onMouseDownCallback) { @@ -112,12 +119,9 @@ namespace AzToolsFramework if (mouseInteraction.m_keyboardModifiers.Ctrl() && !mouseInteraction.m_keyboardModifiers.Shift()) { m_manipulatorView->Draw( - GetManipulatorManagerId(), managerState, - GetManipulatorId(), { - TransformUniformScale(GetSpace()), GetNonUniformScale(), - m_localStart, MouseOver() - }, - debugDisplay, cameraState, mouseInteraction); + GetManipulatorManagerId(), managerState, GetManipulatorId(), + { TransformUniformScale(GetSpace()), GetNonUniformScale(), m_localStart, MouseOver() }, debugDisplay, cameraState, + mouseInteraction); } } @@ -135,4 +139,4 @@ namespace AzToolsFramework { m_manipulatorView->Invalidate(GetManipulatorManagerId()); } -} +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.h index d9e317c378..107a0ccf9f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LineSegmentSelectionManipulator.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -20,12 +20,12 @@ namespace AzToolsFramework { class ManipulatorView; - /// A manipulator to expose where on a line a user is moving their mouse. + //! A manipulator to expose where on a line a user is moving their mouse. class LineSegmentSelectionManipulator : public BaseManipulator , public ManipulatorSpace { - /// Private constructor. + //! Private constructor. LineSegmentSelectionManipulator(); public: @@ -37,10 +37,10 @@ namespace AzToolsFramework ~LineSegmentSelectionManipulator(); - /// A Manipulator must only be created and managed through a shared_ptr. + //! A Manipulator must only be created and managed through a shared_ptr. static AZStd::shared_ptr MakeShared(); - /// Mouse action data used by MouseActionCallback. + //! Mouse action data used by MouseActionCallback. struct Action { AZ::Vector3 m_localLineHitPosition; @@ -57,18 +57,31 @@ namespace AzToolsFramework const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; - void SetStart(const AZ::Vector3& startLocal) { m_localStart = startLocal; } - void SetEnd(const AZ::Vector3& endLocal) { m_localEnd = endLocal; } - const AZ::Vector3& GetStart() const { return m_localStart; } - const AZ::Vector3& GetEnd() const { return m_localEnd; } + void SetStart(const AZ::Vector3& startLocal) + { + m_localStart = startLocal; + } + + void SetEnd(const AZ::Vector3& endLocal) + { + m_localEnd = endLocal; + } + + const AZ::Vector3& GetStart() const + { + return m_localStart; + } + + const AZ::Vector3& GetEnd() const + { + return m_localEnd; + } void SetView(AZStd::unique_ptr&& view); private: - void OnLeftMouseDownImpl( - const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; - void OnLeftMouseUpImpl( - const ViewportInteraction::MouseInteraction& interaction) override; + void OnLeftMouseDownImpl(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; + void OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction) override; void InvalidateImpl() override; void SetBoundsDirtyImpl() override; @@ -79,12 +92,18 @@ namespace AzToolsFramework MouseActionCallback m_onLeftMouseDownCallback = nullptr; MouseActionCallback m_onLeftMouseUpCallback = nullptr; - ViewportInteraction::KeyboardModifiers m_keyboardModifiers; ///< What modifier keys are pressed when interacting with this manipulator. + ViewportInteraction::KeyboardModifiers + m_keyboardModifiers; //!< What modifier keys are pressed when interacting with this manipulator. - AZStd::unique_ptr m_manipulatorView = nullptr; ///< Look of manipulator. + AZStd::unique_ptr m_manipulatorView = nullptr; //!< Look of manipulator. }; LineSegmentSelectionManipulator::Action CalculateManipulationDataAction( - const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Vector3& rayOrigin, - const AZ::Vector3& rayDirection, float rayLength, const AZ::Vector3& localStart, const AZ::Vector3& localEnd); + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, + float rayLength, + const AZ::Vector3& localStart, + const AZ::Vector3& localEnd); } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp index 34ae28bd13..604e74b6f5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "LinearManipulator.h" @@ -22,13 +22,16 @@ namespace AzToolsFramework { LinearManipulator::Starter CalculateLinearManipulationDataStart( - const LinearManipulator::Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, const float intersectionDistance, + const LinearManipulator::Fixed& fixed, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, + const ViewportInteraction::MouseInteraction& interaction, + const float intersectionDistance, const AzFramework::CameraState& cameraState) { - const ManipulatorInteraction manipulatorInteraction = - BuildManipulatorInteraction( - worldFromLocal, nonUniformScale, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection); + const ManipulatorInteraction manipulatorInteraction = BuildManipulatorInteraction( + worldFromLocal, nonUniformScale, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection); const AZ::Vector3 axis = TransformDirectionNoScaling(localTransform, fixed.m_axis); const AZ::Vector3 rayCrossAxis = manipulatorInteraction.m_localRayDirection.Cross(axis); @@ -47,32 +50,35 @@ namespace AzToolsFramework manipulatorInteraction.m_localRayOrigin + manipulatorInteraction.m_localRayDirection * intersectionDistance; Internal::CalculateRayPlaneIntersectingPoint( - manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection, - localIntersectionPoint, startTransition.m_localNormal, start.m_localHitPosition); + manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection, localIntersectionPoint, + startTransition.m_localNormal, start.m_localHitPosition); start.m_screenPosition = interaction.m_mousePick.m_screenCoordinates; start.m_localPosition = localTransform.GetTranslation(); - start.m_localScale = AZ::Vector3(localTransform.GetUniformScale());; + start.m_localScale = AZ::Vector3(localTransform.GetUniformScale()); + ; start.m_localAxis = axis; // sign to determine which side of the linear axis we pressed // (useful to know when the visual axis flips to face the camera) - start.m_sign = - AZ::GetSign((start.m_localHitPosition - localTransform.GetTranslation()).Dot(axis)); + start.m_sign = AZ::GetSign((start.m_localHitPosition - localTransform.GetTranslation()).Dot(axis)); startTransition.m_screenToWorldScale = 1.0f / CalculateScreenToWorldMultiplier((worldFromLocal * localTransform).GetTranslation(), cameraState); - return {startTransition, start}; + return { startTransition, start }; } LinearManipulator::Action CalculateLinearManipulationDataAction( - const LinearManipulator::Fixed& fixed, const LinearManipulator::Starter& starter, - const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, - const GridSnapParameters& gridSnapParams, const ViewportInteraction::MouseInteraction& interaction) + const LinearManipulator::Fixed& fixed, + const LinearManipulator::Starter& starter, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, + const GridSnapParameters& gridSnapParams, + const ViewportInteraction::MouseInteraction& interaction) { - const ManipulatorInteraction manipulatorInteraction = - BuildManipulatorInteraction( - worldFromLocal, nonUniformScale, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection); + const ManipulatorInteraction manipulatorInteraction = BuildManipulatorInteraction( + worldFromLocal, nonUniformScale, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection); const auto& [startTransition, start] = starter; @@ -81,8 +87,8 @@ namespace AzToolsFramework // if an invalid ray intersection is attempted AZ::Vector3 localHitPosition = start.m_localHitPosition; Internal::CalculateRayPlaneIntersectingPoint( - manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection, - start.m_localHitPosition, startTransition.m_localNormal, localHitPosition); + manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection, start.m_localHitPosition, + startTransition.m_localNormal, localHitPosition); localHitPosition = Internal::TryConstrainHitPositionToView( localHitPosition, start.m_localHitPosition, worldFromLocal.GetInverse(), @@ -103,9 +109,8 @@ namespace AzToolsFramework LinearManipulator::Action action; action.m_fixed = fixed; action.m_start = start; - action.m_current.m_localPositionOffset = snapping - ? CalculateSnappedAmount(unsnappedOffset, axis, gridSize * scaleRecip) - : unsnappedOffset; + action.m_current.m_localPositionOffset = + snapping ? CalculateSnappedAmount(unsnappedOffset, axis, gridSize * scaleRecip) : unsnappedOffset; action.m_current.m_screenPosition = interaction.m_mousePick.m_screenCoordinates; action.m_viewportId = interaction.m_interactionId.m_viewportId; @@ -191,7 +196,8 @@ namespace AzToolsFramework // note: m_localTransform must not be made uniform as it may contain a local scale we want to snap m_onLeftMouseUpCallback(CalculateLinearManipulationDataAction( - m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), gridSnapParams, interaction)); + m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), gridSnapParams, + interaction)); } } @@ -202,16 +208,14 @@ namespace AzToolsFramework const ViewportInteraction::MouseInteraction& mouseInteraction) { const AZ::Transform localTransform = m_useVisualsOverride - ? AZ::Transform::CreateFromQuaternionAndTranslation( - m_visualOrientationOverride, GetLocalPosition()) + ? AZ::Transform::CreateFromQuaternionAndTranslation(m_visualOrientationOverride, GetLocalPosition()) : GetLocalTransform(); if (cl_manipulatorDrawDebug) { if (PerformingAction()) { - const GridSnapParameters gridSnapParams = - GridSnapSettings(mouseInteraction.m_interactionId.m_viewportId); + const GridSnapParameters gridSnapParams = GridSnapSettings(mouseInteraction.m_interactionId.m_viewportId); const auto action = CalculateLinearManipulationDataAction( m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), gridSnapParams, @@ -219,9 +223,10 @@ namespace AzToolsFramework // display the exact hit (ray intersection) of the mouse pick on the manipulator DrawTransformAxes( - debugDisplay, TransformUniformScale(GetSpace()) * - AZ::Transform::CreateTranslation( - action.m_start.m_localHitPosition + GetNonUniformScale() * action.m_current.m_localPositionOffset)); + debugDisplay, + TransformUniformScale(GetSpace()) * + AZ::Transform::CreateTranslation( + action.m_start.m_localHitPosition + GetNonUniformScale() * action.m_current.m_localPositionOffset)); } AZ::Transform combined = GetLocalTransform(); @@ -229,8 +234,7 @@ namespace AzToolsFramework combined = GetSpace() * combined; DrawTransformAxes(debugDisplay, combined); - DrawAxis( - debugDisplay, combined.GetTranslation(), TransformDirectionNoScaling(combined, m_fixed.m_axis)); + DrawAxis(debugDisplay, combined.GetTranslation(), TransformDirectionNoScaling(combined, m_fixed.m_axis)); } for (auto& view : m_manipulatorViews) @@ -238,12 +242,9 @@ namespace AzToolsFramework auto nonUniformScale = GetNonUniformScale(); view->Draw( - GetManipulatorManagerId(), managerState, - GetManipulatorId(), { - ApplySpace(localTransform), GetNonUniformScale(), - AZ::Vector3::CreateZero(), MouseOver() - }, - debugDisplay, cameraState, mouseInteraction); + GetManipulatorManagerId(), managerState, GetManipulatorId(), + { ApplySpace(localTransform), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay, cameraState, + mouseInteraction); } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.h index c3d43a2535..240d4c7b9b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -22,13 +22,13 @@ namespace AzToolsFramework { struct GridSnapParameters; - /// LinearManipulator serves as a visual tool for users to modify values - /// in one dimension on an axis defined in 3D space. + //! LinearManipulator serves as a visual tool for users to modify values + //! in one dimension on an axis defined in 3D space. class LinearManipulator : public BaseManipulator , public ManipulatorSpaceWithLocalTransform { - /// Private constructor. + //! Private constructor. explicit LinearManipulator(const AZ::Transform& worldFromLocal); public: @@ -41,68 +41,80 @@ namespace AzToolsFramework ~LinearManipulator() = default; - /// A Manipulator must only be created and managed through a shared_ptr. - /// @note worldFromLocal should not contain scale. + //! A Manipulator must only be created and managed through a shared_ptr. + //! @note worldFromLocal should not contain scale. static AZStd::shared_ptr MakeShared(const AZ::Transform& worldFromLocal); - /// Unchanging data set once for the linear manipulator. + //! Unchanging data set once for the linear manipulator. struct Fixed { - AZ::Vector3 m_axis = AZ::Vector3::CreateAxisX(); ///< The axis the manipulator will move along. + AZ::Vector3 m_axis = AZ::Vector3::CreateAxisX(); //!< The axis the manipulator will move along. }; - /// Data passed between the initial press and first movement of the linear manipulator. + //! Data passed between the initial press and first movement of the linear manipulator. struct StartTransition { - /// The normal in local space of the manipulator when the mouse down event happens. + //! The normal in local space of the manipulator when the mouse down event happens. AZ::Vector3 m_localNormal; - /// Used to scale movement based on camera distance if we want screen space instead - /// of world space displacement. + //! Used to scale movement based on camera distance if we want screen space instead + //! of world space displacement. float m_screenToWorldScale; }; - /// The state of the manipulator at the start of an interaction. + //! The state of the manipulator at the start of an interaction. struct Start { - AZ::Vector3 m_localPosition; ///< The current position of the manipulator in local space. - AZ::Vector3 m_localScale; ///< The current scale of the manipulator in local space. - AZ::Vector3 m_localHitPosition; ///< The intersection point in local space between the ray and the manipulator when the mouse down event happens. - AZ::Vector3 m_localAxis; ///< The axis in the local space of the manipulator itself. - float m_sign; ///< Used to determine which side of the axis we clicked on in case it's flipped to face the camera. - AzFramework::ScreenPoint m_screenPosition; ///< The initial position in screen space of the manipulator. + AZ::Vector3 m_localPosition; //!< The current position of the manipulator in local space. + AZ::Vector3 m_localScale; //!< The current scale of the manipulator in local space. + AZ::Vector3 m_localHitPosition; //!< The intersection point in local space between the ray and the manipulator when the mouse + //!< down event happens. + AZ::Vector3 m_localAxis; //!< The axis in the local space of the manipulator itself. + float m_sign; //!< Used to determine which side of the axis we clicked on in case it's flipped to face the camera. + AzFramework::ScreenPoint m_screenPosition; //!< The initial position in screen space of the manipulator. }; - /// The state of the manipulator during an interaction. + //! The state of the manipulator during an interaction. struct Current { - AZ::Vector3 m_localPositionOffset; ///< The current offset of the manipulator from its starting position in local space. - AZ::Vector3 m_localScaleOffset; ///< The current offset of the manipulator from its starting scale in local space. - AzFramework::ScreenPoint m_screenPosition; ///< The current position in screen space of the manipulator. + AZ::Vector3 m_localPositionOffset; //!< The current offset of the manipulator from its starting position in local space. + AZ::Vector3 m_localScaleOffset; //!< The current offset of the manipulator from its starting scale in local space. + AzFramework::ScreenPoint m_screenPosition; //!< The current position in screen space of the manipulator. }; - /// Mouse action data used by MouseActionCallback (wraps Fixed, Start and Current manipulator state). + //! Mouse action data used by MouseActionCallback (wraps Fixed, Start and Current manipulator state). struct Action { Fixed m_fixed; Start m_start; Current m_current; ViewportInteraction::KeyboardModifiers m_modifiers; - int m_viewportId; ///< The id of the viewport this manipulator is being used in. - AZ::Vector3 LocalScale() const { return m_start.m_localScale + m_current.m_localScaleOffset; } - AZ::Vector3 LocalScaleOffset() const { return m_current.m_localScaleOffset; } - AZ::Vector3 LocalPosition() const { return m_start.m_localPosition + m_current.m_localPositionOffset; } - AZ::Vector3 LocalPositionOffset() const { return m_current.m_localPositionOffset; } + int m_viewportId; //!< The id of the viewport this manipulator is being used in. + AZ::Vector3 LocalScale() const + { + return m_start.m_localScale + m_current.m_localScaleOffset; + } + AZ::Vector3 LocalScaleOffset() const + { + return m_current.m_localScaleOffset; + } + AZ::Vector3 LocalPosition() const + { + return m_start.m_localPosition + m_current.m_localPositionOffset; + } + AZ::Vector3 LocalPositionOffset() const + { + return m_current.m_localPositionOffset; + } AZ::Vector2 ScreenOffset() const { - return AzFramework::Vector2FromScreenVector( - m_current.m_screenPosition - m_start.m_screenPosition); + return AzFramework::Vector2FromScreenVector(m_current.m_screenPosition - m_start.m_screenPosition); } }; - /// This is the function signature of callbacks that will be invoked whenever a manipulator - /// is clicked on or dragged. + //! This is the function signature of callbacks that will be invoked whenever a manipulator + //! is clicked on or dragged. using MouseActionCallback = AZStd::function; - /// Tuple of StartTransition (initial mouse down to mouse move) and Start state. + //! Tuple of StartTransition (initial mouse down to mouse move) and Start state. using Starter = AZStd::tuple; void InstallLeftMouseDownCallback(const MouseActionCallback& onMouseDownCallback); @@ -116,7 +128,10 @@ namespace AzToolsFramework const ViewportInteraction::MouseInteraction& mouseInteraction) override; void SetAxis(const AZ::Vector3& axis); - const AZ::Vector3& GetAxis() const { return m_fixed.m_axis; } + const AZ::Vector3& GetAxis() const + { + return m_fixed.m_axis; + } template void SetViews(Views&& views) @@ -135,12 +150,9 @@ namespace AzToolsFramework } private: - void OnLeftMouseDownImpl( - const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; - void OnLeftMouseUpImpl( - const ViewportInteraction::MouseInteraction& interaction) override; - void OnMouseMoveImpl( - const ViewportInteraction::MouseInteraction& interaction) override; + void OnLeftMouseDownImpl(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; + void OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction) override; + void OnMouseMoveImpl(const ViewportInteraction::MouseInteraction& interaction) override; void InvalidateImpl() override; void SetBoundsDirtyImpl() override; @@ -155,16 +167,24 @@ namespace AzToolsFramework MouseActionCallback m_onLeftMouseUpCallback = nullptr; MouseActionCallback m_onMouseMoveCallback = nullptr; - ManipulatorViews m_manipulatorViews; ///< Look of manipulator. + ManipulatorViews m_manipulatorViews; //!< Look of manipulator. }; LinearManipulator::Starter CalculateLinearManipulationDataStart( - const LinearManipulator::Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, float intersectionDistance, + const LinearManipulator::Fixed& fixed, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, + const ViewportInteraction::MouseInteraction& interaction, + float intersectionDistance, const AzFramework::CameraState& cameraState); LinearManipulator::Action CalculateLinearManipulationDataAction( - const LinearManipulator::Fixed& fixed, const LinearManipulator::Starter& starter, - const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, - const GridSnapParameters& gridSnapParams, const ViewportInteraction::MouseInteraction& interaction); + const LinearManipulator::Fixed& fixed, + const LinearManipulator::Starter& starter, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, + const GridSnapParameters& gridSnapParams, + const ViewportInteraction::MouseInteraction& interaction); } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorBus.h index 7768368d6b..a79a14abc2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorBus.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -26,56 +26,55 @@ namespace AzToolsFramework using ManipulatorManagerId = IdType; static const ManipulatorManagerId InvalidManipulatorManagerId = ManipulatorManagerId(0); - /// EBus interface used to send requests to ManipulatorManager. - class ManipulatorManagerRequests - : public AZ::EBusTraits + //! EBus interface used to send requests to ManipulatorManager. + class ManipulatorManagerRequests : public AZ::EBusTraits { public: - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; /**< We can have multiple manipulator managers. - In the case where there are multiple viewports, each displaying - a different set of entities, a different manipulator manager is required - to provide a different collision space for each viewport so that mouse - hit detection can be handled properly. */ + //! We can have multiple manipulator managers. + //! In the case where there are multiple viewports, each displaying + //! a different set of entities, a different manipulator manager is required + //! to provide a different collision space for each viewport so that mouse + //! hit detection can be handled properly. + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; using BusIdType = ManipulatorManagerId; static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; virtual ~ManipulatorManagerRequests() = default; - /// Register a manipulator with the Manipulator Manager. - /// @param manipulator The manipulator parameter is passed as a shared_ptr so - /// that the system responsible for managing manipulators can maintain ownership - /// of the manipulator even if is destroyed while in use. + //! Register a manipulator with the Manipulator Manager. + //! @param manipulator The manipulator parameter is passed as a shared_ptr so + //! that the system responsible for managing manipulators can maintain ownership + //! of the manipulator even if is destroyed while in use. virtual void RegisterManipulator(AZStd::shared_ptr manipulator) = 0; - /// Unregister a manipulator from the Manipulator Manager. - /// After unregistering the manipulator, it will be excluded from mouse hit detection - /// and will not receive any mouse action events. The Manipulator Manager will also - /// relinquish ownership of the manipulator. + //! Unregister a manipulator from the Manipulator Manager. + //! After unregistering the manipulator, it will be excluded from mouse hit detection + //! and will not receive any mouse action events. The Manipulator Manager will also + //! relinquish ownership of the manipulator. virtual void UnregisterManipulator(BaseManipulator* manipulator) = 0; - /// Delete a manipulator bound. + //! Delete a manipulator bound. virtual void DeleteManipulatorBound(Picking::RegisteredBoundId boundId) = 0; - /// Mark the bound of a manipulator dirty so it's excluded from mouse hit detection. - /// This should be called whenever a manipulator is moved. + //! Mark the bound of a manipulator dirty so it's excluded from mouse hit detection. + //! This should be called whenever a manipulator is moved. virtual void SetBoundDirty(Picking::RegisteredBoundId boundId) = 0; - /// Returns true if the manipulator manager is currently interacting, otherwise false. + //! Returns true if the manipulator manager is currently interacting, otherwise false. virtual bool Interacting() const = 0; - /// Update the bound for a manipulator. - /// If \ref boundId hasn't been registered before or it's invalid, a new bound is created and set using \ref boundShapeData - /// @param manipulatorId The id of the manipulator whose bound needs to update. - /// @param boundId The id of the bound that needs to update. - /// @param boundShapeData The pointer to the new bound shape data. - /// @return If \ref boundId has been registered return the same id, otherwise create a new bound and return its id. + //! Update the bound for a manipulator. + //! If \ref boundId hasn't been registered before or it's invalid, a new bound is created and set using \ref boundShapeData. + //! @param manipulatorId The id of the manipulator whose bound needs to update. + //! @param boundId The id of the bound that needs to update. + //! @param boundShapeData The pointer to the new bound shape data. + //! @return If \ref boundId has been registered return the same id, otherwise create a new bound and return its id. virtual Picking::RegisteredBoundId UpdateBound( - ManipulatorId manipulatorId, Picking::RegisteredBoundId boundId, - const Picking::BoundRequestShapeBase& boundShapeData) = 0; + ManipulatorId manipulatorId, Picking::RegisteredBoundId boundId, const Picking::BoundRequestShapeBase& boundShapeData) = 0; }; - /// Type to inherit to implement ManipulatorManagerRequests. + //! Type to inherit to implement ManipulatorManagerRequests. using ManipulatorManagerRequestBus = AZ::EBus; -}//namespace AzToolsFramework +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.cpp index c856c5f9a8..3a6a2487c3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.cpp @@ -1,17 +1,17 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ -#include "BaseManipulator.h" #include "ManipulatorManager.h" +#include "BaseManipulator.h" #include #include @@ -51,7 +51,8 @@ namespace AzToolsFramework if (manipulator->Registered()) { - AZ_Assert(manipulator->GetManipulatorManagerId() == m_manipulatorManagerId, + AZ_Assert( + manipulator->GetManipulatorManagerId() == m_manipulatorManagerId, "This manipulator was registered with a different manipulator manager!"); return; } @@ -75,8 +76,7 @@ namespace AzToolsFramework } Picking::RegisteredBoundId ManipulatorManager::UpdateBound( - const ManipulatorId manipulatorId, const Picking::RegisteredBoundId boundId, - const Picking::BoundRequestShapeBase& boundShapeData) + const ManipulatorId manipulatorId, const Picking::RegisteredBoundId boundId, const Picking::BoundRequestShapeBase& boundShapeData) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -99,8 +99,7 @@ namespace AzToolsFramework AZ_Assert(boundItr->second == manipulatorId, "Manipulator and its bounds are out of synchronization!"); } - const Picking::RegisteredBoundId newBoundId = - m_boundManager.UpdateOrRegisterBound(boundShapeData, boundId); + const Picking::RegisteredBoundId newBoundId = m_boundManager.UpdateOrRegisterBound(boundShapeData, boundId); if (newBoundId != boundId) { @@ -142,13 +141,6 @@ namespace AzToolsFramework } } - void ManipulatorManager::CheckModifierKeysChanged( - [[maybe_unused]] const ViewportInteraction::KeyboardModifiers keyboardModifiers, - const ViewportInteraction::MousePick& mousePick) - { - RefreshMouseOverState(mousePick); - } - void ManipulatorManager::DrawManipulators( AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, @@ -181,7 +173,8 @@ namespace AzToolsFramework if (found != m_boundIdToManipulatorIdMap.end()) { const auto manipulatorFound = m_manipulatorIdToPtrMap.find(found->second); - AZ_Assert(manipulatorFound != m_manipulatorIdToPtrMap.end(), + AZ_Assert( + manipulatorFound != m_manipulatorIdToPtrMap.end(), "Found a bound without a corresponding Manipulator, " "it's likely a bound was not cleaned up correctly"); rayIntersectionDistance = hitItr.second; @@ -194,10 +187,9 @@ namespace AzToolsFramework bool ManipulatorManager::ConsumeViewportMousePress(const ViewportInteraction::MouseInteraction& interaction) { - if (auto pickedManipulator = PickManipulator(interaction.m_mousePick); - pickedManipulator.has_value()) + if (auto pickedManipulator = PickManipulator(interaction.m_mousePick); pickedManipulator.has_value()) { - auto[manipulator, intersectionDistance] = pickedManipulator.value(); + auto [manipulator, intersectionDistance] = pickedManipulator.value(); if (interaction.m_mouseButtons.Left()) { @@ -249,24 +241,19 @@ namespace AzToolsFramework const ViewportInteraction::MousePick& mousePick) { float intersectionDistance = 0.0f; - const AZStd::shared_ptr pickedManipulator = PerformRaycast( - mousePick.m_rayOrigin, mousePick.m_rayDirection, intersectionDistance); + const AZStd::shared_ptr pickedManipulator = + PerformRaycast(mousePick.m_rayOrigin, mousePick.m_rayDirection, intersectionDistance); - return pickedManipulator.get() != nullptr - ? AZStd::make_optional(AZStd::make_tuple(pickedManipulator, intersectionDistance)) - : AZStd::nullopt; + return pickedManipulator.get() != nullptr ? AZStd::make_optional(AZStd::make_tuple(pickedManipulator, intersectionDistance)) + : AZStd::nullopt; } - ManipulatorManager::PickedManipulatorId ManipulatorManager::PickManipulatorId( - const ViewportInteraction::MousePick& mousePick) + ManipulatorManager::PickedManipulatorId ManipulatorManager::PickManipulatorId(const ViewportInteraction::MousePick& mousePick) { - auto [manipulator, intersectionDistance] = - PickManipulator(mousePick).value_or(PickedManipulator(nullptr, 0.0f)); - const ManipulatorId pickedManipulatorId = manipulator - ? manipulator->GetManipulatorId() - : InvalidManipulatorId; + auto [manipulator, intersectionDistance] = PickManipulator(mousePick).value_or(PickedManipulator(nullptr, 0.0f)); + const ManipulatorId pickedManipulatorId = manipulator ? manipulator->GetManipulatorId() : InvalidManipulatorId; - return PickedManipulatorId{pickedManipulatorId, intersectionDistance}; + return PickedManipulatorId{ pickedManipulatorId, intersectionDistance }; } ManipulatorManager::ConsumeMouseMoveResult ManipulatorManager::ConsumeViewportMouseMove( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.h index 5f57738b8c..66b38579ef 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -23,7 +23,7 @@ namespace AzFramework { struct CameraState; class DebugDisplayRequests; -} +} // namespace AzFramework namespace AzToolsFramework { @@ -40,15 +40,15 @@ namespace AzToolsFramework class BaseManipulator; class LinearManipulator; - /// State of overall manipulator manager. + //! State of overall manipulator manager. struct ManipulatorManagerState { bool m_interacting; }; - /// This class serves to manage all relevant mouse events and coordinate all registered manipulators to function properly. - /// ManipulatorManager does not manage the life cycle of specific manipulators. The users of manipulators are responsible - /// for creating and deleting them at right time, as well as registering and unregistering accordingly. + //! This class serves to manage all relevant mouse events and coordinate all registered manipulators to function properly. + //! ManipulatorManager does not manage the life cycle of specific manipulators. The users of manipulators are responsible + //! for creating and deleting them at right time, as well as registering and unregistering accordingly. class ManipulatorManager : private ManipulatorManagerRequestBus::Handler , private EditorEntityInfoNotificationBus::Handler @@ -59,7 +59,7 @@ namespace AzToolsFramework explicit ManipulatorManager(ManipulatorManagerId managerId); ~ManipulatorManager(); - /// The result of consuming a mouse move. + //! The result of consuming a mouse move. enum class ConsumeMouseMoveResult { None, @@ -80,57 +80,52 @@ namespace AzToolsFramework void DeleteManipulatorBound(Picking::RegisteredBoundId boundId) override; void SetBoundDirty(Picking::RegisteredBoundId boundId) override; Picking::RegisteredBoundId UpdateBound( - ManipulatorId manipulatorId, Picking::RegisteredBoundId boundId, - const Picking::BoundRequestShapeBase& boundShapeData) override; - bool Interacting() const override { return m_activeManipulator != nullptr; } + ManipulatorId manipulatorId, Picking::RegisteredBoundId boundId, const Picking::BoundRequestShapeBase& boundShapeData) override; + bool Interacting() const override + { + return m_activeManipulator != nullptr; + } void DrawManipulators( AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction); - // O3DE_DEPRECATED(LY-117150) - /// Check if the modifier key state has changed - if so we may need to refresh - /// certain manipulator bounds. - AZ_DEPRECATED( - void CheckModifierKeysChanged( - ViewportInteraction::KeyboardModifiers keyboardModifiers, - const ViewportInteraction::MousePick& mousePick), - "CheckModifierKeysChanged is deprecated and will be removed in a future release"); - protected: - /// @param rayOrigin The origin of the ray to test intersection with. - /// @param rayDirection The direction of the ray to test intersection with. - /// @param[out] rayIntersectionDistance The result intersecting point equals "rayOrigin + rayIntersectionDistance * rayDirection". - /// @return A pointer to a manipulator that the ray intersects. Null pointer if no intersection is detected. + //! @param rayOrigin The origin of the ray to test intersection with. + //! @param rayDirection The direction of the ray to test intersection with. + //! @param[out] rayIntersectionDistance The result intersecting point equals "rayOrigin + rayIntersectionDistance * rayDirection". + //! @return A pointer to a manipulator that the ray intersects. Null pointer if no intersection is detected. AZStd::shared_ptr PerformRaycast( const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, float& rayIntersectionDistance); // EditorEntityInfoNotifications ... void OnEntityInfoUpdatedVisibility(AZ::EntityId entityId, bool visible) override; - /// Alias for a Manipulator and intersection distance. + //! Alias for a Manipulator and intersection distance. using PickedManipulator = AZStd::tuple, float>; - /// Alias for a ManipulatorId and intersection distance. + //! Alias for a ManipulatorId and intersection distance. using PickedManipulatorId = AZStd::tuple; - /// Return the picked manipulator and intersection distance if a manipulator was intersected. + //! Return the picked manipulator and intersection distance if a manipulator was intersected. AZStd::optional PickManipulator(const ViewportInteraction::MousePick& mousePick); - /// Wrapper for PickManipulator to return the ManipulatorId directly. + //! Wrapper for PickManipulator to return the ManipulatorId directly. PickedManipulatorId PickManipulatorId(const ViewportInteraction::MousePick& mousePick); - /// Called once per frame after all manipulators have been drawn (and their - /// bounds updated if required). + //! Called once per frame after all manipulators have been drawn (and their + //! bounds updated if required). void RefreshMouseOverState(const ViewportInteraction::MousePick& mousePick); - ManipulatorManagerId m_manipulatorManagerId; ///< This manipulator manager's id. - ManipulatorId m_nextManipulatorIdToGenerate; ///< Id to use for the next manipulator that is registered with this manager. + ManipulatorManagerId m_manipulatorManagerId; //!< This manipulator manager's id. + ManipulatorId m_nextManipulatorIdToGenerate; //!< Id to use for the next manipulator that is registered with this manager. - AZStd::unordered_map> m_manipulatorIdToPtrMap; ///< Mapping from a manipulatorId to the corresponding manipulator. - AZStd::unordered_map m_boundIdToManipulatorIdMap; ///< Mapping from a boundId to the corresponding manipulatorId. + AZStd::unordered_map> + m_manipulatorIdToPtrMap; //!< Mapping from a manipulatorId to the corresponding manipulator. + AZStd::unordered_map + m_boundIdToManipulatorIdMap; //!< Mapping from a boundId to the corresponding manipulatorId. - AZStd::shared_ptr m_activeManipulator; ///< The manipulator we are currently interacting with. - Picking::ManipulatorBoundManager m_boundManager; ///< All active manipulator bounds that could be interacted with. + AZStd::shared_ptr m_activeManipulator; //!< The manipulator we are currently interacting with. + Picking::ManipulatorBoundManager m_boundManager; //!< All active manipulator bounds that could be interacted with. }; // The main/default ManipulatorManagerId to be used for diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.cpp index 8a6398d025..427bb9e9d1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "ManipulatorSnapping.h" @@ -19,19 +19,27 @@ #include AZ_CVAR( - AZ::Color, cl_viewportGridMainColor, AZ::Color::CreateFromRgba(26, 26, 26, 127), nullptr, - AZ::ConsoleFunctorFlags::Null, "Main color for snapping grid"); + AZ::Color, + cl_viewportGridMainColor, + AZ::Color::CreateFromRgba(26, 26, 26, 127), + nullptr, + AZ::ConsoleFunctorFlags::Null, + "Main color for snapping grid"); AZ_CVAR( - AZ::Color, cl_viewportGridFadeColor, AZ::Color::CreateFromRgba(127, 127, 127, 0), nullptr, - AZ::ConsoleFunctorFlags::Null, "Fade color for snapping grid"); + AZ::Color, + cl_viewportGridFadeColor, + AZ::Color::CreateFromRgba(127, 127, 127, 0), + nullptr, + AZ::ConsoleFunctorFlags::Null, + "Fade color for snapping grid"); +AZ_CVAR(int, cl_viewportGridSquareCount, 20, nullptr, AZ::ConsoleFunctorFlags::Null, "Number of grid squares for snapping grid"); +AZ_CVAR(float, cl_viewportGridLineWidth, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "Width of grid lines for snapping grid"); AZ_CVAR( - int, cl_viewportGridSquareCount, 20, nullptr, AZ::ConsoleFunctorFlags::Null, - "Number of grid squares for snapping grid"); -AZ_CVAR( - float, cl_viewportGridLineWidth, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, - "Width of grid lines for snapping grid"); -AZ_CVAR( - float, cl_viewportFadeLineDistanceScale, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, + float, + cl_viewportFadeLineDistanceScale, + 1.0f, + nullptr, + AZ::ConsoleFunctorFlags::Null, "The scale to be applied to the line that fades out (scales the current gridSize)"); namespace AzToolsFramework @@ -43,16 +51,17 @@ namespace AzToolsFramework } ManipulatorInteraction BuildManipulatorInteraction( - const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Vector3& worldRayOrigin, const AZ::Vector3& worldRayDirection) + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Vector3& worldRayOrigin, + const AZ::Vector3& worldRayDirection) { const AZ::Transform worldFromLocalUniform = AzToolsFramework::TransformUniformScale(worldFromLocal); const AZ::Transform localFromWorldUniform = worldFromLocalUniform.GetInverse(); - return {localFromWorldUniform.TransformPoint(worldRayOrigin), - TransformDirectionNoScaling(localFromWorldUniform, worldRayDirection), - NonUniformScaleReciprocal(nonUniformScale), - ScaleReciprocal(worldFromLocalUniform)}; + return { localFromWorldUniform.TransformPoint(worldRayOrigin), + TransformDirectionNoScaling(localFromWorldUniform, worldRayDirection), NonUniformScaleReciprocal(nonUniformScale), + ScaleReciprocal(worldFromLocalUniform) }; } struct SnapAdjustment @@ -87,8 +96,7 @@ namespace AzToolsFramework } AZ::Vector3 CalculateSnappedTerrainPosition( - const AZ::Vector3& worldSurfacePosition, const AZ::Transform& worldFromLocal, - const int viewportId, const float gridSize) + const AZ::Vector3& worldSurfacePosition, const AZ::Transform& worldFromLocal, const int viewportId, const float gridSize) { const AZ::Transform localFromWorld = worldFromLocal.GetInverse(); const AZ::Vector3 localSurfacePosition = localFromWorld.TransformPoint(worldSurfacePosition); @@ -101,8 +109,7 @@ namespace AzToolsFramework // find terrain height at xy snapped location float terrainHeight = 0.0f; ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( - terrainHeight, viewportId, - &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::TerrainHeight, + terrainHeight, viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::TerrainHeight, Vector3ToVector2(worldFromLocal.TransformPoint(localSnappedSurfacePosition))); // set snapped z value to terrain height @@ -116,8 +123,7 @@ namespace AzToolsFramework { bool snapping = false; ViewportInteraction::ViewportInteractionRequestBus::EventResult( - snapping, viewportId, - &ViewportInteraction::ViewportInteractionRequestBus::Events::GridSnappingEnabled); + snapping, viewportId, &ViewportInteraction::ViewportInteractionRequestBus::Events::GridSnappingEnabled); return snapping; } @@ -126,8 +132,7 @@ namespace AzToolsFramework { float gridSize = 0.0f; ViewportInteraction::ViewportInteractionRequestBus::EventResult( - gridSize, viewportId, - &ViewportInteraction::ViewportInteractionRequestBus::Events::GridSize); + gridSize, viewportId, &ViewportInteraction::ViewportInteractionRequestBus::Events::GridSize); return gridSize; } @@ -136,7 +141,8 @@ namespace AzToolsFramework { bool snapping = GridSnapping(viewportId); const float gridSize = GridSize(viewportId); - if (AZ::IsClose(gridSize, 0.0f, 1e-2f)) // Same threshold value as min value for m_spinBox in SnapToWidget constructor in MainWindow.cpp + if (AZ::IsClose( + gridSize, 0.0f, 1e-2f)) // Same threshold value as min value for m_spinBox in SnapToWidget constructor in MainWindow.cpp { snapping = false; } @@ -148,8 +154,7 @@ namespace AzToolsFramework { bool snapping = false; ViewportInteraction::ViewportInteractionRequestBus::EventResult( - snapping, viewportId, - &ViewportInteraction::ViewportInteractionRequestBus::Events::AngleSnappingEnabled); + snapping, viewportId, &ViewportInteraction::ViewportInteractionRequestBus::Events::AngleSnappingEnabled); return snapping; } @@ -158,8 +163,7 @@ namespace AzToolsFramework { float angle = 0.0f; ViewportInteraction::ViewportInteractionRequestBus::EventResult( - angle, viewportId, - &ViewportInteraction::ViewportInteractionRequestBus::Events::AngleStep); + angle, viewportId, &ViewportInteraction::ViewportInteractionRequestBus::Events::AngleStep); return angle; } @@ -168,14 +172,12 @@ namespace AzToolsFramework { bool show = false; ViewportInteraction::ViewportInteractionRequestBus::EventResult( - show, viewportId, - &ViewportInteraction::ViewportInteractionRequestBus::Events::ShowGrid); + show, viewportId, &ViewportInteraction::ViewportInteractionRequestBus::Events::ShowGrid); return show; } - void DrawSnappingGrid( - AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Transform& worldFromLocal, const float squareSize) + void DrawSnappingGrid(AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Transform& worldFromLocal, const float squareSize) { debugDisplay.PushMatrix(worldFromLocal); @@ -197,21 +199,17 @@ namespace AzToolsFramework // draw the faded end parts of the grid lines debugDisplay.DrawLine( - AZ::Vector3(lineOffset, -halfGridSize, 0.0f), - AZ::Vector3(lineOffset, -(halfGridSize + fadeLineLength), 0.0f), + AZ::Vector3(lineOffset, -halfGridSize, 0.0f), AZ::Vector3(lineOffset, -(halfGridSize + fadeLineLength), 0.0f), gridMainColor, gridFadeColor); debugDisplay.DrawLine( - AZ::Vector3(lineOffset, halfGridSize, 0.0f), - AZ::Vector3(lineOffset, (halfGridSize + fadeLineLength), 0.0f), + AZ::Vector3(lineOffset, halfGridSize, 0.0f), AZ::Vector3(lineOffset, (halfGridSize + fadeLineLength), 0.0f), gridMainColor, + gridFadeColor); + debugDisplay.DrawLine( + AZ::Vector3(-halfGridSize, lineOffset, 0.0f), AZ::Vector3(-(halfGridSize + fadeLineLength), lineOffset, 0.0f), gridMainColor, gridFadeColor); debugDisplay.DrawLine( - AZ::Vector3(-halfGridSize, lineOffset, 0.0f), - AZ::Vector3(-(halfGridSize + fadeLineLength), lineOffset, 0.0f), - gridMainColor, gridFadeColor); - debugDisplay.DrawLine( - AZ::Vector3(halfGridSize, lineOffset, 0.0f), - AZ::Vector3((halfGridSize + fadeLineLength), lineOffset, 0.0f), - gridMainColor, gridFadeColor); + AZ::Vector3(halfGridSize, lineOffset, 0.0f), AZ::Vector3((halfGridSize + fadeLineLength), lineOffset, 0.0f), gridMainColor, + gridFadeColor); // build a vector of the main grid lines to draw (start and end positions) lines.push_back(AZ::Vector3(lineOffset, -halfGridSize, 0.0f)); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h index 11860780c7..f2fa104d4c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSnapping.h @@ -1,19 +1,19 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once -#include #include +#include namespace AzFramework { @@ -22,7 +22,7 @@ namespace AzFramework namespace AzToolsFramework { - /// Structure to encapsulate grid snapping properties. + //! Structure to encapsulate grid snapping properties. struct GridSnapParameters { GridSnapParameters(bool gridSnap, float gridSize); @@ -31,96 +31,92 @@ namespace AzToolsFramework float m_gridSize; }; - /// Structure to hold transformed incoming viewport interaction from world space to manipulator space. + //! Structure to hold transformed incoming viewport interaction from world space to manipulator space. struct ManipulatorInteraction { - AZ::Vector3 m_localRayOrigin; ///< The ray origin (start) in the reference from of the manipulator. - AZ::Vector3 m_localRayDirection; ///< The ray direction in the reference from of the manipulator. - AZ::Vector3 m_nonUniformScaleReciprocal; ///< Handles inverting any non-uniform scale which was applied - ///< separately from the transform. - float m_scaleReciprocal; ///< The scale reciprocal (1.0 / scale) of the transform used to move the - ///< ray from world space to local space. + AZ::Vector3 m_localRayOrigin; //!< The ray origin (start) in the reference from of the manipulator. + AZ::Vector3 m_localRayDirection; //!< The ray direction in the reference from of the manipulator. + AZ::Vector3 m_nonUniformScaleReciprocal; //!< Handles inverting any non-uniform scale which was applied + //!< separately from the transform. + float m_scaleReciprocal; //!< The scale reciprocal (1.0 / scale) of the transform used to move the + //!< ray from world space to local space. }; - /// Build a ManipulatorInteraction structure from the incoming viewport interaction. + //! Build a ManipulatorInteraction structure from the incoming viewport interaction. ManipulatorInteraction BuildManipulatorInteraction( - const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Vector3& worldRayOrigin, const AZ::Vector3& worldRayDirection); + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Vector3& worldRayOrigin, + const AZ::Vector3& worldRayDirection); - /// Calculate the offset along an axis to adjust a position to stay snapped to a given grid size. - /// @note This is snap up or down to the nearest grid segment (e.g. 0.2 snaps to 0.0 -> delta 0.2, - /// 0.7 snaps to 1.0 -> delta 0.3). - AZ::Vector3 CalculateSnappedOffset( - const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, float size); + //! Calculate the offset along an axis to adjust a position to stay snapped to a given grid size. + //! @note This is snap up or down to the nearest grid segment (e.g. 0.2 snaps to 0.0 -> delta 0.2, + //! 0.7 snaps to 1.0 -> delta 0.3). + AZ::Vector3 CalculateSnappedOffset(const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, float size); - /// Return the amount to snap from the starting position given the current grid size. - /// @note A movement of more than half size (in either direction) will cause a snap by size. + //! Return the amount to snap from the starting position given the current grid size. + //! @note A movement of more than half size (in either direction) will cause a snap by size. AZ::Vector3 CalculateSnappedAmount(const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, float size); - /// For a given point on the terrain, calculate the closest xy position snapped to the grid - /// (z position is aligned to terrain height, not snapped to z grid) + //! For a given point on the terrain, calculate the closest xy position snapped to the grid + //! (z position is aligned to terrain height, not snapped to z grid) AZ::Vector3 CalculateSnappedTerrainPosition( - const AZ::Vector3& worldSurfacePosition, const AZ::Transform& worldFromLocal, - int viewportId, float gridSize); + const AZ::Vector3& worldSurfacePosition, const AZ::Transform& worldFromLocal, int viewportId, float gridSize); - /// Wrapper for grid snapping and grid size bus calls. + //! Wrapper for grid snapping and grid size bus calls. GridSnapParameters GridSnapSettings(int viewportId); - /// Wrapper for angle snapping enabled bus call. + //! Wrapper for angle snapping enabled bus call. bool AngleSnapping(int viewportId); - /// Wrapper for angle snapping increment bus call. - /// @return Angle in degrees + //! Wrapper for angle snapping increment bus call. + //! @return Angle in degrees. float AngleStep(int viewportId); - /// Wrapper for grid rendering check call. + //! Wrapper for grid rendering check call. bool ShowingGrid(int viewportId); - /// Render the grid used for snapping. - void DrawSnappingGrid( - AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Transform& worldFromLocal, float squareSize); + //! Render the grid used for snapping. + void DrawSnappingGrid(AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Transform& worldFromLocal, float squareSize); - /// Round to x number of significant digits. - /// @param value Number to round. - /// @param exponent Precision to use when rounding. + //! Round to x number of significant digits. + //! @param value Number to round. + //! @param exponent Precision to use when rounding. inline float Round(const float value, const float exponent) { const float precision = std::pow(10.0f, exponent); return roundf(value * precision) / precision; } - /// Round to 3 significant digits (3 digits common usage). + //! Round to 3 significant digits (3 digits common usage). inline float Round3(const float value) { return Round(value, 3.0f); } - /// Util to return sign of floating point number. - /// value > 0 return 1.0 - /// value < 0 return -1.0 - /// value == 0 return 0.0 + //! Util to return sign of floating point number. + //! value > 0 return 1.0 + //! value < 0 return -1.0 + //! value == 0 return 0.0 inline float Sign(const float value) { return static_cast((0.0f < value) - (value < 0.0f)); } - /// Find the max scale element and return the reciprocal of it. - /// Note: The reciprocal will be rounded to three significant digits to eliminate - /// noise in the value returned when dealing with values far from the origin. + //! Find the max scale element and return the reciprocal of it. + //! Note: The reciprocal will be rounded to three significant digits to eliminate + //! noise in the value returned when dealing with values far from the origin. inline float ScaleReciprocal(const AZ::Transform& transform) { return Round3(1.0f / transform.GetUniformScale()); } - /// Find the reciprocal of the non-uniform scale. - /// Each element will be rounded to three significant digits to eliminate noise - /// when dealing with values far from the origin. + //! Find the reciprocal of the non-uniform scale. + //! Each element will be rounded to three significant digits to eliminate noise + //! when dealing with values far from the origin. inline AZ::Vector3 NonUniformScaleReciprocal(const AZ::Vector3& nonUniformScale) { AZ::Vector3 scaleReciprocal = nonUniformScale.GetReciprocal(); - return AZ::Vector3( - Round3(scaleReciprocal.GetX()), - Round3(scaleReciprocal.GetY()), - Round3(scaleReciprocal.GetZ())); + return AZ::Vector3(Round3(scaleReciprocal.GetX()), Round3(scaleReciprocal.GetY()), Round3(scaleReciprocal.GetZ())); } } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.h index e26c6b8947..7c1176dd2c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorSpace.h @@ -20,7 +20,7 @@ namespace AZ namespace AzToolsFramework { - /// Handles location for manipulators which have a global space but no local transformation. + //! Handles location for manipulators which have a global space but no local transformation. class ManipulatorSpace { public: @@ -32,17 +32,16 @@ namespace AzToolsFramework const AZ::Vector3& GetNonUniformScale() const; void SetNonUniformScale(const AZ::Vector3& nonUniformScale); - /// Calculates a transform combining the space and local transform, taking non-uniform scale into account. + //! Calculates a transform combining the space and local transform, taking non-uniform scale into account. AZ::Transform ApplySpace(const AZ::Transform& localTransform) const; private: - AZ::Transform m_space = AZ::Transform::CreateIdentity(); ///< Space the manipulator is in. - AZ::Vector3 m_nonUniformScale = AZ::Vector3::CreateOne(); ///< Handles non-uniform scale for the space the manipulator is in. + AZ::Transform m_space = AZ::Transform::CreateIdentity(); //!< Space the manipulator is in. + AZ::Vector3 m_nonUniformScale = AZ::Vector3::CreateOne(); //!< Handles non-uniform scale for the space the manipulator is in. }; - /// Handles location for manipulators which have a global space and a local position, but no local rotation. - class ManipulatorSpaceWithLocalPosition - : public ManipulatorSpace + //! Handles location for manipulators which have a global space and a local position, but no local rotation. + class ManipulatorSpaceWithLocalPosition : public ManipulatorSpace { public: AZ_TYPE_INFO(ManipulatorSpaceWithLocalPosition, "{47BE15AF-60A8-436B-8F3F-7DDFB97220E6}") @@ -52,12 +51,11 @@ namespace AzToolsFramework void SetLocalPosition(const AZ::Vector3& localPosition); private: - AZ::Vector3 m_localPosition = AZ::Vector3::CreateZero(); ///< Position in local space. + AZ::Vector3 m_localPosition = AZ::Vector3::CreateZero(); //!< Position in local space. }; - /// Handles location for manipulators which have a global space and a local transform (position and rotation). - class ManipulatorSpaceWithLocalTransform - : public ManipulatorSpace + //! Handles location for manipulators which have a global space and a local transform (position and rotation). + class ManipulatorSpaceWithLocalTransform : public ManipulatorSpace { public: AZ_TYPE_INFO(ManipulatorSpaceWithLocalTransform, "{6D100797-1DD8-45B0-A21C-8893B770C0BC}") @@ -72,6 +70,6 @@ namespace AzToolsFramework void SetLocalOrientation(const AZ::Quaternion& localOrientation); private: - AZ::Transform m_localTransform = AZ::Transform::CreateIdentity(); ///< Local transform. + AZ::Transform m_localTransform = AZ::Transform::CreateIdentity(); //!< Local transform. }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorView.cpp index 150e23041d..a4c4a59ee6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorView.cpp @@ -1,26 +1,26 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "ManipulatorView.h" -#include #include +#include #include #include #include -#include #include -#include #include +#include +#include #include #include #include @@ -33,8 +33,7 @@ namespace AzToolsFramework AZ::Transform WorldFromLocalWithUniformScale(const AZ::EntityId entityId) { AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); return TransformUniformScale(worldFromLocal); } @@ -56,13 +55,16 @@ namespace AzToolsFramework return AzToolsFramework::TransformDirectionNoScaling(m_worldFromLocal, direction); } - /// Take into account the location of the camera and orientate the axis so it faces the camera. - /// if we did correct the camera (shouldCorrect is true) then we know the axis facing us it negative. - /// we can use this to change the rendering for a flipped axis if we wish. + // Take into account the location of the camera and orientate the axis so it faces the camera. + // if we did correct the camera (shouldCorrect is true) then we know the axis facing us it negative. + // we can use this to change the rendering for a flipped axis if we wish. static void CameraCorrectAxis( - const AZ::Vector3& axis, AZ::Vector3& correctedAxis, const ManipulatorManagerState& managerState, + const AZ::Vector3& axis, + AZ::Vector3& correctedAxis, + const ManipulatorManagerState& managerState, const ViewportInteraction::MouseInteraction& mouseInteraction, - const AZ::Transform& worldFromLocal, const AZ::Vector3& localPosition, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& localPosition, const AzFramework::CameraState& cameraState, bool* shouldCorrect = nullptr) { @@ -74,9 +76,7 @@ namespace AzToolsFramework const bool correcting = ShouldFlipCameraAxis(worldFromLocal, localPosition, axis, cameraState); // the corrected axis, if no flip was required, output == input - correctedAxis = correcting - ? -axis - : axis; + correctedAxis = correcting ? -axis : axis; // optional out ref to use if we care about the result if (shouldCorrect) @@ -86,10 +86,13 @@ namespace AzToolsFramework } } - /// Calculate quad bound in world space. + // calculate quad bound in world space. static Picking::BoundShapeQuad CalculateQuadBound( - const AZ::Vector3& localPosition, const ManipulatorState& manipulatorState, - const AZ::Vector3& axis1, const AZ::Vector3& axis2, const float size) + const AZ::Vector3& localPosition, + const ManipulatorState& manipulatorState, + const AZ::Vector3& axis1, + const AZ::Vector3& axis2, + const float size) { const AZ::Vector3 worldPosition = manipulatorState.TransformPoint(localPosition); const AZ::Vector3 endAxis1World = manipulatorState.TransformDirectionNoScaling(axis1) * size; @@ -104,8 +107,10 @@ namespace AzToolsFramework } static Picking::BoundShapeQuad CalculateQuadBoundBillboard( - const AZ::Vector3& localPosition, const AZ::Transform& worldFromLocal, - const float size, const AzFramework::CameraState& cameraState) + const AZ::Vector3& localPosition, + const AZ::Transform& worldFromLocal, + const float size, + const AzFramework::CameraState& cameraState) { const AZ::Vector3 worldPosition = worldFromLocal.TransformPoint(localPosition); @@ -117,10 +122,13 @@ namespace AzToolsFramework return quadBound; } - /// Calculate line bound in world space (axis and length). + // calculate line bound in world space (axis and length). static Picking::BoundShapeLineSegment CalculateLineBound( - const AZ::Vector3& localPosition, const AZ::Transform& worldFromLocal, - const AZ::Vector3& axis, const float length, const float width) + const AZ::Vector3& localPosition, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& axis, + const float length, + const float width) { Picking::BoundShapeLineSegment lineBound; lineBound.m_start = worldFromLocal.TransformPoint(localPosition); @@ -129,7 +137,7 @@ namespace AzToolsFramework return lineBound; } - /// Calculate line bound in world space (start and end point). + // calculate line bound in world space (start and end point). static Picking::BoundShapeLineSegment CalculateLineBound( const AZ::Vector3& localStartPosition, const AZ::Vector3& localEndPosition, @@ -143,10 +151,14 @@ namespace AzToolsFramework return lineBound; } - /// Calculate cone bound in world space. + // calculate cone bound in world space. static Picking::BoundShapeCone CalculateConeBound( - const AZ::Vector3& localPosition, const AZ::Transform& worldFromLocal, - const AZ::Vector3& axis, const AZ::Vector3& offset, const float length, const float radius) + const AZ::Vector3& localPosition, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& axis, + const AZ::Vector3& offset, + const float length, + const float radius) { Picking::BoundShapeCone coneBound; coneBound.m_radius = radius; @@ -156,10 +168,13 @@ namespace AzToolsFramework return coneBound; } - /// Calculate box bound in world space. + // calculate box bound in world space. static Picking::BoundShapeBox CalculateBoxBound( - const AZ::Vector3& localPosition, const AZ::Transform& worldFromLocal, - const AZ::Quaternion& orientation, const AZ::Vector3& offset, const AZ::Vector3& halfExtents) + const AZ::Vector3& localPosition, + const AZ::Transform& worldFromLocal, + const AZ::Quaternion& orientation, + const AZ::Vector3& offset, + const AZ::Vector3& halfExtents) { Picking::BoundShapeBox boxBound; boxBound.m_halfExtents = halfExtents; @@ -168,10 +183,13 @@ namespace AzToolsFramework return boxBound; } - /// Calculate cylinder bound in world space. + // calculate cylinder bound in world space. static Picking::BoundShapeCylinder CalculateCylinderBound( - const AZ::Vector3& localPosition, const AZ::Transform& worldFromLocal, - const AZ::Vector3& axis, const float length, const float radius) + const AZ::Vector3& localPosition, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& axis, + const float length, + const float radius) { Picking::BoundShapeCylinder boxBound; boxBound.m_base = worldFromLocal.TransformPoint(localPosition); @@ -181,10 +199,9 @@ namespace AzToolsFramework return boxBound; } - /// Calculate sphere bound in world space. + // calculate sphere bound in world space. static Picking::BoundShapeSphere CalculateSphereBound( - const AZ::Vector3& localPosition, const ManipulatorState& manipulatorState, - const float radius) + const AZ::Vector3& localPosition, const ManipulatorState& manipulatorState, const float radius) { Picking::BoundShapeSphere sphereBound; sphereBound.m_center = manipulatorState.TransformPoint(localPosition); @@ -192,10 +209,13 @@ namespace AzToolsFramework return sphereBound; } - /// Calculate torus bound in world space. + // calculate torus bound in world space. static Picking::BoundShapeTorus CalculateTorusBound( - const AZ::Vector3& localPosition, const AZ::Transform& worldFromLocal, - const AZ::Vector3& axis, const float radius, const float width) + const AZ::Vector3& localPosition, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& axis, + const float radius, + const float width) { Picking::BoundShapeTorus torusBound; torusBound.m_center = worldFromLocal.TransformPoint(localPosition); @@ -205,7 +225,7 @@ namespace AzToolsFramework return torusBound; } - /// Calculate spline bound in world space. + // calculate spline bound in world space. static Picking::BoundShapeSpline CalculateSplineBound( const AZStd::weak_ptr& spline, const AZ::Transform& worldFromLocal, const float width) { @@ -224,8 +244,7 @@ namespace AzToolsFramework return lineWidth[mouseOver]; } - static AZ::Color ViewColor( - const bool mouseOver, const AZ::Color& defaultColor, const AZ::Color& mouseOverColor) + static AZ::Color ViewColor(const bool mouseOver, const AZ::Color& defaultColor, const AZ::Color& mouseOverColor) { const AZStd::array viewColor = { { defaultColor, mouseOverColor } }; return viewColor[mouseOver].GetAsVector4(); @@ -250,19 +269,16 @@ namespace AzToolsFramework void ManipulatorView::SetBoundDirty(const ManipulatorManagerId managerId) { - ManipulatorManagerRequestBus::Event( - managerId, &ManipulatorManagerRequestBus::Events::SetBoundDirty, m_boundId); + ManipulatorManagerRequestBus::Event(managerId, &ManipulatorManagerRequestBus::Events::SetBoundDirty, m_boundId); m_boundDirty = true; } void ManipulatorView::RefreshBound( - const ManipulatorManagerId managerId, const ManipulatorId manipulatorId, - const Picking::BoundRequestShapeBase& bound) + const ManipulatorManagerId managerId, const ManipulatorId manipulatorId, const Picking::BoundRequestShapeBase& bound) { ManipulatorManagerRequestBus::EventResult( - m_boundId, managerId, &ManipulatorManagerRequestBus::Events::UpdateBound, - manipulatorId, m_boundId, bound); + m_boundId, managerId, &ManipulatorManagerRequestBus::Events::UpdateBound, manipulatorId, m_boundId, bound); // store the manager id if we know the bound has been registered m_managerId = managerId; @@ -271,8 +287,7 @@ namespace AzToolsFramework } void ManipulatorView::RefreshBoundInternal( - const ManipulatorManagerId managerId, const ManipulatorId manipulatorId, - const Picking::BoundRequestShapeBase& bound) + const ManipulatorManagerId managerId, const ManipulatorId manipulatorId, const Picking::BoundRequestShapeBase& bound) { // update the manipulator's bounds if necessary // if m_screenSizeFixed is true, any camera movement can potentially change the size @@ -287,8 +302,7 @@ namespace AzToolsFramework { if (m_boundId != Picking::InvalidBoundId) { - ManipulatorManagerRequestBus::Event( - managerId, &ManipulatorManagerRequestBus::Events::DeleteManipulatorBound, m_boundId); + ManipulatorManagerRequestBus::Event(managerId, &ManipulatorManagerRequestBus::Events::DeleteManipulatorBound, m_boundId); m_boundId = Picking::InvalidBoundId; } @@ -297,33 +311,34 @@ namespace AzToolsFramework float ManipulatorView::ManipulatorViewScaleMultiplier( const AZ::Vector3& worldPosition, const AzFramework::CameraState& cameraState) const { - return ScreenSizeFixed() - ? CalculateScreenToWorldMultiplier(worldPosition, cameraState) - : 1.0f; + return ScreenSizeFixed() ? CalculateScreenToWorldMultiplier(worldPosition, cameraState) : 1.0f; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void ManipulatorViewQuad::Draw( - const ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - const ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + const ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + const ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) { const AZ::Vector3 axis1 = m_axis1; const AZ::Vector3 axis2 = m_axis2; CameraCorrectAxis( - axis1, m_cameraCorrectedAxis1, managerState, mouseInteraction, - manipulatorState.m_worldFromLocal, manipulatorState.m_localPosition, cameraState); + axis1, m_cameraCorrectedAxis1, managerState, mouseInteraction, manipulatorState.m_worldFromLocal, + manipulatorState.m_localPosition, cameraState); CameraCorrectAxis( - axis2, m_cameraCorrectedAxis2, managerState, mouseInteraction, - manipulatorState.m_worldFromLocal, manipulatorState.m_localPosition, cameraState); + axis2, m_cameraCorrectedAxis2, managerState, mouseInteraction, manipulatorState.m_worldFromLocal, + manipulatorState.m_localPosition, cameraState); - const Picking::BoundShapeQuad quadBound = - CalculateQuadBound( - manipulatorState.m_localPosition, manipulatorState, m_cameraCorrectedAxis1, m_cameraCorrectedAxis2, - m_size * ManipulatorViewScaleMultiplier( + const Picking::BoundShapeQuad quadBound = CalculateQuadBound( + manipulatorState.m_localPosition, manipulatorState, m_cameraCorrectedAxis1, m_cameraCorrectedAxis2, + m_size * + ManipulatorViewScaleMultiplier( manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState)); debugDisplay.SetLineWidth(defaultLineWidth(manipulatorState.m_mouseOver)); @@ -339,9 +354,7 @@ namespace AzToolsFramework debugDisplay.SetColor(Vector3ToVector4(m_mouseOverColor.GetAsVector3(), 0.5f)); debugDisplay.CullOff(); - debugDisplay.DrawQuad( - quadBound.m_corner1, quadBound.m_corner2, - quadBound.m_corner3, quadBound.m_corner4); + debugDisplay.DrawQuad(quadBound.m_corner1, quadBound.m_corner2, quadBound.m_corner3, quadBound.m_corner4); debugDisplay.CullOn(); } @@ -349,41 +362,46 @@ namespace AzToolsFramework } void ManipulatorViewQuadBillboard::Draw( - const ManipulatorManagerId managerId, const ManipulatorManagerState& /*managerState*/, - const ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + const ManipulatorManagerId managerId, + const ManipulatorManagerState& /*managerState*/, + const ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& /*mouseInteraction*/) { - const Picking::BoundShapeQuad quadBound = - CalculateQuadBoundBillboard(manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, - m_size * ManipulatorViewScaleMultiplier( - manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState), cameraState); + const Picking::BoundShapeQuad quadBound = CalculateQuadBoundBillboard( + manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, + m_size * + ManipulatorViewScaleMultiplier( + manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState), + cameraState); debugDisplay.SetColor(ViewColor(manipulatorState.m_mouseOver, m_color, m_mouseOverColor).GetAsVector4()); - debugDisplay.DrawQuad( - quadBound.m_corner1, quadBound.m_corner2, - quadBound.m_corner3, quadBound.m_corner4); + debugDisplay.DrawQuad(quadBound.m_corner1, quadBound.m_corner2, quadBound.m_corner3, quadBound.m_corner4); RefreshBoundInternal(managerId, manipulatorId, quadBound); } void ManipulatorViewLine::Draw( - const ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - const ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + const ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + const ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) { - const float viewScale = ManipulatorViewScaleMultiplier( - manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); + const float viewScale = + ManipulatorViewScaleMultiplier(manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); CameraCorrectAxis( - m_axis, m_cameraCorrectedAxis, managerState, mouseInteraction, - manipulatorState.m_worldFromLocal, manipulatorState.m_localPosition, cameraState); + m_axis, m_cameraCorrectedAxis, managerState, mouseInteraction, manipulatorState.m_worldFromLocal, + manipulatorState.m_localPosition, cameraState); - const Picking::BoundShapeLineSegment lineBound = - CalculateLineBound( - manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, - m_cameraCorrectedAxis, m_length * viewScale, m_width * viewScale); + const Picking::BoundShapeLineSegment lineBound = CalculateLineBound( + manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, m_cameraCorrectedAxis, m_length * viewScale, + m_width * viewScale); debugDisplay.SetColor(ViewColor(manipulatorState.m_mouseOver, m_color, m_mouseOverColor).GetAsVector4()); debugDisplay.SetLineWidth(defaultLineWidth(manipulatorState.m_mouseOver)); @@ -393,13 +411,16 @@ namespace AzToolsFramework } void ManipulatorViewLineSelect::Draw( - const ManipulatorManagerId managerId, const ManipulatorManagerState& /*managerState*/, - const ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + const ManipulatorManagerId managerId, + const ManipulatorManagerState& /*managerState*/, + const ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) { - const float viewScale = ManipulatorViewScaleMultiplier( - manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); + const float viewScale = + ManipulatorViewScaleMultiplier(manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); const Picking::BoundShapeLineSegment lineBound = CalculateLineBound(m_localStart, m_localEnd, manipulatorState, m_width * viewScale); @@ -407,44 +428,42 @@ namespace AzToolsFramework if (manipulatorState.m_mouseOver) { const LineSegmentSelectionManipulator::Action action = CalculateManipulationDataAction( - manipulatorState.m_worldFromLocal, manipulatorState.m_nonUniformScale, - mouseInteraction.m_mousePick.m_rayOrigin, mouseInteraction.m_mousePick.m_rayDirection, - cameraState.m_farClip, m_localStart, m_localEnd); + manipulatorState.m_worldFromLocal, manipulatorState.m_nonUniformScale, mouseInteraction.m_mousePick.m_rayOrigin, + mouseInteraction.m_mousePick.m_rayDirection, cameraState.m_farClip, m_localStart, m_localEnd); const AZ::Vector3 worldLineHitPosition = manipulatorState.TransformPoint(action.m_localLineHitPosition); debugDisplay.SetColor(AZ::Vector4(0.0f, 1.0f, 0.0f, 1.0f)); debugDisplay.DrawBall( - worldLineHitPosition, ManipulatorViewScaleMultiplier(worldLineHitPosition, cameraState) - * g_defaultManipulatorSphereRadius, false); + worldLineHitPosition, ManipulatorViewScaleMultiplier(worldLineHitPosition, cameraState) * g_defaultManipulatorSphereRadius, + false); } RefreshBoundInternal(managerId, manipulatorId, lineBound); } void ManipulatorViewCone::Draw( - const ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - const ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + const ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + const ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) { - const float viewScale = ManipulatorViewScaleMultiplier( - manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); + const float viewScale = + ManipulatorViewScaleMultiplier(manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); CameraCorrectAxis( - m_axis, m_cameraCorrectedAxis, managerState, mouseInteraction, - manipulatorState.m_worldFromLocal, manipulatorState.m_localPosition, - cameraState, &m_shouldCorrect); + m_axis, m_cameraCorrectedAxis, managerState, mouseInteraction, manipulatorState.m_worldFromLocal, + manipulatorState.m_localPosition, cameraState, &m_shouldCorrect); CameraCorrectAxis( - m_offset, m_cameraCorrectedOffset, managerState, mouseInteraction, - manipulatorState.m_worldFromLocal, manipulatorState.m_localPosition, cameraState); + m_offset, m_cameraCorrectedOffset, managerState, mouseInteraction, manipulatorState.m_worldFromLocal, + manipulatorState.m_localPosition, cameraState); - const Picking::BoundShapeCone coneBound = - CalculateConeBound( - manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, m_cameraCorrectedAxis, - m_cameraCorrectedOffset * viewScale, - m_length * viewScale, - m_radius * viewScale); + const Picking::BoundShapeCone coneBound = CalculateConeBound( + manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, m_cameraCorrectedAxis, m_cameraCorrectedOffset * viewScale, + m_length * viewScale, m_radius * viewScale); debugDisplay.SetColor(ViewColor(manipulatorState.m_mouseOver, m_color, m_mouseOverColor).GetAsVector4()); if (m_shouldCorrect) @@ -460,73 +479,77 @@ namespace AzToolsFramework } void ManipulatorViewBox::Draw( - const ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - const ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + const ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + const ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) { - const float viewScale = ManipulatorViewScaleMultiplier( - manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); + const float viewScale = + ManipulatorViewScaleMultiplier(manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); const AZ::Quaternion orientation = m_orientation; CameraCorrectAxis( - m_offset, m_cameraCorrectedOffset, managerState, mouseInteraction, - manipulatorState.m_worldFromLocal, manipulatorState.m_localPosition, - cameraState); + m_offset, m_cameraCorrectedOffset, managerState, mouseInteraction, manipulatorState.m_worldFromLocal, + manipulatorState.m_localPosition, cameraState); - const Picking::BoundShapeBox boxBound = - CalculateBoxBound(manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, orientation, - m_cameraCorrectedOffset * viewScale, - m_halfExtents * viewScale); + const Picking::BoundShapeBox boxBound = CalculateBoxBound( + manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, orientation, m_cameraCorrectedOffset * viewScale, + m_halfExtents * viewScale); const AZ::Vector3 xAxis = boxBound.m_orientation.TransformVector(AZ::Vector3::CreateAxisX()); const AZ::Vector3 yAxis = boxBound.m_orientation.TransformVector(AZ::Vector3::CreateAxisY()); const AZ::Vector3 zAxis = boxBound.m_orientation.TransformVector(AZ::Vector3::CreateAxisZ()); debugDisplay.SetColor(ViewColor(manipulatorState.m_mouseOver, m_color, m_mouseOverColor).GetAsVector4()); - debugDisplay.DrawSolidOBB(boxBound.m_center, - xAxis, yAxis, zAxis, boxBound.m_halfExtents); + debugDisplay.DrawSolidOBB(boxBound.m_center, xAxis, yAxis, zAxis, boxBound.m_halfExtents); RefreshBoundInternal(managerId, manipulatorId, boxBound); } void ManipulatorViewCylinder::Draw( - const ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - const ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + const ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + const ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) { - const float viewScale = ManipulatorViewScaleMultiplier( - manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); + const float viewScale = + ManipulatorViewScaleMultiplier(manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); CameraCorrectAxis( - m_axis, m_cameraCorrectedAxis, managerState, mouseInteraction, - manipulatorState.m_worldFromLocal, manipulatorState.m_localPosition, cameraState); + m_axis, m_cameraCorrectedAxis, managerState, mouseInteraction, manipulatorState.m_worldFromLocal, + manipulatorState.m_localPosition, cameraState); - const Picking::BoundShapeCylinder cylinderBound = - CalculateCylinderBound( - manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, m_cameraCorrectedAxis, - m_length * viewScale, - m_radius * viewScale); + const Picking::BoundShapeCylinder cylinderBound = CalculateCylinderBound( + manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, m_cameraCorrectedAxis, m_length * viewScale, + m_radius * viewScale); debugDisplay.SetColor(ViewColor(manipulatorState.m_mouseOver, m_color, m_mouseOverColor).GetAsVector4()); - debugDisplay.DrawSolidCylinder(cylinderBound.m_base + cylinderBound.m_axis * cylinderBound.m_height * 0.5f, - cylinderBound.m_axis, cylinderBound.m_radius, cylinderBound.m_height, false); + debugDisplay.DrawSolidCylinder( + cylinderBound.m_base + cylinderBound.m_axis * cylinderBound.m_height * 0.5f, cylinderBound.m_axis, cylinderBound.m_radius, + cylinderBound.m_height, false); RefreshBoundInternal(managerId, manipulatorId, cylinderBound); } void ManipulatorViewSphere::Draw( - const ManipulatorManagerId managerId, const ManipulatorManagerState& /*managerState*/, - const ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + const ManipulatorManagerId managerId, + const ManipulatorManagerState& /*managerState*/, + const ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) { - const Picking::BoundShapeSphere sphereBound = - CalculateSphereBound(manipulatorState.m_localPosition, manipulatorState, - m_radius * ManipulatorViewScaleMultiplier( - manipulatorState.TransformPoint(manipulatorState.m_localPosition), cameraState)); + const Picking::BoundShapeSphere sphereBound = CalculateSphereBound( + manipulatorState.m_localPosition, manipulatorState, + m_radius * ManipulatorViewScaleMultiplier(manipulatorState.TransformPoint(manipulatorState.m_localPosition), cameraState)); if (m_depthTest) { @@ -545,31 +568,32 @@ namespace AzToolsFramework } void ManipulatorViewCircle::Draw( - const ManipulatorManagerId managerId, const ManipulatorManagerState& /*managerState*/, - const ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + const ManipulatorManagerId managerId, + const ManipulatorManagerState& /*managerState*/, + const ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& /*mouseInteraction*/) { - const float viewScale = ManipulatorViewScaleMultiplier( - manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); + const float viewScale = + ManipulatorViewScaleMultiplier(manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); - const Picking::BoundShapeTorus torusBound = - CalculateTorusBound( - manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, m_axis, - m_radius * viewScale, - m_width * viewScale); + const Picking::BoundShapeTorus torusBound = CalculateTorusBound( + manipulatorState.m_localPosition, manipulatorState.m_worldFromLocal, m_axis, m_radius * viewScale, m_width * viewScale); // transform circle based on delta between default z up axis and other axes const AZ::Transform worldFromLocalWithOrientation = AZ::Transform::CreateTranslation(manipulatorState.m_worldFromLocal.GetTranslation()) * - AZ::Transform::CreateFromQuaternion( - (QuaternionFromTransformNoScaling(manipulatorState.m_worldFromLocal) * - AZ::Quaternion::CreateShortestArc(AZ::Vector3::CreateAxisZ(), m_axis)).GetNormalized()); + AZ::Transform::CreateFromQuaternion((QuaternionFromTransformNoScaling(manipulatorState.m_worldFromLocal) * + AZ::Quaternion::CreateShortestArc(AZ::Vector3::CreateAxisZ(), m_axis)) + .GetNormalized()); debugDisplay.CullOn(); debugDisplay.PushMatrix(worldFromLocalWithOrientation); debugDisplay.SetColor(ViewColor(manipulatorState.m_mouseOver, m_color, m_mouseOverColor).GetAsVector4()); - m_drawCircleFunc(debugDisplay, manipulatorState.m_localPosition, torusBound.m_majorRadius, + m_drawCircleFunc( + debugDisplay, manipulatorState.m_localPosition, torusBound.m_majorRadius, worldFromLocalWithOrientation.GetInverse().TransformPoint(cameraState.m_position)); debugDisplay.PopMatrix(); debugDisplay.CullOff(); @@ -578,27 +602,28 @@ namespace AzToolsFramework } void DrawHalfDottedCircle( - AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Vector3& position, - const float radius, const AZ::Vector3& viewPos) + AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Vector3& position, const float radius, const AZ::Vector3& viewPos) { debugDisplay.DrawHalfDottedCircle(position, radius, viewPos); } void DrawFullCircle( - AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Vector3& position, - const float radius, const AZ::Vector3& /*viewPos*/) + AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Vector3& position, const float radius, const AZ::Vector3& /*viewPos*/) { - debugDisplay.DrawCircle(position, radius); + debugDisplay.DrawCircle(position, radius); } void ManipulatorViewSplineSelect::Draw( - const ManipulatorManagerId managerId, const ManipulatorManagerState& /*managerState*/, - const ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + const ManipulatorManagerId managerId, + const ManipulatorManagerState& /*managerState*/, + const ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) { - const float viewScale = ManipulatorViewScaleMultiplier( - manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); + const float viewScale = + ManipulatorViewScaleMultiplier(manipulatorState.m_worldFromLocal.TransformPoint(manipulatorState.m_localPosition), cameraState); const Picking::BoundShapeSpline splineBound = CalculateSplineBound(m_spline, manipulatorState.m_worldFromLocal, m_width * viewScale); @@ -606,16 +631,15 @@ namespace AzToolsFramework if (manipulatorState.m_mouseOver) { const SplineSelectionManipulator::Action action = CalculateManipulationDataAction( - manipulatorState.m_worldFromLocal, mouseInteraction.m_mousePick.m_rayOrigin, - mouseInteraction.m_mousePick.m_rayDirection, m_spline); + manipulatorState.m_worldFromLocal, mouseInteraction.m_mousePick.m_rayOrigin, mouseInteraction.m_mousePick.m_rayDirection, + m_spline); - const AZ::Vector3 worldSplineHitPosition = - manipulatorState.m_worldFromLocal.TransformPoint(action.m_localSplineHitPosition); + const AZ::Vector3 worldSplineHitPosition = manipulatorState.m_worldFromLocal.TransformPoint(action.m_localSplineHitPosition); debugDisplay.SetColor(m_color.GetAsVector4()); debugDisplay.DrawBall( - worldSplineHitPosition, ManipulatorViewScaleMultiplier(worldSplineHitPosition, cameraState) - * g_defaultManipulatorSphereRadius, false); + worldSplineHitPosition, + ManipulatorViewScaleMultiplier(worldSplineHitPosition, cameraState) * g_defaultManipulatorSphereRadius, false); } RefreshBoundInternal(managerId, manipulatorId, splineBound); @@ -624,8 +648,7 @@ namespace AzToolsFramework /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AZStd::unique_ptr CreateManipulatorViewQuad( - const PlanarManipulator& planarManipulator, const AZ::Color& axis1Color, - const AZ::Color& axis2Color, const float size) + const PlanarManipulator& planarManipulator, const AZ::Color& axis1Color, const AZ::Color& axis2Color, const float size) { AZStd::unique_ptr viewQuad = AZStd::make_unique(); viewQuad->m_axis1 = planarManipulator.GetAxis1(); @@ -636,8 +659,7 @@ namespace AzToolsFramework return viewQuad; } - AZStd::unique_ptr CreateManipulatorViewQuadBillboard( - const AZ::Color& color, const float size) + AZStd::unique_ptr CreateManipulatorViewQuadBillboard(const AZ::Color& color, const float size) { AZStd::unique_ptr viewQuad = AZStd::make_unique(); viewQuad->m_size = size; @@ -646,8 +668,7 @@ namespace AzToolsFramework } AZStd::unique_ptr CreateManipulatorViewLine( - const LinearManipulator& linearManipulator, const AZ::Color& color, - const float length, const float width) + const LinearManipulator& linearManipulator, const AZ::Color& color, const float length, const float width) { AZStd::unique_ptr viewLine = AZStd::make_unique(); viewLine->m_axis = linearManipulator.GetAxis(); @@ -658,8 +679,7 @@ namespace AzToolsFramework } AZStd::unique_ptr CreateManipulatorViewLineSelect( - const LineSegmentSelectionManipulator& lineSegmentManipulator, - const AZ::Color& color, const float width) + const LineSegmentSelectionManipulator& lineSegmentManipulator, const AZ::Color& color, const float width) { AZStd::unique_ptr viewLineSelect = AZStd::make_unique(); viewLineSelect->m_localStart = lineSegmentManipulator.GetStart(); @@ -670,8 +690,11 @@ namespace AzToolsFramework } AZStd::unique_ptr CreateManipulatorViewCone( - const LinearManipulator& linearManipulator, const AZ::Color& color, - const AZ::Vector3& offset, const float length, const float radius) + const LinearManipulator& linearManipulator, + const AZ::Color& color, + const AZ::Vector3& offset, + const float length, + const float radius) { AZStd::unique_ptr viewCone = AZStd::make_unique(); viewCone->m_axis = linearManipulator.GetAxis(); @@ -683,8 +706,7 @@ namespace AzToolsFramework } AZStd::unique_ptr CreateManipulatorViewBox( - const AZ::Transform& transform, const AZ::Color& color, - const AZ::Vector3& offset, const AZ::Vector3& halfExtents) + const AZ::Transform& transform, const AZ::Color& color, const AZ::Vector3& offset, const AZ::Vector3& halfExtents) { AZStd::unique_ptr viewBox = AZStd::make_unique(); viewBox->m_orientation = transform.GetRotation(); @@ -695,8 +717,7 @@ namespace AzToolsFramework } AZStd::unique_ptr CreateManipulatorViewCylinder( - const LinearManipulator& linearManipulator, const AZ::Color& color, - const float length, const float radius) + const LinearManipulator& linearManipulator, const AZ::Color& color, const float length, const float radius) { AZStd::unique_ptr viewCylinder = AZStd::make_unique(); viewCylinder->m_axis = linearManipulator.GetAxis(); @@ -718,8 +739,11 @@ namespace AzToolsFramework } AZStd::unique_ptr CreateManipulatorViewCircle( - const AngularManipulator& angularManipulator, const AZ::Color& color, - const float radius, const float width, const ManipulatorViewCircle::DrawCircleFunc drawFunc) + const AngularManipulator& angularManipulator, + const AZ::Color& color, + const float radius, + const float width, + const ManipulatorViewCircle::DrawCircleFunc drawFunc) { AZStd::unique_ptr viewCircle = AZStd::make_unique(); viewCircle->m_axis = angularManipulator.GetAxis(); @@ -731,8 +755,7 @@ namespace AzToolsFramework } AZStd::unique_ptr CreateManipulatorViewSplineSelect( - const SplineSelectionManipulator& splineManipulator, - const AZ::Color& color, const float width) + const SplineSelectionManipulator& splineManipulator, const AZ::Color& color, const float width) { AZStd::unique_ptr viewSplineSelect = AZStd::make_unique(); viewSplineSelect->m_spline = splineManipulator.GetSpline(); @@ -741,16 +764,12 @@ namespace AzToolsFramework return viewSplineSelect; } - AZ::Vector3 CalculateViewDirection( - const Manipulators& manipulators, const AZ::Vector3& worldViewPosition) + AZ::Vector3 CalculateViewDirection(const Manipulators& manipulators, const AZ::Vector3& worldViewPosition) { - const AZ::Transform worldFromLocalWithTransform = - manipulators.GetSpace() * manipulators.GetLocalTransform(); + const AZ::Transform worldFromLocalWithTransform = manipulators.GetSpace() * manipulators.GetLocalTransform(); - AZ::Vector3 lookDirection = - (worldFromLocalWithTransform.GetTranslation() - worldViewPosition).GetNormalized(); + AZ::Vector3 lookDirection = (worldFromLocalWithTransform.GetTranslation() - worldViewPosition).GetNormalized(); - return TransformDirectionNoScaling( - worldFromLocalWithTransform.GetInverse(), lookDirection); + return TransformDirectionNoScaling(worldFromLocalWithTransform.GetInverse(), lookDirection); } } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorView.h index da426d2340..8573f8ce32 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorView.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -26,13 +26,12 @@ namespace AzToolsFramework class LineSegmentSelectionManipulator; class SplineSelectionManipulator; - using DecideColorFn = AZStd::function; + using DecideColorFn = + AZStd::function; extern const float g_defaultManipulatorSphereRadius; - /// State of an individual manipulator. + //! State of an individual manipulator. struct ManipulatorState { AZ::Transform m_worldFromLocal; @@ -40,18 +39,18 @@ namespace AzToolsFramework AZ::Vector3 m_localPosition; bool m_mouseOver; - /// Transforms a point, taking non-uniform scale into account. + //! Transforms a point, taking non-uniform scale into account. AZ::Vector3 TransformPoint(const AZ::Vector3& point) const; - /// Rotates a direction into the space of the manipulator and normalizes it. - /// Non-uniform scaling and translation are not applied. + //! Rotates a direction into the space of the manipulator and normalizes it. + //! Non-uniform scaling and translation are not applied. AZ::Vector3 TransformDirectionNoScaling(const AZ::Vector3& direction) const; }; - /// The base interface for the visual representation of manipulators. - /// The View represents the appearance and bounds of the manipulator for - /// the user to interact with. Any manipulator can have any view (some may - /// be more appropriate than others in certain cases). + //! The base interface for the visual representation of manipulators. + //! The View represents the appearance and bounds of the manipulator for + //! the user to interact with. Any manipulator can have any view (some may + //! be more appropriate than others in certain cases). class ManipulatorView { public: @@ -65,98 +64,107 @@ namespace AzToolsFramework ManipulatorView& operator=(ManipulatorView&&) = default; void SetBoundDirty(ManipulatorManagerId managerId); - void RefreshBound( - ManipulatorManagerId managerId, ManipulatorId manipulatorId, const Picking::BoundRequestShapeBase& bound); + void RefreshBound(ManipulatorManagerId managerId, ManipulatorId manipulatorId, const Picking::BoundRequestShapeBase& bound); void Invalidate(ManipulatorManagerId managerId); virtual void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) = 0; - bool ScreenSizeFixed() const { return m_screenSizeFixed; } + bool ScreenSizeFixed() const + { + return m_screenSizeFixed; + } protected: - AZ::Color m_mouseOverColor = BaseManipulator::s_defaultMouseOverColor; ///< What color should the manipulator - ///< be when the mouse is hovering over it. - /// Scale the manipulator based on the distance - /// from the camera if m_screenSizeFixed is true. - float ManipulatorViewScaleMultiplier( - const AZ::Vector3& worldPosition, const AzFramework::CameraState& cameraState) const; + AZ::Color m_mouseOverColor = BaseManipulator::s_defaultMouseOverColor; //!< What color should the manipulator + //!< be when the mouse is hovering over it. + //! Scale the manipulator based on the distance + //! from the camera if m_screenSizeFixed is true. + float ManipulatorViewScaleMultiplier(const AZ::Vector3& worldPosition, const AzFramework::CameraState& cameraState) const; - /// Wrap the logic for updating a bound. - /// Should be called at the end of the Draw function once a concrete BoundRequestShape has - /// been created to use for dimensions for rendering. - void RefreshBoundInternal( - ManipulatorManagerId managerId, ManipulatorId manipulatorId, const Picking::BoundRequestShapeBase& bound); + //! Wrap the logic for updating a bound. + //! Should be called at the end of the Draw function once a concrete BoundRequestShape has + //! been created to use for dimensions for rendering. + void RefreshBoundInternal(ManipulatorManagerId managerId, ManipulatorId manipulatorId, const Picking::BoundRequestShapeBase& bound); private: - Picking::RegisteredBoundId m_boundId = Picking::InvalidBoundId; ///< Used for hit detection. - ManipulatorManagerId m_managerId = InvalidManipulatorManagerId; /// The manipulator manager this view has been registered with. - bool m_screenSizeFixed = true; ///< Should manipulator size be adjusted based on camera distance. - bool m_boundDirty = true; ///< Do the bounds need to be recalculated. + Picking::RegisteredBoundId m_boundId = Picking::InvalidBoundId; //!< Used for hit detection. + ManipulatorManagerId m_managerId = InvalidManipulatorManagerId; //! The manipulator manager this view has been registered with. + bool m_screenSizeFixed = true; //!< Should manipulator size be adjusted based on camera distance. + bool m_boundDirty = true; //!< Do the bounds need to be recalculated. }; // A collection of views (a manipulator may have 1 - * views) using ManipulatorViews = AZStd::vector>; - /// Display a quad representing part of a plane, rendered as 4 lines. - class ManipulatorViewQuad - : public ManipulatorView + //! Display a quad representing part of a plane, rendered as 4 lines. + class ManipulatorViewQuad : public ManipulatorView { public: AZ_CLASS_ALLOCATOR(ManipulatorViewQuad, AZ::SystemAllocator, 0) AZ_RTTI(ManipulatorViewQuad, "{D85E1B45-495E-4755-BCF2-6AE45F8BB2B0}", ManipulatorView) void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; AZ::Vector3 m_axis1 = AZ::Vector3(1.0f, 0.0f, 0.0f); AZ::Vector3 m_axis2 = AZ::Vector3(0.0f, 1.0f, 0.0f); AZ::Color m_axis1Color = AZ::Color(1.0f, 0.0f, 0.0f, 1.0f); AZ::Color m_axis2Color = AZ::Color(1.0f, 0.0f, 0.0f, 1.0f); - float m_size = 0.06f; ///< size to render and do mouse ray intersection tests against. + float m_size = 0.06f; //!< size to render and do mouse ray intersection tests against. private: AZ::Vector3 m_cameraCorrectedAxis1; AZ::Vector3 m_cameraCorrectedAxis2; }; - /// A screen aligned quad, centered at the position of the manipulator, display filled. - class ManipulatorViewQuadBillboard - : public ManipulatorView + //! A screen aligned quad, centered at the position of the manipulator, display filled. + class ManipulatorViewQuadBillboard : public ManipulatorView { public: AZ_CLASS_ALLOCATOR(ManipulatorViewQuadBillboard, AZ::SystemAllocator, 0) AZ_RTTI(ManipulatorViewQuadBillboard, "{C205E967-E8C6-4A73-A31B-41EE5529B15B}", ManipulatorView) void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; AZ::Color m_color = AZ::Color(1.0f, 0.0f, 0.0f, 1.0f); - float m_size = 0.005f; ///< size to render and do mouse ray intersection tests against. + float m_size = 0.005f; //!< size to render and do mouse ray intersection tests against. }; - /// Displays a debug style line starting from the manipulator's transform, - /// width determines the click area. - class ManipulatorViewLine - : public ManipulatorView + //! Displays a debug style line starting from the manipulator's transform, + //! width determines the click area. + class ManipulatorViewLine : public ManipulatorView { public: AZ_CLASS_ALLOCATOR(ManipulatorViewLine, AZ::SystemAllocator, 0) AZ_RTTI(ManipulatorViewLine, "{831EEF66-4A5C-450C-B152-EA4A0BC8A272}", ManipulatorView) void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; AZ::Vector3 m_axis; @@ -168,19 +176,21 @@ namespace AzToolsFramework AZ::Vector3 m_cameraCorrectedAxis; }; - /// Variant of ManipulatorViewLine which instead of using an axis, provides begin and end - /// points for the line. Used for selection when inserting points along a line. - class ManipulatorViewLineSelect - : public ManipulatorView + //! Variant of ManipulatorViewLine which instead of using an axis, provides begin and end + //! points for the line. Used for selection when inserting points along a line. + class ManipulatorViewLineSelect : public ManipulatorView { public: AZ_CLASS_ALLOCATOR(ManipulatorViewLineSelect, AZ::SystemAllocator, 0) AZ_RTTI(ManipulatorViewLineSelect, "{BF26A947-91F8-4595-9A5B-481876EB2C48}", ManipulatorView) void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; AZ::Vector3 m_localStart; @@ -189,20 +199,22 @@ namespace AzToolsFramework float m_width = 0.0f; }; - /// Displays a filled cone along the specified axis, offset is local translation from - /// the manipulator transform (often used in conjunction with other views to build - /// aggregate views such as arrows - e.g. a line and cone). - class ManipulatorViewCone - : public ManipulatorView + //! Displays a filled cone along the specified axis, offset is local translation from + //! the manipulator transform (often used in conjunction with other views to build + //! aggregate views such as arrows - e.g. a line and cone). + class ManipulatorViewCone : public ManipulatorView { public: AZ_CLASS_ALLOCATOR(ManipulatorViewCone, AZ::SystemAllocator, 0) AZ_RTTI(ManipulatorViewCone, "{BF042887-1F51-4FD8-8CA5-4A649B4AF356}", ManipulatorView) void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; AZ::Vector3 m_offset; @@ -217,20 +229,22 @@ namespace AzToolsFramework bool m_shouldCorrect = false; }; - /// Displays a filled box, offset is local translation from the manipulator - /// transform, box is often used in conjunction with other views, orientation allows - /// the box to be orientated separately from the manipulator transform. - class ManipulatorViewBox - : public ManipulatorView + //! Displays a filled box, offset is local translation from the manipulator + //! transform, box is often used in conjunction with other views, orientation allows + //! the box to be orientated separately from the manipulator transform. + class ManipulatorViewBox : public ManipulatorView { public: AZ_CLASS_ALLOCATOR(ManipulatorViewBox, AZ::SystemAllocator, 0) AZ_RTTI(ManipulatorViewBox, "{2D082201-7878-4C1B-A3DD-7A629E5AD598}", ManipulatorView) void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; AZ::Vector3 m_offset; @@ -242,18 +256,20 @@ namespace AzToolsFramework AZ::Vector3 m_cameraCorrectedOffset; }; - /// Displays a filled cylinder along the axis provided. - class ManipulatorViewCylinder - : public ManipulatorView + //! Displays a filled cylinder along the axis provided. + class ManipulatorViewCylinder : public ManipulatorView { public: AZ_CLASS_ALLOCATOR(ManipulatorViewCylinder, AZ::SystemAllocator, 0) AZ_RTTI(ManipulatorViewCylinder, "{9B8E5EF4-0F85-4CD0-A5FF-3C7097DF58AC}", ManipulatorView) void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; AZ::Vector3 m_axis; @@ -265,20 +281,22 @@ namespace AzToolsFramework AZ::Vector3 m_cameraCorrectedAxis; }; - /// Displays a filled sphere at the transform of the manipulator, often used as - /// a selection manipulator. DecideColorFn allows more complex logic to be used - /// to decide the color of the manipulator (based on hover state etc.) - class ManipulatorViewSphere - : public ManipulatorView + //! Displays a filled sphere at the transform of the manipulator, often used as + //! a selection manipulator. DecideColorFn allows more complex logic to be used + //! to decide the color of the manipulator (based on hover state etc.) + class ManipulatorViewSphere : public ManipulatorView { public: AZ_CLASS_ALLOCATOR(ManipulatorViewSphere, AZ::SystemAllocator, 0) AZ_RTTI(ManipulatorViewSphere, "{324D8329-6E7B-4A5D-AC8A-8C0E1C984E38}", ManipulatorView) void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; float m_radius = 0.0f; @@ -287,23 +305,24 @@ namespace AzToolsFramework bool m_depthTest = false; }; - /// Displays a wire circle. DrawCircleFunc can be used to either draw a full - /// circle or a half dotted circle where the part of the circle facing away - /// from the camera is dotted (useful for angular/rotation manipulators). - class ManipulatorViewCircle - : public ManipulatorView + //! Displays a wire circle. DrawCircleFunc can be used to either draw a full + //! circle or a half dotted circle where the part of the circle facing away + //! from the camera is dotted (useful for angular/rotation manipulators). + class ManipulatorViewCircle : public ManipulatorView { public: AZ_CLASS_ALLOCATOR(ManipulatorViewCircle, AZ::SystemAllocator, 0) AZ_RTTI(ManipulatorViewCircle, "{26563A03-3E48-49EB-9DCF-30EE4F567FCD}", ManipulatorView) - using DrawCircleFunc = - void(*)(AzFramework::DebugDisplayRequests&, const AZ::Vector3&, float, const AZ::Vector3&); + using DrawCircleFunc = void (*)(AzFramework::DebugDisplayRequests&, const AZ::Vector3&, float, const AZ::Vector3&); void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; AZ::Vector3 m_axis; @@ -316,26 +335,26 @@ namespace AzToolsFramework // helpers to provide consistent function pointer interface for deciding // on type of circle to draw (see DrawCircleFunc in ManipulatorViewCircle above) void DrawHalfDottedCircle( - AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Vector3& position, - float radius, const AZ::Vector3& viewPos); + AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Vector3& position, float radius, const AZ::Vector3& viewPos); void DrawFullCircle( - AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Vector3& position, - float radius, const AZ::Vector3& viewPos); + AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Vector3& position, float radius, const AZ::Vector3& viewPos); - /// Used for interaction with spline primitive - it will generate a spline bound - /// to be interacted with and will display the intersection point on the spline - /// where a user may wish to insert a point. - class ManipulatorViewSplineSelect - : public ManipulatorView + //! Used for interaction with spline primitive - it will generate a spline bound + //! to be interacted with and will display the intersection point on the spline + //! where a user may wish to insert a point. + class ManipulatorViewSplineSelect : public ManipulatorView { public: AZ_CLASS_ALLOCATOR(ManipulatorViewSplineSelect, AZ::SystemAllocator, 0) AZ_RTTI(ManipulatorViewSplineSelect, "{60996E49-D6BF-4817-BAA3-D27A407DD21A}", ManipulatorView) void Draw( - ManipulatorManagerId managerId, const ManipulatorManagerState& managerState, - ManipulatorId manipulatorId, const ManipulatorState& manipulatorState, - AzFramework::DebugDisplayRequests& debugDisplay, const AzFramework::CameraState& cameraState, + ManipulatorManagerId managerId, + const ManipulatorManagerState& managerState, + ManipulatorId manipulatorId, + const ManipulatorState& manipulatorState, + AzFramework::DebugDisplayRequests& debugDisplay, + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; AZStd::weak_ptr m_spline; @@ -343,65 +362,61 @@ namespace AzToolsFramework AZ::Color m_color = AZ::Color(0.0f, 1.0f, 0.0f, 1.0f); }; - /// Returns true if axis is pointing away from us (we should flip it). + //! Returns true if axis is pointing away from us (we should flip it). inline bool ShouldFlipCameraAxis( - const AZ::Transform& worldFromLocal, const AZ::Vector3& localPosition, - const AZ::Vector3& axis, const AzFramework::CameraState& cameraState) + const AZ::Transform& worldFromLocal, + const AZ::Vector3& localPosition, + const AZ::Vector3& axis, + const AzFramework::CameraState& cameraState) { - return (worldFromLocal.TransformPoint(localPosition) - cameraState.m_position).Dot( - TransformDirectionNoScaling(worldFromLocal, axis)) > 0.0f; + return (worldFromLocal.TransformPoint(localPosition) - cameraState.m_position) + .Dot(TransformDirectionNoScaling(worldFromLocal, axis)) > 0.0f; } - /// @brief Return the world transform of the entity with uniform scale - choose - /// the largest element. + //! @brief Return the world transform of the entity with uniform scale - choose + //! the largest element. AZ::Transform WorldFromLocalWithUniformScale(AZ::EntityId entityId); - /// Get the non-uniform scale for this entity id. + //! Get the non-uniform scale for this entity id. AZ::Vector3 GetNonUniformScale(AZ::EntityId entityId); // Helpers to create various manipulator views. AZStd::unique_ptr CreateManipulatorViewQuad( - const PlanarManipulator& planarManipulator, const AZ::Color& axis1Color, - const AZ::Color& axis2Color, float size); + const PlanarManipulator& planarManipulator, const AZ::Color& axis1Color, const AZ::Color& axis2Color, float size); - AZStd::unique_ptr CreateManipulatorViewQuadBillboard( - const AZ::Color& color, float size); + AZStd::unique_ptr CreateManipulatorViewQuadBillboard(const AZ::Color& color, float size); AZStd::unique_ptr CreateManipulatorViewLine( - const LinearManipulator& linearManipulator, const AZ::Color& color, - float length, float width); + const LinearManipulator& linearManipulator, const AZ::Color& color, float length, float width); AZStd::unique_ptr CreateManipulatorViewLineSelect( - const LineSegmentSelectionManipulator& lineSegmentManipulator, const AZ::Color& color, - float width); + const LineSegmentSelectionManipulator& lineSegmentManipulator, const AZ::Color& color, float width); AZStd::unique_ptr CreateManipulatorViewCone( - const LinearManipulator& linearManipulator, const AZ::Color& color, - const AZ::Vector3& offset, float length, float radius); + const LinearManipulator& linearManipulator, const AZ::Color& color, const AZ::Vector3& offset, float length, float radius); AZStd::unique_ptr CreateManipulatorViewBox( - const AZ::Transform& transform, const AZ::Color& color, - const AZ::Vector3& offset, const AZ::Vector3& halfExtents); + const AZ::Transform& transform, const AZ::Color& color, const AZ::Vector3& offset, const AZ::Vector3& halfExtents); AZStd::unique_ptr CreateManipulatorViewCylinder( - const LinearManipulator& linearManipulator, const AZ::Color& color, - float length, float radius); + const LinearManipulator& linearManipulator, const AZ::Color& color, float length, float radius); AZStd::unique_ptr CreateManipulatorViewSphere( const AZ::Color& color, float radius, const DecideColorFn& decideColor, bool enableDepthTest = false); AZStd::unique_ptr CreateManipulatorViewCircle( - const AngularManipulator& angularManipulator, const AZ::Color& color, - float radius, float width, ManipulatorViewCircle::DrawCircleFunc drawFunc); + const AngularManipulator& angularManipulator, + const AZ::Color& color, + float radius, + float width, + ManipulatorViewCircle::DrawCircleFunc drawFunc); AZStd::unique_ptr CreateManipulatorViewSplineSelect( - const SplineSelectionManipulator& splineManipulator, const AZ::Color& color, - float width); + const SplineSelectionManipulator& splineManipulator, const AZ::Color& color, float width); - /// Returns the vector between the view (camera) and the manipulator in the space - /// of the Manipulator (manipulator space + local transform). - AZ::Vector3 CalculateViewDirection( - const Manipulators& manipulators, const AZ::Vector3& worldViewPosition); + //! Returns the vector between the view (camera) and the manipulator in the space + //! of the Manipulator (manipulator space + local transform). + AZ::Vector3 CalculateViewDirection(const Manipulators& manipulators, const AZ::Vector3& worldViewPosition); } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp index 83c4c28e9a..922ac95bf7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "MultiLinearManipulator.h" @@ -56,10 +56,13 @@ namespace AzToolsFramework } static MultiLinearManipulator::Action BuildMultiLinearManipulatorAction( - const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, const AZStd::vector& fixedAxes, - const AZStd::vector& starterStates, const GridSnapParameters& gridSnapParams) + const AZStd::vector& starterStates, + const GridSnapParameters& gridSnapParams) { MultiLinearManipulator::Action action; action.m_viewportId = interaction.m_interactionId.m_viewportId; @@ -96,8 +99,8 @@ namespace AzToolsFramework const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); // pass action containing all linear actions for each axis to handler m_onLeftMouseDownCallback(BuildMultiLinearManipulatorAction( - worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), - interaction, m_fixedAxes, m_starters, gridSnapParams)); + worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), interaction, m_fixedAxes, m_starters, + gridSnapParams)); } } @@ -108,8 +111,8 @@ namespace AzToolsFramework const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace()); const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); m_onMouseMoveCallback(BuildMultiLinearManipulatorAction( - worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), - interaction, m_fixedAxes, m_starters, gridSnapParams)); + worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), interaction, m_fixedAxes, m_starters, + gridSnapParams)); } } @@ -120,8 +123,8 @@ namespace AzToolsFramework const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace()); const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); m_onLeftMouseUpCallback(BuildMultiLinearManipulatorAction( - worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), - interaction, m_fixedAxes, m_starters, gridSnapParams)); + worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), interaction, m_fixedAxes, m_starters, + gridSnapParams)); m_starters.clear(); } @@ -138,36 +141,31 @@ namespace AzToolsFramework const AZ::Transform combined = TransformUniformScale(GetSpace()) * GetLocalTransform(); for (const auto& fixed : m_fixedAxes) { - DrawAxis( - debugDisplay, combined.GetTranslation(), TransformDirectionNoScaling(combined, fixed.m_axis)); + DrawAxis(debugDisplay, combined.GetTranslation(), TransformDirectionNoScaling(combined, fixed.m_axis)); } } for (auto& view : m_manipulatorViews) { view->Draw( - GetManipulatorManagerId(), managerState, - GetManipulatorId(), { - ApplySpace(GetLocalTransform()), GetNonUniformScale(), - AZ::Vector3::CreateZero(), MouseOver() - }, - debugDisplay, cameraState, mouseInteraction); + GetManipulatorManagerId(), managerState, GetManipulatorId(), + { ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay, + cameraState, mouseInteraction); } } void MultiLinearManipulator::AddAxis(const AZ::Vector3& axis) { - m_fixedAxes.push_back(LinearManipulator::Fixed{axis}); + m_fixedAxes.push_back(LinearManipulator::Fixed{ axis }); } void MultiLinearManipulator::AddAxes(const AZStd::vector& axes) { AZStd::transform( - axes.begin(), axes.end(), - AZStd::back_inserter(m_fixedAxes), + axes.begin(), axes.end(), AZStd::back_inserter(m_fixedAxes), [](const AZ::Vector3& axis) { - return LinearManipulator::Fixed{axis}; + return LinearManipulator::Fixed{ axis }; }); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.h index 8e31e02605..7cae803dfa 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -80,12 +80,9 @@ namespace AzToolsFramework } private: - void OnLeftMouseDownImpl( - const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; - void OnLeftMouseUpImpl( - const ViewportInteraction::MouseInteraction& interaction) override; - void OnMouseMoveImpl( - const ViewportInteraction::MouseInteraction& interaction) override; + void OnLeftMouseDownImpl(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; + void OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction) override; + void OnMouseMoveImpl(const ViewportInteraction::MouseInteraction& interaction) override; void InvalidateImpl() override; void SetBoundsDirtyImpl() override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.cpp index 6eb96f081c..f146ca4430 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "PlanarManipulator.h" @@ -22,12 +22,15 @@ namespace AzToolsFramework { PlanarManipulator::StartInternal PlanarManipulator::CalculateManipulationDataStart( - const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, - const ViewportInteraction::MouseInteraction& interaction, const float intersectionDistance) + const Fixed& fixed, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, + const ViewportInteraction::MouseInteraction& interaction, + const float intersectionDistance) { - const ManipulatorInteraction manipulatorInteraction = - BuildManipulatorInteraction( - worldFromLocal, nonUniformScale, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection); + const ManipulatorInteraction manipulatorInteraction = BuildManipulatorInteraction( + worldFromLocal, nonUniformScale, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection); const AZ::Vector3 normal = TransformDirectionNoScaling(localTransform, fixed.m_normal); @@ -37,8 +40,8 @@ namespace AzToolsFramework StartInternal startInternal; Internal::CalculateRayPlaneIntersectingPoint( - manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection, - localIntersectionPoint, normal, startInternal.m_localHitPosition); + manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection, localIntersectionPoint, normal, + startInternal.m_localHitPosition); startInternal.m_localPosition = localTransform.GetTranslation(); @@ -46,13 +49,16 @@ namespace AzToolsFramework } PlanarManipulator::Action PlanarManipulator::CalculateManipulationDataAction( - const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Transform& localTransform, const GridSnapParameters& gridSnapParams, + const Fixed& fixed, + const StartInternal& startInternal, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, + const GridSnapParameters& gridSnapParams, const ViewportInteraction::MouseInteraction& interaction) { - const ManipulatorInteraction manipulatorInteraction = - BuildManipulatorInteraction( - worldFromLocal, nonUniformScale, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection); + const ManipulatorInteraction manipulatorInteraction = BuildManipulatorInteraction( + worldFromLocal, nonUniformScale, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection); const AZ::Vector3 normal = TransformDirectionNoScaling(localTransform, fixed.m_normal); @@ -61,8 +67,8 @@ namespace AzToolsFramework // if an invalid ray intersection is attempted AZ::Vector3 localHitPosition = startInternal.m_localHitPosition; Internal::CalculateRayPlaneIntersectingPoint( - manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection, - startInternal.m_localHitPosition, normal, localHitPosition); + manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection, startInternal.m_localHitPosition, normal, + localHitPosition); localHitPosition = Internal::TryConstrainHitPositionToView( localHitPosition, startInternal.m_localHitPosition, worldFromLocal.GetInverse(), @@ -126,8 +132,8 @@ namespace AzToolsFramework const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace()); m_startInternal = CalculateManipulationDataStart( - m_fixed, worldFromLocalUniformScale, GetNonUniformScale(), TransformNormalizedScale(GetLocalTransform()), - interaction, rayIntersectionDistance); + m_fixed, worldFromLocalUniformScale, GetNonUniformScale(), TransformNormalizedScale(GetLocalTransform()), interaction, + rayIntersectionDistance); if (m_onLeftMouseDownCallback) { @@ -180,9 +186,10 @@ namespace AzToolsFramework // display the exact hit (ray intersection) of the mouse pick on the manipulator DrawTransformAxes( - debugDisplay, TransformUniformScale(GetSpace()) * - AZ::Transform::CreateTranslation( - action.m_start.m_localHitPosition + GetNonUniformScale() * action.m_current.m_localOffset)); + debugDisplay, + TransformUniformScale(GetSpace()) * + AZ::Transform::CreateTranslation( + action.m_start.m_localHitPosition + GetNonUniformScale() * action.m_current.m_localOffset)); } AZ::Transform combined = GetLocalTransform(); @@ -191,23 +198,16 @@ namespace AzToolsFramework DrawTransformAxes(debugDisplay, combined); - DrawAxis( - debugDisplay, combined.GetTranslation(), - TransformDirectionNoScaling(GetLocalTransform(), m_fixed.m_axis1)); - DrawAxis( - debugDisplay, combined.GetTranslation(), - TransformDirectionNoScaling(GetLocalTransform(), m_fixed.m_axis2)); + DrawAxis(debugDisplay, combined.GetTranslation(), TransformDirectionNoScaling(GetLocalTransform(), m_fixed.m_axis1)); + DrawAxis(debugDisplay, combined.GetTranslation(), TransformDirectionNoScaling(GetLocalTransform(), m_fixed.m_axis2)); } for (auto& view : m_manipulatorViews) { view->Draw( - GetManipulatorManagerId(), managerState, - GetManipulatorId(), { - ApplySpace(GetLocalTransform()), GetNonUniformScale(), - AZ::Vector3::CreateZero(), MouseOver() - }, - debugDisplay, cameraState, mouseInteraction); + GetManipulatorManagerId(), managerState, GetManipulatorId(), + { ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay, + cameraState, mouseInteraction); } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.h index 154ed4c7d6..3bd028ec0a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/PlanarManipulator.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -23,13 +23,13 @@ namespace AzToolsFramework class ManipulatorView; struct GridSnapParameters; - /// PlanarManipulator serves as a visual tool for users to modify values - /// in two dimension in a plane defined two non-collinear axes in 3D space. + //! PlanarManipulator serves as a visual tool for users to modify values + //! in two dimension in a plane defined two non-collinear axes in 3D space. class PlanarManipulator : public BaseManipulator , public ManipulatorSpaceWithLocalTransform { - /// Private constructor. + //! Private constructor. explicit PlanarManipulator(const AZ::Transform& worldFromLocal); public: @@ -42,43 +42,51 @@ namespace AzToolsFramework ~PlanarManipulator() = default; - /// A Manipulator must only be created and managed through a shared_ptr. + //! A Manipulator must only be created and managed through a shared_ptr. static AZStd::shared_ptr MakeShared(const AZ::Transform& worldFromLocal); - /// Unchanging data set once for the planar manipulator. + //! Unchanging data set once for the planar manipulator. struct Fixed { - AZ::Vector3 m_axis1 = AZ::Vector3::CreateAxisX(); ///< m_axis1 and m_axis2 have to be orthogonal, they together define a plane in 3d space. + AZ::Vector3 m_axis1 = + AZ::Vector3::CreateAxisX(); //!< m_axis1 and m_axis2 have to be orthogonal, they together define a plane in 3d space. AZ::Vector3 m_axis2 = AZ::Vector3::CreateAxisY(); - AZ::Vector3 m_normal = AZ::Vector3::CreateAxisZ(); ///< m_normal is calculated automatically when setting the axes. + AZ::Vector3 m_normal = AZ::Vector3::CreateAxisZ(); //!< m_normal is calculated automatically when setting the axes. }; - /// The state of the manipulator at the start of an interaction. + //! The state of the manipulator at the start of an interaction. struct Start { - AZ::Vector3 m_localPosition; ///< The current position of the manipulator in local space. - AZ::Vector3 m_localHitPosition; ///< The intersection point in local space between the ray and the manipulator when the mouse down event happens. + AZ::Vector3 m_localPosition; //!< The current position of the manipulator in local space. + AZ::Vector3 m_localHitPosition; //!< The intersection point in local space between the ray and the manipulator when the mouse + //!< down event happens. }; - /// The state of the manipulator during an interaction. + //! The state of the manipulator during an interaction. struct Current { - AZ::Vector3 m_localOffset; ///< The current position of the manipulator in local space. + AZ::Vector3 m_localOffset; //!< The current position of the manipulator in local space. }; - /// Mouse action data used by MouseActionCallback (wraps Start and Current manipulator state). + //! Mouse action data used by MouseActionCallback (wraps Start and Current manipulator state). struct Action { Fixed m_fixed; Start m_start; Current m_current; ViewportInteraction::KeyboardModifiers m_modifiers; - AZ::Vector3 LocalPosition() const { return m_start.m_localPosition + m_current.m_localOffset; } - AZ::Vector3 LocalPositionOffset() const { return m_current.m_localOffset; } + AZ::Vector3 LocalPosition() const + { + return m_start.m_localPosition + m_current.m_localOffset; + } + AZ::Vector3 LocalPositionOffset() const + { + return m_current.m_localOffset; + } }; - /// This is the function signature of callbacks that will be invoked whenever a manipulator - /// is being clicked on or dragged. + //! This is the function signature of callbacks that will be invoked whenever a manipulator + //! is being clicked on or dragged. using MouseActionCallback = AZStd::function; void InstallLeftMouseDownCallback(const MouseActionCallback& onMouseDownCallback); @@ -91,11 +99,17 @@ namespace AzToolsFramework const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; - /// Ensure @param axis1 and @param axis2 are not collinear. + //! Ensure @param axis1 and @param axis2 are not collinear. void SetAxes(const AZ::Vector3& axis1, const AZ::Vector3& axis2); - const AZ::Vector3& GetAxis1() const { return m_fixed.m_axis1; } - const AZ::Vector3& GetAxis2() const { return m_fixed.m_axis2; } + const AZ::Vector3& GetAxis1() const + { + return m_fixed.m_axis1; + } + const AZ::Vector3& GetAxis2() const + { + return m_fixed.m_axis2; + } template void SetViews(Views&& views) @@ -104,21 +118,19 @@ namespace AzToolsFramework } private: - void OnLeftMouseDownImpl( - const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; - void OnLeftMouseUpImpl( - const ViewportInteraction::MouseInteraction& interaction) override; - void OnMouseMoveImpl( - const ViewportInteraction::MouseInteraction& interaction) override; + void OnLeftMouseDownImpl(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; + void OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction) override; + void OnMouseMoveImpl(const ViewportInteraction::MouseInteraction& interaction) override; void InvalidateImpl() override; void SetBoundsDirtyImpl() override; - /// Initial data recorded when a press first happens with a planar manipulator. + //! Initial data recorded when a press first happens with a planar manipulator. struct StartInternal { - AZ::Vector3 m_localPosition; ///< The starting position of the manipulator in local space. - AZ::Vector3 m_localHitPosition; ///< The intersection point in world space between the ray and the manipulator when the mouse down event happens. + AZ::Vector3 m_localPosition; //!< The starting position of the manipulator in local space. + AZ::Vector3 m_localHitPosition; //!< The intersection point in world space between the ray and the manipulator when the mouse + //!< down event happens. }; Fixed m_fixed; @@ -128,15 +140,23 @@ namespace AzToolsFramework MouseActionCallback m_onLeftMouseUpCallback = nullptr; MouseActionCallback m_onMouseMoveCallback = nullptr; - ManipulatorViews m_manipulatorViews; ///< Look of manipulator. + ManipulatorViews m_manipulatorViews; //!< Look of manipulator. static StartInternal CalculateManipulationDataStart( - const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, float intersectionDistance); + const Fixed& fixed, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, + const ViewportInteraction::MouseInteraction& interaction, + float intersectionDistance); static Action CalculateManipulationDataAction( - const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, - const AZ::Transform& localTransform, const GridSnapParameters& gridSnapParams, + const Fixed& fixed, + const StartInternal& startInternal, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale, + const AZ::Transform& localTransform, + const GridSnapParameters& gridSnapParams, const ViewportInteraction::MouseInteraction& interaction); }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/RotationManipulators.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/RotationManipulators.cpp index 399bea4024..4bb39509e3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/RotationManipulators.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/RotationManipulators.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "RotationManipulators.h" @@ -28,8 +28,7 @@ namespace AzToolsFramework m_manipulatorSpaceWithLocalTransform.SetSpace(worldFromLocal); } - void RotationManipulators::InstallLeftMouseDownCallback( - const AngularManipulator::MouseActionCallback& onMouseDownCallback) + void RotationManipulators::InstallLeftMouseDownCallback(const AngularManipulator::MouseActionCallback& onMouseDownCallback) { for (AZStd::shared_ptr& manipulator : m_localAngularManipulators) { @@ -39,8 +38,7 @@ namespace AzToolsFramework m_viewAngularManipulator->InstallLeftMouseDownCallback(onMouseDownCallback); } - void RotationManipulators::InstallMouseMoveCallback( - const AngularManipulator::MouseActionCallback& onMouseMoveCallback) + void RotationManipulators::InstallMouseMoveCallback(const AngularManipulator::MouseActionCallback& onMouseMoveCallback) { for (AZStd::shared_ptr& manipulator : m_localAngularManipulators) { @@ -50,8 +48,7 @@ namespace AzToolsFramework m_viewAngularManipulator->InstallMouseMoveCallback(onMouseMoveCallback); } - void RotationManipulators::InstallLeftMouseUpCallback( - const AngularManipulator::MouseActionCallback& onMouseUpCallback) + void RotationManipulators::InstallLeftMouseUpCallback(const AngularManipulator::MouseActionCallback& onMouseUpCallback) { for (AZStd::shared_ptr& manipulator : m_localAngularManipulators) { @@ -109,14 +106,13 @@ namespace AzToolsFramework m_viewAngularManipulator->SetSpace(worldFromLocal); } - void RotationManipulators::SetLocalAxes( - const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3) + void RotationManipulators::SetLocalAxes(const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3) { const AZ::Vector3 axes[] = { axis1, axis2, axis3 }; for (size_t manipulatorIndex = 0; manipulatorIndex < m_localAngularManipulators.size(); ++manipulatorIndex) { - m_localAngularManipulators[manipulatorIndex]->SetAxis(axes[manipulatorIndex]); + m_localAngularManipulators[manipulatorIndex]->SetAxis(axes[manipulatorIndex]); } } @@ -124,34 +120,25 @@ namespace AzToolsFramework { m_viewAngularManipulator->SetAxis(axis); - if (auto circleView = azrtti_cast( - m_viewAngularManipulator->GetView())) + if (auto circleView = azrtti_cast(m_viewAngularManipulator->GetView())) { circleView->m_axis = axis; } } void RotationManipulators::ConfigureView( - const float radius, const AZ::Color& axis1Color, - const AZ::Color& axis2Color, const AZ::Color& axis3Color) + const float radius, const AZ::Color& axis1Color, const AZ::Color& axis2Color, const AZ::Color& axis3Color) { - const AZ::Color colors[] = { - axis1Color, axis2Color, axis3Color - }; + const AZ::Color colors[] = { axis1Color, axis2Color, axis3Color }; for (size_t manipulatorIndex = 0; manipulatorIndex < m_localAngularManipulators.size(); ++manipulatorIndex) { - m_localAngularManipulators[manipulatorIndex]->SetView( - CreateManipulatorViewCircle( - *m_localAngularManipulators[manipulatorIndex], colors[manipulatorIndex], - radius, 0.05f, DrawHalfDottedCircle)); + m_localAngularManipulators[manipulatorIndex]->SetView(CreateManipulatorViewCircle( + *m_localAngularManipulators[manipulatorIndex], colors[manipulatorIndex], radius, 0.05f, DrawHalfDottedCircle)); } - m_viewAngularManipulator->SetView( - CreateManipulatorViewCircle( - *m_viewAngularManipulator, - AZ::Color(1.0f, 1.0f, 1.0f, 1.0f), - radius + (radius * 0.12f), 0.05f, DrawFullCircle)); + m_viewAngularManipulator->SetView(CreateManipulatorViewCircle( + *m_viewAngularManipulator, AZ::Color(1.0f, 1.0f, 1.0f, 1.0f), radius + (radius * 0.12f), 0.05f, DrawFullCircle)); } bool RotationManipulators::PerformingActionViewAxis() const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/RotationManipulators.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/RotationManipulators.h index 11b6e0838c..5ecfa21f26 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/RotationManipulators.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/RotationManipulators.h @@ -1,27 +1,26 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once #include -#include #include +#include namespace AzToolsFramework { - /// RotationManipulators is an aggregation of 3 angular manipulators who share the same origin - /// in addition to a view aligned angular manipulator (facing the camera). - class RotationManipulators - : public Manipulators + //! RotationManipulators is an aggregation of 3 angular manipulators who share the same origin + //! in addition to a view aligned angular manipulator (facing the camera). + class RotationManipulators : public Manipulators { public: AZ_RTTI(RotationManipulators, "{5D1F1D47-1D5B-4E42-B47E-23F108F8BF7D}") @@ -40,12 +39,10 @@ namespace AzToolsFramework void SetLocalOrientationImpl(const AZ::Quaternion& localOrientation) override; void RefreshView(const AZ::Vector3& worldViewPosition) override; - void SetLocalAxes( - const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3); + void SetLocalAxes(const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3); void SetViewAxis(const AZ::Vector3& axis); - void ConfigureView( - float radius, const AZ::Color& axis1Color, const AZ::Color& axis2Color, const AZ::Color& axis3Color); + void ConfigureView(float radius, const AZ::Color& axis1Color, const AZ::Color& axis2Color, const AZ::Color& axis3Color); bool PerformingActionViewAxis() const; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ScaleManipulators.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ScaleManipulators.cpp index caeedd834f..079fde669a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ScaleManipulators.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ScaleManipulators.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "ScaleManipulators.h" @@ -28,8 +28,7 @@ namespace AzToolsFramework m_manipulatorSpaceWithLocalTransform.SetSpace(worldFromLocal); } - void ScaleManipulators::InstallAxisLeftMouseDownCallback( - const LinearManipulator::MouseActionCallback& onMouseDownCallback) + void ScaleManipulators::InstallAxisLeftMouseDownCallback(const LinearManipulator::MouseActionCallback& onMouseDownCallback) { for (AZStd::shared_ptr& manipulator : m_axisScaleManipulators) { @@ -37,8 +36,7 @@ namespace AzToolsFramework } } - void ScaleManipulators::InstallAxisMouseMoveCallback( - const LinearManipulator::MouseActionCallback& onMouseMoveCallback) + void ScaleManipulators::InstallAxisMouseMoveCallback(const LinearManipulator::MouseActionCallback& onMouseMoveCallback) { for (AZStd::shared_ptr& manipulator : m_axisScaleManipulators) { @@ -46,8 +44,7 @@ namespace AzToolsFramework } } - void ScaleManipulators::InstallAxisLeftMouseUpCallback( - const LinearManipulator::MouseActionCallback& onMouseUpCallback) + void ScaleManipulators::InstallAxisLeftMouseUpCallback(const LinearManipulator::MouseActionCallback& onMouseUpCallback) { for (AZStd::shared_ptr& manipulator : m_axisScaleManipulators) { @@ -55,22 +52,19 @@ namespace AzToolsFramework } } - void ScaleManipulators::InstallUniformLeftMouseDownCallback( - const LinearManipulator::MouseActionCallback& onMouseDownCallback) + void ScaleManipulators::InstallUniformLeftMouseDownCallback(const LinearManipulator::MouseActionCallback& onMouseDownCallback) { m_uniformScaleManipulator->InstallLeftMouseDownCallback(onMouseDownCallback); } - void ScaleManipulators::InstallUniformMouseMoveCallback( - const LinearManipulator::MouseActionCallback& onMouseMoveCallback) + void ScaleManipulators::InstallUniformMouseMoveCallback(const LinearManipulator::MouseActionCallback& onMouseMoveCallback) { - m_uniformScaleManipulator->InstallMouseMoveCallback(onMouseMoveCallback); + m_uniformScaleManipulator->InstallMouseMoveCallback(onMouseMoveCallback); } - void ScaleManipulators::InstallUniformLeftMouseUpCallback( - const LinearManipulator::MouseActionCallback& onMouseUpCallback) + void ScaleManipulators::InstallUniformLeftMouseUpCallback(const LinearManipulator::MouseActionCallback& onMouseUpCallback) { - m_uniformScaleManipulator->InstallLeftMouseUpCallback(onMouseUpCallback); + m_uniformScaleManipulator->InstallLeftMouseUpCallback(onMouseUpCallback); } void ScaleManipulators::SetLocalTransformImpl(const AZ::Transform& localTransform) @@ -80,8 +74,7 @@ namespace AzToolsFramework manipulator->SetLocalTransform(localTransform); } - m_uniformScaleManipulator->SetVisualOrientationOverride( - QuaternionFromTransformNoScaling(localTransform)); + m_uniformScaleManipulator->SetVisualOrientationOverride(QuaternionFromTransformNoScaling(localTransform)); m_uniformScaleManipulator->SetLocalOrientation(AZ::Quaternion::CreateIdentity()); } @@ -113,14 +106,13 @@ namespace AzToolsFramework m_uniformScaleManipulator->SetSpace(worldFromLocal); } - void ScaleManipulators::SetAxes( - const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3) + void ScaleManipulators::SetAxes(const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3) { - AZ::Vector3 axes[] = { axis1, axis2, axis3 }; + AZ::Vector3 axes[] = { axis1, axis2, axis3 }; for (size_t manipulatorIndex = 0; manipulatorIndex < m_axisScaleManipulators.size(); ++manipulatorIndex) { - m_axisScaleManipulators[manipulatorIndex]->SetAxis(axes[manipulatorIndex]); + m_axisScaleManipulators[manipulatorIndex]->SetAxis(axes[manipulatorIndex]); } // uniform scale manipulator uses Z axis for scaling (always in world space) @@ -129,32 +121,27 @@ namespace AzToolsFramework } void ScaleManipulators::ConfigureView( - const float axisLength, const AZ::Color& axis1Color, - const AZ::Color& axis2Color, const AZ::Color& axis3Color) + const float axisLength, const AZ::Color& axis1Color, const AZ::Color& axis2Color, const AZ::Color& axis3Color) { const float boxSize = 0.1f; const float lineWidth = 0.05f; - const AZ::Color colors[] = { - axis1Color, axis2Color, axis3Color - }; + const AZ::Color colors[] = { axis1Color, axis2Color, axis3Color }; for (size_t manipulatorIndex = 0; manipulatorIndex < m_axisScaleManipulators.size(); ++manipulatorIndex) { ManipulatorViews views; - views.emplace_back(CreateManipulatorViewLine( - *m_axisScaleManipulators[manipulatorIndex], colors[manipulatorIndex], axisLength, lineWidth)); + views.emplace_back( + CreateManipulatorViewLine(*m_axisScaleManipulators[manipulatorIndex], colors[manipulatorIndex], axisLength, lineWidth)); views.emplace_back(CreateManipulatorViewBox( AZ::Transform::CreateIdentity(), colors[manipulatorIndex], - m_axisScaleManipulators[manipulatorIndex]->GetAxis() * (axisLength - boxSize), - AZ::Vector3(boxSize))); + m_axisScaleManipulators[manipulatorIndex]->GetAxis() * (axisLength - boxSize), AZ::Vector3(boxSize))); m_axisScaleManipulators[manipulatorIndex]->SetViews(AZStd::move(views)); } ManipulatorViews views; views.emplace_back(CreateManipulatorViewBox( - AZ::Transform::CreateIdentity(), AZ::Color::CreateOne(), - AZ::Vector3::CreateZero(), AZ::Vector3(boxSize))); + AZ::Transform::CreateIdentity(), AZ::Color::CreateOne(), AZ::Vector3::CreateZero(), AZ::Vector3(boxSize))); m_uniformScaleManipulator->SetViews(AZStd::move(views)); } @@ -167,4 +154,4 @@ namespace AzToolsFramework manipulatorFn(m_uniformScaleManipulator.get()); } -} +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ScaleManipulators.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ScaleManipulators.h index 24df3cda7b..b06d8f92c5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ScaleManipulators.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ScaleManipulators.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -17,11 +17,10 @@ namespace AzToolsFramework { - /// ScaleManipulators is an aggregation of 3 linear manipulators for each basis axis who share - /// the same transform, and a single linear manipulator at the center of the transform whose - /// axis is world up (z). - class ScaleManipulators - : public Manipulators + //! ScaleManipulators is an aggregation of 3 linear manipulators for each basis axis who share + //! the same transform, and a single linear manipulator at the center of the transform whose + //! axis is world up (z). + class ScaleManipulators : public Manipulators { public: AZ_RTTI(ScaleManipulators, "{C6350CE0-7B7A-46F8-B65F-D4A54DD9A7D9}") @@ -42,16 +41,9 @@ namespace AzToolsFramework void SetLocalPositionImpl(const AZ::Vector3& localPosition) override; void SetLocalOrientationImpl(const AZ::Quaternion& localOrientation) override; - void SetAxes( - const AZ::Vector3& axis1, - const AZ::Vector3& axis2, - const AZ::Vector3& axis3); + void SetAxes(const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3); - void ConfigureView( - float axisLength, - const AZ::Color& axis1Color, - const AZ::Color& axis2Color, - const AZ::Color& axis3Color); + void ConfigureView(float axisLength, const AZ::Color& axis1Color, const AZ::Color& axis2Color, const AZ::Color& axis3Color); private: AZ_DISABLE_COPY_MOVE(ScaleManipulators) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SelectionManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SelectionManipulator.cpp index 4925651580..3071ca74ae 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SelectionManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SelectionManipulator.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "SelectionManipulator.h" @@ -16,8 +16,8 @@ namespace AzToolsFramework { - AZStd::shared_ptr SelectionManipulator::MakeShared(const AZ::Transform& worldFromLocal, - const AZ::Vector3& nonUniformScale) + AZStd::shared_ptr SelectionManipulator::MakeShared( + const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale) { return AZStd::shared_ptr(aznew SelectionManipulator(worldFromLocal, nonUniformScale)); } @@ -93,12 +93,9 @@ namespace AzToolsFramework for (auto& view : m_manipulatorViews) { view->Draw( - GetManipulatorManagerId(), managerState, - GetManipulatorId(), { - TransformUniformScale(GetSpace()), GetNonUniformScale(), - GetLocalPosition(), MouseOver() - }, - debugDisplay, cameraState, mouseInteraction); + GetManipulatorManagerId(), managerState, GetManipulatorId(), + { TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalPosition(), MouseOver() }, debugDisplay, cameraState, + mouseInteraction); } } @@ -117,4 +114,4 @@ namespace AzToolsFramework view->Invalidate(GetManipulatorManagerId()); } } -} +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SelectionManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SelectionManipulator.h index 1ae6ceb729..b862dfd684 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SelectionManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SelectionManipulator.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -20,13 +20,13 @@ namespace AzToolsFramework { class ManipulatorView; - /// Represents a sphere that can be clicked on to trigger a particular behavior - /// For example clicking a preview point to create a translation manipulator. + //! Represents a sphere that can be clicked on to trigger a particular behavior. + //! For example clicking a preview point to create a translation manipulator. class SelectionManipulator : public BaseManipulator , public ManipulatorSpaceWithLocalPosition { - /// Private constructor. + //! Private constructor. SelectionManipulator(const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale = AZ::Vector3::CreateOne()); public: @@ -39,12 +39,12 @@ namespace AzToolsFramework ~SelectionManipulator() = default; - /// A Manipulator must only be created and managed through a shared_ptr. - static AZStd::shared_ptr MakeShared(const AZ::Transform& worldFromLocal, - const AZ::Vector3& nonUniformScale = AZ::Vector3::CreateOne()); + //! A Manipulator must only be created and managed through a shared_ptr. + static AZStd::shared_ptr MakeShared( + const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale = AZ::Vector3::CreateOne()); - /// This is the function signature of callbacks that will be invoked - /// whenever a selection manipulator is clicked on. + //! This is the function signature of callbacks that will be invoked + //! whenever a selection manipulator is clicked on. using MouseActionCallback = AZStd::function; void InstallLeftMouseDownCallback(const MouseActionCallback& onMouseDownCallback); @@ -58,10 +58,25 @@ namespace AzToolsFramework const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; - bool Selected() const { return m_selected; } - void Select() { m_selected = true; } - void Deselect() { m_selected = false; } - void ToggleSelected() { m_selected = !m_selected; } + bool Selected() const + { + return m_selected; + } + + void Select() + { + m_selected = true; + } + + void Deselect() + { + m_selected = false; + } + + void ToggleSelected() + { + m_selected = !m_selected; + } template void SetViews(Views&& views) @@ -70,13 +85,9 @@ namespace AzToolsFramework } private: - void OnLeftMouseDownImpl( - const ViewportInteraction::MouseInteraction& interaction, - float rayIntersectionDistance) override; + void OnLeftMouseDownImpl(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; void OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction) override; - void OnRightMouseDownImpl( - const ViewportInteraction::MouseInteraction& interaction, - float rayIntersectionDistance) override; + void OnRightMouseDownImpl(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; void OnRightMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction) override; void InvalidateImpl() override; @@ -89,6 +100,6 @@ namespace AzToolsFramework MouseActionCallback m_onRightMouseDownCallback = nullptr; MouseActionCallback m_onRightMouseUpCallback = nullptr; - ManipulatorViews m_manipulatorViews; ///< Look of manipulator. + ManipulatorViews m_manipulatorViews; //!< Look of manipulator. }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineHoverSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineHoverSelection.cpp index 43fbbce80b..98972bcf33 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineHoverSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineHoverSelection.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "SplineHoverSelection.h" @@ -20,11 +20,12 @@ namespace AzToolsFramework { - static const AZ::Color s_splineSelectManipulatorColor = AZ::Color(0.0f, 1.0f, 0.0f, 1.0f); + static const AZ::Color SplineSelectManipulatorColor = AZ::Color(0.0f, 1.0f, 0.0f, 1.0f); SplineHoverSelection::SplineHoverSelection( const AZ::EntityComponentIdPair& entityComponentIdPair, - const ManipulatorManagerId managerId, const AZStd::shared_ptr& spline) + const ManipulatorManagerId managerId, + const AZStd::shared_ptr& spline) { m_splineSelectionManipulator = SplineSelectionManipulator::MakeShared(); m_splineSelectionManipulator->Register(managerId); @@ -33,16 +34,14 @@ namespace AzToolsFramework const float splineWidth = 0.05f; m_splineSelectionManipulator->SetSpline(spline); - m_splineSelectionManipulator->SetView(CreateManipulatorViewSplineSelect( - *m_splineSelectionManipulator, s_splineSelectManipulatorColor, splineWidth)); + m_splineSelectionManipulator->SetView( + CreateManipulatorViewSplineSelect(*m_splineSelectionManipulator, SplineSelectManipulatorColor, splineWidth)); m_splineSelectionManipulator->InstallLeftMouseUpCallback( [entityComponentIdPair](const SplineSelectionManipulator::Action& action) - { - InsertVertexAfter( - entityComponentIdPair, action.m_splineAddress.m_segmentIndex, - action.m_localSplineHitPosition); - }); + { + InsertVertexAfter(entityComponentIdPair, action.m_splineAddress.m_segmentIndex, action.m_localSplineHitPosition); + }); } SplineHoverSelection::~SplineHoverSelection() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineHoverSelection.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineHoverSelection.h index 11b10f8516..d8dcd573af 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineHoverSelection.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineHoverSelection.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -19,20 +19,20 @@ namespace AZ { class Spline; class EntityComponentIdPair; -} +} // namespace AZ namespace AzToolsFramework { class SplineSelectionManipulator; - /// SplineHoverSelection is a concrete implementation of HoverSelection wrapping a Spline and - /// SplineManipulator. The underlying manipulators are used to control selection. - class SplineHoverSelection - : public HoverSelection + //! SplineHoverSelection is a concrete implementation of HoverSelection wrapping a Spline and + //! SplineManipulator. The underlying manipulators are used to control selection. + class SplineHoverSelection : public HoverSelection { public: explicit SplineHoverSelection( - const AZ::EntityComponentIdPair& entityComponentIdPair, ManipulatorManagerId managerId, + const AZ::EntityComponentIdPair& entityComponentIdPair, + ManipulatorManagerId managerId, const AZStd::shared_ptr& spline); SplineHoverSelection(const SplineHoverSelection&) = delete; SplineHoverSelection& operator=(const SplineHoverSelection&) = delete; @@ -46,6 +46,6 @@ namespace AzToolsFramework void SetNonUniformScale(const AZ::Vector3& nonUniformScale) override; private: - AZStd::shared_ptr m_splineSelectionManipulator; ///< Manipulator for adding points to spline. + AZStd::shared_ptr m_splineSelectionManipulator; //!< Manipulator for adding points to spline. }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineSelectionManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineSelectionManipulator.cpp index 5bfccefe48..39dbcb67fa 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineSelectionManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineSelectionManipulator.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "SplineSelectionManipulator.h" @@ -18,8 +18,10 @@ namespace AzToolsFramework { SplineSelectionManipulator::Action CalculateManipulationDataAction( - const AZ::Transform& worldFromLocal, const AZ::Vector3& rayOrigin, - const AZ::Vector3& rayDirection, const AZStd::weak_ptr& spline) + const AZ::Transform& worldFromLocal, + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, + const AZStd::weak_ptr& spline) { SplineSelectionManipulator::Action action; if (const AZStd::shared_ptr splinePtr = spline.lock()) @@ -65,9 +67,7 @@ namespace AzToolsFramework if (m_onLeftMouseDownCallback) { m_onLeftMouseDownCallback(CalculateManipulationDataAction( - TransformUniformScale(GetSpace()), - interaction.m_mousePick.m_rayOrigin, - interaction.m_mousePick.m_rayDirection, m_spline)); + TransformUniformScale(GetSpace()), interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection, m_spline)); } } @@ -76,9 +76,7 @@ namespace AzToolsFramework if (MouseOver() && m_onLeftMouseUpCallback) { m_onLeftMouseUpCallback(CalculateManipulationDataAction( - TransformUniformScale(GetSpace()), - interaction.m_mousePick.m_rayOrigin, - interaction.m_mousePick.m_rayDirection, m_spline)); + TransformUniformScale(GetSpace()), interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection, m_spline)); } } @@ -99,12 +97,9 @@ namespace AzToolsFramework if (mouseInteraction.m_keyboardModifiers.Ctrl() && !mouseInteraction.m_keyboardModifiers.Shift()) { m_manipulatorView->Draw( - GetManipulatorManagerId(), managerState, - GetManipulatorId(), { - TransformUniformScale(GetSpace()), GetNonUniformScale(), - AZ::Vector3::CreateZero(), MouseOver() - }, - debugDisplay, cameraState, mouseInteraction); + GetManipulatorManagerId(), managerState, GetManipulatorId(), + { TransformUniformScale(GetSpace()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay, + cameraState, mouseInteraction); } } @@ -122,4 +117,4 @@ namespace AzToolsFramework { m_manipulatorView->Invalidate(GetManipulatorManagerId()); } -} +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineSelectionManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineSelectionManipulator.h index 721c3413ef..e1a2fe26ab 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineSelectionManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SplineSelectionManipulator.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -23,13 +23,13 @@ namespace AzToolsFramework { class ManipulatorView; - /// A manipulator to represent selection of a spline. Underlying spline data is - /// used to test mouse picking ray against to preview closest point on spline. + //! A manipulator to represent selection of a spline. Underlying spline data is + //! used to test mouse picking ray against to preview closest point on spline. class SplineSelectionManipulator : public BaseManipulator , public ManipulatorSpace { - /// Private constructor. + //! Private constructor. SplineSelectionManipulator(); public: @@ -41,10 +41,10 @@ namespace AzToolsFramework ~SplineSelectionManipulator(); - /// A Manipulator must only be created and managed through a shared_ptr. + //! A Manipulator must only be created and managed through a shared_ptr. static AZStd::shared_ptr MakeShared(); - /// Mouse action data used by MouseActionCallback. + //! Mouse action data used by MouseActionCallback. struct Action { AZ::Vector3 m_localSplineHitPosition; @@ -62,29 +62,36 @@ namespace AzToolsFramework const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) override; - void SetSpline(AZStd::shared_ptr spline) { m_spline = AZStd::move(spline); } - AZStd::weak_ptr GetSpline() const { return m_spline; } + void SetSpline(AZStd::shared_ptr spline) + { + m_spline = AZStd::move(spline); + } + AZStd::weak_ptr GetSpline() const + { + return m_spline; + } void SetView(AZStd::unique_ptr&& view); private: - void OnLeftMouseDownImpl( - const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; - void OnLeftMouseUpImpl( - const ViewportInteraction::MouseInteraction& interaction) override; + void OnLeftMouseDownImpl(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; + void OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction) override; void InvalidateImpl() override; void SetBoundsDirtyImpl() override; AZStd::weak_ptr m_spline; - AZStd::unique_ptr m_manipulatorView = nullptr; ///< Look of manipulator and bounds for interaction. + AZStd::unique_ptr m_manipulatorView = nullptr; //!< Look of manipulator and bounds for interaction. MouseActionCallback m_onLeftMouseDownCallback = nullptr; MouseActionCallback m_onLeftMouseUpCallback = nullptr; - ViewportInteraction::KeyboardModifiers m_keyboardModifiers; ///< What modifier keys are pressed when interacting with this manipulator. + ViewportInteraction::KeyboardModifiers + m_keyboardModifiers; //!< What modifier keys are pressed when interacting with this manipulator. }; SplineSelectionManipulator::Action CalculateManipulationDataAction( - const AZ::Transform& worldFromLocal, const AZ::Vector3& rayOrigin, - const AZ::Vector3& rayDirection, const AZStd::weak_ptr& spline); + const AZ::Transform& worldFromLocal, + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, + const AZStd::weak_ptr& spline); } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp index f570c20a7e..aa3f3f5882 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "SurfaceManipulator.h" @@ -18,19 +18,22 @@ namespace AzToolsFramework { SurfaceManipulator::StartInternal SurfaceManipulator::CalculateManipulationDataStart( - const AZ::Transform& worldFromLocal, const AZ::Vector3& worldSurfacePosition, - const AZ::Vector3& localStartPosition, const bool snapping, const float gridSize, const int viewportId) + const AZ::Transform& worldFromLocal, + const AZ::Vector3& worldSurfacePosition, + const AZ::Vector3& localStartPosition, + const bool snapping, + const float gridSize, + const int viewportId) { const AZ::Transform worldFromLocalUniform = AzToolsFramework::TransformUniformScale(worldFromLocal); const AZ::Transform localFromWorldUniform = worldFromLocalUniform.GetInverse(); const AZ::Vector3 localFinalSurfacePosition = snapping - ? CalculateSnappedTerrainPosition( - // note: gridSize is not scaled by scaleRecip here as localStartPosition is - // unscaled itself so the position returned by CalculateSnappedTerrainPosition - // must be in the same space (if localStartPosition were also scaled, gridSize - // would need to be multiplied by scaleRecip) - worldSurfacePosition, worldFromLocalUniform, viewportId, gridSize) + // note: gridSize is not scaled by scaleRecip here as localStartPosition is + // unscaled itself so the position returned by CalculateSnappedTerrainPosition + // must be in the same space (if localStartPosition were also scaled, gridSize + // would need to be multiplied by scaleRecip) + ? CalculateSnappedTerrainPosition(worldSurfacePosition, worldFromLocalUniform, viewportId, gridSize) : localFromWorldUniform.TransformPoint(worldSurfacePosition); // delta/offset between initial vertex position and terrain pick position @@ -44,9 +47,13 @@ namespace AzToolsFramework } SurfaceManipulator::Action SurfaceManipulator::CalculateManipulationDataAction( - const StartInternal& startInternal, const AZ::Transform& worldFromLocal, - const AZ::Vector3& worldSurfacePosition, const bool snapping, const float gridSize, - const ViewportInteraction::KeyboardModifiers keyboardModifiers, const int viewportId) + const StartInternal& startInternal, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& worldSurfacePosition, + const bool snapping, + const float gridSize, + const ViewportInteraction::KeyboardModifiers keyboardModifiers, + const int viewportId) { const AZ::Transform worldFromLocalUniform = AzToolsFramework::TransformUniformScale(worldFromLocal); const AZ::Transform localFromWorldUniform = worldFromLocalUniform.GetInverse(); @@ -54,8 +61,7 @@ namespace AzToolsFramework const float scaleRecip = ScaleReciprocal(worldFromLocalUniform); const AZ::Vector3 localFinalSurfacePosition = snapping - ? CalculateSnappedTerrainPosition( - worldSurfacePosition, worldFromLocalUniform, viewportId, gridSize * scaleRecip) + ? CalculateSnappedTerrainPosition(worldSurfacePosition, worldFromLocalUniform, viewportId, gridSize * scaleRecip) : localFromWorldUniform.TransformPoint(worldSurfacePosition); Action action; @@ -106,17 +112,14 @@ namespace AzToolsFramework interaction.m_mousePick.m_screenCoordinates); m_startInternal = CalculateManipulationDataStart( - worldFromLocalUniformScale, worldSurfacePosition, GetLocalPosition(), - gridSnapParams.m_gridSnap, gridSnapParams.m_gridSize, + worldFromLocalUniformScale, worldSurfacePosition, GetLocalPosition(), gridSnapParams.m_gridSnap, gridSnapParams.m_gridSize, interaction.m_interactionId.m_viewportId); if (m_onLeftMouseDownCallback) { m_onLeftMouseDownCallback(CalculateManipulationDataAction( - m_startInternal, worldFromLocalUniformScale, worldSurfacePosition, - gridSnapParams.m_gridSnap, gridSnapParams.m_gridSize, - interaction.m_keyboardModifiers, - interaction.m_interactionId.m_viewportId)); + m_startInternal, worldFromLocalUniformScale, worldSurfacePosition, gridSnapParams.m_gridSnap, gridSnapParams.m_gridSize, + interaction.m_keyboardModifiers, interaction.m_interactionId.m_viewportId)); } } @@ -133,10 +136,8 @@ namespace AzToolsFramework const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); m_onLeftMouseUpCallback(CalculateManipulationDataAction( - m_startInternal, TransformUniformScale(GetSpace()), worldSurfacePosition, - gridSnapParams.m_gridSnap, - gridSnapParams.m_gridSize, - interaction.m_keyboardModifiers, interaction.m_interactionId.m_viewportId)); + m_startInternal, TransformUniformScale(GetSpace()), worldSurfacePosition, gridSnapParams.m_gridSnap, + gridSnapParams.m_gridSize, interaction.m_keyboardModifiers, interaction.m_interactionId.m_viewportId)); } } @@ -153,10 +154,8 @@ namespace AzToolsFramework const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); m_onMouseMoveCallback(CalculateManipulationDataAction( - m_startInternal, TransformUniformScale(GetSpace()), worldSurfacePosition, - gridSnapParams.m_gridSnap, - gridSnapParams.m_gridSize, - interaction.m_keyboardModifiers, interaction.m_interactionId.m_viewportId)); + m_startInternal, TransformUniformScale(GetSpace()), worldSurfacePosition, gridSnapParams.m_gridSnap, + gridSnapParams.m_gridSize, interaction.m_keyboardModifiers, interaction.m_interactionId.m_viewportId)); } } @@ -172,12 +171,9 @@ namespace AzToolsFramework const ViewportInteraction::MouseInteraction& mouseInteraction) { m_manipulatorView->Draw( - GetManipulatorManagerId(), managerState, - GetManipulatorId(), { - TransformUniformScale(GetSpace()), GetNonUniformScale(), - GetLocalPosition(), MouseOver() - }, - debugDisplay, cameraState, mouseInteraction); + GetManipulatorManagerId(), managerState, GetManipulatorId(), + { TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalPosition(), MouseOver() }, debugDisplay, cameraState, + mouseInteraction); } void SurfaceManipulator::InvalidateImpl() @@ -189,4 +185,4 @@ namespace AzToolsFramework { m_manipulatorView = AZStd::move(view); } -} +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.h index 72eb3a5cda..6461954353 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -21,13 +21,13 @@ namespace AzToolsFramework { class ManipulatorView; - /// Surface manipulator will ensure the point(s) it controls snap precisely to the xy grid - /// while also staying aligned exactly to the height of the terrain. + //! Surface manipulator will ensure the point(s) it controls snap precisely to the xy grid + //! while also staying aligned exactly to the height of the terrain. class SurfaceManipulator : public BaseManipulator , public ManipulatorSpaceWithLocalPosition { - /// Private constructor. + //! Private constructor. explicit SurfaceManipulator(const AZ::Transform& worldFromLocal); public: @@ -40,30 +40,36 @@ namespace AzToolsFramework ~SurfaceManipulator() = default; - /// A Manipulator must only be created and managed through a shared_ptr. + //! A Manipulator must only be created and managed through a shared_ptr. static AZStd::shared_ptr MakeShared(const AZ::Transform& worldFromLocal); - /// The state of the manipulator at the start of an interaction. + //! The state of the manipulator at the start of an interaction. struct Start { - AZ::Vector3 m_localPosition; ///< The current position of the manipulator in local space. - AZ::Vector3 m_snapOffset; ///< The snap offset amount to ensure manipulator is aligned to the grid. + AZ::Vector3 m_localPosition; //!< The current position of the manipulator in local space. + AZ::Vector3 m_snapOffset; //!< The snap offset amount to ensure manipulator is aligned to the grid. }; - /// The state of the manipulator during an interaction. + //! The state of the manipulator during an interaction. struct Current { - AZ::Vector3 m_localOffset; ///< The current offset of the manipulator from its starting position in local space. + AZ::Vector3 m_localOffset; //!< The current offset of the manipulator from its starting position in local space. }; - /// Mouse action data used by MouseActionCallback (wraps Start and Current manipulator state). + //! Mouse action data used by MouseActionCallback (wraps Start and Current manipulator state). struct Action { Start m_start; Current m_current; ViewportInteraction::KeyboardModifiers m_modifiers; - AZ::Vector3 LocalPosition() const { return m_start.m_localPosition + m_current.m_localOffset; } - AZ::Vector3 LocalPositionOffset() const { return m_current.m_localOffset; } + AZ::Vector3 LocalPosition() const + { + return m_start.m_localPosition + m_current.m_localOffset; + } + AZ::Vector3 LocalPositionOffset() const + { + return m_current.m_localOffset; + } }; using MouseActionCallback = AZStd::function; @@ -81,39 +87,44 @@ namespace AzToolsFramework void SetView(AZStd::unique_ptr&& view); private: - void OnLeftMouseDownImpl( - const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; - void OnLeftMouseUpImpl( - const ViewportInteraction::MouseInteraction& interaction) override; - void OnMouseMoveImpl( - const ViewportInteraction::MouseInteraction& interaction) override; + void OnLeftMouseDownImpl(const ViewportInteraction::MouseInteraction& interaction, float rayIntersectionDistance) override; + void OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction) override; + void OnMouseMoveImpl(const ViewportInteraction::MouseInteraction& interaction) override; void InvalidateImpl() override; void SetBoundsDirtyImpl() override; - /// Initial data recorded when a press first happens with a surface manipulator. + //! Initial data recorded when a press first happens with a surface manipulator. struct StartInternal { - AZ::Vector3 m_localPosition; ///< The current position of the manipulator in local space. - AZ::Vector3 m_localHitPosition; ///< The hit position with the terrain in local space. - AZ::Vector3 m_snapOffset; ///< The snap offset amount to ensure manipulator is aligned to the grid. + AZ::Vector3 m_localPosition; //!< The current position of the manipulator in local space. + AZ::Vector3 m_localHitPosition; //!< The hit position with the terrain in local space. + AZ::Vector3 m_snapOffset; //!< The snap offset amount to ensure manipulator is aligned to the grid. }; - StartInternal m_startInternal; ///< Internal initial state recorded/created in OnMouseDown. + StartInternal m_startInternal; //!< Internal initial state recorded/created in OnMouseDown. - AZStd::unique_ptr m_manipulatorView = nullptr; ///< Look of manipulator. + AZStd::unique_ptr m_manipulatorView = nullptr; //!< Look of manipulator. MouseActionCallback m_onLeftMouseDownCallback = nullptr; MouseActionCallback m_onLeftMouseUpCallback = nullptr; MouseActionCallback m_onMouseMoveCallback = nullptr; static StartInternal CalculateManipulationDataStart( - const AZ::Transform& worldFromLocal, const AZ::Vector3& worldSurfacePosition, - const AZ::Vector3& localPosition, bool snapping, float gridSize, int viewportId); + const AZ::Transform& worldFromLocal, + const AZ::Vector3& worldSurfacePosition, + const AZ::Vector3& localPosition, + bool snapping, + float gridSize, + int viewportId); static Action CalculateManipulationDataAction( - const StartInternal& startInternal, const AZ::Transform& worldFromLocal, - const AZ::Vector3& worldSurfacePosition, bool snapping, float gridSize, - ViewportInteraction::KeyboardModifiers keyboardModifiers, int viewportId); + const StartInternal& startInternal, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& worldSurfacePosition, + bool snapping, + float gridSize, + ViewportInteraction::KeyboardModifiers keyboardModifiers, + int viewportId); }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/TranslationManipulators.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/TranslationManipulators.cpp index bfdfd8ba08..57d175c34e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/TranslationManipulators.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/TranslationManipulators.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "TranslationManipulators.h" @@ -77,8 +77,7 @@ namespace AzToolsFramework } } - void TranslationManipulators::InstallLinearManipulatorMouseUpCallback( - const LinearManipulator::MouseActionCallback& onMouseUpCallback) + void TranslationManipulators::InstallLinearManipulatorMouseUpCallback(const LinearManipulator::MouseActionCallback& onMouseUpCallback) { for (AZStd::shared_ptr& manipulator : m_linearManipulators) { @@ -104,8 +103,7 @@ namespace AzToolsFramework } } - void TranslationManipulators::InstallPlanarManipulatorMouseUpCallback( - const PlanarManipulator::MouseActionCallback& onMouseUpCallback) + void TranslationManipulators::InstallPlanarManipulatorMouseUpCallback(const PlanarManipulator::MouseActionCallback& onMouseUpCallback) { for (AZStd::shared_ptr& manipulator : m_planarManipulators) { @@ -122,8 +120,7 @@ namespace AzToolsFramework } } - void TranslationManipulators::InstallSurfaceManipulatorMouseUpCallback( - const SurfaceManipulator::MouseActionCallback& onMouseUpCallback) + void TranslationManipulators::InstallSurfaceManipulatorMouseUpCallback(const SurfaceManipulator::MouseActionCallback& onMouseUpCallback) { if (m_surfaceManipulator) { @@ -242,7 +239,9 @@ namespace AzToolsFramework } void TranslationManipulators::ConfigureLinearView( - float axisLength, const AZ::Color& axis1Color, const AZ::Color& axis2Color, + float axisLength, + const AZ::Color& axis1Color, + const AZ::Color& axis2Color, const AZ::Color& axis3Color /*= AZ::Color(0.0f, 0.0f, 1.0f, 0.5f)*/) { const float coneLength = 0.28f; @@ -251,15 +250,13 @@ namespace AzToolsFramework const AZ::Color axesColor[] = { axis1Color, axis2Color, axis3Color }; - const auto configureLinearView = [lineWidth, coneLength, axisLength, coneRadius]( - LinearManipulator* linearManipulator, const AZ::Color& color) + const auto configureLinearView = + [lineWidth, coneLength, axisLength, coneRadius](LinearManipulator* linearManipulator, const AZ::Color& color) { ManipulatorViews views; - views.emplace_back(CreateManipulatorViewLine( - *linearManipulator, color, axisLength, lineWidth)); + views.emplace_back(CreateManipulatorViewLine(*linearManipulator, color, axisLength, lineWidth)); views.emplace_back(CreateManipulatorViewCone( - *linearManipulator, color, linearManipulator->GetAxis() * (axisLength - coneLength), - coneLength, coneRadius)); + *linearManipulator, color, linearManipulator->GetAxis() * (axisLength - coneLength), coneLength, coneRadius)); linearManipulator->SetViews(AZStd::move(views)); }; @@ -270,7 +267,8 @@ namespace AzToolsFramework } void TranslationManipulators::ConfigurePlanarView( - const AZ::Color& plane1Color, const AZ::Color& plane2Color /*= AZ::Color(0.0f, 1.0f, 0.0f, 0.5f)*/, + const AZ::Color& plane1Color, + const AZ::Color& plane2Color /*= AZ::Color(0.0f, 1.0f, 0.0f, 0.5f)*/, const AZ::Color& plane3Color /*= AZ::Color(0.0f, 0.0f, 1.0f, 0.5f)*/) { const float planeSize = 0.6f; @@ -278,34 +276,29 @@ namespace AzToolsFramework for (size_t manipulatorIndex = 0; manipulatorIndex < m_planarManipulators.size(); ++manipulatorIndex) { - const AZStd::shared_ptr manipulatorView = - CreateManipulatorViewQuad( - *m_planarManipulators[manipulatorIndex], planesColor[manipulatorIndex], - planesColor[(manipulatorIndex + 1) % 3], - planeSize); + const AZStd::shared_ptr manipulatorView = CreateManipulatorViewQuad( + *m_planarManipulators[manipulatorIndex], planesColor[manipulatorIndex], planesColor[(manipulatorIndex + 1) % 3], planeSize); - m_planarManipulators[manipulatorIndex]->SetViews(ManipulatorViews{manipulatorView}); + m_planarManipulators[manipulatorIndex]->SetViews(ManipulatorViews{ manipulatorView }); } } - void TranslationManipulators::ConfigureSurfaceView( - const float radius, const AZ::Color& color) + void TranslationManipulators::ConfigureSurfaceView(const float radius, const AZ::Color& color) { if (m_surfaceManipulator) { - m_surfaceManipulator->SetView(CreateManipulatorViewSphere(color, radius, - [](const ViewportInteraction::MouseInteraction& /*mouseInteraction*/, - bool mouseOver, const AZ::Color& defaultColor) -> AZ::Color - { - const AZ::Color color[2] = + m_surfaceManipulator->SetView(CreateManipulatorViewSphere( + color, radius, + [](const ViewportInteraction::MouseInteraction& /*mouseInteraction*/, bool mouseOver, + const AZ::Color& defaultColor) -> AZ::Color { - defaultColor, - Vector3ToVector4( - BaseManipulator::s_defaultMouseOverColor.GetAsVector3(), s_surfaceManipulatorTransparency) - }; + const AZ::Color color[2] = { + defaultColor, + Vector3ToVector4(BaseManipulator::s_defaultMouseOverColor.GetAsVector3(), s_surfaceManipulatorTransparency) + }; - return color[mouseOver]; - })); + return color[mouseOver]; + })); } } @@ -327,27 +320,17 @@ namespace AzToolsFramework } } - void ConfigureTranslationManipulatorAppearance3d( - TranslationManipulators* translationManipulators) + void ConfigureTranslationManipulatorAppearance3d(TranslationManipulators* translationManipulators) { - translationManipulators->SetAxes( - AZ::Vector3::CreateAxisX(), - AZ::Vector3::CreateAxisY(), - AZ::Vector3::CreateAxisZ()); - translationManipulators->ConfigurePlanarView( - s_xAxisColor, s_yAxisColor, s_zAxisColor); - translationManipulators->ConfigureLinearView( - s_axisLength, s_xAxisColor, s_yAxisColor, s_zAxisColor); - translationManipulators->ConfigureSurfaceView( - s_surfaceManipulatorRadius, s_surfaceManipulatorColor); + translationManipulators->SetAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ()); + translationManipulators->ConfigurePlanarView(s_xAxisColor, s_yAxisColor, s_zAxisColor); + translationManipulators->ConfigureLinearView(s_axisLength, s_xAxisColor, s_yAxisColor, s_zAxisColor); + translationManipulators->ConfigureSurfaceView(s_surfaceManipulatorRadius, s_surfaceManipulatorColor); } - void ConfigureTranslationManipulatorAppearance2d( - TranslationManipulators* translationManipulators) + void ConfigureTranslationManipulatorAppearance2d(TranslationManipulators* translationManipulators) { - translationManipulators->SetAxes( - AZ::Vector3::CreateAxisX(), - AZ::Vector3::CreateAxisY()); + translationManipulators->SetAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY()); translationManipulators->ConfigurePlanarView(s_xAxisColor); translationManipulators->ConfigureLinearView(s_axisLength, s_xAxisColor, s_yAxisColor); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/TranslationManipulators.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/TranslationManipulators.h index 0e7d3108aa..5f5f1a71e3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/TranslationManipulators.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/TranslationManipulators.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -19,16 +19,15 @@ namespace AzToolsFramework { - /// TranslationManipulators is an aggregation of 3 linear manipulators, 3 planar manipulators - /// and one surface manipulator who share the same transform. - class TranslationManipulators - : public Manipulators + //! TranslationManipulators is an aggregation of 3 linear manipulators, 3 planar manipulators + //! and one surface manipulator who share the same transform. + class TranslationManipulators : public Manipulators { public: AZ_RTTI(TranslationManipulators, "{D5E49EA2-30E0-42BC-A51D-6A7F87818260}") AZ_CLASS_ALLOCATOR(TranslationManipulators, AZ::SystemAllocator, 0) - /// How many dimensions does this translation manipulator have + //! How many dimensions does this translation manipulator have. enum class Dimensions { Two, @@ -55,9 +54,7 @@ namespace AzToolsFramework void SetLocalOrientationImpl(const AZ::Quaternion& localOrientation) override; void SetNonUniformScaleImpl(const AZ::Vector3& nonUniformScale) override; - void SetAxes( - const AZ::Vector3& axis1, const AZ::Vector3& axis2, - const AZ::Vector3& axis3 = AZ::Vector3::CreateAxisZ()); + void SetAxes(const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3 = AZ::Vector3::CreateAxisZ()); void ConfigurePlanarView( const AZ::Color& plane1Color, @@ -66,11 +63,11 @@ namespace AzToolsFramework void ConfigureLinearView( float axisLength, - const AZ::Color& axis1Color, const AZ::Color& axis2Color, + const AZ::Color& axis1Color, + const AZ::Color& axis2Color, const AZ::Color& axis3Color = AZ::Color(0.0f, 0.0f, 1.0f, 0.5f)); - void ConfigureSurfaceView( - float radius, const AZ::Color& color); + void ConfigureSurfaceView(float radius, const AZ::Color& color); private: AZ_DISABLE_COPY_MOVE(TranslationManipulators) @@ -78,37 +75,43 @@ namespace AzToolsFramework // Manipulators void ProcessManipulators(const AZStd::function&) override; - const Dimensions m_dimensions; ///< How many dimensions of freedom does this manipulator have. + const Dimensions m_dimensions; //!< How many dimensions of freedom does this manipulator have. AZStd::vector> m_linearManipulators; AZStd::vector> m_planarManipulators; AZStd::shared_ptr m_surfaceManipulator = nullptr; }; - /// IndexedTranslationManipulator wraps a standard TranslationManipulators and allows it to be linked - /// to a particular index in a list of vertices/points. + //! IndexedTranslationManipulator wraps a standard TranslationManipulators and allows it to be linked + //! to a particular index in a list of vertices/points. template struct IndexedTranslationManipulator { explicit IndexedTranslationManipulator( - TranslationManipulators::Dimensions dimensions, AZ::u64 vertIndex, - const Vertex& position, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale) - : m_manipulator(dimensions, worldFromLocal, nonUniformScale) + TranslationManipulators::Dimensions dimensions, + AZ::u64 vertIndex, + const Vertex& position, + const AZ::Transform& worldFromLocal, + const AZ::Vector3& nonUniformScale) + : m_manipulator(dimensions, worldFromLocal, nonUniformScale) { m_vertices.push_back({ position, Vertex::CreateZero(), vertIndex }); } - /// Store vertex start position as manipulator event occurs, index refers to location in container. + //! Store vertex start position as manipulator event occurs, index refers to location in container. struct VertexLookup { Vertex m_start; Vertex m_offset; AZ::u64 m_index; - Vertex CurrentPosition() const { return m_start + m_offset; } + Vertex CurrentPosition() const + { + return m_start + m_offset; + } }; - /// Helper to iterate over all vertices stored by the manipulator. + //! Helper to iterate over all vertices stored by the manipulator. void Process(AZStd::function fn) { for (VertexLookup& vertex : m_vertices) @@ -117,16 +120,14 @@ namespace AzToolsFramework } } - AZStd::vector m_vertices; ///< List of vertices currently associated with this translation manipulator. + AZStd::vector m_vertices; //!< List of vertices currently associated with this translation manipulator. TranslationManipulators m_manipulator; }; - /// Function pointer to configure how a translation manipulator should look and behave (dimensions/axes/views). - using TranslationManipulatorConfiguratorFn = void(*)(TranslationManipulators*); + //! Function pointer to configure how a translation manipulator should look and behave (dimensions/axes/views). + using TranslationManipulatorConfiguratorFn = void (*)(TranslationManipulators*); - void ConfigureTranslationManipulatorAppearance3d( - TranslationManipulators* translationManipulators); - void ConfigureTranslationManipulatorAppearance2d( - TranslationManipulators* translationManipulators); + void ConfigureTranslationManipulatorAppearance3d(TranslationManipulators* translationManipulators); + void ConfigureTranslationManipulatorAppearance2d(TranslationManipulators* translationManipulators); } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/BoundInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/BoundInterface.h index 3b579e889e..e8e822ca32 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/BoundInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/BoundInterface.h @@ -1,14 +1,15 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + #pragma once #include @@ -16,30 +17,44 @@ namespace AzToolsFramework { - /** - * Provide unique type alias for AZ::u64 for manipulator, bounds and manager. - */ + //! Provide unique type alias for AZ::u64 for manipulator, bounds and manager. template class IdType { public: explicit IdType(AZ::u64 id = 0) - : m_id(id) {} - operator AZ::u64() const { return m_id; } + : m_id(id) + { + } + + operator AZ::u64() const + { + return m_id; + } + + bool operator==(IdType other) const + { + return m_id == other.m_id; + } + + bool operator!=(IdType other) const + { + return m_id != other.m_id; + } - bool operator==(IdType other) const { return m_id == other.m_id; } - bool operator!=(IdType other) const { return m_id != other.m_id; } IdType& operator++() // pre-increment { ++m_id; return *this; } + IdType operator++(int) // post-increment { IdType temp = *this; ++*this; return temp; } + private: AZ::u64 m_id; }; @@ -51,10 +66,8 @@ namespace AzToolsFramework using RegisteredBoundId = IdType; static const RegisteredBoundId InvalidBoundId = RegisteredBoundId(0); - /** - * This class serves as the base class for the actual bound shapes that various DefaultContextBoundManager-derived - * classes return from the function CreateShape. - */ + //! This class serves as the base class for the actual bound shapes that various DefaultContextBoundManager-derived + //! classes return from the function CreateShape. class BoundShapeInterface { public: @@ -63,25 +76,33 @@ namespace AzToolsFramework explicit BoundShapeInterface(const RegisteredBoundId boundId) : m_boundId(boundId) , m_valid(false) - {} + { + } virtual ~BoundShapeInterface() = default; - RegisteredBoundId GetBoundId() const { return m_boundId; } + RegisteredBoundId GetBoundId() const + { + return m_boundId; + } - /** - * @param rayOrigin The origin of the ray to test with. - * @param rayDir The direction of the ray to test with. - * @param[out] rayIntersectionDistance The distance of the intersecting point closest to the ray origin. - * @return Boolean indicating whether there is a least one intersecting point between this bound shape and the ray. - */ - virtual bool IntersectRay( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) = 0; + //! @param rayOrigin The origin of the ray to test with. + //! @param rayDir The direction of the ray to test with. + //! @param[out] rayIntersectionDistance The distance of the intersecting point closest to the ray origin. + //! @return Boolean indicating whether there is a least one intersecting point between this bound shape and the ray. + virtual bool IntersectRay(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) = 0; virtual void SetShapeData(const BoundRequestShapeBase& shapeData) = 0; - void SetValidity(bool valid) { m_valid = valid; } - bool IsValid() const { return m_valid; } + void SetValidity(bool valid) + { + m_valid = valid; + } + + bool IsValid() const + { + return m_valid; + } private: RegisteredBoundId m_boundId; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/ContextBoundAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/ContextBoundAPI.h index 4a053ea758..7127ac82ee 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/ContextBoundAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/ContextBoundAPI.h @@ -1,22 +1,22 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once #include -#include #include #include #include +#include #include #include #include @@ -27,9 +27,7 @@ namespace AzToolsFramework { namespace Picking { - /** - * An interface concrete shape types can implement to create specific BoundShapeInterfaces. - */ + //! An interface concrete shape types can implement to create specific BoundShapeInterfaces. class BoundRequestShapeBase { public: @@ -114,11 +112,9 @@ namespace AzToolsFramework float m_radius; }; - /** - * The quad shape consists of 4 points in 3D space. Please set them from \ref m_corner1 to \ref m_corner4 - * in either clock-wise winding or counter clock-wise winding. In another word, \ref m_corner1 and - * \ref corner_2 cannot be diagonal corners. - */ + //! The quad shape consists of 4 points in 3D space. Please set them from \ref m_corner1 to \ref m_corner4 + //! in either clock-wise winding or counter clock-wise winding. In another word, \ref m_corner1 and + //! \ref corner_2 cannot be diagonal corners. class BoundShapeQuad : public BoundRequestShapeBase { public: @@ -138,9 +134,7 @@ namespace AzToolsFramework AZ::Vector3 m_corner4; }; - /** - * The line segment consists of two points in 3D space defining a line the user can interact with. - */ + //! The line segment consists of two points in 3D space defining a line the user can interact with. class BoundShapeLineSegment : public BoundRequestShapeBase { public: @@ -159,10 +153,8 @@ namespace AzToolsFramework float m_width; }; - /** - * The torus shape is approximated by a cylinder whose radius is the sum of the torus's major radius - * and minor radius and height is twice the torus's minor radius. - */ + //! The torus shape is approximated by a cylinder whose radius is the sum of the torus's major radius + //! and minor radius and height is twice the torus's minor radius. class BoundShapeTorus : public BoundRequestShapeBase { public: @@ -182,10 +174,8 @@ namespace AzToolsFramework float m_minorRadius; }; - /** - * The spline is specified by a number of vertices. A piecewise approximation of the curve - * is computed by using a number of linear steps (defined by the granularity of the curve). - */ + //! The spline is specified by a number of vertices. A piecewise approximation of the curve + //! is computed by using a number of linear steps (defined by the granularity of the curve). class BoundShapeSpline : public BoundRequestShapeBase { public: @@ -204,16 +194,14 @@ namespace AzToolsFramework float m_width; }; - /** - * Ray query for intersection against bounds. - */ + //! Ray query for intersection against bounds. struct RaySelectInfo { - AZ::Vector3 m_origin; ///< Start of ray. - AZ::Vector3 m_direction; ///< Direction of ray - make sure m_direction is unit length. - AZStd::vector> m_boundIdsHit; ///< Store the id of the intersected bound - ///< and the parameter of the corresponding - ///< intersecting point. + AZ::Vector3 m_origin; //!< Start of ray. + AZ::Vector3 m_direction; //!< Direction of ray - make sure m_direction is unit length. + AZStd::vector> m_boundIdsHit; //!< Store the id of the intersected bound + //!< and the parameter of the corresponding + //!< intersecting point. }; } // namespace Picking } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBoundManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBoundManager.cpp index d838413a67..342dc4b99e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBoundManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBoundManager.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "ManipulatorBoundManager.h" @@ -16,8 +16,7 @@ namespace AzToolsFramework { namespace Picking { - RegisteredBoundId ManipulatorBoundManager::UpdateOrRegisterBound( - const BoundRequestShapeBase& shapeData, RegisteredBoundId boundId) + RegisteredBoundId ManipulatorBoundManager::UpdateOrRegisterBound(const BoundRequestShapeBase& shapeData, RegisteredBoundId boundId) { if (boundId == InvalidBoundId) { @@ -25,8 +24,7 @@ namespace AzToolsFramework boundId = m_nextBoundId++; } - if (auto result = m_boundIdToShapeMap.find(boundId); - result == m_boundIdToShapeMap.end()) + if (auto result = m_boundIdToShapeMap.find(boundId); result == m_boundIdToShapeMap.end()) { if (AZStd::shared_ptr createdShape = CreateShape(shapeData, boundId)) { @@ -49,19 +47,16 @@ namespace AzToolsFramework void ManipulatorBoundManager::UnregisterBound(const RegisteredBoundId boundId) { - if (const auto findIter = m_boundIdToShapeMap.find(boundId); - findIter != m_boundIdToShapeMap.end()) + if (const auto findIter = m_boundIdToShapeMap.find(boundId); findIter != m_boundIdToShapeMap.end()) { DeleteShape(findIter->second.get()); m_boundIdToShapeMap.erase(findIter); } } - void ManipulatorBoundManager::SetBoundValidity( - const RegisteredBoundId boundId, const bool valid) + void ManipulatorBoundManager::SetBoundValidity(const RegisteredBoundId boundId, const bool valid) { - if (auto found = m_boundIdToShapeMap.find(boundId); - found != m_boundIdToShapeMap.end()) + if (auto found = m_boundIdToShapeMap.find(boundId); found != m_boundIdToShapeMap.end()) { found->second->SetValidity(valid); } @@ -104,9 +99,9 @@ namespace AzToolsFramework const auto hitItr = AZStd::lower_bound( rayHits.begin(), rayHits.end(), BoundIdHitDistance(0, t), [](const BoundIdHitDistance& lhs, const BoundIdHitDistance& rhs) - { - return lhs.second < rhs.second; - }); + { + return lhs.second < rhs.second; + }); rayHits.insert(hitItr, AZStd::make_pair(bound->GetBoundId(), t)); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBoundManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBoundManager.h index 78e714c256..504f06bb49 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBoundManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBoundManager.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -21,10 +21,8 @@ namespace AzToolsFramework { class BoundShapeInterface; - /** - * Handle creating, destroying and storing all active manipulator - * bounds for performing raycasts/picking against. - */ + //! Handle creating, destroying and storing all active manipulator + //! bounds for performing raycasts/picking against. class ManipulatorBoundManager { public: @@ -35,21 +33,19 @@ namespace AzToolsFramework ManipulatorBoundManager& operator=(const ManipulatorBoundManager&) = delete; ~ManipulatorBoundManager() = default; - RegisteredBoundId UpdateOrRegisterBound( - const BoundRequestShapeBase& shapeData, RegisteredBoundId id); + RegisteredBoundId UpdateOrRegisterBound(const BoundRequestShapeBase& shapeData, RegisteredBoundId id); void UnregisterBound(RegisteredBoundId boundId); void SetBoundValidity(RegisteredBoundId boundId, bool valid); - void RaySelect(RaySelectInfo &rayInfo); + void RaySelect(RaySelectInfo& rayInfo); private: - AZStd::shared_ptr CreateShape( - const BoundRequestShapeBase& ptrShape, RegisteredBoundId id); + AZStd::shared_ptr CreateShape(const BoundRequestShapeBase& ptrShape, RegisteredBoundId id); void DeleteShape(const BoundShapeInterface* boundShape); AZStd::unordered_map> m_boundIdToShapeMap; - AZStd::vector> m_bounds; ///< All current manipulator bounds. + AZStd::vector> m_bounds; //!< All current manipulator bounds. - RegisteredBoundId m_nextBoundId = RegisteredBoundId(1); ///< Next bound id to use when a bound is registered. + RegisteredBoundId m_nextBoundId = RegisteredBoundId(1); //!< Next bound id to use when a bound is registered. }; } // namespace Picking } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.cpp index 8a9ebbacbc..8dca45cc9a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.cpp @@ -1,17 +1,18 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include #include +#include #include #include @@ -23,8 +24,7 @@ namespace AzToolsFramework const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, float& rayIntersectionDistance) { float vecRayIntersectionDistance; - if (AZ::Intersect::IntersectRaySphere( - rayOrigin, rayDirection, m_center, m_radius, vecRayIntersectionDistance) > 0) + if (AZ::Intersect::IntersectRaySphere(rayOrigin, rayDirection, m_center, m_radius, vecRayIntersectionDistance) > 0) { rayIntersectionDistance = vecRayIntersectionDistance; return true; @@ -45,8 +45,9 @@ namespace AzToolsFramework bool ManipulatorBoundBox::IntersectRay( const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, float& rayIntersectionDistance) { - return AZ::Intersect::IntersectRayBox(rayOrigin, rayDirection, m_center, m_axis1, m_axis2, m_axis3, - m_halfExtents.GetX(), m_halfExtents.GetY(), m_halfExtents.GetZ(), rayIntersectionDistance) > 0; + return AZ::Intersect::IntersectRayBox( + rayOrigin, rayDirection, m_center, m_axis1, m_axis2, m_axis3, m_halfExtents.GetX(), m_halfExtents.GetY(), + m_halfExtents.GetZ(), rayIntersectionDistance) > 0; } void ManipulatorBoundBox::SetShapeData(const BoundRequestShapeBase& shapeData) @@ -66,8 +67,7 @@ namespace AzToolsFramework { float t1 = std::numeric_limits::max(); float t2 = std::numeric_limits::max(); - if (AZ::Intersect::IntersectRayCappedCylinder( - rayOrigin, rayDirection, m_base, m_axis, m_height, m_radius, t1, t2) > 0) + if (AZ::Intersect::IntersectRayCappedCylinder(rayOrigin, rayDirection, m_base, m_axis, m_height, m_radius, t1, t2) > 0) { rayIntersectionDistance = AZStd::GetMin(t1, t2); return true; @@ -92,8 +92,7 @@ namespace AzToolsFramework { float t1 = std::numeric_limits::max(); float t2 = std::numeric_limits::max(); - if (AZ::Intersect::IntersectRayCone( - rayOrigin, rayDirection, m_apexPosition, m_dir, m_height, m_radius, t1, t2) > 0) + if (AZ::Intersect::IntersectRayCone(rayOrigin, rayDirection, m_apexPosition, m_dir, m_height, m_radius, t1, t2) > 0) { rayIntersectionDistance = AZStd::GetMin(t1, t2); return true; @@ -117,7 +116,7 @@ namespace AzToolsFramework const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, float& rayIntersectionDistance) { return AZ::Intersect::IntersectRayQuad( - rayOrigin, rayDirection, m_corner1, m_corner2, m_corner3, m_corner4, rayIntersectionDistance) > 0; + rayOrigin, rayDirection, m_corner1, m_corner2, m_corner3, m_corner4, rayIntersectionDistance) > 0; } void ManipulatorBoundQuad::SetShapeData(const BoundRequestShapeBase& shapeData) @@ -157,8 +156,7 @@ namespace AzToolsFramework float rayProportion, lineSegmentProportion; // note: here out param is proportion/percentage of line AZ::Intersect::ClosestSegmentSegment( - rayOrigin, rayOrigin + rayDirection * rayLength, - m_worldStart, m_worldEnd, rayProportion, lineSegmentProportion, + rayOrigin, rayOrigin + rayDirection * rayLength, m_worldStart, m_worldEnd, rayProportion, lineSegmentProportion, closestPosRay, closestPosLineSegment); float distanceFromLine = (closestPosRay - closestPosLineSegment).GetLength(); @@ -188,8 +186,7 @@ namespace AzToolsFramework { if (const AZStd::shared_ptr spline = m_spline.lock()) { - AZ::RaySplineQueryResult splineQueryResult = - AZ::IntersectSpline(m_transform, rayOrigin, rayDirection, *spline); + AZ::RaySplineQueryResult splineQueryResult = AZ::IntersectSpline(m_transform, rayOrigin, rayDirection, *spline); if (splineQueryResult.m_distanceSq <= m_width * m_width) { @@ -214,22 +211,25 @@ namespace AzToolsFramework } bool IntersectHollowCylinder( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, - const AZ::Vector3& center, const AZ::Vector3& axis, - const float minorRadius, const float majorRadius, + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, + const AZ::Vector3& center, + const AZ::Vector3& axis, + const float minorRadius, + const float majorRadius, float& rayIntersectionDistance) { - float t1 = std::numeric_limits::max(); - float t2 = std::numeric_limits::max(); + float t1 = AZStd::numeric_limits::max(); + float t2 = AZStd::numeric_limits::max(); const AZ::Vector3 base = center - axis * minorRadius; if (AZ::Intersect::IntersectRayCappedCylinder( - rayOrigin, rayDirection, base, axis, minorRadius * 2.0f, majorRadius + minorRadius, t1, t2) > 0) + rayOrigin, rayDirection, base, axis, minorRadius * 2.0f, majorRadius + minorRadius, t1, t2) > 0) { - const float thresholdSq = powf(majorRadius - minorRadius, 2.0f); + const float threshold = majorRadius - minorRadius; + const float thresholdSq = threshold * threshold; // util lambda used for distance checks at both 't' values - const auto validHolowCylinderHit = - [&rayOrigin, &rayDirection, ¢er, thresholdSq](const float t) + const auto validHolowCylinderHit = [&rayOrigin, &rayDirection, ¢er, thresholdSq](const float t) { // only return a valid intersection if the hit was // not in the 'hollow' part of the cylinder diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.h index ca9eeded11..d72e11fd0a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -27,36 +27,36 @@ namespace AzToolsFramework { namespace Picking { - class ManipulatorBoundSphere - : public BoundShapeInterface + class ManipulatorBoundSphere : public BoundShapeInterface { public: AZ_RTTI(ManipulatorBoundSphere, "{64D1B863-F574-4B31-A4F2-C9744D8567B3}", BoundShapeInterface); AZ_CLASS_ALLOCATOR(ManipulatorBoundSphere, AZ::SystemAllocator, 0); explicit ManipulatorBoundSphere(RegisteredBoundId boundId) - : BoundShapeInterface(boundId) {} + : BoundShapeInterface(boundId) + { + } - bool IntersectRay( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; + bool IntersectRay(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; void SetShapeData(const BoundRequestShapeBase& shapeData) override; AZ::Vector3 m_center = AZ::Vector3::CreateZero(); float m_radius = 0.0f; }; - class ManipulatorBoundBox - : public BoundShapeInterface + class ManipulatorBoundBox : public BoundShapeInterface { public: AZ_RTTI(ManipulatorBoundBox, "{3AD46067-933F-49B4-82E1-DBF12C7BC02E}", BoundShapeInterface); AZ_CLASS_ALLOCATOR(ManipulatorBoundBox, AZ::SystemAllocator, 0); explicit ManipulatorBoundBox(RegisteredBoundId boundId) - : BoundShapeInterface(boundId) {} + : BoundShapeInterface(boundId) + { + } - bool IntersectRay( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; + bool IntersectRay(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; void SetShapeData(const BoundRequestShapeBase& shapeData) override; AZ::Vector3 m_center = AZ::Vector3::CreateZero(); @@ -66,38 +66,38 @@ namespace AzToolsFramework AZ::Vector3 m_halfExtents = AZ::Vector3::CreateZero(); }; - class ManipulatorBoundCylinder - : public BoundShapeInterface + class ManipulatorBoundCylinder : public BoundShapeInterface { public: AZ_RTTI(ManipulatorBoundCylinder, "{D248F9E4-22E6-41A8-898D-704DF307B533}", BoundShapeInterface); AZ_CLASS_ALLOCATOR(ManipulatorBoundCylinder, AZ::SystemAllocator, 0); explicit ManipulatorBoundCylinder(RegisteredBoundId boundId) - : BoundShapeInterface(boundId) {} + : BoundShapeInterface(boundId) + { + } - bool IntersectRay( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; + bool IntersectRay(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; void SetShapeData(const BoundRequestShapeBase& shapeData) override; - AZ::Vector3 m_base = AZ::Vector3::CreateZero(); ///< The center of the circle at the base of the cylinder. + AZ::Vector3 m_base = AZ::Vector3::CreateZero(); //!< The center of the circle at the base of the cylinder. AZ::Vector3 m_axis = AZ::Vector3::CreateZero(); float m_height = 0.0f; float m_radius = 0.0f; }; - class ManipulatorBoundCone - : public BoundShapeInterface + class ManipulatorBoundCone : public BoundShapeInterface { public: AZ_RTTI(ManipulatorBoundCone, "{9430440D-DFF2-4A60-9073-507C4E9DD65D}", BoundShapeInterface); AZ_CLASS_ALLOCATOR(ManipulatorBoundCone, AZ::SystemAllocator, 0); explicit ManipulatorBoundCone(RegisteredBoundId boundId) - : BoundShapeInterface(boundId) {} + : BoundShapeInterface(boundId) + { + } - bool IntersectRay( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; + bool IntersectRay(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; void SetShapeData(const BoundRequestShapeBase& shapeData) override; AZ::Vector3 m_apexPosition = AZ::Vector3::CreateZero(); @@ -106,23 +106,21 @@ namespace AzToolsFramework float m_height = 0.0f; }; - /** - * The quad shape consists of 4 points in 3D space. Please set them from \ref m_corner1 to \ref m_corner4 - * in either clock-wise winding or counter clock-wise winding. In another word, \ref m_corner1 and - * \ref corner_2 cannot be diagonal corners. - */ - class ManipulatorBoundQuad - : public BoundShapeInterface + //! The quad shape consists of 4 points in 3D space. Please set them from \ref m_corner1 to \ref m_corner4 + //! in either clock-wise winding or counter clock-wise winding. In another word, \ref m_corner1 and + //! \ref corner_2 cannot be diagonal corners. + class ManipulatorBoundQuad : public BoundShapeInterface { public: AZ_RTTI(ManipulatorBoundQuad, "{3CDED61C-5786-4299-B5F2-5970DE4457AD}", BoundShapeInterface); AZ_CLASS_ALLOCATOR(ManipulatorBoundQuad, AZ::SystemAllocator, 0); explicit ManipulatorBoundQuad(RegisteredBoundId boundId) - : BoundShapeInterface(boundId) {} + : BoundShapeInterface(boundId) + { + } - bool IntersectRay( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; + bool IntersectRay(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; void SetShapeData(const BoundRequestShapeBase& shapeData) override; AZ::Vector3 m_corner1 = AZ::Vector3::CreateZero(); @@ -131,18 +129,18 @@ namespace AzToolsFramework AZ::Vector3 m_corner4 = AZ::Vector3::CreateZero(); }; - class ManipulatorBoundTorus - : public BoundShapeInterface + class ManipulatorBoundTorus : public BoundShapeInterface { public: AZ_RTTI(ManipulatorBoundTorus, "{46E4711C-178A-4F97-BC14-A048D096E7A1}", BoundShapeInterface); AZ_CLASS_ALLOCATOR(ManipulatorBoundTorus, AZ::SystemAllocator, 0); explicit ManipulatorBoundTorus(RegisteredBoundId boundId) - : BoundShapeInterface(boundId) {} + : BoundShapeInterface(boundId) + { + } - bool IntersectRay( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; + bool IntersectRay(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; void SetShapeData(const BoundRequestShapeBase& shapeData) override; // Approximate a torus as a thin cylinder. A ray intersects a torus when the ray and the torus' @@ -150,22 +148,22 @@ namespace AzToolsFramework // center of the torus. AZ::Vector3 m_center = AZ::Vector3::CreateZero(); AZ::Vector3 m_axis = AZ::Vector3::CreateZero(); - float m_majorRadius = 0.0f; ///< Usually denoted as "R", the distance from the center of the tube to the center of the torus. - float m_minorRadius = 0.0f; ///< Usually denoted as "r", the radius of the tube. + float m_majorRadius = 0.0f; //!< Usually denoted as "R", the distance from the center of the tube to the center of the torus. + float m_minorRadius = 0.0f; //!< Usually denoted as "r", the radius of the tube. }; - class ManipulatorBoundLineSegment - : public BoundShapeInterface + class ManipulatorBoundLineSegment : public BoundShapeInterface { public: AZ_RTTI(ManipulatorBoundLineSegment, "{66801554-1C1A-4E79-B1E7-342DFA779D53}", BoundShapeInterface); AZ_CLASS_ALLOCATOR(ManipulatorBoundLineSegment, AZ::SystemAllocator, 0); explicit ManipulatorBoundLineSegment(RegisteredBoundId boundId) - : BoundShapeInterface(boundId) {} + : BoundShapeInterface(boundId) + { + } - bool IntersectRay( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; + bool IntersectRay(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; void SetShapeData(const BoundRequestShapeBase& shapeData) override; AZ::Vector3 m_worldStart = AZ::Vector3::CreateZero(); @@ -173,18 +171,18 @@ namespace AzToolsFramework float m_width = 0.0f; }; - class ManipulatorBoundSpline - : public BoundShapeInterface + class ManipulatorBoundSpline : public BoundShapeInterface { public: AZ_RTTI(ManipulatorBoundSpline, "{777760FF-8547-45AD-876F-16BA4D9D0584}", BoundShapeInterface); AZ_CLASS_ALLOCATOR(ManipulatorBoundSpline, AZ::SystemAllocator, 0); explicit ManipulatorBoundSpline(RegisteredBoundId boundId) - : BoundShapeInterface(boundId) {} + : BoundShapeInterface(boundId) + { + } - bool IntersectRay( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; + bool IntersectRay(const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDir, float& rayIntersectionDistance) override; void SetShapeData(const BoundRequestShapeBase& shapeData) override; AZStd::weak_ptr m_spline; @@ -192,11 +190,14 @@ namespace AzToolsFramework float m_width = 0.0f; }; - /// Approximate intersection with a torus-like shape. + //! Approximate intersection with a torus-like shape. bool IntersectHollowCylinder( - const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, - const AZ::Vector3& center, const AZ::Vector3& axis, - float minorRadius, float majorRadius, + const AZ::Vector3& rayOrigin, + const AZ::Vector3& rayDirection, + const AZ::Vector3& center, + const AZ::Vector3& axis, + float minorRadius, + float majorRadius, float& rayIntersectionDistance); } // namespace Picking diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp index 7fa9724d65..8ed488b010 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "EditorContextMenu.h" @@ -16,8 +16,7 @@ namespace AzToolsFramework { - void EditorContextMenuUpdate( - EditorContextMenu& contextMenu, const ViewportInteraction::MouseInteractionEvent& mouseInteraction) + void EditorContextMenuUpdate(EditorContextMenu& contextMenu, const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -26,18 +25,17 @@ namespace AzToolsFramework mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Down) { contextMenu.m_shouldOpen = true; - contextMenu.m_clickPoint = ViewportInteraction::QPointFromScreenPoint( - mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates); + contextMenu.m_clickPoint = + ViewportInteraction::QPointFromScreenPoint(mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates); } // disable shouldOpen if right clicking an moving the mouse if (mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Move) { - const QPoint currentScreenCoords = ViewportInteraction::QPointFromScreenPoint( - mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates); + const QPoint currentScreenCoords = + ViewportInteraction::QPointFromScreenPoint(mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates); - contextMenu.m_shouldOpen = contextMenu.m_shouldOpen && - (currentScreenCoords - contextMenu.m_clickPoint).manhattanLength() < 2; + contextMenu.m_shouldOpen = contextMenu.m_shouldOpen && (currentScreenCoords - contextMenu.m_clickPoint).manhattanLength() < 2; } // do show the context menu @@ -58,9 +56,8 @@ namespace AzToolsFramework // Populate global context menu. const int contextMenuFlag = 0; EditorEvents::Bus::BroadcastReverse( - &EditorEvents::PopulateEditorGlobalContextMenu, - contextMenu.m_menu.data(), AzFramework::Vector2FromScreenPoint( - mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates), + &EditorEvents::PopulateEditorGlobalContextMenu, contextMenu.m_menu.data(), + AzFramework::Vector2FromScreenPoint(mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates), contextMenuFlag); if (!contextMenu.m_menu->isEmpty()) @@ -70,4 +67,4 @@ namespace AzToolsFramework } } } -} +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.h index ebce02fa4c..ff5bffc544 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.h @@ -1,22 +1,22 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once #include +#include #include #include -#include namespace AzToolsFramework { @@ -25,7 +25,7 @@ namespace AzToolsFramework struct MouseInteractionEvent; } - /// State of when and where the right-click context menu should appear. + //! State of when and where the right-click context menu should appear. struct EditorContextMenu final { bool m_shouldOpen = false; @@ -33,8 +33,6 @@ namespace AzToolsFramework QPointer m_menu; }; - /// Update to run for context menu (when should it appear/disappear etc). - void EditorContextMenuUpdate( - EditorContextMenu& contextMenu, - const ViewportInteraction::MouseInteractionEvent& mouseInteraction); + //! Update to run for context menu (when should it appear/disappear etc). + void EditorContextMenuUpdate(EditorContextMenu& contextMenu, const ViewportInteraction::MouseInteractionEvent& mouseInteraction); } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/VertexContainerDisplay.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/VertexContainerDisplay.cpp index cd9382c497..10016fbb13 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/VertexContainerDisplay.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/VertexContainerDisplay.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "VertexContainerDisplay.h" @@ -23,8 +23,7 @@ namespace AzToolsFramework const AZ::Vector3 DefaultVertexTextOffset = AZ::Vector3(0.0f, 0.0f, -0.1f); void DisplayVertexContainerIndex( - AzFramework::DebugDisplayRequests& debugDisplay, - const AZ::Vector3& position, const size_t index, const float textSize) + AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Vector3& position, const size_t index, const float textSize) { AZStd::string indexFormat = AZStd::string::format("[%zu]", index); debugDisplay.DrawTextLabel(position, textSize, indexFormat.c_str(), true); @@ -36,7 +35,8 @@ namespace AzToolsFramework const AZ::FixedVertices& vertices, const AZ::Transform& transform, const AZ::Vector3& nonUniformScale, - const bool selected, const float textSize, + const bool selected, + const float textSize, const AZ::Color& textColor, const AZ::Vector3& textOffset) { @@ -52,11 +52,12 @@ namespace AzToolsFramework if (vertices.GetVertex(vertIndex, vertex)) { DisplayVertexContainerIndex( - debugDisplay, transform.TransformPoint(nonUniformScale * (AdaptVertexOut(vertex) + textOffset)), vertIndex, textSize); + debugDisplay, transform.TransformPoint(nonUniformScale * (AdaptVertexOut(vertex) + textOffset)), vertIndex, + textSize); } } } - } + } // namespace VertexContainerDisplay // explicit template instantiations template void VertexContainerDisplay::DisplayVertexContainerIndices( @@ -64,7 +65,8 @@ namespace AzToolsFramework const AZ::FixedVertices& vertices, const AZ::Transform& transform, const AZ::Vector3& nonUniformScale, - bool selected, float textSize, + bool selected, + float textSize, const AZ::Color& textColor, const AZ::Vector3& textOffset); template void VertexContainerDisplay::DisplayVertexContainerIndices( @@ -72,7 +74,8 @@ namespace AzToolsFramework const AZ::FixedVertices& vertices, const AZ::Transform& transform, const AZ::Vector3& nonUniformScale, - bool selected, float textSize, + bool selected, + float textSize, const AZ::Color& textColor, const AZ::Vector3& textOffset); -} +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/VertexContainerDisplay.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/VertexContainerDisplay.h index 1717d770df..c734740d3c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/VertexContainerDisplay.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/VertexContainerDisplay.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -22,22 +22,23 @@ namespace AzFramework namespace AzToolsFramework { - /// Utility functions for rendering vertex container indices. + //! Utility functions for rendering vertex container indices. namespace VertexContainerDisplay { extern const float DefaultVertexTextSize; extern const AZ::Color DefaultVertexTextColor; extern const AZ::Vector3 DefaultVertexTextOffset; - /// Displays all vertex container indices as text at the position of each vertex when selected + //! Displays all vertex container indices as text at the position of each vertex when selected template void DisplayVertexContainerIndices( AzFramework::DebugDisplayRequests& debugDisplay, const AZ::FixedVertices& vertices, const AZ::Transform& transform, const AZ::Vector3& nonUniformScale, - bool selected, float textSize = DefaultVertexTextSize, + bool selected, + float textSize = DefaultVertexTextSize, const AZ::Color& textColor = DefaultVertexTextColor, const AZ::Vector3& textOffset = DefaultVertexTextOffset); - } + } // namespace VertexContainerDisplay } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h index 91eee18cb7..85250f2a32 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -17,8 +17,8 @@ #include #include #include -#include #include +#include #include #include @@ -31,45 +31,51 @@ namespace AzToolsFramework { namespace ViewportInteraction { - /// Result of handling mouse interaction. + //! Result of handling mouse interaction. enum class MouseInteractionResult { - Manipulator, ///< The manipulator manager handled the interaction. - Viewport, ///< The viewport handled the interaction. - None ///< The interaction was not handled. + Manipulator, //!< The manipulator manager handled the interaction. + Viewport, //!< The viewport handled the interaction. + None //!< The interaction was not handled. }; - /// Interface for handling mouse viewport events. + //! Interface for handling mouse viewport events. class MouseViewportRequests { public: - /// @cond + //! @cond virtual ~MouseViewportRequests() = default; - /// @endcond + //! @endcond - /// Implement this function to handle a particular mouse event. - virtual bool HandleMouseInteraction( - const MouseInteractionEvent& /*mouseInteraction*/) { return false; } + //! Implement this function to handle a particular mouse event. + virtual bool HandleMouseInteraction(const MouseInteractionEvent& /*mouseInteraction*/) + { + return false; + } }; - - /// Interface for internal handling mouse viewport events. + + //! Interface for internal handling mouse viewport events. class InternalMouseViewportRequests { public: - /// @cond + //! @cond virtual ~InternalMouseViewportRequests() = default; - /// @endcond + //! @endcond - /// Implement this function to have the viewport handle this mouse event. - virtual bool InternalHandleMouseViewportInteraction( - const MouseInteractionEvent& /*mouseInteraction*/) { return false; } + //! Implement this function to have the viewport handle this mouse event. + virtual bool InternalHandleMouseViewportInteraction(const MouseInteractionEvent& /*mouseInteraction*/) + { + return false; + } - /// Implement this function to have manipulators handle this mouse event. - virtual bool InternalHandleMouseManipulatorInteraction( - const MouseInteractionEvent& /*mouseInteraction*/) { return false; } + //! Implement this function to have manipulators handle this mouse event. + virtual bool InternalHandleMouseManipulatorInteraction(const MouseInteractionEvent& /*mouseInteraction*/) + { + return false; + } - /// Helper to call both viewport and manipulator handle mouse events - /// @note Manipulators always attempt to intercept the event first. + //! Helper to call both viewport and manipulator handle mouse events + //! @note Manipulators always attempt to intercept the event first. MouseInteractionResult InternalHandleAllMouseInteractions(const MouseInteractionEvent& mouseInteraction); }; @@ -90,117 +96,118 @@ namespace AzToolsFramework } } - /// Interface for viewport selection behaviors. + //! Interface for viewport selection behaviors. class ViewportDisplayNotifications { public: - /// @cond + //! @cond virtual ~ViewportDisplayNotifications() = default; - /// @endcond + //! @endcond - /// Display drawing in world space. - /// \ref DisplayViewportSelection is called from \ref EditorInteractionSystemComponent::DisplayViewport. - /// DisplayViewport exists on the \ref AzFramework::ViewportDebugDisplayEventBus and is called from \ref CRenderViewport. - /// \ref DisplayViewportSelection is called after \ref CalculateVisibleEntityDatas on the \ref EditorVisibleEntityDataCache, - /// this ensures usage of the entity cache will be up to date (do not implement \ref AzFramework::ViewportDebugDisplayEventBus - /// directly if wishing to use the \ref EditorVisibleEntityDataCache). + //! Display drawing in world space. + //! \ref DisplayViewportSelection is called from \ref EditorInteractionSystemComponent::DisplayViewport. + //! DisplayViewport exists on the \ref AzFramework::ViewportDebugDisplayEventBus and is called from \ref CRenderViewport. + //! \ref DisplayViewportSelection is called after \ref CalculateVisibleEntityDatas on the \ref EditorVisibleEntityDataCache, + //! this ensures usage of the entity cache will be up to date (do not implement \ref AzFramework::ViewportDebugDisplayEventBus + //! directly if wishing to use the \ref EditorVisibleEntityDataCache). virtual void DisplayViewportSelection( - const AzFramework::ViewportInfo& /*viewportInfo*/, - AzFramework::DebugDisplayRequests& /*debugDisplay*/) {} - /// Display drawing in screen space. - /// \ref DisplayViewportSelection2d is called after \ref DisplayViewportSelection when the viewport has been - /// configured to be orthographic in \ref CRenderViewport. All screen space drawing can be performed here. + const AzFramework::ViewportInfo& /*viewportInfo*/, AzFramework::DebugDisplayRequests& /*debugDisplay*/) + { + } + //! Display drawing in screen space. + //! \ref DisplayViewportSelection2d is called after \ref DisplayViewportSelection when the viewport has been + //! configured to be orthographic in \ref CRenderViewport. All screen space drawing can be performed here. virtual void DisplayViewportSelection2d( - const AzFramework::ViewportInfo& /*viewportInfo*/, - AzFramework::DebugDisplayRequests& /*debugDisplay*/) {} + const AzFramework::ViewportInfo& /*viewportInfo*/, AzFramework::DebugDisplayRequests& /*debugDisplay*/) + { + } }; - /// Interface for internal handling mouse viewport events and display notifications. - /// Implement this for types wishing to provide viewport functionality and - /// set it by using \ref EditorInteractionSystemViewportSelectionRequestBus. + //! Interface for internal handling mouse viewport events and display notifications. + //! Implement this for types wishing to provide viewport functionality and + //! set it by using \ref EditorInteractionSystemViewportSelectionRequestBus. class InternalViewportSelectionRequests : public ViewportDisplayNotifications , public InternalMouseViewportRequests { }; - /// Interface for handling mouse viewport events and display notifications. - /// Use this interface for composition types used by InternalViewportSelectionRequests. + //! Interface for handling mouse viewport events and display notifications. + //! Use this interface for composition types used by InternalViewportSelectionRequests. class ViewportSelectionRequests : public ViewportDisplayNotifications , public MouseViewportRequests { }; - /// The EBusTraits for ViewportInteractionRequests. - class ViewportEBusTraits - : public AZ::EBusTraits + //! The EBusTraits for ViewportInteractionRequests. + class ViewportEBusTraits : public AZ::EBusTraits { public: - using BusIdType = AzFramework::ViewportId; ///< ViewportId - used to address requests to this EBus. + using BusIdType = AzFramework::ViewportId; //!< ViewportId - used to address requests to this EBus. static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; }; - /// A ray projection, originating from a point and extending in a direction specified as a normal. + //! A ray projection, originating from a point and extending in a direction specified as a normal. struct ProjectedViewportRay { AZ::Vector3 origin; AZ::Vector3 direction; }; - /// Requests that can be made to the viewport to query and modify its state. + //! Requests that can be made to the viewport to query and modify its state. class ViewportInteractionRequests { public: - /// Return the current camera state for this viewport. + //! Return the current camera state for this viewport. virtual AzFramework::CameraState GetCameraState() = 0; - /// Return if grid snapping is enabled. + //! Return if grid snapping is enabled. virtual bool GridSnappingEnabled() = 0; - /// Return the grid snapping size. + //! Return the grid snapping size. virtual float GridSize() = 0; - /// Does the grid currently want to be displayed. + //! Does the grid currently want to be displayed. virtual bool ShowGrid() = 0; - /// Return if angle snapping is enabled. + //! Return if angle snapping is enabled. virtual bool AngleSnappingEnabled() = 0; - /// Return the angle snapping/step size. + //! Return the angle snapping/step size. virtual float AngleStep() = 0; - /// Transform a point in world space to screen space coordinates in Qt Widget space. - /// Multiply by DeviceScalingFactor to get the position in viewport pixel space. + //! Transform a point in world space to screen space coordinates in Qt Widget space. + //! Multiply by DeviceScalingFactor to get the position in viewport pixel space. virtual AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) = 0; - /// Transform a point from Qt widget screen space to world space based on the given clip space depth. - /// Depth specifies a relative camera depth to project in the range of [0.f, 1.f]. - /// Returns the world space position if successful. + //! Transform a point from Qt widget screen space to world space based on the given clip space depth. + //! Depth specifies a relative camera depth to project in the range of [0.f, 1.f]. + //! Returns the world space position if successful. virtual AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) = 0; - /// Casts a point in screen space to a ray in world space originating from the viewport camera frustum's near plane. - /// Returns a ray containing the ray's origin and a direction normal, if successful. + //! Casts a point in screen space to a ray in world space originating from the viewport camera frustum's near plane. + //! Returns a ray containing the ray's origin and a direction normal, if successful. virtual AZStd::optional ViewportScreenToWorldRay(const AzFramework::ScreenPoint& screenPosition) = 0; - /// Gets the DPI scaling factor that translates Qt widget space into viewport pixel space. + //! Gets the DPI scaling factor that translates Qt widget space into viewport pixel space. virtual float DeviceScalingFactor() = 0; protected: ~ViewportInteractionRequests() = default; }; - /// Interface to return only viewport specific settings (e.g. snapping). + //! Interface to return only viewport specific settings (e.g. snapping). class ViewportSettings { public: virtual ~ViewportSettings() = default; - /// Return if grid snapping is enabled. + //! Return if grid snapping is enabled. virtual bool GridSnappingEnabled() const = 0; - /// Return the grid snapping size. + //! Return the grid snapping size. virtual float GridSize() const = 0; - /// Does the grid currently want to be displayed. + //! Does the grid currently want to be displayed. virtual bool ShowGrid() const = 0; - /// Return if angle snapping is enabled. + //! Return if angle snapping is enabled. virtual bool AngleSnappingEnabled() const = 0; - /// Return the angle snapping/step size. + //! Return the angle snapping/step size. virtual float AngleStep() const = 0; }; - /// Type to inherit to implement ViewportInteractionRequests. + //! Type to inherit to implement ViewportInteractionRequests. using ViewportInteractionRequestBus = AZ::EBus; //! Requests to freeze the Viewport Input @@ -221,62 +228,62 @@ namespace AzToolsFramework //! Type to inherit to implement ViewportFreezeRequests. using ViewportFreezeRequestBus = AZ::EBus; - /// Viewport requests that are only guaranteed to be serviced by the Main Editor viewport. + //! Viewport requests that are only guaranteed to be serviced by the Main Editor viewport. class MainEditorViewportInteractionRequests { public: - /// Given a point in screen space, return the picked entity (if any). - /// Picked EntityId will be returned, InvalidEntityId will be returned on failure. + //! Given a point in screen space, return the picked entity (if any). + //! Picked EntityId will be returned, InvalidEntityId will be returned on failure. virtual AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) = 0; - /// Given a point in screen space, return the terrain position in world space. + //! Given a point in screen space, return the terrain position in world space. virtual AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) = 0; - /// Return the terrain height given a world position in 2d (xy plane). + //! Return the terrain height given a world position in 2d (xy plane). virtual float TerrainHeight(const AZ::Vector2& position) = 0; - /// Given the current view frustum (viewport) return all visible entities. + //! Given the current view frustum (viewport) return all visible entities. virtual void FindVisibleEntities(AZStd::vector& visibleEntities) = 0; - /// Is the user holding a modifier key to move the manipulator space from local to world. + //! Is the user holding a modifier key to move the manipulator space from local to world. virtual bool ShowingWorldSpace() = 0; - /// Return the widget to use as the parent for the viewport context menu. + //! Return the widget to use as the parent for the viewport context menu. virtual QWidget* GetWidgetForViewportContextMenu() = 0; - /// Set the render context for the viewport. + //! Set the render context for the viewport. virtual void BeginWidgetContext() = 0; - /// End the render context for the viewport. - /// Return to previous context before Begin was called. + //! End the render context for the viewport. + //! Return to previous context before Begin was called. virtual void EndWidgetContext() = 0; protected: ~MainEditorViewportInteractionRequests() = default; }; - /// Type to inherit to implement MainEditorViewportInteractionRequests. + //! Type to inherit to implement MainEditorViewportInteractionRequests. using MainEditorViewportInteractionRequestBus = AZ::EBus; - /// Viewport requests for managing the viewport's cursor state. + //! Viewport requests for managing the viewport's cursor state. class ViewportMouseCursorRequests { public: - /// Begins hiding the cursor and locking it in place, to prevent the cursor from escaping the viewport window. + //! Begins hiding the cursor and locking it in place, to prevent the cursor from escaping the viewport window. virtual void BeginCursorCapture() = 0; - /// Restores the cursor and ends locking it in place, allowing it to be moved freely. + //! Restores the cursor and ends locking it in place, allowing it to be moved freely. virtual void EndCursorCapture() = 0; - /// Gets the most recent recorded cursor position in the viewport in screen space coordinates. + //! Gets the most recent recorded cursor position in the viewport in screen space coordinates. virtual AzFramework::ScreenPoint ViewportCursorScreenPosition() = 0; - /// Gets the cursor position recorded prior to the most recent cursor position. - /// Note: The cursor may be captured by the viewport, in which case this may not correspond to the last result - /// from ViewportCursorScreenPosition. This method will always return the correct position to generate a mouse - /// position delta. + //! Gets the cursor position recorded prior to the most recent cursor position. + //! Note: The cursor may be captured by the viewport, in which case this may not correspond to the last result + //! from ViewportCursorScreenPosition. This method will always return the correct position to generate a mouse + //! position delta. virtual AZStd::optional PreviousViewportCursorScreenPosition() = 0; - /// Is mouse over viewport. + //! Is mouse over viewport. virtual bool IsMouseOver() const = 0; protected: ~ViewportMouseCursorRequests() = default; }; - /// Type to inherit to implement MainEditorViewportInteractionRequests. + //! Type to inherit to implement MainEditorViewportInteractionRequests. using ViewportMouseCursorRequestBus = AZ::EBus; - /// A helper to wrap Begin/EndWidgetContext. + //! A helper to wrap Begin/EndWidgetContext. class WidgetContextGuard { public: @@ -294,17 +301,16 @@ namespace AzToolsFramework } private: - int m_viewportId; ///< The viewport id the widget context is being set on. + int m_viewportId; //!< The viewport id the widget context is being set on. }; } // namespace ViewportInteraction - /// Utility function to return EntityContextId. + //! Utility function to return EntityContextId. inline AzFramework::EntityContextId GetEntityContextId() { AzFramework::EntityContextId entityContextId; - EditorEntityContextRequestBus::BroadcastResult( - entityContextId, &EditorEntityContextRequests::GetEditorEntityContextId); + EditorEntityContextRequestBus::BroadcastResult(entityContextId, &EditorEntityContextRequests::GetEditorEntityContextId); return entityContextId; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp index 8d26054562..99808fcd56 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "ViewportTypes.h" @@ -23,26 +23,24 @@ namespace AzToolsFramework { if (auto serializeContext = azrtti_cast(context)) { - serializeContext->Class()-> - Field("KeyboardModifiers", &KeyboardModifiers::m_keyModifiers); + serializeContext->Class()->Field("KeyboardModifiers", &KeyboardModifiers::m_keyModifiers); - serializeContext->Class()-> - Field("MouseButtons", &MouseButtons::m_mouseButtons); + serializeContext->Class()->Field("MouseButtons", &MouseButtons::m_mouseButtons); - serializeContext->Class()-> - Field("CameraId", &InteractionId::m_cameraId)-> - Field("ViewportId", &InteractionId::m_viewportId); + serializeContext->Class() + ->Field("CameraId", &InteractionId::m_cameraId) + ->Field("ViewportId", &InteractionId::m_viewportId); - serializeContext->Class()-> - Field("RayOrigin", &MousePick::m_rayOrigin)-> - Field("RayDirection", &MousePick::m_rayDirection)-> - Field("ScreenCoordinates", &MousePick::m_screenCoordinates); + serializeContext->Class() + ->Field("RayOrigin", &MousePick::m_rayOrigin) + ->Field("RayDirection", &MousePick::m_rayDirection) + ->Field("ScreenCoordinates", &MousePick::m_screenCoordinates); - serializeContext->Class()-> - Field("MousePick", &MouseInteraction::m_mousePick)-> - Field("MouseButtons", &MouseInteraction::m_mouseButtons)-> - Field("InteractionId", &MouseInteraction::m_interactionId)-> - Field("KeyboardModifiers", &MouseInteraction::m_keyboardModifiers); + serializeContext->Class() + ->Field("MousePick", &MouseInteraction::m_mousePick) + ->Field("MouseButtons", &MouseInteraction::m_mouseButtons) + ->Field("InteractionId", &MouseInteraction::m_interactionId) + ->Field("KeyboardModifiers", &MouseInteraction::m_keyboardModifiers); MouseInteractionEvent::Reflect(*serializeContext); } @@ -50,10 +48,10 @@ namespace AzToolsFramework void MouseInteractionEvent::Reflect(AZ::SerializeContext& serializeContext) { - serializeContext.Class()-> - Field("MouseInteraction", &MouseInteractionEvent::m_mouseInteraction)-> - Field("MouseEvent", &MouseInteractionEvent::m_mouseEvent)-> - Field("WheelDelta", &MouseInteractionEvent::m_wheelDelta); + serializeContext.Class() + ->Field("MouseInteraction", &MouseInteractionEvent::m_mouseInteraction) + ->Field("MouseEvent", &MouseInteractionEvent::m_mouseEvent) + ->Field("WheelDelta", &MouseInteractionEvent::m_wheelDelta); } - } -} + } // namespace ViewportInteraction +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h index d59044e68f..ad045888bc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -27,57 +27,75 @@ namespace AZ namespace AzToolsFramework { - /// Viewport related types that are used when interacting with the viewport. + //! Viewport related types that are used when interacting with the viewport. namespace ViewportInteraction { - /// Flags to represent each modifier key. + //! Flags to represent each modifier key. enum class KeyboardModifier : AZ::u32 { - None = 0, ///< No keyboard modifier. - Alt = 0x01, ///< Alt keyboard modifier. - Shift = 0x02, ///< Shift keyboard modifier. - Ctrl = 0x04, ///< Ctrl keyboard modifier. - Control = Ctrl ///< Alias for Ctrl modifier. + None = 0, //!< No keyboard modifier. + Alt = 0x01, //!< Alt keyboard modifier. + Shift = 0x02, //!< Shift keyboard modifier. + Ctrl = 0x04, //!< Ctrl keyboard modifier. + Control = Ctrl //!< Alias for Ctrl modifier. }; - /// Flags to represent each mouse button. + //! Flags to represent each mouse button. enum class MouseButton : AZ::u32 { - None = 0, ///< No mouse buttons. - Left = 0x01, ///< Left mouse button. - Middle = 0x02, ///< Middle mouse button. - Right = 0x04 ///< Right mouse button. + None = 0, //!< No mouse buttons. + Left = 0x01, //!< Left mouse button. + Middle = 0x02, //!< Middle mouse button. + Right = 0x04 //!< Right mouse button. }; - /// The type of mouse event that occurred. + //! The type of mouse event that occurred. enum class MouseEvent { - Up, ///< Mouse up event, - Down, ///< Mouse down event. - DoubleClick, ///< Mouse double click event. - Wheel, ///< Mouse wheel event. - Move, ///< Mouse move event. + Up, //!< Mouse up event, + Down, //!< Mouse down event. + DoubleClick, //!< Mouse double click event. + Wheel, //!< Mouse wheel event. + Move, //!< Mouse move event. }; - /// Interface over keyboard modifier to query which key is pressed. + //! Interface over keyboard modifier to query which key is pressed. struct KeyboardModifiers { - /// @cond + //! @cond AZ_TYPE_INFO(KeyboardModifiers, "{2635F4DF-E7DC-4919-A97B-9AE35FE086D8}"); KeyboardModifiers() = default; - /// @endcond + //! @endcond - /// Explicit constructor to create a KeyboardModifier struct. - explicit KeyboardModifiers(const AZ::u32 keyModifiers) : m_keyModifiers(keyModifiers) {} + //! Explicit constructor to create a KeyboardModifier struct. + explicit KeyboardModifiers(const AZ::u32 keyModifiers) + : m_keyModifiers(keyModifiers) + { + } - /// Given the current keyboard modifiers, is the Alt key held. - bool Alt() const { return (m_keyModifiers & static_cast(KeyboardModifier::Alt)) != 0; } - /// Given the current keyboard modifiers, is the Shift key held. - bool Shift() const { return (m_keyModifiers & static_cast(KeyboardModifier::Shift)) != 0; } - /// Given the current keyboard modifiers, is the Ctrl key held. - bool Ctrl() const { return (m_keyModifiers & static_cast(KeyboardModifier::Ctrl)) != 0; } - /// Given the current keyboard modifiers, are none being held. - bool None() const { return m_keyModifiers == static_cast(KeyboardModifier::None); } + //! Given the current keyboard modifiers, is the Alt key held. + bool Alt() const + { + return (m_keyModifiers & static_cast(KeyboardModifier::Alt)) != 0; + } + + //! Given the current keyboard modifiers, is the Shift key held. + bool Shift() const + { + return (m_keyModifiers & static_cast(KeyboardModifier::Shift)) != 0; + } + + //! Given the current keyboard modifiers, is the Ctrl key held. + bool Ctrl() const + { + return (m_keyModifiers & static_cast(KeyboardModifier::Ctrl)) != 0; + } + + //! Given the current keyboard modifiers, are none being held. + bool None() const + { + return m_keyModifiers == static_cast(KeyboardModifier::None); + } bool operator==(const KeyboardModifiers& keyboardModifiers) const { @@ -89,132 +107,162 @@ namespace AzToolsFramework return m_keyModifiers != keyboardModifiers.m_keyModifiers; } - AZ::u32 m_keyModifiers = 0; ///< Raw keyboard modifier state. + AZ::u32 m_keyModifiers = 0; //!< Raw keyboard modifier state. }; - /// Interface over mouse buttons to query which button is pressed. + //! Interface over mouse buttons to query which button is pressed. struct MouseButtons { - /// @cond + //! @cond AZ_TYPE_INFO(MouseButtons, "{1D137B5D-73BF-4FD9-BECA-85E6DC3786CB}"); MouseButtons() = default; - /// @endcond + //! @endcond - /// Explicit constructor to create a MouseButton struct. - explicit MouseButtons(const AZ::u32 mouseButtons) : m_mouseButtons(mouseButtons) {} + //! Explicit constructor to create a MouseButton struct. + explicit MouseButtons(const AZ::u32 mouseButtons) + : m_mouseButtons(mouseButtons) + { + } - /// Given the current mouse state, is the left mouse button held. - bool Left() const { return (m_mouseButtons & static_cast(MouseButton::Left)) != 0; } - /// Given the current mouse state, is the middle mouse button held. - bool Middle() const { return (m_mouseButtons & static_cast(MouseButton::Middle)) != 0; } - /// Given the current mouse state, is the right mouse button held. - bool Right() const { return (m_mouseButtons & static_cast(MouseButton::Right)) != 0; } - /// Given the current mouse state, are no mouse buttons held. - bool None() const { return m_mouseButtons == static_cast(MouseButton::None); } - /// Given the current mouse state, are any mouse buttons held. - bool Any() const { return m_mouseButtons != static_cast(MouseButton::None); } + //! Given the current mouse state, is the left mouse button held. + bool Left() const + { + return (m_mouseButtons & static_cast(MouseButton::Left)) != 0; + } - AZ::u32 m_mouseButtons = 0; ///< Current mouse button state (flags). + //! Given the current mouse state, is the middle mouse button held. + bool Middle() const + { + return (m_mouseButtons & static_cast(MouseButton::Middle)) != 0; + } + + //! Given the current mouse state, is the right mouse button held. + bool Right() const + { + return (m_mouseButtons & static_cast(MouseButton::Right)) != 0; + } + + //! Given the current mouse state, are no mouse buttons held. + bool None() const + { + return m_mouseButtons == static_cast(MouseButton::None); + } + + //! Given the current mouse state, are any mouse buttons held. + bool Any() const + { + return m_mouseButtons != static_cast(MouseButton::None); + } + + AZ::u32 m_mouseButtons = 0; //!< Current mouse button state (flags). }; - /// Information relevant when interacting with a particular viewport. + //! Information relevant when interacting with a particular viewport. struct InteractionId { - /// @cond + //! @cond AZ_TYPE_INFO(InteractionId, "{35593FC2-846F-4AAD-8044-4CD84EC84F9A}"); InteractionId() = default; - /// @endcond + //! @endcond InteractionId(AZ::EntityId cameraId, int viewportId) - : m_cameraId(cameraId), m_viewportId(viewportId) {} + : m_cameraId(cameraId) + , m_viewportId(viewportId) + { + } - AZ::EntityId m_cameraId; ///< The entity id of the viewport camera. - int m_viewportId = 0; ///< The id of the viewport being interacted with. + AZ::EntityId m_cameraId; //!< The entity id of the viewport camera. + int m_viewportId = 0; //!< The id of the viewport being interacted with. }; - /// Data representing a mouse pick ray. + //! Data representing a mouse pick ray. struct MousePick { - /// @cond + //! @cond AZ_TYPE_INFO(MousePick, "{A69B9562-FC8C-4DE7-9137-0FF867B1513D}"); MousePick() = default; - /// @endcond + //! @endcond - AZ::Vector3 m_rayOrigin = AZ::Vector3::CreateZero(); ///< World space. - AZ::Vector3 m_rayDirection = AZ::Vector3::CreateZero(); ///< World space - normalized. - AzFramework::ScreenPoint m_screenCoordinates = {}; ///< Screen space. + AZ::Vector3 m_rayOrigin = AZ::Vector3::CreateZero(); //!< World space. + AZ::Vector3 m_rayDirection = AZ::Vector3::CreateZero(); //!< World space - normalized. + AzFramework::ScreenPoint m_screenCoordinates = {}; //!< Screen space. }; - /// State relating to an individual mouse interaction. + //! State relating to an individual mouse interaction. struct MouseInteraction { - /// @cond + //! @cond AZ_TYPE_INFO(MouseInteraction, "{E67357C3-DFE1-40DF-921F-9CBCFE63A68C}"); MouseInteraction() = default; - /// @endcond + //! @endcond - MousePick m_mousePick; ///< The mouse pick ray in world space and screen coordinates in screen space. - MouseButtons m_mouseButtons; ///< The current state of the mouse buttons. + MousePick m_mousePick; //!< The mouse pick ray in world space and screen coordinates in screen space. + MouseButtons m_mouseButtons; //!< The current state of the mouse buttons. InteractionId m_interactionId; /**< The EntityId of the camera this click came from - * and the id of the viewport it originated from. */ - KeyboardModifiers m_keyboardModifiers; ///< The state of the keyboard modifiers (Alt/Ctrl/Shift). + * and the id of the viewport it originated from. */ + KeyboardModifiers m_keyboardModifiers; //!< The state of the keyboard modifiers (Alt/Ctrl/Shift). }; - /// Structure to compose MouseInteraction (mouse state) and - /// MouseEvent (MouseEvent::MouseUp/MouseEvent::DownMove etc.) + //! Structure to compose MouseInteraction (mouse state) and + //! MouseEvent (MouseEvent::MouseUp/MouseEvent::DownMove etc.) struct MouseInteractionEvent { - /// @cond + //! @cond AZ_TYPE_INFO(MouseInteractionEvent, "{67FE0826-DD59-4B5B-BEFE-421E83EA7F31}"); MouseInteractionEvent() = default; - /// @endcond + //! @endcond static void Reflect(AZ::SerializeContext& context); - /// Constructor to create a default MouseInteractionEvent + //! Constructor to create a default MouseInteractionEvent MouseInteractionEvent(MouseInteraction mouseInteraction, const MouseEvent mouseEvent) : m_mouseInteraction(std::move(mouseInteraction)) - , m_mouseEvent(mouseEvent) {} + , m_mouseEvent(mouseEvent) + { + } - /// Special constructor for mouse wheel event. + //! Special constructor for mouse wheel event. MouseInteractionEvent(MouseInteraction mouseInteraction, const float wheelDelta) : m_mouseInteraction(std::move(mouseInteraction)) , m_mouseEvent(MouseEvent::Wheel) - , m_wheelDelta(wheelDelta) {} + , m_wheelDelta(wheelDelta) + { + } - MouseInteraction m_mouseInteraction; ///< Mouse state. - MouseEvent m_mouseEvent; ///< Mouse event. + MouseInteraction m_mouseInteraction; //!< Mouse state. + MouseEvent m_mouseEvent; //!< Mouse event. - /// Special friend function to return the mouse wheel delta (scroll amount) - /// if the event was of type MouseEvent::Wheel. + //! Special friend function to return the mouse wheel delta (scroll amount) + //! if the event was of type MouseEvent::Wheel. friend float MouseWheelDelta(const MouseInteractionEvent& mouseInteractionEvent); private: - float m_wheelDelta = 0.0f; ///< The amount the mouse wheel moved during a mouse wheel event. + float m_wheelDelta = 0.0f; //!< The amount the mouse wheel moved during a mouse wheel event. }; - /// Checked access to mouse wheel delta - ensure event originated from the mouse wheel. + //! Checked access to mouse wheel delta - ensure event originated from the mouse wheel. inline float MouseWheelDelta(const MouseInteractionEvent& mouseInteractionEvent) { - AZ_Assert(mouseInteractionEvent.m_mouseEvent == MouseEvent::Wheel, + AZ_Assert( + mouseInteractionEvent.m_mouseEvent == MouseEvent::Wheel, "Attempting to access mouse wheel delta when mouse interaction event was not mouse wheel"); return mouseInteractionEvent.m_wheelDelta; } - /// Return QPoint from AzFramework::ScreenPoint. + //! Return QPoint from AzFramework::ScreenPoint. inline QPoint QPointFromScreenPoint(const AzFramework::ScreenPoint& screenPoint) { - return {screenPoint.m_x, screenPoint.m_y}; + return { screenPoint.m_x, screenPoint.m_y }; } - /// Return AzFramework::ScreenPoint from QPoint. + //! Return AzFramework::ScreenPoint from QPoint. inline AzFramework::ScreenPoint ScreenPointFromQPoint(const QPoint& qpoint) { - return AzFramework::ScreenPoint{qpoint.x(), qpoint.y()}; + return AzFramework::ScreenPoint{ qpoint.x(), qpoint.y() }; } - /// Map from Qt -> Open 3D Engine buttons.>>>>>>> main + //! Map from Qt -> Open 3D Engine buttons.>>>>>>> main inline AZ::u32 TranslateMouseButtons(const Qt::MouseButtons buttons) { AZ::u32 result = 0; @@ -224,7 +272,7 @@ namespace AzToolsFramework return result; } - /// Map from Qt -> Open 3D Engine modifiers. + //! Map from Qt -> Open 3D Engine modifiers. inline AZ::u32 TranslateKeyboardModifiers(const Qt::KeyboardModifiers modifiers) { AZ::u32 result = 0; @@ -234,19 +282,19 @@ namespace AzToolsFramework return result; } - /// Interface to translate Qt modifiers to Open 3D Engine modifiers. + //! Interface to translate Qt modifiers to Open 3D Engine modifiers. inline KeyboardModifiers BuildKeyboardModifiers(const Qt::KeyboardModifiers modifiers) { return KeyboardModifiers(TranslateKeyboardModifiers(modifiers)); } - /// Interface to translate Qt buttons to Open 3D Engine buttons. + //! Interface to translate Qt buttons to Open 3D Engine buttons. inline MouseButtons BuildMouseButtons(const Qt::MouseButtons buttons) { return MouseButtons(TranslateMouseButtons(buttons)); } - /// Generate mouse buttons from single button enum. + //! Generate mouse buttons from single button enum. inline MouseButtons MouseButtonsFromButton(MouseButton button) { MouseButtons mouseButtons; @@ -254,7 +302,7 @@ namespace AzToolsFramework return mouseButtons; } - /// Reflect all viewport related types. + //! Reflect all viewport related types. void ViewportInteractionReflect(AZ::ReflectContext* context); } // namespace ViewportInteraction } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.cpp index a7f500cc5f..ed776f90ea 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "EditorDefaultSelection.h" @@ -30,8 +30,7 @@ namespace AzToolsFramework ActionOverrideRequestBus::Handler::BusConnect(GetEntityContextId()); ComponentModeFramework::ComponentModeSystemRequestBus::Handler::BusConnect(); - m_manipulatorManager = - AZStd::make_shared(AzToolsFramework::g_mainManipulatorManagerId); + m_manipulatorManager = AZStd::make_shared(AzToolsFramework::g_mainManipulatorManagerId); m_transformComponentSelection = AZStd::make_unique(entityDataCache); } @@ -75,23 +74,18 @@ namespace AzToolsFramework for (const auto& componentModeBuilder : entityAndComponentModeBuilders.m_componentModeBuilders) { m_componentModeCollection.AddComponentMode( - AZ::EntityComponentIdPair( - entityAndComponentModeBuilders.m_entityId, componentModeBuilder.m_componentId), - componentModeBuilder.m_componentType, - componentModeBuilder.m_componentModeBuilder); + AZ::EntityComponentIdPair(entityAndComponentModeBuilders.m_entityId, componentModeBuilder.m_componentId), + componentModeBuilder.m_componentType, componentModeBuilder.m_componentModeBuilder); } } void EditorDefaultSelection::TransitionToComponentMode() { // entering ComponentMode - disable all default actions in the ActionManager - EditorActionRequestBus::Broadcast( - &EditorActionRequests::DisableDefaultActions); + EditorActionRequestBus::Broadcast(&EditorActionRequests::DisableDefaultActions); // attach widget to store ComponentMode specific actions - EditorActionRequestBus::Broadcast( - &EditorActionRequests::AttachOverride, - &PhantomWidget()); + EditorActionRequestBus::Broadcast(&EditorActionRequests::AttachOverride, &PhantomWidget()); if (m_transformComponentSelection) { @@ -103,8 +97,7 @@ namespace AzToolsFramework // refresh button ui ToolsApplicationEvents::Bus::Broadcast( - &ToolsApplicationEvents::Bus::Events::InvalidatePropertyDisplay, - PropertyModificationRefreshLevel::Refresh_EntireTree); + &ToolsApplicationEvents::Bus::Events::InvalidatePropertyDisplay, PropertyModificationRefreshLevel::Refresh_EntireTree); } void EditorDefaultSelection::TransitionFromComponentMode() @@ -117,19 +110,16 @@ namespace AzToolsFramework m_transformComponentSelection->RegisterManipulator(); } - EditorActionRequestBus::Broadcast( - &EditorActionRequests::DetachOverride); + EditorActionRequestBus::Broadcast(&EditorActionRequests::DetachOverride); ClearActionOverrides(); // leaving ComponentMode - enable all default actions in ActionManager - EditorActionRequestBus::Broadcast( - &EditorActionRequests::EnableDefaultActions); + EditorActionRequestBus::Broadcast(&EditorActionRequests::EnableDefaultActions); // refresh button ui ToolsApplicationEvents::Bus::Broadcast( - &ToolsApplicationEvents::Bus::Events::InvalidatePropertyDisplay, - PropertyModificationRefreshLevel::Refresh_EntireTree); + &ToolsApplicationEvents::Bus::Events::InvalidatePropertyDisplay, PropertyModificationRefreshLevel::Refresh_EntireTree); } void EditorDefaultSelection::EndComponentMode() @@ -142,8 +132,7 @@ namespace AzToolsFramework m_componentModeCollection.Refresh(entityComponentIdPair); } - bool EditorDefaultSelection::AddedToComponentMode( - const AZ::EntityComponentIdPair& entityComponentIdPair, const AZ::Uuid& componentType) + bool EditorDefaultSelection::AddedToComponentMode(const AZ::EntityComponentIdPair& entityComponentIdPair, const AZ::Uuid& componentType) { return m_componentModeCollection.AddedToComponentMode(entityComponentIdPair, componentType); } @@ -152,10 +141,10 @@ namespace AzToolsFramework { ComponentModeFramework::ComponentModeDelegateRequestBus::EnumerateHandlers( [componentType](ComponentModeFramework::ComponentModeDelegateRequestBus::InterfaceType* componentModeMouseRequests) - { - componentModeMouseRequests->AddComponentModeOfType(componentType); - return true; - }); + { + componentModeMouseRequests->AddComponentModeOfType(componentType); + return true; + }); TransitionToComponentMode(); } @@ -238,8 +227,7 @@ namespace AzToolsFramework } } - bool EditorDefaultSelection::InternalHandleMouseViewportInteraction( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction) + bool EditorDefaultSelection::InternalHandleMouseViewportInteraction(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { bool enterComponentModeAttempted = false; const bool componentModeBefore = InComponentMode(); @@ -249,15 +237,15 @@ namespace AzToolsFramework { // enumerate all ComponentModeDelegateRequestBus and check if any triggered AddComponentModes ComponentModeFramework::ComponentModeDelegateRequestBus::EnumerateHandlers( - [&mouseInteraction, &enterComponentModeAttempted] - (ComponentModeFramework::ComponentModeDelegateRequestBus::InterfaceType* componentModeMouseRequests) - { - // detect if a double click happened on any Component in the viewport, attempting - // to move it into ComponentMode (note: this is not guaranteed to succeed as an - // incompatible multi-selection may prevent it) - enterComponentModeAttempted = componentModeMouseRequests->DetectEnterComponentModeInteraction(mouseInteraction); - return !enterComponentModeAttempted; - }); + [&mouseInteraction, &enterComponentModeAttempted]( + ComponentModeFramework::ComponentModeDelegateRequestBus::InterfaceType* componentModeMouseRequests) + { + // detect if a double click happened on any Component in the viewport, attempting + // to move it into ComponentMode (note: this is not guaranteed to succeed as an + // incompatible multi-selection may prevent it) + enterComponentModeAttempted = componentModeMouseRequests->DetectEnterComponentModeInteraction(mouseInteraction); + return !enterComponentModeAttempted; + }); // here we know ComponentMode was entered successfully and was not prohibited if (m_componentModeCollection.ModesAdded()) @@ -272,25 +260,24 @@ namespace AzToolsFramework else { ComponentModeFramework::ComponentModeRequestBus::EnumerateHandlers( - [&mouseInteraction, &handled] - (ComponentModeFramework::ComponentModeRequestBus::InterfaceType* componentModeRequest) - { - if (componentModeRequest->HandleMouseInteraction(mouseInteraction)) + [&mouseInteraction, &handled](ComponentModeFramework::ComponentModeRequestBus::InterfaceType* componentModeRequest) { - handled = true; - } + if (componentModeRequest->HandleMouseInteraction(mouseInteraction)) + { + handled = true; + } - return true; - }); + return true; + }); if (!handled) { ComponentModeFramework::ComponentModeDelegateRequestBus::EnumerateHandlers( - [&mouseInteraction] - (ComponentModeFramework::ComponentModeDelegateRequestBus::InterfaceType* componentModeDelegateRequests) - { - return !componentModeDelegateRequests->DetectLeaveComponentModeInteraction(mouseInteraction); - }); + [&mouseInteraction]( + ComponentModeFramework::ComponentModeDelegateRequestBus::InterfaceType* componentModeDelegateRequests) + { + return !componentModeDelegateRequests->DetectLeaveComponentModeInteraction(mouseInteraction); + }); } } @@ -311,8 +298,7 @@ namespace AzToolsFramework } void EditorDefaultSelection::DisplayViewportSelection( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { if (m_transformComponentSelection) { @@ -330,8 +316,7 @@ namespace AzToolsFramework } void EditorDefaultSelection::DisplayViewportSelection2d( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { if (m_transformComponentSelection) { @@ -355,11 +340,12 @@ namespace AzToolsFramework void EditorDefaultSelection::AddActionOverride(const ActionOverride& actionOverride) { // check if an action with this uri is already added - const auto actionIt = AZStd::find_if(m_actions.begin(), m_actions.end(), + const auto actionIt = AZStd::find_if( + m_actions.begin(), m_actions.end(), [actionOverride](const AZStd::shared_ptr& actionOverrideMapping) - { - return actionOverride.m_uri == actionOverrideMapping->m_uri; - }); + { + return actionOverride.m_uri == actionOverrideMapping->m_uri; + }); // if an action with the same uri is already added, store the callback for this action if (actionIt != m_actions.end()) @@ -381,44 +367,45 @@ namespace AzToolsFramework // set callbacks that should happen when this action is triggered auto index = static_cast(m_actions.size()); - QObject::connect(action.get(), &QAction::triggered, [this, index]() - { - const auto vec = m_actions; // increment ref count of shared_ptr, callback may clear actions - for (auto& callback : vec[index]->m_callbacks) + QObject::connect( + action.get(), &QAction::triggered, + [this, index]() { - callback(); - } - }); + const auto vec = m_actions; // increment ref count of shared_ptr, callback may clear actions + for (auto& callback : vec[index]->m_callbacks) + { + callback(); + } + }); - m_actions.emplace_back( - AZStd::make_shared( - actionOverride.m_uri, AZStd::vector>{ actionOverride.m_callback }, - AZStd::move(action))); + m_actions.emplace_back(AZStd::make_shared( + actionOverride.m_uri, AZStd::vector>{ actionOverride.m_callback }, AZStd::move(action))); // register action with edit menu - EditorMenuRequestBus::Broadcast( - &EditorMenuRequests::AddEditMenuAction, m_actions.back()->m_action.get()); + EditorMenuRequestBus::Broadcast(&EditorMenuRequests::AddEditMenuAction, m_actions.back()->m_action.get()); } } void EditorDefaultSelection::ClearActionOverrides() { - AZStd::for_each(m_actions.begin(), m_actions.end(), + AZStd::for_each( + m_actions.begin(), m_actions.end(), [this](const AZStd::shared_ptr& actionMapping) - { - PhantomWidget().removeAction(actionMapping->m_action.get()); - }); + { + PhantomWidget().removeAction(actionMapping->m_action.get()); + }); m_actions.clear(); } void EditorDefaultSelection::RemoveActionOverride(const AZ::Crc32 actionOverrideUri) { - const auto it = AZStd::find_if(m_actions.begin(), m_actions.end(), + const auto it = AZStd::find_if( + m_actions.begin(), m_actions.end(), [actionOverrideUri](const AZStd::shared_ptr& actionMapping) - { - return actionMapping->m_uri == actionOverrideUri; - }); + { + return actionMapping->m_uri == actionOverrideUri; + }); if (it != m_actions.end()) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.h index 414e163e2f..d2f2c2fea5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -19,7 +19,7 @@ namespace AzToolsFramework { - /// The default selection/input handler for the editor (includes handling ComponentMode). + //! The default selection/input handler for the editor (includes handling ComponentMode). class EditorDefaultSelection : public ViewportInteraction::InternalViewportSelectionRequests , private ActionOverrideRequestBus::Handler @@ -28,30 +28,26 @@ namespace AzToolsFramework public: AZ_CLASS_ALLOCATOR_DECL - /// @cond + //! @cond explicit EditorDefaultSelection(const EditorVisibleEntityDataCache* entityDataCache); EditorDefaultSelection(const EditorDefaultSelection&) = delete; EditorDefaultSelection& operator=(const EditorDefaultSelection&) = delete; virtual ~EditorDefaultSelection(); - /// @endcond + //! @endcond - /// Override the default widget used to store QActions while in ComponentMode. - /// @note This should not be necessary during normal operation and is provided - /// as a customization point to aid with testing. + //! Override the default widget used to store QActions while in ComponentMode. + //! @note This should not be necessary during normal operation and is provided + //! as a customization point to aid with testing. void SetOverridePhantomWidget(QWidget* phantomOverrideWidget); private: // ViewportInteraction::InternalMouseViewportRequests ... - bool InternalHandleMouseViewportInteraction( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; - bool InternalHandleMouseManipulatorInteraction( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; + bool InternalHandleMouseViewportInteraction(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; + bool InternalHandleMouseManipulatorInteraction(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; void DisplayViewportSelection( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; void DisplayViewportSelection2d( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; // ActionOverrideRequestBus ... void SetupActionOverrideHandler(QWidget* parent) override; @@ -65,7 +61,10 @@ namespace AzToolsFramework const AZStd::vector& entityAndComponentModeBuilders) override; void AddComponentModes(const ComponentModeFramework::EntityAndComponentModeBuilders& entityAndComponentModeBuilders) override; void EndComponentMode() override; - bool InComponentMode() override { return m_componentModeCollection.InComponentMode(); } + bool InComponentMode() override + { + return m_componentModeCollection.InComponentMode(); + } void Refresh(const AZ::EntityComponentIdPair& entityComponentIdPair) override; bool AddedToComponentMode(const AZ::EntityComponentIdPair& entityComponentIdPair, const AZ::Uuid& componentType) override; void AddSelectedComponentModesOfType(const AZ::Uuid& componentType) override; @@ -77,41 +76,43 @@ namespace AzToolsFramework bool HasMultipleComponentTypes() override; void RefreshActions() override; - /// Helpers to deal with moving in and out of ComponentMode. + //! Helpers to deal with moving in and out of ComponentMode. void TransitionToComponentMode(); void TransitionFromComponentMode(); - /// Accessor used internally to refer to the phantom widget. - /// This will either be the default widget or the override if non-null. + //! Accessor used internally to refer to the phantom widget. + //! This will either be the default widget or the override if non-null. QWidget& PhantomWidget(); - QWidget m_phantomWidget; ///< The phantom widget responsible for holding QActions while in ComponentMode. - QWidget* m_phantomOverrideWidget = nullptr; ///< It's possible to override the phantom widget in special circumstances (eg testing). - ComponentModeFramework::ComponentModeCollection m_componentModeCollection; ///< Handles all active ComponentMode types. - AZStd::unique_ptr m_transformComponentSelection = nullptr; ///< Viewport selection (responsible for - ///< manipulators and transform modifications). - const EditorVisibleEntityDataCache* m_entityDataCache = nullptr; ///< Reference to cached visible EntityData. + QWidget m_phantomWidget; //!< The phantom widget responsible for holding QActions while in ComponentMode. + QWidget* m_phantomOverrideWidget = nullptr; //!< It's possible to override the phantom widget in special circumstances (eg testing). + ComponentModeFramework::ComponentModeCollection m_componentModeCollection; //!< Handles all active ComponentMode types. + AZStd::unique_ptr m_transformComponentSelection = + nullptr; //!< Viewport selection (responsible for + //!< manipulators and transform modifications). + const EditorVisibleEntityDataCache* m_entityDataCache = nullptr; //!< Reference to cached visible EntityData. - /// Mapping between passed ActionOverride (AddActionOverride) and allocated QAction. + //! Mapping between passed ActionOverride (AddActionOverride) and allocated QAction. struct ActionOverrideMapping { ActionOverrideMapping( - const AZ::Crc32 uri, const AZStd::vector>& callbacks, - AZStd::unique_ptr action) + const AZ::Crc32 uri, const AZStd::vector>& callbacks, AZStd::unique_ptr action) : m_uri(uri) , m_callbacks(callbacks) - , m_action(AZStd::move(action)) {} + , m_action(AZStd::move(action)) + { + } - AZ::Crc32 m_uri; ///< Unique identifier for the Action. (In the form 'com.amazon.action.---"). - AZStd::vector> m_callbacks; ///< Callbacks associated with this Action (note: with multi-selections there - ///< will be a callback per Entity/Component). - AZStd::unique_ptr m_action; ///< The QAction associated with the overrideWidget for all ComponentMode actions. + AZ::Crc32 m_uri; //!< Unique identifier for the Action. (In the form 'com.amazon.action.---"). + AZStd::vector> m_callbacks; //!< Callbacks associated with this Action (note: with multi-selections + //!< there will be a callback per Entity/Component). + AZStd::unique_ptr m_action; //!< The QAction associated with the overrideWidget for all ComponentMode actions. }; - AZStd::vector> m_actions; ///< Currently bound actions (corresponding to those set - ///< on the override widget). + AZStd::vector> m_actions; //!< Currently bound actions (corresponding to those set + //!< on the override widget). - AZStd::shared_ptr m_manipulatorManager; ///< The default manipulator manager. - ViewportInteraction::MouseInteraction m_currentInteraction; ///< Current mouse interaction to be used for drawing manipulators. + AZStd::shared_ptr m_manipulatorManager; //!< The default manipulator manager. + ViewportInteraction::MouseInteraction m_currentInteraction; //!< Current mouse interaction to be used for drawing manipulators. }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp index 31da01fadc..6080f6f7ae 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "EditorHelpers.h" @@ -16,21 +16,33 @@ #include #include #include +#include #include #include #include -#include #include -#include +#include AZ_CVAR( - bool, ed_visibility_showAggregateEntitySelectionBounds, false, nullptr, AZ::ConsoleFunctorFlags::Null, + bool, + ed_visibility_showAggregateEntitySelectionBounds, + false, + nullptr, + AZ::ConsoleFunctorFlags::Null, "Display the aggregate selection bounds for a given entity (the union of all component Aabbs)"); AZ_CVAR( - bool, ed_visibility_showAggregateEntityTransformedLocalBounds, false, nullptr, AZ::ConsoleFunctorFlags::Null, + bool, + ed_visibility_showAggregateEntityTransformedLocalBounds, + false, + nullptr, + AZ::ConsoleFunctorFlags::Null, "Display the aggregate transformed local bounds for a given entity (the union of all local component Aabbs)"); AZ_CVAR( - bool, ed_visibility_showAggregateEntityWorldBounds, false, nullptr, AZ::ConsoleFunctorFlags::Null, + bool, + ed_visibility_showAggregateEntityWorldBounds, + false, + nullptr, + AZ::ConsoleFunctorFlags::Null, "Display the aggregate world bounds for a given entity (the union of all world component Aabbs)"); namespace AzToolsFramework @@ -48,8 +60,7 @@ namespace AzToolsFramework static bool HelpersVisible() { bool helpersVisible = false; - EditorRequestBus::BroadcastResult( - helpersVisible, &EditorRequests::DisplayHelpersVisible); + EditorRequestBus::BroadcastResult(helpersVisible, &EditorRequests::DisplayHelpersVisible); return helpersVisible; } @@ -59,25 +70,23 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - return s_iconMinScale + (s_iconMaxScale - s_iconMinScale) * + return s_iconMinScale + + (s_iconMaxScale - s_iconMinScale) * (1.0f - AZ::GetClamp(AZ::GetMax(0.0f, sqrtf(distSq) - s_iconCloseDist) / s_iconFarDist, 0.0f, 1.0f)); } static void DisplayComponents( - const AZ::EntityId entityId, const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) + const AZ::EntityId entityId, const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); const AZ::Entity* entity = AZ::Interface::Get()->FindEntity(entityId); AzFramework::EntityDebugDisplayEventBus::Event( - entityId, &AzFramework::EntityDebugDisplayEvents::DisplayEntityViewport, - viewportInfo, debugDisplay); + entityId, &AzFramework::EntityDebugDisplayEvents::DisplayEntityViewport, viewportInfo, debugDisplay); if (ed_visibility_showAggregateEntitySelectionBounds) { - if (const AZ::Aabb aabb = AzToolsFramework::CalculateEditorEntitySelectionBounds(entityId, viewportInfo); - aabb.IsValid()) + if (const AZ::Aabb aabb = AzToolsFramework::CalculateEditorEntitySelectionBounds(entityId, viewportInfo); aabb.IsValid()) { debugDisplay.SetColor(AZ::Colors::Orange); debugDisplay.DrawWireBox(aabb.GetMin(), aabb.GetMax()); @@ -107,8 +116,7 @@ namespace AzToolsFramework } AZ::EntityId EditorHelpers::HandleMouseInteraction( - const AzFramework::CameraState& cameraState, - const ViewportInteraction::MouseInteractionEvent& mouseInteraction) + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -127,8 +135,7 @@ namespace AzToolsFramework { const AZ::EntityId entityId = m_entityDataCache->GetVisibleEntityId(entityCacheIndex); - if ( m_entityDataCache->IsVisibleEntityLocked(entityCacheIndex) - || !m_entityDataCache->IsVisibleEntityVisible(entityCacheIndex)) + if (m_entityDataCache->IsVisibleEntityLocked(entityCacheIndex) || !m_entityDataCache->IsVisibleEntityVisible(entityCacheIndex)) { continue; } @@ -148,10 +155,8 @@ namespace AzToolsFramework const auto iconRange = static_cast(GetIconScale(distSqFromCamera) * s_iconSize * 0.5f); const auto screenCoords = mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates; - if ( screenCoords.m_x >= screenPosition.m_x - iconRange - && screenCoords.m_x <= screenPosition.m_x + iconRange - && screenCoords.m_y >= screenPosition.m_y - iconRange - && screenCoords.m_y <= screenPosition.m_y + iconRange) + if (screenCoords.m_x >= screenPosition.m_x - iconRange && screenCoords.m_x <= screenPosition.m_x + iconRange && + screenCoords.m_y >= screenPosition.m_y - iconRange && screenCoords.m_y <= screenPosition.m_y + iconRange) { entityIdUnderCursor = entityId; break; @@ -161,16 +166,13 @@ namespace AzToolsFramework using AzFramework::ViewportInfo; // check if components provide an aabb - if (const AZ::Aabb aabb = CalculateEditorEntitySelectionBounds(entityId, ViewportInfo{viewportId}); - aabb.IsValid()) + if (const AZ::Aabb aabb = CalculateEditorEntitySelectionBounds(entityId, ViewportInfo{ viewportId }); aabb.IsValid()) { // coarse grain check if (AabbIntersectMouseRay(mouseInteraction.m_mouseInteraction, aabb)) { // if success, pick against specific component - if (PickEntity( - entityId, mouseInteraction.m_mouseInteraction, - closestDistance, viewportId)) + if (PickEntity(entityId, mouseInteraction.m_mouseInteraction, closestDistance, viewportId)) { entityIdUnderCursor = entityId; } @@ -182,7 +184,8 @@ namespace AzToolsFramework } void EditorHelpers::DisplayHelpers( - const AzFramework::ViewportInfo& viewportInfo, const AzFramework::CameraState& cameraState, + const AzFramework::ViewportInfo& viewportInfo, + const AzFramework::CameraState& cameraState, AzFramework::DebugDisplayRequests& debugDisplay, const AZStd::function& showIconCheck) { @@ -202,8 +205,8 @@ namespace AzToolsFramework // notify components to display DisplayComponents(entityId, viewportInfo, debugDisplay); - if ( m_entityDataCache->IsVisibleEntityIconHidden(entityCacheIndex) - || (m_entityDataCache->IsVisibleEntitySelected(entityCacheIndex) && !showIconCheck(entityId))) + if (m_entityDataCache->IsVisibleEntityIconHidden(entityCacheIndex) || + (m_entityDataCache->IsVisibleEntitySelected(entityCacheIndex) && !showIconCheck(entityId))) { continue; } @@ -219,7 +222,8 @@ namespace AzToolsFramework const float iconSize = s_iconSize * iconScale; using ComponentEntityAccentType = Components::EditorSelectionAccentSystemComponent::ComponentEntityAccentType; - const AZ::Color iconHighlight = [this, entityCacheIndex]() { + const AZ::Color iconHighlight = [this, entityCacheIndex]() + { if (m_entityDataCache->IsVisibleEntityLocked(entityCacheIndex)) { return AZ::Color(AZ::u8(100), AZ::u8(100), AZ::u8(100), AZ::u8(255)); @@ -233,14 +237,9 @@ namespace AzToolsFramework return AZ::Color(1.0f, 1.0f, 1.0f, 1.0f); }(); - EditorViewportIconDisplay::Get()->DrawIcon({ - viewportInfo.m_viewportId, - iconTextureId, - iconHighlight, - entityPosition, - EditorViewportIconDisplayInterface::CoordinateSpace::WorldSpace, - AZ::Vector2{iconSize, iconSize} - }); + EditorViewportIconDisplay::Get()->DrawIcon({ viewportInfo.m_viewportId, iconTextureId, iconHighlight, entityPosition, + EditorViewportIconDisplayInterface::CoordinateSpace::WorldSpace, + AZ::Vector2{ iconSize, iconSize } }); } } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.h index e36203e31d..926cadee34 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -21,7 +21,7 @@ namespace AzFramework class DebugDisplayRequests; struct ViewportInfo; struct CameraState; -} +} // namespace AzFramework namespace AzToolsFramework { @@ -32,37 +32,39 @@ namespace AzToolsFramework struct MouseInteractionEvent; } - /// EditorHelpers are the visualizations that appear for entities - /// when 'Display Helpers' is toggled on inside the editor. - /// These include but are not limited to entity icons and shape visualizations. + //! EditorHelpers are the visualizations that appear for entities + //! when 'Display Helpers' is toggled on inside the editor. + //! These include but are not limited to entity icons and shape visualizations. class EditorHelpers { public: AZ_CLASS_ALLOCATOR_DECL - /// An EditorVisibleEntityDataCache must be passed to EditorHelpers to allow it to - /// efficiently read entity data without resorting to EBus calls. + //! An EditorVisibleEntityDataCache must be passed to EditorHelpers to allow it to + //! efficiently read entity data without resorting to EBus calls. explicit EditorHelpers(const EditorVisibleEntityDataCache* entityDataCache) - : m_entityDataCache(entityDataCache) {} + : m_entityDataCache(entityDataCache) + { + } EditorHelpers(const EditorHelpers&) = delete; EditorHelpers& operator=(const EditorHelpers&) = delete; ~EditorHelpers() = default; - /// Handle any mouse interaction with the EditorHelpers. - /// Used to check if a particular entity was selected. + //! Handle any mouse interaction with the EditorHelpers. + //! Used to check if a particular entity was selected. AZ::EntityId HandleMouseInteraction( - const AzFramework::CameraState& cameraState, - const ViewportInteraction::MouseInteractionEvent& mouseInteraction); + const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteractionEvent& mouseInteraction); - /// Do the drawing responsible for the EditorHelpers. - /// @param showIconCheck Provide a custom callback to filter certain entities from - /// displaying an icon under certain conditions. + //! Do the drawing responsible for the EditorHelpers. + //! @param showIconCheck Provide a custom callback to filter certain entities from + //! displaying an icon under certain conditions. void DisplayHelpers( - const AzFramework::ViewportInfo& viewportInfo, const AzFramework::CameraState& cameraState, + const AzFramework::ViewportInfo& viewportInfo, + const AzFramework::CameraState& cameraState, AzFramework::DebugDisplayRequests& debugDisplay, const AZStd::function& showIconCheck); private: - const EditorVisibleEntityDataCache* m_entityDataCache = nullptr; ///< Entity Data queried by the EditorHelpers. + const EditorVisibleEntityDataCache* m_entityDataCache = nullptr; //!< Entity Data queried by the EditorHelpers. }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.cpp index 12f10e9784..578e113aaf 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "EditorInteractionSystemComponent.h" @@ -45,8 +45,7 @@ namespace AzToolsFramework return m_interactionRequests->InternalHandleMouseManipulatorInteraction(mouseInteraction); } - void EditorInteractionSystemComponent::SetHandler( - const ViewportSelectionRequestsBuilderFn& interactionRequestsBuilder) + void EditorInteractionSystemComponent::SetHandler(const ViewportSelectionRequestsBuilderFn& interactionRequestsBuilder) { // when setting a handler, make sure we're connected to the ViewportDebugDisplayEventBus so we // can forward calls to the specific type implementing ViewportSelectionRequests @@ -57,32 +56,30 @@ namespace AzToolsFramework m_entityDataCache = AZStd::make_unique(); - m_interactionRequests.reset(); // BusConnect/Disconnect in constructor/destructor, + m_interactionRequests.reset(); // BusConnect/Disconnect in constructor/destructor, // so have to reset before assigning the new one m_interactionRequests = interactionRequestsBuilder(m_entityDataCache.get()); } void EditorInteractionSystemComponent::SetDefaultHandler() { - SetHandler([](const EditorVisibleEntityDataCache* entityDataCache) - { - return AZStd::make_unique(entityDataCache); - }); + SetHandler( + [](const EditorVisibleEntityDataCache* entityDataCache) + { + return AZStd::make_unique(entityDataCache); + }); } void EditorInteractionSystemComponent::Reflect(AZ::ReflectContext* context) { if (auto serializeContext = azrtti_cast(context)) { - serializeContext->Class() - ->Version(0) - ; + serializeContext->Class()->Version(0); } } void EditorInteractionSystemComponent::DisplayViewport( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -93,8 +90,7 @@ namespace AzToolsFramework } void EditorInteractionSystemComponent::DisplayViewport2d( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { m_interactionRequests->DisplayViewportSelection2d(viewportInfo, debugDisplay); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.h index 2205add970..8fba5c923d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -18,9 +18,9 @@ namespace AzToolsFramework { - /// System Component to wrap active input handler. - /// EditorInteractionSystemComponent is notified of viewport mouse events from RenderViewport - /// and forwards them to a concrete implementation of ViewportSelectionRequests. + //! System Component to wrap active input handler. + //! EditorInteractionSystemComponent is notified of viewport mouse events from RenderViewport + //! and forwards them to a concrete implementation of ViewportSelectionRequests. class EditorInteractionSystemComponent : public AZ::Component , private EditorInteractionSystemViewportSelectionRequestBus::Handler @@ -37,18 +37,12 @@ namespace AzToolsFramework void SetDefaultHandler() override; // EditorInteractionSystemViewportSelectionRequestBus ... - bool InternalHandleMouseViewportInteraction( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; - bool InternalHandleMouseManipulatorInteraction( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; + bool InternalHandleMouseViewportInteraction(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; + bool InternalHandleMouseManipulatorInteraction(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; // AzFramework::ViewportDebugDisplayEventBus - void DisplayViewport( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; - void DisplayViewport2d( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; + void DisplayViewport(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; + void DisplayViewport2d(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; private: // AZ::Component @@ -58,11 +52,11 @@ namespace AzToolsFramework // EditorEventsBus void NotifyCentralWidgetInitialized() override; - AZStd::unique_ptr m_entityDataCache = nullptr; ///< Visible EntityData cache to be used by concrete - ///< instantiations of ViewportSelectionRequests. + AZStd::unique_ptr m_entityDataCache = nullptr; //!< Visible EntityData cache to be used by concrete + //!< instantiations of ViewportSelectionRequests. - AZStd::unique_ptr m_interactionRequests; ///< Hold a concrete implementation of - ///< ViewportSelectionRequests to handle viewport - ///< input and drawing for the Editor. + AZStd::unique_ptr m_interactionRequests; //!< Hold a concrete implementation of + //!< ViewportSelectionRequests to handle viewport + //!< input and drawing for the Editor. }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemViewportSelectionRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemViewportSelectionRequestBus.h index 09135069d8..184fa29aa0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemViewportSelectionRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemViewportSelectionRequestBus.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -22,10 +22,9 @@ namespace AzToolsFramework { class EditorVisibleEntityDataCache; - /// Bus to handle all mouse events originating from the viewport. - /// Coordinated by the EditorInteractionSystemComponent - class EditorInteractionSystemViewportSelectionRequests - : public AZ::EBusTraits + //! Bus to handle all mouse events originating from the viewport. + //! Coordinated by the EditorInteractionSystemComponent + class EditorInteractionSystemViewportSelectionRequests : public AZ::EBusTraits { public: using BusIdType = AzFramework::EntityContextId; @@ -36,32 +35,31 @@ namespace AzToolsFramework ~EditorInteractionSystemViewportSelectionRequests() = default; }; - /// Alias for factory function to create a new type implementing the ViewportSelectionRequests interface. + //! Alias for factory function to create a new type implementing the ViewportSelectionRequests interface. using ViewportSelectionRequestsBuilderFn = AZStd::function(const EditorVisibleEntityDataCache*)>; - /// Interface for system component implementing the ViewportSelectionRequests interface. - /// This interface also includes a setter to set a custom handler also implementing - /// the ViewportSelectionRequests interface to customize editor behavior. - class EditorInteractionSystemViewportSelection - : public ViewportInteraction::InternalViewportSelectionRequests + //! Interface for system component implementing the ViewportSelectionRequests interface. + //! This interface also includes a setter to set a custom handler also implementing + //! the ViewportSelectionRequests interface to customize editor behavior. + class EditorInteractionSystemViewportSelection : public ViewportInteraction::InternalViewportSelectionRequests { public: - /// \ref SetHandler takes a factory function to create a new type implementing - /// the ViewportSelectionRequests interface. - /// It provides a handler implementing ViewportSelectionRequests to handle all - /// viewport mouse input and drawing. + //! \ref SetHandler takes a factory function to create a new type implementing + //! the ViewportSelectionRequests interface. + //! It provides a handler implementing ViewportSelectionRequests to handle all + //! viewport mouse input and drawing. virtual void SetHandler(const ViewportSelectionRequestsBuilderFn& interactionRequestsBuilder) = 0; - /// \ref SetDefaultHandler is a utility function to set the - /// default editor handler (currently \ref EditorDefaultSelection). - /// This is useful to call after setting another mode and then wishing - /// to return to normal operation of the editor. + //! \ref SetDefaultHandler is a utility function to set the + //! default editor handler (currently \ref EditorDefaultSelection). + //! This is useful to call after setting another mode and then wishing + //! to return to normal operation of the editor. virtual void SetDefaultHandler() = 0; }; - /// Type to inherit to implement EditorInteractionSystemViewportSelection. - /// @note Called by viewport events (RenderViewport) and then handled by concrete - /// implementation of InternalViewportSelectionRequests. + //! Type to inherit to implement EditorInteractionSystemViewportSelection. + //! @note Called by viewport events (RenderViewport) and then handled by concrete + //! implementation of InternalViewportSelectionRequests. using EditorInteractionSystemViewportSelectionRequestBus = AZ::EBus; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.cpp index 1be8ee927b..e026c1f9e0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.cpp @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "EditorPickEntitySelection.h" @@ -19,9 +19,8 @@ namespace AzToolsFramework { AZ_CLASS_ALLOCATOR_IMPL(EditorPickEntitySelection, AZ::SystemAllocator, 0) - EditorPickEntitySelection::EditorPickEntitySelection( - const EditorVisibleEntityDataCache* entityDataCache) - : m_editorHelpers(AZStd::make_unique(entityDataCache)) + EditorPickEntitySelection::EditorPickEntitySelection(const EditorVisibleEntityDataCache* entityDataCache) + : m_editorHelpers(AZStd::make_unique(entityDataCache)) { } @@ -29,8 +28,7 @@ namespace AzToolsFramework { if (m_hoveredEntityId.IsValid()) { - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetEntityHighlighted, m_hoveredEntityId, false); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetEntityHighlighted, m_hoveredEntityId, false); } } @@ -41,8 +39,7 @@ namespace AzToolsFramework // highlighted - hoveredEntityId is an in/out param that is updated based on the change in // entityIdUnderCursor. static void HandleAccents( - const AZ::EntityId entityIdUnderCursor, AZ::EntityId& hoveredEntityId, - const ViewportInteraction::MouseButtons mouseButtons) + const AZ::EntityId entityIdUnderCursor, AZ::EntityId& hoveredEntityId, const ViewportInteraction::MouseButtons mouseButtons) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -55,8 +52,7 @@ namespace AzToolsFramework { if (hoveredEntityId.IsValid()) { - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetEntityHighlighted, hoveredEntityId, false); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetEntityHighlighted, hoveredEntityId, false); hoveredEntityId.SetInvalid(); } @@ -68,8 +64,7 @@ namespace AzToolsFramework { if (entityIdUnderCursor.IsValid() && entityIdUnderCursor != hoveredEntityId) { - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetEntityHighlighted, entityIdUnderCursor, true); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetEntityHighlighted, entityIdUnderCursor, true); hoveredEntityId = entityIdUnderCursor; } @@ -93,8 +88,7 @@ namespace AzToolsFramework if (m_cachedEntityIdUnderCursor.IsValid()) { // if we clicked on a valid entity id, actually try to set it - EditorPickModeRequestBus::Broadcast( - &EditorPickModeRequests::PickModeSelectEntity, m_cachedEntityIdUnderCursor); + EditorPickModeRequestBus::Broadcast(&EditorPickModeRequests::PickModeSelectEntity, m_cachedEntityIdUnderCursor); } // after a click, always stop pick mode, whether we set an entity or not @@ -105,16 +99,18 @@ namespace AzToolsFramework } void EditorPickEntitySelection::DisplayViewportSelection( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { const AzFramework::CameraState cameraState = GetCameraState(viewportInfo.m_viewportId); m_editorHelpers->DisplayHelpers( - viewportInfo, cameraState, debugDisplay, [](AZ::EntityId){ return true; }); + viewportInfo, cameraState, debugDisplay, + [](AZ::EntityId) + { + return true; + }); HandleAccents( - m_cachedEntityIdUnderCursor, m_hoveredEntityId, - ViewportInteraction::BuildMouseButtons(QGuiApplication::mouseButtons())); + m_cachedEntityIdUnderCursor, m_hoveredEntityId, ViewportInteraction::BuildMouseButtons(QGuiApplication::mouseButtons())); } } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.h index 07aafe2607..2c956e1534 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -17,10 +17,9 @@ namespace AzToolsFramework { - /// Viewport interaction that will handle assigning an entity in the viewport to - /// an entity field in the entity inspector. - class EditorPickEntitySelection - : public ViewportInteraction::InternalViewportSelectionRequests + //! Viewport interaction that will handle assigning an entity in the viewport to + //! an entity field in the entity inspector. + class EditorPickEntitySelection : public ViewportInteraction::InternalViewportSelectionRequests { public: AZ_CLASS_ALLOCATOR_DECL @@ -30,15 +29,12 @@ namespace AzToolsFramework private: // ViewportInteraction::InternalViewportSelectionRequests ... - bool InternalHandleMouseViewportInteraction( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; + bool InternalHandleMouseViewportInteraction(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; void DisplayViewportSelection( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; - AZStd::unique_ptr m_editorHelpers; ///< Editor visualization of entities (icons, shapes, debug visuals etc). - - AZ::EntityId m_hoveredEntityId; ///< What EntityId is the mouse currently hovering over (if any). - AZ::EntityId m_cachedEntityIdUnderCursor; ///< Store the EntityId on each mouse move for use in Display. + AZStd::unique_ptr m_editorHelpers; //!< Editor visualization of entities (icons, shapes, debug visuals etc). + AZ::EntityId m_hoveredEntityId; //!< What EntityId is the mouse currently hovering over (if any). + AZ::EntityId m_cachedEntityIdUnderCursor; //!< Store the EntityId on each mouse move for use in Display. }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp index d0143c5517..7856c159ab 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp @@ -1,38 +1,36 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "EditorSelectionUtil.h" -#include -#include -#include #include +#include +#include +#include #include #include #include namespace AzToolsFramework { - /// Default ray length for picking in the viewport. + // default ray length for picking in the viewport static const float s_pickRayLength = 1000.0f; - AZ::Vector3 CalculateCenterOffset( - const AZ::EntityId entityId, const EditorTransformComponentSelectionRequests::Pivot pivot) + AZ::Vector3 CalculateCenterOffset(const AZ::EntityId entityId, const EditorTransformComponentSelectionRequests::Pivot pivot) { if (Centered(pivot)) { const AZ::Entity* entity = AZ::Interface::Get()->FindEntity(entityId); - if (const AZ::Aabb localBound = AzFramework::CalculateEntityLocalBoundsUnion(entity); - localBound.IsValid()) + if (const AZ::Aabb localBound = AzFramework::CalculateEntityLocalBoundsUnion(entity); localBound.IsValid()) { return localBound.GetCenter(); } @@ -41,76 +39,71 @@ namespace AzToolsFramework return AZ::Vector3::CreateZero(); } - float CalculateScreenToWorldMultiplier( - const AZ::Vector3& worldPosition, const AzFramework::CameraState& cameraState) + float CalculateScreenToWorldMultiplier(const AZ::Vector3& worldPosition, const AzFramework::CameraState& cameraState) { const float apparentDistance = 10.0f; // compute the distance from the camera, projected onto the camera's forward direction // note: this keeps the scale value the same when positions are at the edge of the screen - const float projectedCameraDistance = - std::abs((cameraState.m_position - worldPosition).Dot(cameraState.m_forward)); + const float projectedCameraDistance = std::abs((cameraState.m_position - worldPosition).Dot(cameraState.m_forward)); // author sizes of bounds/manipulators as they would appear // in perspective 10 meters from the camera. return AZ::GetMax(projectedCameraDistance, cameraState.m_nearClip) / apparentDistance; } - AzFramework::ScreenPoint GetScreenPosition(const int viewportId, const AZ::Vector3& worldTranslation) + AzFramework::ScreenPoint GetScreenPosition(const int viewportId, const AZ::Vector3& worldTranslation) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); auto screenPosition = AzFramework::ScreenPoint(0, 0); ViewportInteraction::ViewportInteractionRequestBus::EventResult( - screenPosition, viewportId, - &ViewportInteraction::ViewportInteractionRequestBus::Events::ViewportWorldToScreen, + screenPosition, viewportId, &ViewportInteraction::ViewportInteractionRequestBus::Events::ViewportWorldToScreen, worldTranslation); return screenPosition; } - bool AabbIntersectMouseRay( - const ViewportInteraction::MouseInteraction& mouseInteraction, const AZ::Aabb& aabb) + bool AabbIntersectMouseRay(const ViewportInteraction::MouseInteraction& mouseInteraction, const AZ::Aabb& aabb) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - const AZ::Vector3 rayScaledDir = - mouseInteraction.m_mousePick.m_rayDirection * s_pickRayLength; + const AZ::Vector3 rayScaledDir = mouseInteraction.m_mousePick.m_rayDirection * s_pickRayLength; AZ::Vector3 startNormal; float t, end; return AZ::Intersect::IntersectRayAABB( - mouseInteraction.m_mousePick.m_rayOrigin, rayScaledDir, - rayScaledDir.GetReciprocal(), aabb, t, end, startNormal) > 0; + mouseInteraction.m_mousePick.m_rayOrigin, rayScaledDir, rayScaledDir.GetReciprocal(), aabb, t, end, startNormal) > 0; } bool PickEntity( - const AZ::EntityId entityId, const ViewportInteraction::MouseInteraction& mouseInteraction, - float& closestDistance, const int viewportId) + const AZ::EntityId entityId, + const ViewportInteraction::MouseInteraction& mouseInteraction, + float& closestDistance, + const int viewportId) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); bool entityPicked = false; EditorComponentSelectionRequestsBus::EnumerateHandlersId( - entityId, [mouseInteraction, &entityPicked, &closestDistance, viewportId] - (EditorComponentSelectionRequests* handler) -> bool - { - if (handler->SupportsEditorRayIntersect()) + entityId, + [mouseInteraction, &entityPicked, &closestDistance, viewportId](EditorComponentSelectionRequests* handler) -> bool { - float distance = std::numeric_limits::max(); - const bool intersection = handler->EditorSelectionIntersectRayViewport( - { viewportId }, mouseInteraction.m_mousePick.m_rayOrigin, - mouseInteraction.m_mousePick.m_rayDirection, distance); - - if (intersection && distance < closestDistance) + if (handler->SupportsEditorRayIntersect()) { - entityPicked = true; - closestDistance = distance; - } - } + float distance = std::numeric_limits::max(); + const bool intersection = handler->EditorSelectionIntersectRayViewport( + { viewportId }, mouseInteraction.m_mousePick.m_rayOrigin, mouseInteraction.m_mousePick.m_rayDirection, distance); - return true; // iterate over all handlers - }); + if (intersection && distance < closestDistance) + { + entityPicked = true; + closestDistance = distance; + } + } + + return true; // iterate over all handlers + }); return entityPicked; } @@ -119,9 +112,8 @@ namespace AzToolsFramework { AzFramework::CameraState cameraState; ViewportInteraction::ViewportInteractionRequestBus::EventResult( - cameraState, viewportId, - &ViewportInteraction::ViewportInteractionRequestBus::Events::GetCameraState); - + cameraState, viewportId, &ViewportInteraction::ViewportInteractionRequestBus::Events::GetCameraState); + return cameraState; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h index e904277078..a7c6368d65 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -30,56 +30,53 @@ namespace AzFramework namespace AzToolsFramework { - /// Is the pivot at the center of the object (middle of extents) or at the - /// exported authored object root position. + //! Is the pivot at the center of the object (middle of extents) or at the + //! exported authored object root position. inline bool Centered(const EditorTransformComponentSelectionRequests::Pivot pivot) { return pivot == EditorTransformComponentSelectionRequests::Pivot::Center; } - /// Return offset from object pivot to center if center is true, otherwise Vector3::Zero. + //! Return offset from object pivot to center if center is true, otherwise Vector3::Zero. AZ::Vector3 CalculateCenterOffset(AZ::EntityId entityId, EditorTransformComponentSelectionRequests::Pivot pivot); - /// Calculate scale factor based on distance from camera - float CalculateScreenToWorldMultiplier( - const AZ::Vector3& worldPosition, const AzFramework::CameraState& cameraState); + //! Calculate scale factor based on distance from camera + float CalculateScreenToWorldMultiplier(const AZ::Vector3& worldPosition, const AzFramework::CameraState& cameraState); - /// Map from world space to screen space. - AzFramework::ScreenPoint GetScreenPosition(int viewportId, const AZ::Vector3& worldTranslation); + //! Map from world space to screen space. + AzFramework::ScreenPoint GetScreenPosition(int viewportId, const AZ::Vector3& worldTranslation); - /// Given a mouse interaction, determine if the pick ray from its position - /// in screen space intersected an aabb in world space. - bool AabbIntersectMouseRay( - const ViewportInteraction::MouseInteraction& mouseInteraction, const AZ::Aabb& aabb); + //! Given a mouse interaction, determine if the pick ray from its position + //! in screen space intersected an aabb in world space. + bool AabbIntersectMouseRay(const ViewportInteraction::MouseInteraction& mouseInteraction, const AZ::Aabb& aabb); - /// Return if a mouse interaction (pick ray) did intersect the tested EntityId. + //! Return if a mouse interaction (pick ray) did intersect the tested EntityId. bool PickEntity( - AZ::EntityId entityId, const ViewportInteraction::MouseInteraction& mouseInteraction, - float& closestDistance, int viewportId); + AZ::EntityId entityId, const ViewportInteraction::MouseInteraction& mouseInteraction, float& closestDistance, int viewportId); - /// Wrapper for EBus call to return the CameraState for a given viewport. + //! Wrapper for EBus call to return the CameraState for a given viewport. AzFramework::CameraState GetCameraState(int viewportId); - /// Wrapper for EBus call to return the DPI scaling for a given viewport. - float GetScreenDisplayScaling(const int viewportId); + //! Wrapper for EBus call to return the DPI scaling for a given viewport. + float GetScreenDisplayScaling(int viewportId); - /// A utility to return the center of several points. - /// Take several positions and store the min and max of each in - /// turn - when all points have been added return the center/midpoint. + //! A utility to return the center of several points. + //! Take several positions and store the min and max of each in + //! turn - when all points have been added return the center/midpoint. class MidpointCalculator { public: - /// Default constructed with min and max initialized to opposites. + //! Default constructed with min and max initialized to opposites. MidpointCalculator() = default; - /// Call this for all positions you want to be considered. + //! Call this for all positions you want to be considered. void AddPosition(const AZ::Vector3& position) { m_minPosition = position.GetMin(m_minPosition); m_maxPosition = position.GetMax(m_maxPosition); } - /// Once all positions have been added, call this to return the midpoint. + //! Once all positions have been added, call this to return the midpoint. AZ::Vector3 CalculateMidpoint() const { return m_minPosition + (m_maxPosition - m_minPosition) * 0.5f; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index 5603c1a0f7..fee0267766 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -1,29 +1,30 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "EditorTransformComponentSelection.h" -#include #include #include #include #include +#include #include #include #include #include -#include +#include #include #include +#include #include #include #include @@ -36,7 +37,6 @@ #include #include #include -#include #include #include #include @@ -47,20 +47,40 @@ namespace AzToolsFramework AZ_CLASS_ALLOCATOR_IMPL(EditorTransformComponentSelection, AZ::SystemAllocator, 0) AZ_CVAR( - float, cl_viewportGizmoAxisLineWidth, 4.0f, nullptr, AZ::ConsoleFunctorFlags::Null, + float, + cl_viewportGizmoAxisLineWidth, + 4.0f, + nullptr, + AZ::ConsoleFunctorFlags::Null, "The width of the line for the viewport axis gizmo"); AZ_CVAR( - float, cl_viewportGizmoAxisLineLength, 0.7f, nullptr, AZ::ConsoleFunctorFlags::Null, + float, + cl_viewportGizmoAxisLineLength, + 0.7f, + nullptr, + AZ::ConsoleFunctorFlags::Null, "The length of the line for the viewport axis gizmo"); AZ_CVAR( - float, cl_viewportGizmoAxisLabelOffset, 1.15f, nullptr, AZ::ConsoleFunctorFlags::Null, + float, + cl_viewportGizmoAxisLabelOffset, + 1.15f, + nullptr, + AZ::ConsoleFunctorFlags::Null, "The offset of the label for the viewport axis gizmo"); AZ_CVAR( - float, cl_viewportGizmoAxisLabelSize, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, + float, + cl_viewportGizmoAxisLabelSize, + 1.0f, + nullptr, + AZ::ConsoleFunctorFlags::Null, "The size of each label for the viewport axis gizmo"); AZ_CVAR( - AZ::Vector2, cl_viewportGizmoAxisScreenPosition, AZ::Vector2(0.045f, 0.9f), nullptr, - AZ::ConsoleFunctorFlags::Null, "The screen position of the gizmo in normalized (0-1) ndc space"); + AZ::Vector2, + cl_viewportGizmoAxisScreenPosition, + AZ::Vector2(0.045f, 0.9f), + nullptr, + AZ::ConsoleFunctorFlags::Null, + "The screen position of the gizmo in normalized (0-1) ndc space"); // strings related to new viewport interaction model (EditorTransformComponentSelection) static const char* const s_togglePivotTitleRightClick = "Toggle pivot"; @@ -125,7 +145,8 @@ namespace AzToolsFramework static const int s_defaultViewportId = 0; - static const float s_pivotSize = 0.075f; ///< The size of the pivot (box) to render when selected. + static const float s_pivotSize = 0.075f; // the size of the pivot (box) to render when selected + // data passed to manipulators when processing mouse interactions // m_entityIds should be sorted based on the entity hierarchy // (see SortEntitiesByLocationInHierarchy and BuildSortedEntityIdVectorFromEntityIdContainer) @@ -146,8 +167,7 @@ namespace AzToolsFramework bool OptionalFrame::HasTransformOverride() const { - return m_translationOverride.has_value() - || m_orientationOverride.has_value(); + return m_translationOverride.has_value() || m_orientationOverride.has_value(); } bool OptionalFrame::HasEntityOverride() const @@ -226,7 +246,7 @@ namespace AzToolsFramework return mouseInteraction.m_mouseInteraction.m_mouseButtons.Middle() && mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Down && (mouseInteraction.m_mouseInteraction.m_keyboardModifiers.Alt() || - mouseInteraction.m_mouseInteraction.m_keyboardModifiers.Ctrl()); + mouseInteraction.m_mouseInteraction.m_keyboardModifiers.Ctrl()); } static bool ManipulatorDitto(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) @@ -263,8 +283,7 @@ namespace AzToolsFramework } } - static EditorTransformComponentSelectionRequests::Pivot TogglePivotMode( - const EditorTransformComponentSelectionRequests::Pivot pivot) + static EditorTransformComponentSelectionRequests::Pivot TogglePivotMode(const EditorTransformComponentSelectionRequests::Pivot pivot) { switch (pivot) { @@ -282,8 +301,7 @@ namespace AzToolsFramework template static AZStd::vector EntityIdVectorFromContainer(const EntityIdContainer& entityIdContainer) { - static_assert(AZStd::is_same::value, - "Container type is not an EntityId"); + static_assert(AZStd::is_same::value, "Container type is not an EntityId"); AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); return AZStd::vector(entityIdContainer.begin(), entityIdContainer.end()); @@ -293,8 +311,7 @@ namespace AzToolsFramework template static AZStd::vector EntityIdVectorFromMap(const EntityIdMap& entityIdMap) { - static_assert(AZStd::is_same::value, - "Container key type is not an EntityId"); + static_assert(AZStd::is_same::value, "Container key type is not an EntityId"); AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -318,10 +335,15 @@ namespace AzToolsFramework template static void BoxSelectAddRemoveToEntitySelection( - const AZStd::optional& boxSelect, const AzFramework::ScreenPoint& screenPosition, const AZ::EntityId visibleEntityId, - const EntityIdContainer& incomingEntityIds, EntityIdContainer& outgoingEntityIds, + const AZStd::optional& boxSelect, + const AzFramework::ScreenPoint& screenPosition, + const AZ::EntityId visibleEntityId, + const EntityIdContainer& incomingEntityIds, + EntityIdContainer& outgoingEntityIds, EditorTransformComponentSelection& entityTransformComponentSelection, - EntitySelectFuncType selectFunc1, EntitySelectFuncType selectFunc2, Compare outgoingCheck) + EntitySelectFuncType selectFunc1, + EntitySelectFuncType selectFunc2, + Compare outgoingCheck) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -349,10 +371,14 @@ namespace AzToolsFramework template static void EntityBoxSelectUpdateGeneral( - const AZStd::optional& boxSelect, EditorTransformComponentSelection& editorTransformComponentSelection, - const EntityIdContainer& activeSelectedEntityIds, EntityIdContainer& selectedEntityIdsBeforeBoxSelect, - EntityIdContainer& potentialSelectedEntityIds, EntityIdContainer& potentialDeselectedEntityIds, - const EditorVisibleEntityDataCache& entityDataCache, const int viewportId, + const AZStd::optional& boxSelect, + EditorTransformComponentSelection& editorTransformComponentSelection, + const EntityIdContainer& activeSelectedEntityIds, + EntityIdContainer& selectedEntityIdsBeforeBoxSelect, + EntityIdContainer& potentialSelectedEntityIds, + EntityIdContainer& potentialDeselectedEntityIds, + const EditorVisibleEntityDataCache& entityDataCache, + const int viewportId, const ViewportInteraction::KeyboardModifiers currentKeyboardModifiers, const ViewportInteraction::KeyboardModifiers& previousKeyboardModifiers) { @@ -382,8 +408,7 @@ namespace AzToolsFramework for (size_t entityCacheIndex = 0; entityCacheIndex < entityDataCache.VisibleEntityDataCount(); ++entityCacheIndex) { - if ( entityDataCache.IsVisibleEntityLocked(entityCacheIndex) - || !entityDataCache.IsVisibleEntityVisible(entityCacheIndex)) + if (entityDataCache.IsVisibleEntityLocked(entityCacheIndex) || !entityDataCache.IsVisibleEntityVisible(entityCacheIndex)) { continue; } @@ -396,10 +421,8 @@ namespace AzToolsFramework if (currentKeyboardModifiers.Ctrl()) { BoxSelectAddRemoveToEntitySelection( - boxSelect, screenPosition, entityId, - selectedEntityIdsBeforeBoxSelect, potentialDeselectedEntityIds, - editorTransformComponentSelection, - &EditorTransformComponentSelection::RemoveEntityFromSelection, + boxSelect, screenPosition, entityId, selectedEntityIdsBeforeBoxSelect, potentialDeselectedEntityIds, + editorTransformComponentSelection, &EditorTransformComponentSelection::RemoveEntityFromSelection, &EditorTransformComponentSelection::AddEntityToSelection, [](const typename EntityIdContainer::const_iterator entityId, const EntityIdContainer& entityIds) { @@ -409,10 +432,8 @@ namespace AzToolsFramework else { BoxSelectAddRemoveToEntitySelection( - boxSelect, screenPosition, entityId, - activeSelectedEntityIds, potentialSelectedEntityIds, - editorTransformComponentSelection, - &EditorTransformComponentSelection::AddEntityToSelection, + boxSelect, screenPosition, entityId, activeSelectedEntityIds, potentialSelectedEntityIds, + editorTransformComponentSelection, &EditorTransformComponentSelection::AddEntityToSelection, &EditorTransformComponentSelection::RemoveEntityFromSelection, [](const typename EntityIdContainer::const_iterator entityId, const EntityIdContainer& entityIds) { @@ -429,62 +450,53 @@ namespace AzToolsFramework for (auto& entityIdLookup : entityIdManipulators.m_lookups) { - entityIdLookup.second.m_initial = - AZ::Transform::CreateTranslation(GetWorldTranslation(entityIdLookup.first)); + entityIdLookup.second.m_initial = AZ::Transform::CreateTranslation(GetWorldTranslation(entityIdLookup.first)); } } static void DestroyCluster(const ViewportUi::ClusterId clusterId) { ViewportUi::ViewportUiRequestBus::Event( - ViewportUi::DefaultViewportId, - &ViewportUi::ViewportUiRequestBus::Events::RemoveCluster, - clusterId); + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::RemoveCluster, clusterId); } static void SetViewportUiClusterVisible(const ViewportUi::ClusterId clusterId, const bool visible) { ViewportUi::ViewportUiRequestBus::Event( - ViewportUi::DefaultViewportId, - &ViewportUi::ViewportUiRequestBus::Events::SetClusterVisible, - clusterId, visible); + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::SetClusterVisible, clusterId, visible); } static void SetViewportUiClusterActiveButton(const ViewportUi::ClusterId clusterId, const ViewportUi::ButtonId buttonId) { ViewportUi::ViewportUiRequestBus::Event( - ViewportUi::DefaultViewportId, - &ViewportUi::ViewportUiRequestBus::Events::SetClusterActiveButton, - clusterId, buttonId); + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::SetClusterActiveButton, clusterId, buttonId); } static ViewportUi::ButtonId RegisterClusterButton(const ViewportUi::ClusterId clusterId, const char* iconName) { ViewportUi::ButtonId buttonId; ViewportUi::ViewportUiRequestBus::EventResult( - buttonId, ViewportUi::DefaultViewportId, - &ViewportUi::ViewportUiRequestBus::Events::CreateClusterButton, - clusterId, AZStd::string::format(":/stylesheet/img/UI20/toolbar/%s.svg", iconName)); + buttonId, ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateClusterButton, clusterId, + AZStd::string::format(":/stylesheet/img/UI20/toolbar/%s.svg", iconName)); return buttonId; } // return either center or entity pivot - static AZ::Vector3 CalculatePivotTranslation( - const AZ::EntityId entityId, const EditorTransformComponentSelectionRequests::Pivot pivot) + static AZ::Vector3 CalculatePivotTranslation(const AZ::EntityId entityId, const EditorTransformComponentSelectionRequests::Pivot pivot) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); return worldFromLocal.TransformPoint(CalculateCenterOffset(entityId, pivot)); } void EditorTransformComponentSelection::UpdateSpaceCluster(const ReferenceFrame referenceFrame) { - auto buttonIdFromFrameFn = [this](const ReferenceFrame referenceFrame) { + auto buttonIdFromFrameFn = [this](const ReferenceFrame referenceFrame) + { switch (referenceFrame) { case ReferenceFrame::Local: @@ -498,14 +510,13 @@ namespace AzToolsFramework }; ViewportUi::ViewportUiRequestBus::Event( - ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::SetClusterActiveButton, m_spaceCluster.m_spaceClusterId, - buttonIdFromFrameFn(referenceFrame)); + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::SetClusterActiveButton, + m_spaceCluster.m_spaceClusterId, buttonIdFromFrameFn(referenceFrame)); } namespace ETCS { - PivotOrientationResult CalculatePivotOrientation( - const AZ::EntityId entityId, const ReferenceFrame referenceFrame) + PivotOrientationResult CalculatePivotOrientation(const AZ::EntityId entityId, const ReferenceFrame referenceFrame) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -515,21 +526,17 @@ namespace AzToolsFramework switch (referenceFrame) { case ReferenceFrame::Local: - AZ::TransformBus::EventResult( - result.m_worldOrientation, entityId, - &AZ::TransformBus::Events::GetWorldRotationQuaternion); + AZ::TransformBus::EventResult(result.m_worldOrientation, entityId, &AZ::TransformBus::Events::GetWorldRotationQuaternion); break; case ReferenceFrame::Parent: { AZ::EntityId parentId; - AZ::TransformBus::EventResult( - parentId, entityId, &AZ::TransformBus::Events::GetParentId); + AZ::TransformBus::EventResult(parentId, entityId, &AZ::TransformBus::Events::GetParentId); if (parentId.IsValid()) { AZ::TransformBus::EventResult( - result.m_worldOrientation, parentId, - &AZ::TransformBus::Events::GetWorldRotationQuaternion); + result.m_worldOrientation, parentId, &AZ::TransformBus::Events::GetWorldRotationQuaternion); result.m_parentId = parentId; } @@ -559,8 +566,7 @@ namespace AzToolsFramework { // check if this entity has a parent AZ::EntityId parentId; - AZ::TransformBus::EventResult( - parentId, entityIdLookupIt->first, &AZ::TransformBus::Events::GetParentId); + AZ::TransformBus::EventResult(parentId, entityIdLookupIt->first, &AZ::TransformBus::Events::GetParentId); // if no parent, space will be world, terminate if (!parentId.IsValid()) @@ -575,9 +581,7 @@ namespace AzToolsFramework if (!commonParentId.IsValid()) { commonParentId = parentId; - AZ::TransformBus::EventResult( - result.m_worldOrientation, parentId, - &AZ::TransformBus::Events::GetWorldRotationQuaternion); + AZ::TransformBus::EventResult(result.m_worldOrientation, parentId, &AZ::TransformBus::Events::GetWorldRotationQuaternion); } // if we know we still have a parent in common @@ -602,8 +606,7 @@ namespace AzToolsFramework static AZ::Vector3 CalculatePivotTranslationForEntityIds( const EntityIdMap& entityIdMap, const EditorTransformComponentSelectionRequests::Pivot pivot) { - static_assert(AZStd::is_same::value, - "Container key type is not an EntityId"); + static_assert(AZStd::is_same::value, "Container key type is not an EntityId"); AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -628,11 +631,9 @@ namespace AzToolsFramework namespace ETCS { template - PivotOrientationResult CalculatePivotOrientationForEntityIds( - const EntityIdMap& entityIdMap, const ReferenceFrame referenceFrame) + PivotOrientationResult CalculatePivotOrientationForEntityIds(const EntityIdMap& entityIdMap, const ReferenceFrame referenceFrame) { - static_assert(AZStd::is_same::value, - "Container key type is not an EntityId"); + static_assert(AZStd::is_same::value, "Container key type is not an EntityId"); AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -660,12 +661,11 @@ namespace AzToolsFramework { template PivotOrientationResult CalculateSelectionPivotOrientation( - const EntityIdMap& entityIdMap, const OptionalFrame& pivotOverrideFrame, - const ReferenceFrame referenceFrame) + const EntityIdMap& entityIdMap, const OptionalFrame& pivotOverrideFrame, const ReferenceFrame referenceFrame) { - static_assert(AZStd::is_same::value, - "Container key type is not an EntityId"); - static_assert(AZStd::is_same::value, + static_assert(AZStd::is_same::value, "Container key type is not an EntityId"); + static_assert( + AZStd::is_same::value, "Container value type is not an EntityIdManipulators::Lookup"); AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -728,20 +728,16 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - return pivotOverrideFrame.m_translationOverride.value_or( - CalculatePivotTranslationForEntityIds(entityIdMap, pivot)); + return pivotOverrideFrame.m_translationOverride.value_or(CalculatePivotTranslationForEntityIds(entityIdMap, pivot)); } template static AZ::Quaternion RecalculateAverageManipulatorOrientation( - const EntityIdMap& entityIdMap, - const OptionalFrame& pivotOverrideFrame, - const ReferenceFrame referenceFrame) + const EntityIdMap& entityIdMap, const OptionalFrame& pivotOverrideFrame, const ReferenceFrame referenceFrame) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - return ETCS::CalculateSelectionPivotOrientation( - entityIdMap, pivotOverrideFrame, referenceFrame).m_worldOrientation; + return ETCS::CalculateSelectionPivotOrientation(entityIdMap, pivotOverrideFrame, referenceFrame).m_worldOrientation; } template @@ -756,15 +752,12 @@ namespace AzToolsFramework // return final transform, if we have an override for translation use that, otherwise // use centered translation of selection return AZ::Transform::CreateFromQuaternionAndTranslation( - RecalculateAverageManipulatorOrientation( - entityIdMap, pivotOverrideFrame, referenceFrame), - RecalculateAverageManipulatorTranslation( - entityIdMap, pivotOverrideFrame, pivot)); + RecalculateAverageManipulatorOrientation(entityIdMap, pivotOverrideFrame, referenceFrame), + RecalculateAverageManipulatorTranslation(entityIdMap, pivotOverrideFrame, pivot)); } template - static void BuildSortedEntityIdVectorFromEntityIdMap( - const EntityIdMap& entityIds, EntityIdList& sortedEntityIdsOut) + static void BuildSortedEntityIdVectorFromEntityIdMap(const EntityIdMap& entityIds, EntityIdList& sortedEntityIdsOut) { sortedEntityIdsOut = EntityIdVectorFromMap(entityIds); SortEntitiesByLocationInHierarchy(sortedEntityIdsOut); @@ -777,8 +770,7 @@ namespace AzToolsFramework for (auto& entityIdLookup : entityManipulators.m_lookups) { AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - worldFromLocal, entityIdLookup.first, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityIdLookup.first, &AZ::TransformBus::Events::GetWorldTM); entityIdLookup.second.m_initial = worldFromLocal; } @@ -804,11 +796,13 @@ namespace AzToolsFramework template static void UpdateTranslationManipulator( - const Action& action, const EntityIdContainer& entityIdContainer, + const Action& action, + const EntityIdContainer& entityIdContainer, EntityIdManipulators& entityIdManipulators, OptionalFrame& pivotOverrideFrame, ViewportInteraction::KeyboardModifiers& prevModifiers, - bool& transformChangedInternally, const AZStd::optional spaceLock) + bool& transformChangedInternally, + const AZStd::optional spaceLock) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -817,8 +811,7 @@ namespace AzToolsFramework if (action.m_modifiers.Ctrl()) { // moving with ctrl - setting override - pivotOverrideFrame.m_translationOverride = - entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); + pivotOverrideFrame.m_translationOverride = entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); InitializeTranslationLookup(entityIdManipulators); } else @@ -827,8 +820,7 @@ namespace AzToolsFramework // note: used for parent and world depending on the current reference frame const auto pivotOrientation = - ETCS::CalculateSelectionPivotOrientation( - entityIdManipulators.m_lookups, pivotOverrideFrame, referenceFrame); + ETCS::CalculateSelectionPivotOrientation(entityIdManipulators.m_lookups, pivotOverrideFrame, referenceFrame); // note: must use sorted entityIds based on hierarchy order when updating transforms for (AZ::EntityId entityId : entityIdContainer) @@ -847,46 +839,37 @@ namespace AzToolsFramework { // move in each entities local space at once AZ::Quaternion worldOrientation = AZ::Quaternion::CreateIdentity(); - AZ::TransformBus::EventResult( - worldOrientation, entityId, &AZ::TransformBus::Events::GetWorldRotationQuaternion); + AZ::TransformBus::EventResult(worldOrientation, entityId, &AZ::TransformBus::Events::GetWorldRotationQuaternion); - const AZ::Transform space = - entityIdManipulators.m_manipulators->GetLocalTransform().GetInverse() * - AZ::Transform::CreateFromQuaternionAndTranslation( - worldOrientation, worldTranslation); + const AZ::Transform space = entityIdManipulators.m_manipulators->GetLocalTransform().GetInverse() * + AZ::Transform::CreateFromQuaternionAndTranslation(worldOrientation, worldTranslation); - const AZ::Vector3 localOffset = space.TransformVector(action.LocalPositionOffset()); + const AZ::Vector3 localOffset = space.TransformVector(action.LocalPositionOffset()); if (action.m_modifiers != prevModifiers) { - entityItLookupIt->second.m_initial = - AZ::Transform::CreateTranslation(worldTranslation - localOffset); + entityItLookupIt->second.m_initial = AZ::Transform::CreateTranslation(worldTranslation - localOffset); } ETCS::SetEntityWorldTranslation( - entityId, entityItLookupIt->second.m_initial.GetTranslation() + localOffset, - transformChangedInternally); + entityId, entityItLookupIt->second.m_initial.GetTranslation() + localOffset, transformChangedInternally); } break; case ReferenceFrame::Parent: case ReferenceFrame::World: { - AZ::Quaternion offsetRotation = - pivotOrientation.m_worldOrientation * - QuaternionFromTransformNoScaling( - entityIdManipulators.m_manipulators->GetLocalTransform().GetInverse()); + AZ::Quaternion offsetRotation = pivotOrientation.m_worldOrientation * + QuaternionFromTransformNoScaling(entityIdManipulators.m_manipulators->GetLocalTransform().GetInverse()); const AZ::Vector3 localOffset = offsetRotation.TransformVector(action.LocalPositionOffset()); if (action.m_modifiers != prevModifiers) { - entityItLookupIt->second.m_initial = - AZ::Transform::CreateTranslation(worldTranslation - localOffset); + entityItLookupIt->second.m_initial = AZ::Transform::CreateTranslation(worldTranslation - localOffset); } ETCS::SetEntityWorldTranslation( - entityId, entityItLookupIt->second.m_initial.GetTranslation() + localOffset, - transformChangedInternally); + entityId, entityItLookupIt->second.m_initial.GetTranslation() + localOffset, transformChangedInternally); } break; } @@ -895,8 +878,7 @@ namespace AzToolsFramework // if transform pivot override has been set, make sure to update it when we move it if (pivotOverrideFrame.m_translationOverride) { - pivotOverrideFrame.m_translationOverride = - entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); + pivotOverrideFrame.m_translationOverride = entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); } } @@ -904,8 +886,10 @@ namespace AzToolsFramework } static void HandleAccents( - const bool hasSelectedEntities, const AZ::EntityId entityIdUnderCursor, - const bool ctrlHeld, AZ::EntityId& hoveredEntityId, + const bool hasSelectedEntities, + const AZ::EntityId entityIdUnderCursor, + const bool ctrlHeld, + AZ::EntityId& hoveredEntityId, const ViewportInteraction::MouseButtons mouseButtons, const bool usingBoxSelect) { @@ -914,13 +898,11 @@ namespace AzToolsFramework const bool invalidMouseButtonHeld = mouseButtons.Middle() || mouseButtons.Right(); if ((hoveredEntityId.IsValid() && hoveredEntityId != entityIdUnderCursor) || - (hasSelectedEntities && !ctrlHeld && hoveredEntityId.IsValid()) || - invalidMouseButtonHeld) + (hasSelectedEntities && !ctrlHeld && hoveredEntityId.IsValid()) || invalidMouseButtonHeld) { if (hoveredEntityId.IsValid()) { - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetEntityHighlighted, hoveredEntityId, false); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetEntityHighlighted, hoveredEntityId, false); hoveredEntityId.SetInvalid(); } @@ -930,8 +912,7 @@ namespace AzToolsFramework { if (entityIdUnderCursor.IsValid()) { - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetEntityHighlighted, entityIdUnderCursor, true); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetEntityHighlighted, entityIdUnderCursor, true); hoveredEntityId = entityIdUnderCursor; } @@ -946,15 +927,13 @@ namespace AzToolsFramework // get unsnapped terrain position (world space) AZ::Vector3 worldSurfacePosition; ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( - worldSurfacePosition, viewportId, - &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, + worldSurfacePosition, viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, mouseInteraction.m_mousePick.m_screenCoordinates); // convert to local space - snap if enabled const GridSnapParameters gridSnapParams = GridSnapSettings(viewportId); const AZ::Vector3 finalSurfacePosition = gridSnapParams.m_gridSnap - ? CalculateSnappedTerrainPosition( - worldSurfacePosition, AZ::Transform::CreateIdentity(), viewportId, gridSnapParams.m_gridSize) + ? CalculateSnappedTerrainPosition(worldSurfacePosition, AZ::Transform::CreateIdentity(), viewportId, gridSnapParams.m_gridSize) : worldSurfacePosition; return finalSurfacePosition; @@ -981,10 +960,9 @@ namespace AzToolsFramework for (AZ::EntityId entityId : entityIds) { AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); - transformsBefore.insert({ entityId, worldFromLocal }); + transformsBefore.insert({ entityId, worldFromLocal }); } return transformsBefore; @@ -992,8 +970,7 @@ namespace AzToolsFramework // ask the visible entity data cache if the entity is selectable in the viewport // (useful in the context of drawing when we only care about entities we can see) - static bool SelectableInVisibleViewportCache( - const EditorVisibleEntityDataCache& entityDataCache, const AZ::EntityId entityId) + static bool SelectableInVisibleViewportCache(const EditorVisibleEntityDataCache& entityDataCache, const AZ::EntityId entityId) { if (auto entityIndex = entityDataCache.GetVisibleEntityIndexFromId(entityId)) { @@ -1021,15 +998,12 @@ namespace AzToolsFramework // is handled internally - this call is often required after an action/shortcut of some kind static void RefreshUiAfterChange(const EntityIdList& entitiyIds) { - EditorTransformChangeNotificationBus::Broadcast( - &EditorTransformChangeNotifications::OnEntityTransformChanged, entitiyIds); + EditorTransformChangeNotificationBus::Broadcast(&EditorTransformChangeNotifications::OnEntityTransformChanged, entitiyIds); - ToolsApplicationNotificationBus::Broadcast( - &ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); + ToolsApplicationNotificationBus::Broadcast(&ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); } - EditorTransformComponentSelection::EditorTransformComponentSelection( - const EditorVisibleEntityDataCache* entityDataCache) + EditorTransformComponentSelection::EditorTransformComponentSelection(const EditorVisibleEntityDataCache* entityDataCache) : m_entityDataCache(entityDataCache) { const AzFramework::EntityContextId entityContextId = GetEntityContextId(); @@ -1090,101 +1064,96 @@ namespace AzToolsFramework m_boxSelect.InstallLeftMouseDown( [this, entityBoxSelectData](const ViewportInteraction::MouseInteractionEvent& /*mouseInteraction*/) - { - // begin selection undo/redo command - entityBoxSelectData->m_boxSelectSelectionCommand = - AZStd::make_unique(EntityIdList(), s_entityBoxSelectUndoRedoDesc); - // grab currently selected entities - entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect = m_selectedEntityIds; - }); + { + // begin selection undo/redo command + entityBoxSelectData->m_boxSelectSelectionCommand = + AZStd::make_unique(EntityIdList(), s_entityBoxSelectUndoRedoDesc); + // grab currently selected entities + entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect = m_selectedEntityIds; + }); m_boxSelect.InstallMouseMove( [this, entityBoxSelectData](const ViewportInteraction::MouseInteractionEvent& mouseInteraction) - { - EntityBoxSelectUpdateGeneral( - m_boxSelect.BoxRegion(), *this, m_selectedEntityIds, entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect, - entityBoxSelectData->m_potentialSelectedEntityIds, entityBoxSelectData->m_potentialDeselectedEntityIds, - *m_entityDataCache, mouseInteraction.m_mouseInteraction.m_interactionId.m_viewportId, - mouseInteraction.m_mouseInteraction.m_keyboardModifiers, - m_boxSelect.PreviousModifiers()); - }); + { + EntityBoxSelectUpdateGeneral( + m_boxSelect.BoxRegion(), *this, m_selectedEntityIds, entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect, + entityBoxSelectData->m_potentialSelectedEntityIds, entityBoxSelectData->m_potentialDeselectedEntityIds, + *m_entityDataCache, mouseInteraction.m_mouseInteraction.m_interactionId.m_viewportId, + mouseInteraction.m_mouseInteraction.m_keyboardModifiers, m_boxSelect.PreviousModifiers()); + }); m_boxSelect.InstallLeftMouseUp( [this, entityBoxSelectData]() - { - entityBoxSelectData->m_boxSelectSelectionCommand->UpdateSelection(EntityIdVectorFromContainer(m_selectedEntityIds)); - - // if we know a change in selection has occurred, record the undo step - if ( !entityBoxSelectData->m_potentialDeselectedEntityIds.empty() - || !entityBoxSelectData->m_potentialSelectedEntityIds.empty()) { - ScopedUndoBatch undoBatch(s_entityBoxSelectUndoRedoDesc); + entityBoxSelectData->m_boxSelectSelectionCommand->UpdateSelection(EntityIdVectorFromContainer(m_selectedEntityIds)); - // restore manipulator overrides when undoing - if (m_entityIdManipulators.m_manipulators && m_selectedEntityIds.empty()) + // if we know a change in selection has occurred, record the undo step + if (!entityBoxSelectData->m_potentialDeselectedEntityIds.empty() || + !entityBoxSelectData->m_potentialSelectedEntityIds.empty()) { - CreateEntityManipulatorDeselectCommand(undoBatch); + ScopedUndoBatch undoBatch(s_entityBoxSelectUndoRedoDesc); + + // restore manipulator overrides when undoing + if (m_entityIdManipulators.m_manipulators && m_selectedEntityIds.empty()) + { + CreateEntityManipulatorDeselectCommand(undoBatch); + } + + entityBoxSelectData->m_boxSelectSelectionCommand->SetParent(undoBatch.GetUndoBatch()); + entityBoxSelectData->m_boxSelectSelectionCommand.release(); + + SetSelectedEntities(EntityIdVectorFromContainer(m_selectedEntityIds)); + // note: manipulators will be updated in AfterEntitySelectionChanged + + // clear pivot override when selection is empty + if (m_selectedEntityIds.empty()) + { + m_pivotOverrideFrame.Reset(); + } + } + else + { + entityBoxSelectData->m_boxSelectSelectionCommand.reset(); } - entityBoxSelectData->m_boxSelectSelectionCommand->SetParent(undoBatch.GetUndoBatch()); - entityBoxSelectData->m_boxSelectSelectionCommand.release(); - - SetSelectedEntities(EntityIdVectorFromContainer(m_selectedEntityIds)); - // note: manipulators will be updated in AfterEntitySelectionChanged - - // clear pivot override when selection is empty - if (m_selectedEntityIds.empty()) - { - m_pivotOverrideFrame.Reset(); - } - } - else - { - entityBoxSelectData->m_boxSelectSelectionCommand.reset(); - } - - entityBoxSelectData->m_potentialSelectedEntityIds.clear(); - entityBoxSelectData->m_potentialDeselectedEntityIds.clear(); - entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect.clear(); - }); + entityBoxSelectData->m_potentialSelectedEntityIds.clear(); + entityBoxSelectData->m_potentialDeselectedEntityIds.clear(); + entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect.clear(); + }); m_boxSelect.InstallDisplayScene( - [this, entityBoxSelectData] - (const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) - { - const auto modifiers = ViewportInteraction::KeyboardModifiers( - ViewportInteraction::TranslateKeyboardModifiers(QApplication::queryKeyboardModifiers())); - - if (m_boxSelect.PreviousModifiers() != modifiers) + [this, entityBoxSelectData](const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - EntityBoxSelectUpdateGeneral( - m_boxSelect.BoxRegion(), *this, m_selectedEntityIds, - entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect, - entityBoxSelectData->m_potentialSelectedEntityIds, - entityBoxSelectData->m_potentialDeselectedEntityIds, - *m_entityDataCache, viewportInfo.m_viewportId, modifiers, - m_boxSelect.PreviousModifiers()); - } + const auto modifiers = ViewportInteraction::KeyboardModifiers( + ViewportInteraction::TranslateKeyboardModifiers(QApplication::queryKeyboardModifiers())); - debugDisplay.DepthTestOff(); - debugDisplay.SetColor(s_selectedEntityAabbColor); - - for (AZ::EntityId entityId : entityBoxSelectData->m_potentialSelectedEntityIds) - { - const auto entityIdIt = entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect.find(entityId); - - // don't show box when re-adding from previous selection - if (entityIdIt != entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect.end()) + if (m_boxSelect.PreviousModifiers() != modifiers) { - continue; + EntityBoxSelectUpdateGeneral( + m_boxSelect.BoxRegion(), *this, m_selectedEntityIds, entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect, + entityBoxSelectData->m_potentialSelectedEntityIds, entityBoxSelectData->m_potentialDeselectedEntityIds, + *m_entityDataCache, viewportInfo.m_viewportId, modifiers, m_boxSelect.PreviousModifiers()); } - const AZ::Aabb bound = CalculateEditorEntitySelectionBounds(entityId, viewportInfo); - debugDisplay.DrawSolidBox(bound.GetMin(), bound.GetMax()); - } + debugDisplay.DepthTestOff(); + debugDisplay.SetColor(s_selectedEntityAabbColor); - debugDisplay.DepthTestOn(); - }); + for (AZ::EntityId entityId : entityBoxSelectData->m_potentialSelectedEntityIds) + { + const auto entityIdIt = entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect.find(entityId); + + // don't show box when re-adding from previous selection + if (entityIdIt != entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect.end()) + { + continue; + } + + const AZ::Aabb bound = CalculateEditorEntitySelectionBounds(entityId, viewportInfo); + debugDisplay.DrawSolidBox(bound.GetMin(), bound.GetMax()); + } + + debugDisplay.DepthTestOn(); + }); } EntityManipulatorCommand::State EditorTransformComponentSelection::CreateManipulatorCommandStateFromSelf() const @@ -1197,14 +1166,9 @@ namespace AzToolsFramework return {}; } - return { - BuildPivotOverride( - m_pivotOverrideFrame.HasTranslationOverride(), - m_pivotOverrideFrame.HasOrientationOverride()), - TransformNormalizedScale( - m_entityIdManipulators.m_manipulators->GetLocalTransform()), - m_pivotOverrideFrame.m_pickedEntityIdOverride - }; + return { BuildPivotOverride(m_pivotOverrideFrame.HasTranslationOverride(), m_pivotOverrideFrame.HasOrientationOverride()), + TransformNormalizedScale(m_entityIdManipulators.m_manipulators->GetLocalTransform()), + m_pivotOverrideFrame.m_pickedEntityIdOverride }; } void EditorTransformComponentSelection::BeginRecordManipulatorCommand() @@ -1214,14 +1178,13 @@ namespace AzToolsFramework // we must have an existing parent undo batch active when beginning to record // a manipulator command UndoSystem::URSequencePoint* currentUndoOperation = nullptr; - ToolsApplicationRequests::Bus::BroadcastResult( - currentUndoOperation, &ToolsApplicationRequests::GetCurrentUndoBatch); + ToolsApplicationRequests::Bus::BroadcastResult(currentUndoOperation, &ToolsApplicationRequests::GetCurrentUndoBatch); if (currentUndoOperation) { // check here if translation or orientation override are set - m_manipulatorMoveCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + m_manipulatorMoveCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); } } @@ -1234,10 +1197,11 @@ namespace AzToolsFramework m_manipulatorMoveCommand->SetManipulatorAfter(CreateManipulatorCommandStateFromSelf()); UndoSystem::URSequencePoint* currentUndoOperation = nullptr; - ToolsApplicationRequests::Bus::BroadcastResult( - currentUndoOperation, &ToolsApplicationRequests::GetCurrentUndoBatch); + ToolsApplicationRequests::Bus::BroadcastResult(currentUndoOperation, &ToolsApplicationRequests::GetCurrentUndoBatch); - AZ_Assert(currentUndoOperation, "The only way we should have reached this block is if " + AZ_Assert( + currentUndoOperation, + "The only way we should have reached this block is if " "m_manipulatorMoveCommand was created by calling BeginRecordManipulatorMouseMoveCommand. " "If we've reached this point and currentUndoOperation is null, something bad has happened " "in the undo system"); @@ -1254,18 +1218,15 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - AZStd::unique_ptr translationManipulators = - AZStd::make_unique( - TranslationManipulators::Dimensions::Three, - AZ::Transform::CreateIdentity(), AZ::Vector3::CreateOne()); + AZStd::unique_ptr translationManipulators = AZStd::make_unique( + TranslationManipulators::Dimensions::Three, AZ::Transform::CreateIdentity(), AZ::Vector3::CreateOne()); InitializeManipulators(*translationManipulators); ConfigureTranslationManipulatorAppearance3d(&*translationManipulators); translationManipulators->SetLocalTransform( - RecalculateAverageManipulatorTransform( - m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode, m_referenceFrame)); + RecalculateAverageManipulatorTransform(m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode, m_referenceFrame)); // lambdas capture shared_ptr by value to increment ref count auto manipulatorEntityIds = AZStd::make_shared(); @@ -1277,95 +1238,92 @@ namespace AzToolsFramework // linear translationManipulators->InstallLinearManipulatorMouseDownCallback( [this, manipulatorEntityIds]([[maybe_unused]] const LinearManipulator::Action& action) mutable - { - // important to sort entityIds based on hierarchy order when updating transforms - BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds->m_entityIds); + { + // important to sort entityIds based on hierarchy order when updating transforms + BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds->m_entityIds); - InitializeTranslationLookup(m_entityIdManipulators); + InitializeTranslationLookup(m_entityIdManipulators); - m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); - m_axisPreview.m_orientation = QuaternionFromTransformNoScaling( - m_entityIdManipulators.m_manipulators->GetLocalTransform()); + m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); + m_axisPreview.m_orientation = QuaternionFromTransformNoScaling(m_entityIdManipulators.m_manipulators->GetLocalTransform()); - // [ref 1.] - BeginRecordManipulatorCommand(); - }); + // [ref 1.] + BeginRecordManipulatorCommand(); + }); ViewportInteraction::KeyboardModifiers prevModifiers{}; translationManipulators->InstallLinearManipulatorMouseMoveCallback( [this, prevModifiers, manipulatorEntityIds](const LinearManipulator::Action& action) mutable -> void - { - UpdateTranslationManipulator( - action, manipulatorEntityIds->m_entityIds, m_entityIdManipulators, m_pivotOverrideFrame, prevModifiers, + { + UpdateTranslationManipulator( + action, manipulatorEntityIds->m_entityIds, m_entityIdManipulators, m_pivotOverrideFrame, prevModifiers, m_transformChangedInternally, m_spaceCluster.m_spaceLock); - }); + }); translationManipulators->InstallLinearManipulatorMouseUpCallback( [this]([[maybe_unused]] const LinearManipulator::Action& action) mutable - { - EndRecordManipulatorCommand(); - }); + { + EndRecordManipulatorCommand(); + }); // planar translationManipulators->InstallPlanarManipulatorMouseDownCallback( [this, manipulatorEntityIds]([[maybe_unused]] const PlanarManipulator::Action& action) - { - // important to sort entityIds based on hierarchy order when updating transforms - BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds->m_entityIds); + { + // important to sort entityIds based on hierarchy order when updating transforms + BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds->m_entityIds); - InitializeTranslationLookup(m_entityIdManipulators); + InitializeTranslationLookup(m_entityIdManipulators); - m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); - m_axisPreview.m_orientation = QuaternionFromTransformNoScaling( - m_entityIdManipulators.m_manipulators->GetLocalTransform()); + m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); + m_axisPreview.m_orientation = QuaternionFromTransformNoScaling(m_entityIdManipulators.m_manipulators->GetLocalTransform()); - // [ref 1.] - BeginRecordManipulatorCommand(); - }); + // [ref 1.] + BeginRecordManipulatorCommand(); + }); translationManipulators->InstallPlanarManipulatorMouseMoveCallback( [this, prevModifiers, manipulatorEntityIds](const PlanarManipulator::Action& action) mutable -> void - { - UpdateTranslationManipulator( - action, manipulatorEntityIds->m_entityIds, m_entityIdManipulators, m_pivotOverrideFrame, prevModifiers, + { + UpdateTranslationManipulator( + action, manipulatorEntityIds->m_entityIds, m_entityIdManipulators, m_pivotOverrideFrame, prevModifiers, m_transformChangedInternally, m_spaceCluster.m_spaceLock); - }); + }); translationManipulators->InstallPlanarManipulatorMouseUpCallback( [this, manipulatorEntityIds](const PlanarManipulator::Action& /*action*/) - { - EndRecordManipulatorCommand(); - }); + { + EndRecordManipulatorCommand(); + }); // surface translationManipulators->InstallSurfaceManipulatorMouseDownCallback( [this, manipulatorEntityIds]([[maybe_unused]] const SurfaceManipulator::Action& action) - { - BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds->m_entityIds); + { + BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds->m_entityIds); - InitializeTranslationLookup(m_entityIdManipulators); + InitializeTranslationLookup(m_entityIdManipulators); - m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); - m_axisPreview.m_orientation = QuaternionFromTransformNoScaling( - m_entityIdManipulators.m_manipulators->GetLocalTransform()); + m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); + m_axisPreview.m_orientation = QuaternionFromTransformNoScaling(m_entityIdManipulators.m_manipulators->GetLocalTransform()); - // [ref 1.] - BeginRecordManipulatorCommand(); - }); + // [ref 1.] + BeginRecordManipulatorCommand(); + }); translationManipulators->InstallSurfaceManipulatorMouseMoveCallback( [this, prevModifiers, manipulatorEntityIds](const SurfaceManipulator::Action& action) mutable -> void - { - UpdateTranslationManipulator( - action, manipulatorEntityIds->m_entityIds, m_entityIdManipulators, m_pivotOverrideFrame, prevModifiers, + { + UpdateTranslationManipulator( + action, manipulatorEntityIds->m_entityIds, m_entityIdManipulators, m_pivotOverrideFrame, prevModifiers, m_transformChangedInternally, m_spaceCluster.m_spaceLock); - }); + }); translationManipulators->InstallSurfaceManipulatorMouseUpCallback( [this, manipulatorEntityIds](const SurfaceManipulator::Action& /*action*/) - { - EndRecordManipulatorCommand(); - }); + { + EndRecordManipulatorCommand(); + }); // transfer ownership m_entityIdManipulators.m_manipulators = AZStd::move(translationManipulators); @@ -1381,18 +1339,12 @@ namespace AzToolsFramework InitializeManipulators(*rotationManipulators); rotationManipulators->SetLocalTransform( - RecalculateAverageManipulatorTransform( - m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode, m_referenceFrame)); + RecalculateAverageManipulatorTransform(m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode, m_referenceFrame)); // view - rotationManipulators->SetLocalAxes( - AZ::Vector3::CreateAxisX(), - AZ::Vector3::CreateAxisY(), - AZ::Vector3::CreateAxisZ()); + rotationManipulators->SetLocalAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ()); rotationManipulators->ConfigureView( - 2.0f, - AzFramework::ViewportColors::XAxisColor, - AzFramework::ViewportColors::YAxisColor, + 2.0f, AzFramework::ViewportColors::XAxisColor, AzFramework::ViewportColors::YAxisColor, AzFramework::ViewportColors::ZAxisColor); struct SharedRotationState @@ -1403,149 +1355,139 @@ namespace AzToolsFramework }; // lambdas capture shared_ptr by value to increment ref count - AZStd::shared_ptr sharedRotationState = - AZStd::make_shared(); + AZStd::shared_ptr sharedRotationState = AZStd::make_shared(); rotationManipulators->InstallLeftMouseDownCallback( [this, sharedRotationState](const AngularManipulator::Action& /*action*/) mutable -> void - { - sharedRotationState->m_savedOrientation = AZ::Quaternion::CreateIdentity(); - sharedRotationState->m_referenceFrameAtMouseDown = m_referenceFrame; - // important to sort entityIds based on hierarchy order when updating transforms - BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, sharedRotationState->m_entityIds); - - for (auto& entityIdLookup : m_entityIdManipulators.m_lookups) { - AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - worldFromLocal, entityIdLookup.first, &AZ::TransformBus::Events::GetWorldTM); + sharedRotationState->m_savedOrientation = AZ::Quaternion::CreateIdentity(); + sharedRotationState->m_referenceFrameAtMouseDown = m_referenceFrame; + // important to sort entityIds based on hierarchy order when updating transforms + BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, sharedRotationState->m_entityIds); - entityIdLookup.second.m_initial = worldFromLocal; - } + for (auto& entityIdLookup : m_entityIdManipulators.m_lookups) + { + AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); + AZ::TransformBus::EventResult(worldFromLocal, entityIdLookup.first, &AZ::TransformBus::Events::GetWorldTM); - m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); - m_axisPreview.m_orientation = QuaternionFromTransformNoScaling( - m_entityIdManipulators.m_manipulators->GetLocalTransform()); + entityIdLookup.second.m_initial = worldFromLocal; + } - // [ref 1.] - BeginRecordManipulatorCommand(); - }); + m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); + m_axisPreview.m_orientation = QuaternionFromTransformNoScaling(m_entityIdManipulators.m_manipulators->GetLocalTransform()); + + // [ref 1.] + BeginRecordManipulatorCommand(); + }); ViewportInteraction::KeyboardModifiers prevModifiers{}; rotationManipulators->InstallMouseMoveCallback( - [this, prevModifiers, sharedRotationState] - (const AngularManipulator::Action& action) mutable -> void - { - const ReferenceFrame referenceFrame = m_spaceCluster.m_spaceLock.value_or(ReferenceFrameFromModifiers(action.m_modifiers)); - const AZ::Quaternion manipulatorOrientation = action.m_start.m_rotation * action.m_current.m_delta; - // store the pivot override frame when positioning the manipulator manually (ctrl) - // so we don't lose the orientation when adding/removing entities from the selection - if (action.m_modifiers.Ctrl()) + [this, prevModifiers, sharedRotationState](const AngularManipulator::Action& action) mutable -> void { - m_pivotOverrideFrame.m_orientationOverride = manipulatorOrientation; - } + const ReferenceFrame referenceFrame = m_spaceCluster.m_spaceLock.value_or(ReferenceFrameFromModifiers(action.m_modifiers)); + const AZ::Quaternion manipulatorOrientation = action.m_start.m_rotation * action.m_current.m_delta; + // store the pivot override frame when positioning the manipulator manually (ctrl) + // so we don't lose the orientation when adding/removing entities from the selection + if (action.m_modifiers.Ctrl()) + { + m_pivotOverrideFrame.m_orientationOverride = manipulatorOrientation; + } - // only update the manipulator orientation if we're rotating in a local reference frame or we're - // manually modifying the manipulator orientation independent of the entity by holding ctrl - if ((sharedRotationState->m_referenceFrameAtMouseDown == ReferenceFrame::Local - && m_entityIdManipulators.m_lookups.size() == 1) || action.m_modifiers.Ctrl()) - { - m_entityIdManipulators.m_manipulators->SetLocalTransform( - AZ::Transform::CreateFromQuaternionAndTranslation( - manipulatorOrientation, - m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation())); - } + // only update the manipulator orientation if we're rotating in a local reference frame or we're + // manually modifying the manipulator orientation independent of the entity by holding ctrl + if ((sharedRotationState->m_referenceFrameAtMouseDown == ReferenceFrame::Local && + m_entityIdManipulators.m_lookups.size() == 1) || + action.m_modifiers.Ctrl()) + { + m_entityIdManipulators.m_manipulators->SetLocalTransform(AZ::Transform::CreateFromQuaternionAndTranslation( + manipulatorOrientation, m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation())); + } - // save state if we change the type of rotation we're doing to to prevent snapping - if (prevModifiers != action.m_modifiers) - { - UpdateInitialRotation(m_entityIdManipulators); - sharedRotationState->m_savedOrientation = action.m_current.m_delta.GetInverseFull(); - } + // save state if we change the type of rotation we're doing to to prevent snapping + if (prevModifiers != action.m_modifiers) + { + UpdateInitialRotation(m_entityIdManipulators); + sharedRotationState->m_savedOrientation = action.m_current.m_delta.GetInverseFull(); + } - // allow the user to modify the orientation without moving the object if ctrl is held - if (action.m_modifiers.Ctrl()) - { - UpdateInitialRotation(m_entityIdManipulators); - sharedRotationState->m_savedOrientation = action.m_current.m_delta.GetInverseFull(); - } - else - { - const auto pivotOrientation = - ETCS::CalculateSelectionPivotOrientation( + // allow the user to modify the orientation without moving the object if ctrl is held + if (action.m_modifiers.Ctrl()) + { + UpdateInitialRotation(m_entityIdManipulators); + sharedRotationState->m_savedOrientation = action.m_current.m_delta.GetInverseFull(); + } + else + { + const auto pivotOrientation = ETCS::CalculateSelectionPivotOrientation( m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, ReferenceFrame::Parent); - // note: must use sorted entityIds based on hierarchy order when updating transforms - for (AZ::EntityId entityId : sharedRotationState->m_entityIds) - { - auto entityIdLookupIt = m_entityIdManipulators.m_lookups.find(entityId); - if (entityIdLookupIt == m_entityIdManipulators.m_lookups.end()) + // note: must use sorted entityIds based on hierarchy order when updating transforms + for (AZ::EntityId entityId : sharedRotationState->m_entityIds) { - continue; - } - - // make sure we take into account how we move the axis independent of object - // if Ctrl was held to adjust the orientation of the axes separately - const AZ::Transform offsetRotation = AZ::Transform::CreateFromQuaternion( - sharedRotationState->m_savedOrientation * action.m_current.m_delta); - - switch (referenceFrame) - { - case ReferenceFrame::Local: + auto entityIdLookupIt = m_entityIdManipulators.m_lookups.find(entityId); + if (entityIdLookupIt == m_entityIdManipulators.m_lookups.end()) { - const AZ::Quaternion rotation = entityIdLookupIt->second.m_initial.GetRotation().GetNormalized(); - const AZ::Vector3 position = entityIdLookupIt->second.m_initial.GetTranslation(); - const float scale = entityIdLookupIt->second.m_initial.GetUniformScale(); - - const AZ::Vector3 centerOffset = CalculateCenterOffset(entityId, m_pivotMode); - - // scale -> rotate -> translate - SetEntityWorldTransform( - entityId, - AZ::Transform::CreateTranslation(position) * - AZ::Transform::CreateFromQuaternion(rotation) * - AZ::Transform::CreateTranslation(centerOffset) * offsetRotation * - AZ::Transform::CreateTranslation(-centerOffset) * - AZ::Transform::CreateUniformScale(scale)); + continue; } - break; - case ReferenceFrame::Parent: + + // make sure we take into account how we move the axis independent of object + // if Ctrl was held to adjust the orientation of the axes separately + const AZ::Transform offsetRotation = + AZ::Transform::CreateFromQuaternion(sharedRotationState->m_savedOrientation * action.m_current.m_delta); + + switch (referenceFrame) { - const AZ::Transform pivotTransform = - AZ::Transform::CreateFromQuaternionAndTranslation( + case ReferenceFrame::Local: + { + const AZ::Quaternion rotation = entityIdLookupIt->second.m_initial.GetRotation().GetNormalized(); + const AZ::Vector3 position = entityIdLookupIt->second.m_initial.GetTranslation(); + const float scale = entityIdLookupIt->second.m_initial.GetUniformScale(); + + const AZ::Vector3 centerOffset = CalculateCenterOffset(entityId, m_pivotMode); + + // scale -> rotate -> translate + SetEntityWorldTransform( + entityId, + AZ::Transform::CreateTranslation(position) * AZ::Transform::CreateFromQuaternion(rotation) * + AZ::Transform::CreateTranslation(centerOffset) * offsetRotation * + AZ::Transform::CreateTranslation(-centerOffset) * AZ::Transform::CreateUniformScale(scale)); + } + break; + case ReferenceFrame::Parent: + { + const AZ::Transform pivotTransform = AZ::Transform::CreateFromQuaternionAndTranslation( pivotOrientation.m_worldOrientation, m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation()); - const AZ::Transform transformInPivotSpace = - pivotTransform.GetInverse() * entityIdLookupIt->second.m_initial; + const AZ::Transform transformInPivotSpace = + pivotTransform.GetInverse() * entityIdLookupIt->second.m_initial; - SetEntityWorldTransform(entityId, pivotTransform * offsetRotation * transformInPivotSpace); - } - break; - case ReferenceFrame::World: - { - const AZ::Transform pivotTransform = - AZ::Transform::CreateFromQuaternionAndTranslation( + SetEntityWorldTransform(entityId, pivotTransform * offsetRotation * transformInPivotSpace); + } + break; + case ReferenceFrame::World: + { + const AZ::Transform pivotTransform = AZ::Transform::CreateFromQuaternionAndTranslation( AZ::Quaternion::CreateIdentity(), m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation()); - const AZ::Transform transformInPivotSpace = - pivotTransform.GetInverse() * entityIdLookupIt->second.m_initial; + const AZ::Transform transformInPivotSpace = + pivotTransform.GetInverse() * entityIdLookupIt->second.m_initial; - SetEntityWorldTransform(entityId, pivotTransform * offsetRotation * transformInPivotSpace); + SetEntityWorldTransform(entityId, pivotTransform * offsetRotation * transformInPivotSpace); + } + break; } - break; } } - } - prevModifiers = action.m_modifiers; - }); + prevModifiers = action.m_modifiers; + }); rotationManipulators->InstallLeftMouseUpCallback( [this](const AngularManipulator::Action& /*action*/) - { - EndRecordManipulatorCommand(); - }); + { + EndRecordManipulatorCommand(); + }); rotationManipulators->Register(g_mainManipulatorManagerId); @@ -1557,30 +1499,20 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - AZStd::unique_ptr scaleManipulators = - AZStd::make_unique(AZ::Transform::CreateIdentity()); + AZStd::unique_ptr scaleManipulators = AZStd::make_unique(AZ::Transform::CreateIdentity()); InitializeManipulators(*scaleManipulators); scaleManipulators->SetLocalTransform( - RecalculateAverageManipulatorTransform( - m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode, m_referenceFrame)); + RecalculateAverageManipulatorTransform(m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode, m_referenceFrame)); - scaleManipulators->SetAxes( - AZ::Vector3::CreateAxisX(), - AZ::Vector3::CreateAxisY(), - AZ::Vector3::CreateAxisZ()); - scaleManipulators->ConfigureView( - 2.0f, - AZ::Color::CreateOne(), - AZ::Color::CreateOne(), - AZ::Color::CreateOne()); + scaleManipulators->SetAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ()); + scaleManipulators->ConfigureView(2.0f, AZ::Color::CreateOne(), AZ::Color::CreateOne(), AZ::Color::CreateOne()); // lambdas capture shared_ptr by value to increment ref count auto manipulatorEntityIds = AZStd::make_shared(); - auto uniformLeftMouseDownCallback = - [this, manipulatorEntityIds]([[maybe_unused]] const LinearManipulator::Action& action) + auto uniformLeftMouseDownCallback = [this, manipulatorEntityIds]([[maybe_unused]] const LinearManipulator::Action& action) { // important to sort entityIds based on hierarchy order when updating transforms BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds->m_entityIds); @@ -1588,22 +1520,19 @@ namespace AzToolsFramework for (auto& entityIdLookup : m_entityIdManipulators.m_lookups) { AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - worldFromLocal, entityIdLookup.first, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityIdLookup.first, &AZ::TransformBus::Events::GetWorldTM); entityIdLookup.second.m_initial = worldFromLocal; } m_axisPreview.m_translation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); - m_axisPreview.m_orientation = QuaternionFromTransformNoScaling( - m_entityIdManipulators.m_manipulators->GetLocalTransform()); + m_axisPreview.m_orientation = QuaternionFromTransformNoScaling(m_entityIdManipulators.m_manipulators->GetLocalTransform()); }; auto uniformLeftMouseUpCallback = [this, manipulatorEntityIds]([[maybe_unused]] const LinearManipulator::Action& action) { - m_entityIdManipulators.m_manipulators->SetLocalTransform( - RecalculateAverageManipulatorTransform( - m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode, m_referenceFrame)); + m_entityIdManipulators.m_manipulators->SetLocalTransform(RecalculateAverageManipulatorTransform( + m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode, m_referenceFrame)); }; auto uniformLeftMouseMoveCallback = [this, manipulatorEntityIds](const LinearManipulator::Action& action) @@ -1620,7 +1549,8 @@ namespace AzToolsFramework const AZ::Transform initial = entityIdLookupIt->second.m_initial; const float initialScale = initial.GetUniformScale(); - const auto sumVectorElements = [](const AZ::Vector3& vec) { + const auto sumVectorElements = [](const AZ::Vector3& vec) + { return vec.GetX() + vec.GetY() + vec.GetZ(); }; @@ -1630,19 +1560,16 @@ namespace AzToolsFramework if (action.m_modifiers.Alt()) { - const AZ::Transform pivotTransform = TransformNormalizedScale( - entityIdLookupIt->second.m_initial); - const AZ::Transform transformInPivotSpace = - pivotTransform.GetInverse() * initial; + const AZ::Transform pivotTransform = TransformNormalizedScale(entityIdLookupIt->second.m_initial); + const AZ::Transform transformInPivotSpace = pivotTransform.GetInverse() * initial; SetEntityWorldTransform(entityId, pivotTransform * scaleTransform * transformInPivotSpace); } else { - const AZ::Transform pivotTransform = TransformNormalizedScale( - m_entityIdManipulators.m_manipulators->GetLocalTransform()); - const AZ::Transform transformInPivotSpace = - pivotTransform.GetInverse() * initial; + const AZ::Transform pivotTransform = + TransformNormalizedScale(m_entityIdManipulators.m_manipulators->GetLocalTransform()); + const AZ::Transform transformInPivotSpace = pivotTransform.GetInverse() * initial; SetEntityWorldTransform(entityId, pivotTransform * scaleTransform * transformInPivotSpace); } @@ -1674,11 +1601,10 @@ namespace AzToolsFramework { if (IsSelectableInViewport(entityId)) { - const AZ::ComponentId transformComponentId = GetTransformComponentId(entityId); + const AZ::ComponentId transformComponentId = GetTransformComponentId(entityId); if (transformComponentId != AZ::InvalidComponentId) { - manipulators.AddEntityComponentIdPair( - AZ::EntityComponentIdPair(entityId, transformComponentId)); + manipulators.AddEntityComponentIdPair(AZ::EntityComponentIdPair(entityId, transformComponentId)); m_entityIdManipulators.m_lookups.insert_key(entityId); } } @@ -1692,11 +1618,10 @@ namespace AzToolsFramework { if (IsSelectableInViewport(entityId)) { - const AZ::ComponentId transformComponentId = GetTransformComponentId(entityId); + const AZ::ComponentId transformComponentId = GetTransformComponentId(entityId); if (transformComponentId != AZ::InvalidComponentId) { - manipulators.AddEntityComponentIdPair( - AZ::EntityComponentIdPair(entityId, transformComponentId)); + manipulators.AddEntityComponentIdPair(AZ::EntityComponentIdPair(entityId, transformComponentId)); m_entityIdManipulators.m_lookups.insert_key(entityId); } } @@ -1754,8 +1679,7 @@ namespace AzToolsFramework CreateEntityManipulatorDeselectCommand(undoBatch); } - auto selectionCommand = - AZStd::make_unique(nextEntityIds, s_entityDeselectUndoRedoDesc); + auto selectionCommand = AZStd::make_unique(nextEntityIds, s_entityDeselectUndoRedoDesc); selectionCommand->SetParent(undoBatch.GetUndoBatch()); selectionCommand.release(); @@ -1785,8 +1709,7 @@ namespace AzToolsFramework return false; } - bool EditorTransformComponentSelection::HandleMouseInteraction( - const ViewportInteraction::MouseInteractionEvent& mouseInteraction) + bool EditorTransformComponentSelection::HandleMouseInteraction(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -1816,17 +1739,15 @@ namespace AzToolsFramework } AZ::Transform worldFromLocal; - AZ::TransformBus::EventResult( - worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); const AZ::Vector3 boxPosition = worldFromLocal.TransformPoint(CalculateCenterOffset(entityId, m_pivotMode)); - const AZ::Vector3 scaledSize = AZ::Vector3(s_pivotSize) * - CalculateScreenToWorldMultiplier(worldFromLocal.GetTranslation(), cameraState); + const AZ::Vector3 scaledSize = + AZ::Vector3(s_pivotSize) * CalculateScreenToWorldMultiplier(worldFromLocal.GetTranslation(), cameraState); if (AabbIntersectMouseRay( - mouseInteraction.m_mouseInteraction, - AZ::Aabb::CreateFromMinMax(boxPosition - scaledSize, boxPosition + scaledSize))) + mouseInteraction.m_mouseInteraction, AZ::Aabb::CreateFromMinMax(boxPosition - scaledSize, boxPosition + scaledSize))) { m_cachedEntityIdUnderCursor = entityId; } @@ -1834,16 +1755,15 @@ namespace AzToolsFramework const AZ::EntityId entityIdUnderCursor = m_cachedEntityIdUnderCursor; - EditorContextMenuUpdate( - m_contextMenu, mouseInteraction); + EditorContextMenuUpdate(m_contextMenu, mouseInteraction); m_boxSelect.HandleMouseInteraction(mouseInteraction); if (Input::CycleManipulator(mouseInteraction)) { const size_t scrollBound = 2; - const auto nextMode = (static_cast(m_mode) + scrollBound + - (MouseWheelDelta(mouseInteraction) < 0.0f ? 1 : -1)) % scrollBound; + const auto nextMode = + (static_cast(m_mode) + scrollBound + (MouseWheelDelta(mouseInteraction) < 0.0f ? 1 : -1)) % scrollBound; SetTransformMode(static_cast(nextMode)); @@ -1883,8 +1803,7 @@ namespace AzToolsFramework if (entityIdUnderCursor.IsValid()) { AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - worldFromLocal, entityIdUnderCursor, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityIdUnderCursor, &AZ::TransformBus::Events::GetWorldTM); switch (m_mode) { @@ -1912,8 +1831,7 @@ namespace AzToolsFramework if (entityIdUnderCursor.IsValid()) { AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - worldFromLocal, entityIdUnderCursor, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityIdUnderCursor, &AZ::TransformBus::Events::GetWorldTM); switch (m_mode) { @@ -1938,15 +1856,14 @@ namespace AzToolsFramework // try snapping to the terrain (if in Translation mode) and entity wasn't picked if (Input::SnapTerrain(mouseInteraction)) { - for(AZ::EntityId entityId : m_selectedEntityIds) + for (AZ::EntityId entityId : m_selectedEntityIds) { ScopedUndoBatch::MarkEntityDirty(entityId); } if (m_mode == Mode::Translation) { - const AZ::Vector3 finalSurfacePosition = - PickTerrainPosition(mouseInteraction.m_mouseInteraction); + const AZ::Vector3 finalSurfacePosition = PickTerrainPosition(mouseInteraction.m_mouseInteraction); // handle modifier alternatives if (Input::IndividualDitto(mouseInteraction)) @@ -1958,7 +1875,7 @@ namespace AzToolsFramework CopyTranslationToSelectedEntitiesGroup(finalSurfacePosition); } } - else if(m_mode == Mode::Rotation) + else if (m_mode == Mode::Rotation) { // handle modifier alternatives if (Input::IndividualDitto(mouseInteraction)) @@ -1981,14 +1898,13 @@ namespace AzToolsFramework { ScopedUndoBatch undoBatch(s_dittoManipulatorUndoRedoDesc); - auto manipulatorCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); if (entityIdUnderCursor.IsValid()) { AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - worldFromLocal, entityIdUnderCursor, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityIdUnderCursor, &AZ::TransformBus::Events::GetWorldTM); // set orientation/translation to match picked entity switch (m_mode) @@ -2029,13 +1945,9 @@ namespace AzToolsFramework DelegateClearManipulatorOverride(); } - manipulatorCommand->SetManipulatorAfter( - EntityManipulatorCommand::State( - BuildPivotOverride( - m_pivotOverrideFrame.HasTranslationOverride(), - m_pivotOverrideFrame.HasOrientationOverride()), - m_entityIdManipulators.m_manipulators->GetLocalTransform(), - entityIdUnderCursor)); + manipulatorCommand->SetManipulatorAfter(EntityManipulatorCommand::State( + BuildPivotOverride(m_pivotOverrideFrame.HasTranslationOverride(), m_pivotOverrideFrame.HasOrientationOverride()), + m_entityIdManipulators.m_manipulators->GetLocalTransform(), entityIdUnderCursor)); manipulatorCommand->SetParent(undoBatch.GetUndoBatch()); manipulatorCommand.release(); @@ -2073,9 +1985,7 @@ namespace AzToolsFramework QObject::connect(actions.back().get(), &QAction::triggered, actions.back().get(), callback); - EditorActionRequestBus::Broadcast( - &EditorActionRequests::AddActionViaBus, - actionId, actions.back().get()); + EditorActionRequestBus::Broadcast(&EditorActionRequests::AddActionViaBus, actionId, actions.back().get()); } void EditorTransformComponentSelection::OnEscape() @@ -2090,18 +2000,17 @@ namespace AzToolsFramework AZ::ComponentApplicationBus::Broadcast( &AZ::ComponentApplicationRequests::EnumerateEntities, [&func](const AZ::Entity* entity) - { - const AZ::EntityId entityId = entity->GetId(); - - bool editorEntity = false; - EditorEntityContextRequestBus::BroadcastResult( - editorEntity, &EditorEntityContextRequests::IsEditorEntity, entityId); - - if (editorEntity) { - func(entityId); - } - }); + const AZ::EntityId entityId = entity->GetId(); + + bool editorEntity = false; + EditorEntityContextRequestBus::BroadcastResult(editorEntity, &EditorEntityContextRequests::IsEditorEntity, entityId); + + if (editorEntity) + { + func(entityId); + } + }); } void EditorTransformComponentSelection::DelegateClearManipulatorOverride() @@ -2149,22 +2058,22 @@ namespace AzToolsFramework }; // lock selection - AddAction(m_actions, { QKeySequence(Qt::Key_L) }, - /*ID_EDIT_FREEZE =*/ 32900, - s_lockSelectionTitle, s_lockSelectionDesc, + AddAction( + m_actions, { QKeySequence(Qt::Key_L) }, + /*ID_EDIT_FREEZE =*/32900, s_lockSelectionTitle, s_lockSelectionDesc, [lockUnlock]() - { - lockUnlock(true); - }); + { + lockUnlock(true); + }); // unlock selection - AddAction(m_actions, { QKeySequence(Qt::CTRL + Qt::Key_L) }, - /*ID_EDIT_UNFREEZE =*/ 32973, - s_lockSelectionTitle, s_lockSelectionDesc, + AddAction( + m_actions, { QKeySequence(Qt::CTRL + Qt::Key_L) }, + /*ID_EDIT_UNFREEZE =*/32973, s_lockSelectionTitle, s_lockSelectionDesc, [lockUnlock]() - { - lockUnlock(false); - }); + { + lockUnlock(false); + }); const auto showHide = [this](const bool show) { @@ -2189,145 +2098,148 @@ namespace AzToolsFramework }; // hide selection - AddAction(m_actions, { QKeySequence(Qt::Key_H) }, - /*ID_EDIT_HIDE =*/ 32898, - s_hideSelectionTitle, s_hideSelectionDesc, + AddAction( + m_actions, { QKeySequence(Qt::Key_H) }, + /*ID_EDIT_HIDE =*/32898, s_hideSelectionTitle, s_hideSelectionDesc, [showHide]() - { - showHide(false); - }); + { + showHide(false); + }); // show selection - AddAction(m_actions, { QKeySequence(Qt::CTRL + Qt::Key_H) }, - /*ID_EDIT_UNHIDE =*/ 32974, - s_hideSelectionTitle, s_hideSelectionDesc, + AddAction( + m_actions, { QKeySequence(Qt::CTRL + Qt::Key_H) }, + /*ID_EDIT_UNHIDE =*/32974, s_hideSelectionTitle, s_hideSelectionDesc, [showHide]() - { - showHide(true); - }); + { + showHide(true); + }); // unlock all entities in the level/scene - AddAction(m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_L) }, - /*ID_EDIT_UNFREEZEALL =*/ 32901, - s_unlockAllTitle, s_unlockAllDesc, + AddAction( + m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_L) }, + /*ID_EDIT_UNFREEZEALL =*/32901, s_unlockAllTitle, s_unlockAllDesc, []() - { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - - ScopedUndoBatch undoBatch(s_unlockAllUndoRedoDesc); - - EnumerateEditorEntities([](AZ::EntityId entityId) { - ScopedUndoBatch::MarkEntityDirty(entityId); - SetEntityLockState(entityId, false); + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + + ScopedUndoBatch undoBatch(s_unlockAllUndoRedoDesc); + + EnumerateEditorEntities( + [](AZ::EntityId entityId) + { + ScopedUndoBatch::MarkEntityDirty(entityId); + SetEntityLockState(entityId, false); + }); }); - }); // show all entities in the level/scene - AddAction(m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_H) }, - /*ID_EDIT_UNHIDEALL =*/ 32899, - s_showAllTitle, s_showAllDesc, + AddAction( + m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_H) }, + /*ID_EDIT_UNHIDEALL =*/32899, s_showAllTitle, s_showAllDesc, []() - { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - - ScopedUndoBatch undoBatch(s_showAllEntitiesUndoRedoDesc); - - EnumerateEditorEntities([](AZ::EntityId entityId) { - ScopedUndoBatch::MarkEntityDirty(entityId); - SetEntityVisibility(entityId, true); + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + + ScopedUndoBatch undoBatch(s_showAllEntitiesUndoRedoDesc); + + EnumerateEditorEntities( + [](AZ::EntityId entityId) + { + ScopedUndoBatch::MarkEntityDirty(entityId); + SetEntityVisibility(entityId, true); + }); }); - }); // select all entities in the level/scene - AddAction(m_actions, { QKeySequence(Qt::CTRL + Qt::Key_A) }, - /*ID_EDIT_SELECTALL =*/ 33376, - s_selectAllTitle, s_selectAllDesc, + AddAction( + m_actions, { QKeySequence(Qt::CTRL + Qt::Key_A) }, + /*ID_EDIT_SELECTALL =*/33376, s_selectAllTitle, s_selectAllDesc, [this]() - { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - - ScopedUndoBatch undoBatch(s_selectAllEntitiesUndoRedoDesc); - - if (m_entityIdManipulators.m_manipulators) { - auto manipulatorCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - // note, nothing will change that the manipulatorCommand needs to keep track - // for after so no need to call SetManipulatorAfter + ScopedUndoBatch undoBatch(s_selectAllEntitiesUndoRedoDesc); - manipulatorCommand->SetParent(undoBatch.GetUndoBatch()); - manipulatorCommand.release(); - } - - EnumerateEditorEntities([this](AZ::EntityId entityId) - { - if (IsSelectableInViewport(entityId)) + if (m_entityIdManipulators.m_manipulators) { - AddEntityToSelection(entityId); + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + + // note, nothing will change that the manipulatorCommand needs to keep track + // for after so no need to call SetManipulatorAfter + + manipulatorCommand->SetParent(undoBatch.GetUndoBatch()); + manipulatorCommand.release(); } + + EnumerateEditorEntities( + [this](AZ::EntityId entityId) + { + if (IsSelectableInViewport(entityId)) + { + AddEntityToSelection(entityId); + } + }); + + auto nextEntityIds = EntityIdVectorFromContainer(m_selectedEntityIds); + + auto selectionCommand = AZStd::make_unique(nextEntityIds, s_selectAllEntitiesUndoRedoDesc); + selectionCommand->SetParent(undoBatch.GetUndoBatch()); + selectionCommand.release(); + + SetSelectedEntities(nextEntityIds); + RegenerateManipulators(); }); - auto nextEntityIds = EntityIdVectorFromContainer(m_selectedEntityIds); - - auto selectionCommand = AZStd::make_unique( - nextEntityIds, s_selectAllEntitiesUndoRedoDesc); - selectionCommand->SetParent(undoBatch.GetUndoBatch()); - selectionCommand.release(); - - SetSelectedEntities(nextEntityIds); - RegenerateManipulators(); - }); - // invert current selection - AddAction(m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_I) }, - /*ID_EDIT_INVERTSELECTION =*/ 33692, - s_invertSelectionTitle, s_invertSelectionDesc, + AddAction( + m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_I) }, + /*ID_EDIT_INVERTSELECTION =*/33692, s_invertSelectionTitle, s_invertSelectionDesc, [this]() - { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - - ScopedUndoBatch undoBatch(s_invertSelectionUndoRedoDesc); - - if (m_entityIdManipulators.m_manipulators) { - auto manipulatorCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - // note, nothing will change that the manipulatorCommand needs to keep track - // for after so no need to call SetManipulatorAfter + ScopedUndoBatch undoBatch(s_invertSelectionUndoRedoDesc); - manipulatorCommand->SetParent(undoBatch.GetUndoBatch()); - manipulatorCommand.release(); - } - - EntityIdSet entityIds; - EnumerateEditorEntities([this, &entityIds](AZ::EntityId entityId) - { - const auto entityIdIt = AZStd::find(m_selectedEntityIds.begin(), m_selectedEntityIds.end(), entityId); - if (entityIdIt == m_selectedEntityIds.end()) + if (m_entityIdManipulators.m_manipulators) { - if (IsSelectableInViewport(entityId)) - { - entityIds.insert(entityId); - } + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + + // note, nothing will change that the manipulatorCommand needs to keep track + // for after so no need to call SetManipulatorAfter + + manipulatorCommand->SetParent(undoBatch.GetUndoBatch()); + manipulatorCommand.release(); } + + EntityIdSet entityIds; + EnumerateEditorEntities( + [this, &entityIds](AZ::EntityId entityId) + { + const auto entityIdIt = AZStd::find(m_selectedEntityIds.begin(), m_selectedEntityIds.end(), entityId); + if (entityIdIt == m_selectedEntityIds.end()) + { + if (IsSelectableInViewport(entityId)) + { + entityIds.insert(entityId); + } + } + }); + + m_selectedEntityIds = entityIds; + + auto nextEntityIds = EntityIdVectorFromContainer(entityIds); + + auto selectionCommand = AZStd::make_unique(nextEntityIds, s_invertSelectionUndoRedoDesc); + selectionCommand->SetParent(undoBatch.GetUndoBatch()); + selectionCommand.release(); + + SetSelectedEntities(nextEntityIds); + RegenerateManipulators(); }); - m_selectedEntityIds = entityIds; - - auto nextEntityIds = EntityIdVectorFromContainer(entityIds); - - auto selectionCommand = AZStd::make_unique(nextEntityIds, s_invertSelectionUndoRedoDesc); - selectionCommand->SetParent(undoBatch.GetUndoBatch()); - selectionCommand.release(); - - SetSelectedEntities(nextEntityIds); - RegenerateManipulators(); - }); - bool isPrefabSystemEnabled = false; AzFramework::ApplicationRequests::Bus::BroadcastResult( isPrefabSystemEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled); @@ -2340,8 +2252,10 @@ namespace AzToolsFramework { // duplicate selection AddAction( - m_actions, {QKeySequence(Qt::CTRL + Qt::Key_D)}, - /*ID_EDIT_CLONE =*/33525, s_duplicateTitle, s_duplicateDesc, []() { + m_actions, { QKeySequence(Qt::CTRL + Qt::Key_D) }, + /*ID_EDIT_CLONE =*/33525, s_duplicateTitle, s_duplicateDesc, + []() + { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); // Clear Widget selection - Prevents issues caused by cloning entities while a property in the Reflected Property Editor @@ -2366,121 +2280,113 @@ namespace AzToolsFramework // delete selection AddAction( m_actions, { QKeySequence(Qt::Key_Delete) }, - /*ID_EDIT_DELETE=*/ 33480, - s_deleteTitle, s_deleteDesc, + /*ID_EDIT_DELETE=*/33480, s_deleteTitle, s_deleteDesc, [this]() - { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + { + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - ScopedUndoBatch undoBatch(s_deleteUndoRedoDesc); + ScopedUndoBatch undoBatch(s_deleteUndoRedoDesc); - CreateEntityManipulatorDeselectCommand(undoBatch); + CreateEntityManipulatorDeselectCommand(undoBatch); - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::DeleteEntitiesAndAllDescendants, - EntityIdVectorFromContainer(m_selectedEntityIds)); + ToolsApplicationRequestBus::Broadcast( + &ToolsApplicationRequests::DeleteEntitiesAndAllDescendants, EntityIdVectorFromContainer(m_selectedEntityIds)); - m_selectedEntityIds.clear(); - m_pivotOverrideFrame.Reset(); - }); + m_selectedEntityIds.clear(); + m_pivotOverrideFrame.Reset(); + }); AddAction( m_actions, { QKeySequence(Qt::Key_Space) }, - /*ID_EDIT_ESCAPE=*/ 33513, - "", "", + /*ID_EDIT_ESCAPE=*/33513, "", "", [this]() - { - DeselectEntities(); - }); + { + DeselectEntities(); + }); AddAction( m_actions, { QKeySequence(Qt::Key_P) }, - /*ID_EDIT_PIVOT=*/ 36203, - s_togglePivotTitleEditMenu, s_togglePivotDesc, + /*ID_EDIT_PIVOT=*/36203, s_togglePivotTitleEditMenu, s_togglePivotDesc, [this]() - { - ToggleCenterPivotSelection(); - }); + { + ToggleCenterPivotSelection(); + }); AddAction( m_actions, { QKeySequence(Qt::Key_R) }, - /*ID_EDIT_RESET=*/ 36204, - s_resetEntityTransformTitle, s_resetEntityTransformDesc, + /*ID_EDIT_RESET=*/36204, s_resetEntityTransformTitle, s_resetEntityTransformDesc, [this]() - { - switch (m_mode) { - case Mode::Rotation: - ResetOrientationForSelectedEntitiesLocal(); - break; - case Mode::Scale: - CopyScaleToSelectedEntitiesIndividualLocal(1.0f); - break; - case Mode::Translation: - ResetTranslationForSelectedEntitiesLocal(); - break; - } - }); + switch (m_mode) + { + case Mode::Rotation: + ResetOrientationForSelectedEntitiesLocal(); + break; + case Mode::Scale: + CopyScaleToSelectedEntitiesIndividualLocal(1.0f); + break; + case Mode::Translation: + ResetTranslationForSelectedEntitiesLocal(); + break; + } + }); AddAction( m_actions, { QKeySequence(Qt::CTRL + Qt::Key_R) }, - /*ID_EDIT_RESET_MANIPULATOR=*/ 36207, - s_resetManipulatorTitle, s_resetManipulatorDesc, + /*ID_EDIT_RESET_MANIPULATOR=*/36207, s_resetManipulatorTitle, s_resetManipulatorDesc, AZStd::bind(AZStd::mem_fn(&EditorTransformComponentSelection::DelegateClearManipulatorOverride), this)); AddAction( m_actions, { QKeySequence(Qt::ALT + Qt::Key_R) }, - /*ID_EDIT_RESET_LOCAL=*/ 36205, - s_resetTransformLocalTitle, s_resetTransformLocalDesc, + /*ID_EDIT_RESET_LOCAL=*/36205, s_resetTransformLocalTitle, s_resetTransformLocalDesc, [this]() - { - switch (m_mode) { - case Mode::Rotation: - ResetOrientationForSelectedEntitiesLocal(); - break; - case Mode::Scale: - CopyScaleToSelectedEntitiesIndividualWorld(1.0f); - break; - case Mode::Translation: - // do nothing - break; - } - }); + switch (m_mode) + { + case Mode::Rotation: + ResetOrientationForSelectedEntitiesLocal(); + break; + case Mode::Scale: + CopyScaleToSelectedEntitiesIndividualWorld(1.0f); + break; + case Mode::Translation: + // do nothing + break; + } + }); AddAction( m_actions, { QKeySequence(Qt::SHIFT + Qt::Key_R) }, - /*ID_EDIT_RESET_WORLD=*/ 36206, - s_resetTransformWorldTitle, s_resetTransformWorldDesc, + /*ID_EDIT_RESET_WORLD=*/36206, s_resetTransformWorldTitle, s_resetTransformWorldDesc, [this]() - { - switch (m_mode) { - case Mode::Rotation: + switch (m_mode) { - // begin an undo batch so operations inside CopyOrientation... and - // DelegateClear... are grouped into a single undo/redo - ScopedUndoBatch undoBatch { s_resetTransformWorldTitle }; - CopyOrientationToSelectedEntitiesIndividual(AZ::Quaternion::CreateIdentity()); - ClearManipulatorOrientationOverride(); + case Mode::Rotation: + { + // begin an undo batch so operations inside CopyOrientation... and + // DelegateClear... are grouped into a single undo/redo + ScopedUndoBatch undoBatch{ s_resetTransformWorldTitle }; + CopyOrientationToSelectedEntitiesIndividual(AZ::Quaternion::CreateIdentity()); + ClearManipulatorOrientationOverride(); + } + break; + case Mode::Scale: + case Mode::Translation: + break; } - break; - case Mode::Scale: - case Mode::Translation: - break; - } - }); - + }); + AddAction( m_actions, { QKeySequence(Qt::Key_U) }, /*ID_VIEWPORTUI_VISIBLE=*/50040, "Toggle ViewportUI", "Hide/Unhide Viewport UI", - [this]() - { + [this]() + { SetViewportUiClusterVisible(m_transformModeClusterId, !m_viewportUiVisible); SetViewportUiClusterVisible(m_spaceCluster.m_spaceClusterId, !m_viewportUiVisible); m_viewportUiVisible = !m_viewportUiVisible; - }); - + }); + EditorMenuRequestBus::Broadcast(&EditorMenuRequests::RestoreEditMenuToDefault); } @@ -2488,8 +2394,7 @@ namespace AzToolsFramework { for (auto& action : m_actions) { - EditorActionRequestBus::Broadcast( - &EditorActionRequests::RemoveActionViaBus, action.get()); + EditorActionRequestBus::Broadcast(&EditorActionRequests::RemoveActionViaBus, action.get()); } m_actions.clear(); @@ -2558,42 +2463,37 @@ namespace AzToolsFramework { // create the cluster for changing transform mode ViewportUi::ViewportUiRequestBus::EventResult( - m_transformModeClusterId, ViewportUi::DefaultViewportId, - &ViewportUi::ViewportUiRequestBus::Events::CreateCluster, ViewportUi::Alignment::TopLeft); + m_transformModeClusterId, ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateCluster, + ViewportUi::Alignment::TopLeft); // create and register the buttons (strings correspond to icons even if the values appear different) m_translateButtonId = RegisterClusterButton(m_transformModeClusterId, "Move"); m_rotateButtonId = RegisterClusterButton(m_transformModeClusterId, "Translate"); m_scaleButtonId = RegisterClusterButton(m_transformModeClusterId, "Scale"); - auto onButtonClicked = - [this](ViewportUi::ButtonId buttonId) + auto onButtonClicked = [this](ViewportUi::ButtonId buttonId) + { + if (buttonId == m_translateButtonId) { - if (buttonId == m_translateButtonId) - { - SetTransformMode(Mode::Translation); - } - else if (buttonId == m_rotateButtonId) - { - SetTransformMode(Mode::Rotation); - } - else if (buttonId == m_scaleButtonId) - { - SetTransformMode(Mode::Scale); - } - }; + SetTransformMode(Mode::Translation); + } + else if (buttonId == m_rotateButtonId) + { + SetTransformMode(Mode::Rotation); + } + else if (buttonId == m_scaleButtonId) + { + SetTransformMode(Mode::Scale); + } + }; m_transformModeSelectionHandler = AZ::Event::Handler(onButtonClicked); ViewportUi::ViewportUiRequestBus::Event( - ViewportUi::DefaultViewportId, - &ViewportUi::ViewportUiRequestBus::Events::SetClusterActiveButton, - m_transformModeClusterId, + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::SetClusterActiveButton, m_transformModeClusterId, m_translateButtonId); ViewportUi::ViewportUiRequestBus::Event( - ViewportUi::DefaultViewportId, - &ViewportUi::ViewportUiRequestBus::Events::RegisterClusterEventHandler, - m_transformModeClusterId, + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::RegisterClusterEventHandler, m_transformModeClusterId, m_transformModeSelectionHandler); } @@ -2609,7 +2509,8 @@ namespace AzToolsFramework m_spaceCluster.m_parentButtonId = RegisterClusterButton(m_spaceCluster.m_spaceClusterId, "Parent"); m_spaceCluster.m_localButtonId = RegisterClusterButton(m_spaceCluster.m_spaceClusterId, "Local"); - auto onButtonClicked = [this](ViewportUi::ButtonId buttonId) { + auto onButtonClicked = [this](ViewportUi::ButtonId buttonId) + { if (buttonId == m_spaceCluster.m_localButtonId) { // Unlock @@ -2674,14 +2575,13 @@ namespace AzToolsFramework if (m_pivotOverrideFrame.m_orientationOverride && m_entityIdManipulators.m_manipulators) { - m_pivotOverrideFrame.m_orientationOverride = QuaternionFromTransformNoScaling( - m_entityIdManipulators.m_manipulators->GetLocalTransform()); + m_pivotOverrideFrame.m_orientationOverride = + QuaternionFromTransformNoScaling(m_entityIdManipulators.m_manipulators->GetLocalTransform()); } if (m_pivotOverrideFrame.m_translationOverride && m_entityIdManipulators.m_manipulators) { - m_pivotOverrideFrame.m_translationOverride = - m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); + m_pivotOverrideFrame.m_translationOverride = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); } m_mode = mode; @@ -2758,8 +2658,7 @@ namespace AzToolsFramework // we are responsible for updating the current selection m_didSetSelectedEntities = true; - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetSelectedEntities, entityIds); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, entityIds); } void EditorTransformComponentSelection::RefreshManipulators(const RefreshType refreshType) @@ -2779,15 +2678,13 @@ namespace AzToolsFramework break; case RefreshType::Orientation: transform = AZ::Transform::CreateFromQuaternionAndTranslation( - RecalculateAverageManipulatorOrientation( - m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_referenceFrame), + RecalculateAverageManipulatorOrientation(m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_referenceFrame), m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation()); break; case RefreshType::Translation: transform = AZ::Transform::CreateFromQuaternionAndTranslation( m_entityIdManipulators.m_manipulators->GetLocalTransform().GetRotation(), - RecalculateAverageManipulatorTranslation( - m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode)); + RecalculateAverageManipulatorTranslation(m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode)); break; } @@ -2810,9 +2707,8 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators) { - m_entityIdManipulators.m_manipulators->SetLocalTransform( - AZ::Transform::CreateFromQuaternionAndTranslation( - orientation, m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation())); + m_entityIdManipulators.m_manipulators->SetLocalTransform(AZ::Transform::CreateFromQuaternionAndTranslation( + orientation, m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation())); m_entityIdManipulators.m_manipulators->SetBoundsDirty(); } @@ -2839,15 +2735,14 @@ namespace AzToolsFramework { ScopedUndoBatch undoBatch(s_resetManipulatorTranslationUndoRedoDesc); - auto manipulatorCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); m_pivotOverrideFrame.ResetPickedTranslation(); m_pivotOverrideFrame.m_pickedEntityIdOverride.SetInvalid(); - m_entityIdManipulators.m_manipulators->SetLocalTransform( - RecalculateAverageManipulatorTransform( - m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode, m_referenceFrame)); + m_entityIdManipulators.m_manipulators->SetLocalTransform(RecalculateAverageManipulatorTransform( + m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_pivotMode, m_referenceFrame)); m_entityIdManipulators.m_manipulators->SetBoundsDirty(); @@ -2864,20 +2759,18 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators) { - ScopedUndoBatch undoBatch { s_resetManipulatorOrientationUndoRedoDesc }; + ScopedUndoBatch undoBatch{ s_resetManipulatorOrientationUndoRedoDesc }; - auto manipulatorCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); m_pivotOverrideFrame.ResetPickedOrientation(); m_pivotOverrideFrame.m_pickedEntityIdOverride.SetInvalid(); // parent reference frame is the default (when no modifiers are held) - m_entityIdManipulators.m_manipulators->SetLocalTransform( - AZ::Transform::CreateFromQuaternionAndTranslation( - ETCS::CalculatePivotOrientationForEntityIds( - m_entityIdManipulators.m_lookups, ReferenceFrame::Parent).m_worldOrientation, - m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation())); + m_entityIdManipulators.m_manipulators->SetLocalTransform(AZ::Transform::CreateFromQuaternionAndTranslation( + ETCS::CalculatePivotOrientationForEntityIds(m_entityIdManipulators.m_lookups, ReferenceFrame::Parent).m_worldOrientation, + m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation())); m_entityIdManipulators.m_manipulators->SetBoundsDirty(); @@ -2900,8 +2793,7 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - static_assert(AZStd::is_same::value, - "Container key type is not an EntityId"); + static_assert(AZStd::is_same::value, "Container key type is not an EntityId"); AZ::EntityId parentId; AZ::TransformBus::EventResult(parentId, entityId, &AZ::TransformBus::Events::GetParentId); @@ -2935,11 +2827,10 @@ namespace AzToolsFramework ScopedUndoBatch undoBatch(s_dittoTranslationGroupUndoRedoDesc); // store previous translation manipulator position - const AZ::Vector3 previousPivotTranslation = - m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); + const AZ::Vector3 previousPivotTranslation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); - auto manipulatorCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); // refresh the transform pivot override if it's set if (m_pivotOverrideFrame.m_translationOverride) @@ -2947,15 +2838,11 @@ namespace AzToolsFramework OverrideManipulatorTranslation(translation); } - manipulatorCommand->SetManipulatorAfter( - EntityManipulatorCommand::State( - BuildPivotOverride( - m_pivotOverrideFrame.HasTranslationOverride(), - m_pivotOverrideFrame.HasOrientationOverride()), - AZ::Transform::CreateFromQuaternionAndTranslation( - QuaternionFromTransformNoScaling( - m_entityIdManipulators.m_manipulators->GetLocalTransform()), translation), - m_pivotOverrideFrame.m_pickedEntityIdOverride)); + manipulatorCommand->SetManipulatorAfter(EntityManipulatorCommand::State( + BuildPivotOverride(m_pivotOverrideFrame.HasTranslationOverride(), m_pivotOverrideFrame.HasOrientationOverride()), + AZ::Transform::CreateFromQuaternionAndTranslation( + QuaternionFromTransformNoScaling(m_entityIdManipulators.m_manipulators->GetLocalTransform()), translation), + m_pivotOverrideFrame.m_pickedEntityIdOverride)); manipulatorCommand->SetParent(undoBatch.GetUndoBatch()); manipulatorCommand.release(); @@ -2995,8 +2882,8 @@ namespace AzToolsFramework { ScopedUndoBatch undoBatch(s_dittoTranslationIndividualUndoRedoDesc); - auto manipulatorCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); // refresh the transform pivot override if it's set if (m_pivotOverrideFrame.m_translationOverride) @@ -3004,15 +2891,11 @@ namespace AzToolsFramework OverrideManipulatorTranslation(translation); } - manipulatorCommand->SetManipulatorAfter( - EntityManipulatorCommand::State( - BuildPivotOverride( - m_pivotOverrideFrame.HasTranslationOverride(), - m_pivotOverrideFrame.HasOrientationOverride()), - AZ::Transform::CreateFromQuaternionAndTranslation( - QuaternionFromTransformNoScaling( - m_entityIdManipulators.m_manipulators->GetLocalTransform()), translation), - m_pivotOverrideFrame.m_pickedEntityIdOverride)); + manipulatorCommand->SetManipulatorAfter(EntityManipulatorCommand::State( + BuildPivotOverride(m_pivotOverrideFrame.HasTranslationOverride(), m_pivotOverrideFrame.HasOrientationOverride()), + AZ::Transform::CreateFromQuaternionAndTranslation( + QuaternionFromTransformNoScaling(m_entityIdManipulators.m_manipulators->GetLocalTransform()), translation), + m_pivotOverrideFrame.m_pickedEntityIdOverride)); manipulatorCommand->SetParent(undoBatch.GetUndoBatch()); manipulatorCommand.release(); @@ -3084,17 +2967,16 @@ namespace AzToolsFramework RefreshUiAfterChange(manipulatorEntityIds.m_entityIds); } - void EditorTransformComponentSelection::CopyOrientationToSelectedEntitiesIndividual( - const AZ::Quaternion& orientation) + void EditorTransformComponentSelection::CopyOrientationToSelectedEntitiesIndividual(const AZ::Quaternion& orientation) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); if (m_entityIdManipulators.m_manipulators) { - ScopedUndoBatch undoBatch { s_dittoEntityOrientationIndividualUndoRedoDesc }; + ScopedUndoBatch undoBatch{ s_dittoEntityOrientationIndividualUndoRedoDesc }; - auto manipulatorCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); ManipulatorEntityIds manipulatorEntityIds; BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds.m_entityIds); @@ -3130,8 +3012,7 @@ namespace AzToolsFramework } } - void EditorTransformComponentSelection::CopyOrientationToSelectedEntitiesGroup( - const AZ::Quaternion& orientation) + void EditorTransformComponentSelection::CopyOrientationToSelectedEntitiesGroup(const AZ::Quaternion& orientation) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -3139,8 +3020,8 @@ namespace AzToolsFramework { ScopedUndoBatch undoBatch(s_dittoEntityOrientationGroupUndoRedoDesc); - auto manipulatorCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); ManipulatorEntityIds manipulatorEntityIds; BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds.m_entityIds); @@ -3148,8 +3029,7 @@ namespace AzToolsFramework // save initial transforms const auto transformsBefore = RecordTransformsBefore(manipulatorEntityIds.m_entityIds); - const AZ::Transform currentTransform = - m_entityIdManipulators.m_manipulators->GetLocalTransform(); + const AZ::Transform currentTransform = m_entityIdManipulators.m_manipulators->GetLocalTransform(); const AZ::Transform nextTransform = AZ::Transform::CreateFromQuaternionAndTranslation( orientation, m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation()); @@ -3163,8 +3043,7 @@ namespace AzToolsFramework const auto transformIt = transformsBefore.find(entityId); if (transformIt != transformsBefore.end()) { - const AZ::Transform transformInPivotSpace = - currentTransform.GetInverse() * transformIt->second; + const AZ::Transform transformInPivotSpace = currentTransform.GetInverse() * transformIt->second; SetEntityWorldTransform(entityId, nextTransform * transformInPivotSpace); } @@ -3186,7 +3065,7 @@ namespace AzToolsFramework AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); ScopedUndoBatch undoBatch(s_resetOrientationToParentUndoRedoDesc); - for (const auto& entityIdLookup: m_entityIdManipulators.m_lookups) + for (const auto& entityIdLookup : m_entityIdManipulators.m_lookups) { ScopedUndoBatch::MarkEntityDirty(entityIdLookup.first); SetEntityLocalRotation(entityIdLookup.first, AZ::Vector3::CreateZero()); @@ -3209,14 +3088,12 @@ namespace AzToolsFramework ScopedUndoBatch undoBatch(s_resetTranslationToParentUndoRedoDesc); ManipulatorEntityIds manipulatorEntityIds; - BuildSortedEntityIdVectorFromEntityIdMap( - m_entityIdManipulators.m_lookups, manipulatorEntityIds.m_entityIds); + BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds.m_entityIds); for (AZ::EntityId entityId : manipulatorEntityIds.m_entityIds) { AZ::EntityId parentId; - AZ::TransformBus::EventResult( - parentId, entityId, &AZ::TransformBus::Events::GetParentId); + AZ::TransformBus::EventResult(parentId, entityId, &AZ::TransformBus::Events::GetParentId); if (parentId.IsValid()) { @@ -3231,11 +3108,15 @@ namespace AzToolsFramework } } - void EditorTransformComponentSelection::PopulateEditorGlobalContextMenu( - QMenu* menu, const AZ::Vector2& /*point*/, const int /*flags*/) + void EditorTransformComponentSelection::PopulateEditorGlobalContextMenu(QMenu* menu, const AZ::Vector2& /*point*/, const int /*flags*/) { QAction* action = menu->addAction(QObject::tr(s_togglePivotTitleRightClick)); - QObject::connect(action, &QAction::triggered, action, [this]() { ToggleCenterPivotSelection(); }); + QObject::connect( + action, &QAction::triggered, action, + [this]() + { + ToggleCenterPivotSelection(); + }); } void EditorTransformComponentSelection::BeforeEntitySelectionChanged() @@ -3281,8 +3162,10 @@ namespace AzToolsFramework } static void DrawPreviewAxis( - AzFramework::DebugDisplayRequests& display, const AZ::Transform& transform, - const float axisLength, const AzFramework::CameraState& cameraState) + AzFramework::DebugDisplayRequests& display, + const AZ::Transform& transform, + const float axisLength, + const AzFramework::CameraState& cameraState) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -3297,8 +3180,8 @@ namespace AzToolsFramework const auto axisFlip = [&transform, &cameraState](const AZ::Vector3& axis) -> float { return ShouldFlipCameraAxis( - AZ::Transform::CreateIdentity(), transform.GetTranslation(), - TransformDirectionNoScaling(transform, axis), cameraState) + AZ::Transform::CreateIdentity(), transform.GetTranslation(), TransformDirectionNoScaling(transform, axis), + cameraState) ? -1.0f : 1.0f; }; @@ -3306,18 +3189,15 @@ namespace AzToolsFramework display.SetColor(s_fadedXAxisColor); display.DrawLine( transform.GetTranslation(), - transform.GetTranslation() + transform.GetBasisX().GetNormalizedSafe() * - axisLength * axisFlip(AZ::Vector3::CreateAxisX())); + transform.GetTranslation() + transform.GetBasisX().GetNormalizedSafe() * axisLength * axisFlip(AZ::Vector3::CreateAxisX())); display.SetColor(s_fadedYAxisColor); display.DrawLine( transform.GetTranslation(), - transform.GetTranslation() + transform.GetBasisY().GetNormalizedSafe() * - axisLength * axisFlip(AZ::Vector3::CreateAxisY())); + transform.GetTranslation() + transform.GetBasisY().GetNormalizedSafe() * axisLength * axisFlip(AZ::Vector3::CreateAxisY())); display.SetColor(s_fadedZAxisColor); display.DrawLine( transform.GetTranslation(), - transform.GetTranslation() + transform.GetBasisZ().GetNormalizedSafe() * - axisLength * axisFlip(AZ::Vector3::CreateAxisZ())); + transform.GetTranslation() + transform.GetBasisZ().GetNormalizedSafe() * axisLength * axisFlip(AZ::Vector3::CreateAxisZ())); display.DepthWriteOn(); display.DepthTestOn(); @@ -3330,15 +3210,11 @@ namespace AzToolsFramework static void DrawManipulatorGrid( AzFramework::DebugDisplayRequests& debugDisplay, const EntityIdManipulators& entityIdManipulators, const float gridSize) { - const AZ::Matrix3x3 orientation = - AZ::Matrix3x3::CreateFromTransform(entityIdManipulators.m_manipulators->GetLocalTransform()); + const AZ::Matrix3x3 orientation = AZ::Matrix3x3::CreateFromTransform(entityIdManipulators.m_manipulators->GetLocalTransform()); - const AZ::Vector3 translation = - entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); + const AZ::Vector3 translation = entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); - DrawSnappingGrid( - debugDisplay, AZ::Transform::CreateFromMatrix3x3AndTranslation(orientation, translation), - gridSize); + DrawSnappingGrid(debugDisplay, AZ::Transform::CreateFromMatrix3x3AndTranslation(orientation, translation), gridSize); } void EditorTransformComponentSelection::DisplayViewportSelection( @@ -3348,16 +3224,14 @@ namespace AzToolsFramework CheckDirtyEntityIds(); - const auto modifiers = ViewportInteraction::KeyboardModifiers( - ViewportInteraction::TranslateKeyboardModifiers(QApplication::queryKeyboardModifiers())); + const auto modifiers = + ViewportInteraction::KeyboardModifiers(ViewportInteraction::TranslateKeyboardModifiers(QApplication::queryKeyboardModifiers())); m_cursorState.Update(); HandleAccents( - !m_selectedEntityIds.empty(), m_cachedEntityIdUnderCursor, - modifiers.Ctrl(), m_hoveredEntityId, - ViewportInteraction::BuildMouseButtons( - QGuiApplication::mouseButtons()), m_boxSelect.Active()); + !m_selectedEntityIds.empty(), m_cachedEntityIdUnderCursor, modifiers.Ctrl(), m_hoveredEntityId, + ViewportInteraction::BuildMouseButtons(QGuiApplication::mouseButtons()), m_boxSelect.Active()); const ReferenceFrame referenceFrame = m_spaceCluster.m_spaceLock.value_or(ReferenceFrameFromModifiers(modifiers)); @@ -3370,10 +3244,8 @@ namespace AzToolsFramework refresh = true; } - refresh = refresh - || (m_triedToRefresh - && m_entityIdManipulators.m_manipulators - && !m_entityIdManipulators.m_manipulators->PerformingAction()); + refresh = refresh || + (m_triedToRefresh && m_entityIdManipulators.m_manipulators && !m_entityIdManipulators.m_manipulators->PerformingAction()); // we've moved from parent to world space, parent to local space or vice versa by holding or // releasing shift and/or alt - make sure we update the manipulator orientation appropriately @@ -3386,8 +3258,7 @@ namespace AzToolsFramework const auto entityFilter = [this](AZ::EntityId entityId) { - const bool entityHasManipulator = - m_entityIdManipulators.m_lookups.find(entityId) != m_entityIdManipulators.m_lookups.end(); + const bool entityHasManipulator = m_entityIdManipulators.m_lookups.find(entityId) != m_entityIdManipulators.m_lookups.end(); return !entityHasManipulator; }; @@ -3398,15 +3269,12 @@ namespace AzToolsFramework { if (m_pivotOverrideFrame.m_pickedEntityIdOverride.IsValid()) { - const AZ::Transform pickedEntityWorldTransform = - AZ::Transform::CreateFromQuaternionAndTranslation( - ETCS::CalculatePivotOrientation( - m_pivotOverrideFrame.m_pickedEntityIdOverride, referenceFrame).m_worldOrientation, - CalculatePivotTranslation( - m_pivotOverrideFrame.m_pickedEntityIdOverride, m_pivotMode)); + const AZ::Transform pickedEntityWorldTransform = AZ::Transform::CreateFromQuaternionAndTranslation( + ETCS::CalculatePivotOrientation(m_pivotOverrideFrame.m_pickedEntityIdOverride, referenceFrame).m_worldOrientation, + CalculatePivotTranslation(m_pivotOverrideFrame.m_pickedEntityIdOverride, m_pivotMode)); - const float scaledSize = s_pivotSize * - CalculateScreenToWorldMultiplier(pickedEntityWorldTransform.GetTranslation(), cameraState); + const float scaledSize = + s_pivotSize * CalculateScreenToWorldMultiplier(pickedEntityWorldTransform.GetTranslation(), cameraState); debugDisplay.DepthWriteOff(); debugDisplay.DepthTestOff(); @@ -3421,8 +3289,8 @@ namespace AzToolsFramework // check what pivot orientation we are in (based on if a modifier is // held to move us from parent to world space or parent to local space) // or if we set a pivot override - const auto pivotResult = ETCS::CalculateSelectionPivotOrientation( - m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_referenceFrame); + const auto pivotResult = + ETCS::CalculateSelectionPivotOrientation(m_entityIdManipulators.m_lookups, m_pivotOverrideFrame, m_referenceFrame); // if the reference frame was parent space and the selection does have a // valid parent, draw a preview axis at its position/orientation @@ -3432,8 +3300,7 @@ namespace AzToolsFramework { const AZ::Transform& worldFromLocal = m_entityDataCache->GetVisibleEntityTransform(*parentEntityIndex); - const float adjustedLineLength = - CalculateScreenToWorldMultiplier(worldFromLocal.GetTranslation(), cameraState); + const float adjustedLineLength = CalculateScreenToWorldMultiplier(worldFromLocal.GetTranslation(), cameraState); DrawPreviewAxis(debugDisplay, worldFromLocal, adjustedLineLength, cameraState); } @@ -3452,10 +3319,11 @@ namespace AzToolsFramework const AZ::Vector3 boxPosition = worldFromLocal.TransformPoint(CalculateCenterOffset(entityId, m_pivotMode)); - const AZ::Vector3 scaledSize = AZ::Vector3(s_pivotSize) * - CalculateScreenToWorldMultiplier(worldFromLocal.GetTranslation(), cameraState); + const AZ::Vector3 scaledSize = + AZ::Vector3(s_pivotSize) * CalculateScreenToWorldMultiplier(worldFromLocal.GetTranslation(), cameraState); - const AZ::Color hiddenNormal[] = { AzFramework::ViewportColors::SelectedColor, AzFramework::ViewportColors::HiddenColor }; + const AZ::Color hiddenNormal[] = { AzFramework::ViewportColors::SelectedColor, + AzFramework::ViewportColors::HiddenColor }; AZ::Color boxColor = hiddenNormal[hidden]; const AZ::Color lockedOther[] = { boxColor, AzFramework::ViewportColors::LockColor }; boxColor = lockedOther[locked]; @@ -3470,8 +3338,7 @@ namespace AzToolsFramework debugDisplay.DepthWriteOn(); debugDisplay.DepthTestOn(); - if (ShowingGrid(viewportInfo.m_viewportId) && m_mode == Mode::Translation && - !ComponentModeFramework::InComponentMode()) + if (ShowingGrid(viewportInfo.m_viewportId) && m_mode == Mode::Translation && !ComponentModeFramework::InComponentMode()) { const GridSnapParameters gridSnapParams = GridSnapSettings(viewportInfo.m_viewportId); if (gridSnapParams.m_gridSnap && m_entityIdManipulators.m_manipulators) @@ -3491,11 +3358,11 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators->PerformingAction()) { - const float adjustedLineLength = 2.0f * - CalculateScreenToWorldMultiplier(m_axisPreview.m_translation, cameraState); + const float adjustedLineLength = 2.0f * CalculateScreenToWorldMultiplier(m_axisPreview.m_translation, cameraState); - DrawPreviewAxis(debugDisplay, AZ::Transform::CreateFromQuaternionAndTranslation( - m_axisPreview.m_orientation, m_axisPreview.m_translation), + DrawPreviewAxis( + debugDisplay, + AZ::Transform::CreateFromQuaternionAndTranslation(m_axisPreview.m_orientation, m_axisPreview.m_translation), adjustedLineLength, cameraState); } } @@ -3503,20 +3370,17 @@ namespace AzToolsFramework m_boxSelect.DisplayScene(viewportInfo, debugDisplay); } - static void DrawAxisGizmo( - const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) + static void DrawAxisGizmo(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { // get the editor cameras current orientation const int viewportId = viewportInfo.m_viewportId; const AzFramework::CameraState editorCameraState = GetCameraState(viewportId); - const AZ::Matrix3x3& editorCameraOrientation = - AZ::Matrix3x3::CreateFromMatrix4x4(AzFramework::CameraTransform(editorCameraState)); + const AZ::Matrix3x3& editorCameraOrientation = AZ::Matrix3x3::CreateFromMatrix4x4(AzFramework::CameraTransform(editorCameraState)); // create a gizmo camera transform about the origin matching the orientation of the editor camera // (10 units back in the y axis to produce an orbit effect) const AZ::Transform gizmoCameraOffset = AZ::Transform::CreateTranslation(AZ::Vector3::CreateAxisY(10.0f)); - const AZ::Transform gizmoCameraTransform = - AZ::Transform::CreateFromMatrix3x3(editorCameraOrientation) * gizmoCameraOffset; + const AZ::Transform gizmoCameraTransform = AZ::Transform::CreateFromMatrix3x3(editorCameraOrientation) * gizmoCameraOffset; const AzFramework::CameraState gizmoCameraState = AzFramework::CreateDefaultCamera(gizmoCameraTransform, editorCameraState.m_viewportSize); @@ -3529,16 +3393,9 @@ namespace AzToolsFramework // map from a position in world space (relative to the the gizmo camera near the origin) to a position in // screen space - const auto calculateGizmoAxis = - [&cameraView, &cameraProjection, &screenOffset] - (const AZ::Vector3& axis) + const auto calculateGizmoAxis = [&cameraView, &cameraProjection, &screenOffset](const AZ::Vector3& axis) { - auto result = AZ::Vector2( - AzFramework::WorldToScreenNDC( - axis, - cameraView, - cameraProjection) - ); + auto result = AZ::Vector2(AzFramework::WorldToScreenNDC(axis, cameraView, cameraProjection)); result.SetY(1.0f - result.GetY()); return result + screenOffset; }; @@ -3552,7 +3409,7 @@ namespace AzToolsFramework const AZ::Vector2 gizmoAxisX = gizmoEndAxisX - gizmoStart; const AZ::Vector2 gizmoAxisY = gizmoEndAxisY - gizmoStart; - const AZ::Vector2 gizmoAxisZ = gizmoEndAxisZ - gizmoStart; + const AZ::Vector2 gizmoAxisZ = gizmoEndAxisZ - gizmoStart; // draw the axes of the gizmo debugDisplay.SetLineWidth(cl_viewportGizmoAxisLineWidth); @@ -3579,8 +3436,7 @@ namespace AzToolsFramework } void EditorTransformComponentSelection::DisplayViewportSelection2d( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) + const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -3595,8 +3451,7 @@ namespace AzToolsFramework // check what the 'authoritative' selected entity ids are after an undo/redo EntityIdList selectedEntityIds; - ToolsApplicationRequests::Bus::BroadcastResult( - selectedEntityIds, &ToolsApplicationRequests::GetSelectedEntities); + ToolsApplicationRequests::Bus::BroadcastResult(selectedEntityIds, &ToolsApplicationRequests::GetSelectedEntities); RefreshSelectedEntityIds(selectedEntityIds); } @@ -3614,9 +3469,7 @@ namespace AzToolsFramework // update selected entityId set m_selectedEntityIds.clear(); m_selectedEntityIds.reserve(selectedEntityIds.size()); - AZStd::copy( - selectedEntityIds.begin(), selectedEntityIds.end(), - AZStd::inserter(m_selectedEntityIds, m_selectedEntityIds.end())); + AZStd::copy(selectedEntityIds.begin(), selectedEntityIds.end(), AZStd::inserter(m_selectedEntityIds, m_selectedEntityIds.end())); } void EditorTransformComponentSelection::OnTransformChanged( @@ -3690,8 +3543,7 @@ namespace AzToolsFramework m_selectedEntityIdsAndManipulatorsDirty = true; } - void EditorTransformComponentSelection::EnteredComponentMode( - const AZStd::vector& /*componentModeTypes*/) + void EditorTransformComponentSelection::EnteredComponentMode(const AZStd::vector& /*componentModeTypes*/) { SetViewportUiClusterVisible(m_transformModeClusterId, false); @@ -3700,8 +3552,7 @@ namespace AzToolsFramework ToolsApplicationNotificationBus::Handler::BusDisconnect(); } - void EditorTransformComponentSelection::LeftComponentMode( - const AZStd::vector& /*componentModeTypes*/) + void EditorTransformComponentSelection::LeftComponentMode(const AZStd::vector& /*componentModeTypes*/) { SetViewportUiClusterVisible(m_transformModeClusterId, true); @@ -3714,8 +3565,8 @@ namespace AzToolsFramework { if (m_entityIdManipulators.m_manipulators) { - auto manipulatorCommand = AZStd::make_unique( - CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); manipulatorCommand->SetManipulatorAfter(EntityManipulatorCommand::State()); @@ -3734,32 +3585,27 @@ namespace AzToolsFramework return {}; } - void EditorTransformComponentSelection::SetEntityWorldTranslation( - const AZ::EntityId entityId, const AZ::Vector3& worldTranslation) + void EditorTransformComponentSelection::SetEntityWorldTranslation(const AZ::EntityId entityId, const AZ::Vector3& worldTranslation) { ETCS::SetEntityWorldTranslation(entityId, worldTranslation, m_transformChangedInternally); } - void EditorTransformComponentSelection::SetEntityLocalTranslation( - const AZ::EntityId entityId, const AZ::Vector3& localTranslation) + void EditorTransformComponentSelection::SetEntityLocalTranslation(const AZ::EntityId entityId, const AZ::Vector3& localTranslation) { ETCS::SetEntityLocalTranslation(entityId, localTranslation, m_transformChangedInternally); } - void EditorTransformComponentSelection::SetEntityWorldTransform( - const AZ::EntityId entityId, const AZ::Transform& worldTransform) + void EditorTransformComponentSelection::SetEntityWorldTransform(const AZ::EntityId entityId, const AZ::Transform& worldTransform) { ETCS::SetEntityWorldTransform(entityId, worldTransform, m_transformChangedInternally); } - void EditorTransformComponentSelection::SetEntityLocalScale( - const AZ::EntityId entityId, const float localScale) + void EditorTransformComponentSelection::SetEntityLocalScale(const AZ::EntityId entityId, const float localScale) { ETCS::SetEntityLocalScale(entityId, localScale, m_transformChangedInternally); } - void EditorTransformComponentSelection::SetEntityLocalRotation( - const AZ::EntityId entityId, const AZ::Vector3& localRotation) + void EditorTransformComponentSelection::SetEntityLocalRotation(const AZ::EntityId entityId, const AZ::Vector3& localRotation) { ETCS::SetEntityLocalRotation(entityId, localRotation, m_transformChangedInternally); } @@ -3788,44 +3634,37 @@ namespace AzToolsFramework void SetEntityWorldTranslation(AZ::EntityId entityId, const AZ::Vector3& worldTranslation, bool& internal) { ScopeSwitch sw(internal); - AZ::TransformBus::Event( - entityId, &AZ::TransformBus::Events::SetWorldTranslation, worldTranslation); + AZ::TransformBus::Event(entityId, &AZ::TransformBus::Events::SetWorldTranslation, worldTranslation); } void SetEntityLocalTranslation(AZ::EntityId entityId, const AZ::Vector3& localTranslation, bool& internal) { ScopeSwitch sw(internal); - AZ::TransformBus::Event( - entityId, &AZ::TransformBus::Events::SetLocalTranslation, localTranslation); + AZ::TransformBus::Event(entityId, &AZ::TransformBus::Events::SetLocalTranslation, localTranslation); } void SetEntityWorldTransform(AZ::EntityId entityId, const AZ::Transform& worldTransform, bool& internal) { ScopeSwitch sw(internal); - AZ::TransformBus::Event( - entityId, &AZ::TransformBus::Events::SetWorldTM, worldTransform); + AZ::TransformBus::Event(entityId, &AZ::TransformBus::Events::SetWorldTM, worldTransform); } void SetEntityLocalScale(AZ::EntityId entityId, float localScale, bool& internal) { ScopeSwitch sw(internal); - AZ::TransformBus::Event( - entityId, &AZ::TransformBus::Events::SetLocalUniformScale, localScale); + AZ::TransformBus::Event(entityId, &AZ::TransformBus::Events::SetLocalUniformScale, localScale); } void SetEntityLocalRotation(AZ::EntityId entityId, const AZ::Vector3& localRotation, bool& internal) { ScopeSwitch sw(internal); - AZ::TransformBus::Event( - entityId, &AZ::TransformBus::Events::SetLocalRotation, localRotation); + AZ::TransformBus::Event(entityId, &AZ::TransformBus::Events::SetLocalRotation, localRotation); } } // namespace ETCS // explicit instantiations - template ETCS::PivotOrientationResult - ETCS::CalculatePivotOrientationForEntityIds( - const EntityIdManipulatorLookups&, ReferenceFrame); - template ETCS::PivotOrientationResult - ETCS::CalculateSelectionPivotOrientation( - const EntityIdManipulatorLookups&, const OptionalFrame&, const ReferenceFrame referenceFrame); + template ETCS::PivotOrientationResult ETCS::CalculatePivotOrientationForEntityIds( + const EntityIdManipulatorLookups&, ReferenceFrame); + template ETCS::PivotOrientationResult ETCS::CalculateSelectionPivotOrientation( + const EntityIdManipulatorLookups&, const OptionalFrame&, const ReferenceFrame referenceFrame); } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.cpp index 9ca20068ed..8cd19b8d2d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.cpp @@ -1,17 +1,17 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ -#include #include "EditorTransformComponentSelectionRequestBus.h" +#include namespace AzToolsFramework { @@ -19,50 +19,68 @@ namespace AzToolsFramework { if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - #define TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests() \ - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) \ - ->Attribute(AZ::Script::Attributes::Category, "Editor") \ - ->Attribute(AZ::Script::Attributes::Module, "editor") +#define TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests() \ + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) \ + ->Attribute(AZ::Script::Attributes::Category, "Editor") \ + ->Attribute(AZ::Script::Attributes::Module, "editor") - behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::Mode::Rotation)>("TransformMode_Rotation") - TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); - behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::Mode::Translation)>("TransformMode_Translation") - TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); + behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::Mode::Rotation)>( + "TransformMode_Rotation") TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); + behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::Mode::Translation)>( + "TransformMode_Translation") TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::Mode::Scale)>("TransformMode_Scale") TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); - behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::RefreshType::Translation)>("TransformRefreshType_Translation") - TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); - behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::RefreshType::Orientation)>("TransformRefreshType_Orientation") - TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); - behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::RefreshType::All)>("TransformRefreshType_All") - TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); + behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::RefreshType::Translation)>( + "TransformRefreshType_Translation") TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); + behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::RefreshType::Orientation)>( + "TransformRefreshType_Orientation") TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); + behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::RefreshType::All)>( + "TransformRefreshType_All") TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); - behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::Pivot::Object)>("TransformPivot_Object") - TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); - behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::Pivot::Center)>("TransformPivot_Center") - TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); + behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::Pivot::Object)>( + "TransformPivot_Object") TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); + behaviorContext->EnumProperty(EditorTransformComponentSelectionRequests::Pivot::Center)>( + "TransformPivot_Center") TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests(); - behaviorContext->EBus("EditorTransformComponentSelectionRequestBus") - TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests() + behaviorContext + ->EBus("EditorTransformComponentSelectionRequestBus") + TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests() ->Event("SetTransformMode", &EditorTransformComponentSelectionRequestBus::Events::SetTransformMode) ->Event("GetTransformMode", &EditorTransformComponentSelectionRequestBus::Events::GetTransformMode) // Reflecting GetManipulatorTransform will require hash to be implemented, a pending task. //->Event("GetManipulatorTransform", &EditorTransformComponentSelectionRequestBus::Events::GetManipulatorTransform) ->Event("RefreshManipulators", &EditorTransformComponentSelectionRequestBus::Events::RefreshManipulators) - ->Event("OverrideManipulatorOrientation", &EditorTransformComponentSelectionRequestBus::Events::OverrideManipulatorOrientation) - ->Event("OverrideManipulatorTranslation", &EditorTransformComponentSelectionRequestBus::Events::OverrideManipulatorTranslation) - ->Event("CopyTranslationToSelectedEntitiesIndividual", &EditorTransformComponentSelectionRequestBus::Events::CopyTranslationToSelectedEntitiesIndividual) - ->Event("CopyTranslationToSelectedEntitiesGroup", &EditorTransformComponentSelectionRequestBus::Events::CopyTranslationToSelectedEntitiesGroup) - ->Event("ResetTranslationForSelectedEntitiesLocal", &EditorTransformComponentSelectionRequestBus::Events::ResetTranslationForSelectedEntitiesLocal) - ->Event("CopyOrientationToSelectedEntitiesIndividual", &EditorTransformComponentSelectionRequestBus::Events::CopyOrientationToSelectedEntitiesIndividual) - ->Event("CopyOrientationToSelectedEntitiesGroup", &EditorTransformComponentSelectionRequestBus::Events::CopyOrientationToSelectedEntitiesGroup) - ->Event("ResetOrientationForSelectedEntitiesLocal", &EditorTransformComponentSelectionRequestBus::Events::ResetOrientationForSelectedEntitiesLocal) - ->Event("CopyScaleToSelectedEntitiesIndividualLocal", &EditorTransformComponentSelectionRequestBus::Events::CopyScaleToSelectedEntitiesIndividualLocal) - ->Event("CopyScaleToSelectedEntitiesIndividualWorld", &EditorTransformComponentSelectionRequestBus::Events::CopyScaleToSelectedEntitiesIndividualWorld) - ; + ->Event( + "OverrideManipulatorOrientation", &EditorTransformComponentSelectionRequestBus::Events::OverrideManipulatorOrientation) + ->Event( + "OverrideManipulatorTranslation", &EditorTransformComponentSelectionRequestBus::Events::OverrideManipulatorTranslation) + ->Event( + "CopyTranslationToSelectedEntitiesIndividual", + &EditorTransformComponentSelectionRequestBus::Events::CopyTranslationToSelectedEntitiesIndividual) + ->Event( + "CopyTranslationToSelectedEntitiesGroup", + &EditorTransformComponentSelectionRequestBus::Events::CopyTranslationToSelectedEntitiesGroup) + ->Event( + "ResetTranslationForSelectedEntitiesLocal", + &EditorTransformComponentSelectionRequestBus::Events::ResetTranslationForSelectedEntitiesLocal) + ->Event( + "CopyOrientationToSelectedEntitiesIndividual", + &EditorTransformComponentSelectionRequestBus::Events::CopyOrientationToSelectedEntitiesIndividual) + ->Event( + "CopyOrientationToSelectedEntitiesGroup", + &EditorTransformComponentSelectionRequestBus::Events::CopyOrientationToSelectedEntitiesGroup) + ->Event( + "ResetOrientationForSelectedEntitiesLocal", + &EditorTransformComponentSelectionRequestBus::Events::ResetOrientationForSelectedEntitiesLocal) + ->Event( + "CopyScaleToSelectedEntitiesIndividualLocal", + &EditorTransformComponentSelectionRequestBus::Events::CopyScaleToSelectedEntitiesIndividualLocal) + ->Event( + "CopyScaleToSelectedEntitiesIndividualWorld", + &EditorTransformComponentSelectionRequestBus::Events::CopyScaleToSelectedEntitiesIndividualWorld); - #undef TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests +#undef TEMP_SET_ATTRIBUTES_FOR_EditorTransformComponentSelectionRequests } } } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.h index 9cd78f8c50..966f9333fc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -16,12 +16,10 @@ #include #include - namespace AzToolsFramework { - /// Provide interface for EditorTransformComponentSelection requests. - class EditorTransformComponentSelectionRequests - : public AZ::EBusTraits + //! Provide interface for EditorTransformComponentSelection requests. + class EditorTransformComponentSelectionRequests : public AZ::EBusTraits { public: using BusIdType = AzFramework::EntityContextId; @@ -30,7 +28,7 @@ namespace AzToolsFramework static void Reflect(AZ::ReflectContext* context); - /// What type of transform editing are we in. + //! What type of transform editing are we in. enum class Mode { // note: ordering of these is important - do not change. @@ -40,7 +38,7 @@ namespace AzToolsFramework Scale }; - /// Specify the type of refresh (what type of transform modification caused the refresh). + //! Specify the type of refresh (what type of transform modification caused the refresh). enum class RefreshType { Translation, @@ -48,69 +46,69 @@ namespace AzToolsFramework All }; - /// How is the pivot aligned (object/authored position or center). + //! How is the pivot aligned (object/authored position or center). enum class Pivot { Object, Center }; - /// Set what kind of transform the type that implements this bus should use. + //! Set what kind of transform the type that implements this bus should use. virtual void SetTransformMode(Mode mode) = 0; - /// Return what transform mode the type that implements this bus is using. + //! Return what transform mode the type that implements this bus is using. virtual Mode GetTransformMode() = 0; - /// Return the current Entity Manipulator transform. - /// An AZStd::optional is returned as if we do not have a selection - /// there will be no Manipulator present. In this case we return an empty optional. + //! Return the current Entity Manipulator transform. + //! An AZStd::optional is returned as if we do not have a selection + //! there will be no Manipulator present. In this case we return an empty optional. virtual AZStd::optional GetManipulatorTransform() = 0; - /// Refresh the Manipulator based on the current entity selection. - /// This may be useful if the Entity transform has been set outside - /// of the EditorTransformComponentSelection and we want to make sure the - /// Manipulator stays up to date (in sync) with the current Entity transform. + //! Refresh the Manipulator based on the current entity selection. + //! This may be useful if the Entity transform has been set outside + //! of the EditorTransformComponentSelection and we want to make sure the + //! Manipulator stays up to date (in sync) with the current Entity transform. virtual void RefreshManipulators(RefreshType refreshType) = 0; - /// Set an orientation override for the Manipulator. - /// Useful if we've picked another Entity transform to use as our reference point. + //! Set an orientation override for the Manipulator. + //! Useful if we've picked another Entity transform to use as our reference point. virtual void OverrideManipulatorOrientation(const AZ::Quaternion& orientation) = 0; - /// Set a translation override for the Manipulator. - /// Useful if we've picked another Entity transform to use as our reference point. + //! Set a translation override for the Manipulator. + //! Useful if we've picked another Entity transform to use as our reference point. virtual void OverrideManipulatorTranslation(const AZ::Vector3& translation) = 0; - /// Copy translation to each individual entity so they all appear in the exact same position. + //! Copy translation to each individual entity so they all appear in the exact same position. virtual void CopyTranslationToSelectedEntitiesIndividual(const AZ::Vector3& translation) = 0; - /// Copy translation to manipulator position with each entity keeping the same relative position as before. + //! Copy translation to manipulator position with each entity keeping the same relative position as before. virtual void CopyTranslationToSelectedEntitiesGroup(const AZ::Vector3& translation) = 0; - /// Reset the translation of an entity to the same position as its parent. - /// Note: This is a noop if the entity does not have a parent. + //! Reset the translation of an entity to the same position as its parent. + //! Note: This is a noop if the entity does not have a parent. virtual void ResetTranslationForSelectedEntitiesLocal() = 0; - /// Copy orientation to each individual entity so they all appear in the exact same orientation. + //! Copy orientation to each individual entity so they all appear in the exact same orientation. virtual void CopyOrientationToSelectedEntitiesIndividual(const AZ::Quaternion& orientation) = 0; - /// Copy orientation to manipulator with each entity keeping the same relative orientation as before. + //! Copy orientation to manipulator with each entity keeping the same relative orientation as before. virtual void CopyOrientationToSelectedEntitiesGroup(const AZ::Quaternion& orientation) = 0; - /// Reset the orientation of an entity to the same orientation as its parent. - /// Note: This will be the aligned to the world axes (identity) if the entity does not have a parent. + //! Reset the orientation of an entity to the same orientation as its parent. + //! Note: This will be the aligned to the world axes (identity) if the entity does not have a parent. virtual void ResetOrientationForSelectedEntitiesLocal() = 0; - /// Copy scale to each individual entity in local space without moving position. + //! Copy scale to each individual entity in local space without moving position. virtual void CopyScaleToSelectedEntitiesIndividualLocal(float scale) = 0; - /// Copy scale to to each individual entity in world (absolute) space. + //! Copy scale to to each individual entity in world (absolute) space. virtual void CopyScaleToSelectedEntitiesIndividualWorld(float scale) = 0; protected: ~EditorTransformComponentSelectionRequests() = default; }; - /// Type to inherit to implement EditorTransformComponentSelectionRequests. + //! Type to inherit to implement EditorTransformComponentSelectionRequests. using EditorTransformComponentSelectionRequestBus = AZ::EBus; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp index 253c27fe02..0e066684d2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp @@ -1,33 +1,31 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "EditorVisibleEntityDataCache.h" #include +#include #include #include -#include namespace AzToolsFramework { - /// Cached Entity data required by the selection. + //! Cached Entity data required by the selection. struct EntityData final { using ComponentEntityAccentType = Components::EditorSelectionAccentSystemComponent::ComponentEntityAccentType; EntityData() = default; - EntityData( - AZ::EntityId entityId, const AZ::Transform& worldFromLocal, - bool locked, bool visible, bool selected, bool iconHidden); + EntityData(AZ::EntityId entityId, const AZ::Transform& worldFromLocal, bool locked, bool visible, bool selected, bool iconHidden); AZ::Transform m_worldFromLocal; AZ::EntityId m_entityId; @@ -38,7 +36,7 @@ namespace AzToolsFramework bool m_iconHidden = false; }; - using EntityDatas = AZStd::vector; ///< Alias for vector of EntityDatas. + using EntityDatas = AZStd::vector; //!< Alias for vector of EntityDatas. // Predicate to sort EntityIds with EntityDatas interchangeably. struct EntityDataComparer @@ -52,18 +50,27 @@ namespace AzToolsFramework class EditorVisibleEntityDataCache::EditorVisibleEntityDataCacheImpl { public: - EntityIdList m_visibleEntityIds; ///< The EntityIds that are visible this frame. - EntityIdList m_prevVisibleEntityIds; ///< The EntityIds that were visible the previous frame (unsorted). - EntityDatas m_visibleEntityDatas; ///< Cached EntityData required by EditorTransformComponentSelection. + EntityIdList m_visibleEntityIds; //!< The EntityIds that are visible this frame. + EntityIdList m_prevVisibleEntityIds; //!< The EntityIds that were visible the previous frame (unsorted). + EntityDatas m_visibleEntityDatas; //!< Cached EntityData required by EditorTransformComponentSelection. }; // constructor for EntityData to support emplace_back in vector EntityData::EntityData( - const AZ::EntityId entityId, const AZ::Transform& worldFromLocal, - const bool locked, const bool visible, const bool selected, const bool iconHidden) - : m_worldFromLocal(worldFromLocal), m_entityId(entityId) - , m_locked(locked), m_visible(visible), m_selected(selected) - , m_iconHidden(iconHidden) {} + const AZ::EntityId entityId, + const AZ::Transform& worldFromLocal, + const bool locked, + const bool visible, + const bool selected, + const bool iconHidden) + : m_worldFromLocal(worldFromLocal) + , m_entityId(entityId) + , m_locked(locked) + , m_visible(visible) + , m_selected(selected) + , m_iconHidden(iconHidden) + { + } bool EntityDataComparer::operator()(const AZ::EntityId lhs, const EntityData& rhs) const { @@ -98,20 +105,17 @@ namespace AzToolsFramework static EntityData EntityDataFromEntityId(const AZ::EntityId entityId) { bool visible = false; - EditorEntityInfoRequestBus::EventResult( - visible, entityId, &EditorEntityInfoRequestBus::Events::IsVisible); + EditorEntityInfoRequestBus::EventResult(visible, entityId, &EditorEntityInfoRequestBus::Events::IsVisible); bool locked = false; - EditorEntityInfoRequestBus::EventResult( - locked, entityId, &EditorEntityInfoRequestBus::Events::IsLocked); + EditorEntityInfoRequestBus::EventResult(locked, entityId, &EditorEntityInfoRequestBus::Events::IsLocked); bool iconHidden = false; EditorEntityIconComponentRequestBus::EventResult( iconHidden, entityId, &EditorEntityIconComponentRequests::IsEntityIconHiddenInViewport); AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); return { entityId, worldFromLocal, locked, visible, IsSelected(entityId), iconHidden }; } @@ -155,16 +159,14 @@ namespace AzToolsFramework AZStd::sort(m_impl->m_visibleEntityDatas.begin(), m_impl->m_visibleEntityDatas.end()); } - void EditorVisibleEntityDataCache::CalculateVisibleEntityDatas( - const AzFramework::ViewportInfo& viewportInfo) + void EditorVisibleEntityDataCache::CalculateVisibleEntityDatas(const AzFramework::ViewportInfo& viewportInfo) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); // request list of visible entities from authoritative system EntityIdList nextVisibleEntityIds; ViewportInteraction::MainEditorViewportInteractionRequestBus::Event( - viewportInfo.m_viewportId, - &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::FindVisibleEntities, + viewportInfo.m_viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::FindVisibleEntities, nextVisibleEntityIds); // only bother resorting if we know the lists have changed @@ -181,31 +183,26 @@ namespace AzToolsFramework // find entities that are visible this frame but weren't last frame AZStd::vector added; std::set_difference( - m_impl->m_visibleEntityIds.begin(), m_impl->m_visibleEntityIds.end(), - m_impl->m_visibleEntityDatas.begin(), m_impl->m_visibleEntityDatas.end(), - std::back_inserter(added), EntityDataComparer()); + m_impl->m_visibleEntityIds.begin(), m_impl->m_visibleEntityIds.end(), m_impl->m_visibleEntityDatas.begin(), + m_impl->m_visibleEntityDatas.end(), std::back_inserter(added), EntityDataComparer()); // find entities that are not visible this frame but were last frame AZStd::vector removed; std::set_difference( - m_impl->m_visibleEntityDatas.begin(), m_impl->m_visibleEntityDatas.end(), - m_impl->m_visibleEntityIds.begin(), m_impl->m_visibleEntityIds.end(), - std::back_inserter(removed), EntityDataComparer()); + m_impl->m_visibleEntityDatas.begin(), m_impl->m_visibleEntityDatas.end(), m_impl->m_visibleEntityIds.begin(), + m_impl->m_visibleEntityIds.end(), std::back_inserter(removed), EntityDataComparer()); // search for entityData in removed list, return true if it is found const auto removePredicate = [&removed](const EntityData& entityData) { - const auto removeIt = std::equal_range( - removed.begin(), removed.end(), entityData); + const auto removeIt = std::equal_range(removed.begin(), removed.end(), entityData); return removeIt.first != removeIt.second; }; // erase-remove idiom - bubble entities to be removed to the end, then erase them in one go m_impl->m_visibleEntityDatas.erase( - AZStd::remove_if( - m_impl->m_visibleEntityDatas.begin(), - m_impl->m_visibleEntityDatas.end(), removePredicate), + AZStd::remove_if(m_impl->m_visibleEntityDatas.begin(), m_impl->m_visibleEntityDatas.end(), removePredicate), m_impl->m_visibleEntityDatas.end()); // for newly added entities, request their initial state when first cached @@ -240,8 +237,7 @@ namespace AzToolsFramework return m_impl->m_visibleEntityDatas[index].m_entityId; } - EditorVisibleEntityDataCache::ComponentEntityAccentType EditorVisibleEntityDataCache::GetVisibleEntityAccent( - const size_t index) const + EditorVisibleEntityDataCache::ComponentEntityAccentType EditorVisibleEntityDataCache::GetVisibleEntityAccent(const size_t index) const { return m_impl->m_visibleEntityDatas[index].m_accent; } @@ -273,8 +269,8 @@ namespace AzToolsFramework AZStd::optional EditorVisibleEntityDataCache::GetVisibleEntityIndexFromId(const AZ::EntityId entityId) const { - const auto entityIdIt = std::equal_range( - m_impl->m_visibleEntityDatas.begin(), m_impl->m_visibleEntityDatas.end(), entityId, EntityDataComparer()); + const auto entityIdIt = + std::equal_range(m_impl->m_visibleEntityDatas.begin(), m_impl->m_visibleEntityDatas.end(), entityId, EntityDataComparer()); if (entityIdIt.first != entityIdIt.second) { @@ -318,8 +314,7 @@ namespace AzToolsFramework } } - void EditorVisibleEntityDataCache::OnTransformChanged( - const AZ::Transform& /*local*/, const AZ::Transform& world) + void EditorVisibleEntityDataCache::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -367,8 +362,7 @@ namespace AzToolsFramework } } - void EditorVisibleEntityDataCache::OnEntityIconChanged( - const AZ::Data::AssetId& /*entityIconAssetId*/) + void EditorVisibleEntityDataCache::OnEntityIconChanged(const AZ::Data::AssetId& /*entityIconAssetId*/) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h index 72c1595e7b..0d74825bf8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h @@ -1,14 +1,14 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #pragma once @@ -22,8 +22,8 @@ namespace AzToolsFramework { - /// A cache of packed EntityData that can be iterated over efficiently without - /// the need to make individual EBus calls + //! A cache of packed EntityData that can be iterated over efficiently without + //! the need to make individual EBus calls class EditorVisibleEntityDataCache : private EditorEntityVisibilityNotificationBus::Router , private EditorEntityLockComponentNotificationBus::Router @@ -45,7 +45,7 @@ namespace AzToolsFramework void CalculateVisibleEntityDatas(const AzFramework::ViewportInfo& viewportInfo); - /// EditorVisibleEntityDataCache interface + //! EditorVisibleEntityDataCache interface size_t VisibleEntityDataCount() const; AZ::Vector3 GetVisibleEntityPosition(size_t index) const; const AZ::Transform& GetVisibleEntityTransform(size_t index) const; @@ -72,8 +72,7 @@ namespace AzToolsFramework void OnEntityLockChanged(bool locked) override; // TransformNotificationBus - void OnTransformChanged( - const AZ::Transform& local, const AZ::Transform& world) override; + void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; // EditorComponentSelectionNotificationsBus void OnAccentTypeChanged(EntityAccentType accent) override; @@ -86,6 +85,6 @@ namespace AzToolsFramework void OnEntityIconChanged(const AZ::Data::AssetId& entityIconAssetId) override; class EditorVisibleEntityDataCacheImpl; - AZStd::unique_ptr m_impl; ///< Internal representation of entity data cache. + AZStd::unique_ptr m_impl; //!< Internal representation of entity data cache. }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/Tests/ComponentModeTests.cpp b/Code/Framework/AzToolsFramework/Tests/ComponentModeTests.cpp index a4ee80fa5f..45699ddb78 100644 --- a/Code/Framework/AzToolsFramework/Tests/ComponentModeTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/ComponentModeTests.cpp @@ -1,30 +1,31 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ #include "ComponentModeTestDoubles.h" #include "ComponentModeTestFixture.h" #include +#include #include #include #include -#include #include +#include #include #include #include #include -#include #include +#include #include #include #include @@ -32,7 +33,6 @@ #include #include #include -#include #include namespace UnitTest @@ -47,19 +47,16 @@ namespace UnitTest /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Given QWidget rootWidget; - ActionOverrideRequestBus::Event( - GetEntityContextId(), &ActionOverrideRequests::SetupActionOverrideHandler, &rootWidget); + ActionOverrideRequestBus::Event(GetEntityContextId(), &ActionOverrideRequests::SetupActionOverrideHandler, &rootWidget); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // When ComponentModeSystemRequestBus::Broadcast( - &ComponentModeSystemRequests::BeginComponentMode, - AZStd::vector{}); + &ComponentModeSystemRequests::BeginComponentMode, AZStd::vector{}); bool inComponentMode = false; - ComponentModeSystemRequestBus::BroadcastResult( - inComponentMode, &ComponentModeSystemRequests::InComponentMode); + ComponentModeSystemRequestBus::BroadcastResult(inComponentMode, &ComponentModeSystemRequests::InComponentMode); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -69,11 +66,9 @@ namespace UnitTest /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // When - ComponentModeSystemRequestBus::Broadcast( - &ComponentModeSystemRequests::EndComponentMode); + ComponentModeSystemRequestBus::Broadcast(&ComponentModeSystemRequests::EndComponentMode); - ComponentModeSystemRequestBus::BroadcastResult( - inComponentMode, &ComponentModeSystemRequests::InComponentMode); + ComponentModeSystemRequestBus::BroadcastResult(inComponentMode, &ComponentModeSystemRequests::InComponentMode); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -81,8 +76,7 @@ namespace UnitTest EXPECT_FALSE(inComponentMode); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - ActionOverrideRequestBus::Event( - GetEntityContextId(), &ActionOverrideRequests::TeardownActionOverrideHandler); + ActionOverrideRequestBus::Event(GetEntityContextId(), &ActionOverrideRequests::TeardownActionOverrideHandler); } TEST_F(ComponentModeTestFixture, TwoComponentsOnSingleEntityWithSameComponentModeBothBegin) @@ -104,8 +98,7 @@ namespace UnitTest // mimic selecting the entity in the viewport (after selection the ComponentModeDelegate // connects to the ComponentModeDelegateRequestBus on the entity/component pair address) const AzToolsFramework::EntityIdList entityIds = { entityId }; - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetSelectedEntities, entityIds); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, entityIds); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -113,8 +106,7 @@ namespace UnitTest // move all selected components into ComponentMode // (mimic pressing the 'Edit' button to begin Component Mode) ComponentModeSystemRequestBus::Broadcast( - &ComponentModeSystemRequests::AddSelectedComponentModesOfType, - AZ::AzTypeInfo::Uuid()); + &ComponentModeSystemRequests::AddSelectedComponentModesOfType, AZ::AzTypeInfo::Uuid()); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -152,8 +144,7 @@ namespace UnitTest // mimic selecting the entity in the viewport (after selection the ComponentModeDelegate // connects to the ComponentModeDelegateRequestBus on the entity/component pair address) const AzToolsFramework::EntityIdList entityIds = { entityId }; - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetSelectedEntities, entityIds); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, entityIds); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -161,8 +152,7 @@ namespace UnitTest // move all selected components into ComponentMode // (mimic pressing the 'Edit' button to begin Component Mode) ComponentModeSystemRequestBus::Broadcast( - &ComponentModeSystemRequests::AddSelectedComponentModesOfType, - AZ::AzTypeInfo::Uuid()); + &ComponentModeSystemRequests::AddSelectedComponentModesOfType, AZ::AzTypeInfo::Uuid()); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -202,8 +192,7 @@ namespace UnitTest // mimic selecting the entity in the viewport (after selection the ComponentModeDelegate // connects to the ComponentModeDelegateRequestBus on the entity/component pair address) const AzToolsFramework::EntityIdList entityIds = { entityId }; - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetSelectedEntities, entityIds); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, entityIds); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -211,16 +200,13 @@ namespace UnitTest // move all selected components into ComponentMode // (mimic pressing the 'Edit' button to begin Component Mode) ComponentModeSystemRequestBus::Broadcast( - &ComponentModeSystemRequests::AddSelectedComponentModesOfType, - AZ::AzTypeInfo::Uuid()); + &ComponentModeSystemRequests::AddSelectedComponentModesOfType, AZ::AzTypeInfo::Uuid()); bool nextModeCycled = true; - ComponentModeSystemRequestBus::BroadcastResult( - nextModeCycled, &ComponentModeSystemRequests::SelectNextActiveComponentMode); + ComponentModeSystemRequestBus::BroadcastResult(nextModeCycled, &ComponentModeSystemRequests::SelectNextActiveComponentMode); bool previousModeCycled = true; - ComponentModeSystemRequestBus::BroadcastResult( - previousModeCycled, &ComponentModeSystemRequests::SelectPreviousActiveComponentMode); + ComponentModeSystemRequestBus::BroadcastResult(previousModeCycled, &ComponentModeSystemRequests::SelectPreviousActiveComponentMode); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -250,8 +236,7 @@ namespace UnitTest // mimic selecting the entity in the viewport (after selection the ComponentModeDelegate // connects to the ComponentModeDelegateRequestBus on the entity/component pair address) const AzToolsFramework::EntityIdList entityIds = { entityId }; - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetSelectedEntities, entityIds); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, entityIds); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -259,15 +244,13 @@ namespace UnitTest // move all selected components into ComponentMode // (mimic pressing the 'Edit' button to begin Component Mode) ComponentModeSystemRequestBus::Broadcast( - &ComponentModeSystemRequests::AddSelectedComponentModesOfType, - AZ::AzTypeInfo::Uuid()); + &ComponentModeSystemRequests::AddSelectedComponentModesOfType, AZ::AzTypeInfo::Uuid()); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Then bool multipleComponentModeTypes = true; - ComponentModeSystemRequestBus::BroadcastResult( - multipleComponentModeTypes, &ComponentModeSystemRequests::HasMultipleComponentTypes); + ComponentModeSystemRequestBus::BroadcastResult(multipleComponentModeTypes, &ComponentModeSystemRequests::HasMultipleComponentTypes); EXPECT_FALSE(multipleComponentModeTypes); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -294,8 +277,7 @@ namespace UnitTest // mimic selecting the entity in the viewport (after selection the ComponentModeDelegate // connects to the ComponentModeDelegateRequestBus on the entity/component pair address) const AzToolsFramework::EntityIdList entityIds = { entityId }; - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetSelectedEntities, entityIds); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, entityIds); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -303,15 +285,13 @@ namespace UnitTest // move all selected components into ComponentMode // (mimic pressing the 'Edit' button to begin Component Mode) ComponentModeSystemRequestBus::Broadcast( - &ComponentModeSystemRequests::AddSelectedComponentModesOfType, - AZ::AzTypeInfo::Uuid()); + &ComponentModeSystemRequests::AddSelectedComponentModesOfType, AZ::AzTypeInfo::Uuid()); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Then bool multipleComponentModeTypes = true; - ComponentModeSystemRequestBus::BroadcastResult( - multipleComponentModeTypes, &ComponentModeSystemRequests::HasMultipleComponentTypes); + ComponentModeSystemRequestBus::BroadcastResult(multipleComponentModeTypes, &ComponentModeSystemRequests::HasMultipleComponentTypes); EXPECT_FALSE(multipleComponentModeTypes); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -341,8 +321,7 @@ namespace UnitTest // mimic selecting the entity in the viewport (after selection the ComponentModeDelegate // connects to the ComponentModeDelegateRequestBus on the entity/component pair address) const AzToolsFramework::EntityIdList entityIds = { entityId }; - ToolsApplicationRequestBus::Broadcast( - &ToolsApplicationRequests::SetSelectedEntities, entityIds); + ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, entityIds); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -350,15 +329,13 @@ namespace UnitTest // move all selected components into ComponentMode // (mimic pressing the 'Edit' button to begin Component Mode) ComponentModeSystemRequestBus::Broadcast( - &ComponentModeSystemRequests::AddSelectedComponentModesOfType, - AZ::AzTypeInfo::Uuid()); + &ComponentModeSystemRequests::AddSelectedComponentModesOfType, AZ::AzTypeInfo::Uuid()); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Then bool multipleComponentModeTypes = false; - ComponentModeSystemRequestBus::BroadcastResult( - multipleComponentModeTypes, &ComponentModeSystemRequests::HasMultipleComponentTypes); + ComponentModeSystemRequestBus::BroadcastResult(multipleComponentModeTypes, &ComponentModeSystemRequests::HasMultipleComponentTypes); bool secondComponentModeInstantiated = false; ComponentModeSystemRequestBus::BroadcastResult( @@ -366,8 +343,7 @@ namespace UnitTest AZ::EntityComponentIdPair(entityId, placeholder2->GetId())); AZ::Uuid activeComponentType = AZ::Uuid::CreateNull(); - ComponentModeSystemRequestBus::BroadcastResult( - activeComponentType, &ComponentModeSystemRequests::ActiveComponentMode); + ComponentModeSystemRequestBus::BroadcastResult(activeComponentType, &ComponentModeSystemRequests::ActiveComponentMode); EXPECT_TRUE(multipleComponentModeTypes); EXPECT_TRUE(secondComponentModeInstantiated); @@ -412,13 +388,11 @@ namespace UnitTest // Component Mode is will sent the notification to the correct address. ComponentModeActionSignalRequestBus::Event( AZ::EntityComponentIdPair(entityId, placeholder1->GetId()), - &ComponentModeActionSignalRequests::SetComponentModeActionNotificationBusToNotify, - checkerBusId); + &ComponentModeActionSignalRequests::SetComponentModeActionNotificationBusToNotify, checkerBusId); ComponentModeActionSignalRequestBus::Event( AZ::EntityComponentIdPair(entityId, placeholder2->GetId()), - &ComponentModeActionSignalRequests::SetComponentModeActionNotificationBusToNotify, - checkerBusId); + &ComponentModeActionSignalRequests::SetComponentModeActionNotificationBusToNotify, checkerBusId); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -470,8 +444,7 @@ namespace UnitTest using MouseInteractionResult = AzToolsFramework::ViewportInteraction::MouseInteractionResult; MouseInteractionResult handled = MouseInteractionResult::None; EditorInteractionSystemViewportSelectionRequestBus::BroadcastResult( - handled, &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, - interactionEvent); + handled, &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, interactionEvent); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -482,8 +455,7 @@ namespace UnitTest } // Test version of EntityPropertyEditor to detect/ensure certain functions were called - class TestEntityPropertyEditor - : public AzToolsFramework::EntityPropertyEditor + class TestEntityPropertyEditor : public AzToolsFramework::EntityPropertyEditor { public: void InvalidatePropertyDisplay(PropertyModificationRefreshLevel level) override; @@ -496,8 +468,7 @@ namespace UnitTest } // Simple fixture to encapsulate a TestEntityPropertyEditor - class ComponentModePinnedSelectionFixture - : public ToolsApplicationFixture + class ComponentModePinnedSelectionFixture : public ToolsApplicationFixture { public: void SetUpEditorFixtureImpl() override @@ -533,7 +504,7 @@ namespace UnitTest /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // When // select entity - const auto selectedEntities = AzToolsFramework::EntityIdList { entityId }; + const auto selectedEntities = AzToolsFramework::EntityIdList{ entityId }; SelectEntities(selectedEntities); // pin entity @@ -549,8 +520,7 @@ namespace UnitTest EXPECT_TRUE(m_testEntityPropertyEditor->IsLockedToSpecificEntities()); EXPECT_TRUE(m_testEntityPropertyEditor->m_invalidatePropertyDisplayCalled); - bool couldBeginComponentMode = - AzToolsFramework::ComponentModeFramework::CouldBeginComponentModeWithEntity(entityId); + bool couldBeginComponentMode = AzToolsFramework::ComponentModeFramework::CouldBeginComponentModeWithEntity(entityId); EXPECT_FALSE(couldBeginComponentMode); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -566,29 +536,26 @@ namespace UnitTest entity->Deactivate(); AzToolsFramework::EntityCompositionRequestBus::Broadcast( - &AzToolsFramework::EntityCompositionRequestBus::Events::AddComponentsToEntities, - AzToolsFramework::EntityIdList{entityId}, + &AzToolsFramework::EntityCompositionRequestBus::Events::AddComponentsToEntities, AzToolsFramework::EntityIdList{ entityId }, AZ::ComponentTypeList{ AZ::AzTypeInfo::Uuid() }); AzToolsFramework::EntityCompositionRequestBus::Broadcast( - &AzToolsFramework::EntityCompositionRequestBus::Events::AddComponentsToEntities, - AzToolsFramework::EntityIdList{entityId}, - AZ::ComponentTypeList{AZ::AzTypeInfo::Uuid()}); + &AzToolsFramework::EntityCompositionRequestBus::Events::AddComponentsToEntities, AzToolsFramework::EntityIdList{ entityId }, + AZ::ComponentTypeList{ AZ::AzTypeInfo::Uuid() }); entity->Activate(); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // When - SelectEntities(AzToolsFramework::EntityIdList{entityId}); + SelectEntities(AzToolsFramework::EntityIdList{ entityId }); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Then AZ::Entity::ComponentArrayType pendingComponents; AzToolsFramework::EditorPendingCompositionRequestBus::Event( - entityId, &AzToolsFramework::EditorPendingCompositionRequestBus::Events::GetPendingComponents, - pendingComponents); + entityId, &AzToolsFramework::EditorPendingCompositionRequestBus::Events::GetPendingComponents, pendingComponents); // ensure we do have pending components EXPECT_EQ(pendingComponents.size(), 1); From 1a6b6d5bc0e90ac9c2691124f2240e8cfef3123a Mon Sep 17 00:00:00 2001 From: jackalbe <23512001+jackalbe@users.noreply.github.com> Date: Mon, 7 Jun 2021 09:04:37 -0500 Subject: [PATCH 555/811] {LYN-4230} Fixed loading *.pak files in Release builds (#1127) * {LYN-4230} Fixed loading *.pak files in Release builds * Helios - Release mode should load all *.pak files * Tests: made a separate installation folder with a reduced "engine.pak" and a full "game.pak" which loads in release * added unit test to regress the bug fix --- .../AzFramework/Archive/Archive.cpp | 12 +++---- Code/Framework/Tests/ArchiveTests.cpp | 33 +++++++++++++++++++ 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp index 4a80db2b24..04573eb2e5 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp @@ -1681,13 +1681,11 @@ namespace AZ::IO AZStd::vector files; do { - if (AZStd::wildcard_match(pWildcardIn, fileIterator.m_filename)) - { - AZStd::string foundFilename{ fileIterator.m_filename }; - AZStd::to_lower(foundFilename.begin(), foundFilename.end()); - files.emplace_back(AZStd::move(foundFilename)); - } - } while (fileIterator = FindNext(fileIterator)); + AZStd::string foundFilename{ fileIterator.m_filename }; + AZStd::to_lower(foundFilename.begin(), foundFilename.end()); + files.emplace_back(AZStd::move(foundFilename)); + } + while (fileIterator = FindNext(fileIterator)); // Open files in alphabet order. AZStd::sort(files.begin(), files.end()); diff --git a/Code/Framework/Tests/ArchiveTests.cpp b/Code/Framework/Tests/ArchiveTests.cpp index 6dc081ee72..ddc7060083 100644 --- a/Code/Framework/Tests/ArchiveTests.cpp +++ b/Code/Framework/Tests/ArchiveTests.cpp @@ -281,6 +281,39 @@ namespace UnitTest TestFGetCachedFileData(fileInArchiveFile, dataString.size(), dataString.data()); } + TEST_F(ArchiveTestFixture, TestArchiveOpenPacks_FindsMultiplePaks_Works) + { + AZ::IO::IArchive* archive = AZ::Interface::Get(); + ASSERT_NE(nullptr, archive); + + AZ::IO::FileIOBase* fileIo = AZ::IO::FileIOBase::GetInstance(); + ASSERT_NE(nullptr, fileIo); + + auto resetArchiveFile = [archive, fileIo](const AZStd::string& filePath) + { + archive->ClosePack(filePath.c_str()); + fileIo->Remove(filePath.c_str()); + + auto pArchive = archive->OpenArchive(filePath.c_str(), nullptr, AZ::IO::INestedArchive::FLAGS_CREATE_NEW); + EXPECT_NE(nullptr, pArchive); + pArchive.reset(); + archive->ClosePack(filePath.c_str()); + }; + + AZStd::string testArchivePath_pakOne = "@usercache@/one.pak"; + AZStd::string testArchivePath_pakTwo = "@usercache@/two.pak"; + + // reset test files in case they already exist + resetArchiveFile(testArchivePath_pakOne); + resetArchiveFile(testArchivePath_pakTwo); + + // open and fetch the opened pak file using a *.pak + AZStd::vector fullPaths; + archive->OpenPacks("@usercache@/*.pak", AZ::IO::IArchive::EPathResolutionRules::FLAGS_PATH_REAL, &fullPaths); + EXPECT_TRUE(AZStd::any_of(fullPaths.cbegin(), fullPaths.cend(), [](auto& path) { return path.ends_with("one.pak"); })); + EXPECT_TRUE(AZStd::any_of(fullPaths.cbegin(), fullPaths.cend(), [](auto& path) { return path.ends_with("two.pak"); })); + } + TEST_F(ArchiveTestFixture, TestArchiveFGetCachedFileData_LooseFile) { // ------setup loose file FGetCachedFileData tests ------------------------- From bd7c5f4ee2aa2a8f98d32c9a8df767ded2e7ca9f Mon Sep 17 00:00:00 2001 From: antonmic Date: Mon, 7 Jun 2021 08:39:08 -0700 Subject: [PATCH 556/811] Pass changes WIP: small improvements --- .../RPI/Code/Source/RPI.Public/Pass/Pass.cpp | 10 ++++----- .../Source/RPI.Public/Pass/PassSystem.cpp | 21 ++++++++++++++++--- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp index 391db8361d..e53ffbf122 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp @@ -1027,7 +1027,7 @@ namespace AZ void Pass::QueueForBuild() { -#if OLD_SCHOOL +#if 0//OLD_SCHOOL // Don't queue if we're in building phase //if (PassSystemInterface::Get()->GetState() != RPI::PassSystemState::Building) { @@ -1107,7 +1107,7 @@ namespace AZ execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForInitialization); #if OLD_SCHOOL - AZ_Assert(!execute == m_flags.m_alreadyReset, "ANTON - EARLY OUT FLAGS do not match for pass BUILD!!"); + AZ_Assert(!execute == m_flags.m_alreadyReset, "ANTON - EARLY OUT FLAGS do not match for pass RESET!!"); if (m_flags.m_alreadyReset) { return; @@ -1143,6 +1143,8 @@ namespace AZ { AZ_RPI_BREAK_ON_TARGET_PASS; + AZ_Assert(m_state == PassState::Reset, "ANTON - BUILDING PASS BUT STATE IS NOT RESET!!"); + bool execute = (m_state == PassState::Idle || m_state == PassState::Reset); execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForBuild); execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForInitialization); @@ -1161,10 +1163,7 @@ namespace AZ } #endif - //Reset(); - m_state = PassState::Building; - m_queueState = PassQueueState::NoQueue; // Bindings, inputs and attachments CreateBindingsFromTemplate(); @@ -1187,6 +1186,7 @@ namespace AZ UpdateAttachmentUsageIndices(); m_state = PassState::Built; + m_queueState = PassQueueState::NoQueue; // If this pass's Build() wasn't called from the Pass System, then it was called by it's parent pass // In which case we don't need to queue for initialization because the parent will already be queued diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp index bbd9ac7df8..a7021ee6fd 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -214,13 +214,23 @@ namespace AZ SortPassListAscending(buildListCopy); + Pass* previousPassInList = nullptr; for (const Ptr& pass : buildListCopy) { - pass->Reset(); + if (pass.get() != previousPassInList); + { + pass->Reset(); + previousPassInList = pass.get(); + } } + previousPassInList = nullptr; for (const Ptr& pass : buildListCopy) { - pass->Build(true); + if (pass.get() != previousPassInList); + { + pass->Build(true); + previousPassInList = pass.get(); + } } loopCounter++; } @@ -263,9 +273,14 @@ namespace AZ SortPassListAscending(initListCopy); + Pass* previousPassInList = nullptr; for (const Ptr& pass : initListCopy) { - pass->Initialize(); + if (pass.get() != previousPassInList); + { + pass->Initialize(); + previousPassInList = pass.get(); + } } loopCounter++; } From 9e3d4727003eff4e008d635512506214016a8bb3 Mon Sep 17 00:00:00 2001 From: Nicholas Van Sickle Date: Mon, 7 Jun 2021 09:21:10 -0700 Subject: [PATCH 557/811] Switch EditorContextMenu back to using popup instead of exec (#1158) Switch EditorContextMenu back to using popup instead of exec The switch to exec was a deliberate change, but upon further testing with the latest version of our camera input controllers (both the Legacy and Modern variants) it is no longer necessary to call exec, and doing so can cause a bug in which the cursor is still hidden when the context menu appears. --- .../AzToolsFramework/Viewport/EditorContextMenu.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp index 8ed488b010..308f0f074f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp @@ -62,7 +62,8 @@ namespace AzToolsFramework if (!contextMenu.m_menu->isEmpty()) { - contextMenu.m_menu->exec(QCursor::pos()); + // Use popup instead of exec; this avoids blocking input event processing while the menu dialog is active + contextMenu.m_menu->popup(QCursor::pos()); } } } From 3e74c4f1e1a4ad854a0adbe045797de31d0c8fdb Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Mon, 7 Jun 2021 09:22:13 -0700 Subject: [PATCH 558/811] fixed minor type. Beh method name should say entityId, not entity --- .../Code/Source/AutoGen/AutoComponent_Source.jinja | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 12ff01468e..21bf6ab69b 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -368,26 +368,26 @@ void {{ ClassName }}::Signal{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.jo ->Method("{{ UpperFirst(Property.attrib['Name']) }}", [](const {{ ClassName }}* self, {{ ', '.join(paramDefines) }}) { self->m_controller->{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.join(paramNames) }}); }) - ->Method("{{ UpperFirst(Property.attrib['Name']) }}ByEntity", [](AZ::EntityId id, {{ ', '.join(paramDefines) }}) { + ->Method("{{ UpperFirst(Property.attrib['Name']) }}ByEntityId", [](AZ::EntityId id, {{ ', '.join(paramDefines) }}) { AZ::Entity* entity = AZ::Interface::Get()->FindEntity(id); if (!entity) { - AZ_Warning("Network Property", false, "{{ ClassName }} {{ UpperFirst(Property.attrib['Name']) }}ByEntity failed. The entity with id %s doesn't exist, please provide a valid entity id.", id.ToString().c_str()) + AZ_Warning("Network Property", false, "{{ ClassName }} {{ UpperFirst(Property.attrib['Name']) }}ByEntityId failed. The entity with id %s doesn't exist, please provide a valid entity id.", id.ToString().c_str()) return; } {{ ClassName }}* networkComponent = entity->FindComponent<{{ ClassName }}>(); if (!networkComponent) { - AZ_Warning("Network Property", false, "{{ ClassName }} {{ UpperFirst(Property.attrib['Name']) }}ByEntity failed. Entity '%s' (id: %s) is missing {{ ClassName }}, be sure to add {{ ClassName }} to this entity.", entity->GetName().c_str(), id.ToString().c_str()) + AZ_Warning("Network Property", false, "{{ ClassName }} {{ UpperFirst(Property.attrib['Name']) }}ByEntityId failed. Entity '%s' (id: %s) is missing {{ ClassName }}, be sure to add {{ ClassName }} to this entity.", entity->GetName().c_str(), id.ToString().c_str()) return; } {{ ClassName }}Controller* controller = static_cast<{{ ClassName }}Controller*>(networkComponent->GetController()); if (!controller) { - AZ_Warning("Network Property", false, "{{ ClassName }} {{ UpperFirst(Property.attrib['Name']) }}ByEntity method failed. Entity '%s' (id: %s) {{ ClassName }} is missing the network controller. This RemoteProcedure can only be invoked from {{InvokeFrom}} network entities, because this entity doesn't have a controller, it must not be a {{InvokeFrom}} entity. Please check your network context before attempting to call {{ UpperFirst(Property.attrib['Name']) }}.", entity->GetName().c_str(), id.ToString().c_str()) + AZ_Warning("Network Property", false, "{{ ClassName }} {{ UpperFirst(Property.attrib['Name']) }}ByEntityId method failed. Entity '%s' (id: %s) {{ ClassName }} is missing the network controller. This RemoteProcedure can only be invoked from {{InvokeFrom}} network entities, because this entity doesn't have a controller, it must not be a {{InvokeFrom}} entity. Please check your network context before attempting to call {{ UpperFirst(Property.attrib['Name']) }}.", entity->GetName().c_str(), id.ToString().c_str()) return; } @@ -431,19 +431,19 @@ void {{ ClassName }}::Signal{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.jo return self->m_controller->Get{{ UpperFirst(Property.attrib['Name']) }}Event(); }) ->Attribute(AZ::Script::Attributes::AzEventDescription, {{ LowerFirst(Property.attrib['Name']) }}EventDesc) - ->Method("Get{{ UpperFirst(Property.attrib['Name']) }}EventByEntity", [](AZ::EntityId id) -> AZ::Event<{{ ', '.join(paramTypes) }}>* + ->Method("Get{{ UpperFirst(Property.attrib['Name']) }}EventByEntityId", [](AZ::EntityId id) -> AZ::Event<{{ ', '.join(paramTypes) }}>* { AZ::Entity* entity = AZ::Interface::Get()->FindEntity(id); if (!entity) { - AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }}EventByEntity failed. The entity with id %s doesn't exist, please provide a valid entity id.", id.ToString().c_str()) + AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }}EventByEntityId failed. The entity with id %s doesn't exist, please provide a valid entity id.", id.ToString().c_str()) return nullptr; } {{ ClassName }}* networkComponent = entity->FindComponent<{{ ClassName }}>(); if (!networkComponent) { - AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }}EventByEntity failed. Entity '%s' (id: %s) is missing {{ ClassName }}, be sure to add {{ ClassName }} to this entity.", entity->GetName().c_str(), id.ToString().c_str()) + AZ_Warning("Network Property", false, "{{ ClassName }} Get{{ UpperFirst(Property.attrib['Name']) }}EventByEntityId failed. Entity '%s' (id: %s) is missing {{ ClassName }}, be sure to add {{ ClassName }} to this entity.", entity->GetName().c_str(), id.ToString().c_str()) return nullptr; } From 6d6f8413c8fa260ff2dec8dc1aaa674125a915ad Mon Sep 17 00:00:00 2001 From: mgwynn Date: Mon, 7 Jun 2021 14:14:32 -0400 Subject: [PATCH 559/811] Incorporating review comments. Some parameter modifications. Some cli edge case handling. Remove remove_tag member from project info --- .../ProjectManager/Source/ProjectInfo.cpp | 2 - .../Tools/ProjectManager/Source/ProjectInfo.h | 14 ++++--- .../ProjectManager/Source/PythonBindings.cpp | 20 +++++----- scripts/o3de/o3de/project_properties.py | 39 +++++++++++-------- 4 files changed, 43 insertions(+), 32 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp index 85716fccfa..99649cbfdf 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp @@ -26,8 +26,6 @@ namespace O3DE::ProjectManager , m_backgroundImagePath(backgroundImagePath) , m_needsBuild(needsBuild) { - m_userTags = QStringList(); - m_userTagsForRemoval = QStringList(); } bool ProjectInfo::operator==(const ProjectInfo& rhs) diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.h b/Code/Tools/ProjectManager/Source/ProjectInfo.h index 47a10dbc14..184916a514 100644 --- a/Code/Tools/ProjectManager/Source/ProjectInfo.h +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.h @@ -25,8 +25,15 @@ namespace O3DE::ProjectManager public: ProjectInfo() = default; - ProjectInfo(const QString& path, const QString& projectName, const QString& displayName, const QString& origin, - const QString& summary, const QString& imagePath, const QString& backgroundImagePath, bool needsBuild + ProjectInfo( + const QString& path, + const QString& projectName, + const QString& displayName, + const QString& origin, + const QString& summary, + const QString& imagePath, + const QString& backgroundImagePath, + bool needsBuild); bool operator==(const ProjectInfo& rhs); bool operator!=(const ProjectInfo& rhs); @@ -49,9 +56,6 @@ namespace O3DE::ProjectManager // Used in project creation - // Used to flag tags for removal - QStringList m_userTagsForRemoval; - bool m_needsBuild = false; //! Does this project need to be built }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 9fa10ce3d8..fe01209172 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -53,6 +53,7 @@ namespace Platform #define Py_To_String(obj) obj.cast().c_str() #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string +#define Py_To_List(obj) obj.cast> namespace RedirectOutput { @@ -678,6 +679,12 @@ namespace O3DE::ProjectManager { projectInfo.m_projectName = Py_To_String(projectData["project_name"]); projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName); + projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin); + projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary); + for (const auto& tag : projectData["user_tags"]) + { + projectInfo.m_userTags.append(Py_To_String(tag)); + } } catch ([[maybe_unused]] const std::exception& e) { @@ -753,17 +760,11 @@ namespace O3DE::ProjectManager return ExecuteWithLockErrorHandling([&] { std::list newTags; - for (auto& i : projectInfo.m_userTags) + for (const auto& i : projectInfo.m_userTags) { newTags.push_back(i.toStdString()); } - std::list removedTags; - for (auto& i : projectInfo.m_userTagsForRemoval) - { - removedTags.push_back(i.toStdString()); - } - m_editProjectProperties.attr("edit_project_props")( pybind11::str(projectInfo.m_path.toStdString()), // proj_path pybind11::none(), // proj_name not used @@ -771,8 +772,9 @@ namespace O3DE::ProjectManager pybind11::str(projectInfo.m_displayName.toStdString()), // new_display pybind11::str(projectInfo.m_summary.toStdString()), // new_summary pybind11::str(projectInfo.m_imagePath.toStdString()), // new_icon - pybind11::list(pybind11::cast(newTags)), // new_tag - pybind11::list(pybind11::cast(removedTags))); // remove_tag + pybind11::none(), // add_tags not used + pybind11::none(), // remove_tags not used + pybind11::list(pybind11::cast(newTags))); // replace_tags }); } diff --git a/scripts/o3de/o3de/project_properties.py b/scripts/o3de/o3de/project_properties.py index 83e76fc18f..b2268131c0 100644 --- a/scripts/o3de/o3de/project_properties.py +++ b/scripts/o3de/o3de/project_properties.py @@ -30,7 +30,7 @@ def get_project_props(name: str = None, path: pathlib.Path = None) -> dict: return proj_json def edit_project_props(proj_path, proj_name, new_origin, new_display, - new_summary, new_icon, new_tag, remove_tag) -> int: + new_summary, new_icon, new_tags, delete_tags, replace_tags) -> int: proj_json = get_project_props(proj_name, proj_path) if not proj_json: @@ -44,18 +44,22 @@ def edit_project_props(proj_path, proj_name, new_origin, new_display, proj_json['summary'] = new_summary if new_icon: proj_json['icon_path'] = new_icon - if new_tag: - for tag in new_tag: - proj_json.setdefault('user_tags', []).append(tag) - if remove_tag: + if new_tags: + tag_list = [new_tags] if isinstance(new_tags, str) else new_tags + proj_json.setdefault('user_tags', []).extend(tag_list) + if delete_tags: + removal_list = [delete_tags] if isinstance(delete_tags, str) else delete_tags if 'user_tags' in proj_json: - for del_tag in remove_tag: - if del_tag in proj_json['user_tags']: - proj_json['user_tags'].remove(del_tag) + for tag in removal_list: + if tag in proj_json['user_tags']: + proj_json['user_tags'].remove(tag) else: - logger.warn(f'{del_tag} not found in user_tags for removal.') + logger.warn(f'{tag} not found in user_tags for removal.') else: - logger.warn(f'user_tags property not found for removal of {remove_tag}.') + logger.warn(f'user_tags property not found for removal of {remove_tags}.') + if replace_tags: + tag_list = [replace_tags] if isinstance(replace_tags, str) else replace_tags + proj_json['user_tags'] = tag_list manifest.save_o3de_manifest(proj_json, pathlib.Path(proj_path) / 'project.json') return 0 @@ -67,8 +71,9 @@ def _edit_project_props(args: argparse) -> int: args.project_display, args.project_summary, args.project_icon, - args.project_tag, - args.remove_tag) + args.add_tags, + args.delete_tags, + args.replace_tags) def add_parser_args(parser): group = parser.add_mutually_exclusive_group(required=True) @@ -85,10 +90,12 @@ def add_parser_args(parser): help='Sets the summary description of the project.') group.add_argument('-pi', '--project-icon', type=str, required=False, help='Sets the path to the projects icon resource.') - group.add_argument('-pt', '--project-tag', type=default, required=False, - help='Adds tag(s) to user_tags property. These tags are intended for documentation and filtering.') - group.add_argument('-rt', '--remove-tag', type=default, required=False, - help='Removes tag(s) from the user_tags property.') + group.add_argument('-at', '--add-tags', type=str, nargs='*', required=False, + help='Adds tag(s) to user_tags property. Space delimited list (ex. -at A B C)') + group.add_argument('-dt', '--delete-tags', type=str, nargs ='*', required=False, + help='Removes tag(s) from the user_tags property. Space delimited list (ex. -dt A B C') + group.add_argument('-rt', '--replace-tags', type=str, nargs ='*', required=False, + help='Replace entirety of user_tags proeprty with space delimited list of values') parser.set_defaults(func=_edit_project_props) def add_args(subparsers) -> None: From 01b200ad42ddf57386cea3ad44c9121e286e2477 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Mon, 7 Jun 2021 14:19:48 -0400 Subject: [PATCH 560/811] removing unused define --- Code/Tools/ProjectManager/Source/PythonBindings.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index fe01209172..1db8c92d3f 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -53,7 +53,6 @@ namespace Platform #define Py_To_String(obj) obj.cast().c_str() #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string -#define Py_To_List(obj) obj.cast> namespace RedirectOutput { From b0826c5f9cdeb3d2d51d23fec5aaea5c6eaa0302 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Mon, 7 Jun 2021 15:08:18 -0400 Subject: [PATCH 561/811] added tag managerment arguments for CLI to mutually exclusive group --- scripts/o3de/o3de/project_properties.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/o3de/o3de/project_properties.py b/scripts/o3de/o3de/project_properties.py index b2268131c0..52f1346b51 100644 --- a/scripts/o3de/o3de/project_properties.py +++ b/scripts/o3de/o3de/project_properties.py @@ -90,12 +90,13 @@ def add_parser_args(parser): help='Sets the summary description of the project.') group.add_argument('-pi', '--project-icon', type=str, required=False, help='Sets the path to the projects icon resource.') + group = parser.add_mutually_exclusive_group(required=False) group.add_argument('-at', '--add-tags', type=str, nargs='*', required=False, help='Adds tag(s) to user_tags property. Space delimited list (ex. -at A B C)') group.add_argument('-dt', '--delete-tags', type=str, nargs ='*', required=False, help='Removes tag(s) from the user_tags property. Space delimited list (ex. -dt A B C') group.add_argument('-rt', '--replace-tags', type=str, nargs ='*', required=False, - help='Replace entirety of user_tags proeprty with space delimited list of values') + help='Replace entirety of user_tags property with space delimited list of values') parser.set_defaults(func=_edit_project_props) def add_args(subparsers) -> None: From 1900a422035dcb16fa82144d6a59f630ab9fe952 Mon Sep 17 00:00:00 2001 From: mgwynn Date: Mon, 7 Jun 2021 15:43:47 -0400 Subject: [PATCH 562/811] remove const ref from iterator for python object conversion since pybind only returns copies and produces a clang error --- Code/Tools/ProjectManager/Source/PythonBindings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 1db8c92d3f..5d1463598a 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -680,7 +680,7 @@ namespace O3DE::ProjectManager projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName); projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin); projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary); - for (const auto& tag : projectData["user_tags"]) + for (auto tag : projectData["user_tags"]) { projectInfo.m_userTags.append(Py_To_String(tag)); } From 57faa2d37701966d2b64f7bd643e49ecdba26eb7 Mon Sep 17 00:00:00 2001 From: scottr Date: Mon, 7 Jun 2021 15:15:14 -0700 Subject: [PATCH 563/811] [cpack_installer] installer upload to s3 --- cmake/Packaging.cmake | 43 ++++++++++++++- .../Platform/Windows/PackagingPostBuild.cmake | 52 ++++++++++++++++++- scripts/build/tools/upload_to_s3.py | 5 ++ 3 files changed, 96 insertions(+), 4 deletions(-) diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index 3e23511fa1..d473ac93d7 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -16,6 +16,8 @@ endif() # public facing options will be used for conversion into cpack specific ones below. set(LY_INSTALLER_DOWNLOAD_URL "" CACHE STRING "URL embedded into the installer to download additional artifacts") set(LY_INSTALLER_LICENSE_URL "" CACHE STRING "Optionally embed a link to the license instead of raw text") +set(LY_INSTALLER_UPLOAD_URL "" CACHE STRING "URL used to automatically upload the artifacts. Currently only accepts S3 URLs e.g. s3:///") +set(LY_INSTALLER_AWS_PROFILE "" CACHE STRING "AWS CLI profile for uploading artifacts. You can also use LY_INSTALLER_AWS_PROFILE environment variable.") set(CPACK_DESIRED_CMAKE_VERSION 3.20.2) @@ -103,6 +105,41 @@ install(FILES ${_cmake_package_dest} DESTINATION ./Tools/Redistributables/CMake ) +# checks for and removes trailing slash +function(strip_trailing_slash in_url out_url) + string(LENGTH ${in_url} _url_length) + MATH(EXPR _url_length "${_url_length}-1") + + string(SUBSTRING ${in_url} 0 ${_url_length} _clean_url) + if("${in_url}" STREQUAL "${_clean_url}/") + set(${out_url} ${_clean_url} PARENT_SCOPE) + else() + set(${out_url} ${in_url} PARENT_SCOPE) + endif() +endfunction() + +set(_versioned_target_url_tag ${LY_VERSION_STRING}/${PAL_HOST_PLATFORM_NAME}) + +if(LY_INSTALLER_UPLOAD_URL) + ly_is_s3_url(${LY_INSTALLER_UPLOAD_URL} _is_s3_bucket) + if(NOT _is_s3_bucket) + message(FATAL_ERROR "Only S3 installer uploading is supported at this time") + endif() + + if (LY_INSTALLER_AWS_PROFILE) + set(CPACK_AWS_PROFILE ${LY_INSTALLER_AWS_PROFILE}) + elseif (DEFINED ENV{LY_INSTALLER_AWS_PROFILE}) + set(CPACK_AWS_PROFILE $ENV{LY_INSTALLER_AWS_PROFILE}) + else() + message(FATAL_ERROR + "An AWS profile is required for installer S3 uploading. Please provide " + "one via LY_INSTALLER_AWS_PROFILE CLI argument or environment variable") + endif() + + strip_trailing_slash(${LY_INSTALLER_UPLOAD_URL} LY_INSTALLER_UPLOAD_URL) + set(CPACK_UPLOAD_URL ${LY_INSTALLER_UPLOAD_URL}/${_versioned_target_url_tag}) +endif() + # IMPORTANT: required to be included AFTER setting all property overrides include(CPack REQUIRED) @@ -146,9 +183,11 @@ ly_configure_cpack_component( ) if(LY_INSTALLER_DOWNLOAD_URL) - # this will set the following variables: CPACK_DOWNLOAD_SITE, CPACK_DOWNLOAD_ALL, and CPACK_UPLOAD_DIRECTORY + strip_trailing_slash(${LY_INSTALLER_DOWNLOAD_URL} LY_INSTALLER_DOWNLOAD_URL) + + # this will set the following variables: CPACK_DOWNLOAD_SITE, CPACK_DOWNLOAD_ALL, and CPACK_UPLOAD_DIRECTORY (local) cpack_configure_downloads( - ${LY_INSTALLER_DOWNLOAD_URL} + ${LY_INSTALLER_DOWNLOAD_URL}/${_versioned_target_url_tag} UPLOAD_DIRECTORY ${CMAKE_BINARY_DIR}/_CPack_Uploads # to match the _CPack_Packages directory ALL ) diff --git a/cmake/Platform/Windows/PackagingPostBuild.cmake b/cmake/Platform/Windows/PackagingPostBuild.cmake index d379358bf4..89b3efb44b 100644 --- a/cmake/Platform/Windows/PackagingPostBuild.cmake +++ b/cmake/Platform/Windows/PackagingPostBuild.cmake @@ -59,12 +59,21 @@ set(_light_command message(STATUS "Creating Bootstrap Installer...") execute_process( COMMAND ${_candle_command} - COMMAND_ERROR_IS_FATAL ANY + RESULT_VARIABLE _candle_result + ERROR_VARIABLE _candle_errors ) +if(NOT ${_candle_result} EQUAL 0) + message(FATAL_ERROR "An error occurred invoking candle.exe. ${_candle_errors}") +endif() + execute_process( COMMAND ${_light_command} - COMMAND_ERROR_IS_FATAL ANY + RESULT_VARIABLE _light_result + ERROR_VARIABLE _light_errors ) +if(NOT ${_light_result} EQUAL 0) + message(FATAL_ERROR "An error occurred invoking light.exe. ${_light_errors}") +endif() file(COPY ${_bootstrap_output_file} DESTINATION ${CPACK_PACKAGE_DIRECTORY} @@ -87,3 +96,42 @@ file(COPY ${_artifacts} DESTINATION ${CPACK_UPLOAD_DIRECTORY} ) message(STATUS "Artifacts copied to ${CPACK_UPLOAD_DIRECTORY}") + +if(NOT CPACK_UPLOAD_URL) + return() +endif() + +file(REAL_PATH "${CPACK_SOURCE_DIR}/.." _root_path) + +file(TO_NATIVE_PATH "${_root_path}/python/python.cmd" _python_cmd) +file(TO_NATIVE_PATH "${_root_path}/scripts/build/tools/upload_to_s3.py" _upload_script) +file(TO_NATIVE_PATH "${_cpack_wix_out_dir}" _cpack_wix_out_dir) + +# strip the scheme and extract the bucket/key prefix from the URL +string(REPLACE "s3://" "" _stripped_url ${CPACK_UPLOAD_URL}) +string(REPLACE "/" ";" _tokens ${_stripped_url}) + +list(POP_FRONT _tokens _bucket) +string(JOIN "/" _prefix ${_tokens}) + +set(_file_regex ".*(cab|exe|msi)$") + +set(_upload_command + ${_python_cmd} -s + -u ${_upload_script} + --base_dir ${_cpack_wix_out_dir} + --file_regex="${_file_regex}" + --bucket ${_bucket} + --key_prefix ${_prefix} + --profile ${CPACK_AWS_PROFILE} +) + +execute_process( + COMMAND ${_upload_command} + RESULT_VARIABLE _upload_result + ERROR_VARIABLE _upload_errors +) + +if (NOT ${_upload_result} EQUAL 0) + message(FATAL_ERROR "An error occurred uploading artifacts. ${_upload_errors}") +endif() diff --git a/scripts/build/tools/upload_to_s3.py b/scripts/build/tools/upload_to_s3.py index d6d6d8ddb5..5dfe5eb66e 100755 --- a/scripts/build/tools/upload_to_s3.py +++ b/scripts/build/tools/upload_to_s3.py @@ -65,6 +65,11 @@ def get_client(service_name, profile_name): def get_files_to_upload(base_dir, regex): # Get all file names in base directory files = [x for x in os.listdir(base_dir) if os.path.isfile(os.path.join(base_dir, x))] + # strip the surround quotes, if they exist + try: + regex = json.loads(regex) + except: + pass # Get all file names matching the regular expression, those file will be uploaded to S3 files_to_upload = [x for x in files if re.match(regex, x)] return files_to_upload From 8aa310dff58768e3bbfd511b1a532523cdfc8308 Mon Sep 17 00:00:00 2001 From: scottr Date: Mon, 7 Jun 2021 15:29:29 -0700 Subject: [PATCH 564/811] [cpack_installer] option to set upload url via environment variable --- cmake/Packaging.cmake | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index d473ac93d7..6c077ac617 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -16,8 +16,9 @@ endif() # public facing options will be used for conversion into cpack specific ones below. set(LY_INSTALLER_DOWNLOAD_URL "" CACHE STRING "URL embedded into the installer to download additional artifacts") set(LY_INSTALLER_LICENSE_URL "" CACHE STRING "Optionally embed a link to the license instead of raw text") -set(LY_INSTALLER_UPLOAD_URL "" CACHE STRING "URL used to automatically upload the artifacts. Currently only accepts S3 URLs e.g. s3:///") -set(LY_INSTALLER_AWS_PROFILE "" CACHE STRING "AWS CLI profile for uploading artifacts. You can also use LY_INSTALLER_AWS_PROFILE environment variable.") +set(LY_INSTALLER_UPLOAD_URL "" CACHE STRING + "URL used to automatically upload the artifacts. Can also be set via LY_INSTALLER_UPLOAD_URL environment variable. Currently only accepts S3 URLs e.g. s3:///") +set(LY_INSTALLER_AWS_PROFILE "" CACHE STRING "AWS CLI profile for uploading artifacts. Can also be set via LY_INSTALLER_AWS_PROFILE environment variable.") set(CPACK_DESIRED_CMAKE_VERSION 3.20.2) @@ -120,6 +121,10 @@ endfunction() set(_versioned_target_url_tag ${LY_VERSION_STRING}/${PAL_HOST_PLATFORM_NAME}) +if(NOT LY_INSTALLER_UPLOAD_URL AND DEFINED ENV{LY_INSTALLER_UPLOAD_URL}) + set(LY_INSTALLER_UPLOAD_URL $ENV{LY_INSTALLER_UPLOAD_URL}) +endif() + if(LY_INSTALLER_UPLOAD_URL) ly_is_s3_url(${LY_INSTALLER_UPLOAD_URL} _is_s3_bucket) if(NOT _is_s3_bucket) From 36cb0f6d40d4ae756dbf878dd5b99b2611038ef0 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Mon, 7 Jun 2021 15:59:58 -0700 Subject: [PATCH 565/811] SPEC-7178 Removal of precompiled cpp files (#1171) * SPEC-7178 Removal of precompiled cpp files * Missing files... --- .../CrySystem/CrySystem_precompiled.cpp | 14 -------------- Code/CryEngine/CrySystem/crysystem_files.cmake | 1 - .../AzToolsFramework_precompiled.cpp | 13 ------------- .../aztoolsframework_files.cmake | 1 - .../ComponentEntityEditorPlugin_precompiled.cpp | 12 ------------ .../componententityeditorplugin_files.cmake | 1 - .../EditorAssetImporter_precompiled.cpp | 15 --------------- .../editorassetimporter_files.cmake | 1 - .../FFMPEGPlugin/FFMPEGPlugin_precompiled.cpp | 13 ------------- .../FFMPEGPlugin/ffmpegplugin_files.cmake | 1 - .../PerforcePlugin_precompiled.cpp | 15 --------------- .../PerforcePlugin/perforceplugin_files.cmake | 1 - .../ProjectSettingsTool_precompiled.cpp | 12 ------------ .../projectsettingstool_files.cmake | 1 - .../Standalone/StandaloneTools_precompiled.cpp | 14 -------------- .../Standalone/standalone_tools_files.cmake | 1 - .../Source/AssetMemoryAnalyzer_precompiled.cpp | 12 ------------ .../Code/assetmemoryanalyzer_files.cmake | 1 - .../Code/Source/ImageProcessing_precompiled.cpp | 13 ------------- .../Code/imageprocessing_files.cmake | 1 - .../Source/RHI/Atom_RHI_DX12_precompiled.cpp | 12 ------------ .../atom_rhi_dx12_private_common_files.cmake | 1 - .../Code/Source/Atom_RHI_Metal_precompiled.cpp | 12 ------------ .../Code/atom_rhi_metal_common_files.cmake | 1 - .../Code/Source/Atom_RHI_Null_precompiled.cpp | 12 ------------ .../Null/Code/atom_rhi_null_common_files.cmake | 1 - .../Code/Source/Atom_RHI_Vulkan_precompiled.cpp | 12 ------------ .../Code/atom_rhi_vulkan_common_files.cmake | 1 - .../Code/Source/AtomFont_precompiled.cpp | 14 -------------- .../AtomFont/Code/atomfont_files.cmake | 1 - Gems/Camera/Code/Source/Camera_precompiled.cpp | 12 ------------ Gems/Camera/Code/camera_files.cmake | 1 - .../Code/Source/CameraFramework_precompiled.cpp | 12 ------------ .../Code/cameraframework_files.cmake | 1 - .../Code/Source/DebugDraw_precompiled.cpp | 13 ------------- .../DebugDraw/Code/debugdraw_editor_files.cmake | 1 - Gems/DebugDraw/Code/debugdraw_files.cmake | 1 - .../Rendering/OpenGL2/Source/GLExtensions.h | 1 + .../Code/Source/EMotionFX_precompiled.cpp | 14 -------------- .../EMotionFX/Code/emotionfx_editor_files.cmake | 1 - Gems/EMotionFX/Code/emotionfx_files.cmake | 1 - .../Code/Source/FastNoise_precompiled.cpp | 12 ------------ Gems/FastNoise/Code/fastnoise_files.cmake | 1 - .../Code/Source/Gestures_precompiled.cpp | 12 ------------ Gems/Gestures/Code/gestures_files.cmake | 1 - .../Code/Source/GradientSignal_precompiled.cpp | 12 ------------ .../Code/gradientsignal_files.cmake | 1 - Gems/GraphCanvas/Code/graphcanvas_files.cmake | 1 - Gems/GraphCanvas/Code/precompiled.cpp | 14 -------------- .../Code/Source/HttpRequestor_precompiled.cpp | 13 ------------- .../Code/httprequestor_files.cmake | 1 - .../Code/lmbraws_unsupported_files.cmake | 1 - Gems/ImGui/Code/Source/ImGui_precompiled.cpp | 12 ------------ Gems/ImGui/Code/imgui_common_files.cmake | 1 - .../ImGui/Code/imgui_lyutils_static_files.cmake | 1 - .../Code/Source/InAppPurchases_precompiled.cpp | 13 ------------- .../Code/inapppurchases_files.cmake | 1 - .../Code/Source/LmbrCentral_precompiled.cpp | 13 ------------- Gems/LmbrCentral/Code/lmbrcentral_files.cmake | 1 - .../Code/Editor/UiCanvasEditor_precompiled.cpp | 12 ------------ .../Source/Animation/LyShine_precompiled.cpp | 13 ------------- .../LyShine/Code/Source/LyShine_precompiled.cpp | 13 ------------- Gems/LyShine/Code/lyshine_static_files.cmake | 1 - .../Code/lyshine_uicanvaseditor_files.cmake | 1 - .../Code/Source/LyShineExamples_precompiled.cpp | 13 ------------- .../Code/lyshineexamples_files.cmake | 1 - .../Source/Cinematics/Maestro_precompiled.cpp | 14 -------------- .../Maestro/Code/Source/Maestro_precompiled.cpp | 12 ------------ Gems/Maestro/Code/maestro_static_files.cmake | 1 - .../Code/Source/MessagePopup_precompiled.cpp | 12 ------------ Gems/MessagePopup/Code/messagepopup_files.cmake | 1 - .../Code/Source/Metastream_precompiled.cpp | 12 ------------ Gems/Metastream/Code/metastream_files.cmake | 1 - .../Code/Source/Microphone_precompiled.cpp | 13 ------------- Gems/Microphone/Code/microphone_files.cmake | 1 - .../Code/Source/Multiplayer_precompiled.cpp | 13 ------------- .../Code/multiplayer_debug_files.cmake | 1 - Gems/Multiplayer/Code/multiplayer_files.cmake | 1 - .../Code/multiplayer_tools_files.cmake | 1 - .../Source/NumericalMethods_precompiled.cpp | 13 ------------- .../numericalmethods_files.cmake | 1 - .../Source/PhysXUnsupported_precompiled.cpp | 13 ------------- Gems/PhysX/Code/Source/PhysX_precompiled.cpp | 13 ------------- Gems/PhysX/Code/physx_files.cmake | 1 - .../PhysXDebugUnsupported_precompiled.cpp | 13 ------------- .../Code/Source/PhysXDebug_precompiled.cpp | 12 ------------ .../Code/physxdebug_editor_files.cmake | 1 - Gems/PhysXDebug/Code/physxdebug_files.cmake | 1 - .../Code/physxdebug_unsupported_files.cmake | 1 - Gems/ScriptCanvas/Code/Editor/precompiled.cpp | 13 ------------- Gems/ScriptCanvas/Code/Source/precompiled.cpp | 13 ------------- .../Code/scriptcanvasgem_editor_files.cmake | 1 - .../scriptcanvasgem_editor_shared_files.cmake | 1 - .../Code/scriptcanvasgem_game_files.cmake | 1 - .../Code/scriptcanvasgem_tests_files.cmake | 1 - .../Code/Source/precompiled.cpp | 13 ------------- ...scriptcanvasdeveloper_gem_common_files.cmake | 1 - .../Source/ScriptCanvasPhysics_precompiled.cpp | 13 ------------- .../Code/scriptcanvas_physics_files.cmake | 1 - .../scriptcanvas_physics_shared_files.cmake | 1 - Gems/ScriptEvents/Code/Source/precompiled.cpp | 13 ------------- .../Code/scriptevents_editor_files.cmake | 1 - Gems/ScriptEvents/Code/scriptevents_files.cmake | 1 - .../ScriptedEntityTweener_precompiled.cpp | 13 ------------- .../Code/scriptedentitytweener_files.cmake | 1 - .../Code/Source/SliceFavorites_precompiled.cpp | 13 ------------- .../Code/slicefavorites_files.cmake | 1 - .../Source/StartingPointCamera_precompiled.cpp | 12 ------------ .../Code/startingpointcamera_files.cmake | 1 - .../Source/StartingPointInput_precompiled.cpp | 12 ------------ .../Code/startingpointinput_editor_files.cmake | 2 -- .../Code/startingpointinput_files.cmake | 1 - Gems/StartingPointMovement/Code/CMakeLists.txt | 16 ---------------- .../StartingPointMovement_precompiled.cpp | 12 ------------ .../Code/startingpointmovement_files.cmake | 17 ----------------- .../startingpointmovement_shared_files.cmake | 3 +++ .../Code/Source/SurfaceData_precompiled.cpp | 12 ------------ Gems/SurfaceData/Code/surfacedata_files.cmake | 1 - .../Code/Source/TextureAtlas_precompiled.cpp | 13 ------------- Gems/TextureAtlas/Code/textureatlas_files.cmake | 1 - .../Source/TickBusOrderViewer_precompiled.cpp | 12 ------------ .../Code/tickbusorderviewer_files.cmake | 1 - Gems/Twitch/Code/Source/Twitch_precompiled.cpp | 13 ------------- .../Twitch/Code/lmbraws_unsupported_files.cmake | 1 - Gems/Twitch/Code/twitch_files.cmake | 1 - .../Code/Source/Vegetation_precompiled.cpp | 12 ------------ Gems/Vegetation/Code/vegetation_files.cmake | 1 - .../Code/Source/VirtualGamepad_precompiled.cpp | 13 ------------- .../Code/virtualgamepad_files.cmake | 1 - .../Source/WhiteBoxUnsupported_precompiled.cpp | 13 ------------- .../Code/Source/WhiteBox_precompiled.cpp | 13 ------------- .../Code/whitebox_supported_files.cmake | 1 - .../Code/whitebox_unsupported_files.cmake | 1 - 133 files changed, 4 insertions(+), 869 deletions(-) delete mode 100644 Code/CryEngine/CrySystem/CrySystem_precompiled.cpp delete mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFramework_precompiled.cpp delete mode 100644 Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin_precompiled.cpp delete mode 100644 Code/Sandbox/Plugins/EditorAssetImporter/EditorAssetImporter_precompiled.cpp delete mode 100644 Code/Sandbox/Plugins/FFMPEGPlugin/FFMPEGPlugin_precompiled.cpp delete mode 100644 Code/Sandbox/Plugins/PerforcePlugin/PerforcePlugin_precompiled.cpp delete mode 100644 Code/Sandbox/Plugins/ProjectSettingsTool/ProjectSettingsTool_precompiled.cpp delete mode 100644 Code/Tools/Standalone/StandaloneTools_precompiled.cpp delete mode 100644 Gems/AssetMemoryAnalyzer/Code/Source/AssetMemoryAnalyzer_precompiled.cpp delete mode 100644 Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessing_precompiled.cpp delete mode 100644 Gems/Atom/RHI/DX12/Code/Source/RHI/Atom_RHI_DX12_precompiled.cpp delete mode 100644 Gems/Atom/RHI/Metal/Code/Source/Atom_RHI_Metal_precompiled.cpp delete mode 100644 Gems/Atom/RHI/Null/Code/Source/Atom_RHI_Null_precompiled.cpp delete mode 100644 Gems/Atom/RHI/Vulkan/Code/Source/Atom_RHI_Vulkan_precompiled.cpp delete mode 100644 Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont_precompiled.cpp delete mode 100644 Gems/Camera/Code/Source/Camera_precompiled.cpp delete mode 100644 Gems/CameraFramework/Code/Source/CameraFramework_precompiled.cpp delete mode 100644 Gems/DebugDraw/Code/Source/DebugDraw_precompiled.cpp delete mode 100644 Gems/EMotionFX/Code/Source/EMotionFX_precompiled.cpp delete mode 100644 Gems/FastNoise/Code/Source/FastNoise_precompiled.cpp delete mode 100644 Gems/Gestures/Code/Source/Gestures_precompiled.cpp delete mode 100644 Gems/GradientSignal/Code/Source/GradientSignal_precompiled.cpp delete mode 100644 Gems/GraphCanvas/Code/precompiled.cpp delete mode 100644 Gems/HttpRequestor/Code/Source/HttpRequestor_precompiled.cpp delete mode 100644 Gems/ImGui/Code/Source/ImGui_precompiled.cpp delete mode 100644 Gems/InAppPurchases/Code/Source/InAppPurchases_precompiled.cpp delete mode 100644 Gems/LmbrCentral/Code/Source/LmbrCentral_precompiled.cpp delete mode 100644 Gems/LyShine/Code/Editor/UiCanvasEditor_precompiled.cpp delete mode 100644 Gems/LyShine/Code/Source/Animation/LyShine_precompiled.cpp delete mode 100644 Gems/LyShine/Code/Source/LyShine_precompiled.cpp delete mode 100644 Gems/LyShineExamples/Code/Source/LyShineExamples_precompiled.cpp delete mode 100644 Gems/Maestro/Code/Source/Cinematics/Maestro_precompiled.cpp delete mode 100644 Gems/Maestro/Code/Source/Maestro_precompiled.cpp delete mode 100644 Gems/MessagePopup/Code/Source/MessagePopup_precompiled.cpp delete mode 100644 Gems/Metastream/Code/Source/Metastream_precompiled.cpp delete mode 100644 Gems/Microphone/Code/Source/Microphone_precompiled.cpp delete mode 100644 Gems/Multiplayer/Code/Source/Multiplayer_precompiled.cpp delete mode 100644 Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods_precompiled.cpp delete mode 100644 Gems/PhysX/Code/Source/PhysXUnsupported_precompiled.cpp delete mode 100644 Gems/PhysX/Code/Source/PhysX_precompiled.cpp delete mode 100644 Gems/PhysXDebug/Code/Source/PhysXDebugUnsupported_precompiled.cpp delete mode 100644 Gems/PhysXDebug/Code/Source/PhysXDebug_precompiled.cpp delete mode 100644 Gems/ScriptCanvas/Code/Editor/precompiled.cpp delete mode 100644 Gems/ScriptCanvas/Code/Source/precompiled.cpp delete mode 100644 Gems/ScriptCanvasDeveloper/Code/Source/precompiled.cpp delete mode 100644 Gems/ScriptCanvasPhysics/Code/Source/ScriptCanvasPhysics_precompiled.cpp delete mode 100644 Gems/ScriptEvents/Code/Source/precompiled.cpp delete mode 100644 Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweener_precompiled.cpp delete mode 100644 Gems/SliceFavorites/Code/Source/SliceFavorites_precompiled.cpp delete mode 100644 Gems/StartingPointCamera/Code/Source/StartingPointCamera_precompiled.cpp delete mode 100644 Gems/StartingPointInput/Code/Source/StartingPointInput_precompiled.cpp delete mode 100644 Gems/StartingPointMovement/Code/Source/StartingPointMovement_precompiled.cpp delete mode 100644 Gems/StartingPointMovement/Code/startingpointmovement_files.cmake delete mode 100644 Gems/SurfaceData/Code/Source/SurfaceData_precompiled.cpp delete mode 100644 Gems/TextureAtlas/Code/Source/TextureAtlas_precompiled.cpp delete mode 100644 Gems/TickBusOrderViewer/Code/Source/TickBusOrderViewer_precompiled.cpp delete mode 100644 Gems/Twitch/Code/Source/Twitch_precompiled.cpp delete mode 100644 Gems/Vegetation/Code/Source/Vegetation_precompiled.cpp delete mode 100644 Gems/VirtualGamepad/Code/Source/VirtualGamepad_precompiled.cpp delete mode 100644 Gems/WhiteBox/Code/Source/WhiteBoxUnsupported_precompiled.cpp delete mode 100644 Gems/WhiteBox/Code/Source/WhiteBox_precompiled.cpp diff --git a/Code/CryEngine/CrySystem/CrySystem_precompiled.cpp b/Code/CryEngine/CrySystem/CrySystem_precompiled.cpp deleted file mode 100644 index eaa80bbdc1..0000000000 --- a/Code/CryEngine/CrySystem/CrySystem_precompiled.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. -// If you make changes in ICryPak.h, make changes here, to dirty the PCH. -#include "CrySystem_precompiled.h" diff --git a/Code/CryEngine/CrySystem/crysystem_files.cmake b/Code/CryEngine/CrySystem/crysystem_files.cmake index 84250de95b..f0398ffb88 100644 --- a/Code/CryEngine/CrySystem/crysystem_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_files.cmake @@ -75,6 +75,5 @@ set(FILES ViewSystem/View.h ViewSystem/ViewSystem.cpp ViewSystem/ViewSystem.h - CrySystem_precompiled.cpp WindowsErrorReporting.cpp ) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFramework_precompiled.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFramework_precompiled.cpp deleted file mode 100644 index f9de86bce5..0000000000 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFramework_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "AzToolsFramework_precompiled.h" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index 8d0180f6ce..e5ac1f9693 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -11,7 +11,6 @@ set(FILES AzToolsFramework_precompiled.h - AzToolsFramework_precompiled.cpp AssetEditor/AssetEditorBus.h AssetEditor/AssetEditorToolbar.ui AssetEditor/AssetEditorStatusBar.ui diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin_precompiled.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin_precompiled.cpp deleted file mode 100644 index ce0194251b..0000000000 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "ComponentEntityEditorPlugin_precompiled.h" diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/componententityeditorplugin_files.cmake b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/componententityeditorplugin_files.cmake index 6672bc8b47..2b5877b1e6 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/componententityeditorplugin_files.cmake +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/componententityeditorplugin_files.cmake @@ -15,7 +15,6 @@ set(FILES ComponentEntityEditorPlugin.cpp SandboxIntegration.h SandboxIntegration.cpp - ComponentEntityEditorPlugin_precompiled.cpp ComponentEntityEditorPlugin_precompiled.h UI/ComponentEntityEditorOutlinerWindow.qrc UI/QComponentEntityEditorMainWindow.h diff --git a/Code/Sandbox/Plugins/EditorAssetImporter/EditorAssetImporter_precompiled.cpp b/Code/Sandbox/Plugins/EditorAssetImporter/EditorAssetImporter_precompiled.cpp deleted file mode 100644 index a77146223e..0000000000 --- a/Code/Sandbox/Plugins/EditorAssetImporter/EditorAssetImporter_precompiled.cpp +++ /dev/null @@ -1,15 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorAssetImporter_precompiled.h" - diff --git a/Code/Sandbox/Plugins/EditorAssetImporter/editorassetimporter_files.cmake b/Code/Sandbox/Plugins/EditorAssetImporter/editorassetimporter_files.cmake index 68f7a450a1..c017aa6320 100644 --- a/Code/Sandbox/Plugins/EditorAssetImporter/editorassetimporter_files.cmake +++ b/Code/Sandbox/Plugins/EditorAssetImporter/editorassetimporter_files.cmake @@ -23,7 +23,6 @@ set(FILES SceneSerializationHandler.h SceneSerializationHandler.cpp Main.cpp - EditorAssetImporter_precompiled.cpp EditorAssetImporter_precompiled.h AssetImporter.qrc AssetImporterWindow.ui diff --git a/Code/Sandbox/Plugins/FFMPEGPlugin/FFMPEGPlugin_precompiled.cpp b/Code/Sandbox/Plugins/FFMPEGPlugin/FFMPEGPlugin_precompiled.cpp deleted file mode 100644 index b7f4fd23cc..0000000000 --- a/Code/Sandbox/Plugins/FFMPEGPlugin/FFMPEGPlugin_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "FFMPEGPlugin_precompiled.h" - diff --git a/Code/Sandbox/Plugins/FFMPEGPlugin/ffmpegplugin_files.cmake b/Code/Sandbox/Plugins/FFMPEGPlugin/ffmpegplugin_files.cmake index 9ae55cc45a..1c36b4c5bc 100644 --- a/Code/Sandbox/Plugins/FFMPEGPlugin/ffmpegplugin_files.cmake +++ b/Code/Sandbox/Plugins/FFMPEGPlugin/ffmpegplugin_files.cmake @@ -12,7 +12,6 @@ set(FILES FFMPEGPlugin.rc main.cpp - FFMPEGPlugin_precompiled.cpp FFMPEGPlugin_precompiled.h FFMPEGPlugin.cpp FFMPEGPlugin.h diff --git a/Code/Sandbox/Plugins/PerforcePlugin/PerforcePlugin_precompiled.cpp b/Code/Sandbox/Plugins/PerforcePlugin/PerforcePlugin_precompiled.cpp deleted file mode 100644 index cc1ded61a4..0000000000 --- a/Code/Sandbox/Plugins/PerforcePlugin/PerforcePlugin_precompiled.cpp +++ /dev/null @@ -1,15 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "PerforcePlugin_precompiled.h" - diff --git a/Code/Sandbox/Plugins/PerforcePlugin/perforceplugin_files.cmake b/Code/Sandbox/Plugins/PerforcePlugin/perforceplugin_files.cmake index 6e3a497aca..11e81d3358 100644 --- a/Code/Sandbox/Plugins/PerforcePlugin/perforceplugin_files.cmake +++ b/Code/Sandbox/Plugins/PerforcePlugin/perforceplugin_files.cmake @@ -20,6 +20,5 @@ set(FILES PerforceSourceControl.cpp PerforceSourceControl.h resource.h - PerforcePlugin_precompiled.cpp PerforcePlugin_precompiled.h ) diff --git a/Code/Sandbox/Plugins/ProjectSettingsTool/ProjectSettingsTool_precompiled.cpp b/Code/Sandbox/Plugins/ProjectSettingsTool/ProjectSettingsTool_precompiled.cpp deleted file mode 100644 index 82549e649a..0000000000 --- a/Code/Sandbox/Plugins/ProjectSettingsTool/ProjectSettingsTool_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "ProjectSettingsTool_precompiled.h" diff --git a/Code/Sandbox/Plugins/ProjectSettingsTool/projectsettingstool_files.cmake b/Code/Sandbox/Plugins/ProjectSettingsTool/projectsettingstool_files.cmake index 235109e629..72287be08a 100644 --- a/Code/Sandbox/Plugins/ProjectSettingsTool/projectsettingstool_files.cmake +++ b/Code/Sandbox/Plugins/ProjectSettingsTool/projectsettingstool_files.cmake @@ -11,7 +11,6 @@ set(FILES main.cpp - ProjectSettingsTool_precompiled.cpp ProjectSettingsTool_precompiled.h DefaultImageValidator.cpp DefaultImageValidator.h diff --git a/Code/Tools/Standalone/StandaloneTools_precompiled.cpp b/Code/Tools/Standalone/StandaloneTools_precompiled.cpp deleted file mode 100644 index 073859f9b8..0000000000 --- a/Code/Tools/Standalone/StandaloneTools_precompiled.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "StandaloneTools_precompiled.h" - diff --git a/Code/Tools/Standalone/standalone_tools_files.cmake b/Code/Tools/Standalone/standalone_tools_files.cmake index 57e3e45d66..65933bd8c6 100644 --- a/Code/Tools/Standalone/standalone_tools_files.cmake +++ b/Code/Tools/Standalone/standalone_tools_files.cmake @@ -10,7 +10,6 @@ # set(FILES - StandaloneTools_precompiled.cpp StandaloneTools_precompiled.h targetver.h Source/StandaloneToolsApplication.cpp diff --git a/Gems/AssetMemoryAnalyzer/Code/Source/AssetMemoryAnalyzer_precompiled.cpp b/Gems/AssetMemoryAnalyzer/Code/Source/AssetMemoryAnalyzer_precompiled.cpp deleted file mode 100644 index 75643c0cf7..0000000000 --- a/Gems/AssetMemoryAnalyzer/Code/Source/AssetMemoryAnalyzer_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "AssetMemoryAnalyzer_precompiled.h" diff --git a/Gems/AssetMemoryAnalyzer/Code/assetmemoryanalyzer_files.cmake b/Gems/AssetMemoryAnalyzer/Code/assetmemoryanalyzer_files.cmake index 88994a2b47..8119a6e870 100644 --- a/Gems/AssetMemoryAnalyzer/Code/assetmemoryanalyzer_files.cmake +++ b/Gems/AssetMemoryAnalyzer/Code/assetmemoryanalyzer_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/AssetMemoryAnalyzer_precompiled.cpp Source/AssetMemoryAnalyzer_precompiled.h Include/AssetMemoryAnalyzer/AssetMemoryAnalyzerBus.h Source/AssetMemoryAnalyzer.cpp diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessing_precompiled.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessing_precompiled.cpp deleted file mode 100644 index 35211fa378..0000000000 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessing_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright(c) Amazon.com, Inc.or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution(the "License").All use of this software is governed by the License, -*or, if provided, by the license below or the license accompanying this file.Do not -* remove or modify any license notices.This file is distributed on an "AS IS" BASIS, -*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "ImageProcessing_precompiled.h" diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake b/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake index 69c678877d..c7ecee12bb 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/ImageProcessing_precompiled.cpp Source/ImageProcessing_precompiled.h Source/Compressors/CryTextureSquisher/CryTextureSquisher.cpp Source/Compressors/CryTextureSquisher/CryTextureSquisher.h diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Atom_RHI_DX12_precompiled.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Atom_RHI_DX12_precompiled.cpp deleted file mode 100644 index cb87449665..0000000000 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Atom_RHI_DX12_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ -#include diff --git a/Gems/Atom/RHI/DX12/Code/atom_rhi_dx12_private_common_files.cmake b/Gems/Atom/RHI/DX12/Code/atom_rhi_dx12_private_common_files.cmake index 3325964d17..13917b3f0d 100644 --- a/Gems/Atom/RHI/DX12/Code/atom_rhi_dx12_private_common_files.cmake +++ b/Gems/Atom/RHI/DX12/Code/atom_rhi_dx12_private_common_files.cmake @@ -11,7 +11,6 @@ set(FILES Source/RHI/Atom_RHI_DX12_precompiled.h - Source/RHI/Atom_RHI_DX12_precompiled.cpp Source/RHI/Buffer.cpp Source/RHI/Buffer.h Source/RHI/BufferPool.cpp diff --git a/Gems/Atom/RHI/Metal/Code/Source/Atom_RHI_Metal_precompiled.cpp b/Gems/Atom/RHI/Metal/Code/Source/Atom_RHI_Metal_precompiled.cpp deleted file mode 100644 index 42d5a87697..0000000000 --- a/Gems/Atom/RHI/Metal/Code/Source/Atom_RHI_Metal_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "Atom_RHI_Metal_precompiled.h" diff --git a/Gems/Atom/RHI/Metal/Code/atom_rhi_metal_common_files.cmake b/Gems/Atom/RHI/Metal/Code/atom_rhi_metal_common_files.cmake index 3eb2579038..d678075f14 100644 --- a/Gems/Atom/RHI/Metal/Code/atom_rhi_metal_common_files.cmake +++ b/Gems/Atom/RHI/Metal/Code/atom_rhi_metal_common_files.cmake @@ -10,6 +10,5 @@ # set(FILES - Source/Atom_RHI_Metal_precompiled.cpp Source/Atom_RHI_Metal_precompiled.h ) diff --git a/Gems/Atom/RHI/Null/Code/Source/Atom_RHI_Null_precompiled.cpp b/Gems/Atom/RHI/Null/Code/Source/Atom_RHI_Null_precompiled.cpp deleted file mode 100644 index 56bdaca01b..0000000000 --- a/Gems/Atom/RHI/Null/Code/Source/Atom_RHI_Null_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "Atom_RHI_Null_precompiled.h" diff --git a/Gems/Atom/RHI/Null/Code/atom_rhi_null_common_files.cmake b/Gems/Atom/RHI/Null/Code/atom_rhi_null_common_files.cmake index f0f7fd03de..aeb34c55a6 100644 --- a/Gems/Atom/RHI/Null/Code/atom_rhi_null_common_files.cmake +++ b/Gems/Atom/RHI/Null/Code/atom_rhi_null_common_files.cmake @@ -10,6 +10,5 @@ # set(FILES - Source/Atom_RHI_Null_precompiled.cpp Source/Atom_RHI_Null_precompiled.h ) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/Atom_RHI_Vulkan_precompiled.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/Atom_RHI_Vulkan_precompiled.cpp deleted file mode 100644 index 65e8f51730..0000000000 --- a/Gems/Atom/RHI/Vulkan/Code/Source/Atom_RHI_Vulkan_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "Atom_RHI_Vulkan_precompiled.h" diff --git a/Gems/Atom/RHI/Vulkan/Code/atom_rhi_vulkan_common_files.cmake b/Gems/Atom/RHI/Vulkan/Code/atom_rhi_vulkan_common_files.cmake index 83a962fb2b..717f2ff994 100644 --- a/Gems/Atom/RHI/Vulkan/Code/atom_rhi_vulkan_common_files.cmake +++ b/Gems/Atom/RHI/Vulkan/Code/atom_rhi_vulkan_common_files.cmake @@ -10,6 +10,5 @@ # set(FILES - Source/Atom_RHI_Vulkan_precompiled.cpp Source/Atom_RHI_Vulkan_precompiled.h ) diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont_precompiled.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont_precompiled.cpp deleted file mode 100644 index 63f8a2bddb..0000000000 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont_precompiled.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include diff --git a/Gems/AtomLyIntegration/AtomFont/Code/atomfont_files.cmake b/Gems/AtomLyIntegration/AtomFont/Code/atomfont_files.cmake index d2b76a2d79..533fe9e527 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/atomfont_files.cmake +++ b/Gems/AtomLyIntegration/AtomFont/Code/atomfont_files.cmake @@ -33,5 +33,4 @@ set(FILES Include/AtomLyIntegration/AtomFont/AtomNullFont.h Include/AtomLyIntegration/AtomFont/resource.h Include/AtomLyIntegration/AtomFont/AtomFont_precompiled.h - Source/AtomFont_precompiled.cpp ) diff --git a/Gems/Camera/Code/Source/Camera_precompiled.cpp b/Gems/Camera/Code/Source/Camera_precompiled.cpp deleted file mode 100644 index a305cdc9df..0000000000 --- a/Gems/Camera/Code/Source/Camera_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "Camera_precompiled.h" diff --git a/Gems/Camera/Code/camera_files.cmake b/Gems/Camera/Code/camera_files.cmake index f8bf93d66d..43f29435c5 100644 --- a/Gems/Camera/Code/camera_files.cmake +++ b/Gems/Camera/Code/camera_files.cmake @@ -16,6 +16,5 @@ set(FILES camera_files.cmake Source/CameraComponentController.cpp Source/CameraComponentController.h Source/CameraViewRegistrationBus.h - Source/Camera_precompiled.cpp Source/Camera_precompiled.h ) diff --git a/Gems/CameraFramework/Code/Source/CameraFramework_precompiled.cpp b/Gems/CameraFramework/Code/Source/CameraFramework_precompiled.cpp deleted file mode 100644 index e5c5926821..0000000000 --- a/Gems/CameraFramework/Code/Source/CameraFramework_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CameraFramework_precompiled.h" diff --git a/Gems/CameraFramework/Code/cameraframework_files.cmake b/Gems/CameraFramework/Code/cameraframework_files.cmake index f6571f1689..c62e7d6455 100644 --- a/Gems/CameraFramework/Code/cameraframework_files.cmake +++ b/Gems/CameraFramework/Code/cameraframework_files.cmake @@ -16,6 +16,5 @@ set(FILES Include/CameraFramework/ICameraTransformBehavior.h Source/CameraRigComponent.h Source/CameraRigComponent.cpp - Source/CameraFramework_precompiled.cpp Source/CameraFramework_precompiled.h ) diff --git a/Gems/DebugDraw/Code/Source/DebugDraw_precompiled.cpp b/Gems/DebugDraw/Code/Source/DebugDraw_precompiled.cpp deleted file mode 100644 index d5601bd1c0..0000000000 --- a/Gems/DebugDraw/Code/Source/DebugDraw_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "DebugDraw_precompiled.h" diff --git a/Gems/DebugDraw/Code/debugdraw_editor_files.cmake b/Gems/DebugDraw/Code/debugdraw_editor_files.cmake index a5adb2faac..da5e2c0870 100644 --- a/Gems/DebugDraw/Code/debugdraw_editor_files.cmake +++ b/Gems/DebugDraw/Code/debugdraw_editor_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/DebugDraw_precompiled.cpp Source/DebugDraw_precompiled.h Include/DebugDraw/DebugDrawBus.h Source/DebugDrawModule.cpp diff --git a/Gems/DebugDraw/Code/debugdraw_files.cmake b/Gems/DebugDraw/Code/debugdraw_files.cmake index 4e0b115f1b..bc53fd1d26 100644 --- a/Gems/DebugDraw/Code/debugdraw_files.cmake +++ b/Gems/DebugDraw/Code/debugdraw_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/DebugDraw_precompiled.cpp Source/DebugDraw_precompiled.h Include/DebugDraw/DebugDrawBus.h Source/DebugDrawLineComponent.cpp diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.h index 731641f6aa..78ffa4ecda 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.h @@ -12,6 +12,7 @@ #pragma once +#include #include QT_FORWARD_DECLARE_CLASS(QOpenGLContext); diff --git a/Gems/EMotionFX/Code/Source/EMotionFX_precompiled.cpp b/Gems/EMotionFX/Code/Source/EMotionFX_precompiled.cpp deleted file mode 100644 index c827107a59..0000000000 --- a/Gems/EMotionFX/Code/Source/EMotionFX_precompiled.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - - -#include "EMotionFX_precompiled.h" diff --git a/Gems/EMotionFX/Code/emotionfx_editor_files.cmake b/Gems/EMotionFX/Code/emotionfx_editor_files.cmake index d8216822d4..8d88013e39 100644 --- a/Gems/EMotionFX/Code/emotionfx_editor_files.cmake +++ b/Gems/EMotionFX/Code/emotionfx_editor_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/EMotionFX_precompiled.cpp Source/EMotionFX_precompiled.h ../Assets/Editor/Layouts/Layouts.qrc ../Assets/Editor/Images/Icons/Resources.qrc diff --git a/Gems/EMotionFX/Code/emotionfx_files.cmake b/Gems/EMotionFX/Code/emotionfx_files.cmake index 6650bb05be..88440f2d1d 100644 --- a/Gems/EMotionFX/Code/emotionfx_files.cmake +++ b/Gems/EMotionFX/Code/emotionfx_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/EMotionFX_precompiled.cpp Source/EMotionFX_precompiled.h Include/Integration/AnimationBus.h Include/Integration/MotionExtractionBus.h diff --git a/Gems/FastNoise/Code/Source/FastNoise_precompiled.cpp b/Gems/FastNoise/Code/Source/FastNoise_precompiled.cpp deleted file mode 100644 index 015459eeae..0000000000 --- a/Gems/FastNoise/Code/Source/FastNoise_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "FastNoise_precompiled.h" diff --git a/Gems/FastNoise/Code/fastnoise_files.cmake b/Gems/FastNoise/Code/fastnoise_files.cmake index 1846b689f7..56b7997848 100644 --- a/Gems/FastNoise/Code/fastnoise_files.cmake +++ b/Gems/FastNoise/Code/fastnoise_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/FastNoise_precompiled.cpp Source/FastNoise_precompiled.h Include/FastNoise/Ebuses/FastNoiseBus.h Include/FastNoise/Ebuses/FastNoiseGradientRequestBus.h diff --git a/Gems/Gestures/Code/Source/Gestures_precompiled.cpp b/Gems/Gestures/Code/Source/Gestures_precompiled.cpp deleted file mode 100644 index f0f3900ac9..0000000000 --- a/Gems/Gestures/Code/Source/Gestures_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "Gestures_precompiled.h" diff --git a/Gems/Gestures/Code/gestures_files.cmake b/Gems/Gestures/Code/gestures_files.cmake index c4b6dec967..c94189a295 100644 --- a/Gems/Gestures/Code/gestures_files.cmake +++ b/Gems/Gestures/Code/gestures_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/Gestures_precompiled.cpp Source/Gestures_precompiled.h Include/Gestures/GestureRecognizerClickOrTap.h Include/Gestures/GestureRecognizerClickOrTap.inl diff --git a/Gems/GradientSignal/Code/Source/GradientSignal_precompiled.cpp b/Gems/GradientSignal/Code/Source/GradientSignal_precompiled.cpp deleted file mode 100644 index cc70b11143..0000000000 --- a/Gems/GradientSignal/Code/Source/GradientSignal_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "GradientSignal_precompiled.h" diff --git a/Gems/GradientSignal/Code/gradientsignal_files.cmake b/Gems/GradientSignal/Code/gradientsignal_files.cmake index 1b5b16b5e0..88c6c604fe 100644 --- a/Gems/GradientSignal/Code/gradientsignal_files.cmake +++ b/Gems/GradientSignal/Code/gradientsignal_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/GradientSignal_precompiled.cpp Source/GradientSignal_precompiled.h Include/GradientSignal/GradientSampler.h Include/GradientSignal/SmoothStep.h diff --git a/Gems/GraphCanvas/Code/graphcanvas_files.cmake b/Gems/GraphCanvas/Code/graphcanvas_files.cmake index 98db1c7709..13d8fa8832 100644 --- a/Gems/GraphCanvas/Code/graphcanvas_files.cmake +++ b/Gems/GraphCanvas/Code/graphcanvas_files.cmake @@ -10,7 +10,6 @@ # set(FILES - precompiled.cpp precompiled.h Include/GraphCanvas/Widgets/RootGraphicsItem.h Include/GraphCanvas/tools.h diff --git a/Gems/GraphCanvas/Code/precompiled.cpp b/Gems/GraphCanvas/Code/precompiled.cpp deleted file mode 100644 index 51bab26696..0000000000 --- a/Gems/GraphCanvas/Code/precompiled.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "precompiled.h" - diff --git a/Gems/HttpRequestor/Code/Source/HttpRequestor_precompiled.cpp b/Gems/HttpRequestor/Code/Source/HttpRequestor_precompiled.cpp deleted file mode 100644 index 87aa3da28e..0000000000 --- a/Gems/HttpRequestor/Code/Source/HttpRequestor_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "HttpRequestor_precompiled.h" diff --git a/Gems/HttpRequestor/Code/httprequestor_files.cmake b/Gems/HttpRequestor/Code/httprequestor_files.cmake index c699e829c5..2e83237d35 100644 --- a/Gems/HttpRequestor/Code/httprequestor_files.cmake +++ b/Gems/HttpRequestor/Code/httprequestor_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/HttpRequestor_precompiled.cpp Source/HttpRequestor_precompiled.h Source/HttpRequestManager.cpp Source/HttpRequestManager.h diff --git a/Gems/HttpRequestor/Code/lmbraws_unsupported_files.cmake b/Gems/HttpRequestor/Code/lmbraws_unsupported_files.cmake index bc5bbc81ca..dee0851f34 100644 --- a/Gems/HttpRequestor/Code/lmbraws_unsupported_files.cmake +++ b/Gems/HttpRequestor/Code/lmbraws_unsupported_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/HttpRequestor_precompiled.cpp Source/HttpRequestor_precompiled.h Source/ComponentStub.cpp ) diff --git a/Gems/ImGui/Code/Source/ImGui_precompiled.cpp b/Gems/ImGui/Code/Source/ImGui_precompiled.cpp deleted file mode 100644 index aa38ffff9c..0000000000 --- a/Gems/ImGui/Code/Source/ImGui_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "ImGui_precompiled.h" diff --git a/Gems/ImGui/Code/imgui_common_files.cmake b/Gems/ImGui/Code/imgui_common_files.cmake index 8ece0845d6..851cd0ccf5 100644 --- a/Gems/ImGui/Code/imgui_common_files.cmake +++ b/Gems/ImGui/Code/imgui_common_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/ImGui_precompiled.cpp Source/ImGui_precompiled.h Include/ImGuiBus.h Include/ImGuiContextScope.h diff --git a/Gems/ImGui/Code/imgui_lyutils_static_files.cmake b/Gems/ImGui/Code/imgui_lyutils_static_files.cmake index 64e5ea4072..9ed0113424 100644 --- a/Gems/ImGui/Code/imgui_lyutils_static_files.cmake +++ b/Gems/ImGui/Code/imgui_lyutils_static_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/ImGui_precompiled.cpp Source/ImGui_precompiled.h Include/LYImGuiUtils/HistogramContainer.h Include/LYImGuiUtils/ImGuiDrawHelpers.h diff --git a/Gems/InAppPurchases/Code/Source/InAppPurchases_precompiled.cpp b/Gems/InAppPurchases/Code/Source/InAppPurchases_precompiled.cpp deleted file mode 100644 index b865614634..0000000000 --- a/Gems/InAppPurchases/Code/Source/InAppPurchases_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates, or -* a third party where indicated. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "InAppPurchases_precompiled.h" diff --git a/Gems/InAppPurchases/Code/inapppurchases_files.cmake b/Gems/InAppPurchases/Code/inapppurchases_files.cmake index 7b75343af9..01a867313b 100644 --- a/Gems/InAppPurchases/Code/inapppurchases_files.cmake +++ b/Gems/InAppPurchases/Code/inapppurchases_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/InAppPurchases_precompiled.cpp Source/InAppPurchases_precompiled.h Include/InAppPurchases/InAppPurchasesBus.h Include/InAppPurchases/InAppPurchasesInterface.h diff --git a/Gems/LmbrCentral/Code/Source/LmbrCentral_precompiled.cpp b/Gems/LmbrCentral/Code/Source/LmbrCentral_precompiled.cpp deleted file mode 100644 index 5752d6a093..0000000000 --- a/Gems/LmbrCentral/Code/Source/LmbrCentral_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "LmbrCentral_precompiled.h" diff --git a/Gems/LmbrCentral/Code/lmbrcentral_files.cmake b/Gems/LmbrCentral/Code/lmbrcentral_files.cmake index 9b4d01af23..d18da75507 100644 --- a/Gems/LmbrCentral/Code/lmbrcentral_files.cmake +++ b/Gems/LmbrCentral/Code/lmbrcentral_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/LmbrCentral_precompiled.cpp Source/LmbrCentral_precompiled.h include/LmbrCentral/Ai/NavigationComponentBus.h include/LmbrCentral/Ai/NavigationAreaBus.h diff --git a/Gems/LyShine/Code/Editor/UiCanvasEditor_precompiled.cpp b/Gems/LyShine/Code/Editor/UiCanvasEditor_precompiled.cpp deleted file mode 100644 index e894c3a0f7..0000000000 --- a/Gems/LyShine/Code/Editor/UiCanvasEditor_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "UiCanvasEditor_precompiled.h" diff --git a/Gems/LyShine/Code/Source/Animation/LyShine_precompiled.cpp b/Gems/LyShine/Code/Source/Animation/LyShine_precompiled.cpp deleted file mode 100644 index 02d8df72c1..0000000000 --- a/Gems/LyShine/Code/Source/Animation/LyShine_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "LyShine_precompiled.h" diff --git a/Gems/LyShine/Code/Source/LyShine_precompiled.cpp b/Gems/LyShine/Code/Source/LyShine_precompiled.cpp deleted file mode 100644 index 02d8df72c1..0000000000 --- a/Gems/LyShine/Code/Source/LyShine_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "LyShine_precompiled.h" diff --git a/Gems/LyShine/Code/lyshine_static_files.cmake b/Gems/LyShine/Code/lyshine_static_files.cmake index 8491a66030..2435a01623 100644 --- a/Gems/LyShine/Code/lyshine_static_files.cmake +++ b/Gems/LyShine/Code/lyshine_static_files.cmake @@ -16,7 +16,6 @@ set(FILES Source/LyShine.h Source/LyShineDebug.cpp Source/LyShineDebug.h - Source/LyShine_precompiled.cpp Source/LyShine_precompiled.h Source/StringUtfUtils.h Source/UiImageComponent.cpp diff --git a/Gems/LyShine/Code/lyshine_uicanvaseditor_files.cmake b/Gems/LyShine/Code/lyshine_uicanvaseditor_files.cmake index 82fc50584c..a434ec2343 100644 --- a/Gems/LyShine/Code/lyshine_uicanvaseditor_files.cmake +++ b/Gems/LyShine/Code/lyshine_uicanvaseditor_files.cmake @@ -12,7 +12,6 @@ set(FILES Editor/LyShineEditorSystemComponent.cpp Editor/LyShineEditorSystemComponent.h - Editor/UiCanvasEditor_precompiled.cpp Editor/UiCanvasEditor_precompiled.h Editor/UiCanvasEditor.qrc Editor/Animation/UiAnimViewDialog.cpp diff --git a/Gems/LyShineExamples/Code/Source/LyShineExamples_precompiled.cpp b/Gems/LyShineExamples/Code/Source/LyShineExamples_precompiled.cpp deleted file mode 100644 index 33c6ac3831..0000000000 --- a/Gems/LyShineExamples/Code/Source/LyShineExamples_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates, or -* a third party where indicated. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "LyShineExamples_precompiled.h" diff --git a/Gems/LyShineExamples/Code/lyshineexamples_files.cmake b/Gems/LyShineExamples/Code/lyshineexamples_files.cmake index 08fccda4ea..c82899c374 100644 --- a/Gems/LyShineExamples/Code/lyshineexamples_files.cmake +++ b/Gems/LyShineExamples/Code/lyshineexamples_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/LyShineExamples_precompiled.cpp Source/LyShineExamples_precompiled.h Include/LyShineExamples/LyShineExamplesBus.h Include/LyShineExamples/LyShineExamplesCppExampleBus.h diff --git a/Gems/Maestro/Code/Source/Cinematics/Maestro_precompiled.cpp b/Gems/Maestro/Code/Source/Cinematics/Maestro_precompiled.cpp deleted file mode 100644 index 40dec66d87..0000000000 --- a/Gems/Maestro/Code/Source/Cinematics/Maestro_precompiled.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "Maestro_precompiled.h" diff --git a/Gems/Maestro/Code/Source/Maestro_precompiled.cpp b/Gems/Maestro/Code/Source/Maestro_precompiled.cpp deleted file mode 100644 index d0c3f18d11..0000000000 --- a/Gems/Maestro/Code/Source/Maestro_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "Maestro_precompiled.h" diff --git a/Gems/Maestro/Code/maestro_static_files.cmake b/Gems/Maestro/Code/maestro_static_files.cmake index c0fb90ddca..3fd5671898 100644 --- a/Gems/Maestro/Code/maestro_static_files.cmake +++ b/Gems/Maestro/Code/maestro_static_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/Maestro_precompiled.cpp Source/Maestro_precompiled.h Source/Cinematics/ShadowsSetupNode.h Source/Cinematics/ShadowsSetupNode.cpp diff --git a/Gems/MessagePopup/Code/Source/MessagePopup_precompiled.cpp b/Gems/MessagePopup/Code/Source/MessagePopup_precompiled.cpp deleted file mode 100644 index 45495b87d0..0000000000 --- a/Gems/MessagePopup/Code/Source/MessagePopup_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright(c) Amazon.com, Inc.or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -*/ - -#include "MessagePopup_precompiled.h" diff --git a/Gems/MessagePopup/Code/messagepopup_files.cmake b/Gems/MessagePopup/Code/messagepopup_files.cmake index 3c8b98378a..73a5f3f6b6 100644 --- a/Gems/MessagePopup/Code/messagepopup_files.cmake +++ b/Gems/MessagePopup/Code/messagepopup_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/MessagePopup_precompiled.cpp Source/MessagePopup_precompiled.h Include/MessagePopup/MessagePopupBus.h Source/MessagePopupSystemComponent.cpp diff --git a/Gems/Metastream/Code/Source/Metastream_precompiled.cpp b/Gems/Metastream/Code/Source/Metastream_precompiled.cpp deleted file mode 100644 index 7b4896ad9f..0000000000 --- a/Gems/Metastream/Code/Source/Metastream_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "Metastream_precompiled.h" diff --git a/Gems/Metastream/Code/metastream_files.cmake b/Gems/Metastream/Code/metastream_files.cmake index c5fd0ee95b..575aa09340 100644 --- a/Gems/Metastream/Code/metastream_files.cmake +++ b/Gems/Metastream/Code/metastream_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/Metastream_precompiled.cpp Source/Metastream_precompiled.h Include/Metastream/MetastreamBus.h Source/DataCache.h diff --git a/Gems/Microphone/Code/Source/Microphone_precompiled.cpp b/Gems/Microphone/Code/Source/Microphone_precompiled.cpp deleted file mode 100644 index a584ed909d..0000000000 --- a/Gems/Microphone/Code/Source/Microphone_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "Microphone_precompiled.h" diff --git a/Gems/Microphone/Code/microphone_files.cmake b/Gems/Microphone/Code/microphone_files.cmake index 1058deb13c..d32a723cfb 100644 --- a/Gems/Microphone/Code/microphone_files.cmake +++ b/Gems/Microphone/Code/microphone_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/Microphone_precompiled.cpp Source/Microphone_precompiled.h Source/MicrophoneSystemComponent.cpp Source/MicrophoneSystemComponent.h diff --git a/Gems/Multiplayer/Code/Source/Multiplayer_precompiled.cpp b/Gems/Multiplayer/Code/Source/Multiplayer_precompiled.cpp deleted file mode 100644 index fa8fd7b67c..0000000000 --- a/Gems/Multiplayer/Code/Source/Multiplayer_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "Multiplayer_precompiled.h" diff --git a/Gems/Multiplayer/Code/multiplayer_debug_files.cmake b/Gems/Multiplayer/Code/multiplayer_debug_files.cmake index 8d0b121735..4b175c7691 100644 --- a/Gems/Multiplayer/Code/multiplayer_debug_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_debug_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/Multiplayer_precompiled.cpp Source/Multiplayer_precompiled.h Source/Debug/MultiplayerDebugModule.cpp Source/Debug/MultiplayerDebugModule.h diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index 73de45ba9d..9f5ca8c805 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -41,7 +41,6 @@ set(FILES Include/Multiplayer/NetworkTime/RewindableObject.inl Include/Multiplayer/Physics/PhysicsUtils.h Include/Multiplayer/ReplicationWindows/IReplicationWindow.h - Source/Multiplayer_precompiled.cpp Source/Multiplayer_precompiled.h Source/MultiplayerSystemComponent.cpp Source/MultiplayerSystemComponent.h diff --git a/Gems/Multiplayer/Code/multiplayer_tools_files.cmake b/Gems/Multiplayer/Code/multiplayer_tools_files.cmake index 3fef954ba6..bc0b3feeeb 100644 --- a/Gems/Multiplayer/Code/multiplayer_tools_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_tools_files.cmake @@ -11,7 +11,6 @@ set(FILES Include/Multiplayer/IMultiplayerTools.h - Source/Multiplayer_precompiled.cpp Source/Multiplayer_precompiled.h Source/Pipeline/NetworkPrefabProcessor.cpp Source/Pipeline/NetworkPrefabProcessor.h diff --git a/Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods_precompiled.cpp b/Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods_precompiled.cpp deleted file mode 100644 index 4b6948a654..0000000000 --- a/Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include diff --git a/Gems/PhysX/Code/NumericalMethods/numericalmethods_files.cmake b/Gems/PhysX/Code/NumericalMethods/numericalmethods_files.cmake index 1e7abecd31..eb96204150 100644 --- a/Gems/PhysX/Code/NumericalMethods/numericalmethods_files.cmake +++ b/Gems/PhysX/Code/NumericalMethods/numericalmethods_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/NumericalMethods_precompiled.cpp Source/NumericalMethods_precompiled.h Include/NumericalMethods/Optimization.h Include/NumericalMethods/Eigenanalysis.h diff --git a/Gems/PhysX/Code/Source/PhysXUnsupported_precompiled.cpp b/Gems/PhysX/Code/Source/PhysXUnsupported_precompiled.cpp deleted file mode 100644 index 04bb39a00f..0000000000 --- a/Gems/PhysX/Code/Source/PhysXUnsupported_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include diff --git a/Gems/PhysX/Code/Source/PhysX_precompiled.cpp b/Gems/PhysX/Code/Source/PhysX_precompiled.cpp deleted file mode 100644 index 1300e5b541..0000000000 --- a/Gems/PhysX/Code/Source/PhysX_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include diff --git a/Gems/PhysX/Code/physx_files.cmake b/Gems/PhysX/Code/physx_files.cmake index 6350c06e0d..24aa42d62a 100644 --- a/Gems/PhysX/Code/physx_files.cmake +++ b/Gems/PhysX/Code/physx_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/PhysX_precompiled.cpp Source/PhysX_precompiled.h Source/SystemComponent.cpp Source/SystemComponent.h diff --git a/Gems/PhysXDebug/Code/Source/PhysXDebugUnsupported_precompiled.cpp b/Gems/PhysXDebug/Code/Source/PhysXDebugUnsupported_precompiled.cpp deleted file mode 100644 index 4199046abd..0000000000 --- a/Gems/PhysXDebug/Code/Source/PhysXDebugUnsupported_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include diff --git a/Gems/PhysXDebug/Code/Source/PhysXDebug_precompiled.cpp b/Gems/PhysXDebug/Code/Source/PhysXDebug_precompiled.cpp deleted file mode 100644 index 2fb13c5f8a..0000000000 --- a/Gems/PhysXDebug/Code/Source/PhysXDebug_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "PhysXDebug_precompiled.h" diff --git a/Gems/PhysXDebug/Code/physxdebug_editor_files.cmake b/Gems/PhysXDebug/Code/physxdebug_editor_files.cmake index 2645795a77..460da598a0 100644 --- a/Gems/PhysXDebug/Code/physxdebug_editor_files.cmake +++ b/Gems/PhysXDebug/Code/physxdebug_editor_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/PhysXDebug_precompiled.cpp Source/PhysXDebug_precompiled.h Source/EditorSystemComponent.cpp Source/EditorSystemComponent.h diff --git a/Gems/PhysXDebug/Code/physxdebug_files.cmake b/Gems/PhysXDebug/Code/physxdebug_files.cmake index 7eea56626b..2d04c8e5de 100644 --- a/Gems/PhysXDebug/Code/physxdebug_files.cmake +++ b/Gems/PhysXDebug/Code/physxdebug_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/PhysXDebug_precompiled.cpp Source/PhysXDebug_precompiled.h Include/PhysXDebug/PhysXDebugBus.h Source/Module.cpp diff --git a/Gems/PhysXDebug/Code/physxdebug_unsupported_files.cmake b/Gems/PhysXDebug/Code/physxdebug_unsupported_files.cmake index e5d7ae7e46..76649b2a91 100644 --- a/Gems/PhysXDebug/Code/physxdebug_unsupported_files.cmake +++ b/Gems/PhysXDebug/Code/physxdebug_unsupported_files.cmake @@ -11,6 +11,5 @@ set(FILES Source/ModuleUnsupported.cpp - Source/PhysXDebugUnsupported_precompiled.cpp Source/PhysXDebugUnsupported_precompiled.h ) diff --git a/Gems/ScriptCanvas/Code/Editor/precompiled.cpp b/Gems/ScriptCanvas/Code/Editor/precompiled.cpp deleted file mode 100644 index 6fdd7bdc45..0000000000 --- a/Gems/ScriptCanvas/Code/Editor/precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "precompiled.h" diff --git a/Gems/ScriptCanvas/Code/Source/precompiled.cpp b/Gems/ScriptCanvas/Code/Source/precompiled.cpp deleted file mode 100644 index 6fdd7bdc45..0000000000 --- a/Gems/ScriptCanvas/Code/Source/precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "precompiled.h" diff --git a/Gems/ScriptCanvas/Code/scriptcanvasgem_editor_files.cmake b/Gems/ScriptCanvas/Code/scriptcanvasgem_editor_files.cmake index 2f1555af3d..54fd98b4ce 100644 --- a/Gems/ScriptCanvas/Code/scriptcanvasgem_editor_files.cmake +++ b/Gems/ScriptCanvas/Code/scriptcanvasgem_editor_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Editor/precompiled.cpp Editor/precompiled.h Editor/ScriptCanvasEditorGem.cpp Editor/Settings.h diff --git a/Gems/ScriptCanvas/Code/scriptcanvasgem_editor_shared_files.cmake b/Gems/ScriptCanvas/Code/scriptcanvasgem_editor_shared_files.cmake index 17b62d1d3d..42b6bfed72 100644 --- a/Gems/ScriptCanvas/Code/scriptcanvasgem_editor_shared_files.cmake +++ b/Gems/ScriptCanvas/Code/scriptcanvasgem_editor_shared_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Editor/precompiled.cpp Editor/precompiled.h Editor/ScriptCanvasEditorGem.cpp Include/ScriptCanvas/ScriptCanvasGem.h diff --git a/Gems/ScriptCanvas/Code/scriptcanvasgem_game_files.cmake b/Gems/ScriptCanvas/Code/scriptcanvasgem_game_files.cmake index ead7f6d660..dfe0c6f5e3 100644 --- a/Gems/ScriptCanvas/Code/scriptcanvasgem_game_files.cmake +++ b/Gems/ScriptCanvas/Code/scriptcanvasgem_game_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/precompiled.cpp Source/precompiled.h Source/ScriptCanvasGem.cpp ) diff --git a/Gems/ScriptCanvas/Code/scriptcanvasgem_tests_files.cmake b/Gems/ScriptCanvas/Code/scriptcanvasgem_tests_files.cmake index 9a877a2b42..7791c9ca48 100644 --- a/Gems/ScriptCanvas/Code/scriptcanvasgem_tests_files.cmake +++ b/Gems/ScriptCanvas/Code/scriptcanvasgem_tests_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/precompiled.cpp Source/precompiled.h Tests/ScriptCanvasTest.cpp ) diff --git a/Gems/ScriptCanvasDeveloper/Code/Source/precompiled.cpp b/Gems/ScriptCanvasDeveloper/Code/Source/precompiled.cpp deleted file mode 100644 index 6fdd7bdc45..0000000000 --- a/Gems/ScriptCanvasDeveloper/Code/Source/precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "precompiled.h" diff --git a/Gems/ScriptCanvasDeveloper/Code/scriptcanvasdeveloper_gem_common_files.cmake b/Gems/ScriptCanvasDeveloper/Code/scriptcanvasdeveloper_gem_common_files.cmake index fd63448066..34de0f5910 100644 --- a/Gems/ScriptCanvasDeveloper/Code/scriptcanvasdeveloper_gem_common_files.cmake +++ b/Gems/ScriptCanvasDeveloper/Code/scriptcanvasdeveloper_gem_common_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/precompiled.cpp Source/precompiled.h Include/ScriptCanvasDeveloper/ScriptCanvasDeveloperGem.h Include/ScriptCanvasDeveloper/ScriptCanvasDeveloperComponent.h diff --git a/Gems/ScriptCanvasPhysics/Code/Source/ScriptCanvasPhysics_precompiled.cpp b/Gems/ScriptCanvasPhysics/Code/Source/ScriptCanvasPhysics_precompiled.cpp deleted file mode 100644 index 683b5507b8..0000000000 --- a/Gems/ScriptCanvasPhysics/Code/Source/ScriptCanvasPhysics_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "ScriptCanvasPhysics_precompiled.h" diff --git a/Gems/ScriptCanvasPhysics/Code/scriptcanvas_physics_files.cmake b/Gems/ScriptCanvasPhysics/Code/scriptcanvas_physics_files.cmake index b2fdfacf67..8815d67909 100644 --- a/Gems/ScriptCanvasPhysics/Code/scriptcanvas_physics_files.cmake +++ b/Gems/ScriptCanvasPhysics/Code/scriptcanvas_physics_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/ScriptCanvasPhysics_precompiled.cpp Source/ScriptCanvasPhysics_precompiled.h Source/PhysicsNodeLibrary.cpp Source/PhysicsNodeLibrary.h diff --git a/Gems/ScriptCanvasPhysics/Code/scriptcanvas_physics_shared_files.cmake b/Gems/ScriptCanvasPhysics/Code/scriptcanvas_physics_shared_files.cmake index 769a3db241..b7c97e99ec 100644 --- a/Gems/ScriptCanvasPhysics/Code/scriptcanvas_physics_shared_files.cmake +++ b/Gems/ScriptCanvasPhysics/Code/scriptcanvas_physics_shared_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/ScriptCanvasPhysics_precompiled.cpp Source/ScriptCanvasPhysics_precompiled.h Source/ScriptCanvasPhysicsModule.cpp ) diff --git a/Gems/ScriptEvents/Code/Source/precompiled.cpp b/Gems/ScriptEvents/Code/Source/precompiled.cpp deleted file mode 100644 index 6fdd7bdc45..0000000000 --- a/Gems/ScriptEvents/Code/Source/precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "precompiled.h" diff --git a/Gems/ScriptEvents/Code/scriptevents_editor_files.cmake b/Gems/ScriptEvents/Code/scriptevents_editor_files.cmake index 8fc57de0dd..c3a491d5bf 100644 --- a/Gems/ScriptEvents/Code/scriptevents_editor_files.cmake +++ b/Gems/ScriptEvents/Code/scriptevents_editor_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/precompiled.cpp Source/precompiled.h Source/Editor/ScriptEventsEditorGem.cpp Source/Editor/ScriptEventsSystemEditorComponent.cpp diff --git a/Gems/ScriptEvents/Code/scriptevents_files.cmake b/Gems/ScriptEvents/Code/scriptevents_files.cmake index a79f81ab28..348ac8b1b5 100644 --- a/Gems/ScriptEvents/Code/scriptevents_files.cmake +++ b/Gems/ScriptEvents/Code/scriptevents_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/precompiled.cpp Source/precompiled.h Source/ScriptEventsGem.cpp ) diff --git a/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweener_precompiled.cpp b/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweener_precompiled.cpp deleted file mode 100644 index 85423f94c1..0000000000 --- a/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweener_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates, or -* a third party where indicated. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "ScriptedEntityTweener_precompiled.h" diff --git a/Gems/ScriptedEntityTweener/Code/scriptedentitytweener_files.cmake b/Gems/ScriptedEntityTweener/Code/scriptedentitytweener_files.cmake index b889832c16..e3d8d57e2b 100644 --- a/Gems/ScriptedEntityTweener/Code/scriptedentitytweener_files.cmake +++ b/Gems/ScriptedEntityTweener/Code/scriptedentitytweener_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/ScriptedEntityTweener_precompiled.cpp Source/ScriptedEntityTweener_precompiled.h Include/ScriptedEntityTweener/ScriptedEntityTweenerBus.h Include/ScriptedEntityTweener/ScriptedEntityTweenerEnums.h diff --git a/Gems/SliceFavorites/Code/Source/SliceFavorites_precompiled.cpp b/Gems/SliceFavorites/Code/Source/SliceFavorites_precompiled.cpp deleted file mode 100644 index 99dba85db4..0000000000 --- a/Gems/SliceFavorites/Code/Source/SliceFavorites_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "SliceFavorites_precompiled.h" diff --git a/Gems/SliceFavorites/Code/slicefavorites_files.cmake b/Gems/SliceFavorites/Code/slicefavorites_files.cmake index c0b878cbb8..06fcdc87e3 100644 --- a/Gems/SliceFavorites/Code/slicefavorites_files.cmake +++ b/Gems/SliceFavorites/Code/slicefavorites_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/SliceFavorites_precompiled.cpp Source/SliceFavorites_precompiled.h Include/SliceFavorites/SliceFavoritesBus.h Source/SliceFavoritesSystemComponent.cpp diff --git a/Gems/StartingPointCamera/Code/Source/StartingPointCamera_precompiled.cpp b/Gems/StartingPointCamera/Code/Source/StartingPointCamera_precompiled.cpp deleted file mode 100644 index 79702ea5f2..0000000000 --- a/Gems/StartingPointCamera/Code/Source/StartingPointCamera_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "StartingPointCamera_precompiled.h" diff --git a/Gems/StartingPointCamera/Code/startingpointcamera_files.cmake b/Gems/StartingPointCamera/Code/startingpointcamera_files.cmake index e0f5331e41..9f4c100f77 100644 --- a/Gems/StartingPointCamera/Code/startingpointcamera_files.cmake +++ b/Gems/StartingPointCamera/Code/startingpointcamera_files.cmake @@ -33,6 +33,5 @@ set(FILES Source/CameraTransformBehaviors/OffsetCameraPosition.cpp Source/CameraTransformBehaviors/Rotate.h Source/CameraTransformBehaviors/Rotate.cpp - Source/StartingPointCamera_precompiled.cpp Source/StartingPointCamera_precompiled.h ) diff --git a/Gems/StartingPointInput/Code/Source/StartingPointInput_precompiled.cpp b/Gems/StartingPointInput/Code/Source/StartingPointInput_precompiled.cpp deleted file mode 100644 index e4c7581b08..0000000000 --- a/Gems/StartingPointInput/Code/Source/StartingPointInput_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "StartingPointInput_precompiled.h" diff --git a/Gems/StartingPointInput/Code/startingpointinput_editor_files.cmake b/Gems/StartingPointInput/Code/startingpointinput_editor_files.cmake index b1e619c55d..fd69b6180c 100644 --- a/Gems/StartingPointInput/Code/startingpointinput_editor_files.cmake +++ b/Gems/StartingPointInput/Code/startingpointinput_editor_files.cmake @@ -24,6 +24,4 @@ set(FILES Source/InputNode.cpp Source/StartingPointInputGem.cpp Source/StartingPointInput_precompiled.h - Source/StartingPointInput_precompiled.cpp - ) diff --git a/Gems/StartingPointInput/Code/startingpointinput_files.cmake b/Gems/StartingPointInput/Code/startingpointinput_files.cmake index 2208dff6b5..c330233722 100644 --- a/Gems/StartingPointInput/Code/startingpointinput_files.cmake +++ b/Gems/StartingPointInput/Code/startingpointinput_files.cmake @@ -27,5 +27,4 @@ set(FILES Source/InputHandlerNodeable.ScriptCanvasNodeable.xml Source/InputNode.ScriptCanvasGrammar.xml Source/StartingPointInput_precompiled.h - Source/StartingPointInput_precompiled.cpp ) diff --git a/Gems/StartingPointMovement/Code/CMakeLists.txt b/Gems/StartingPointMovement/Code/CMakeLists.txt index 417dfe01ee..b9178dc839 100644 --- a/Gems/StartingPointMovement/Code/CMakeLists.txt +++ b/Gems/StartingPointMovement/Code/CMakeLists.txt @@ -9,21 +9,6 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -ly_add_target( - NAME StartingPointMovement.Static STATIC - NAMESPACE Gem - FILES_CMAKE - startingpointmovement_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Source - PUBLIC - Include - BUILD_DEPENDENCIES - PRIVATE - AZ::AzCore -) - ly_add_target( NAME StartingPointMovement ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} NAMESPACE Gem @@ -36,7 +21,6 @@ ly_add_target( Include BUILD_DEPENDENCIES PRIVATE - Gem::StartingPointMovement.Static AZ::AzCore AZ::AzFramework ) diff --git a/Gems/StartingPointMovement/Code/Source/StartingPointMovement_precompiled.cpp b/Gems/StartingPointMovement/Code/Source/StartingPointMovement_precompiled.cpp deleted file mode 100644 index 7027e2ede1..0000000000 --- a/Gems/StartingPointMovement/Code/Source/StartingPointMovement_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "StartingPointMovement_precompiled.h" diff --git a/Gems/StartingPointMovement/Code/startingpointmovement_files.cmake b/Gems/StartingPointMovement/Code/startingpointmovement_files.cmake deleted file mode 100644 index 21ce5801ac..0000000000 --- a/Gems/StartingPointMovement/Code/startingpointmovement_files.cmake +++ /dev/null @@ -1,17 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - Include/StartingPointMovement/StartingPointMovementConstants.h - Include/StartingPointMovement/StartingPointMovementUtilities.h - Source/StartingPointMovement_precompiled.cpp - Source/StartingPointMovement_precompiled.h -) diff --git a/Gems/StartingPointMovement/Code/startingpointmovement_shared_files.cmake b/Gems/StartingPointMovement/Code/startingpointmovement_shared_files.cmake index f6bc7b14ea..3fec69b2fe 100644 --- a/Gems/StartingPointMovement/Code/startingpointmovement_shared_files.cmake +++ b/Gems/StartingPointMovement/Code/startingpointmovement_shared_files.cmake @@ -11,4 +11,7 @@ set(FILES Source/StartingPointMovementGem.cpp + Include/StartingPointMovement/StartingPointMovementConstants.h + Include/StartingPointMovement/StartingPointMovementUtilities.h + Source/StartingPointMovement_precompiled.h ) diff --git a/Gems/SurfaceData/Code/Source/SurfaceData_precompiled.cpp b/Gems/SurfaceData/Code/Source/SurfaceData_precompiled.cpp deleted file mode 100644 index ce5861193f..0000000000 --- a/Gems/SurfaceData/Code/Source/SurfaceData_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "SurfaceData_precompiled.h" diff --git a/Gems/SurfaceData/Code/surfacedata_files.cmake b/Gems/SurfaceData/Code/surfacedata_files.cmake index f906a12afc..20abf8d3ab 100644 --- a/Gems/SurfaceData/Code/surfacedata_files.cmake +++ b/Gems/SurfaceData/Code/surfacedata_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/SurfaceData_precompiled.cpp Source/SurfaceData_precompiled.h Include/SurfaceData/SurfaceDataConstants.h Include/SurfaceData/SurfaceDataTypes.h diff --git a/Gems/TextureAtlas/Code/Source/TextureAtlas_precompiled.cpp b/Gems/TextureAtlas/Code/Source/TextureAtlas_precompiled.cpp deleted file mode 100644 index 53e132032b..0000000000 --- a/Gems/TextureAtlas/Code/Source/TextureAtlas_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "TextureAtlas_precompiled.h" diff --git a/Gems/TextureAtlas/Code/textureatlas_files.cmake b/Gems/TextureAtlas/Code/textureatlas_files.cmake index c45c1d49a8..f96daa05d0 100644 --- a/Gems/TextureAtlas/Code/textureatlas_files.cmake +++ b/Gems/TextureAtlas/Code/textureatlas_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/TextureAtlas_precompiled.cpp Source/TextureAtlas_precompiled.h Include/TextureAtlas/TextureAtlasBus.h Include/TextureAtlas/TextureAtlasNotificationBus.h diff --git a/Gems/TickBusOrderViewer/Code/Source/TickBusOrderViewer_precompiled.cpp b/Gems/TickBusOrderViewer/Code/Source/TickBusOrderViewer_precompiled.cpp deleted file mode 100644 index aa7933d130..0000000000 --- a/Gems/TickBusOrderViewer/Code/Source/TickBusOrderViewer_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "TickBusOrderViewer_precompiled.h" diff --git a/Gems/TickBusOrderViewer/Code/tickbusorderviewer_files.cmake b/Gems/TickBusOrderViewer/Code/tickbusorderviewer_files.cmake index ceae29ebe3..a4f0b2228b 100644 --- a/Gems/TickBusOrderViewer/Code/tickbusorderviewer_files.cmake +++ b/Gems/TickBusOrderViewer/Code/tickbusorderviewer_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/TickBusOrderViewer_precompiled.cpp Source/TickBusOrderViewer_precompiled.h Include/TickBusOrderViewer/TickBusOrderViewerBus.h Source/TickBusOrderViewerSystemComponent.cpp diff --git a/Gems/Twitch/Code/Source/Twitch_precompiled.cpp b/Gems/Twitch/Code/Source/Twitch_precompiled.cpp deleted file mode 100644 index 40f10ede34..0000000000 --- a/Gems/Twitch/Code/Source/Twitch_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "Twitch_precompiled.h" diff --git a/Gems/Twitch/Code/lmbraws_unsupported_files.cmake b/Gems/Twitch/Code/lmbraws_unsupported_files.cmake index 1fb36a4871..5c98bf6b97 100644 --- a/Gems/Twitch/Code/lmbraws_unsupported_files.cmake +++ b/Gems/Twitch/Code/lmbraws_unsupported_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/Twitch_precompiled.cpp Source/Twitch_precompiled.h Source/ComponentStub.cpp ) diff --git a/Gems/Twitch/Code/twitch_files.cmake b/Gems/Twitch/Code/twitch_files.cmake index cba8e44961..f06ef55371 100644 --- a/Gems/Twitch/Code/twitch_files.cmake +++ b/Gems/Twitch/Code/twitch_files.cmake @@ -14,7 +14,6 @@ set(FILES Include/Twitch/TwitchTypes.h Include/Twitch/BaseTypes.h Include/Twitch/RESTTypes.h - Source/Twitch_precompiled.cpp Source/Twitch_precompiled.h Source/TwitchSystemComponent.cpp Source/TwitchSystemComponent.h diff --git a/Gems/Vegetation/Code/Source/Vegetation_precompiled.cpp b/Gems/Vegetation/Code/Source/Vegetation_precompiled.cpp deleted file mode 100644 index c8ed8a1b9d..0000000000 --- a/Gems/Vegetation/Code/Source/Vegetation_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "Vegetation_precompiled.h" diff --git a/Gems/Vegetation/Code/vegetation_files.cmake b/Gems/Vegetation/Code/vegetation_files.cmake index ff741902e2..abfd568862 100644 --- a/Gems/Vegetation/Code/vegetation_files.cmake +++ b/Gems/Vegetation/Code/vegetation_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/Vegetation_precompiled.cpp Source/Vegetation_precompiled.h Include/Vegetation/DescriptorListAsset.h Include/Vegetation/Descriptor.h diff --git a/Gems/VirtualGamepad/Code/Source/VirtualGamepad_precompiled.cpp b/Gems/VirtualGamepad/Code/Source/VirtualGamepad_precompiled.cpp deleted file mode 100644 index 8049f28d48..0000000000 --- a/Gems/VirtualGamepad/Code/Source/VirtualGamepad_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "VirtualGamepad_precompiled.h" diff --git a/Gems/VirtualGamepad/Code/virtualgamepad_files.cmake b/Gems/VirtualGamepad/Code/virtualgamepad_files.cmake index 8d026b7dbb..874d6252a2 100644 --- a/Gems/VirtualGamepad/Code/virtualgamepad_files.cmake +++ b/Gems/VirtualGamepad/Code/virtualgamepad_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/VirtualGamepad_precompiled.cpp Source/VirtualGamepad_precompiled.h Include/VirtualGamepad/VirtualGamepadBus.h Source/InputDeviceVirtualGamepad.cpp diff --git a/Gems/WhiteBox/Code/Source/WhiteBoxUnsupported_precompiled.cpp b/Gems/WhiteBox/Code/Source/WhiteBoxUnsupported_precompiled.cpp deleted file mode 100644 index 611ac1f0a1..0000000000 --- a/Gems/WhiteBox/Code/Source/WhiteBoxUnsupported_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - -#include diff --git a/Gems/WhiteBox/Code/Source/WhiteBox_precompiled.cpp b/Gems/WhiteBox/Code/Source/WhiteBox_precompiled.cpp deleted file mode 100644 index 892230742f..0000000000 --- a/Gems/WhiteBox/Code/Source/WhiteBox_precompiled.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - -#include "WhiteBox_precompiled.h" diff --git a/Gems/WhiteBox/Code/whitebox_supported_files.cmake b/Gems/WhiteBox/Code/whitebox_supported_files.cmake index 41aa4433cc..372f8cee45 100644 --- a/Gems/WhiteBox/Code/whitebox_supported_files.cmake +++ b/Gems/WhiteBox/Code/whitebox_supported_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Source/WhiteBox_precompiled.cpp Source/WhiteBox_precompiled.h Include/WhiteBox/WhiteBoxBus.h Source/WhiteBoxAllocator.cpp diff --git a/Gems/WhiteBox/Code/whitebox_unsupported_files.cmake b/Gems/WhiteBox/Code/whitebox_unsupported_files.cmake index a44907e1be..3dca84c067 100644 --- a/Gems/WhiteBox/Code/whitebox_unsupported_files.cmake +++ b/Gems/WhiteBox/Code/whitebox_unsupported_files.cmake @@ -11,6 +11,5 @@ set(FILES Source/WhiteBoxModuleUnsupported.cpp - Source/WhiteBoxUnsupported_precompiled.cpp Source/WhiteBoxUnsupported_precompiled.h ) From 593b679fa3a2c2bfc393d0fee256e50f51cd3c1b Mon Sep 17 00:00:00 2001 From: Terry Michaels Date: Mon, 7 Jun 2021 18:11:56 -0500 Subject: [PATCH 566/811] Main toolbar consolidation and cleanup (#1167) * Moving menu options around * Consolidation and moving of toolbar functioanlity * Fixed non-unity build missing header * Updated camera icon to the correct one * Addressed review feedback * Addressed review feedback * Moved icons to new folder structure/naming --- .../AzQtComponents/Images/Menu/camera.svg | 9 + .../AzQtComponents/Images/Menu/debug.svg | 7 + .../AzQtComponents/Images/Menu/resolution.svg | 7 + .../AzQtComponents/Images/resources.qrc | 5 + Code/Sandbox/Editor/InfoBar.cpp | 394 ------------- Code/Sandbox/Editor/InfoBar.h | 121 ---- Code/Sandbox/Editor/InfoBar.ui | 333 ----------- Code/Sandbox/Editor/LayoutWnd.cpp | 138 ----- Code/Sandbox/Editor/LayoutWnd.h | 8 - Code/Sandbox/Editor/MainWindow.cpp | 98 ---- Code/Sandbox/Editor/MainWindow.h | 2 - Code/Sandbox/Editor/Style/Editor.qss | 14 - Code/Sandbox/Editor/ToolbarManager.cpp | 13 - Code/Sandbox/Editor/ViewportTitleDlg.cpp | 517 +++++++++++++++--- Code/Sandbox/Editor/ViewportTitleDlg.h | 95 +++- Code/Sandbox/Editor/ViewportTitleDlg.ui | 154 ++---- Code/Sandbox/Editor/editor_lib_files.cmake | 4 - 17 files changed, 597 insertions(+), 1322 deletions(-) create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/camera.svg create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/debug.svg create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/resolution.svg delete mode 100644 Code/Sandbox/Editor/InfoBar.cpp delete mode 100644 Code/Sandbox/Editor/InfoBar.h delete mode 100644 Code/Sandbox/Editor/InfoBar.ui diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/camera.svg b/Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/camera.svg new file mode 100644 index 0000000000..7fa565d5b8 --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/camera.svg @@ -0,0 +1,9 @@ + + + Camera + + + + + + \ No newline at end of file diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/debug.svg b/Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/debug.svg new file mode 100644 index 0000000000..938e4e3342 --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/debug.svg @@ -0,0 +1,7 @@ + + + debug + + + + \ No newline at end of file diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/resolution.svg b/Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/resolution.svg new file mode 100644 index 0000000000..2434d6707d --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Images/Menu/resolution.svg @@ -0,0 +1,7 @@ + + + resolution + + + + \ No newline at end of file diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Images/resources.qrc b/Code/Framework/AzQtComponents/AzQtComponents/Images/resources.qrc index 7b0c6530ab..2487917f67 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Images/resources.qrc +++ b/Code/Framework/AzQtComponents/AzQtComponents/Images/resources.qrc @@ -15,4 +15,9 @@ Notifications/download.svg Notifications/link.svg + + Menu/resolution.svg + Menu/debug.svg + Menu/camera.svg + diff --git a/Code/Sandbox/Editor/InfoBar.cpp b/Code/Sandbox/Editor/InfoBar.cpp deleted file mode 100644 index 14ef2e7f05..0000000000 --- a/Code/Sandbox/Editor/InfoBar.cpp +++ /dev/null @@ -1,394 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "InfoBar.h" - -// Editor -#include "MainWindow.h" -#include "DisplaySettings.h" -#include "GameEngine.h" -#include "Include/ITransformManipulator.h" -#include "ActionManager.h" -#include "Settings.h" -#include "Include/IObjectManager.h" -#include "MathConversion.h" - -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -#include -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -#include - -#include - -void BeautifyEulerAngles(Vec3& v) -{ - if (v.x + v.y + v.z >= 360.0f) - { - v.x = 180.0f - v.x; - v.y = 180.0f - v.y; - v.z = 180.0f - v.z; - } -} - -///////////////////////////////////////////////////////////////////////////// -// CInfoBar dialog -CInfoBar::CInfoBar(QWidget* parent) - : QWidget(parent) - , ui(new Ui::CInfoBar) -{ - ui->setupUi(this); - - m_bSelectionChanged = false; - m_bDragMode = false; - m_prevMoveSpeed = 0; - m_currValue = Vec3(-111, +222, -333); //this wasn't initialized. I don't know what a good value is - m_oldMainVolume = 1.0f; - - GetIEditor()->RegisterNotifyListener(this); - - //audio request setup - m_oMuteAudioRequest.pData = &m_oMuteAudioRequestData; - m_oUnmuteAudioRequest.pData = &m_oUnmuteAudioRequestData; - - OnInitDialog(); - - auto comboBoxTextChanged = static_cast(&QComboBox::currentTextChanged); - connect(ui->m_moveSpeed, comboBoxTextChanged, this, &CInfoBar::OnUpdateMoveSpeedText); - connect(ui->m_moveSpeed->lineEdit(), &QLineEdit::returnPressed, this, &CInfoBar::OnSpeedComboBoxEnter); - - // Hide some buttons from the expander menu - AzQtComponents::Style::addClass(ui->m_physDoStepBtn, "expanderMenu_hide"); - AzQtComponents::Style::addClass(ui->m_physSingleStepBtn, "expanderMenu_hide"); - - connect(ui->m_physicsBtn, &QToolButton::clicked, this, &CInfoBar::OnBnClickedPhysics); - connect(ui->m_physSingleStepBtn, &QToolButton::clicked, this, &CInfoBar::OnBnClickedSingleStepPhys); - connect(ui->m_physDoStepBtn, &QToolButton::clicked, this, &CInfoBar::OnBnClickedDoStepPhys); - connect(ui->m_syncPlayerBtn, &QToolButton::clicked, this, &CInfoBar::OnBnClickedSyncplayer); - connect(ui->m_gotoPos, &QToolButton::clicked, this, &CInfoBar::OnBnClickedGotoPosition); - connect(ui->m_muteBtn, &QToolButton::clicked, this, &CInfoBar::OnBnClickedMuteAudio); - connect(ui->m_vrBtn, &QToolButton::clicked, this, &CInfoBar::OnBnClickedEnableVR); - - connect(this, &CInfoBar::ActionTriggered, MainWindow::instance()->GetActionManager(), &ActionManager::ActionTriggered); - - connect(ui->m_physicsBtn, &QAbstractButton::toggled, ui->m_physicsBtn, [this](bool checked) { - ui->m_physicsBtn->setToolTip(checked ? tr("Stop Simulation (Ctrl+P)") : tr("Simulate (Ctrl+P)")); - }); - connect(ui->m_physSingleStepBtn, &QAbstractButton::toggled, ui->m_physSingleStepBtn, [this](bool checked) { - ui->m_physSingleStepBtn->setToolTip(checked ? tr("Disable Physics/AI Single-step Mode ('<' in Game Mode)") : tr("Enable Physics/AI Single-step Mode ('<' in Game Mode)")); - }); - connect(ui->m_syncPlayerBtn, &QAbstractButton::toggled, ui->m_syncPlayerBtn, [this](bool checked) { - ui->m_syncPlayerBtn->setToolTip(checked ? tr("Synchronize Player with Camera") : tr("Move Player and Camera Separately")); - }); - connect(ui->m_muteBtn, &QAbstractButton::toggled, ui->m_muteBtn, [this](bool checked) { - ui->m_muteBtn->setToolTip(checked ? tr("Un-mute Audio") : tr("Mute Audio")); - }); - connect(ui->m_vrBtn, &QAbstractButton::toggled, ui->m_vrBtn, [this](bool checked) { - ui->m_vrBtn->setToolTip(checked ? tr("Disable VR Preview") : tr("Enable VR Preview")); - }); - - ui->m_moveSpeed->setValidator(new QDoubleValidator(m_minSpeed, m_maxSpeed, m_numDecimals, ui->m_moveSpeed)); - - // Save off the move speed here since setting up the combo box can cause it to update values in the background. - float cameraMoveSpeed = gSettings.cameraMoveSpeed; - - // Populate the presets in the ComboBox - for (float presetValue : m_speedPresetValues) - { - ui->m_moveSpeed->addItem(QString().setNum(presetValue, 'f', m_numDecimals), presetValue); - } - - SetSpeedComboBox(cameraMoveSpeed); - - ui->m_moveSpeed->setInsertPolicy(QComboBox::NoInsert); - - using namespace AzToolsFramework::ComponentModeFramework; - EditorComponentModeNotificationBus::Handler::BusConnect(AzToolsFramework::GetEntityContextId()); -} - -////////////////////////////////////////////////////////////////////////// -CInfoBar::~CInfoBar() -{ - using namespace AzToolsFramework::ComponentModeFramework; - EditorComponentModeNotificationBus::Handler::BusDisconnect(); - - GetIEditor()->UnregisterNotifyListener(this); - - AZ::VR::VREventBus::Handler::BusDisconnect(); -} - -////////////////////////////////////////////////////////////////////////// -void CInfoBar::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - if (event == eNotify_OnIdleUpdate) - { - IdleUpdate(); - } - else if (event == eNotify_OnBeginGameMode || event == eNotify_OnEndGameMode) - { - // Audio: determine muted state of audio - //m_bMuted = gEnv->pAudioSystem->GetMainVolume() == 0.f; - ui->m_muteBtn->setChecked(gSettings.bMuteAudio); - } - else if (event == eNotify_OnBeginLoad || event == eNotify_OnCloseScene) - { - // make sure AI/Physics is disabled on level load (CE-4229) - if (GetIEditor()->GetGameEngine()->GetSimulationMode()) - { - OnBnClickedPhysics(); - } - - ui->m_physicsBtn->setEnabled(false); - ui->m_physSingleStepBtn->setEnabled(false); - ui->m_physDoStepBtn->setEnabled(false); - } - else if (event == eNotify_OnEndLoad || event == eNotify_OnEndNewScene) - { - ui->m_physicsBtn->setEnabled(true); - ui->m_physSingleStepBtn->setEnabled(true); - ui->m_physDoStepBtn->setEnabled(true); - } - else if (event == eNotify_OnSelectionChange) - { - m_bSelectionChanged = true; - } -} - -void CInfoBar::IdleUpdate() -{ - if (!m_idleUpdateEnabled) - { - return; - } - - bool updateUI = false; - // Update Width/Height of selection rectangle. - AABB box; - GetIEditor()->GetSelectedRegion(box); - float width = box.max.x - box.min.x; - float height = box.max.y - box.min.y; - if (m_width != width || m_height != height) - { - m_width = width; - m_height = height; - updateUI = true; - } - - Vec3 marker = GetIEditor()->GetMarkerPosition(); - - int selectedEntitiesCount = 0; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult( - selectedEntitiesCount, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntitiesCount); - if (selectedEntitiesCount != m_numSelected) - { - m_numSelected = selectedEntitiesCount; - updateUI = true; - } - - QString str; - if (updateUI) - { - if (m_numSelected == 0) - { - str = tr("None Selected"); - } - else if (m_numSelected == 1) - { - str = tr("1 Object Selected"); - } - else - { - str = tr("%1 Objects Selected").arg(m_numSelected); - } - - ui->m_statusText->setText(str); - m_sLastText = str; - } - - if (gSettings.cameraMoveSpeed != m_prevMoveSpeed && - !ui->m_moveSpeed->lineEdit()->hasFocus()) - { - m_prevMoveSpeed = gSettings.cameraMoveSpeed; - SetSpeedComboBox(gSettings.cameraMoveSpeed); - } - - { - bool bPhysics = GetIEditor()->GetGameEngine()->GetSimulationMode(); - if ((ui->m_physicsBtn->isChecked() && !bPhysics) || - (!ui->m_physicsBtn->isChecked() && bPhysics)) - { - ui->m_physicsBtn->setChecked(bPhysics); - } - - // Unsupported for Phyics:: atm - bool bSingleStep = false; - if (ui->m_physSingleStepBtn->isChecked() != bSingleStep) - { - ui->m_physSingleStepBtn->setChecked(bSingleStep); - } - - bool bSyncPlayer = GetIEditor()->GetGameEngine()->IsSyncPlayerPosition(); - if ((!ui->m_syncPlayerBtn->isChecked() && !bSyncPlayer) || - (ui->m_syncPlayerBtn->isChecked() && bSyncPlayer)) - { - ui->m_syncPlayerBtn->setChecked(!bSyncPlayer); - } - } - - // if our selection changed, or if our display values are out of date - if (m_bSelectionChanged) - { - m_bSelectionChanged = false; - } -} - -inline double Round(double fVal, double fStep) -{ - if (fStep > 0.f) - { - fVal = int_round(fVal / fStep) * fStep; - } - return fVal; -} - -void CInfoBar::OnUpdateMoveSpeedText(const QString& text) -{ - gSettings.cameraMoveSpeed = aznumeric_cast(Round(text.toDouble(), m_speedStep)); -} - -void CInfoBar::OnSpeedComboBoxEnter() -{ - ui->m_moveSpeed->clearFocus(); -} - -void CInfoBar::OnInitDialog() -{ - QFontMetrics metrics({}); - int width = metrics.boundingRect("-9999.99").width() * m_fieldWidthMultiplier; - - ui->m_moveSpeed->setFixedWidth(width); - - ui->m_physicsBtn->setEnabled(false); - ui->m_physSingleStepBtn->setEnabled(false); - ui->m_physDoStepBtn->setEnabled(false); - - ui->m_muteBtn->setChecked(gSettings.bMuteAudio); - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequest, gSettings.bMuteAudio ? m_oMuteAudioRequest : m_oUnmuteAudioRequest); - - //This is here just in case this class hasn't been created before - //a VR headset was initialized - ui->m_vrBtn->setEnabled(false); - if (AZ::VR::HMDDeviceRequestBus::GetTotalNumOfEventHandlers() != 0) - { - ui->m_vrBtn->setEnabled(true); - } - - AZ::VR::VREventBus::Handler::BusConnect(); -} - -void CInfoBar::OnHMDInitialized() -{ - ui->m_vrBtn->setEnabled(true); -} - -void CInfoBar::OnHMDShutdown() -{ - ui->m_vrBtn->setEnabled(false); -} - -void CInfoBar::OnBnClickedTerrainCollision() -{ - emit ActionTriggered(ID_TERRAIN_COLLISION); -} - -void CInfoBar::OnBnClickedPhysics() -{ - if (!ui->m_physicsBtn->isEnabled()) - { - return; - } - - bool bPhysics = GetIEditor()->GetGameEngine()->GetSimulationMode(); - ui->m_physicsBtn->setChecked(bPhysics); - emit ActionTriggered(ID_SWITCH_PHYSICS); - - if (bPhysics && ui->m_physSingleStepBtn->isChecked()) - { - OnBnClickedSingleStepPhys(); - } -} - -void CInfoBar::OnBnClickedSingleStepPhys() -{ -} - -void CInfoBar::OnBnClickedDoStepPhys() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CInfoBar::OnBnClickedSyncplayer() -{ - emit ActionTriggered(ID_GAME_SYNCPLAYER); -} - -////////////////////////////////////////////////////////////////////////// -void CInfoBar::OnBnClickedGotoPosition() -{ - emit ActionTriggered(ID_DISPLAY_GOTOPOSITION); -} - -////////////////////////////////////////////////////////////////////////// -void CInfoBar::OnBnClickedMuteAudio() -{ - gSettings.bMuteAudio = !gSettings.bMuteAudio; - - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequest, gSettings.bMuteAudio ? m_oMuteAudioRequest : m_oUnmuteAudioRequest); - - ui->m_muteBtn->setChecked(gSettings.bMuteAudio); -} - -void CInfoBar::OnBnClickedEnableVR() -{ - gSettings.bEnableGameModeVR = !gSettings.bEnableGameModeVR; - ui->m_vrBtn->setChecked(gSettings.bEnableGameModeVR); -} - -void CInfoBar::EnteredComponentMode(const AZStd::vector& /*componentModeTypes*/) -{ - ui->m_physicsBtn->setDisabled(true); -} - -void CInfoBar::LeftComponentMode(const AZStd::vector& /*componentModeTypes*/) -{ - ui->m_physicsBtn->setEnabled(true); -} - -void CInfoBar::SetSpeedComboBox(double value) -{ - value = AZStd::clamp(Round(value, m_speedStep), m_minSpeed, m_maxSpeed); - - int index = ui->m_moveSpeed->findData(value); - if (index != -1) - { - ui->m_moveSpeed->setCurrentIndex(index); - } - else - { - ui->m_moveSpeed->lineEdit()->setText(QString().setNum(value, 'f', m_numDecimals)); - } -} - -#include diff --git a/Code/Sandbox/Editor/InfoBar.h b/Code/Sandbox/Editor/InfoBar.h deleted file mode 100644 index 6e547d46c6..0000000000 --- a/Code/Sandbox/Editor/InfoBar.h +++ /dev/null @@ -1,121 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_INFOBAR_H -#define CRYINCLUDE_EDITOR_INFOBAR_H - -#pragma once -// InfoBar.h : header file -// - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#endif - -///////////////////////////////////////////////////////////////////////////// -// CInfoBar dialog - -namespace Ui { - class CInfoBar; -} - -class CInfoBar - : public QWidget - , public IEditorNotifyListener - , public AZ::VR::VREventBus::Handler - , private AzToolsFramework::ComponentModeFramework::EditorComponentModeNotificationBus::Handler -{ - Q_OBJECT - - // Construction -public: - CInfoBar(QWidget* parent = nullptr); - ~CInfoBar(); - - // Toggle the mute audio button - void ToggleAudio() { OnBnClickedMuteAudio(); } - void SetSpeedComboBox(double value); - -Q_SIGNALS: - void ActionTriggered(int command); - - // Implementation -protected: - void IdleUpdate(); - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - - virtual void OnOK() {}; - virtual void OnCancel() {}; - - void OnBnClickedSyncplayer(); - void OnBnClickedGotoPosition(); - - void OnSpeedComboBoxEnter(); - void OnUpdateMoveSpeedText(const QString&); - void OnBnClickedTerrainCollision(); - void OnBnClickedPhysics(); - void OnBnClickedSingleStepPhys(); - void OnBnClickedDoStepPhys(); - void OnBnClickedMuteAudio(); - void OnBnClickedEnableVR(); - void OnInitDialog(); - - ////////////////////////////////////////////////////////////////////////// - /// VR Event Bus Implementation - ////////////////////////////////////////////////////////////////////////// - void OnHMDInitialized() override; - void OnHMDShutdown() override; - ////////////////////////////////////////////////////////////////////////// - - // EditorComponentModeNotificationBus - void EnteredComponentMode(const AZStd::vector& componentModeTypes) override; - void LeftComponentMode(const AZStd::vector& componentModeTypes) override; - - float m_width, m_height; - //int m_heightMapX,m_heightMapY; - double m_fieldWidthMultiplier = 1.8; - - int m_numSelected; - float m_prevMoveSpeed; - - // Speed combobox/lineEdit settings - double m_minSpeed = 0.1; - double m_maxSpeed = 100.0; - double m_speedStep = 0.1; - int m_numDecimals = 1; - - // Speed presets - float m_speedPresetValues[3] = { 0.1f, 1.0f, 10.0f }; - - bool m_bSelectionChanged; - - bool m_bDragMode; - QString m_sLastText; - - Vec3 m_lastValue; - Vec3 m_currValue; - float m_oldMainVolume; - - Audio::SAudioRequest m_oMuteAudioRequest; - Audio::SAudioManagerRequestData m_oMuteAudioRequestData; - Audio::SAudioRequest m_oUnmuteAudioRequest; - Audio::SAudioManagerRequestData m_oUnmuteAudioRequestData; - - QScopedPointer ui; - - bool m_idleUpdateEnabled = true; -}; - -#endif // CRYINCLUDE_EDITOR_INFOBAR_H diff --git a/Code/Sandbox/Editor/InfoBar.ui b/Code/Sandbox/Editor/InfoBar.ui deleted file mode 100644 index 84207629df..0000000000 --- a/Code/Sandbox/Editor/InfoBar.ui +++ /dev/null @@ -1,333 +0,0 @@ - - - CInfoBar - - - - 0 - 0 - 1600 - 27 - - - - - 0 - 0 - - - - true - - - b - - - - 0 - - - QLayout::SetFixedSize - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - 0 - - - - No Objects Selected - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - - - 0 - 0 - - - - Go to Position - - - Go to Position - - - - :/InfoBar/GotoLocation-default.svg:/InfoBar/GotoLocation-default.svg - - - - 22 - 18 - - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 1 - 18 - - - - - - - - Speed - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Camera Movement Speed - - - true - - - - - - - - 0 - 0 - - - - Synchronize Player with Camera - - - Synchronize Player with Camera - - - - :/InfoBar/NoPlayerSync-default.svg - :/InfoBar/NoPlayerSync-selected.svg - :/InfoBar/NoPlayerSync-default.svg - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 1 - 18 - - - - - - - - Simulate (Ctrl+P) - - - Simulate (Ctrl+P) - - - - :/InfoBar/PhysicsCol-default.svg:/InfoBar/PhysicsCol-default.svg - - - - 18 - 18 - - - - true - - - - - - - - 0 - 0 - - - - Enable Physics/AI Single-step Mode ('<' in Game Mode) - - - Enable Physics/AI Single-step Mode ('<' in Game Mode) - - - - :/InfoBar/Pause-default.svg:/InfoBar/Pause-default.svg - - - - 18 - 18 - - - - true - - - false - - - - - - - - 0 - 0 - - - - Perform a Single Physics/AI Simulation Step ('>' in Game Mode) - - - Perform a Single Physics/AI Simulation Step ('>' in Game Mode) - - - - :/InfoBar/PausePlay-default.svg:/InfoBar/PausePlay-default.svg - - - - 18 - 18 - - - - false - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 1 - 18 - - - - - - - - - 0 - 0 - - - - Mute Audio - - - Mute Audio - - - - :/InfoBar/Mute-default.svg:/InfoBar/Mute-default.svg - - - - 18 - 18 - - - - true - - - - - - - - 0 - 0 - - - - Enable VR Preview - - - Enable VR Preview - - - - :/InfoBar/VR-default.svg:/InfoBar/VR-default.svg - - - - 18 - 18 - - - - true - - - - - - - - - - diff --git a/Code/Sandbox/Editor/LayoutWnd.cpp b/Code/Sandbox/Editor/LayoutWnd.cpp index 54389f30c1..1de4d9584a 100644 --- a/Code/Sandbox/Editor/LayoutWnd.cpp +++ b/Code/Sandbox/Editor/LayoutWnd.cpp @@ -94,134 +94,12 @@ void CLayoutSplitter::CreateLayoutView(int row, int col, int id) viewPane->SetId(id); } -////////////////////////////////////////////////////////////////////////// -// InfoBarExpanderWatcher -////////////////////////////////////////////////////////////////////////// - -class InfoBarExpanderWatcher - : public QObject -{ -public: - InfoBarExpanderWatcher(QObject* parent = nullptr) - : QObject(parent) - { - } - - bool eventFilter(QObject* obj, QEvent* event) override - { - switch (event->type()) - { - case QEvent::MouseButtonPress: - case QEvent::MouseButtonRelease: - case QEvent::MouseButtonDblClick: - { - if (qobject_cast(obj)) - { - auto mouseEvent = static_cast(event); - auto expansion = qobject_cast(obj); - - expansion->setPopupMode(QToolButton::InstantPopup); - auto menu = new QMenu(expansion); - - auto toolbar = qobject_cast(expansion->parentWidget()); - - auto toolWidgets = toolbar->findChildren(); - - if (toolWidgets.count() > 0) - { - for (auto toolWidget : toolWidgets) - { - if (AzQtComponents::Style::hasClass(toolWidget, "expanderMenu_hide")) - { - continue; - } - - if (auto toolButton = qobject_cast(toolWidget)) - { - if (!toolButton->isVisible()) - { - // Skip some empty buttons - if (toolButton->text().isEmpty()) - { - continue; - } - - QString plainText = QTextDocumentFragment::fromHtml(toolButton->text()).toPlainText(); - QAction* action = new QAction(plainText, menu); - - if (!toolButton->isEnabled()) - { - action->setEnabled(false); - } - - connect(action, &QAction::triggered, toolButton, &QToolButton::clicked); - - if (toolButton->isCheckable()) - { - action->setCheckable(true); - } - - action->setChecked(toolButton->isChecked()); - - menu->addAction(action); - } - } - else if (auto toolCombo = qobject_cast(toolWidget)) - { - // Add custom menu for Speed - if (toolCombo->objectName() == "m_moveSpeed") - { - double currentValue = toolCombo->lineEdit()->text().toDouble(); - - QMenu* newMenu = menu->addMenu(QString("Speed: %1").arg(currentValue)); - - double presets[] = { 0.1, 1.0, 10.0 }; - for (double preset : presets) - { - QAction* presetAction = new QAction(newMenu); - presetAction->setText(QString::number(preset)); - - connect(presetAction, &QAction::triggered, this, [preset, this]() { - if (m_infoBar) - { - m_infoBar->SetSpeedComboBox(preset); - } - }); - - newMenu->addAction(presetAction); - } - } - } - } - } - - menu->exec(mouseEvent->globalPos()); - return true; - } - - break; - } - } - - return QObject::eventFilter(obj, event); - } - - void SetInfoBar(CInfoBar* infoBar) - { - m_infoBar = infoBar; - } - -private: - CInfoBar* m_infoBar = nullptr; -}; - ////////////////////////////////////////////////////////////////////////// // CLayoutWnd ////////////////////////////////////////////////////////////////////////// CLayoutWnd::CLayoutWnd(QSettings* settings, QWidget* parent) : AzQtComponents::ToolBarArea(parent) , m_settings(settings) - , m_expanderWatcher(new InfoBarExpanderWatcher(this)) { m_bMaximized = false; m_maximizedView = 0; @@ -230,23 +108,8 @@ CLayoutWnd::CLayoutWnd(QSettings* settings, QWidget* parent) m_maximizedViewId = 0; m_infoBarSize = QSize(0, 0); - m_infoBar = new CInfoBar(this); connect(qApp, &QApplication::focusChanged, this, &CLayoutWnd::OnFocusChanged); - m_expanderWatcher->SetInfoBar(m_infoBar); - - m_infoToolBar = CreateToolBarFromWidget(m_infoBar, - Qt::BottomToolBarArea, - QStringLiteral("Info Panel")); - m_infoToolBar->setMovable(false); - m_infoToolBar->setObjectName("InfoBar"); - AzQtComponents::Style::addClass(m_infoToolBar, "DefaultSpacing"); - - if (QToolButton* expansion = AzQtComponents::ToolBar::getToolBarExpansionButton(m_infoToolBar)) - { - expansion->installEventFilter(m_expanderWatcher); - } - setContextMenuPolicy(Qt::NoContextMenu); } @@ -415,7 +278,6 @@ void CLayoutWnd::CreateLayout(EViewLayout layout, bool bBindViewports, EViewport } QRect rcView = rect(); - rcView.setBottom(rcView.bottom() - m_infoBar->height()); // Ensure we delete our old view immediately so it can relinquish its backing ViewportContext if (m_maximizedView) diff --git a/Code/Sandbox/Editor/LayoutWnd.h b/Code/Sandbox/Editor/LayoutWnd.h index 87240cbf76..2af56f907c 100644 --- a/Code/Sandbox/Editor/LayoutWnd.h +++ b/Code/Sandbox/Editor/LayoutWnd.h @@ -20,7 +20,6 @@ #if !defined(Q_MOC_RUN) #include "Viewport.h" -#include "InfoBar.h" #include #include @@ -77,8 +76,6 @@ private: friend class CLayoutWnd; }; -class InfoBarExpanderWatcher; - /** Main layout window. */ class CLayoutWnd @@ -116,8 +113,6 @@ public: //! Switch 2D viewports. void Cycle2DViewport(); - CInfoBar& GetInfoBar() { return *m_infoBar; } - public slots: void ResetLayout(); @@ -162,11 +157,8 @@ private: // Id of maximized view pane. int m_maximizedViewId; - CInfoBar* m_infoBar; - QToolBar* m_infoToolBar; QSize m_infoBarSize; QSettings* m_settings; - InfoBarExpanderWatcher* m_expanderWatcher; }; ///////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index 9e983c3593..31eac05824 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -297,68 +297,6 @@ namespace } } -class SnapToWidget - : public QWidget -{ -public: - typedef AZStd::function SetValueCallback; - typedef AZStd::function GetValueCallback; - - SnapToWidget(QAction* defaultAction, SetValueCallback setValueCallback, GetValueCallback getValueCallback) - : m_setValueCallback(setValueCallback) - , m_getValueCallback(getValueCallback) - { - QHBoxLayout* layout = new QHBoxLayout(); - setLayout(layout); - - m_toolButton = new QToolButton(); - m_toolButton->setAutoRaise(true); - m_toolButton->setCheckable(false); - m_toolButton->setDefaultAction(defaultAction); - - m_spinBox = new AzQtComponents::DoubleSpinBox(); - - layout->addWidget(m_toolButton); - layout->addWidget(m_spinBox); - - m_spinBox->setEnabled(defaultAction->isChecked()); - m_spinBox->setMinimum(1e-2f); - - { - QSignalBlocker signalBlocker(m_spinBox); - m_spinBox->setValue(m_getValueCallback()); - } - - QObject::connect(m_spinBox, QOverload::of(&AzQtComponents::DoubleSpinBox::valueChanged), this, &SnapToWidget::OnValueChanged); - QObject::connect(defaultAction, &QAction::changed, this, &SnapToWidget::OnActionChanged); - } - - void SetIcon(QIcon icon) - { - m_toolButton->setIcon(icon); - } - -protected: - - void OnValueChanged(double value) - { - m_setValueCallback(value); - } - - void OnActionChanged() - { - m_spinBox->setEnabled(m_toolButton->isChecked()); - } - -private: - - QToolButton* m_toolButton = nullptr; - AzQtComponents::DoubleSpinBox* m_spinBox = nullptr; - - SetValueCallback m_setValueCallback; - GetValueCallback m_getValueCallback; -}; - ///////////////////////////////////////////////////////////////////////////// // MainWindow ///////////////////////////////////////////////////////////////////////////// @@ -1274,36 +1212,6 @@ void UndoRedoToolButton::Update(int count) setEnabled(count > 0); } -QWidget* MainWindow::CreateSnapToGridWidget() -{ - SnapToWidget::SetValueCallback setCallback = [](double snapStep) - { - SandboxEditor::SetGridSnappingSize(snapStep); - }; - - SnapToWidget::GetValueCallback getCallback = []() - { - return SandboxEditor::GridSnappingSize(); - }; - - return new SnapToWidget(m_actionManager->GetAction(ID_SNAP_TO_GRID), setCallback, getCallback); -} - -QWidget* MainWindow::CreateSnapToAngleWidget() -{ - SnapToWidget::SetValueCallback setCallback = [](double snapAngle) - { - SandboxEditor::SetAngleSnappingSize(snapAngle); - }; - - SnapToWidget::GetValueCallback getCallback = []() - { - return SandboxEditor::AngleSnappingSize(); - }; - - return new SnapToWidget(m_actionManager->GetAction(ID_SNAPANGLE), setCallback, getCallback); -} - bool MainWindow::IsPreview() const { return GetIEditor()->IsInPreviewMode(); @@ -2016,12 +1924,6 @@ QWidget* MainWindow::CreateToolbarWidget(int actionId) case ID_TOOLBAR_WIDGET_REDO: w = CreateUndoRedoButton(ID_REDO); break; - case ID_TOOLBAR_WIDGET_SNAP_GRID: - w = CreateSnapToGridWidget(); - break; - case ID_TOOLBAR_WIDGET_SNAP_ANGLE: - w = CreateSnapToAngleWidget(); - break; case ID_TOOLBAR_WIDGET_SPACER_RIGHT: w = CreateSpacerRightWidget(); break; diff --git a/Code/Sandbox/Editor/MainWindow.h b/Code/Sandbox/Editor/MainWindow.h index ab60b0e0d4..43600b039e 100644 --- a/Code/Sandbox/Editor/MainWindow.h +++ b/Code/Sandbox/Editor/MainWindow.h @@ -202,8 +202,6 @@ private: // AzToolsFramework::SourceControlNotificationBus::Handler: void ConnectivityStateChanged(const AzToolsFramework::SourceControlState state) override; - QWidget* CreateSnapToGridWidget(); - QWidget* CreateSnapToAngleWidget(); QWidget* CreateSpacerRightWidget(); QToolButton* CreateUndoRedoButton(int command); diff --git a/Code/Sandbox/Editor/Style/Editor.qss b/Code/Sandbox/Editor/Style/Editor.qss index fa7d67dd43..2e96c73f35 100644 --- a/Code/Sandbox/Editor/Style/Editor.qss +++ b/Code/Sandbox/Editor/Style/Editor.qss @@ -144,20 +144,6 @@ EditorWindow QToolBar border-bottom: 2px solid #111111; } -/* InfoBar (Toolbar below the main viewport) */ - -QToolBar#InfoBar -{ - qproperty-iconSize: 22px 18px; -} - -QToolBar#InfoBar AzQtComponents--VectorElement[Coordinate="X"] QLabel, -QToolBar#InfoBar AzQtComponents--VectorElement[Coordinate="Y"] QLabel, -QToolBar#InfoBar AzQtComponents--VectorElement[Coordinate="Z"] QLabel -{ - background-color: #333333; -} - DockWidgetTitleBar #DockWidgetContextMenu { qproperty-icon: url(:/Cards/img/UI20/Cards/menu_ico.svg); diff --git a/Code/Sandbox/Editor/ToolbarManager.cpp b/Code/Sandbox/Editor/ToolbarManager.cpp index 391eabae33..241b969da7 100644 --- a/Code/Sandbox/Editor/ToolbarManager.cpp +++ b/Code/Sandbox/Editor/ToolbarManager.cpp @@ -582,19 +582,6 @@ AmazonToolbar ToolbarManager::GetEditModeToolbar() const { AmazonToolbar t = AmazonToolbar("EditMode", QObject::tr("Edit Mode Toolbar")); t.SetMainToolbar(true); - t.AddAction(ID_TOOLBAR_WIDGET_UNDO, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_TOOLBAR_WIDGET_REDO, ORIGINAL_TOOLBAR_VERSION); - - t.AddAction(ID_TOOLBAR_SEPARATOR, ORIGINAL_TOOLBAR_VERSION); - - t.AddAction(ID_EDITMODE_MOVE, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_EDITMODE_ROTATE, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_EDITMODE_SCALE, ORIGINAL_TOOLBAR_VERSION); - - t.AddAction(ID_TOOLBAR_SEPARATOR, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_TOOLBAR_WIDGET_SNAP_GRID, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_TOOLBAR_WIDGET_SNAP_ANGLE, ORIGINAL_TOOLBAR_VERSION); - return t; } diff --git a/Code/Sandbox/Editor/ViewportTitleDlg.cpp b/Code/Sandbox/Editor/ViewportTitleDlg.cpp index 5ccb83cd5b..f85aa1f06d 100644 --- a/Code/Sandbox/Editor/ViewportTitleDlg.cpp +++ b/Code/Sandbox/Editor/ViewportTitleDlg.cpp @@ -21,6 +21,8 @@ // Qt #include +#include + // CryCommon #include @@ -35,16 +37,20 @@ #include "Objects/SelectionGroup.h" #include "UsedResources.h" #include "Include/IObjectManager.h" +#include "ActionManager.h" +#include "MainWindow.h" +#include "GameEngine.h" +#include "MathConversion.h" +#include "EditorViewportSettings.h" -#include - +#include +#include AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include "ui_ViewportTitleDlg.h" AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING #endif //!defined(Q_MOC_RUN) - // CViewportTitleDlg dialog inline namespace Helpers @@ -103,7 +109,9 @@ CViewportTitleDlg::CViewportTitleDlg(QWidget* pParent) layout->addWidget(container); container->setObjectName("ViewportTitleDlgContainer"); - m_pViewPane = NULL; + m_prevMoveSpeed = 0; + + m_pViewPane = nullptr; GetIEditor()->RegisterNotifyListener(this); GetISystem()->GetISystemEventDispatcher()->RegisterListener(this); @@ -111,21 +119,176 @@ CViewportTitleDlg::CViewportTitleDlg(QWidget* pParent) LoadCustomPresets("AspectRatioPresets", "AspectRatioPreset", m_customAspectRatioPresets); LoadCustomPresets("ResPresets", "ResPreset", m_customResPresets); - OnInitDialog(); + // audio request setup + m_oMuteAudioRequest.pData = &m_oMuteAudioRequestData; + m_oUnmuteAudioRequest.pData = &m_oUnmuteAudioRequestData; - connect(m_ui->m_fovLabel, &QWidget::customContextMenuRequested, this, &CViewportTitleDlg::PopUpFOVMenu); - connect(m_ui->m_fovStaticCtrl, &QWidget::customContextMenuRequested, this, &CViewportTitleDlg::PopUpFOVMenu); - connect(m_ui->m_ratioStaticCtrl, &QWidget::customContextMenuRequested, this, &CViewportTitleDlg::PopUpAspectMenu); - connect(m_ui->m_ratioLabel, &QWidget::customContextMenuRequested, this, &CViewportTitleDlg::PopUpAspectMenu); - connect(m_ui->m_sizeStaticCtrl, &QWidget::customContextMenuRequested, this, &CViewportTitleDlg::PopUpResolutionMenu); + SetupCameraDropdownMenu(); + SetupResolutionDropdownMenu(); + SetupViewportInformationMenu(); + SetupOverflowMenu(); + + Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequest, gSettings.bMuteAudio ? m_oMuteAudioRequest : m_oUnmuteAudioRequest); + + connect(this, &CViewportTitleDlg::ActionTriggered, MainWindow::instance()->GetActionManager(), &ActionManager::ActionTriggered); + + AZ::VR::VREventBus::Handler::BusConnect(); + + OnInitDialog(); } CViewportTitleDlg::~CViewportTitleDlg() { + AZ::VR::VREventBus::Handler::BusDisconnect(); GetISystem()->GetISystemEventDispatcher()->RemoveListener(this); GetIEditor()->UnregisterNotifyListener(this); } +void CViewportTitleDlg::SetupCameraDropdownMenu() +{ + // Setup the camera dropdown menu + QMenu* cameraMenu = new QMenu(this); + cameraMenu->addMenu(GetFovMenu()); + m_ui->m_cameraMenu->setMenu(cameraMenu); + m_ui->m_cameraMenu->setPopupMode(QToolButton::InstantPopup); + QAction* gotoPositionAction = new QAction("Go to position", cameraMenu); + connect(gotoPositionAction, &QAction::triggered, this, &CViewportTitleDlg::OnBnClickedGotoPosition); + cameraMenu->addAction(gotoPositionAction); + m_syncPlayerToCameraAction = new QAction("Sync camera to player", cameraMenu); + m_syncPlayerToCameraAction->setCheckable(true); + connect(m_syncPlayerToCameraAction, &QAction::triggered, this, &CViewportTitleDlg::OnBnClickedSyncplayer); + cameraMenu->addAction(m_syncPlayerToCameraAction); + + cameraMenu->addSeparator(); + + auto cameraSpeedActionWidget = new QWidgetAction(cameraMenu); + auto cameraSpeedContainer = new QWidget(cameraMenu); + auto cameraSpeedLabel = new QLabel(tr("Camera Speed"), cameraMenu); + m_cameraSpeed = new QComboBox(cameraMenu); + m_cameraSpeed->setEditable(true); + m_cameraSpeed->setValidator(new QDoubleValidator(m_minSpeed, m_maxSpeed, m_numDecimals, m_cameraSpeed)); + + QHBoxLayout* cameraSpeedLayout = new QHBoxLayout; + cameraSpeedLayout->addWidget(cameraSpeedLabel); + cameraSpeedLayout->addWidget(m_cameraSpeed); + cameraSpeedContainer->setLayout(cameraSpeedLayout); + cameraSpeedActionWidget->setDefaultWidget(cameraSpeedContainer); + + // Save off the move speed here since setting up the combo box can cause it to update values in the background. + float cameraMoveSpeed = gSettings.cameraMoveSpeed; + + // Populate the presets in the ComboBox + for (float presetValue : m_speedPresetValues) + { + m_cameraSpeed->addItem(QString().setNum(presetValue, 'f', m_numDecimals), presetValue); + } + + auto comboBoxTextChanged = static_cast(&QComboBox::currentTextChanged); + + SetSpeedComboBox(cameraMoveSpeed); + m_cameraSpeed->setInsertPolicy(QComboBox::NoInsert); + connect(m_cameraSpeed, comboBoxTextChanged, this, &CViewportTitleDlg::OnUpdateMoveSpeedText); + connect(m_cameraSpeed->lineEdit(), &QLineEdit::returnPressed, this, &CViewportTitleDlg::OnSpeedComboBoxEnter); + + cameraMenu->addAction(cameraSpeedActionWidget); +} + +void CViewportTitleDlg::SetupResolutionDropdownMenu() +{ + // Setup the resolution dropdown menu + QMenu* resolutionMenu = new QMenu(this); + resolutionMenu->addMenu(GetAspectMenu()); + resolutionMenu->addMenu(GetResolutionMenu()); + m_ui->m_resolutionMenu->setMenu(resolutionMenu); + m_ui->m_resolutionMenu->setPopupMode(QToolButton::InstantPopup); +} + +void CViewportTitleDlg::SetupViewportInformationMenu() +{ + // Setup the debug information button + m_ui->m_debugInformationMenu->setMenu(GetViewportInformationMenu()); + connect(m_ui->m_debugInformationMenu, &QToolButton::clicked, this, &CViewportTitleDlg::OnToggleDisplayInfo); + m_ui->m_debugInformationMenu->setPopupMode(QToolButton::MenuButtonPopup); + +} + +void CViewportTitleDlg::SetupOverflowMenu() +{ + // Setup the overflow menu + QMenu* overFlowMenu = new QMenu(this); + m_debugHelpersAction = new QAction("Debug Helpers", overFlowMenu); + m_debugHelpersAction->setCheckable(true); + m_debugHelpersAction->setChecked(Helpers::IsHelpersShown()); + connect(m_debugHelpersAction, &QAction::triggered, this, &CViewportTitleDlg::OnToggleHelpers); + overFlowMenu->addAction(m_debugHelpersAction); + + m_audioMuteAction = new QAction("Mute Audio", overFlowMenu); + connect(m_audioMuteAction, &QAction::triggered, this, &CViewportTitleDlg::OnBnClickedMuteAudio); + overFlowMenu->addAction(m_audioMuteAction); + + m_enableVRAction = new QAction("Enable VR Preview", overFlowMenu); + connect(m_enableVRAction, &QAction::triggered, this, &CViewportTitleDlg::OnBnClickedEnableVR); + overFlowMenu->addAction(m_enableVRAction); + + overFlowMenu->addSeparator(); + + m_enableGridSnappingAction = new QAction("Enable Grid Snapping", overFlowMenu); + connect(m_enableGridSnappingAction, &QAction::triggered, this, &CViewportTitleDlg::OnGridSnappingToggled); + m_enableGridSnappingAction->setCheckable(true); + overFlowMenu->addAction(m_enableGridSnappingAction); + + m_gridSizeActionWidget = new QWidgetAction(overFlowMenu); + auto gridSizeContainer = new QWidget(overFlowMenu); + auto gridSizeLabel = new QLabel(tr("Grid Size"), overFlowMenu); + + m_gridSpinBox = new AzQtComponents::DoubleSpinBox(); + m_gridSpinBox->setValue(SandboxEditor::GridSnappingSize()); + m_gridSpinBox->setMinimum(1e-2f); + + QObject::connect( + m_gridSpinBox, QOverload::of(&AzQtComponents::DoubleSpinBox::valueChanged), this, &CViewportTitleDlg::OnGridSpinBoxChanged); + + QHBoxLayout* gridSizeLayout = new QHBoxLayout; + gridSizeLayout->addWidget(gridSizeLabel); + gridSizeLayout->addWidget(m_gridSpinBox); + gridSizeContainer->setLayout(gridSizeLayout); + m_gridSizeActionWidget->setDefaultWidget(gridSizeContainer); + overFlowMenu->addAction(m_gridSizeActionWidget); + + overFlowMenu->addSeparator(); + + m_enableAngleSnappingAction = new QAction("Enable Grid Snapping", overFlowMenu); + connect(m_enableAngleSnappingAction, &QAction::triggered, this, &CViewportTitleDlg::OnAngleSnappingToggled); + m_enableAngleSnappingAction->setCheckable(true); + overFlowMenu->addAction(m_enableAngleSnappingAction); + + m_angleSizeActionWidget = new QWidgetAction(overFlowMenu); + auto angleSizeContainer = new QWidget(overFlowMenu); + auto angleSizeLabel = new QLabel(tr("Angle Snapping"), overFlowMenu); + + m_angleSpinBox = new AzQtComponents::DoubleSpinBox(); + m_angleSpinBox->setValue(SandboxEditor::AngleSnappingSize()); + m_angleSpinBox->setMinimum(1e-2f); + + QObject::connect( + m_angleSpinBox, QOverload::of(&AzQtComponents::DoubleSpinBox::valueChanged), this, + &CViewportTitleDlg::OnAngleSpinBoxChanged); + + QHBoxLayout* angleSizeLayout = new QHBoxLayout; + angleSizeLayout->addWidget(angleSizeLabel); + angleSizeLayout->addWidget(m_angleSpinBox); + angleSizeContainer->setLayout(angleSizeLayout); + m_angleSizeActionWidget->setDefaultWidget(angleSizeContainer); + overFlowMenu->addAction(m_angleSizeActionWidget); + + m_ui->m_overflowBtn->setMenu(overFlowMenu); + m_ui->m_overflowBtn->setPopupMode(QToolButton::InstantPopup); + connect(overFlowMenu, &QMenu::aboutToShow, this, &CViewportTitleDlg::UpdateOverFlowMenuState); + + UpdateMuteActionText(); +} + + ////////////////////////////////////////////////////////////////////////// void CViewportTitleDlg::SetViewPane(CLayoutViewPane* pViewPane) { @@ -140,21 +303,27 @@ void CViewportTitleDlg::SetViewPane(CLayoutViewPane* pViewPane) void CViewportTitleDlg::OnInitDialog() { m_ui->m_titleBtn->setText(m_title); - m_ui->m_sizeStaticCtrl->setText(QString()); - - m_ui->m_toggleHelpersBtn->setChecked(GetIEditor()->GetDisplaySettings()->IsDisplayHelpers()); - // Add a child parented to us that listens for r_displayInfo changes. auto displayInfoHelper = new CViewportTitleDlgDisplayInfoHelper(this); connect(displayInfoHelper, &CViewportTitleDlgDisplayInfoHelper::ViewportInfoStatusUpdated, this, &CViewportTitleDlg::UpdateDisplayInfo); UpdateDisplayInfo(); - connect(m_ui->m_toggleHelpersBtn, &QToolButton::clicked, this, &CViewportTitleDlg::OnToggleHelpers); - connect(m_ui->m_toggleDisplayInfoBtn, &QToolButton::clicked, this, &CViewportTitleDlg::OnToggleDisplayInfo); + // This is here just in case this class hasn't been created before + // a VR headset was initialized + m_enableVRAction->setEnabled(false); + if (AZ::VR::HMDDeviceRequestBus::GetTotalNumOfEventHandlers() != 0) + { + m_enableVRAction->setEnabled(true); + } + + AZ::VR::VREventBus::Handler::BusConnect(); + + QFontMetrics metrics({}); + int width = metrics.boundingRect("-9999.99").width() * m_fieldWidthMultiplier; + + m_cameraSpeed->setFixedWidth(width); - m_ui->m_toggleHelpersBtn->setProperty("class", "big"); - m_ui->m_toggleDisplayInfoBtn->setProperty("class", "big"); } ////////////////////////////////////////////////////////////////////////// @@ -177,6 +346,80 @@ void CViewportTitleDlg::OnMaximize() void CViewportTitleDlg::OnToggleHelpers() { Helpers::ToggleHelpers(); + m_debugHelpersAction->setChecked(Helpers::IsHelpersShown()); +} + +void CViewportTitleDlg::SetNoViewportInfo() +{ + AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Broadcast( + &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::SetDisplayState, AZ::AtomBridge::ViewportInfoDisplayState::NoInfo); +} + +void CViewportTitleDlg::SetNormalViewportInfo() +{ + AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Broadcast( + &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::SetDisplayState, AZ::AtomBridge::ViewportInfoDisplayState::NormalInfo); +} + +void CViewportTitleDlg::SetFullViewportInfo() +{ + AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Broadcast( + &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::SetDisplayState, AZ::AtomBridge::ViewportInfoDisplayState::FullInfo); +} + +void CViewportTitleDlg::SetCompactViewportInfo() +{ + AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Broadcast( + &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::SetDisplayState, AZ::AtomBridge::ViewportInfoDisplayState::CompactInfo); +} + + +////////////////////////////////////////////////////////////////////////// +void CViewportTitleDlg::UpdateDisplayInfo() +{ + if (m_viewportInformationMenu == nullptr) + { + // Nothing to update, just return; + return; + } + + AZ::AtomBridge::ViewportInfoDisplayState state = AZ::AtomBridge::ViewportInfoDisplayState::NoInfo; + AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::BroadcastResult( + state, + &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::GetDisplayState + ); + + m_noInformationAction->setChecked(false); + m_normalInformationAction->setChecked(false); + m_fullInformationAction->setChecked(false); + m_compactInformationAction->setChecked(false); + + switch (state) + { + case AZ::AtomBridge::ViewportInfoDisplayState::NormalInfo: + { + m_normalInformationAction->setChecked(true); + break; + } + case AZ::AtomBridge::ViewportInfoDisplayState::FullInfo: + { + m_fullInformationAction->setChecked(true); + break; + } + case AZ::AtomBridge::ViewportInfoDisplayState::CompactInfo: + { + m_compactInformationAction->setChecked(true); + break; + } + case AZ::AtomBridge::ViewportInfoDisplayState::NoInfo: + default: + { + m_noInformationAction->setChecked(true); + break; + } + } + + m_ui->m_debugInformationMenu->setChecked(state != AZ::AtomBridge::ViewportInfoDisplayState::NoInfo); } ////////////////////////////////////////////////////////////////////////// @@ -184,27 +427,12 @@ void CViewportTitleDlg::OnToggleDisplayInfo() { AZ::AtomBridge::ViewportInfoDisplayState state = AZ::AtomBridge::ViewportInfoDisplayState::NoInfo; AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::BroadcastResult( - state, - &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::GetDisplayState - ); + state, &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::GetDisplayState); state = aznumeric_cast( - (aznumeric_cast(state)+1) % aznumeric_cast(AZ::AtomBridge::ViewportInfoDisplayState::Invalid)); + (aznumeric_cast(state) + 1) % aznumeric_cast(AZ::AtomBridge::ViewportInfoDisplayState::Invalid)); // SetDisplayState will fire OnViewportInfoDisplayStateChanged and notify us, no need to call UpdateDisplayInfo. AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Broadcast( - &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::SetDisplayState, - state - ); -} - -////////////////////////////////////////////////////////////////////////// -void CViewportTitleDlg::UpdateDisplayInfo() -{ - AZ::AtomBridge::ViewportInfoDisplayState state = AZ::AtomBridge::ViewportInfoDisplayState::NoInfo; - AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::BroadcastResult( - state, - &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::GetDisplayState - ); - m_ui->m_toggleDisplayInfoBtn->setChecked(state != AZ::AtomBridge::ViewportInfoDisplayState::NoInfo); + &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::SetDisplayState, state); } ////////////////////////////////////////////////////////////////////////// @@ -277,7 +505,7 @@ void CViewportTitleDlg::CreateFOVMenu() { if (!m_fovMenu) { - m_fovMenu = new QMenu(this); + m_fovMenu = new QMenu("FOV", this); } m_fovMenu->clear(); @@ -292,17 +520,6 @@ void CViewportTitleDlg::CreateFOVMenu() connect(action, &QAction::triggered, this, &CViewportTitleDlg::OnMenuFOVCustom); } -void CViewportTitleDlg::PopUpFOVMenu() -{ - if (m_pViewPane == NULL) - { - return; - } - - CreateFOVMenu(); - m_fovMenu->exec(QCursor::pos()); -} - QMenu* const CViewportTitleDlg::GetFovMenu() { CreateFOVMenu(); @@ -379,9 +596,9 @@ void CViewportTitleDlg::OnMenuAspectRatioCustom() ////////////////////////////////////////////////////////////////////////// void CViewportTitleDlg::CreateAspectMenu() { - if (!m_aspectMenu) + if (m_aspectMenu == nullptr) { - m_aspectMenu = new QMenu(this); + m_aspectMenu = new QMenu("Aspect Ratio"); } m_aspectMenu->clear(); @@ -396,23 +613,48 @@ void CViewportTitleDlg::CreateAspectMenu() connect(customAction, &QAction::triggered, this, &CViewportTitleDlg::OnMenuAspectRatioCustom); } -void CViewportTitleDlg::PopUpAspectMenu() -{ - if (!m_pViewPane) - { - return; - } - - CreateAspectMenu(); - m_aspectMenu->exec(QCursor::pos()); -} - QMenu* const CViewportTitleDlg::GetAspectMenu() { CreateAspectMenu(); return m_aspectMenu; } +QMenu* const CViewportTitleDlg::GetViewportInformationMenu() +{ + CreateViewportInformationMenu(); + return m_viewportInformationMenu; +} + +void CViewportTitleDlg::CreateViewportInformationMenu() +{ + if (m_viewportInformationMenu == nullptr) + { + m_viewportInformationMenu = new QMenu("Viewport Information"); + + m_noInformationAction = new QAction(tr("None"), m_viewportInformationMenu); + m_noInformationAction->setCheckable(true); + connect(m_noInformationAction, &QAction::triggered, this, &CViewportTitleDlg::SetNoViewportInfo); + m_viewportInformationMenu->addAction(m_noInformationAction); + + m_normalInformationAction = new QAction(tr("Normal"), m_viewportInformationMenu); + m_normalInformationAction->setCheckable(true); + connect(m_normalInformationAction, &QAction::triggered, this, &CViewportTitleDlg::SetNormalViewportInfo); + m_viewportInformationMenu->addAction(m_normalInformationAction); + + m_fullInformationAction = new QAction(tr("Full"), m_viewportInformationMenu); + m_fullInformationAction->setCheckable(true); + connect(m_fullInformationAction, &QAction::triggered, this, &CViewportTitleDlg::SetFullViewportInfo); + m_viewportInformationMenu->addAction(m_fullInformationAction); + + m_compactInformationAction = new QAction(tr("Compact"), m_viewportInformationMenu); + m_compactInformationAction->setCheckable(true); + connect(m_compactInformationAction, &QAction::triggered, this, &CViewportTitleDlg::SetCompactViewportInfo); + m_viewportInformationMenu->addAction(m_compactInformationAction); + + UpdateDisplayInfo(); + } +} + void CViewportTitleDlg::AddResolutionMenus(QMenu* menu, std::function callback, const QStringList& customPresets) { static const CRenderViewport::SResolution resolutions[] = { @@ -479,7 +721,7 @@ void CViewportTitleDlg::CreateResolutionMenu() { if (!m_resolutionMenu) { - m_resolutionMenu = new QMenu(this); + m_resolutionMenu = new QMenu("Resolution"); } m_resolutionMenu->clear(); @@ -494,17 +736,6 @@ void CViewportTitleDlg::CreateResolutionMenu() connect(action, &QAction::triggered, this, &CViewportTitleDlg::OnMenuResolutionCustom); } -void CViewportTitleDlg::PopUpResolutionMenu() -{ - if (!m_pViewPane) - { - return; - } - - CreateResolutionMenu(); - m_resolutionMenu->exec(QCursor::pos()); -} - QMenu* const CViewportTitleDlg::GetResolutionMenu() { CreateResolutionMenu(); @@ -514,14 +745,14 @@ QMenu* const CViewportTitleDlg::GetResolutionMenu() ////////////////////////////////////////////////////////////////////////// void CViewportTitleDlg::OnViewportSizeChanged(int width, int height) { - m_ui->m_sizeStaticCtrl->setText(QString::fromLatin1("%1 x %2").arg(width).arg(height)); + m_resolutionMenu->setTitle(QString::fromLatin1("Resolution: %1 x %2").arg(width).arg(height)); if (width != 0 && height != 0) { // Calculate greatest common divider of width & height int whGCD = gcd(width, height); - m_ui->m_ratioStaticCtrl->setText(QString::fromLatin1("%1:%2").arg(width / whGCD).arg(height / whGCD)); + m_aspectMenu->setTitle(QString::fromLatin1("Ratio: %1:%2").arg(width / whGCD).arg(height / whGCD)); } } @@ -529,9 +760,9 @@ void CViewportTitleDlg::OnViewportSizeChanged(int width, int height) void CViewportTitleDlg::OnViewportFOVChanged(float fov) { const float degFOV = RAD2DEG(fov); - if (m_ui && m_ui->m_fovStaticCtrl) + if (m_fovMenu) { - m_ui->m_fovStaticCtrl->setText(QString::fromLatin1("%1%2").arg(qRound(degFOV)).arg(QString(QByteArray::fromPercentEncoding("%C2%B0")))); + m_fovMenu->setTitle(QString::fromLatin1("FOV: %1%2").arg(qRound(degFOV)).arg(QString(QByteArray::fromPercentEncoding("%C2%B0")))); } } @@ -541,7 +772,11 @@ void CViewportTitleDlg::OnEditorNotifyEvent(EEditorNotifyEvent event) switch (event) { case eNotify_OnDisplayRenderUpdate: - m_ui->m_toggleHelpersBtn->setChecked(GetIEditor()->GetDisplaySettings()->IsDisplayHelpers()); + m_debugHelpersAction->setChecked(Helpers::IsHelpersShown()); + break; + case eNotify_OnBeginGameMode: + case eNotify_OnEndGameMode: + UpdateMuteActionText(); break; } } @@ -615,6 +850,132 @@ bool CViewportTitleDlg::eventFilter(QObject* object, QEvent* event) return QWidget::eventFilter(object, event) || consumeEvent; } +void CViewportTitleDlg::OnBnClickedSyncplayer() +{ + emit ActionTriggered(ID_GAME_SYNCPLAYER); + + bool bSyncPlayer = GetIEditor()->GetGameEngine()->IsSyncPlayerPosition(); + m_syncPlayerToCameraAction->setChecked(!bSyncPlayer); +} + +void CViewportTitleDlg::OnBnClickedGotoPosition() +{ + emit ActionTriggered(ID_DISPLAY_GOTOPOSITION); +} + +void CViewportTitleDlg::OnBnClickedMuteAudio() +{ + gSettings.bMuteAudio = !gSettings.bMuteAudio; + + Audio::AudioSystemRequestBus::Broadcast( + &Audio::AudioSystemRequestBus::Events::PushRequest, gSettings.bMuteAudio ? m_oMuteAudioRequest : m_oUnmuteAudioRequest); + + UpdateMuteActionText(); +} + +void CViewportTitleDlg::UpdateMuteActionText() +{ + m_audioMuteAction->setText(gSettings.bMuteAudio ? tr("Un-mute Audio") : tr("Mute Audio")); +} + +void CViewportTitleDlg::OnHMDInitialized() +{ + m_enableVRAction->setEnabled(true); +} + +void CViewportTitleDlg::OnHMDShutdown() +{ + m_enableVRAction->setEnabled(false); +} + +void CViewportTitleDlg::OnBnClickedEnableVR() +{ + gSettings.bEnableGameModeVR = !gSettings.bEnableGameModeVR; + + m_enableVRAction->setText(gSettings.bEnableGameModeVR ? tr("Disable VR Preview") : tr("Enable VR Preview")); +} + +inline double Round(double fVal, double fStep) +{ + if (fStep > 0.f) + { + fVal = int_round(fVal / fStep) * fStep; + } + return fVal; +} + +void CViewportTitleDlg::SetSpeedComboBox(double value) +{ + value = AZStd::clamp(Round(value, m_speedStep), m_minSpeed, m_maxSpeed); + + int index = m_cameraSpeed->findData(value); + if (index != -1) + { + m_cameraSpeed->setCurrentIndex(index); + } + else + { + m_cameraSpeed->lineEdit()->setText(QString().setNum(value, 'f', m_numDecimals)); + } +} + +void CViewportTitleDlg::OnSpeedComboBoxEnter() +{ + m_cameraSpeed->clearFocus(); +} + +void CViewportTitleDlg::OnUpdateMoveSpeedText(const QString& text) +{ + gSettings.cameraMoveSpeed = aznumeric_cast(Round(text.toDouble(), m_speedStep)); +} + +void CViewportTitleDlg::CheckForCameraSpeedUpdate() +{ + if (gSettings.cameraMoveSpeed != m_prevMoveSpeed && !m_cameraSpeed->lineEdit()->hasFocus()) + { + m_prevMoveSpeed = gSettings.cameraMoveSpeed; + SetSpeedComboBox(gSettings.cameraMoveSpeed); + } +} + +void CViewportTitleDlg::OnGridSnappingToggled() +{ + m_gridSizeActionWidget->setEnabled(m_enableGridSnappingAction->isChecked()); + MainWindow::instance()->GetActionManager()->GetAction(ID_SNAP_TO_GRID)->trigger(); +} + +void CViewportTitleDlg::OnAngleSnappingToggled() +{ + m_angleSizeActionWidget->setEnabled(m_enableAngleSnappingAction->isChecked()); + MainWindow::instance()->GetActionManager()->GetAction(ID_SNAPANGLE)->trigger(); +} + +void CViewportTitleDlg::OnGridSpinBoxChanged(double value) +{ + SandboxEditor::SetGridSnappingSize(value); +} + +void CViewportTitleDlg::OnAngleSpinBoxChanged(double value) +{ + SandboxEditor::SetAngleSnappingSize(value); +} + +void CViewportTitleDlg::UpdateOverFlowMenuState() +{ + bool gridSnappingActive = MainWindow::instance()->GetActionManager()->GetAction(ID_SNAP_TO_GRID)->isChecked(); + { + QSignalBlocker signalBlocker(m_enableGridSnappingAction); + m_enableGridSnappingAction->setChecked(gridSnappingActive); + } + m_gridSizeActionWidget->setEnabled(gridSnappingActive); + + bool angleSnappingActive = MainWindow::instance()->GetActionManager()->GetAction(ID_SNAPANGLE)->isChecked(); + { + QSignalBlocker signalBlocker(m_enableAngleSnappingAction); + m_enableAngleSnappingAction->setChecked(angleSnappingActive); + } + m_angleSizeActionWidget->setEnabled(angleSnappingActive); +} namespace { diff --git a/Code/Sandbox/Editor/ViewportTitleDlg.h b/Code/Sandbox/Editor/ViewportTitleDlg.h index ce2f116d97..dd0816082a 100644 --- a/Code/Sandbox/Editor/ViewportTitleDlg.h +++ b/Code/Sandbox/Editor/ViewportTitleDlg.h @@ -19,8 +19,16 @@ #include "RenderViewport.h" #include +#include + #include #include +#include +#include + +#include + +#include #endif // CViewportTitleDlg dialog @@ -42,6 +50,7 @@ class CViewportTitleDlg : public QWidget , public IEditorNotifyListener , public ISystemEventListener + , public AZ::VR::VREventBus::Handler { Q_OBJECT public: @@ -63,10 +72,15 @@ public: bool eventFilter(QObject* object, QEvent* event) override; + void SetSpeedComboBox(double value); + QMenu* const GetFovMenu(); QMenu* const GetAspectMenu(); QMenu* const GetResolutionMenu(); +Q_SIGNALS: + void ActionTriggered(int command); + protected: virtual void OnInitDialog(); @@ -75,9 +89,20 @@ protected: void OnMaximize(); void OnToggleHelpers(); - void OnToggleDisplayInfo(); void UpdateDisplayInfo(); + ////////////////////////////////////////////////////////////////////////// + /// VR Event Bus Implementation + ////////////////////////////////////////////////////////////////////////// + void OnHMDInitialized() override; + void OnHMDShutdown() override; + ////////////////////////////////////////////////////////////////////////// + + void SetupCameraDropdownMenu(); + void SetupResolutionDropdownMenu(); + void SetupViewportInformationMenu(); + void SetupOverflowMenu(); + QString m_title; CLayoutViewPane* m_pViewPane; @@ -87,22 +112,84 @@ protected: QStringList m_customFOVPresets; QStringList m_customAspectRatioPresets; + float m_prevMoveSpeed; + + // Speed combobox/lineEdit settings + double m_minSpeed = 0.1; + double m_maxSpeed = 100.0; + double m_speedStep = 0.1; + int m_numDecimals = 1; + + // Speed presets + float m_speedPresetValues[3] = { 0.1f, 1.0f, 10.0f }; + + double m_fieldWidthMultiplier = 1.8; + + void OnMenuFOVCustom(); void CreateFOVMenu(); - void PopUpFOVMenu(); void OnMenuAspectRatioCustom(); void CreateAspectMenu(); - void PopUpAspectMenu(); void OnMenuResolutionCustom(); void CreateResolutionMenu(); - void PopUpResolutionMenu(); + + void CreateViewportInformationMenu(); + QMenu* const GetViewportInformationMenu(); + void SetNoViewportInfo(); + void SetNormalViewportInfo(); + void SetFullViewportInfo(); + void SetCompactViewportInfo(); + + void OnBnClickedSyncplayer(); + void OnBnClickedGotoPosition(); + void OnBnClickedMuteAudio(); + void OnBnClickedEnableVR(); + + void UpdateMuteActionText(); + + void OnToggleDisplayInfo(); + + void OnSpeedComboBoxEnter(); + void OnUpdateMoveSpeedText(const QString&); + + void CheckForCameraSpeedUpdate(); + + void OnGridSnappingToggled(); + void OnAngleSnappingToggled(); + + void OnGridSpinBoxChanged(double value); + void OnAngleSpinBoxChanged(double value); + + void UpdateOverFlowMenuState(); QMenu* m_fovMenu = nullptr; QMenu* m_aspectMenu = nullptr; QMenu* m_resolutionMenu = nullptr; + QMenu* m_viewportInformationMenu = nullptr; + QAction* m_noInformationAction = nullptr; + QAction* m_normalInformationAction = nullptr; + QAction* m_fullInformationAction = nullptr; + QAction* m_compactInformationAction = nullptr; + QAction* m_debugHelpersAction = nullptr; + QAction* m_syncPlayerToCameraAction = nullptr; + QAction* m_audioMuteAction = nullptr; + QAction* m_enableVRAction = nullptr; + QAction* m_enableGridSnappingAction = nullptr; + QAction* m_enableAngleSnappingAction = nullptr; + QComboBox* m_cameraSpeed = nullptr; + AzQtComponents::DoubleSpinBox* m_gridSpinBox = nullptr; + AzQtComponents::DoubleSpinBox* m_angleSpinBox = nullptr; + QWidgetAction* m_gridSizeActionWidget = nullptr; + QWidgetAction* m_angleSizeActionWidget = nullptr; + + Audio::SAudioRequest m_oMuteAudioRequest; + Audio::SAudioManagerRequestData m_oMuteAudioRequestData; + Audio::SAudioRequest m_oUnmuteAudioRequest; + Audio::SAudioManagerRequestData m_oUnmuteAudioRequestData; + QScopedPointer m_ui; }; diff --git a/Code/Sandbox/Editor/ViewportTitleDlg.ui b/Code/Sandbox/Editor/ViewportTitleDlg.ui index e7b5cce1ec..2d547bfa99 100644 --- a/Code/Sandbox/Editor/ViewportTitleDlg.ui +++ b/Code/Sandbox/Editor/ViewportTitleDlg.ui @@ -61,121 +61,43 @@ - - - Qt::CustomContextMenu - - - FOV: - - + + + + :/Menu/camera.svg:/Menu/camera.svg + + + + + + + + + :/Menu/debug.svg:/Menu/debug.svg + + + + true + + + + + + + + :/Menu/resolution.svg:/Menu/resolution.svg + + + - - - - 0 - 0 - - - - Qt::CustomContextMenu - - - 120° - - - - - - - Qt::CustomContextMenu - - - Ratio: - - - - - - - - 0 - 0 - - - - - 40 - 0 - - - - Qt::CustomContextMenu - - - 000:000 - - - - - - - - 0 - 0 - - - - - 60 - 0 - - - - Qt::CustomContextMenu - - - 0000 x 0000 - - - - - - - - - - Toggle display info - - - Toggle display info - - - - :/stylesheet/img/UI20/Info.svg:/stylesheet/img/UI20/Info.svg - - - true - - - - - - - Toggle display helpers - - - Toggle display helpers - - - - :/stylesheet/img/UI20/Helpers.svg:/stylesheet/img/UI20/Helpers.svg - - - true - - + + + + :/stylesheet/img/UI20/menu-centered.svg:/stylesheet/img/UI20/menu-centered.svg + + + @@ -187,6 +109,8 @@ 1 - - + + + + diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index ebd7f89cfb..dc9d794021 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -424,10 +424,6 @@ set(FILES GotoPositionDlg.cpp GotoPositionDlg.h GotoPositionDlg.ui - InfoBar.cpp - InfoBar.qrc - InfoBar.h - InfoBar.ui LayoutConfigDialog.cpp LayoutConfigDialog.h LayoutConfigDialog.ui From d67628d88c70a89576e9e4c5f17107f2e8760fd9 Mon Sep 17 00:00:00 2001 From: guthadam Date: Mon, 7 Jun 2021 18:23:40 -0500 Subject: [PATCH 567/811] ATOM-15701 changed material inspector highlight color --- .../MaterialEditor/Code/Source/Window/MaterialEditor.qss | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditor.qss b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditor.qss index e518d80740..506c5a2952 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditor.qss +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditor.qss @@ -11,8 +11,8 @@ */ /* Style for visualizing property values overridden from their prefab values */ -AzToolsFramework--PropertyRowWidget[IsOverridden=true] QLabel +AzToolsFramework--PropertyRowWidget[IsOverridden="true"] QLabel { font-weight: bold; - color: #F5A623; + color: #1E70EB; } From 40c7a6bd2d530d53a2f19d365b2639f40490f4c8 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Mon, 7 Jun 2021 17:02:42 -0700 Subject: [PATCH 568/811] Integrate remaining requests and rename Handling Requests interfaces for clarity --- .../Session/ISessionHandlingRequests.h | 33 +++++---- .../Source/MultiplayerSystemComponent.cpp | 67 +++++++++++++++++++ .../Code/Source/MultiplayerSystemComponent.h | 9 +++ 3 files changed, 95 insertions(+), 14 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h b/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h index a0731626ef..2537842d8a 100644 --- a/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h +++ b/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h @@ -45,14 +45,14 @@ namespace AzFramework AZStd::string m_playerSessionId; }; - //! ISessionHandlingClientRequests - //! The session handling events to invoke multiplayer component handle the work on client side - class ISessionHandlingClientRequests + //! ISessionLocalUserRequests + //! Requests made to the local user to manage their connection to a session + class ISessionLocalUserRequests { public: - AZ_RTTI(ISessionHandlingClientRequests, "{41DE6BD3-72BC-4443-BFF9-5B1B9396657A}"); - ISessionHandlingClientRequests() = default; - virtual ~ISessionHandlingClientRequests() = default; + AZ_RTTI(ISessionLocalUserRequests, "{41DE6BD3-72BC-4443-BFF9-5B1B9396657A}"); + ISessionLocalUserRequests() = default; + virtual ~ISessionLocalUserRequests() = default; // Request the player join session // @param sessionConnectionConfig The required properties to handle the player join session process @@ -63,14 +63,14 @@ namespace AzFramework virtual void RequestPlayerLeaveSession() = 0; }; - //! ISessionHandlingServerRequests - //! The session handling events to invoke server provider handle the work on server side - class ISessionHandlingServerRequests + //! ISessionProviderRequests + //! Requests made to the service providing server/fleet management by the server + class ISessionProviderRequests { public: - AZ_RTTI(ISessionHandlingServerRequests, "{4F0C17BA-F470-4242-A8CB-EC7EA805257C}"); - ISessionHandlingServerRequests() = default; - virtual ~ISessionHandlingServerRequests() = default; + AZ_RTTI(ISessionProviderRequests, "{4F0C17BA-F470-4242-A8CB-EC7EA805257C}"); + ISessionProviderRequests() = default; + virtual ~ISessionProviderRequests() = default; // Handle the destroy session process virtual void HandleDestroySession() = 0; @@ -84,9 +84,14 @@ namespace AzFramework // @param playerConnectionConfig The required properties to handle the player leave session process virtual void HandlePlayerLeaveSession(const PlayerConnectionConfig& playerConnectionConfig) = 0; - // Retrieves the file location of a pem-encoded TLS certificate + // Retrieves the file location of a pem-encoded TLS certificate for Client to Server communication // @return If successful, returns the file location of TLS certificate file; if not successful, returns // empty string. - virtual AZStd::string GetSessionCertificate() = 0; + virtual AZStd::string GetExternalSessionCertificate() = 0; + + // Retrieves the file location of a pem-encoded TLS certificate for Server to Server communication + // @return If successful, returns the file location of TLS certificate file; if not successful, returns + // empty string. + virtual AZStd::string GetInternalSessionCertificate() = 0; }; } // namespace AzFramework diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index ce4b7d8601..18d8bd6e2e 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -169,6 +170,24 @@ namespace Multiplayer AZ::TickBus::Handler::BusDisconnect(); } + bool MultiplayerSystemComponent::RequestPlayerJoinSession(const AzFramework::SessionConnectionConfig& config) + { + AZ::Interface::Get()->InitializeMultiplayer(MultiplayerAgentType::Client); + INetworkInterface* networkInterface = AZ::Interface::Get()->RetrieveNetworkInterface(AZ::Name(MPNetworkInterfaceName)); + + const IpAddress ipAddress(config.m_ipAddress.c_str(), config.m_port, networkInterface->GetType()); + networkInterface->Connect(ipAddress); + return true; + } + + void MultiplayerSystemComponent::RequestPlayerLeaveSession() + { + AZ::Interface::Get()->InitializeMultiplayer(MultiplayerAgentType::Uninitialized); + INetworkInterface* networkInterface = AZ::Interface::Get()->RetrieveNetworkInterface(AZ::Name(MPNetworkInterfaceName)); + auto visitor = [](IConnection& connection) { connection.Disconnect(DisconnectReason::TerminatedByUser, TerminationEndpoint::Local); }; + networkInterface->GetConnectionSet().VisitConnections(visitor); + } + bool MultiplayerSystemComponent::OnSessionHealthCheck() { return true; @@ -176,6 +195,21 @@ namespace Multiplayer bool MultiplayerSystemComponent::OnCreateSessionBegin(const AzFramework::SessionConfig& sessionConfig) { + // Check if session manager has a certificate for us and pass it along if so + AZ::CVarFixedString externalCertPath = AZ::CVarFixedString(AZ::Interface::Get()->GetExternalSessionCertificate()); + if (!externalCertPath.empty()) + { + AZ::CVarFixedString commandString = "net_SslExternalCertificateFile " + externalCertPath; + AZ::Interface::Get()->PerformCommand(commandString.c_str()); + } + + AZ::CVarFixedString internalCertPath = AZ::CVarFixedString(AZ::Interface::Get()->GetInternalSessionCertificate()); + if (!internalCertPath.empty()) + { + AZ::CVarFixedString commandString = "net_SslInternalCertificateFile " + internalCertPath; + AZ::Interface::Get()->PerformCommand(commandString.c_str()); + } + Multiplayer::MultiplayerAgentType serverType = sv_isDedicated ? MultiplayerAgentType::DedicatedServer : MultiplayerAgentType::ClientServer; AZ::Interface::Get()->InitializeMultiplayer(serverType); return m_networkInterface->Listen(sessionConfig.m_port); @@ -497,6 +531,10 @@ namespace Multiplayer { AZLOG_INFO("New incoming connection from remote address: %s", connection->GetRemoteAddress().GetString().c_str()); m_connAcquiredEvent.Signal(datum); + AzFramework::PlayerConnectionConfig config; + config.m_playerConnectionId = aznumeric_cast(connection->GetConnectionId()); + config.m_playerSessionId = AZStd::to_string(config.m_playerConnectionId); + AZ::Interface::Get()->ValidatePlayerJoinSession(config); } // Hosts will spawn a new default player prefab for the user that just connected @@ -558,6 +596,34 @@ namespace Multiplayer delete connectionData; connection->SetUserData(nullptr); } + + // Signal to session management that a user triggered a disconnect + if (m_agentType == MultiplayerAgentType::Client && connection->GetConnectionRole() == ConnectionRole::Connector) + { + AZ::Interface::Get()->LeaveSession(); + } + + // Signal to session management that a user has left the server + if (m_agentType == MultiplayerAgentType::DedicatedServer || m_agentType == MultiplayerAgentType::ClientServer) + { + if (connection->GetConnectionRole() == ConnectionRole::Connector) + { + AzFramework::PlayerConnectionConfig config; + config.m_playerConnectionId = aznumeric_cast(connection->GetConnectionId()); + config.m_playerSessionId = AZStd::to_string(config.m_playerConnectionId); + AZ::Interface::Get()->HandlePlayerLeaveSession(config); + } + } + + // Signal to session management when there are no remaining players in a dedicated server for potential cleanup + // We avoid this for client server as the host itself is a user + if (m_agentType == MultiplayerAgentType::DedicatedServer) + { + if (m_networkInterface->GetConnectionSet().GetConnectionCount() == 0) + { + AZ::Interface::Get()->HandleDestroySession(); + } + } } MultiplayerAgentType MultiplayerSystemComponent::GetAgentType() const @@ -788,6 +854,7 @@ namespace Multiplayer } AZ_CONSOLEFREEFUNC(host, AZ::ConsoleFunctorFlags::DontReplicate, "Opens a multiplayer connection as a host for other clients to connect to"); + void connect([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { AZ::Interface::Get()->InitializeMultiplayer(MultiplayerAgentType::Client); diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index ab3e54ad6d..505df52a6a 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include @@ -45,6 +47,7 @@ namespace Multiplayer : public AZ::Component , public AZ::TickBus::Handler , public AzFramework::SessionNotificationBus::Handler + , public AzFramework::ISessionLocalUserRequests , public AzNetworking::IConnectionListener , public IMultiplayer { @@ -96,6 +99,12 @@ namespace Multiplayer void OnDisconnect(AzNetworking::IConnection* connection, AzNetworking::DisconnectReason reason, AzNetworking::TerminationEndpoint endpoint) override; //! @} + //! ISessionLocalUserRequests interface + //! @{ + bool RequestPlayerJoinSession(const AzFramework::SessionConnectionConfig& sessionConnectionConfig) override; + void RequestPlayerLeaveSession() override; + //! @} + //! IMultiplayer interface //! @{ MultiplayerAgentType GetAgentType() const override; From 03989f77bb120188bad5c0cb9fdd973becd988f7 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Mon, 7 Jun 2021 17:06:00 -0700 Subject: [PATCH 569/811] Cleanup includes --- Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp | 1 - Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h | 1 - 2 files changed, 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 18d8bd6e2e..44e17c0ef4 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -32,7 +32,6 @@ #include #include #include -#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index 505df52a6a..f6ca670d87 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -25,7 +25,6 @@ #include #include #include -#include #include #include #include From 6f4c0c2ce898dcdf84cb02c0e34e3e740a72c1ae Mon Sep 17 00:00:00 2001 From: puvvadar Date: Mon, 7 Jun 2021 17:12:29 -0700 Subject: [PATCH 570/811] Rename interfaces for clarity --- .../Session/ISessionHandlingRequests.h | 20 +++++++++---------- .../Source/MultiplayerSystemComponent.cpp | 12 ++++++----- .../Code/Source/MultiplayerSystemComponent.h | 4 ++-- 3 files changed, 19 insertions(+), 17 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h b/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h index 2537842d8a..10c1d1cdd5 100644 --- a/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h +++ b/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h @@ -45,14 +45,14 @@ namespace AzFramework AZStd::string m_playerSessionId; }; - //! ISessionLocalUserRequests - //! Requests made to the local user to manage their connection to a session - class ISessionLocalUserRequests + //! ISessionHandlingClientRequests + //! Requests made to the client to manage their connection to a session + class ISessionHandlingClientRequests { public: - AZ_RTTI(ISessionLocalUserRequests, "{41DE6BD3-72BC-4443-BFF9-5B1B9396657A}"); - ISessionLocalUserRequests() = default; - virtual ~ISessionLocalUserRequests() = default; + AZ_RTTI(ISessionHandlingClientRequests, "{41DE6BD3-72BC-4443-BFF9-5B1B9396657A}"); + ISessionHandlingClientRequests() = default; + virtual ~ISessionHandlingClientRequests() = default; // Request the player join session // @param sessionConnectionConfig The required properties to handle the player join session process @@ -65,12 +65,12 @@ namespace AzFramework //! ISessionProviderRequests //! Requests made to the service providing server/fleet management by the server - class ISessionProviderRequests + class ISessionHandlingProviderRequests { public: - AZ_RTTI(ISessionProviderRequests, "{4F0C17BA-F470-4242-A8CB-EC7EA805257C}"); - ISessionProviderRequests() = default; - virtual ~ISessionProviderRequests() = default; + AZ_RTTI(ISessionHandlingProviderRequests, "{4F0C17BA-F470-4242-A8CB-EC7EA805257C}"); + ISessionHandlingProviderRequests() = default; + virtual ~ISessionHandlingProviderRequests() = default; // Handle the destroy session process virtual void HandleDestroySession() = 0; diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 44e17c0ef4..336f27e7e4 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -157,6 +157,7 @@ namespace Multiplayer m_networkInterface = AZ::Interface::Get()->CreateNetworkInterface(AZ::Name(MPNetworkInterfaceName), sv_protocol, TrustZone::ExternalClientToServer, *this); m_consoleCommandHandler.Connect(AZ::Interface::Get()->GetConsoleCommandInvokedEvent()); AZ::Interface::Register(this); + AZ::Interface::Register(this); //! Register our gems multiplayer components to assign NetComponentIds RegisterMultiplayerComponents(); @@ -164,6 +165,7 @@ namespace Multiplayer void MultiplayerSystemComponent::Deactivate() { + AZ::Interface::Unregister(this); AZ::Interface::Unregister(this); AzFramework::SessionNotificationBus::Handler::BusDisconnect(); AZ::TickBus::Handler::BusDisconnect(); @@ -195,14 +197,14 @@ namespace Multiplayer bool MultiplayerSystemComponent::OnCreateSessionBegin(const AzFramework::SessionConfig& sessionConfig) { // Check if session manager has a certificate for us and pass it along if so - AZ::CVarFixedString externalCertPath = AZ::CVarFixedString(AZ::Interface::Get()->GetExternalSessionCertificate()); + AZ::CVarFixedString externalCertPath = AZ::CVarFixedString(AZ::Interface::Get()->GetExternalSessionCertificate()); if (!externalCertPath.empty()) { AZ::CVarFixedString commandString = "net_SslExternalCertificateFile " + externalCertPath; AZ::Interface::Get()->PerformCommand(commandString.c_str()); } - AZ::CVarFixedString internalCertPath = AZ::CVarFixedString(AZ::Interface::Get()->GetInternalSessionCertificate()); + AZ::CVarFixedString internalCertPath = AZ::CVarFixedString(AZ::Interface::Get()->GetInternalSessionCertificate()); if (!internalCertPath.empty()) { AZ::CVarFixedString commandString = "net_SslInternalCertificateFile " + internalCertPath; @@ -533,7 +535,7 @@ namespace Multiplayer AzFramework::PlayerConnectionConfig config; config.m_playerConnectionId = aznumeric_cast(connection->GetConnectionId()); config.m_playerSessionId = AZStd::to_string(config.m_playerConnectionId); - AZ::Interface::Get()->ValidatePlayerJoinSession(config); + AZ::Interface::Get()->ValidatePlayerJoinSession(config); } // Hosts will spawn a new default player prefab for the user that just connected @@ -610,7 +612,7 @@ namespace Multiplayer AzFramework::PlayerConnectionConfig config; config.m_playerConnectionId = aznumeric_cast(connection->GetConnectionId()); config.m_playerSessionId = AZStd::to_string(config.m_playerConnectionId); - AZ::Interface::Get()->HandlePlayerLeaveSession(config); + AZ::Interface::Get()->HandlePlayerLeaveSession(config); } } @@ -620,7 +622,7 @@ namespace Multiplayer { if (m_networkInterface->GetConnectionSet().GetConnectionCount() == 0) { - AZ::Interface::Get()->HandleDestroySession(); + AZ::Interface::Get()->HandleDestroySession(); } } } diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index f6ca670d87..c089b243bd 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -46,7 +46,7 @@ namespace Multiplayer : public AZ::Component , public AZ::TickBus::Handler , public AzFramework::SessionNotificationBus::Handler - , public AzFramework::ISessionLocalUserRequests + , public AzFramework::ISessionHandlingClientRequests , public AzNetworking::IConnectionListener , public IMultiplayer { @@ -98,7 +98,7 @@ namespace Multiplayer void OnDisconnect(AzNetworking::IConnection* connection, AzNetworking::DisconnectReason reason, AzNetworking::TerminationEndpoint endpoint) override; //! @} - //! ISessionLocalUserRequests interface + //! ISessionHandlingClientRequests interface //! @{ bool RequestPlayerJoinSession(const AzFramework::SessionConnectionConfig& sessionConnectionConfig) override; void RequestPlayerLeaveSession() override; From 45b1bbc85cd273a5f0392488b862b2395620e005 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Mon, 7 Jun 2021 17:13:52 -0700 Subject: [PATCH 571/811] Fix duplicate include --- Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 336f27e7e4..bd5f4e63de 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -36,7 +36,6 @@ #include #include #include -#include #include From 2b227a17d1ce1ddad9517c3ffa9b83ca269f8885 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Mon, 7 Jun 2021 17:20:12 -0700 Subject: [PATCH 572/811] Remove extraneous code --- .../Multiplayer/Code/Source/MultiplayerSystemComponent.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index bd5f4e63de..6f8569251f 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -597,12 +597,6 @@ namespace Multiplayer connection->SetUserData(nullptr); } - // Signal to session management that a user triggered a disconnect - if (m_agentType == MultiplayerAgentType::Client && connection->GetConnectionRole() == ConnectionRole::Connector) - { - AZ::Interface::Get()->LeaveSession(); - } - // Signal to session management that a user has left the server if (m_agentType == MultiplayerAgentType::DedicatedServer || m_agentType == MultiplayerAgentType::ClientServer) { @@ -854,7 +848,6 @@ namespace Multiplayer } AZ_CONSOLEFREEFUNC(host, AZ::ConsoleFunctorFlags::DontReplicate, "Opens a multiplayer connection as a host for other clients to connect to"); - void connect([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { AZ::Interface::Get()->InitializeMultiplayer(MultiplayerAgentType::Client); From 9373c5fd0d45ed20170f9f8f580fc80c031b6cbe Mon Sep 17 00:00:00 2001 From: evanchia Date: Mon, 7 Jun 2021 18:31:57 -0700 Subject: [PATCH 573/811] Fixing xml directory race condition on incremental runs --- scripts/build/Jenkins/Jenkinsfile | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile index 1bce2988bf..4d350da55a 100644 --- a/scripts/build/Jenkins/Jenkinsfile +++ b/scripts/build/Jenkins/Jenkinsfile @@ -365,8 +365,11 @@ def ExportTestResults(Map options, String platform, String type, String workspac def o3deroot = "${workspace}/${ENGINE_REPOSITORY_NAME}" dir("${o3deroot}/${params.OUTPUT_DIRECTORY}") { junit testResults: "Testing/**/*.xml" - palRmDir("Testing") + palRmDir("Testing/*") } + // Recreate test runner xml directories that need to be pre generated + palMkdir("Testing/Pytest") + palMkdir("Testing/Gtest") } } From 9afe5225e6424756281127e8175c218cba1770ae Mon Sep 17 00:00:00 2001 From: evanchia Date: Mon, 7 Jun 2021 18:39:03 -0700 Subject: [PATCH 574/811] removing wildcard from rmdir, not windows compatible --- 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 4d350da55a..e1384fcbe5 100644 --- a/scripts/build/Jenkins/Jenkinsfile +++ b/scripts/build/Jenkins/Jenkinsfile @@ -365,7 +365,7 @@ def ExportTestResults(Map options, String platform, String type, String workspac def o3deroot = "${workspace}/${ENGINE_REPOSITORY_NAME}" dir("${o3deroot}/${params.OUTPUT_DIRECTORY}") { junit testResults: "Testing/**/*.xml" - palRmDir("Testing/*") + palRmDir("Testing") } // Recreate test runner xml directories that need to be pre generated palMkdir("Testing/Pytest") From b2a6616a3174be80524fe03108754e7ec01bffee Mon Sep 17 00:00:00 2001 From: evanchia Date: Mon, 7 Jun 2021 18:50:21 -0700 Subject: [PATCH 575/811] fixed cwd error --- scripts/build/Jenkins/Jenkinsfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile index e1384fcbe5..693cf31727 100644 --- a/scripts/build/Jenkins/Jenkinsfile +++ b/scripts/build/Jenkins/Jenkinsfile @@ -366,10 +366,10 @@ def ExportTestResults(Map options, String platform, String type, String workspac dir("${o3deroot}/${params.OUTPUT_DIRECTORY}") { junit testResults: "Testing/**/*.xml" palRmDir("Testing") + // Recreate test runner xml directories that need to be pre generated + palMkdir("Testing/Pytest") + palMkdir("Testing/Gtest") } - // Recreate test runner xml directories that need to be pre generated - palMkdir("Testing/Pytest") - palMkdir("Testing/Gtest") } } From 7ca7ad9b7280dc64c2562110cac069be1916e6ff Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Mon, 7 Jun 2021 19:50:40 -0700 Subject: [PATCH 576/811] Fix missing user_tags exception and configure gems button --- .../Resources/ProjectManager.qss | 24 +++++++++++++++++++ .../ProjectManager/Source/PythonBindings.cpp | 7 ++++-- .../Source/UpdateProjectCtrl.cpp | 4 ++-- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qss b/Code/Tools/ProjectManager/Resources/ProjectManager.qss index c18d61fc24..80470591a8 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qss +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qss @@ -291,6 +291,30 @@ QTabBar::tab:pressed height:50px; } +#projectSettingsTab::tab-bar > QPushButton { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #888888, stop: 1.0 #555555); + qproperty-flat: true; + margin-right:30px; + margin-bottom:12px; + margin-top:0px; + min-width:170px; + max-width:170px; + min-height:26px; + max-height:26px; + border-radius: 3px; + text-align:center; + font-size:13px; +} +#projectSettingsTab::tab-bar > QPushButton:hover { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #999999, stop: 1.0 #666666); +} +#projectSettingsTab::tab-bar > QPushButton:pressed { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #555555, stop: 1.0 #777777); +} + #projectSettingsTopFrame { background-color:#1E252F; } diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 73e860112f..5e7c78d2ec 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -682,9 +682,12 @@ namespace O3DE::ProjectManager projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName); projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin); projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary); - for (auto tag : projectData["user_tags"]) + if (projectData.contains("user_tags")) { - projectInfo.m_userTags.append(Py_To_String(tag)); + for (auto tag : projectData["user_tags"]) + { + projectInfo.m_userTags.append(Py_To_String(tag)); + } } } catch ([[maybe_unused]] const std::exception& e) diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp index 3fb2d97e25..be1f0e5529 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp @@ -58,7 +58,7 @@ namespace O3DE::ProjectManager tabWidget->tabBar()->setObjectName("projectSettingsTabBar"); tabWidget->addTab(m_updateSettingsScreen, tr("General")); - QPushButton* gemsButton = new QPushButton(tr("Add More Gems"), this); + QPushButton* gemsButton = new QPushButton(tr("Configure Gems"), this); topBarHLayout->addWidget(gemsButton); tabWidget->setCornerWidget(gemsButton); @@ -189,7 +189,7 @@ namespace O3DE::ProjectManager { if (m_stack->currentIndex() == ScreenOrder::Gems) { - m_header->setSubTitle(QString(tr("Add More Gems to \"%1\"")).arg(m_projectInfo.m_projectName)); + m_header->setSubTitle(QString(tr("Configure Gems for \"%1\"")).arg(m_projectInfo.m_projectName)); m_nextButton->setText(tr("Confirm")); } else From 4e79e6004ceca5cb416baa9f8c780ce11636a9cb Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Tue, 8 Jun 2021 07:39:35 +0200 Subject: [PATCH 577/811] [LYN-3845] On the Actor component, click on the Animation Editor button, EMFX isn't opening (#1169) We're opening the Animation Editor now also in case no actor has been chosen yet. In this case the Animation Editor will also just be started without loading any assets. --- .../Editor/Components/EditorActorComponent.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index 7d5b7ade00..4b4685ebb1 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp @@ -435,19 +435,17 @@ namespace EMotionFX void EditorActorComponent::LaunchAnimationEditor(const AZ::Data::AssetId& assetId, const AZ::Data::AssetType&) { + // call to open must be done before LoadCharacter + const char* panelName = EMStudio::MainWindow::GetEMotionFXPaneName(); + EBUS_EVENT(AzToolsFramework::EditorRequests::Bus, OpenViewPane, panelName); + if (assetId.IsValid()) { AZ::Data::AssetId animgraphAssetId; - animgraphAssetId.SetInvalid(); EditorAnimGraphComponentRequestBus::EventResult(animgraphAssetId, GetEntityId(), &EditorAnimGraphComponentRequestBus::Events::GetAnimGraphAssetId); AZ::Data::AssetId motionSetAssetId; - motionSetAssetId.SetInvalid(); EditorAnimGraphComponentRequestBus::EventResult(motionSetAssetId, GetEntityId(), &EditorAnimGraphComponentRequestBus::Events::GetMotionSetAssetId); - // call to open must be done before LoadCharacter - const char* panelName = EMStudio::MainWindow::GetEMotionFXPaneName(); - EBUS_EVENT(AzToolsFramework::EditorRequests::Bus, OpenViewPane, panelName); - EMStudio::MainWindow* mainWindow = EMStudio::GetMainWindow(); if (mainWindow) { From a30d9621d5e930d66fc6ed7fda4fdb2b288866ae Mon Sep 17 00:00:00 2001 From: antonmic Date: Mon, 7 Jun 2021 23:05:36 -0700 Subject: [PATCH 578/811] Pass changes WIP: various fixes, exposure sample now works --- .../Code/Source/CoreLights/LightCullingTilePreparePass.cpp | 2 +- .../Feature/Common/Code/Source/PostProcessing/TaaPass.cpp | 4 ++-- .../Feature/Common/Code/Source/PostProcessing/TaaPass.h | 2 +- Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp | 3 +-- Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp | 6 +++--- 5 files changed, 8 insertions(+), 9 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.cpp index c144525cec..4f2a4f0346 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingTilePreparePass.cpp @@ -176,7 +176,7 @@ namespace AZ { LoadShader(); AZ_Assert(GetPassState() != RPI::PassState::Rendering, "LightCullingTilePreparePass: Trying to reload shader during rendering"); - if (GetPassState() == RPI::PassState::Initialized) + if (GetPassState() == RPI::PassState::Idle) { ChooseShaderVariant(); } diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp index 9f885ede70..38e03ab156 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp @@ -108,7 +108,7 @@ namespace AZ::Render Base::ResetInternal(); } - void TaaPass::BuildAttachmentsInternal() + void TaaPass::BuildInternal() { m_accumulationAttachments[0] = FindAttachment(Name("Accumulation1")); m_accumulationAttachments[1] = FindAttachment(Name("Accumulation2")); @@ -143,7 +143,7 @@ namespace AZ::Render m_outputColorBinding->SetAttachment(m_accumulationAttachments[1]); } - Base::BuildAttachmentsInternal(); + Base::BuildInternal(); } void TaaPass::UpdateAttachmentImage(RPI::Ptr& attachment) diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.h index 6133720691..e8f4796e7b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.h @@ -63,7 +63,7 @@ namespace AZ::Render // Pass behavior overrides... void FrameBeginInternal(FramePrepareParams params) override; void ResetInternal() override; - void BuildAttachmentsInternal() override; + void BuildInternal() override; void UpdateAttachmentImage(RPI::Ptr& attachment); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp index 4002216361..78e30e7176 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp @@ -1160,8 +1160,6 @@ namespace AZ { AZ_RPI_BREAK_ON_TARGET_PASS; - AZ_Assert(m_state == PassState::Reset, "ANTON - BUILDING PASS BUT STATE IS NOT RESET!!"); - bool execute = (m_state == PassState::Idle || m_state == PassState::Reset); execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForBuild); execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForInitialization); @@ -1180,6 +1178,7 @@ namespace AZ } #endif + AZ_Assert(m_state == PassState::Reset, "ANTON - BUILDING PASS BUT STATE IS NOT RESET!!"); m_state = PassState::Building; // Bindings, inputs and attachments diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp index a7021ee6fd..76ea52b4a3 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -217,7 +217,7 @@ namespace AZ Pass* previousPassInList = nullptr; for (const Ptr& pass : buildListCopy) { - if (pass.get() != previousPassInList); + if (pass.get() != previousPassInList) { pass->Reset(); previousPassInList = pass.get(); @@ -226,7 +226,7 @@ namespace AZ previousPassInList = nullptr; for (const Ptr& pass : buildListCopy) { - if (pass.get() != previousPassInList); + if (pass.get() != previousPassInList) { pass->Build(true); previousPassInList = pass.get(); @@ -276,7 +276,7 @@ namespace AZ Pass* previousPassInList = nullptr; for (const Ptr& pass : initListCopy) { - if (pass.get() != previousPassInList); + if (pass.get() != previousPassInList) { pass->Initialize(); previousPassInList = pass.get(); From 863aac2cb95a5738570389be7e5881cc10541b40 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Tue, 8 Jun 2021 08:41:58 +0200 Subject: [PATCH 579/811] [LYN-3727] Actor Draw Bounds Draw Bounds & [LYN-3725] Actor Draw Skeleton Doesn't Draw Skeleton (#1168) * [LYN-3727] Actor Draw Bounds Draw Bounds & [LYN-3725] Actor Draw Skeleton Doesn't Draw Skeleton * Added skeleton, aabb and emfx debug drawing to the actor component. * Aux geom rendering is flickering as also reported in the Discord channels. Trick with using the scene notification bus did not work as the actor instance is not bound to a given scene as far as I am aware. --- .../Atom/RPI.Public/AuxGeom/AuxGeomDraw.h | 2 +- .../Code/Source/AtomActorInstance.cpp | 119 +++++++++++++++++- .../Code/Source/AtomActorInstance.h | 11 +- .../Components/EditorActorComponent.cpp | 1 + 4 files changed, 130 insertions(+), 3 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/AuxGeom/AuxGeomDraw.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/AuxGeom/AuxGeomDraw.h index 0e7f11e46e..525bbc1521 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/AuxGeom/AuxGeomDraw.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/AuxGeom/AuxGeomDraw.h @@ -81,7 +81,7 @@ namespace AZ //! Common arguments for free polygon (point, line, Triangle) draws. struct AuxGeomDynamicDrawArguments { - const AZ::Vector3* m_verts = nullptr; //!< An array of points, 1 for each vertice. + const AZ::Vector3* m_verts = nullptr; //!< An array of points, 1 for each vertex. uint32_t m_vertCount = 0; //!< The number of vertices. const AZ::Color* m_colors; //!< An array of colors, must have either vertCount entries or 1 entry. uint32_t m_colorCount = 0; //!< The number of colors, must equal 1 or vertCount. diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp index 9079f639ba..532c8720b5 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -27,6 +28,8 @@ #include #include +#include +#include #include #include @@ -57,6 +60,8 @@ namespace AZ Activate(); AzFramework::BoundsRequestBus::Handler::BusConnect(m_entityId); } + + m_auxGeomFeatureProcessor = RPI::Scene::GetFeatureProcessorForEntity(m_entityId); } AtomActorInstance::~AtomActorInstance() @@ -88,7 +93,119 @@ namespace AZ AZ::Interface::Get()->RefreshEntityLocalBoundsUnion(m_entityId); } - AZ::Aabb AtomActorInstance:: GetWorldBounds() + void AtomActorInstance::DebugDraw(const DebugOptions& debugOptions) + { + if (m_auxGeomFeatureProcessor) + { + if (RPI::AuxGeomDrawPtr auxGeom = m_auxGeomFeatureProcessor->GetDrawQueue()) + { + if (debugOptions.m_drawAABB) + { + const MCore::AABB emfxAabb = m_actorInstance->GetAABB(); + const AZ::Aabb azAabb = AZ::Aabb::CreateFromMinMax(emfxAabb.GetMin(), emfxAabb.GetMax()); + auxGeom->DrawAabb(azAabb, AZ::Color(0.0f, 1.0f, 1.0f, 1.0f), RPI::AuxGeomDraw::DrawStyle::Line); + } + + if (debugOptions.m_drawSkeleton) + { + RenderSkeleton(auxGeom.get()); + } + + if (debugOptions.m_emfxDebugDraw) + { + RenderEMFXDebugDraw(auxGeom.get()); + } + } + } + } + + void AtomActorInstance::RenderSkeleton(RPI::AuxGeomDraw* auxGeom) + { + AZ_Assert(m_actorInstance, "Valid actor instance required."); + const EMotionFX::TransformData* transformData = m_actorInstance->GetTransformData(); + 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(); + + m_auxVertices.clear(); + m_auxVertices.reserve(numJoints * 2); + + for (AZ::u32 jointIndex = 0; jointIndex < numJoints; ++jointIndex) + { + const EMotionFX::Node* joint = skeleton->GetNode(jointIndex); + if (!joint->GetSkeletalLODStatus(lodLevel)) + { + continue; + } + + const AZ::u32 parentIndex = joint->GetParentIndex(); + if (parentIndex == InvalidIndex32) + { + continue; + } + + const AZ::Vector3 parentPos = pose->GetWorldSpaceTransform(parentIndex).mPosition; + m_auxVertices.emplace_back(parentPos); + + const AZ::Vector3 bonePos = pose->GetWorldSpaceTransform(jointIndex).mPosition; + m_auxVertices.emplace_back(bonePos); + } + + const AZ::Color skeletonColor(0.604f, 0.804f, 0.196f, 1.0f); + RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments lineArgs; + lineArgs.m_verts = m_auxVertices.data(); + lineArgs.m_vertCount = m_auxVertices.size(); + lineArgs.m_colors = &skeletonColor; + lineArgs.m_colorCount = 1; + lineArgs.m_depthTest = RPI::AuxGeomDraw::DepthTest::Off; + auxGeom->DrawLines(lineArgs); + } + + void AtomActorInstance::RenderEMFXDebugDraw(RPI::AuxGeomDraw* auxGeom) + { + EMotionFX::DebugDraw& debugDraw = EMotionFX::GetDebugDraw(); + debugDraw.Lock(); + EMotionFX::DebugDraw::ActorInstanceData* actorInstanceData = debugDraw.GetActorInstanceData(m_actorInstance); + actorInstanceData->Lock(); + const AZStd::vector& lines = actorInstanceData->GetLines(); + if (lines.empty()) + { + actorInstanceData->Unlock(); + debugDraw.Unlock(); + return; + } + + m_auxVertices.clear(); + m_auxVertices.reserve(lines.size() * 2); + m_auxColors.clear(); + m_auxColors.reserve(m_auxVertices.size()); + + for (const EMotionFX::DebugDraw::Line& line : actorInstanceData->GetLines()) + { + m_auxVertices.emplace_back(line.m_start); + m_auxColors.emplace_back(line.m_startColor); + m_auxVertices.emplace_back(line.m_end); + m_auxColors.emplace_back(line.m_endColor); + } + + AZ_Assert(m_auxVertices.size() == m_auxColors.size(), + "Number of vertices and number of colors need to match."); + actorInstanceData->Unlock(); + debugDraw.Unlock(); + + RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments lineArgs; + lineArgs.m_verts = m_auxVertices.data(); + lineArgs.m_vertCount = m_auxVertices.size(); + lineArgs.m_colors = m_auxColors.data(); + lineArgs.m_colorCount = m_auxColors.size(); + lineArgs.m_depthTest = RPI::AuxGeomDraw::DepthTest::Off; + auxGeom->DrawLines(lineArgs); + } + + AZ::Aabb AtomActorInstance::GetWorldBounds() { return m_worldAABB; } diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h index e05280e896..98e47e7128 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h @@ -42,6 +42,8 @@ namespace EMotionFX } namespace AZ::RPI { + class AuxGeomDraw; + class AuxGeomFeatureProcessorInterface; class Model; class Buffer; class StreamingImage; @@ -89,7 +91,7 @@ namespace AZ // RenderActorInstance overrides ... void OnTick(float timeDelta) override; void UpdateBounds() override; - void DebugDraw(const DebugOptions& debugOptions) override { AZ_UNUSED(debugOptions) }; + void DebugDraw(const DebugOptions& debugOptions) override; void SetMaterials(const EMotionFX::Integration::ActorAsset::MaterialList& materialPerLOD) override { AZ_UNUSED(materialPerLOD); }; void SetSkinningMethod(EMotionFX::Integration::SkinningMethod emfxSkinningMethod); SkinningMethod GetAtomSkinningMethod() const; @@ -177,6 +179,13 @@ namespace AZ void InitWrinkleMasks(); void UpdateWrinkleMasks(); + // Helper and debug geometry rendering + void RenderSkeleton(RPI::AuxGeomDraw* auxGeom); + void RenderEMFXDebugDraw(RPI::AuxGeomDraw* auxGeom); + RPI::AuxGeomFeatureProcessorInterface* m_auxGeomFeatureProcessor = nullptr; + AZStd::vector m_auxVertices; + AZStd::vector m_auxColors; + AZStd::intrusive_ptr m_skinnedMeshInputBuffers = nullptr; AZStd::intrusive_ptr m_skinnedMeshInstance; AZ::Data::Instance m_boneTransforms = nullptr; diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index 4b4685ebb1..5c085e96f7 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp @@ -553,6 +553,7 @@ namespace EMotionFX RenderActorInstance::DebugOptions debugOptions; debugOptions.m_drawAABB = m_renderBounds; debugOptions.m_drawSkeleton = m_renderSkeleton; + debugOptions.m_emfxDebugDraw = true; m_renderActorInstance->DebugDraw(debugOptions); } } From bcff7ff6988240ebd556ce7ce25a76ed53c0d581 Mon Sep 17 00:00:00 2001 From: greerdv Date: Tue, 8 Jun 2021 14:53:22 +0100 Subject: [PATCH 580/811] fix argument processing for physx debug console commands --- Gems/PhysXDebug/Code/Source/SystemComponent.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 34315eb11e..5f3186604c 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -565,9 +565,9 @@ namespace PhysXDebug static void physx_CullingBoxSize([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { const int argumentCount = arguments.size(); - if (argumentCount == 2) + if (argumentCount == 1) { - float newCullingBoxSize = (float)strtol(AZ::CVarFixedString(arguments[1]).c_str(), nullptr, 10); + float newCullingBoxSize = (float)strtol(AZ::CVarFixedString(arguments[0]).c_str(), nullptr, 10); PhysXDebug::PhysXDebugRequestBus::Broadcast(&PhysXDebug::PhysXDebugRequestBus::Events::SetCullingBoxSize, newCullingBoxSize); } else @@ -584,9 +584,9 @@ namespace PhysXDebug const int argumentCount = arguments.size(); - if (argumentCount == 2) + if (argumentCount == 1) { - const auto userPreference = static_cast(strtol(AZ::CVarFixedString(arguments[1]).c_str(), nullptr, 10)); + const auto userPreference = static_cast(strtol(AZ::CVarFixedString(arguments[0]).c_str(), nullptr, 10)); switch (userPreference) { From 937118f0a1685aa5f13128ab77e4a96629461288 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Tue, 8 Jun 2021 17:49:52 +0100 Subject: [PATCH 581/811] physxdebug switch viewport id to AzFramework::g_defaultSceneEntityDebugDisplayId (#1188) --- Gems/PhysXDebug/Code/Source/SystemComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 5f3186604c..c693599a59 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -42,7 +42,7 @@ namespace PhysXDebug const float SystemComponent::m_maxCullingBoxSize = 150.0f; namespace Internal { - const AZ::Crc32 VewportId = 0; // was AzFramework::g_defaultSceneEntityDebugDisplayId but it didn't render to the viewport. + const AZ::Crc32 VewportId = AzFramework::g_defaultSceneEntityDebugDisplayId; } bool UseEditorPhysicsScene() From b24c83122e3679a63349de4a1204e53061ea744f Mon Sep 17 00:00:00 2001 From: sharmajs-amzn <82233357+sharmajs-amzn@users.noreply.github.com> Date: Tue, 8 Jun 2021 09:52:17 -0700 Subject: [PATCH 582/811] fixes for missing dependency tests (#1141) --- AutomatedTesting/TestAssets/ReportOneMissingDependency.txt | 5 +++++ Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py | 5 +++-- 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 AutomatedTesting/TestAssets/ReportOneMissingDependency.txt diff --git a/AutomatedTesting/TestAssets/ReportOneMissingDependency.txt b/AutomatedTesting/TestAssets/ReportOneMissingDependency.txt new file mode 100644 index 0000000000..24a8493ee5 --- /dev/null +++ b/AutomatedTesting/TestAssets/ReportOneMissingDependency.txt @@ -0,0 +1,5 @@ +This is the UUID for libs / particles / milestone2particles . xml. +6BDE282B49C957F7B0714B26579BCA9A +This isn an invalid UUID +33bdee92F3225688ABEE534F6058593F +This is another invalid UUID B076CDDC-14DK-50F4-A5E9-7518ABB3E851 \ No newline at end of file diff --git a/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py b/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py index 8e2b93c20a..a9c9a2fa5b 100644 --- a/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py +++ b/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py @@ -597,9 +597,10 @@ class AssetProcessor(object): run_result = subprocess.run(command, close_fds=True, timeout=timeout, capture_output=capture_output) output_list = None if capture_output: - output_list = run_result.stdout.splitlines() if decode: - output_list = [line.decode('utf-8') for line in output_list] + output_list = run_result.stdout.decode('utf-8').splitlines() + else: + output_list = run_result.stdout.splitlines() if run_result.returncode != 0: errorMessage = f"{command} returned error code: {run_result.returncode}" From 0fcd6e84ece985151153176482f2ad054da2d1e6 Mon Sep 17 00:00:00 2001 From: Terry Michaels Date: Tue, 8 Jun 2021 12:02:02 -0500 Subject: [PATCH 583/811] Added mechanism for viewpanes to request buttons on the main toolbar (#1189) --- .../AzToolsFramework/API/ViewPaneOptions.h | 3 +++ .../Sandbox/Editor/Core/LevelEditorMenuHandler.cpp | 11 +++++++++++ Code/Sandbox/Editor/MainWindow.cpp | 4 +++- Code/Sandbox/Editor/ToolbarManager.cpp | 14 ++++++++++++++ Code/Sandbox/Editor/ToolbarManager.h | 2 ++ 5 files changed, 33 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h index fb86968ebb..4891d2ef85 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h @@ -42,6 +42,9 @@ namespace AzToolsFramework bool detachedWindow = false; ///< set to true if the view pane should use a detached, non-dockable widget. This is to workaround a problem with QOpenGLWidget on macOS. Currently this has no effect on other platforms. bool isDisabledInSimMode = false; ///< set to true if the view pane should not be openable from level editor menu when editor is in simulation mode. + + bool showOnToolsToolbar = false; ///< set to true if the view pane should create a button on the tools toolbar to open/close the pane + QString toolbarIcon; ///< path to the icon to use for the toolbar button - only used if showOnToolsToolbar is set to true }; } // namespace AzToolsFramework diff --git a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp index 8f6e927a84..6292a99ec5 100644 --- a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp +++ b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp @@ -912,6 +912,12 @@ QAction* LevelEditorMenuHandler::CreateViewPaneAction(const QtViewPane* view) action = new QAction(menuText, this); action->setObjectName(view->m_name); action->setCheckable(true); + + if (view->m_options.showOnToolsToolbar) + { + action->setIcon(QIcon(view->m_options.toolbarIcon)); + } + m_actionManager->AddAction(view->m_id, action); if (!view->m_options.shortcut.isEmpty()) @@ -941,6 +947,11 @@ QAction* LevelEditorMenuHandler::CreateViewPaneMenuItem( menu->addAction(action); + if (view->m_options.showOnToolsToolbar) + { + m_mainWindow->GetToolbarManager()->AddButtonToEditToolbar(action); + } + return action; } diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index 31eac05824..3753c29064 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -470,9 +470,11 @@ void MainWindow::Initialize() InitToolActionHandlers(); + // Initialize toolbars before we setup the menu so that any tools can be added to the toolbar as needed + InitToolBars(); + m_levelEditorMenuHandler->Initialize(); - InitToolBars(); InitStatusBar(); AzToolsFramework::SourceControlNotificationBus::Handler::BusConnect(); diff --git a/Code/Sandbox/Editor/ToolbarManager.cpp b/Code/Sandbox/Editor/ToolbarManager.cpp index 241b969da7..137057a4fa 100644 --- a/Code/Sandbox/Editor/ToolbarManager.cpp +++ b/Code/Sandbox/Editor/ToolbarManager.cpp @@ -623,6 +623,20 @@ AmazonToolbar ToolbarManager::GetMiscToolbar() const return t; } +void ToolbarManager::AddButtonToEditToolbar(QAction* action) +{ + QString toolbarName = "EditMode"; + const AmazonToolbar* toolbar = FindToolbar(toolbarName); + + if (toolbar) + { + if (toolbar->Toolbar()) + { + toolbar->Toolbar()->addAction(action); + } + } +} + const AmazonToolbar* ToolbarManager::FindDefaultToolbar(const QString& toolbarName) const { for (const AmazonToolbar& toolbar : m_standardToolbars) diff --git a/Code/Sandbox/Editor/ToolbarManager.h b/Code/Sandbox/Editor/ToolbarManager.h index 70228636f5..1867316d01 100644 --- a/Code/Sandbox/Editor/ToolbarManager.h +++ b/Code/Sandbox/Editor/ToolbarManager.h @@ -169,6 +169,8 @@ public: AmazonToolbar GetMiscToolbar() const; AmazonToolbar GetPlayConsoleToolbar() const; + void AddButtonToEditToolbar(QAction* action); + private: Q_DISABLE_COPY(ToolbarManager); void SaveToolbars(); From 2d1e47793de79a98a7e7f9f0b84403ed424c55ef Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Tue, 8 Jun 2021 10:06:25 -0700 Subject: [PATCH 584/811] Move Duplicate menu items and shortcuts out of the Prefab Wip flag Make duplicate prefab workflows available by default in Prefab mode. --- .../EditorTransformComponentSelection.cpp | 51 ++++++++----------- .../Editor/Core/LevelEditorMenuHandler.cpp | 14 +---- .../SandboxIntegration.cpp | 15 ++---- 3 files changed, 26 insertions(+), 54 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index fee0267766..eadb870563 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -2240,42 +2240,31 @@ namespace AzToolsFramework RegenerateManipulators(); }); - bool isPrefabSystemEnabled = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult( - isPrefabSystemEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled); + // duplicate selection + AddAction( + m_actions, { QKeySequence(Qt::CTRL + Qt::Key_D) }, + /*ID_EDIT_CLONE =*/33525, s_duplicateTitle, s_duplicateDesc, + []() + { + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - bool prefabWipFeaturesEnabled = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult( - prefabWipFeaturesEnabled, &AzFramework::ApplicationRequests::ArePrefabWipFeaturesEnabled); - - if (!isPrefabSystemEnabled || (isPrefabSystemEnabled && prefabWipFeaturesEnabled)) - { - // duplicate selection - AddAction( - m_actions, { QKeySequence(Qt::CTRL + Qt::Key_D) }, - /*ID_EDIT_CLONE =*/33525, s_duplicateTitle, s_duplicateDesc, - []() + // Clear Widget selection - Prevents issues caused by cloning entities while a property in the Reflected Property Editor + // is being edited. + if (QApplication::focusWidget()) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + QApplication::focusWidget()->clearFocus(); + } - // Clear Widget selection - Prevents issues caused by cloning entities while a property in the Reflected Property Editor - // is being edited. - if (QApplication::focusWidget()) - { - QApplication::focusWidget()->clearFocus(); - } + ScopedUndoBatch undoBatch(s_duplicateUndoRedoDesc); + auto selectionCommand = AZStd::make_unique(EntityIdList(), s_duplicateUndoRedoDesc); + selectionCommand->SetParent(undoBatch.GetUndoBatch()); + selectionCommand.release(); - ScopedUndoBatch undoBatch(s_duplicateUndoRedoDesc); - auto selectionCommand = AZStd::make_unique(EntityIdList(), s_duplicateUndoRedoDesc); - selectionCommand->SetParent(undoBatch.GetUndoBatch()); - selectionCommand.release(); + bool handled = false; + EditorRequestBus::Broadcast(&EditorRequests::CloneSelection, handled); - bool handled = false; - EditorRequestBus::Broadcast(&EditorRequests::CloneSelection, handled); - - // selection update handled in AfterEntitySelectionChanged - }); - } + // selection update handled in AfterEntitySelectionChanged + }); // delete selection AddAction( diff --git a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp index 6292a99ec5..39c7ae43fd 100644 --- a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp +++ b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp @@ -473,18 +473,8 @@ void LevelEditorMenuHandler::PopulateEditMenu(ActionManager::MenuWrapper& editMe // editMenu->addAction(ID_EDIT_PASTE); // editMenu.AddSeparator(); - bool isPrefabSystemEnabled = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult(isPrefabSystemEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled); - - bool prefabWipFeaturesEnabled = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult( - prefabWipFeaturesEnabled, &AzFramework::ApplicationRequests::ArePrefabWipFeaturesEnabled); - - if (!isPrefabSystemEnabled || (isPrefabSystemEnabled && prefabWipFeaturesEnabled)) - { - // Duplicate - editMenu.AddAction(ID_EDIT_CLONE); - } + // Duplicate + editMenu.AddAction(ID_EDIT_CLONE); // Delete editMenu.AddAction(ID_EDIT_DELETE); diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 8161d07547..694714cc6e 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -670,18 +670,11 @@ void SandboxIntegrationManager::PopulateEditorGlobalContextMenu(QMenu* menu, con AzToolsFramework::EditorContextMenuBus::Broadcast(&AzToolsFramework::EditorContextMenuEvents::PopulateEditorGlobalContextMenu, menu); } - bool prefabWipFeaturesEnabled = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult( - prefabWipFeaturesEnabled, &AzFramework::ApplicationRequests::ArePrefabWipFeaturesEnabled); - - if (!prefabSystemEnabled || (prefabSystemEnabled && prefabWipFeaturesEnabled)) + action = menu->addAction(QObject::tr("Duplicate")); + QObject::connect(action, &QAction::triggered, action, [this] { ContextMenu_Duplicate(); }); + if (selected.size() == 0) { - action = menu->addAction(QObject::tr("Duplicate")); - QObject::connect(action, &QAction::triggered, action, [this] { ContextMenu_Duplicate(); }); - if (selected.size() == 0) - { - action->setDisabled(true); - } + action->setDisabled(true); } if (!prefabSystemEnabled) From 47e5c72f2e0a5e036ce367053e691fe4d2ebc00c Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Tue, 8 Jun 2021 18:20:34 +0100 Subject: [PATCH 585/811] fixed missing methods in SC from Trigger and Collision events (#1185) --- .../Physics/Collision/CollisionEvents.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionEvents.cpp b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionEvents.cpp index 4c9124f594..9f9e5c51ad 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionEvents.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionEvents.cpp @@ -37,9 +37,10 @@ namespace AzPhysics if (auto* behaviorContext = azdynamic_cast(context)) { behaviorContext->Class() - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Method("GetTriggerEntityId", &TriggerEvent::GetTriggerEntityId) - ->Method("GetOtherEntityId", &TriggerEvent::GetOtherEntityId) + ->Attribute(AZ::Script::Attributes::Module, "physics") + ->Attribute(AZ::Script::Attributes::Category, "Physics") + ->Method("Get Trigger EntityId", &TriggerEvent::GetTriggerEntityId) + ->Method("Get Other EntityId", &TriggerEvent::GetOtherEntityId) ; } } @@ -104,10 +105,11 @@ namespace AzPhysics if (auto* behaviorContext = azdynamic_cast(context)) { behaviorContext->Class() - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) - ->Property("Contacts", BehaviorValueProperty(&CollisionEvent::m_contacts)) - ->Method("GetBody1EntityId", &CollisionEvent::GetBody1EntityId) - ->Method("GetBody2EntityId", &CollisionEvent::GetBody2EntityId) + ->Attribute(AZ::Script::Attributes::Module, "physics") + ->Attribute(AZ::Script::Attributes::Category, "Physics") + ->Property("Contacts", BehaviorValueGetter(&CollisionEvent::m_contacts), nullptr) + ->Method("Get Body 1 EntityId", &CollisionEvent::GetBody1EntityId) + ->Method("Get Body 2 EntityId", &CollisionEvent::GetBody2EntityId) ; } } From 80f62d0523d61a401e37c1e66c09f57c680f9cd5 Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Tue, 8 Jun 2021 10:44:20 -0700 Subject: [PATCH 586/811] LYN-3708 | Optimize Prefab instance propagation to stabilize UX (#700) * Add instanceToIgnore to calls leading to instances being added to the queue for propagation. * Change PrefabUndoEntityUpdate to make it so that the instance triggering the prefab template change is not reloaded on propagation, since it will already be up to date due to the way we generated the patch to begin with. * Add FindPrefabDomValue utility function for paths * Expose the level root prefab template id in the Prefab EOS Interface * Fix Instance Alias Path generation to work with the new FindValueInPrefabDom function * Stop reloading ancestors on propagation, and fix instance reloading so that the level dom is used (and overrides are preserved) * Remove commented out code, refactor FindPrefabDomValue for paths (was handling an edge case incorrectly, and it's not even triggered) * Fix issue with PathView reference - with PathView already being a reference, this resulted in a copy and triggered a warning during automated review builds. * Additional fix to the build warning, remove redundant error message * Revert changes to Instance::GetAbsoluteInstanceAliasPath(), as they were impacting serialization. * Remove the dependency to the level root prefab template in the propagation code, climb up the hierarchy instead. This allows tests to work despite not using the EOS properly. Also use PrefabDomPaths to retrieve the instance dom from the root dom instead of iterating. * Remove now unused PrefabDomUtils function, extend optimization to link updates. * Trigger a full instance propagation to correctly refresh alias references. This is an issue in the test because some operations are called from the backend API and will not trigger propagation properly. Tests will soon be rewritten to more properly represent frontend workflows. * Fixes lingering issues with propagation: - Restores code that fixes the selection if entityIds have changed; - Fixes Do() function on link update. Prefab containers will propagate correctly while still being stable during editing. * Remove GetRootPrefabInstanceTemplateId (no longer necessary after the code has been rewritten) * Fix optimization code to account for instances being removed and propagation being run out of order in Create Prefab undo. * Renamed variable, added comments for clarity. * Restore asserts on instance not being found; Rename Do to Redo for clarity; Add comments. * Fixed incomplete comment. --- .../PrefabEditorEntityOwnershipService.h | 2 +- .../Instance/InstanceToTemplateInterface.h | 9 +- .../Instance/InstanceToTemplatePropagator.cpp | 4 +- .../Instance/InstanceToTemplatePropagator.h | 2 +- .../Instance/InstanceUpdateExecutor.cpp | 89 ++++++++++++++----- .../Prefab/Instance/InstanceUpdateExecutor.h | 2 +- .../InstanceUpdateExecutorInterface.h | 2 +- .../Prefab/PrefabPublicHandler.cpp | 24 ++--- .../Prefab/PrefabPublicHandler.h | 6 +- .../Prefab/PrefabSystemComponent.cpp | 14 ++- .../Prefab/PrefabSystemComponent.h | 4 +- .../Prefab/PrefabSystemComponentInterface.h | 2 +- .../AzToolsFramework/Prefab/PrefabUndo.cpp | 26 ++++-- .../AzToolsFramework/Prefab/PrefabUndo.h | 9 +- .../Tests/Prefab/PrefabEntityAliasTests.cpp | 1 + 15 files changed, 135 insertions(+), 61 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h index d8eb81dd40..d8bc63cfc6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h @@ -197,7 +197,7 @@ namespace AzToolsFramework AZ::IO::PathView filePath, Prefab::InstanceOptionalReference instanceToParentUnder) override; Prefab::InstanceOptionalReference GetRootPrefabInstance() override; - + const AZStd::vector>& GetPlayInEditorAssetData() override; ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplateInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplateInterface.h index c2ddbcf24f..c9b4b5acc3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplateInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplateInterface.h @@ -47,8 +47,13 @@ namespace AzToolsFramework virtual void AppendEntityAliasToPatchPaths(PrefabDom& providedPatch, const AZ::EntityId& entityId) = 0; - //! Updates the template links (updating instances) for the given templateId using the providedPatch - virtual bool PatchTemplate(PrefabDomValue& providedPatch, TemplateId templateId) = 0; + //! Updates the template links (updating instances) for the given template and triggers propagation on its instances. + //! @param providedPatch The patch to apply to the template. + //! @param templateId The id of the template to update. + //! @param instanceToExclude An optional reference to an instance of the template being updated that should not be refreshes as part of propagation. + //! Defaults to nullopt, which means that all instances will be refreshed. + //! @return True if the template was patched correctly, false if the operation failed. + virtual bool PatchTemplate(PrefabDomValue& providedPatch, TemplateId templateId, InstanceOptionalReference instanceToExclude = AZStd::nullopt) = 0; virtual void ApplyPatchesToInstance(const AZ::EntityId& entityId, PrefabDom& patches, const Instance& instanceToAddPatches) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index 6d3ddedd51..9fb6293b74 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -172,7 +172,7 @@ namespace AzToolsFramework } } - bool InstanceToTemplatePropagator::PatchTemplate(PrefabDomValue& providedPatch, TemplateId templateId) + bool InstanceToTemplatePropagator::PatchTemplate(PrefabDomValue& providedPatch, TemplateId templateId, InstanceOptionalReference instanceToExclude) { PrefabDom& templateDomReference = m_prefabSystemComponentInterface->FindTemplateDom(templateId); @@ -184,7 +184,7 @@ namespace AzToolsFramework if (result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success) { m_prefabSystemComponentInterface->SetTemplateDirtyFlag(templateId, true); - m_prefabSystemComponentInterface->PropagateTemplateChanges(templateId); + m_prefabSystemComponentInterface->PropagateTemplateChanges(templateId, instanceToExclude); return true; } else diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h index 9a6aad8ac1..358494091d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h @@ -37,7 +37,7 @@ namespace AzToolsFramework InstanceOptionalReference GetTopMostInstanceInHierarchy(AZ::EntityId entityId); - bool PatchTemplate(PrefabDomValue& providedPatch, TemplateId templateId) override; + bool PatchTemplate(PrefabDomValue& providedPatch, TemplateId templateId, InstanceOptionalReference instanceToExclude = AZStd::nullopt) override; void ApplyPatchesToInstance(const AZ::EntityId& entityId, PrefabDom& patches, const Instance& instanceToAddPatches) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.cpp index 6194adf784..b7a81a7f0c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.cpp @@ -56,7 +56,7 @@ namespace AzToolsFramework AZ::Interface::Unregister(this); } - void InstanceUpdateExecutor::AddTemplateInstancesToQueue(TemplateId instanceTemplateId) + void InstanceUpdateExecutor::AddTemplateInstancesToQueue(TemplateId instanceTemplateId, InstanceOptionalReference instanceToExclude) { auto findInstancesResult = m_templateInstanceMapperInterface->FindInstancesOwnedByTemplate(instanceTemplateId); @@ -70,9 +70,18 @@ namespace AzToolsFramework return; } + Instance* instanceToExcludePtr = nullptr; + if (instanceToExclude.has_value()) + { + instanceToExcludePtr = &(instanceToExclude->get()); + } + for (auto instance : findInstancesResult->get()) { - m_instancesUpdateQueue.emplace_back(instance); + if (instance != instanceToExcludePtr) + { + m_instancesUpdateQueue.emplace_back(instance); + } } } @@ -103,7 +112,7 @@ namespace AzToolsFramework EntityIdList selectedEntityIds; ToolsApplicationRequestBus::BroadcastResult(selectedEntityIds, &ToolsApplicationRequests::GetSelectedEntities); - ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, EntityIdList()); + PrefabDom instanceDomFromRootDocument; // Process all instances in the queue, capped to the batch size. // Even though we potentially initialized the batch size to the queue, it's possible for the queue size to shrink @@ -148,13 +157,62 @@ namespace AzToolsFramework continue; } - Template& currentTemplate = currentTemplateReference->get(); Instance::EntityList newEntities; - if (PrefabDomUtils::LoadInstanceFromPrefabDom(*instanceToUpdate, newEntities, currentTemplate.GetPrefabDom())) + + // Climb up to the root of the instance hierarchy from this instance + InstanceOptionalConstReference rootInstance = *instanceToUpdate; + AZStd::vector pathOfInstances; + + while (rootInstance->get().GetParentInstance() != AZStd::nullopt) { - // If a link was created for a nested instance before the changes were propagated, - // then we associate it correctly here - instanceToUpdate->GetNestedInstances([&](AZStd::unique_ptr& nestedInstance) { + pathOfInstances.emplace_back(rootInstance); + rootInstance = rootInstance->get().GetParentInstance(); + } + + AZStd::string aliasPathResult = ""; + for (auto instanceIter = pathOfInstances.rbegin(); instanceIter != pathOfInstances.rend(); ++instanceIter) + { + aliasPathResult.append("/Instances/"); + aliasPathResult.append((*instanceIter)->get().GetInstanceAlias()); + } + + PrefabDomPath rootPrefabDomPath(aliasPathResult.c_str()); + + PrefabDom& rootPrefabTemplateDom = + m_prefabSystemComponentInterface->FindTemplateDom(rootInstance->get().GetTemplateId()); + + auto instanceDomFromRootValue = rootPrefabDomPath.Get(rootPrefabTemplateDom); + if (!instanceDomFromRootValue) + { + AZ_Assert( + false, + "InstanceUpdateExecutor::UpdateTemplateInstancesInQueue - " + "Could not load Instance DOM from the top level ancestor's DOM."); + + isUpdateSuccessful = false; + continue; + } + + PrefabDomValueReference instanceDomFromRoot = *instanceDomFromRootValue; + if (!instanceDomFromRoot.has_value()) + { + AZ_Assert( + false, + "InstanceUpdateExecutor::UpdateTemplateInstancesInQueue - " + "Could not load Instance DOM from the top level ancestor's DOM."); + + isUpdateSuccessful = false; + continue; + } + + // If a link was created for a nested instance before the changes were propagated, + // then we associate it correctly here + instanceDomFromRootDocument.CopyFrom(instanceDomFromRoot->get(), instanceDomFromRootDocument.GetAllocator()); + if (PrefabDomUtils::LoadInstanceFromPrefabDom(*instanceToUpdate, newEntities, instanceDomFromRootDocument)) + { + Template& currentTemplate = currentTemplateReference->get(); + instanceToUpdate->GetNestedInstances([&](AZStd::unique_ptr& nestedInstance) + { if (nestedInstance->GetLinkId() != InvalidLinkId) { return; @@ -179,22 +237,11 @@ namespace AzToolsFramework AzToolsFramework::EditorEntityContextRequestBus::Broadcast( &AzToolsFramework::EditorEntityContextRequests::HandleEntitiesAdded, newEntities); } - else - { - AZ_Error( - "Prefab", false, - "InstanceUpdateExecutor::UpdateTemplateInstancesInQueue - " - "Could not load Instance from Prefab DOM of Template with Id '%llu' on file path '%s'.", - currentTemplateId, currentTemplate.GetFilePath().c_str()); - - isUpdateSuccessful = false; - } } - for (auto entityIdIterator = selectedEntityIds.begin(); entityIdIterator != selectedEntityIds.end(); entityIdIterator++) { - // Since entities get recreated during propagation, we need to check whether the entities correspoding to the list - // of selected entity ids are present or not. + // Since entities get recreated during propagation, we need to check whether the entities + // corresponding to the list of selected entity ids are present or not. AZ::Entity* entity = GetEntityById(*entityIdIterator); if (entity == nullptr) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.h index fa13c34b98..a3fdd019c2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutor.h @@ -35,7 +35,7 @@ namespace AzToolsFramework explicit InstanceUpdateExecutor(int instanceCountToUpdateInBatch = 0); - void AddTemplateInstancesToQueue(TemplateId instanceTemplateId) override; + void AddTemplateInstancesToQueue(TemplateId instanceTemplateId, InstanceOptionalReference instanceToExclude = AZStd::nullopt) override; bool UpdateTemplateInstancesInQueue() override; virtual void RemoveTemplateInstanceFromQueue(const Instance* instance) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutorInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutorInterface.h index d794c4929d..2454a995cf 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutorInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceUpdateExecutorInterface.h @@ -27,7 +27,7 @@ namespace AzToolsFramework virtual ~InstanceUpdateExecutorInterface() = default; // Add all Instances of Template with given Id into a queue for updating them later. - virtual void AddTemplateInstancesToQueue(TemplateId instanceTemplateId) = 0; + virtual void AddTemplateInstancesToQueue(TemplateId instanceTemplateId, InstanceOptionalReference instanceToExclude = AZStd::nullopt) = 0; // Update Instances in the waiting queue. virtual bool UpdateTemplateInstancesInQueue() = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 4656dcf48f..fcdbc5ce07 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -242,11 +242,13 @@ namespace AzToolsFramework m_instanceToTemplateInterface->GenerateDomForEntity(containerAfterReset, *containerEntity); // Update the state of the entity - PrefabUndoEntityUpdate* state = aznew PrefabUndoEntityUpdate(AZStd::to_string(static_cast(containerEntityId))); - state->SetParent(undoBatch.GetUndoBatch()); - state->Capture(containerBeforeReset, containerAfterReset, containerEntityId); + auto templateId = instanceToCreate->get().GetTemplateId(); - state->Redo(); + PrefabDom transformPatch; + m_instanceToTemplateInterface->GeneratePatch(transformPatch, containerBeforeReset, containerAfterReset); + m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(transformPatch, containerEntityId); + + m_instanceToTemplateInterface->PatchTemplate(transformPatch, templateId); } // This clears any entities marked as dirty due to reparenting of entities during the process of creating a prefab. @@ -661,12 +663,12 @@ namespace AzToolsFramework else { Internal_HandleContainerOverride( - parentUndoBatch, entityId, patch, owningInstance->get().GetLinkId()); + parentUndoBatch, entityId, patch, owningInstance->get().GetLinkId(), owningInstance->get().GetParentInstance()); } } else { - Internal_HandleEntityChange(parentUndoBatch, entityId, beforeState, afterState); + Internal_HandleEntityChange(parentUndoBatch, entityId, beforeState, afterState, owningInstance); if (isNewParentOwnedByDifferentInstance) { @@ -679,25 +681,27 @@ namespace AzToolsFramework } void PrefabPublicHandler::Internal_HandleContainerOverride( - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, const PrefabDom& patch, const LinkId linkId) + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, const PrefabDom& patch, + const LinkId linkId, InstanceOptionalReference parentInstance) { // Save these changes as patches to the link PrefabUndoLinkUpdate* linkUpdate = aznew PrefabUndoLinkUpdate(AZStd::to_string(static_cast(entityId))); linkUpdate->SetParent(undoBatch); linkUpdate->Capture(patch, linkId); - linkUpdate->Redo(); + linkUpdate->Redo(parentInstance); } void PrefabPublicHandler::Internal_HandleEntityChange( - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, PrefabDom& beforeState, PrefabDom& afterState) + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, PrefabDom& beforeState, + PrefabDom& afterState, InstanceOptionalReference instance) { // Update the state of the entity PrefabUndoEntityUpdate* state = aznew PrefabUndoEntityUpdate(AZStd::to_string(static_cast(entityId))); state->SetParent(undoBatch); state->Capture(beforeState, afterState, entityId); - state->Redo(); + state->Redo(instance); } void PrefabPublicHandler::Internal_HandleInstanceChange( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 167791d1c1..f3d778d8de 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -162,9 +162,11 @@ namespace AzToolsFramework InstanceOptionalConstReference instance, const AZStd::unordered_set& templateSourcePaths); static void Internal_HandleContainerOverride( - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, const PrefabDom& patch, const LinkId linkId); + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, const PrefabDom& patch, + const LinkId linkId, InstanceOptionalReference parentInstance = AZStd::nullopt); static void Internal_HandleEntityChange( - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, PrefabDom& beforeState, PrefabDom& afterState); + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId entityId, PrefabDom& beforeState, + PrefabDom& afterState, InstanceOptionalReference instance = AZStd::nullopt); void Internal_HandleInstanceChange(UndoSystem::URSequencePoint* undoBatch, AZ::Entity* entity, AZ::EntityId beforeParentId, AZ::EntityId afterParentId); void UpdateLinkPatchesWithNewEntityAliases( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index 5f5564b4e1..ab77d53283 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -141,8 +141,10 @@ namespace AzToolsFramework return newInstance; } - void PrefabSystemComponent::PropagateTemplateChanges(TemplateId templateId) + void PrefabSystemComponent::PropagateTemplateChanges(TemplateId templateId, InstanceOptionalReference instanceToExclude) { + UpdatePrefabInstances(templateId, instanceToExclude); + auto templateIdToLinkIdsIterator = m_templateToLinkIdsMap.find(templateId); if (templateIdToLinkIdsIterator != m_templateToLinkIdsMap.end()) { @@ -153,10 +155,6 @@ namespace AzToolsFramework templateIdToLinkIdsIterator->second.end())); UpdateLinkedInstances(linkIdsToUpdateQueue); } - else - { - UpdatePrefabInstances(templateId); - } } void PrefabSystemComponent::UpdatePrefabTemplate(TemplateId templateId, const PrefabDom& updatedDom) @@ -174,9 +172,9 @@ namespace AzToolsFramework } } - void PrefabSystemComponent::UpdatePrefabInstances(const TemplateId& templateId) + void PrefabSystemComponent::UpdatePrefabInstances(const TemplateId& templateId, InstanceOptionalReference instanceToExclude) { - m_instanceUpdateExecutor.AddTemplateInstancesToQueue(templateId); + m_instanceUpdateExecutor.AddTemplateInstancesToQueue(templateId, instanceToExclude); } void PrefabSystemComponent::UpdateLinkedInstances(AZStd::queue& linkIdsQueue) @@ -250,8 +248,6 @@ namespace AzToolsFramework if (targetTemplateIdToLinkIdMap[targetTemplateId].first.empty() && targetTemplateIdToLinkIdMap[targetTemplateId].second) { - UpdatePrefabInstances(targetTemplateId); - auto templateToLinkIter = m_templateToLinkIdsMap.find(targetTemplateId); if (templateToLinkIter != m_templateToLinkIdsMap.end()) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h index 0a9a450f64..a5170b8eef 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h @@ -215,14 +215,14 @@ namespace AzToolsFramework */ void UpdatePrefabTemplate(TemplateId templateId, const PrefabDom& updatedDom) override; - void PropagateTemplateChanges(TemplateId templateId) override; + void PropagateTemplateChanges(TemplateId templateId, InstanceOptionalReference instanceToExclude = AZStd::nullopt) override; /** * Updates all Instances owned by a Template. * * @param templateId The id of the Template owning Instances to update. */ - void UpdatePrefabInstances(const TemplateId& templateId); + void UpdatePrefabInstances(const TemplateId& templateId, InstanceOptionalReference instanceToExclude = AZStd::nullopt); private: AZ_DISABLE_COPY_MOVE(PrefabSystemComponent); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h index f47941254a..8daf4e731b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h @@ -56,7 +56,7 @@ namespace AzToolsFramework virtual PrefabDom& FindTemplateDom(TemplateId templateId) = 0; virtual void UpdatePrefabTemplate(TemplateId templateId, const PrefabDom& updatedDom) = 0; - virtual void PropagateTemplateChanges(TemplateId templateId) = 0; + virtual void PropagateTemplateChanges(TemplateId templateId, InstanceOptionalReference instanceToExclude = AZStd::nullopt) = 0; virtual AZStd::unique_ptr InstantiatePrefab(AZ::IO::PathView filePath) = 0; virtual AZStd::unique_ptr InstantiatePrefab(const TemplateId& templateId) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index aadcdcdea0..d0b3426495 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -70,10 +70,10 @@ namespace AzToolsFramework const AZ::EntityId& entityId) { //get the entity alias for future undo/redo - InstanceOptionalReference instanceOptionalReference = m_instanceEntityMapperInterface->FindOwningInstance(entityId); - AZ_Error("Prefab", instanceOptionalReference, + auto instanceReference = m_instanceEntityMapperInterface->FindOwningInstance(entityId); + AZ_Error("Prefab", instanceReference, "Failed to find an owning instance for the entity with id %llu.", static_cast(entityId)); - Instance& instance = instanceOptionalReference->get(); + Instance& instance = instanceReference->get(); m_templateId = instance.GetTemplateId(); m_entityAlias = (instance.GetEntityAlias(entityId)).value(); @@ -106,6 +106,17 @@ namespace AzToolsFramework m_templateId); } + void PrefabUndoEntityUpdate::Redo(InstanceOptionalReference instanceToExclude) + { + [[maybe_unused]] bool isPatchApplicationSuccessful = + m_instanceToTemplateInterface->PatchTemplate(m_redoPatch, m_templateId, instanceToExclude); + + AZ_Error( + "Prefab", isPatchApplicationSuccessful, + "Applying the patch on the entity with alias '%s' in template with id '%llu' was unsuccessful", m_entityAlias.c_str(), + m_templateId); + } + //PrefabInstanceLinkUndo PrefabUndoInstanceLink::PrefabUndoInstanceLink(const AZStd::string& undoOperationName) : PrefabUndoBase(undoOperationName) @@ -290,7 +301,12 @@ namespace AzToolsFramework UpdateLink(m_linkDomNext); } - void PrefabUndoLinkUpdate::UpdateLink(PrefabDom& linkDom) + void PrefabUndoLinkUpdate::Redo(InstanceOptionalReference instanceToExclude) + { + UpdateLink(m_linkDomNext, instanceToExclude); + } + + void PrefabUndoLinkUpdate::UpdateLink(PrefabDom& linkDom, InstanceOptionalReference instanceToExclude) { LinkReference link = m_prefabSystemComponentInterface->FindLink(m_linkId); @@ -304,7 +320,7 @@ namespace AzToolsFramework //propagate the link changes link->get().UpdateTarget(); - m_prefabSystemComponentInterface->PropagateTemplateChanges(link->get().GetTargetTemplateId()); + m_prefabSystemComponentInterface->PropagateTemplateChanges(link->get().GetTargetTemplateId(), instanceToExclude); //mark as dirty m_prefabSystemComponentInterface->SetTemplateDirtyFlag(link->get().GetTargetTemplateId(), true); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h index 33d9e5ad33..7ae677571a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h @@ -71,11 +71,12 @@ namespace AzToolsFramework void Capture( PrefabDom& initialState, - PrefabDom& endState, - const AZ::EntityId& entity); + PrefabDom& endState, const AZ::EntityId& entity); void Undo() override; void Redo() override; + //! Overload to allow to apply the change, but prevent instanceToExclude from being refreshed. + void Redo(InstanceOptionalReference instanceToExclude); private: InstanceEntityMapperInterface* m_instanceEntityMapperInterface = nullptr; @@ -139,9 +140,11 @@ namespace AzToolsFramework void Undo() override; void Redo() override; + //! Overload to allow to apply the change, but prevent instanceToExclude from being refreshed. + void Redo(InstanceOptionalReference instanceToExclude); private: - void UpdateLink(PrefabDom& linkDom); + void UpdateLink(PrefabDom& linkDom, InstanceOptionalReference instanceToExclude = AZStd::nullopt); LinkId m_linkId; PrefabDom m_linkDomNext; //data for delete/update diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabEntityAliasTests.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabEntityAliasTests.cpp index 0cf39a3572..458625fa3f 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabEntityAliasTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabEntityAliasTests.cpp @@ -242,6 +242,7 @@ namespace UnitTest // Patch the nested prefab to reference an entity in its parent ASSERT_TRUE(m_instanceToTemplateInterface->PatchEntityInTemplate(patch, newEntity->GetId())); + m_instanceUpdateExecutorInterface->AddTemplateInstancesToQueue(rootInstance->GetTemplateId()); m_instanceUpdateExecutorInterface->UpdateTemplateInstancesInQueue(); // Using the aliases we saved grab the updated entities so we can verify the entity reference is still preserved From dd95d2b02e4a65c460de95f004950d426d742330 Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Tue, 8 Jun 2021 19:44:33 +0100 Subject: [PATCH 587/811] ensure brute force ray intersection works (#1170) * ensure brute force ray intersection works in the same space as kd-tree intersection * add additional tests for ray casts against meshes using brute force approach * update api and add some additional test cases * comment tidy-up and other small updates/fixes for ray intersection code * fix issue with values at the end of a ray --- Gems/Atom/RPI/Code/CMakeLists.txt | 1 + .../Include/Atom/RPI.Public/Model/Model.h | 33 +- .../Atom/RPI.Reflect/Model/ModelAsset.h | 24 +- .../Code/Source/RPI.Public/Model/Model.cpp | 21 +- .../Source/RPI.Reflect/Model/ModelAsset.cpp | 51 ++-- .../Source/RPI.Reflect/Model/ModelKdTree.cpp | 6 +- Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp | 286 ++++++++++++------ 7 files changed, 279 insertions(+), 143 deletions(-) diff --git a/Gems/Atom/RPI/Code/CMakeLists.txt b/Gems/Atom/RPI/Code/CMakeLists.txt index 2898967add..8a2684347e 100644 --- a/Gems/Atom/RPI/Code/CMakeLists.txt +++ b/Gems/Atom/RPI/Code/CMakeLists.txt @@ -150,6 +150,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) PRIVATE AZ::AtomCore AZ::AzTest + AZ::AzTestShared AZ::AzFramework AZ::AzToolsFramework Legacy::CryCommon diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/Model.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/Model.h index 35af200759..514e3e37a5 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/Model.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/Model.h @@ -61,12 +61,13 @@ namespace AZ //! Important: only to be used in the Editor, it may kick off a job to calculate spatial information. //! [GFX TODO][ATOM-4343 Bake mesh spatial during AP processing] //! - //! @param rayStart position where the ray starts - //! @param dir direction where the ray ends (does not have to be unit length) - //! @param distanceFactor if an intersection is detected, this will be set such that distanceFactor * dir.length == distance to intersection - //! @param normal if an intersection is detected, this will be set to the normal at the point of intersection - //! @return true if the ray intersects the mesh - bool LocalRayIntersection(const AZ::Vector3& rayStart, const AZ::Vector3& dir, float& distanceFactor, AZ::Vector3& normal) const; + //! @param rayStart The starting point of the ray. + //! @param rayDir The direction and length of the ray (magnitude is encoded in the direction). + //! @param[out] distanceNormalized If an intersection is found, will be set to the normalized distance of the intersection + //! (in the range 0.0-1.0) - to calculate the actual distance, multiply distanceNormalized by the magnitude of rayDir. + //! @param[out] normal If an intersection is found, will be set to the normal at the point of collision. + //! @return True if the ray intersects the mesh. + bool LocalRayIntersection(const AZ::Vector3& rayStart, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const; //! Checks a ray for intersection against this model, where the ray is in a different coordinate space. //! Important: only to be used in the Editor, it may kick off a job to calculate spatial information. @@ -74,13 +75,19 @@ namespace AZ //! //! @param modelTransform a transform that puts the model into the ray's coordinate space //! @param nonUniformScale Non-uniform scale applied in the model's local frame. - //! @param rayStart position where the ray starts - //! @param dir direction where the ray ends (does not have to be unit length) - //! @param distanceFactor if an intersection is detected, this will be set such that distanceFactor * dir.length == distance to intersection - //! @param normal if an intersection is detected, this will be set to the normal at the point of intersection - //! @return true if the ray intersects the mesh - bool RayIntersection(const AZ::Transform& modelTransform, const AZ::Vector3& nonUniformScale, const AZ::Vector3& rayStart, - const AZ::Vector3& dir, float& distanceFactor, AZ::Vector3& normal) const; + //! @param rayStart The starting point of the ray. + //! @param rayDir The direction and length of the ray (magnitude is encoded in the direction). + //! @param[out] distanceNormalized If an intersection is found, will be set to the normalized distance of the intersection + //! (in the range 0.0-1.0) - to calculate the actual distance, multiply distanceNormalized by the magnitude of rayDir. + //! @param[out] normal If an intersection is found, will be set to the normal at the point of collision. + //! @return True if the ray intersects the mesh. + bool RayIntersection( + const AZ::Transform& modelTransform, + const AZ::Vector3& nonUniformScale, + const AZ::Vector3& rayStart, + const AZ::Vector3& rayDir, + float& distanceNormalized, + AZ::Vector3& normal) const; //! Get available UV names from the model and its lods. const AZStd::unordered_set& GetUvNames() const; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAsset.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAsset.h index 8a773dc29e..f3da349195 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAsset.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAsset.h @@ -63,12 +63,14 @@ namespace AZ //! Important: only to be used in the Editor, it may kick off a job to calculate spatial information. //! [GFX TODO][ATOM-4343 Bake mesh spatial information during AP processing] //! - //! @param rayStart position where the ray starts - //! @param dir direction where the ray ends (does not have to be unit length) - //! @param distance if an intersection is detected, this will be set such that distanceFactor * dir.length == distance to intersection - //! @param normal if an intersection is detected, this will be set to the normal at the point of collision - //! @return true if the ray intersects the mesh - virtual bool LocalRayIntersectionAgainstModel(const AZ::Vector3& rayStart, const AZ::Vector3& dir, float& distance, AZ::Vector3& normal) const; + //! @param rayStart The starting point of the ray. + //! @param rayDir The direction and length of the ray (magnitude is encoded in the direction). + //! @param[out] distanceNormalized If an intersection is found, will be set to the normalized distance of the intersection + //! (in the range 0.0-1.0) - to calculate the actual distance, multiply distanceNormalized by the magnitude of rayDir. + //! @param[out] normal If an intersection is found, will be set to the normal at the point of collision. + //! @return True if the ray intersects the mesh. + virtual bool LocalRayIntersectionAgainstModel( + const AZ::Vector3& rayStart, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const; private: void SetReady(); @@ -79,9 +81,15 @@ namespace AZ // mutable method void BuildKdTree() const; - bool BruteForceRayIntersect(const AZ::Vector3& rayStart, const AZ::Vector3& dir, float& distance, AZ::Vector3& normal) const; + bool BruteForceRayIntersect( + const AZ::Vector3& rayStart, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const; - bool LocalRayIntersectionAgainstMesh(const ModelLodAsset::Mesh& mesh, const AZ::Vector3& rayStart, const AZ::Vector3& dir, float& distance, AZ::Vector3& normal) const; + bool LocalRayIntersectionAgainstMesh( + const ModelLodAsset::Mesh& mesh, + const AZ::Vector3& rayStart, + const AZ::Vector3& rayDir, + float& distanceNormalized, + AZ::Vector3& normal) const; // Various model information used in raycasting AZ::Name m_positionName{ "POSITION" }; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp index 86477bf785..17ff2c64c8 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp @@ -137,12 +137,12 @@ namespace AZ return m_modelAsset; } - bool Model::LocalRayIntersection(const AZ::Vector3& rayStart, const AZ::Vector3& dir, float& distance, AZ::Vector3& normal) const + bool Model::LocalRayIntersection(const AZ::Vector3& rayStart, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const { AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); float start; float end; - const int result = Intersect::IntersectRayAABB2(rayStart, dir.GetReciprocal(), m_aabb, start, end); + const int result = Intersect::IntersectRayAABB2(rayStart, rayDir.GetReciprocal(), m_aabb, start, end); if (Intersect::ISECT_RAY_AABB_NONE != result) { if (ModelAsset* modelAssetPtr = m_modelAsset.Get()) @@ -151,7 +151,7 @@ namespace AZ AZ::Debug::Timer timer; timer.Stamp(); #endif - const bool hit = modelAssetPtr->LocalRayIntersectionAgainstModel(rayStart, dir, distance, normal); + const bool hit = modelAssetPtr->LocalRayIntersectionAgainstModel(rayStart, rayDir, distanceNormalized, normal); #if defined(AZ_RPI_PROFILE_RAYCASTING_AGAINST_MODELS) if (hit) { @@ -166,8 +166,12 @@ namespace AZ } bool Model::RayIntersection( - const AZ::Transform& modelTransform, const AZ::Vector3& nonUniformScale, const AZ::Vector3& rayStart, const AZ::Vector3& dir, - float& distanceFactor, AZ::Vector3& normal) const + const AZ::Transform& modelTransform, + const AZ::Vector3& nonUniformScale, + const AZ::Vector3& rayStart, + const AZ::Vector3& rayDir, + float& distanceNormalized, + AZ::Vector3& normal) const { AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); const AZ::Vector3 clampedScale = nonUniformScale.GetMax(AZ::Vector3(AZ::MinTransformScale)); @@ -175,12 +179,13 @@ namespace AZ const AZ::Transform inverseTM = modelTransform.GetInverse(); const AZ::Vector3 raySrcLocal = inverseTM.TransformPoint(rayStart) / clampedScale; - // Instead of just rotating 'dir' we need it to be scaled too, so that 'distanceFactor' will be in the target units rather than object local units. - const AZ::Vector3 rayDest = rayStart + dir; + // Instead of just rotating 'rayDir' we need it to be scaled too, so that 'distanceNormalized' will be in the target units rather + // than object local units. + const AZ::Vector3 rayDest = rayStart + rayDir; const AZ::Vector3 rayDestLocal = inverseTM.TransformPoint(rayDest) / clampedScale; const AZ::Vector3 rayDirLocal = rayDestLocal - raySrcLocal; - bool result = LocalRayIntersection(raySrcLocal, rayDirLocal, distanceFactor, normal); + const bool result = LocalRayIntersection(raySrcLocal, rayDirLocal, distanceNormalized, normal); normal = (normal * clampedScale).GetNormalized(); return result; } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp index 988d07e66d..52fda0f56b 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -75,7 +76,8 @@ namespace AZ m_status = Data::AssetData::AssetStatus::Ready; } - bool ModelAsset::LocalRayIntersectionAgainstModel(const AZ::Vector3& rayStart, const AZ::Vector3& dir, float& distance, AZ::Vector3& normal) const + bool ModelAsset::LocalRayIntersectionAgainstModel( + const AZ::Vector3& rayStart, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); @@ -85,7 +87,7 @@ namespace AZ m_modelTriangleCount = CalculateTriangleCount(); } - // check the total vertex count for this model and skip kdtree if the model is simple enough + // check the total vertex count for this model and skip kd-tree if the model is simple enough if (*m_modelTriangleCount > s_minimumModelTriangleCountToOptimize) { if (!m_kdTree) @@ -97,11 +99,11 @@ namespace AZ } else { - return m_kdTree->RayIntersection(rayStart, dir, distance, normal); + return m_kdTree->RayIntersection(rayStart, rayDir, distanceNormalized, normal); } } - return BruteForceRayIntersect(rayStart, dir, distance, normal); + return BruteForceRayIntersect(rayStart, rayDir, distanceNormalized, normal); } void ModelAsset::BuildKdTree() const @@ -136,7 +138,8 @@ namespace AZ } } - bool ModelAsset::BruteForceRayIntersect(const AZ::Vector3& rayStart, const AZ::Vector3& dir, float& distance, AZ::Vector3& normal) const + bool ModelAsset::BruteForceRayIntersect( + const AZ::Vector3& rayStart, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const { // brute force - check every triangle if (GetLodAssets().empty() == false) @@ -144,27 +147,27 @@ namespace AZ // intersect against the highest level of detail if (ModelLodAsset* loadAssetPtr = GetLodAssets()[0].Get()) { - float shortestDistance = std::numeric_limits::max(); bool anyHit = false; - AZ::Vector3 intersectionNormal; - + float shortestDistanceNormalized = AZStd::numeric_limits::max(); for (const ModelLodAsset::Mesh& mesh : loadAssetPtr->GetMeshes()) { - if (LocalRayIntersectionAgainstMesh(mesh, rayStart, dir, distance, intersectionNormal)) + float currentDistanceNormalized; + if (LocalRayIntersectionAgainstMesh(mesh, rayStart, rayDir, currentDistanceNormalized, intersectionNormal)) { anyHit = true; - if (distance < shortestDistance) + + if (currentDistanceNormalized < shortestDistanceNormalized) { normal = intersectionNormal; - shortestDistance = distance; + shortestDistanceNormalized = currentDistanceNormalized; } } } if (anyHit) { - distance = shortestDistance; + distanceNormalized = shortestDistanceNormalized; } return anyHit; @@ -174,7 +177,12 @@ namespace AZ return false; } - bool ModelAsset::LocalRayIntersectionAgainstMesh(const ModelLodAsset::Mesh& mesh, const AZ::Vector3& rayStart, const AZ::Vector3& dir, float& distance, AZ::Vector3& normal) const + bool ModelAsset::LocalRayIntersectionAgainstMesh( + const ModelLodAsset::Mesh& mesh, + const AZ::Vector3& rayStart, + const AZ::Vector3& rayDir, + float& distanceNormalized, + AZ::Vector3& normal) const { const BufferAssetView& indexBufferView = mesh.GetIndexBufferAssetView(); const AZStd::array_view& streamBufferList = mesh.GetStreamBufferInfoList(); @@ -217,14 +225,13 @@ namespace AZ AZStd::array_view indexRawBuffer = indexAssetViewPtr->GetBuffer(); RHI::BufferViewDescriptor indexRawDesc = indexAssetViewPtr->GetBufferViewDescriptor(); - float closestNormalizedDistance = 1.f; bool anyHit = false; - const AZ::Vector3 rayEnd = rayStart + dir * distance; + const AZ::Vector3 rayEnd = rayStart + rayDir; AZ::Vector3 a, b, c; AZ::Vector3 intersectionNormal; - float normalizedDistance = 1.f; + float shortestDistanceNormalized = AZStd::numeric_limits::max(); const AZ::u32* indexPtr = reinterpret_cast(indexRawBuffer.data()); for (uint32_t indexIter = 0; indexIter <= indexRawDesc.m_elementCount - 3; indexIter += 3, indexPtr += 3) { @@ -247,20 +254,22 @@ namespace AZ p = reinterpret_cast(&positionRawBuffer[index2 * positionElementSize]); c.Set(const_cast(p)); - if (AZ::Intersect::IntersectSegmentTriangleCCW(rayStart, rayEnd, a, b, c, intersectionNormal, normalizedDistance)) + float currentDistanceNormalized; + if (AZ::Intersect::IntersectSegmentTriangleCCW(rayStart, rayEnd, a, b, c, intersectionNormal, currentDistanceNormalized)) { - if (normalizedDistance < closestNormalizedDistance) + anyHit = true; + + if (currentDistanceNormalized < shortestDistanceNormalized) { normal = intersectionNormal; - closestNormalizedDistance = normalizedDistance; + shortestDistanceNormalized = currentDistanceNormalized; } - anyHit = true; } } if (anyHit) { - distance = closestNormalizedDistance * distance; + distanceNormalized = shortestDistanceNormalized; } return anyHit; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelKdTree.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelKdTree.cpp index bee489c2fd..2ee6d93df3 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelKdTree.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelKdTree.cpp @@ -208,10 +208,10 @@ namespace AZ bool ModelKdTree::RayIntersection( const AZ::Vector3& raySrc, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const { - float closestDistanceNormalized = AZStd::numeric_limits::max(); - if (RayIntersectionRecursively(m_pRootNode.get(), raySrc, rayDir, closestDistanceNormalized, normal)) + float shortestDistanceNormalized = AZStd::numeric_limits::max(); + if (RayIntersectionRecursively(m_pRootNode.get(), raySrc, rayDir, shortestDistanceNormalized, normal)) { - distanceNormalized = closestDistanceNormalized; + distanceNormalized = shortestDistanceNormalized; return true; } diff --git a/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp b/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp index 3ce17bee8b..f039240ee0 100644 --- a/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -568,7 +569,7 @@ namespace UnitTest ValidateModelAsset(serializedModelAsset.Get(), expectedModel); } - // Tests that if we try to set the name on a Model + // Tests that if we try to set the name on a Model // before calling Begin that it will fail. TEST_F(ModelTests, SetNameNoBegin) { @@ -581,7 +582,7 @@ namespace UnitTest creator.SetName("TestName"); } - // Tests that if we try to add a ModelLod to a Model + // Tests that if we try to add a ModelLod to a Model // before calling Begin that it will fail. TEST_F(ModelTests, AddLodNoBegin) { @@ -598,7 +599,7 @@ namespace UnitTest creator.AddLodAsset(AZStd::move(lod)); } - // Tests that if we create a ModelAsset without adding + // Tests that if we create a ModelAsset without adding // any ModelLodAssets that the creator will properly fail to produce an asset. TEST_F(ModelTests, CreateModelNoLods) { @@ -618,8 +619,8 @@ namespace UnitTest ASSERT_EQ(asset.Get(), nullptr); } - // Tests that if we call SetLodIndexBuffer without calling - // Begin first on the ModelLodAssetCreator that it + // Tests that if we call SetLodIndexBuffer without calling + // Begin first on the ModelLodAssetCreator that it // fails as expected. TEST_F(ModelTests, SetLodIndexBufferNoBegin) { @@ -633,8 +634,8 @@ namespace UnitTest creator.SetLodIndexBuffer(validIndexBuffer); } - // Tests that if we call AddLodStreamBuffer without calling - // Begin first on the ModelLodAssetCreator that it + // Tests that if we call AddLodStreamBuffer without calling + // Begin first on the ModelLodAssetCreator that it // fails as expected. TEST_F(ModelTests, AddLodStreamBufferNoBegin) { @@ -648,8 +649,8 @@ namespace UnitTest creator.AddLodStreamBuffer(validStreamBuffer); } - // Tests that if we call BeginMesh without calling - // Begin first on the ModelLodAssetCreator that it + // Tests that if we call BeginMesh without calling + // Begin first on the ModelLodAssetCreator that it // fails as expected. TEST_F(ModelTests, BeginMeshNoBegin) { @@ -662,13 +663,13 @@ namespace UnitTest } // Tests that if we try to set an AABB on a mesh - // without calling Begin or BeginMesh that it fails + // without calling Begin or BeginMesh that it fails // as expected. Also tests the case that Begin *is* // called but BeginMesh is not. TEST_F(ModelTests, SetAabbNoBeginNoBeginMesh) { using namespace AZ; - + RPI::ModelLodAssetCreator creator; AZ::Aabb aabb = AZ::Aabb::CreateCenterRadius(AZ::Vector3::CreateZero(), 1.0f); @@ -691,13 +692,13 @@ namespace UnitTest } // Tests that if we try to set the material id on a mesh - // without calling Begin or BeginMesh that it fails + // without calling Begin or BeginMesh that it fails // as expected. Also tests the case that Begin *is* // called but BeginMesh is not. TEST_F(ModelTests, SetMaterialIdNoBeginNoBeginMesh) { using namespace AZ; - + RPI::ModelLodAssetCreator creator; { @@ -715,7 +716,7 @@ namespace UnitTest } // Tests that if we try to set the index buffer on a mesh - // without calling Begin or BeginMesh that it fails + // without calling Begin or BeginMesh that it fails // as expected. Also tests the case that Begin *is* // called but BeginMesh is not. TEST_F(ModelTests, SetIndexBufferNoBeginNoBeginMesh) @@ -751,7 +752,7 @@ namespace UnitTest } // Tests that if we try to add a stream buffer on a mesh - // without calling Begin or BeginMesh that it fails + // without calling Begin or BeginMesh that it fails // as expected. Also tests the case that Begin *is* // called but BeginMesh is not. TEST_F(ModelTests, AddStreamBufferNoBeginNoBeginMesh) @@ -785,7 +786,7 @@ namespace UnitTest } } - // Tests that if we try to end the creation of a + // Tests that if we try to end the creation of a // ModelLodAsset that has no meshes that it fails // as expected. TEST_F(ModelTests, CreateLodNoMeshes) @@ -804,7 +805,7 @@ namespace UnitTest ASSERT_EQ(asset.Get(), nullptr); } - // Tests that validation still fails when expected + // Tests that validation still fails when expected // even after producing a valid mesh due to a missing // BeginMesh call TEST_F(ModelTests, SecondMeshFailureNoBeginMesh) @@ -862,8 +863,8 @@ namespace UnitTest ASSERT_EQ(asset->GetMeshes().size(), 1); } - // Tests that validation still fails when expected - // even after producing a valid mesh due to SetMeshX + // Tests that validation still fails when expected + // even after producing a valid mesh due to SetMeshX // calls coming after End TEST_F(ModelTests, SecondMeshAfterEnd) { @@ -907,7 +908,7 @@ namespace UnitTest AZ::Aabb aabb = AZ::Aabb::CreateCenterRadius(Vector3::CreateZero(), 1.0f); ErrorMessageFinder messageFinder("Begin() was not called", 6); - + creator.BeginMesh(); creator.SetMeshAabb(AZStd::move(aabb)); creator.SetMeshMaterialAsset(m_materialAsset); @@ -955,6 +956,20 @@ namespace UnitTest EXPECT_EQ(uvStreamTangentBitmask.GetFullTangentBitmask(), 0x70000F51); } + // + // +----+ + // / /| + // +----+ | + // | | + + // | |/ + // +----+ + // + static constexpr AZStd::array CubePositions = { -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, + -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f }; + static constexpr AZStd::array CubeIndices = { + uint32_t{ 0 }, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6, 0, 4, 2, 4, 6, 2, 1, 3, 5, 5, 3, 7, 0, 1, 4, 4, 1, 5, 2, 6, 3, 6, 7, 3, + }; + // This class creates a Model with one LOD, whose mesh contains 2 planes. Plane 1 is in the XY plane at Z=-0.5, and // plane 2 is in the XY plane at Z=0.5. The two planes each have 9 quads which have been triangulated. It only has // a position and index buffer. @@ -972,52 +987,75 @@ namespace UnitTest // *---*---*---* // \ / \ / \ / \ // *---*---*---* + static constexpr AZStd::array TwoSeparatedPlanesPositions{ + -1.0f, -0.333f, -0.5f, -0.333f, -1.0f, -0.5f, -0.333f, -0.333f, -0.5f, 0.333f, -0.333f, -0.5f, 1.0f, -1.0f, -0.5f, + 1.0f, -0.333f, -0.5f, 0.333f, -1.0f, -0.5f, 0.333f, 1.0f, -0.5f, 1.0f, 0.333f, -0.5f, 1.0f, 1.0f, -0.5f, + 0.333f, 0.333f, -0.5f, -0.333f, 1.0f, -0.5f, -0.333f, 0.333f, -0.5f, -1.0f, 1.0f, -0.5f, -1.0f, 0.333f, -0.5f, + -1.0f, -0.333f, 0.5f, -0.333f, -1.0f, 0.5f, -0.333f, -0.333f, 0.5f, 0.333f, -0.333f, 0.5f, 1.0f, -1.0f, 0.5f, + 1.0f, -0.333f, 0.5f, -0.333f, -0.333f, 0.5f, 0.333f, -1.0f, 0.5f, 0.333f, -0.333f, 0.5f, 0.333f, 1.0f, 0.5f, + 1.0f, 0.333f, 0.5f, 1.0f, 1.0f, 0.5f, 0.333f, 0.333f, 0.5f, 1.0f, -0.333f, 0.5f, -0.333f, 1.0f, 0.5f, + -0.333f, 0.333f, 0.5f, 0.333f, -0.333f, 0.5f, 0.333f, 0.333f, 0.5f, -1.0f, 1.0f, 0.5f, -0.333f, 0.333f, 0.5f, + -1.0f, 0.333f, 0.5f, -1.0f, -1.0f, -0.5f, -1.0f, -1.0f, 0.5f, 0.333f, -0.333f, 0.5f, 0.333f, -1.0f, 0.5f, + 1.0f, -1.0f, 0.5f, 0.333f, -1.0f, 0.5f, 0.333f, 0.333f, 0.5f, 0.333f, -0.333f, 0.5f, 1.0f, -0.333f, 0.5f, + -0.333f, 0.333f, 0.5f, -0.333f, -0.333f, 0.5f, 0.333f, -0.333f, 0.5f, + }; + // clang-format off + static constexpr AZStd::array TwoSeparatedPlanesIndices{ + uint32_t{ 0 }, 1, 2, 3, 4, 5, 2, 6, 3, 7, 8, 9, 10, 5, 8, 11, 10, 7, 12, 3, 10, 13, 12, 11, 14, 2, 12, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 25, 29, 27, 24, 30, 31, 32, 33, 34, 29, 35, 17, 34, + 0, 36, 1, 3, 6, 4, 2, 1, 6, 7, 10, 8, 10, 3, 5, 11, 12, 10, 12, 2, 3, 13, 14, 12, 14, 0, 2, + 15, 37, 16, 38, 39, 40, 17, 16, 41, 24, 27, 25, 42, 43, 44, 29, 34, 27, 45, 46, 47, 33, 35, 34, 35, 15, 17, + }; + // clang-format on + + // Ensure that the index buffer references all the positions in the position buffer + static constexpr inline auto minmaxElement = AZStd::minmax_element(begin(TwoSeparatedPlanesIndices), end(TwoSeparatedPlanesIndices)); + static_assert(*minmaxElement.second == (TwoSeparatedPlanesPositions.size() / 3) - 1); + template class TD; - class TwoSeparatedPlanesMesh + class TestMesh { public: - TwoSeparatedPlanesMesh() + TestMesh(const float* positions, size_t positionCount, const uint32_t* indices, size_t indicesCount) { - using namespace AZ; - - RPI::ModelLodAssetCreator lodCreator; - lodCreator.Begin(Data::AssetId(AZ::Uuid::CreateRandom())); + AZ::RPI::ModelLodAssetCreator lodCreator; + lodCreator.Begin(AZ::Data::AssetId(AZ::Uuid::CreateRandom())); lodCreator.BeginMesh(); - lodCreator.SetMeshAabb(Aabb::CreateFromMinMax({-1.0f, -1.0f, -0.5f}, {1.0f, 1.0f, 0.5f})); + lodCreator.SetMeshAabb(AZ::Aabb::CreateFromMinMax({-1.0f, -1.0f, -0.5f}, {1.0f, 1.0f, 0.5f})); lodCreator.SetMeshMaterialAsset( AZ::Data::Asset(AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 0), AZ::AzTypeInfo::Uuid(), "") ); { - AZ::Data::Asset indexBuffer = BuildTestBuffer(s_indexes.size(), sizeof(uint32_t)); - AZStd::copy(s_indexes.begin(), s_indexes.end(), reinterpret_cast(const_cast(indexBuffer->GetBuffer().data()))); + AZ::Data::Asset indexBuffer = BuildTestBuffer(indicesCount, sizeof(uint32_t)); + AZStd::copy(indices, indices + indicesCount, reinterpret_cast(const_cast(indexBuffer->GetBuffer().data()))); lodCreator.SetMeshIndexBuffer({ indexBuffer, - RHI::BufferViewDescriptor::CreateStructured(0, s_indexes.size(), sizeof(uint32_t)) + AZ::RHI::BufferViewDescriptor::CreateStructured(0, indicesCount, sizeof(uint32_t)) }); } { - AZ::Data::Asset positionBuffer = BuildTestBuffer(s_positions.size() / 3, sizeof(float) * 3); - AZStd::copy(s_positions.begin(), s_positions.end(), reinterpret_cast(const_cast(positionBuffer->GetBuffer().data()))); + AZ::Data::Asset positionBuffer = BuildTestBuffer(positionCount / 3, sizeof(float) * 3); + AZStd::copy(positions, positions + positionCount, reinterpret_cast(const_cast(positionBuffer->GetBuffer().data()))); lodCreator.AddMeshStreamBuffer( AZ::RHI::ShaderSemantic(AZ::Name("POSITION")), AZ::Name(), { positionBuffer, - RHI::BufferViewDescriptor::CreateStructured(0, s_positions.size() / 3, sizeof(float) * 3) + AZ::RHI::BufferViewDescriptor::CreateStructured(0, positionCount / 3, sizeof(float) * 3) } ); } lodCreator.EndMesh(); - Data::Asset lodAsset; + AZ::Data::Asset lodAsset; lodCreator.End(lodAsset); - RPI::ModelAssetCreator modelCreator; - modelCreator.Begin(Data::AssetId(AZ::Uuid::CreateRandom())); + AZ::RPI::ModelAssetCreator modelCreator; + modelCreator.Begin(AZ::Data::AssetId(AZ::Uuid::CreateRandom())); modelCreator.SetName("TestModel"); modelCreator.AddLodAsset(AZStd::move(lodAsset)); modelCreator.End(m_modelAsset); @@ -1030,40 +1068,20 @@ namespace UnitTest private: AZ::Data::Asset m_modelAsset; - - static constexpr AZStd::array s_positions{ - -1.0f, -0.333f, -0.5f, -0.333f, -1.0f, -0.5f, -0.333f, -0.333f, -0.5f, 0.333f, -0.333f, -0.5f, 1.0f, -1.0f, -0.5f, - 1.0f, -0.333f, -0.5f, 0.333f, -1.0f, -0.5f, 0.333f, 1.0f, -0.5f, 1.0f, 0.333f, -0.5f, 1.0f, 1.0f, -0.5f, - 0.333f, 0.333f, -0.5f, -0.333f, 1.0f, -0.5f, -0.333f, 0.333f, -0.5f, -1.0f, 1.0f, -0.5f, -1.0f, 0.333f, -0.5f, - -1.0f, -0.333f, 0.5f, -0.333f, -1.0f, 0.5f, -0.333f, -0.333f, 0.5f, 0.333f, -0.333f, 0.5f, 1.0f, -1.0f, 0.5f, - 1.0f, -0.333f, 0.5f, -0.333f, -0.333f, 0.5f, 0.333f, -1.0f, 0.5f, 0.333f, -0.333f, 0.5f, 0.333f, 1.0f, 0.5f, - 1.0f, 0.333f, 0.5f, 1.0f, 1.0f, 0.5f, 0.333f, 0.333f, 0.5f, 1.0f, -0.333f, 0.5f, -0.333f, 1.0f, 0.5f, - -0.333f, 0.333f, 0.5f, 0.333f, -0.333f, 0.5f, 0.333f, 0.333f, 0.5f, -1.0f, 1.0f, 0.5f, -0.333f, 0.333f, 0.5f, - -1.0f, 0.333f, 0.5f, -1.0f, -1.0f, -0.5f, -1.0f, -1.0f, 0.5f, 0.333f, -0.333f, 0.5f, 0.333f, -1.0f, 0.5f, - 1.0f, -1.0f, 0.5f, 0.333f, -1.0f, 0.5f, 0.333f, 0.333f, 0.5f, 0.333f, -0.333f, 0.5f, 1.0f, -0.333f, 0.5f, - -0.333f, 0.333f, 0.5f, -0.333f, -0.333f, 0.5f, 0.333f, -0.333f, 0.5f, - }; - static constexpr AZStd::array s_indexes{ - uint32_t{0}, 1, 2, 3, 4, 5, 2, 6, 3, 7, 8, 9, 10, 5, 8, 11, 10, 7, 12, 3, 10, 13, 12, 11, 14, 2, 12, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 25, 29, 27, 24, 30, 31, 32, 33, 34, 29, 35, 17, 34, - 0, 36, 1, 3, 6, 4, 2, 1, 6, 7, 10, 8, 10, 3, 5, 11, 12, 10, 12, 2, 3, 13, 14, 12, 14, 0, 2, - 15, 37, 16, 38, 39, 40, 17, 16, 41, 24, 27, 25, 42, 43, 44, 29, 34, 27, 45, 46, 47, 33, 35, 34, 35, 15, 17, - }; - - // Ensure that the index buffer references all the positions in the position buffer - static constexpr inline auto minmaxElement = AZStd::minmax_element(begin(s_indexes), end(s_indexes)); - static_assert(*minmaxElement.second == (s_positions.size() / 3) - 1); }; - struct KdTreeIntersectParams + struct IntersectParams { float xpos; float ypos; float zpos; + float xdir; + float ydir; + float zdir; float expectedDistance; bool expectedShouldIntersect; - friend std::ostream& operator<<(std::ostream& os, const KdTreeIntersectParams& param) + friend std::ostream& operator<<(std::ostream& os, const IntersectParams& param) { return os << "xpos:" << param.xpos @@ -1076,13 +1094,15 @@ namespace UnitTest class KdTreeIntersectsParameterizedFixture : public ModelTests - , public ::testing::WithParamInterface + , public ::testing::WithParamInterface { }; TEST_P(KdTreeIntersectsParameterizedFixture, KdTreeIntersects) { - TwoSeparatedPlanesMesh mesh; + TestMesh mesh( + TwoSeparatedPlanesPositions.data(), TwoSeparatedPlanesPositions.size(), TwoSeparatedPlanesIndices.data(), + TwoSeparatedPlanesIndices.size()); AZ::RPI::ModelKdTree kdTree; ASSERT_TRUE(kdTree.Build(mesh.GetModel().Get())); @@ -1092,38 +1112,40 @@ namespace UnitTest EXPECT_THAT( kdTree.RayIntersection( - AZ::Vector3(GetParam().xpos, GetParam().ypos, GetParam().zpos), AZ::Vector3::CreateAxisZ(-1.0f), distance, normal), + AZ::Vector3(GetParam().xpos, GetParam().ypos, GetParam().zpos), + AZ::Vector3(GetParam().xdir, GetParam().ydir, GetParam().zdir), distance, normal), testing::Eq(GetParam().expectedShouldIntersect)); EXPECT_THAT(distance, testing::FloatEq(GetParam().expectedDistance)); } - static constexpr inline AZStd::array intersectTestData{ - KdTreeIntersectParams{ -0.1f, 0.0f, 1.0f, 0.5f, true }, - KdTreeIntersectParams{ 0.0f, 0.0f, 1.0f, 0.5f, true }, - KdTreeIntersectParams{ 0.1f, 0.0f, 1.0f, 0.5f, true }, + static constexpr AZStd::array KdTreeIntersectTestData{ + IntersectParams{ -0.1f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.1f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, // Test the center of each triangle - KdTreeIntersectParams{-0.111f, -0.111f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{-0.111f, -0.778f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{-0.111f, 0.555f, 1.0f, 0.5f, true}, // Should intersect triangle with indices {29, 34, 27} and {11, 12, 10} - KdTreeIntersectParams{-0.555f, -0.555f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{-0.555f, 0.111f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{-0.555f, 0.778f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{-0.778f, -0.111f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{-0.778f, -0.778f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{-0.778f, 0.555f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{0.111f, -0.555f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{0.111f, 0.111f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{0.111f, 0.778f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{0.555f, -0.111f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{0.555f, -0.778f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{0.555f, 0.555f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{0.778f, -0.555f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{0.778f, 0.111f, 1.0f, 0.5f, true}, - KdTreeIntersectParams{0.778f, 0.778f, 1.0f, 0.5f, true}, + IntersectParams{ -0.111f, -0.111f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ -0.111f, -0.778f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ -0.111f, 0.555f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, + true }, // Should intersect triangle with indices {29, 34, 27} and {11, 12, 10} + IntersectParams{ -0.555f, -0.555f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ -0.555f, 0.111f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ -0.555f, 0.778f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ -0.778f, -0.111f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ -0.778f, -0.778f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ -0.778f, 0.555f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.111f, -0.555f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.111f, 0.111f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.111f, 0.778f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.555f, -0.111f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.555f, -0.778f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.555f, 0.555f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.778f, -0.555f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.778f, 0.111f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 0.778f, 0.778f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, true }, }; - INSTANTIATE_TEST_CASE_P(KdTreeIntersectsPlane, KdTreeIntersectsParameterizedFixture, ::testing::ValuesIn(intersectTestData)); + INSTANTIATE_TEST_CASE_P(KdTreeIntersectsPlane, KdTreeIntersectsParameterizedFixture, ::testing::ValuesIn(KdTreeIntersectTestData)); class KdTreeIntersectsFixture : public ModelTests @@ -1133,7 +1155,10 @@ namespace UnitTest { ModelTests::SetUp(); - m_mesh = AZStd::make_unique(); + m_mesh = AZStd::make_unique( + TwoSeparatedPlanesPositions.data(), TwoSeparatedPlanesPositions.size(), TwoSeparatedPlanesIndices.data(), + TwoSeparatedPlanesIndices.size()); + m_kdTree = AZStd::make_unique(); ASSERT_TRUE(m_kdTree->Build(m_mesh->GetModel().Get())); } @@ -1146,7 +1171,7 @@ namespace UnitTest ModelTests::TearDown(); } - AZStd::unique_ptr m_mesh; + AZStd::unique_ptr m_mesh; AZStd::unique_ptr m_kdTree; }; @@ -1154,7 +1179,7 @@ namespace UnitTest { float t = AZStd::numeric_limits::max(); AZ::Vector3 normal; - + constexpr float rayLength = 100.0f; EXPECT_THAT( m_kdTree->RayIntersection( @@ -1181,4 +1206,85 @@ namespace UnitTest EXPECT_THAT( m_kdTree->RayIntersection(AZ::Vector3::CreateAxisZ(5.0f), -AZ::Vector3::CreateAxisZ(), t, normal), testing::Eq(false)); } + + class BruteForceIntersectsParameterizedFixture + : public ModelTests + , public ::testing::WithParamInterface + { + }; + + TEST_P(BruteForceIntersectsParameterizedFixture, BruteForceIntersectsCube) + { + TestMesh mesh(CubePositions.data(), CubePositions.size(), CubeIndices.data(), CubeIndices.size()); + + float distance = AZStd::numeric_limits::max(); + AZ::Vector3 normal; + + EXPECT_THAT( + mesh.GetModel()->LocalRayIntersectionAgainstModel( + AZ::Vector3(GetParam().xpos, GetParam().ypos, GetParam().zpos), + AZ::Vector3(GetParam().xdir, GetParam().ydir, GetParam().zdir), distance, normal), + testing::Eq(GetParam().expectedShouldIntersect)); + EXPECT_THAT(distance, testing::FloatEq(GetParam().expectedDistance)); + } + + static constexpr AZStd::array BruteForceIntersectTestData{ + IntersectParams{ 5.0f, 0.0f, 5.0f, 0.0f, 0.0f, -1.0f, AZStd::numeric_limits::max(), false }, + IntersectParams{ 0.0f, 0.0f, 1.5f, 0.0f, 0.0f, -1.0f, 0.5f, true }, + IntersectParams{ 5.0f, 0.0f, 0.0f, -10.0f, 0.0f, 0.0f, 0.4f, true }, + IntersectParams{ -5.0f, 0.0f, 0.0f, 20.0f, 0.0f, 0.0f, 0.2f, true }, + IntersectParams{ 0.0f, -10.0f, 0.0f, 0.0f, 20.0f, 0.0f, 0.45f, true }, + IntersectParams{ 0.0f, 20.0f, 0.0f, 0.0f, -40.0f, 0.0f, 0.475f, true }, + IntersectParams{ 0.0f, 20.0f, 0.0f, 0.0f, -19.0f, 0.0f, 1.0f, true }, + }; + + INSTANTIATE_TEST_CASE_P( + BruteForceIntersects, BruteForceIntersectsParameterizedFixture, ::testing::ValuesIn(BruteForceIntersectTestData)); + + class BruteForceModelIntersectsFixture + : public ModelTests + { + public: + void SetUp() override + { + ModelTests::SetUp(); + m_mesh = AZStd::make_unique(CubePositions.data(), CubePositions.size(), CubeIndices.data(), CubeIndices.size()); + } + + void TearDown() override + { + m_mesh.reset(); + ModelTests::TearDown(); + } + + AZStd::unique_ptr m_mesh; + }; + + TEST_F(BruteForceModelIntersectsFixture, BruteForceIntersectionDetectedWithCube) + { + float t = 0.0f; + AZ::Vector3 normal; + + // firing down the negative z axis, positioned 5 units from cube (cube is 2x2x2 so intersection + // happens at 1 in z) + EXPECT_THAT( + m_mesh->GetModel()->LocalRayIntersectionAgainstModel( + AZ::Vector3::CreateAxisZ(5.0f), -AZ::Vector3::CreateAxisZ(10.0f), t, normal), + testing::Eq(true)); + EXPECT_THAT(t, testing::FloatEq(0.4f)); + } + + TEST_F(BruteForceModelIntersectsFixture, BruteForceIntersectionDetectedAndNormalSetAtEndOfRay) + { + float t = 0.0f; + AZ::Vector3 normal = AZ::Vector3::CreateOne(); // invalid starting normal + + // ensure the intersection happens right at the end of the ray + EXPECT_THAT( + m_mesh->GetModel()->LocalRayIntersectionAgainstModel( + AZ::Vector3::CreateAxisY(10.0f), -AZ::Vector3::CreateAxisY(9.0f), t, normal), + testing::Eq(true)); + EXPECT_THAT(t, testing::FloatEq(1.0f)); + EXPECT_THAT(normal, IsClose(AZ::Vector3::CreateAxisY())); + } } // namespace UnitTest From 6973d9c7a3c4593b66aadea908d8c097248f3c20 Mon Sep 17 00:00:00 2001 From: antonmic Date: Tue, 8 Jun 2021 12:03:58 -0700 Subject: [PATCH 588/811] Pass changes WIP: moved child pass creation to Build phase --- .../DisplayMapper/DisplayMapperPass.cpp | 68 ++++--------------- .../Source/LuxCore/LuxCoreTexturePass.cpp | 4 -- .../DepthOfFieldReadBackFocusDepthPass.cpp | 33 +++++---- .../DepthOfFieldReadBackFocusDepthPass.h | 1 + .../ReflectionScreenSpaceBlurPass.cpp | 8 +-- .../ReflectionScreenSpaceBlurPass.h | 3 +- .../Include/Atom/RPI.Public/Pass/ParentPass.h | 2 +- .../Code/Include/Atom/RPI.Public/Pass/Pass.h | 2 + .../Source/RPI.Public/Pass/ParentPass.cpp | 15 ++-- .../Pass/Specific/EnvironmentCubeMapPass.cpp | 4 -- .../Pass/Specific/SwapChainPass.cpp | 4 -- .../Code/Source/RPI.Public/RenderPipeline.cpp | 2 + 12 files changed, 49 insertions(+), 97 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp index b6fa0b5c41..f5b301ca5c 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/DisplayMapperPass.cpp @@ -46,8 +46,6 @@ namespace AZ DisplayMapperPass::DisplayMapperPass(const RPI::PassDescriptor& descriptor) : RPI::ParentPass(descriptor) { - m_flags.m_alreadyCreated = false; - AzFramework::NativeWindowHandle windowHandle = nullptr; AzFramework::WindowSystemRequestBus::BroadcastResult( windowHandle, @@ -61,8 +59,6 @@ namespace AZ { m_displayMapperConfigurationDescriptor = passData->m_config; } - - m_needToRebuildChildren = true; } DisplayMapperPass::~DisplayMapperPass() @@ -199,24 +195,14 @@ namespace AZ void DisplayMapperPass::FrameEndInternal() { GetDisplayMapperConfiguration(); - if (m_needToRebuildChildren) - { - ClearChildren(); - BuildGradingLutTemplate(); - CreateGradingAndAcesPasses(); - } ParentPass::FrameEndInternal(); } void DisplayMapperPass::CreateChildPassesInternal() { - if (m_needToRebuildChildren) - { - ClearChildren(); - BuildGradingLutTemplate(); - CreateGradingAndAcesPasses(); - } - ParentPass::CreateChildPassesInternal(); + ClearChildren(); + BuildGradingLutTemplate(); + CreateGradingAndAcesPasses(); } AZStd::shared_ptr CreatePassTemplateHelper( @@ -485,7 +471,6 @@ namespace AZ { AddChild(m_ldrGradingLookupTablePass); } - m_needToRebuildChildren = false; } void DisplayMapperPass::GetDisplayMapperConfiguration() @@ -513,7 +498,8 @@ namespace AZ desc.m_ldrColorGradingLut != m_displayMapperConfigurationDescriptor.m_ldrColorGradingLut || desc.m_acesParameterOverrides.m_overrideDefaults != m_displayMapperConfigurationDescriptor.m_acesParameterOverrides.m_overrideDefaults) { - m_needToRebuildChildren = true; + m_flags.m_createChildren = true; + QueueForBuild(); } m_displayMapperConfigurationDescriptor = desc; } @@ -527,41 +513,15 @@ namespace AZ void DisplayMapperPass::ClearChildren() { - if (m_acesOutputTransformPass) - { - RemoveChild(m_acesOutputTransformPass); - m_acesOutputTransformPass = nullptr; - } - if (m_bakeAcesOutputTransformLutPass) - { - RemoveChild(m_bakeAcesOutputTransformLutPass); - m_bakeAcesOutputTransformLutPass = nullptr; - } - if (m_acesOutputTransformLutPass) - { - RemoveChild(m_acesOutputTransformLutPass); - m_acesOutputTransformLutPass = nullptr; - } - if (m_displayMapperPassthroughPass) - { - RemoveChild(m_displayMapperPassthroughPass); - m_displayMapperPassthroughPass = nullptr; - } - if (m_displayMapperOnlyGammaCorrectionPass) - { - RemoveChild(m_displayMapperOnlyGammaCorrectionPass); - m_displayMapperOnlyGammaCorrectionPass = nullptr; - } - if (m_ldrGradingLookupTablePass) - { - RemoveChild(m_ldrGradingLookupTablePass); - m_ldrGradingLookupTablePass = nullptr; - } - if (m_outputTransformPass) - { - RemoveChild(m_outputTransformPass); - m_outputTransformPass = nullptr; - } + RemoveChildren(); + + m_acesOutputTransformPass = nullptr; + m_bakeAcesOutputTransformLutPass = nullptr; + m_acesOutputTransformLutPass = nullptr; + m_displayMapperPassthroughPass = nullptr; + m_displayMapperOnlyGammaCorrectionPass = nullptr; + m_ldrGradingLookupTablePass = nullptr; + m_outputTransformPass = nullptr; } } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp b/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp index 7708605e29..724511b355 100644 --- a/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreTexturePass.cpp @@ -28,8 +28,6 @@ namespace AZ LuxCoreTexturePass::LuxCoreTexturePass(const RPI::PassDescriptor& descriptor) : ParentPass(descriptor) { - m_flags.m_alreadyCreated = false; - RPI::PassSystemInterface* passSystem = RPI::PassSystemInterface::Get(); // Create render target pass @@ -41,8 +39,6 @@ namespace AZ // Create readback m_readback = AZStd::make_shared(AZ::RHI::ScopeId{ Uuid::CreateRandom().ToString() }); - - CreateChildPasses(); } LuxCoreTexturePass::~LuxCoreTexturePass() diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.cpp index c355b7c8a7..6050ac2b2e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.cpp @@ -34,18 +34,6 @@ namespace AZ DepthOfFieldReadBackFocusDepthPass::DepthOfFieldReadBackFocusDepthPass(const RPI::PassDescriptor& descriptor) : ParentPass(descriptor) { - RPI::PassSystemInterface* passSystem = RPI::PassSystemInterface::Get(); - - // Create read back pass - m_readbackPass = passSystem->CreatePass(AZ::Name("DepthOfFieldReadBackPass")); - AZ_Assert(m_readbackPass, "DepthOfFieldReadBackFocusDepthPass : read back pass is invalid"); - - AddChild(m_readbackPass); - - // Find GetDepth pass on template - auto pass = FindChildPass(Name("DepthOfFieldWriteFocusDepthFromGpu")); - m_getDepthPass = static_cast(pass.get()); - // Create buffer for read back focus depth. We append static counter to avoid name conflicts. RPI::CommonBufferDescriptor desc; desc.m_bufferName = "DepthOfFieldReadBackAutoFocusDepthBuffer"; @@ -55,9 +43,6 @@ namespace AZ desc.m_bufferData = nullptr; desc.m_elementFormat = RHI::Format::R32_FLOAT; m_buffer = RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc); - - m_getDepthPass->SetBufferRef(m_buffer); - m_readbackPass->SetBufferRef(m_buffer); } DepthOfFieldReadBackFocusDepthPass::~DepthOfFieldReadBackFocusDepthPass() @@ -85,6 +70,24 @@ namespace AZ } } + void DepthOfFieldReadBackFocusDepthPass::CreateChildPassesInternal() + { + RPI::PassSystemInterface* passSystem = RPI::PassSystemInterface::Get(); + + // Create read back pass + m_readbackPass = passSystem->CreatePass(AZ::Name("DepthOfFieldReadBackPass")); + AZ_Assert(m_readbackPass, "DepthOfFieldReadBackFocusDepthPass : read back pass is invalid"); + + AddChild(m_readbackPass); + + // Find GetDepth pass on template + auto pass = FindChildPass(Name("DepthOfFieldWriteFocusDepthFromGpu")); + m_getDepthPass = static_cast(pass.get()); + + m_getDepthPass->SetBufferRef(m_buffer); + m_readbackPass->SetBufferRef(m_buffer); + } + void DepthOfFieldReadBackFocusDepthPass::FrameBeginInternal(FramePrepareParams params) { RPI::Scene* scene = GetScene(); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.h index 75842fb67a..db29576d22 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldReadBackFocusDepthPass.h @@ -43,6 +43,7 @@ namespace AZ protected: // Pass behavior overrides... + void CreateChildPassesInternal() override; void FrameBeginInternal(FramePrepareParams params) override; private: diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp index 680d117b98..631ff803dd 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp @@ -47,7 +47,7 @@ namespace AZ RemoveChildren(); } - void ReflectionScreenSpaceBlurPass::CreateChildPasses(uint32_t numBlurMips) + void ReflectionScreenSpaceBlurPass::CreateChildPassesInternal() { RPI::PassSystemInterface* passSystem = RPI::PassSystemInterface::Get(); @@ -83,7 +83,7 @@ namespace AZ horizontalBlurChildDesc.m_passTemplate = blurHorizontalPassTemplate; // add child passes to perform the vertical and horizontal Gaussian blur for each roughness mip level - for (uint32_t mip = 0; mip < numBlurMips; ++mip) + for (uint32_t mip = 0; mip < m_numBlurMips; ++mip) { // create Vertical blur child passes { @@ -116,6 +116,7 @@ namespace AZ void ReflectionScreenSpaceBlurPass::BuildInternal() { RemoveChildren(); + m_flags.m_createChildren = true; Data::Instance pool = RPI::ImageSystemInterface::Get()->GetSystemAttachmentPool(); @@ -163,8 +164,7 @@ namespace AZ m_ownedAttachments.push_back(transientPassAttachment); } - // create child passes, one vertical and one horizontal blur per mip level - CreateChildPasses(mipLevels - 1); + m_numBlurMips = mipLevels - 1; // call ParentPass::BuildInternal() first to configure the slots and auto-add the empty bindings, // then we will assign attachments to the bindings diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h index f344fc8e9b..4a2ccce1d4 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h @@ -40,7 +40,7 @@ namespace AZ private: explicit ReflectionScreenSpaceBlurPass(const RPI::PassDescriptor& descriptor); - void CreateChildPasses(uint32_t numBlurMips); + void CreateChildPassesInternal() override; // Pass Overrides... void ResetInternal() override; @@ -50,6 +50,7 @@ namespace AZ AZStd::vector> m_horizontalBlurChildPasses; Data::Instance m_frameBufferImageAttachment; + uint32_t m_numBlurMips = 0; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h index ca7baf1a0f..727398040d 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h @@ -118,7 +118,7 @@ namespace AZ // Finds the pass in m_children and removes it void RemoveChild(Ptr pass); - // Orphans all children from clearing m_children. + // Orphans all children by clearing m_children. void RemoveChildren(); private: diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h index a184e8ed32..1cfd2e759e 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/Pass.h @@ -40,6 +40,7 @@ friend class PassSystem; \ friend class PassFactory; \ friend class ParentPass; \ + friend class RenderPipeline; \ friend class UnitTest::PassTests; \ namespace UnitTest @@ -394,6 +395,7 @@ namespace AZ uint64_t m_initialized : 1; uint64_t m_alreadyCreated : 1; + uint64_t m_createChildren : 1; // OLD SCHOOL uint64_t m_alreadyPrepared : 1; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp index 6b95a6e17a..e06ffca556 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/ParentPass.cpp @@ -40,7 +40,7 @@ namespace AZ ParentPass::ParentPass(const PassDescriptor& descriptor) : Pass(descriptor) { - CreateChildPasses(); + m_flags.m_createChildren = true; } ParentPass::~ParentPass() @@ -248,7 +248,7 @@ namespace AZ void ParentPass::CreateChildPasses() { - if (m_flags.m_alreadyCreated) + if (!m_flags.m_createChildren || m_flags.m_alreadyCreated) { return; } @@ -258,14 +258,7 @@ namespace AZ CreatePassesFromTemplate(); CreateChildPassesInternal(); - for (Ptr& child : m_children) - { - ParentPass* asParent = child->AsParent(); - if (asParent != nullptr) - { - asParent->CreateChildPasses(); - } - } + m_flags.m_createChildren = false; } void ParentPass::ResetInternal() @@ -278,6 +271,8 @@ namespace AZ void ParentPass::BuildInternal() { + CreateChildPasses(); + for (const Ptr& child : m_children) { child->Build(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp index be06343ab9..28a03de297 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp @@ -37,8 +37,6 @@ namespace AZ EnvironmentCubeMapPass::EnvironmentCubeMapPass(const PassDescriptor& passDescriptor) : ParentPass(passDescriptor) { - m_flags.m_alreadyCreated = false; - // load pass data const EnvironmentCubeMapPassData* passData = PassUtils::GetPassData(passDescriptor); if (passData == nullptr) @@ -88,8 +86,6 @@ namespace AZ AZ::Matrix4x4 viewToClipMatrix; MakePerspectiveFovMatrixRH(viewToClipMatrix, AZ::Constants::HalfPi, 1.0f, 0.1f, 100.0f, true); m_view->SetViewToClipMatrix(viewToClipMatrix); - - CreateChildPasses(); } EnvironmentCubeMapPass::~EnvironmentCubeMapPass() diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp index 45fb890e91..a7add17042 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/SwapChainPass.cpp @@ -26,8 +26,6 @@ namespace AZ , m_windowContext(windowContext) , m_childTemplateName(childTemplateName) { - m_flags.m_alreadyCreated = false; - PassSystemInterface* passSystem = PassSystemInterface::Get(); // Create child pass @@ -44,8 +42,6 @@ namespace AZ m_childPass = passSystem->CreatePassFromRequest(&childRequest); AZ_Assert(m_childPass, "SwapChain child pass is invalid: check your passs pipeline, run configuration and your AssetProcessor set project (project_path)"); - - CreateChildPasses(); AzFramework::WindowNotificationBus::Handler::BusConnect(m_windowContext->GetWindowHandle()); } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp index 86d76287bb..2c4c61f5aa 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp @@ -107,6 +107,8 @@ namespace AZ pipeline->m_originalRenderSettings = desc.m_renderSettings; pipeline->m_activeRenderSettings = desc.m_renderSettings; pipeline->m_rootPass->SetRenderPipeline(pipeline); + pipeline->m_rootPass->Build(); + pipeline->m_rootPass->Initialize(); pipeline->BuildPipelineViews(); } From fa55b495c4401b3ac626ec352e59e8a7107871c1 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Tue, 8 Jun 2021 13:36:27 -0700 Subject: [PATCH 589/811] Add handling for session provider ticket --- .../Session/ISessionHandlingRequests.h | 6 +- .../AutoGen/Multiplayer.AutoPackets.xml | 1 + .../ClientToServerConnectionData.cpp | 4 +- .../ClientToServerConnectionData.h | 6 +- .../ClientToServerConnectionData.inl | 5 ++ .../ServerToClientConnectionData.h | 3 + .../ServerToClientConnectionData.inl | 10 +++ .../Source/MultiplayerSystemComponent.cpp | 65 +++++++++++++------ 8 files changed, 75 insertions(+), 25 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h b/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h index 10c1d1cdd5..d55f38f65c 100644 --- a/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h +++ b/Code/Framework/AzFramework/AzFramework/Session/ISessionHandlingRequests.h @@ -46,7 +46,7 @@ namespace AzFramework }; //! ISessionHandlingClientRequests - //! Requests made to the client to manage their connection to a session + //! Requests made to the client to manage their membership in a session class ISessionHandlingClientRequests { public: @@ -87,11 +87,11 @@ namespace AzFramework // Retrieves the file location of a pem-encoded TLS certificate for Client to Server communication // @return If successful, returns the file location of TLS certificate file; if not successful, returns // empty string. - virtual AZStd::string GetExternalSessionCertificate() = 0; + virtual AZ::IO::Path GetExternalSessionCertificate() = 0; // Retrieves the file location of a pem-encoded TLS certificate for Server to Server communication // @return If successful, returns the file location of TLS certificate file; if not successful, returns // empty string. - virtual AZStd::string GetInternalSessionCertificate() = 0; + virtual AZ::IO::Path GetInternalSessionCertificate() = 0; }; } // namespace AzFramework diff --git a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml index 642832805d..ce8931107f 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml @@ -9,6 +9,7 @@ + diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp index ee308f6ed8..11207df27d 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp @@ -21,10 +21,12 @@ namespace Multiplayer ClientToServerConnectionData::ClientToServerConnectionData ( AzNetworking::IConnection* connection, - AzNetworking::IConnectionListener& connectionListener + AzNetworking::IConnectionListener& connectionListener, + AZStd::string providerTicket ) : m_connection(connection) , m_entityReplicationManager(*connection, connectionListener, EntityReplicationManager::Mode::LocalClientToRemoteServer) + , m_providerTicket(providerTicket) { m_entityReplicationManager.SetMaxRemoteEntitiesPendingCreationCount(cl_ClientMaxRemoteEntitiesPendingCreationCount); m_entityReplicationManager.SetEntityPendingRemovalMs(cl_ClientEntityReplicatorPendingRemovalTimeMs); diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h index 2e7be47842..52c5dea00d 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h @@ -24,7 +24,8 @@ namespace Multiplayer ClientToServerConnectionData ( AzNetworking::IConnection* connection, - AzNetworking::IConnectionListener& connectionListener + AzNetworking::IConnectionListener& connectionListener, + AZStd::string providerTicket = "" ); ~ClientToServerConnectionData() override; @@ -38,8 +39,11 @@ namespace Multiplayer void SetCanSendUpdates(bool canSendUpdates) override; //! @} + AZStd::string GetProviderTicket() const; + private: EntityReplicationManager m_entityReplicationManager; + AZStd::string m_providerTicket; AzNetworking::IConnection* m_connection = nullptr; bool m_canSendUpdates = true; }; diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.inl b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.inl index 6d4a332b6e..f23c8dd1d9 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.inl +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.inl @@ -21,4 +21,9 @@ namespace Multiplayer { m_canSendUpdates = canSendUpdates; } + + inline AZStd::string ClientToServerConnectionData::GetProviderTicket() const + { + return m_providerTicket; + } } diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h index faa11bc225..c171cdbe5d 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h @@ -41,6 +41,8 @@ namespace Multiplayer NetworkEntityHandle GetPrimaryPlayerEntity(); const NetworkEntityHandle& GetPrimaryPlayerEntity() const; + AZStd::string GetProviderTicket() const; + void SetProviderTicket(AZStd::string); private: void OnControlledEntityRemove(); @@ -51,6 +53,7 @@ namespace Multiplayer NetworkEntityHandle m_controlledEntity; EntityStopEvent::Handler m_controlledEntityRemovedHandler; EntityServerMigrationEvent::Handler m_controlledEntityMigrationHandler; + AZStd::string m_ticket; AzNetworking::IConnection* m_connection = nullptr; bool m_canSendUpdates = false; }; diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.inl b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.inl index 0a4215a363..0427936f00 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.inl +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.inl @@ -32,4 +32,14 @@ namespace Multiplayer { return m_controlledEntity; } + + inline AZStd::string ServerToClientConnectionData::GetProviderTicket() const + { + return m_ticket; + } + + inline void ServerToClientConnectionData::SetProviderTicket(AZStd::string ticket) + { + m_ticket = ticket; + } } diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 6f8569251f..d0d2c609b3 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -176,7 +176,13 @@ namespace Multiplayer INetworkInterface* networkInterface = AZ::Interface::Get()->RetrieveNetworkInterface(AZ::Name(MPNetworkInterfaceName)); const IpAddress ipAddress(config.m_ipAddress.c_str(), config.m_port, networkInterface->GetType()); - networkInterface->Connect(ipAddress); + ConnectionId connectionId = networkInterface->Connect(ipAddress); + + AzNetworking::IConnection* connection = networkInterface->GetConnectionSet().GetConnection(connectionId); + if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so + { + connection->SetUserData(new ClientToServerConnectionData(connection, *this, config.m_playerSessionId)); + } return true; } @@ -196,18 +202,23 @@ namespace Multiplayer bool MultiplayerSystemComponent::OnCreateSessionBegin(const AzFramework::SessionConfig& sessionConfig) { // Check if session manager has a certificate for us and pass it along if so - AZ::CVarFixedString externalCertPath = AZ::CVarFixedString(AZ::Interface::Get()->GetExternalSessionCertificate()); - if (!externalCertPath.empty()) + if (AZ::Interface::Get() != nullptr) { - AZ::CVarFixedString commandString = "net_SslExternalCertificateFile " + externalCertPath; - AZ::Interface::Get()->PerformCommand(commandString.c_str()); - } + AZ::CVarFixedString externalCertPath = AZ::CVarFixedString( + AZ::Interface::Get()->GetExternalSessionCertificate().c_str()); + if (!externalCertPath.empty()) + { + AZ::CVarFixedString commandString = "net_SslExternalCertificateFile " + externalCertPath; + AZ::Interface::Get()->PerformCommand(commandString.c_str()); + } - AZ::CVarFixedString internalCertPath = AZ::CVarFixedString(AZ::Interface::Get()->GetInternalSessionCertificate()); - if (!internalCertPath.empty()) - { - AZ::CVarFixedString commandString = "net_SslInternalCertificateFile " + internalCertPath; - AZ::Interface::Get()->PerformCommand(commandString.c_str()); + AZ::CVarFixedString internalCertPath = AZ::CVarFixedString( + AZ::Interface::Get()->GetInternalSessionCertificate().c_str()); + if (!internalCertPath.empty()) + { + AZ::CVarFixedString commandString = "net_SslInternalCertificateFile " + internalCertPath; + AZ::Interface::Get()->PerformCommand(commandString.c_str()); + } } Multiplayer::MultiplayerAgentType serverType = sv_isDedicated ? MultiplayerAgentType::DedicatedServer : MultiplayerAgentType::ClientServer; @@ -370,6 +381,17 @@ namespace Multiplayer { if (connection->SendReliablePacket(MultiplayerPackets::Accept(InvalidHostId, sv_map))) { + // Validate our session with the provider if any + if (AZ::Interface::Get() != nullptr) + { + AzFramework::PlayerConnectionConfig config; + config.m_playerConnectionId = aznumeric_cast(connection->GetConnectionId()); + config.m_playerSessionId = packet.GetTicket(); + AZ::Interface::Get()->ValidatePlayerJoinSession(config); + + reinterpret_cast(connection->GetUserData())->SetProviderTicket(packet.GetTicket().c_str()); + } + // Sync our console ConsoleReplicator consoleReplicator(connection); AZ::Interface::Get()->VisitRegisteredFunctors([&consoleReplicator](AZ::ConsoleFunctorBase* functor) { consoleReplicator.Visit(functor); }); @@ -525,16 +547,17 @@ namespace Multiplayer if (connection->GetConnectionRole() == ConnectionRole::Connector) { AZLOG_INFO("New outgoing connection to remote address: %s", connection->GetRemoteAddress().GetString().c_str()); - connection->SendReliablePacket(MultiplayerPackets::Connect(0)); + AZ::CVarFixedString providerTicket; + if (connection->GetUserData() != nullptr) + { + providerTicket = reinterpret_cast(connection->GetUserData())->GetProviderTicket(); + } + connection->SendReliablePacket(MultiplayerPackets::Connect(0, providerTicket)); } else { AZLOG_INFO("New incoming connection from remote address: %s", connection->GetRemoteAddress().GetString().c_str()); m_connAcquiredEvent.Signal(datum); - AzFramework::PlayerConnectionConfig config; - config.m_playerConnectionId = aznumeric_cast(connection->GetConnectionId()); - config.m_playerSessionId = AZStd::to_string(config.m_playerConnectionId); - AZ::Interface::Get()->ValidatePlayerJoinSession(config); } // Hosts will spawn a new default player prefab for the user that just connected @@ -600,20 +623,22 @@ namespace Multiplayer // Signal to session management that a user has left the server if (m_agentType == MultiplayerAgentType::DedicatedServer || m_agentType == MultiplayerAgentType::ClientServer) { - if (connection->GetConnectionRole() == ConnectionRole::Connector) + if (AZ::Interface::Get() != nullptr && + connection->GetConnectionRole() == ConnectionRole::Connector) { AzFramework::PlayerConnectionConfig config; config.m_playerConnectionId = aznumeric_cast(connection->GetConnectionId()); - config.m_playerSessionId = AZStd::to_string(config.m_playerConnectionId); + config.m_playerSessionId = reinterpret_cast(connection->GetUserData())->GetProviderTicket(); AZ::Interface::Get()->HandlePlayerLeaveSession(config); } } // Signal to session management when there are no remaining players in a dedicated server for potential cleanup // We avoid this for client server as the host itself is a user - if (m_agentType == MultiplayerAgentType::DedicatedServer) + if (m_agentType == MultiplayerAgentType::DedicatedServer && connection->GetConnectionRole() == ConnectionRole::Connector) { - if (m_networkInterface->GetConnectionSet().GetConnectionCount() == 0) + if (AZ::Interface::Get() != nullptr + && m_networkInterface->GetConnectionSet().GetConnectionCount() == 0) { AZ::Interface::Get()->HandleDestroySession(); } From a766e3af5c08a63e2f6edcddae26376ef8b57dd4 Mon Sep 17 00:00:00 2001 From: chcurran Date: Tue, 8 Jun 2021 13:54:25 -0700 Subject: [PATCH 590/811] Fixes for internal if-branch node parser bug (LYN-4347) and exposing properties for AZStd::tuple (LYN-3910) --- .../AzCore/RTTI/AzStdOnDemandPrettyName.inl | 51 +- .../AzCore/RTTI/AzStdOnDemandReflection.inl | 24 +- .../Grammar/AbstractCodeModel.cpp | 36 +- ...ionIfBranchWithConnectedInput.scriptcanvas | 2499 +++++++++++++++++ .../Tests/ScriptCanvas_RuntimeInterpreted.cpp | 5 + 5 files changed, 2590 insertions(+), 25 deletions(-) create mode 100644 Gems/ScriptCanvasTesting/Assets/ScriptCanvas/UnitTests/LY_SC_UnitTest_ParseFunctionIfBranchWithConnectedInput.scriptcanvas diff --git a/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandPrettyName.inl b/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandPrettyName.inl index 26e269573d..4f4a21301c 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandPrettyName.inl +++ b/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandPrettyName.inl @@ -161,7 +161,56 @@ namespace AZ return "A pair is an fixed size collection of two elements."; } }; - + + template + void GetTypeNamesFold(AZStd::vector& result, AZ::BehaviorContext& context) + { + result.push_back(OnDemandPrettyName::Get(context)); + }; + + template + void GetTypeNames(AZStd::vector& result, AZ::BehaviorContext& context) + { + (GetTypeNamesFold(result, context), ...); + }; + + template + void GetTypeNamesFold(AZStd::string& result, AZ::BehaviorContext& context) + { + if (!result.empty()) + { + result += ", "; + } + + result += OnDemandPrettyName::Get(context); + }; + + template + void GetTypeNames(AZStd::string& result, AZ::BehaviorContext& context) + { + (GetTypeNamesFold(result, context), ...); + }; + + template + struct OnDemandPrettyName> + { + static AZStd::string Get(AZ::BehaviorContext& context) + { + AZStd::string typeNames; + GetTypeNames(typeNames, context); + return AZStd::string::format("Tuple<%s>", typeNames.c_str()); + } + }; + + template + struct OnDemandToolTip> + { + static AZStd::string Get(AZ::BehaviorContext&) + { + return "A tuple is an fixed size collection of any number of any type of element."; + } + }; + template struct OnDemandPrettyName< AZStd::unordered_map > { diff --git a/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl b/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl index 537d3e5c83..2132dff3c4 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl +++ b/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl @@ -813,20 +813,27 @@ namespace AZ { using ContainerType = AZStd::tuple; - template - static void ReflectUnpackMethodFold(BehaviorContext::ClassBuilder& builder) + template + static void ReflectUnpackMethodFold(BehaviorContext::ClassBuilder& builder, const AZStd::vector& typeNames, [[maybe_unused]] size_t inputIndex) { const AZStd::string methodName = AZStd::string::format("Get%zu", Index); - builder->Method(methodName.data(), [](ContainerType& value) { return AZStd::get(value); }) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) + builder->Method(methodName.data(), [](ContainerType& thisPointer) { return AZStd::get(thisPointer); }) + ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::List) ->Attribute(AZ::ScriptCanvasAttributes::TupleGetFunctionIndex, Index) ; + + builder->Property + ( AZStd::string::format("element_%zu_%s", Index, typeNames[Index].c_str()).c_str() + , [](ContainerType& thisPointer) { return AZStd::get(thisPointer); } + , [](ContainerType& thisPointer, const t_Arg& element) { AZStd::get(thisPointer) = element; }); } - template + template static void ReflectUnpackMethods(BehaviorContext::ClassBuilder& builder, AZStd::index_sequence) { - (ReflectUnpackMethodFold(builder), ...); + AZStd::vector typeNames; + ScriptCanvasOnDemandReflection::GetTypeNames(typeNames, *builder.m_context); + (ReflectUnpackMethodFold(builder, typeNames, Indices), ...); } static void Reflect(ReflectContext* context) @@ -851,9 +858,10 @@ namespace AZ ->Attribute(AZ::ScriptCanvasAttributes::TupleConstructorFunction, constructorHolder) ; - ReflectUnpackMethods(builder, AZStd::make_index_sequence{}); + ReflectUnpackMethods(builder, AZStd::make_index_sequence{}); + builder->Method("GetSize", []() { return AZStd::tuple_size::value; }) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) + ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::List) ; } } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp index 2a485c9501..bc07d16a7e 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp @@ -3356,23 +3356,27 @@ namespace ScriptCanvas if (executionIf->GetId().m_node->IsIfBranchPrefacedWithBooleanExpression()) { - auto removeChildOutcome = RemoveChild(executionIf->ModParent(), executionIf); - if (!removeChildOutcome.IsSuccess()) + ExecutionTreePtr booleanExpression; + { - AddError(executionIf->GetNodeId(), executionIf, ScriptCanvas::ParseErrors::FailedToRemoveChild); + auto removeChildOutcome = RemoveChild(executionIf->ModParent(), executionIf); + if (!removeChildOutcome.IsSuccess()) + { + AddError(executionIf->GetNodeId(), executionIf, ScriptCanvas::ParseErrors::FailedToRemoveChild); + } + + if (!IsErrorFree()) + { + return; + } + + const auto indexAndChild = removeChildOutcome.TakeValue(); + + booleanExpression = CreateChild(executionIf->ModParent(), executionIf->GetId().m_node, executionIf->GetId().m_slot); + executionIf->ModParent()->InsertChild(indexAndChild.first, { indexAndChild.second.m_slot, indexAndChild.second.m_output, booleanExpression }); + executionIf->SetParent(booleanExpression); } - if (!IsErrorFree()) - { - return; - } - - const auto indexAndChild = removeChildOutcome.TakeValue(); - - ExecutionTreePtr booleanExpression = CreateChild(executionIf->ModParent(), executionIf->GetId().m_node, executionIf->GetId().m_slot); - executionIf->ModParent()->InsertChild(indexAndChild.first, { indexAndChild.second.m_slot, indexAndChild.second.m_output, booleanExpression }); - executionIf->SetParent(booleanExpression); - // make a condition here auto symbol = CheckLogicalExpressionSymbol(booleanExpression); if (symbol != Symbol::FunctionCall && symbol != Symbol::Count) @@ -3402,7 +3406,7 @@ namespace ScriptCanvas return; } - const auto indexAndChild2 = removeChildOutcome.TakeValue(); + const auto indexAndChild2 = removeChildOutcome2.TakeValue(); // parse if statement internal function ExecutionTreePtr internalFunction = CreateChild(booleanExpression->ModParent(), booleanExpression->GetId().m_node, booleanExpression->GetId().m_slot); @@ -4782,7 +4786,7 @@ namespace ScriptCanvas { PropertyExtractionPtr extraction = AZStd::make_shared(); extraction->m_slot = slot; - extraction->m_name = propertyField.first; + extraction->m_name = AZ::ReplaceCppArtifacts(propertyField.first); execution->AddPropertyExtractionSource(slot, extraction); } else diff --git a/Gems/ScriptCanvasTesting/Assets/ScriptCanvas/UnitTests/LY_SC_UnitTest_ParseFunctionIfBranchWithConnectedInput.scriptcanvas b/Gems/ScriptCanvasTesting/Assets/ScriptCanvas/UnitTests/LY_SC_UnitTest_ParseFunctionIfBranchWithConnectedInput.scriptcanvas new file mode 100644 index 0000000000..38df5159c2 --- /dev/null +++ b/Gems/ScriptCanvasTesting/Assets/ScriptCanvas/UnitTests/LY_SC_UnitTest_ParseFunctionIfBranchWithConnectedInput.scriptcanvas @@ -0,0 +1,2499 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp b/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp index 1633b0fc51..5bda0f3941 100644 --- a/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp +++ b/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp @@ -90,6 +90,11 @@ public: } }; +TEST_F(ScriptCanvasTestFixture, ParseFunctionIfBranchWithConnectedInput) +{ + RunUnitTestGraph("LY_SC_UnitTest_ParseFunctionIfBranchWithConnectedInput"); +} + TEST_F(ScriptCanvasTestFixture, UseRawBehaviorProperties) { RunUnitTestGraph("LY_SC_UnitTest_UseRawBehaviorProperties"); From 4b3d0d1054d88833de47d07840b356fa436562b2 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 8 Jun 2021 14:01:50 -0700 Subject: [PATCH 591/811] LYN-4327 [SDK] External Gem's aren't added to the project solution when using SDK (#1191) * should pickup the external directories registered by the project * Add support for AzTest and AzTestRunner in the SDK * missing IMPORT_LIB * Moved where .Assets targets get generated so they are visible in the SDK * generate the Directory.Build.props in the right path * excluding target on platforms that dont support it --- CMakeLists.txt | 36 +++++++-------- Code/Framework/AzTest/CMakeLists.txt | 46 +++++++++---------- Code/LauncherUnified/launcher_generator.cmake | 23 ++++++++++ Code/Tools/AzTestRunner/CMakeLists.txt | 36 ++++++++------- .../Android/platform_traits_android.cmake | 2 +- .../Linux/platform_traits_linux.cmake | 2 +- .../Platform/Mac/platform_traits_mac.cmake | 2 +- .../Windows/platform_traits_windows.cmake | 2 +- .../Platform/iOS/platform_traits_ios.cmake | 2 +- cmake/Platform/Common/Install_common.cmake | 13 +++++- .../Platform/Common/VisualStudio_common.cmake | 2 +- scripts/ctest/CMakeLists.txt | 29 ------------ 12 files changed, 100 insertions(+), 95 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 387f536966..6ca9aeacb8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -88,28 +88,28 @@ if(NOT INSTALLED_ENGINE) # Add external subdirectories listed in the engine.json. LY_EXTERNAL_SUBDIRS is a cache variable so the user can add extra # external subdirectories add_engine_json_external_subdirectories() - get_property(external_subdirs GLOBAL PROPERTY LY_EXTERNAL_SUBDIRS) - list(APPEND LY_EXTERNAL_SUBDIRS ${external_subdirs}) - - # Loop over the additional external subdirectories and invoke add_subdirectory on them - foreach(external_directory ${LY_EXTERNAL_SUBDIRS}) - # Hash the extenal_directory name and append it to the Binary Directory section of add_subdirectory - # This is to deal with potential situations where multiple external directories has the same last directory name - # For example if D:/Company1/RayTracingGem and F:/Company2/Path/RayTracingGem were both added as a subdirectory - file(REAL_PATH ${external_directory} full_directory_path) - string(SHA256 full_directory_hash ${full_directory_path}) - # Truncate the full_directory_hash down to 8 characters to avoid hitting the Windows 260 character path limit - # when the external subdirectory contains relative paths of significant length - string(SUBSTRING ${full_directory_hash} 0 8 full_directory_hash) - # Use the last directory as the suffix path to use for the Binary Directory - get_filename_component(directory_name ${external_directory} NAME) - add_subdirectory(${external_directory} ${CMAKE_BINARY_DIR}/External/${directory_name}-${full_directory_hash}) - endforeach() - else() ly_find_o3de_packages() endif() +get_property(external_subdirs GLOBAL PROPERTY LY_EXTERNAL_SUBDIRS) +list(APPEND LY_EXTERNAL_SUBDIRS ${external_subdirs}) + +# Loop over the additional external subdirectories and invoke add_subdirectory on them +foreach(external_directory ${LY_EXTERNAL_SUBDIRS}) + # Hash the extenal_directory name and append it to the Binary Directory section of add_subdirectory + # This is to deal with potential situations where multiple external directories has the same last directory name + # For example if D:/Company1/RayTracingGem and F:/Company2/Path/RayTracingGem were both added as a subdirectory + file(REAL_PATH ${external_directory} full_directory_path) + string(SHA256 full_directory_hash ${full_directory_path}) + # Truncate the full_directory_hash down to 8 characters to avoid hitting the Windows 260 character path limit + # when the external subdirectory contains relative paths of significant length + string(SUBSTRING ${full_directory_hash} 0 8 full_directory_hash) + # Use the last directory as the suffix path to use for the Binary Directory + get_filename_component(directory_name ${external_directory} NAME) + add_subdirectory(${external_directory} ${CMAKE_BINARY_DIR}/External/${directory_name}-${full_directory_hash}) +endforeach() + ################################################################################ # Post-processing ################################################################################ diff --git a/Code/Framework/AzTest/CMakeLists.txt b/Code/Framework/AzTest/CMakeLists.txt index ff31b32a24..fe5ec2d0ff 100644 --- a/Code/Framework/AzTest/CMakeLists.txt +++ b/Code/Framework/AzTest/CMakeLists.txt @@ -8,29 +8,25 @@ # remove or modify any license notices. This file is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # + +ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/AzTest/Platform/${PAL_PLATFORM_NAME}) -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) - - ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/AzTest/Platform/${PAL_PLATFORM_NAME}) - - ly_add_target( - NAME AzTest STATIC - NAMESPACE AZ - FILES_CMAKE - AzTest/aztest_files.cmake - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - ${pal_dir} - BUILD_DEPENDENCIES - PUBLIC - 3rdParty::googletest::GMock - 3rdParty::googletest::GTest - 3rdParty::GoogleBenchmark - AZ::AzCore - PLATFORM_INCLUDE_FILES - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake - ) - -endif() +ly_add_target( + NAME AzTest STATIC + NAMESPACE AZ + FILES_CMAKE + AzTest/aztest_files.cmake + ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake + INCLUDE_DIRECTORIES + PUBLIC + . + ${pal_dir} + BUILD_DEPENDENCIES + PUBLIC + 3rdParty::googletest::GMock + 3rdParty::googletest::GTest + 3rdParty::GoogleBenchmark + AZ::AzCore + PLATFORM_INCLUDE_FILES + ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake +) diff --git a/Code/LauncherUnified/launcher_generator.cmake b/Code/LauncherUnified/launcher_generator.cmake index c5d60eb29e..2f4c8a8b74 100644 --- a/Code/LauncherUnified/launcher_generator.cmake +++ b/Code/LauncherUnified/launcher_generator.cmake @@ -16,6 +16,7 @@ set_property(GLOBAL PROPERTY LAUNCHER_UNIFIED_BINARY_DIR ${CMAKE_CURRENT_BINARY_ # When using an installed engine, this file will be included by the FindLauncherGenerator.cmake script get_property(LY_PROJECTS_TARGET_NAME GLOBAL PROPERTY LY_PROJECTS_TARGET_NAME) foreach(project_name project_path IN ZIP_LISTS LY_PROJECTS_TARGET_NAME LY_PROJECTS) + # Computes the realpath to the project # If the project_path is relative, it is evaluated relative to the ${LY_ROOT_FOLDER} # Otherwise the the absolute project_path is returned with symlinks resolved @@ -35,6 +36,28 @@ foreach(project_name project_path IN ZIP_LISTS LY_PROJECTS_TARGET_NAME LY_PROJEC "to the LY_PROJECTS_TARGET_NAME global property. Other configuration errors might occur") endif() endif() + + ################################################################################ + # Assets + ################################################################################ + if(PAL_TRAIT_BUILD_HOST_TOOLS) + add_custom_target(${project_name}.Assets + COMMENT "Processing ${project_name} assets..." + COMMAND "${CMAKE_COMMAND}" + -DLY_LOCK_FILE=$/project_assets.lock + -P ${LY_ROOT_FOLDER}/cmake/CommandExecution.cmake + EXEC_COMMAND $ + --zeroAnalysisMode + --project-path=${project_real_path} + --platforms=${LY_ASSET_DEPLOY_ASSET_TYPE} + ) + set_target_properties(${project_name}.Assets + PROPERTIES + EXCLUDE_FROM_ALL TRUE + FOLDER ${project_name} + ) + endif() + ################################################################################ # Monolithic game ################################################################################ diff --git a/Code/Tools/AzTestRunner/CMakeLists.txt b/Code/Tools/AzTestRunner/CMakeLists.txt index d3598c397e..e6dd09e15b 100644 --- a/Code/Tools/AzTestRunner/CMakeLists.txt +++ b/Code/Tools/AzTestRunner/CMakeLists.txt @@ -9,12 +9,12 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) +ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) - ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) - - include(${pal_dir}/platform_traits_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) +include(${pal_dir}/platform_traits_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) +if(PAL_TRAIT_AZTESTRUNNER_SUPPORTED) + ly_add_target( NAME AzTestRunner ${PAL_TRAIT_AZTESTRUNNER_LAUNCHER_TYPE} NAMESPACE AZ @@ -32,19 +32,23 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) AZ::AzTest AZ::AzFramework ) + + if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) + + ly_add_target( + NAME AzTestRunner.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAMESPACE AZ + FILES_CMAKE + aztestrunner_test_files.cmake + BUILD_DEPENDENCIES + PRIVATE + AZ::AzTest + ) - ly_add_target( - NAME AzTestRunner.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} - NAMESPACE AZ - FILES_CMAKE - aztestrunner_test_files.cmake - BUILD_DEPENDENCIES - PRIVATE - AZ::AzTest - ) + ly_add_googletest( + NAME AZ::AzTestRunner.Tests + ) - ly_add_googletest( - NAME AZ::AzTestRunner.Tests - ) + endif() endif() diff --git a/Code/Tools/AzTestRunner/Platform/Android/platform_traits_android.cmake b/Code/Tools/AzTestRunner/Platform/Android/platform_traits_android.cmake index 40de4bd3eb..77d7b868d4 100644 --- a/Code/Tools/AzTestRunner/Platform/Android/platform_traits_android.cmake +++ b/Code/Tools/AzTestRunner/Platform/Android/platform_traits_android.cmake @@ -9,5 +9,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +set(PAL_TRAIT_AZTESTRUNNER_SUPPORTED TRUE) set(PAL_TRAIT_AZTESTRUNNER_LAUNCHER_TYPE MODULE) - diff --git a/Code/Tools/AzTestRunner/Platform/Linux/platform_traits_linux.cmake b/Code/Tools/AzTestRunner/Platform/Linux/platform_traits_linux.cmake index 59922965bb..4c623c1f7b 100644 --- a/Code/Tools/AzTestRunner/Platform/Linux/platform_traits_linux.cmake +++ b/Code/Tools/AzTestRunner/Platform/Linux/platform_traits_linux.cmake @@ -9,5 +9,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +set(PAL_TRAIT_AZTESTRUNNER_SUPPORTED TRUE) set(PAL_TRAIT_AZTESTRUNNER_LAUNCHER_TYPE EXECUTABLE) - diff --git a/Code/Tools/AzTestRunner/Platform/Mac/platform_traits_mac.cmake b/Code/Tools/AzTestRunner/Platform/Mac/platform_traits_mac.cmake index 59922965bb..4c623c1f7b 100644 --- a/Code/Tools/AzTestRunner/Platform/Mac/platform_traits_mac.cmake +++ b/Code/Tools/AzTestRunner/Platform/Mac/platform_traits_mac.cmake @@ -9,5 +9,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +set(PAL_TRAIT_AZTESTRUNNER_SUPPORTED TRUE) set(PAL_TRAIT_AZTESTRUNNER_LAUNCHER_TYPE EXECUTABLE) - diff --git a/Code/Tools/AzTestRunner/Platform/Windows/platform_traits_windows.cmake b/Code/Tools/AzTestRunner/Platform/Windows/platform_traits_windows.cmake index 59922965bb..4c623c1f7b 100644 --- a/Code/Tools/AzTestRunner/Platform/Windows/platform_traits_windows.cmake +++ b/Code/Tools/AzTestRunner/Platform/Windows/platform_traits_windows.cmake @@ -9,5 +9,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +set(PAL_TRAIT_AZTESTRUNNER_SUPPORTED TRUE) set(PAL_TRAIT_AZTESTRUNNER_LAUNCHER_TYPE EXECUTABLE) - diff --git a/Code/Tools/AzTestRunner/Platform/iOS/platform_traits_ios.cmake b/Code/Tools/AzTestRunner/Platform/iOS/platform_traits_ios.cmake index 59922965bb..4c623c1f7b 100644 --- a/Code/Tools/AzTestRunner/Platform/iOS/platform_traits_ios.cmake +++ b/Code/Tools/AzTestRunner/Platform/iOS/platform_traits_ios.cmake @@ -9,5 +9,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +set(PAL_TRAIT_AZTESTRUNNER_SUPPORTED TRUE) set(PAL_TRAIT_AZTESTRUNNER_LAUNCHER_TYPE EXECUTABLE) - diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 4aeaf21e95..a579e3128d 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -162,7 +162,18 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME) elseif(target_type STREQUAL MODULE_LIBRARY) set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") elseif(target_type STREQUAL SHARED_LIBRARY) - string(APPEND target_file_contents "set_property(TARGET ${TARGET_NAME} PROPERTY IMPORTED_IMPLIB_$ \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\")\n") + string(APPEND target_file_contents +"set_property(TARGET ${TARGET_NAME} + APPEND_STRING PROPERTY IMPORTED_IMPLIB + $<$$:\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"$ +) +") + string(APPEND target_file_contents +"set_property(TARGET ${TARGET_NAME} + PROPERTY IMPORTED_IMPLIB_$> + \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\" +) +") set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") diff --git a/cmake/Platform/Common/VisualStudio_common.cmake b/cmake/Platform/Common/VisualStudio_common.cmake index fd38a8c7ce..9a23a26d34 100644 --- a/cmake/Platform/Common/VisualStudio_common.cmake +++ b/cmake/Platform/Common/VisualStudio_common.cmake @@ -10,5 +10,5 @@ # if(CMAKE_GENERATOR MATCHES "Visual Studio 16") - configure_file("${CMAKE_CURRENT_LIST_DIR}/Directory.Build.props" "${CMAKE_CURRENT_BINARY_DIR}/Directory.Build.props" COPYONLY) + configure_file("${CMAKE_CURRENT_LIST_DIR}/Directory.Build.props" "${CMAKE_BINARY_DIR}/Directory.Build.props" COPYONLY) endif() \ No newline at end of file diff --git a/scripts/ctest/CMakeLists.txt b/scripts/ctest/CMakeLists.txt index f9824889e3..575be53cc7 100644 --- a/scripts/ctest/CMakeLists.txt +++ b/scripts/ctest/CMakeLists.txt @@ -16,35 +16,6 @@ if(NOT PAL_TRAIT_BUILD_TESTS_SUPPORTED) return() endif() -################################################################################ -# Asset Processing Target -# i.e. Tests depend on AutomatedTesting.Assets -################################################################################ - -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) - get_property(LY_PROJECTS_TARGET_NAME GLOBAL PROPERTY LY_PROJECTS_TARGET_NAME) - foreach(project_target_name project_path IN ZIP_LISTS LY_PROJECTS_TARGET_NAME LY_PROJECTS) - file(REAL_PATH ${project_path} project_real_path BASE_DIRECTORY ${LY_ROOT_FOLDER}) - # With the lock file, asset processing jobs are serialized to avoid race conditions - # on files that are created temporarily in source folders during shader processing. - add_custom_target(${project_target_name}.Assets - COMMENT "Processing ${project_target_name} assets..." - COMMAND "${CMAKE_COMMAND}" - -DLY_LOCK_FILE=$/project_assets.lock - -P ${LY_ROOT_FOLDER}/cmake/CommandExecution.cmake - EXEC_COMMAND $ - --zeroAnalysisMode - --project-path=${project_real_path} - --platforms=${LY_ASSET_DEPLOY_ASSET_TYPE} - ) - set_target_properties(${project_target_name}.Assets - PROPERTIES - EXCLUDE_FROM_ALL TRUE - FOLDER ${project_target_name} - ) - endforeach() -endif() - ################################################################################ # Tests ################################################################################ From 5f82e5a11134a4571a6b69d351a178cd6faf5372 Mon Sep 17 00:00:00 2001 From: bosnichd Date: Tue, 8 Jun 2021 15:15:20 -0600 Subject: [PATCH 592/811] Fix typo. (#1192) --- Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.cpp b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.cpp index 5107a02835..c750aea38d 100644 --- a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.cpp +++ b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.cpp @@ -693,7 +693,7 @@ namespace ImGui ImGui::TextColored(ImGui::Colors::s_PlainLabelColor, "Left Stick"); ImGui::NextColumn(); ImGui::Bullet(); - ImGui::TextColored(ImGui::Colors::s_PlainLabelColor, "Mova Mouse Pointer"); + ImGui::TextColored(ImGui::Colors::s_PlainLabelColor, "Move Mouse Pointer"); ImGui::Separator(); ImGui::NextColumn(); From b1fca488bf94b66d65e9421d2e5600af778b4763 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 8 Jun 2021 14:24:22 -0700 Subject: [PATCH 593/811] LYN-4332 Metric jobs not passing JOB_NAME, BUILD_NUMBER, NODE_NAME, CHANGE_ID (#1190) * Fix quotes * Revert "Fix quotes" This reverts commit 29ace5ef2bf1c78991a8cfeb840bfb30c4ce5d8d. * evaluating the parameters * Revert "Revert "Fix quotes"" This reverts commit 4f7008e9ccbd5fdc0b33853a4fb1f50285233da9. * just one eval * double escaping * another attempt to happiness * changing NODE_NAME to LABEL_NAME since that one is more stable and doesnt have spaces --- scripts/build/Platform/Linux/build_config.json | 2 +- scripts/build/Platform/Linux/python_linux.sh | 4 ++-- scripts/build/Platform/Mac/build_config.json | 2 +- scripts/build/Platform/Mac/python_mac.sh | 4 ++-- scripts/build/Platform/Windows/build_config.json | 2 +- scripts/build/Platform/iOS/build_config.json | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/scripts/build/Platform/Linux/build_config.json b/scripts/build/Platform/Linux/build_config.json index ee6da77b29..660bc50da6 100644 --- a/scripts/build/Platform/Linux/build_config.json +++ b/scripts/build/Platform/Linux/build_config.json @@ -24,7 +24,7 @@ "COMMAND": "python_linux.sh", "PARAMETERS": { "SCRIPT_PATH": "scripts/build/ci_build_metrics.py", - "SCRIPT_PARAMETERS": "--platform Linux --jobname '${JOB_NAME}' --jobnumber '${BUILD_NUMBER}' --jobnode '${NODE_NAME}' --changelist '${CHANGE_ID}'" + "SCRIPT_PARAMETERS": "--platform Linux --jobname=\\'${JOB_NAME}\\' --jobnumber \\'${BUILD_NUMBER}\\' --jobnode \\'${NODE_LABEL}\\' --changelist \\'${CHANGE_ID}\\'" } }, "debug": { diff --git a/scripts/build/Platform/Linux/python_linux.sh b/scripts/build/Platform/Linux/python_linux.sh index 6e1bd73b36..0fe205fcc2 100755 --- a/scripts/build/Platform/Linux/python_linux.sh +++ b/scripts/build/Platform/Linux/python_linux.sh @@ -12,5 +12,5 @@ set -o errexit # exit on the first failure encountered -echo [ci_build] python/python.sh -u ${SCRIPT_PATH} ${SCRIPT_PARAMETERS} -python/python.sh -u ${SCRIPT_PATH} ${SCRIPT_PARAMETERS} \ No newline at end of file +echo [ci_build] python/python.sh -u ${SCRIPT_PATH} $(eval echo ${SCRIPT_PARAMETERS}) +python/python.sh -u ${SCRIPT_PATH} $(eval echo ${SCRIPT_PARAMETERS}) \ No newline at end of file diff --git a/scripts/build/Platform/Mac/build_config.json b/scripts/build/Platform/Mac/build_config.json index 971e5e47a1..c02227c613 100644 --- a/scripts/build/Platform/Mac/build_config.json +++ b/scripts/build/Platform/Mac/build_config.json @@ -24,7 +24,7 @@ "COMMAND": "python_mac.sh", "PARAMETERS": { "SCRIPT_PATH": "scripts/build/ci_build_metrics.py", - "SCRIPT_PARAMETERS": "--platform Mac --jobname '${JOB_NAME}' --jobnumber '${BUILD_NUMBER}' --jobnode '${NODE_NAME}' --changelist '${CHANGE_ID}'" + "SCRIPT_PARAMETERS": "--platform Mac --jobname \\'${JOB_NAME}\\' --jobnumber \\'${BUILD_NUMBER}\\' --jobnode \\'${NODE_LABEL}\\' --changelist \\'${CHANGE_ID}\\'" } }, "debug": { diff --git a/scripts/build/Platform/Mac/python_mac.sh b/scripts/build/Platform/Mac/python_mac.sh index 6e1bd73b36..0fe205fcc2 100755 --- a/scripts/build/Platform/Mac/python_mac.sh +++ b/scripts/build/Platform/Mac/python_mac.sh @@ -12,5 +12,5 @@ set -o errexit # exit on the first failure encountered -echo [ci_build] python/python.sh -u ${SCRIPT_PATH} ${SCRIPT_PARAMETERS} -python/python.sh -u ${SCRIPT_PATH} ${SCRIPT_PARAMETERS} \ No newline at end of file +echo [ci_build] python/python.sh -u ${SCRIPT_PATH} $(eval echo ${SCRIPT_PARAMETERS}) +python/python.sh -u ${SCRIPT_PATH} $(eval echo ${SCRIPT_PARAMETERS}) \ No newline at end of file diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index 552ef2c6fd..71abf9021f 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -56,7 +56,7 @@ "COMMAND": "python_windows.cmd", "PARAMETERS": { "SCRIPT_PATH": "scripts/build/ci_build_metrics.py", - "SCRIPT_PARAMETERS": "--platform Windows --jobname \"!JOB_NAME!\" --jobnumber \"!BUILD_NUMBER!\" --jobnode \"!NODE_NAME!\" --changelist \"!CHANGE_ID!\"" + "SCRIPT_PARAMETERS": "--platform Windows --jobname \"!JOB_NAME!\" --jobnumber \"!BUILD_NUMBER!\" --jobnode \"!NODE_LABEL!\" --changelist \"!CHANGE_ID!\"" } }, "windows_packaging_all": { diff --git a/scripts/build/Platform/iOS/build_config.json b/scripts/build/Platform/iOS/build_config.json index 2d9c57f6ee..9fd0f8c7fc 100644 --- a/scripts/build/Platform/iOS/build_config.json +++ b/scripts/build/Platform/iOS/build_config.json @@ -14,7 +14,7 @@ "COMMAND": "../Mac/python_mac.sh", "PARAMETERS": { "SCRIPT_PATH": "scripts/build/ci_build_metrics.py", - "SCRIPT_PARAMETERS": "--platform iOS --jobname '${JOB_NAME}' --jobnumber '${BUILD_NUMBER}' --jobnode '${NODE_NAME}' --changelist '${CHANGE_ID}'" + "SCRIPT_PARAMETERS": "--platform iOS --jobname '${JOB_NAME}' --jobname \\'${JOB_NAME}\\' --jobnumber \\'${BUILD_NUMBER}\\' --jobnode \\'${NODE_LABEL}\\' --changelist \\'${CHANGE_ID}\\'" } }, "debug": { From ef2d89a8435b43b71ee5baeb95b3a72a6f861695 Mon Sep 17 00:00:00 2001 From: "Tom \"spot\" Callaway" <72474383+spotaws@users.noreply.github.com> Date: Tue, 8 Jun 2021 17:38:52 -0400 Subject: [PATCH 594/811] fix AzGenericTypeInfo template handling with clang 12+ (#833) Co-authored-by: Tom spot Callaway --- Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h | 21 ++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h b/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h index 0a7d6367a6..be64f384c7 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h +++ b/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h @@ -150,8 +150,13 @@ namespace AZ // also needs to be an overload for every version because they all represent overloads for different non-types. namespace AzGenericTypeInfo { - template - constexpr bool false_v = false; + /// Needs to match declared parameter type. + template