From a71a5746ccd6734a68b8c592cab757879993301f Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Tue, 13 Apr 2021 17:15:10 +0100 Subject: [PATCH 001/231] [LY-113714] Jira: LY-113714 https://jira.agscollab.com/browse/LY-113714 --- .../Serialization/EditContextConstants.inl | 2 + .../Components/img/UI20/line.svg | 7 ++++ .../AzQtComponents/Components/resources.qrc | 1 + .../UI/PropertyEditor/PropertyRowWidget.cpp | 37 ++++++++++++++++++- .../UI/PropertyEditor/PropertyRowWidget.hxx | 8 ++++ Code/Sandbox/Editor/Style/Editor.qss | 5 +++ Gems/Vegetation/Code/Source/Descriptor.cpp | 2 + 7 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg diff --git a/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl b/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl index d4658d4e8c..de67013741 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl +++ b/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl @@ -62,6 +62,8 @@ namespace AZ const static AZ::Crc32 ButtonTooltip = AZ_CRC("ButtonTooltip", 0x1605a7d2); const static AZ::Crc32 CheckboxTooltip = AZ_CRC("CheckboxTooltip", 0x1159eb78); const static AZ::Crc32 CheckboxDefaultValue = AZ_CRC("CheckboxDefaultValue", 0x03f117e6); + //! Emboldens the text and adds a line above this item within the RPE. + const static AZ::Crc32 RPESectionSeparator = AZ_CRC("RPESectionSeparator", 0xc6249a95); //! Affects the display order of a node relative to it's parent/children. Higher values display further down (after) lower values. Default is 0, negative values are allowed. Must be applied as an attribute to the EditorData element const static AZ::Crc32 DisplayOrder = AZ_CRC("DisplayOrder", 0x23660ec2); //! Specifies whether the UI should support multi-edit for aggregate instances of this property diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg new file mode 100644 index 0000000000..60f7c07c8d --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg @@ -0,0 +1,7 @@ + + + line + + + + \ 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 77dead96a1..decc1bd72f 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc @@ -627,6 +627,7 @@ img/UI20/Settings.svg img/UI20/Asset_Folder.svg img/UI20/Asset_File.svg + img/UI20/line.svg img/UI20/AssetEditor/default_document.svg diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index 8c371baf8c..a16c1f7480 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -44,6 +44,24 @@ namespace AzToolsFramework m_iconOpen = s_iconOpen; m_iconClosed = s_iconClosed; + m_outerLayout = new QVBoxLayout(nullptr); + m_outerLayout->setSpacing(0); + m_outerLayout->setContentsMargins(0, 0, 0, 0); + + // separatorLayout will contain a spacer and a separator line. The width of the spacer is adjusted later to ensure the line is the + // correct length. + QHBoxLayout* separatorLayout = new QHBoxLayout(nullptr); + m_outerLayout->addLayout(separatorLayout); + + m_separatorIndent = new QSpacerItem(1, 1); + separatorLayout->addItem(m_separatorIndent); + + m_separatorLine.load(QStringLiteral(":/Gallery/line.svg")); + m_separatorLine.setFixedHeight(3); + + separatorLayout->addWidget(&m_separatorLine); + m_separatorLine.setVisible(false); + m_mainLayout = new QHBoxLayout(); m_mainLayout->setSpacing(0); m_mainLayout->setContentsMargins(0, 1, 0, 1); @@ -118,7 +136,8 @@ namespace AzToolsFramework m_handler = nullptr; m_containerSize = 0; - setLayout(m_mainLayout); + m_outerLayout->addLayout(m_mainLayout); + setLayout(m_outerLayout); } bool PropertyRowWidget::HasChildWidgetAlready() const @@ -301,6 +320,9 @@ namespace AzToolsFramework } } + m_isSectionSeparator = false; + m_separatorLine.setVisible(false); + RefreshAttributesFromNode(true); // --------------------- HANDLER discovery: @@ -946,6 +968,11 @@ namespace AzToolsFramework { HandleChangeNotifyAttribute(reader, m_sourceNode ? m_sourceNode->GetParent() : nullptr, m_editingCompleteNotifiers); } + else if (attributeName == AZ::Edit::Attributes::RPESectionSeparator) + { + m_separatorLine.setVisible(true); + m_isSectionSeparator = true; + } } void PropertyRowWidget::SetReadOnlyQueryFunction(const ReadOnlyQueryFunction& readOnlyQueryFunction) @@ -1070,6 +1097,7 @@ namespace AzToolsFramework { m_dropDownArrow->hide(); } + m_separatorIndent->changeSize((m_treeDepth * m_treeIndentation) + m_leafIndentation, 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_indent->changeSize((m_treeDepth * m_treeIndentation) + m_leafIndentation, 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_leftHandSideLayout->invalidate(); m_leftHandSideLayout->update(); @@ -1085,6 +1113,7 @@ namespace AzToolsFramework connect(m_dropDownArrow, &QCheckBox::clicked, this, &PropertyRowWidget::OnClickedExpansionButton); } m_dropDownArrow->show(); + m_separatorIndent->changeSize((m_treeDepth * m_treeIndentation), 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_indent->changeSize((m_treeDepth * m_treeIndentation), 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_leftHandSideLayout->invalidate(); m_leftHandSideLayout->update(); @@ -1095,6 +1124,7 @@ namespace AzToolsFramework void PropertyRowWidget::SetIndentSize(int w) { + m_separatorIndent->changeSize(w, 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_indent->changeSize(w, 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_leftHandSideLayout->invalidate(); m_leftHandSideLayout->update(); @@ -1318,6 +1348,11 @@ namespace AzToolsFramework return canBeTopLevel(this); } + bool PropertyRowWidget::IsSectionSeparator() const + { + return m_isSectionSeparator; + } + bool PropertyRowWidget::GetAppendDefaultLabelToName() { return false; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx index e4b538ccdc..af1b68b66f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx @@ -25,6 +25,7 @@ AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // class '...' needs t #include #include #include +#include #include AZ_POP_DISABLE_WARNING @@ -44,6 +45,7 @@ namespace AzToolsFramework Q_PROPERTY(bool hasChildRows READ HasChildRows); Q_PROPERTY(bool isTopLevel READ IsTopLevel); Q_PROPERTY(int getLevel READ GetLevel); + Q_PROPERTY(bool isSectionSeparator READ IsSectionSeparator); Q_PROPERTY(bool appendDefaultLabelToName READ GetAppendDefaultLabelToName WRITE AppendDefaultLabelToName) public: AZ_CLASS_ALLOCATOR(PropertyRowWidget, AZ::SystemAllocator, 0) @@ -82,6 +84,7 @@ namespace AzToolsFramework PropertyRowWidget* GetParentRow() const { return m_parentRow; } int GetLevel() const; bool IsTopLevel() const; + bool IsSectionSeparator() const; // Remove the default label and append the text to the name label. bool GetAppendDefaultLabelToName(); @@ -161,6 +164,9 @@ namespace AzToolsFramework QHBoxLayout* m_leftHandSideLayout; QHBoxLayout* m_middleLayout; QHBoxLayout* m_rightHandSideLayout; + QVBoxLayout* m_outerLayout; + QSvgWidget m_separatorLine; + QSpacerItem* m_separatorIndent; QPointer m_dropDownArrow; QPointer m_containerClearButton; @@ -229,6 +235,8 @@ namespace AzToolsFramework int m_treeIndentation = 14; int m_leafIndentation = 16; + bool m_isSectionSeparator = false; + QIcon m_iconOpen; QIcon m_iconClosed; diff --git a/Code/Sandbox/Editor/Style/Editor.qss b/Code/Sandbox/Editor/Style/Editor.qss index 0c3f64b85c..7887560105 100644 --- a/Code/Sandbox/Editor/Style/Editor.qss +++ b/Code/Sandbox/Editor/Style/Editor.qss @@ -38,6 +38,11 @@ AzToolsFramework--ComponentPaletteWidget > QTreeView background-color: #222222; } +AzToolsFramework--PropertyRowWidget[isSectionSeparator="true"] QLabel#Name +{ + font-weight: bold; +} + /* Style for visualizing property values overridden from their prefab values */ AzToolsFramework--PropertyRowWidget[IsOverridden=true] #Name QLabel, AzToolsFramework--ComponentEditorHeader #Title[IsOverridden="true"] diff --git a/Gems/Vegetation/Code/Source/Descriptor.cpp b/Gems/Vegetation/Code/Source/Descriptor.cpp index 93a301f073..4fd1037f09 100644 --- a/Gems/Vegetation/Code/Source/Descriptor.cpp +++ b/Gems/Vegetation/Code/Source/Descriptor.cpp @@ -170,6 +170,8 @@ namespace Vegetation { edit->Class( "Vegetation Descriptor", "Details used to create vegetation instances") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::RPESectionSeparator, true) // For this ComboBox to actually work, there is a PropertyHandler registration in EditorVegetationSystemComponent.cpp ->DataElement(AZ::Edit::UIHandlers::ComboBox, &Descriptor::m_spawnerType, "Instance Spawner", "The type of instances to spawn") ->Attribute(AZ::Edit::Attributes::GenericValueList, &Descriptor::GetSpawnerTypeList) From a94700786133526d14971bddfdd87e5d989d8678 Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Wed, 14 Apr 2021 15:15:42 +0100 Subject: [PATCH 002/231] Darken line --- .../AzQtComponents/AzQtComponents/Components/img/UI20/line.svg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg index 60f7c07c8d..fe01efddba 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg @@ -2,6 +2,6 @@ line - + \ No newline at end of file From 490b2afd319c595850df82f6038e13a4fa179102 Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Fri, 16 Apr 2021 10:59:27 +0100 Subject: [PATCH 003/231] [LY-105687] Jira: LY-105687 https://jira.agscollab.com/browse/LY-105687 --- .../Components/FancyDocking.cpp | 14 +++++++ .../AzQtComponents/Components/FancyDocking.h | 2 + .../Components/Widgets/TabWidget.cpp | 24 ++++++++---- .../Components/Widgets/TabWidget.h | 3 ++ .../img/UI20/Cursors/Grab_release.svg | 37 +++++++++++++++++++ .../Components/img/UI20/Cursors/Grabbing.svg | 23 ++++++++++++ .../AzQtComponents/Components/resources.qrc | 2 + 7 files changed, 98 insertions(+), 7 deletions(-) create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp index 76df971108..bc8da127a6 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp @@ -159,6 +159,8 @@ namespace AzQtComponents // Timer for updating our hovered drop zone opacity QObject::connect(m_dropZoneHoverFadeInTimer, &QTimer::timeout, this, &FancyDocking::onDropZoneHoverFadeInUpdate); m_dropZoneHoverFadeInTimer->setInterval(g_FancyDockingConstants.dropZoneHoverFadeUpdateIntervalMS); + QIcon dragIcon = QIcon(QStringLiteral(":/Cursors/Grabbing.svg")); + m_dragCursor = QCursor(dragIcon.pixmap(32), 10, 5); } FancyDocking::~FancyDocking() @@ -1884,6 +1886,8 @@ namespace AzQtComponents return; } + QApplication::setOverrideCursor(m_dragCursor); + QPoint relativePressPos = pressPos; // If we are dragging a floating window, we need to grab a reference to its @@ -1999,6 +2003,11 @@ namespace AzQtComponents clearDraggingState(); } + if (QApplication::overrideCursor()) + { + QApplication::restoreOverrideCursor(); + } + return true; } @@ -2376,6 +2385,11 @@ namespace AzQtComponents */ void FancyDocking::dropDockWidget(QDockWidget* dock, QWidget* onto, Qt::DockWidgetArea area) { + if (QApplication::overrideCursor()) + { + QApplication::restoreOverrideCursor(); + } + // If the dock widget we are dropping is currently a tab, we need to retrieve it from // the tab widget, and remove it as a tab. We also need to remove its item from our // cache of widget <-> tab container since we are moving it somewhere else. diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.h b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.h index a466ce7087..20b90ad25c 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.h +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.h @@ -266,6 +266,8 @@ namespace AzQtComponents QString m_floatingWindowIdentifierPrefix; QString m_tabContainerIdentifierPrefix; + + QCursor m_dragCursor; }; } // namespace AzQtComponents diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp index 895785f47b..8f408b01ef 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -419,6 +420,14 @@ namespace AzQtComponents // a mouse move. The paint handler updates the close button's visibility setAttribute(Qt::WA_Hover); AzQtComponents::Style::addClass(this, g_emptyStyleClass); + + QIcon icon = QIcon(QStringLiteral(":/Cursors/Grab release.svg")); + m_hoverCursor = QCursor(icon.pixmap(32), 10, 5); + + icon = QIcon(QStringLiteral(":/Cursors/Grabbing.svg")); + m_dragCursor = QCursor(icon.pixmap(32), 10, 5); + + this->setCursor(m_hoverCursor); } void TabBar::setHandleOverflow(bool handleOverflow) @@ -479,6 +488,13 @@ namespace AzQtComponents void TabBar::mouseReleaseEvent(QMouseEvent* mouseEvent) { + // Ensure we don't reset the cursor in the case of a dummy event being sent from DockTabWidget to trigger the animation. + Qt::MouseButtons realButtons = QApplication::mouseButtons(); + if (QApplication::overrideCursor() && !(realButtons & Qt::LeftButton)) + { + QApplication::restoreOverrideCursor(); + } + if (m_movingTab && !(mouseEvent->buttons() & Qt::LeftButton)) { // When a moving tab is released, there is a short animation to put the moving tab @@ -632,13 +648,7 @@ namespace AzQtComponents { QPoint p = tabRect(i).topLeft(); - int rightPadding = g_closeButtonPadding; - if (m_overflowing == Overflowing) - { - rightPadding = 0; - } - - p.setX(p.x() + tabRect(i).width() - rightPadding - g_closeButtonWidth); + p.setX(p.x() + tabRect(i).width() - g_closeButtonPadding - g_closeButtonWidth); p.setY(p.y() + 1 + (tabRect(i).height() - g_closeButtonWidth) / 2); tabBtn->move(p); } diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.h b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.h index 3f12f79907..e86deef7b4 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.h +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.h @@ -203,6 +203,9 @@ namespace AzQtComponents bool m_movingTab = false; QPoint m_lastMousePress; + QCursor m_dragCursor; + QCursor m_hoverCursor; + void resetOverflow(); void overflowIfNeeded(); void showCloseButtonAt(int index); diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg new file mode 100644 index 0000000000..c0da9b802f --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg new file mode 100644 index 0000000000..e70be77d51 --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg @@ -0,0 +1,23 @@ + + + + + + + + + + diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc index f9e601fb6d..048758c283 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc @@ -636,5 +636,7 @@ img/UI20/Cursors/Pointer.svg + img/UI20/Cursors/Grab_release.svg + img/UI20/Cursors/Grabbing.svg From db4b080544d305052602e0ba7e8260ee90bf0a87 Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Fri, 16 Apr 2021 14:55:39 +0100 Subject: [PATCH 004/231] Renamed svg --- .../AzQtComponents/Components/Widgets/TabWidget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp index 8f408b01ef..121f35db61 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp @@ -421,7 +421,7 @@ namespace AzQtComponents setAttribute(Qt::WA_Hover); AzQtComponents::Style::addClass(this, g_emptyStyleClass); - QIcon icon = QIcon(QStringLiteral(":/Cursors/Grab release.svg")); + QIcon icon = QIcon(QStringLiteral(":/Cursors/Grab_release.svg")); m_hoverCursor = QCursor(icon.pixmap(32), 10, 5); icon = QIcon(QStringLiteral(":/Cursors/Grabbing.svg")); From 2a339edc4e9ddafedc6dac297abdd1d9c8faf3ca Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Fri, 16 Apr 2021 10:59:27 +0100 Subject: [PATCH 005/231] [LY-105687] Jira: LY-105687 https://jira.agscollab.com/browse/LY-105687 Renamed svg --- .../Components/FancyDocking.cpp | 14 +++++++ .../AzQtComponents/Components/FancyDocking.h | 2 + .../Components/Widgets/TabWidget.cpp | 24 ++++++++---- .../Components/Widgets/TabWidget.h | 3 ++ .../img/UI20/Cursors/Grab_release.svg | 37 +++++++++++++++++++ .../Components/img/UI20/Cursors/Grabbing.svg | 23 ++++++++++++ .../AzQtComponents/Components/resources.qrc | 2 + 7 files changed, 98 insertions(+), 7 deletions(-) create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp index 76df971108..bc8da127a6 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp @@ -159,6 +159,8 @@ namespace AzQtComponents // Timer for updating our hovered drop zone opacity QObject::connect(m_dropZoneHoverFadeInTimer, &QTimer::timeout, this, &FancyDocking::onDropZoneHoverFadeInUpdate); m_dropZoneHoverFadeInTimer->setInterval(g_FancyDockingConstants.dropZoneHoverFadeUpdateIntervalMS); + QIcon dragIcon = QIcon(QStringLiteral(":/Cursors/Grabbing.svg")); + m_dragCursor = QCursor(dragIcon.pixmap(32), 10, 5); } FancyDocking::~FancyDocking() @@ -1884,6 +1886,8 @@ namespace AzQtComponents return; } + QApplication::setOverrideCursor(m_dragCursor); + QPoint relativePressPos = pressPos; // If we are dragging a floating window, we need to grab a reference to its @@ -1999,6 +2003,11 @@ namespace AzQtComponents clearDraggingState(); } + if (QApplication::overrideCursor()) + { + QApplication::restoreOverrideCursor(); + } + return true; } @@ -2376,6 +2385,11 @@ namespace AzQtComponents */ void FancyDocking::dropDockWidget(QDockWidget* dock, QWidget* onto, Qt::DockWidgetArea area) { + if (QApplication::overrideCursor()) + { + QApplication::restoreOverrideCursor(); + } + // If the dock widget we are dropping is currently a tab, we need to retrieve it from // the tab widget, and remove it as a tab. We also need to remove its item from our // cache of widget <-> tab container since we are moving it somewhere else. diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.h b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.h index a466ce7087..20b90ad25c 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.h +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.h @@ -266,6 +266,8 @@ namespace AzQtComponents QString m_floatingWindowIdentifierPrefix; QString m_tabContainerIdentifierPrefix; + + QCursor m_dragCursor; }; } // namespace AzQtComponents diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp index 895785f47b..121f35db61 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -419,6 +420,14 @@ namespace AzQtComponents // a mouse move. The paint handler updates the close button's visibility setAttribute(Qt::WA_Hover); AzQtComponents::Style::addClass(this, g_emptyStyleClass); + + QIcon icon = QIcon(QStringLiteral(":/Cursors/Grab_release.svg")); + m_hoverCursor = QCursor(icon.pixmap(32), 10, 5); + + icon = QIcon(QStringLiteral(":/Cursors/Grabbing.svg")); + m_dragCursor = QCursor(icon.pixmap(32), 10, 5); + + this->setCursor(m_hoverCursor); } void TabBar::setHandleOverflow(bool handleOverflow) @@ -479,6 +488,13 @@ namespace AzQtComponents void TabBar::mouseReleaseEvent(QMouseEvent* mouseEvent) { + // Ensure we don't reset the cursor in the case of a dummy event being sent from DockTabWidget to trigger the animation. + Qt::MouseButtons realButtons = QApplication::mouseButtons(); + if (QApplication::overrideCursor() && !(realButtons & Qt::LeftButton)) + { + QApplication::restoreOverrideCursor(); + } + if (m_movingTab && !(mouseEvent->buttons() & Qt::LeftButton)) { // When a moving tab is released, there is a short animation to put the moving tab @@ -632,13 +648,7 @@ namespace AzQtComponents { QPoint p = tabRect(i).topLeft(); - int rightPadding = g_closeButtonPadding; - if (m_overflowing == Overflowing) - { - rightPadding = 0; - } - - p.setX(p.x() + tabRect(i).width() - rightPadding - g_closeButtonWidth); + p.setX(p.x() + tabRect(i).width() - g_closeButtonPadding - g_closeButtonWidth); p.setY(p.y() + 1 + (tabRect(i).height() - g_closeButtonWidth) / 2); tabBtn->move(p); } diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.h b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.h index 3f12f79907..e86deef7b4 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.h +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.h @@ -203,6 +203,9 @@ namespace AzQtComponents bool m_movingTab = false; QPoint m_lastMousePress; + QCursor m_dragCursor; + QCursor m_hoverCursor; + void resetOverflow(); void overflowIfNeeded(); void showCloseButtonAt(int index); diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg new file mode 100644 index 0000000000..c0da9b802f --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg new file mode 100644 index 0000000000..e70be77d51 --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg @@ -0,0 +1,23 @@ + + + + + + + + + + diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc index f9e601fb6d..048758c283 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc @@ -636,5 +636,7 @@ img/UI20/Cursors/Pointer.svg + img/UI20/Cursors/Grab_release.svg + img/UI20/Cursors/Grabbing.svg From 2dbd9e4a050e141a45c85a12b4d245f0695f581a Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Mon, 19 Apr 2021 15:54:41 +0100 Subject: [PATCH 006/231] Changed to use direct line drawing rather than adding svg. --- .../Components/img/UI20/line.svg | 7 ---- .../UI/PropertyEditor/PropertyRowWidget.cpp | 40 +++++++------------ .../UI/PropertyEditor/PropertyRowWidget.hxx | 4 +- 3 files changed, 16 insertions(+), 35 deletions(-) delete mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg deleted file mode 100644 index fe01efddba..0000000000 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/line.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - line - - - - \ No newline at end of file diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index a16c1f7480..5b02e81e6d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -27,6 +27,7 @@ AZ_PUSH_DISABLE_WARNING(4244 4251 4800, "-Wunknown-warning-option") // 4244: con #include #include #include +#include AZ_POP_DISABLE_WARNING static const int LabelColumnStretch = 2; @@ -44,24 +45,6 @@ namespace AzToolsFramework m_iconOpen = s_iconOpen; m_iconClosed = s_iconClosed; - m_outerLayout = new QVBoxLayout(nullptr); - m_outerLayout->setSpacing(0); - m_outerLayout->setContentsMargins(0, 0, 0, 0); - - // separatorLayout will contain a spacer and a separator line. The width of the spacer is adjusted later to ensure the line is the - // correct length. - QHBoxLayout* separatorLayout = new QHBoxLayout(nullptr); - m_outerLayout->addLayout(separatorLayout); - - m_separatorIndent = new QSpacerItem(1, 1); - separatorLayout->addItem(m_separatorIndent); - - m_separatorLine.load(QStringLiteral(":/Gallery/line.svg")); - m_separatorLine.setFixedHeight(3); - - separatorLayout->addWidget(&m_separatorLine); - m_separatorLine.setVisible(false); - m_mainLayout = new QHBoxLayout(); m_mainLayout->setSpacing(0); m_mainLayout->setContentsMargins(0, 1, 0, 1); @@ -136,8 +119,20 @@ namespace AzToolsFramework m_handler = nullptr; m_containerSize = 0; - m_outerLayout->addLayout(m_mainLayout); - setLayout(m_outerLayout); + setLayout(m_mainLayout); + } + + void PropertyRowWidget::paintEvent(QPaintEvent* event) + { + QStylePainter p(this); + + if (IsSectionSeparator()) + { + const QPen linePen(QColor(0x3B3E3F)); + p.setPen(linePen); + int indent = m_treeDepth * m_treeIndentation; + p.drawLine(event->rect().topLeft() + QPoint(indent, 0), event->rect().topRight()); + } } bool PropertyRowWidget::HasChildWidgetAlready() const @@ -321,7 +316,6 @@ namespace AzToolsFramework } m_isSectionSeparator = false; - m_separatorLine.setVisible(false); RefreshAttributesFromNode(true); @@ -970,7 +964,6 @@ namespace AzToolsFramework } else if (attributeName == AZ::Edit::Attributes::RPESectionSeparator) { - m_separatorLine.setVisible(true); m_isSectionSeparator = true; } } @@ -1097,7 +1090,6 @@ namespace AzToolsFramework { m_dropDownArrow->hide(); } - m_separatorIndent->changeSize((m_treeDepth * m_treeIndentation) + m_leafIndentation, 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_indent->changeSize((m_treeDepth * m_treeIndentation) + m_leafIndentation, 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_leftHandSideLayout->invalidate(); m_leftHandSideLayout->update(); @@ -1113,7 +1105,6 @@ namespace AzToolsFramework connect(m_dropDownArrow, &QCheckBox::clicked, this, &PropertyRowWidget::OnClickedExpansionButton); } m_dropDownArrow->show(); - m_separatorIndent->changeSize((m_treeDepth * m_treeIndentation), 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_indent->changeSize((m_treeDepth * m_treeIndentation), 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_leftHandSideLayout->invalidate(); m_leftHandSideLayout->update(); @@ -1124,7 +1115,6 @@ namespace AzToolsFramework void PropertyRowWidget::SetIndentSize(int w) { - m_separatorIndent->changeSize(w, 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_indent->changeSize(w, 1, QSizePolicy::Fixed, QSizePolicy::Fixed); m_leftHandSideLayout->invalidate(); m_leftHandSideLayout->update(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx index af1b68b66f..d08779caa4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx @@ -129,6 +129,7 @@ namespace AzToolsFramework void SetSelectionEnabled(bool selectionEnabled); void SetSelected(bool selected); bool eventFilter(QObject *watched, QEvent *event) override; + void paintEvent(QPaintEvent*) override; /// Apply tooltip to widget and some of its children. void SetDescription(const QString& text); @@ -164,9 +165,6 @@ namespace AzToolsFramework QHBoxLayout* m_leftHandSideLayout; QHBoxLayout* m_middleLayout; QHBoxLayout* m_rightHandSideLayout; - QVBoxLayout* m_outerLayout; - QSvgWidget m_separatorLine; - QSpacerItem* m_separatorIndent; QPointer m_dropDownArrow; QPointer m_containerClearButton; From b1d8330870f31399d05aa0c1d1b28e5f55512580 Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Tue, 20 Apr 2021 17:20:19 +0100 Subject: [PATCH 007/231] Review fixes. --- .../AzQtComponents/AzQtComponents/Components/resources.qrc | 1 - .../AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx | 1 - 2 files changed, 2 deletions(-) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc index e253c6492d..f9e601fb6d 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc @@ -630,7 +630,6 @@ img/UI20/Settings.svg img/UI20/Asset_Folder.svg img/UI20/Asset_File.svg - img/UI20/line.svg img/UI20/AssetEditor/default_document.svg diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx index d08779caa4..2fb695fca5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx @@ -25,7 +25,6 @@ AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // class '...' needs t #include #include #include -#include #include AZ_POP_DISABLE_WARNING From bfa964a23edd6bce5f6ae0da11506aa0895f0961 Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Wed, 21 Apr 2021 10:19:12 +0100 Subject: [PATCH 008/231] Moved TabWidget grab animation to mouse press to match fancy docking behavior, fixed missed mouse up cursor restore --- .../AzQtComponents/Components/FancyDocking.cpp | 15 +++++---------- .../Components/Widgets/TabWidget.cpp | 6 ++++++ 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp index bc8da127a6..2fb06a8367 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp @@ -2003,11 +2003,6 @@ namespace AzQtComponents clearDraggingState(); } - if (QApplication::overrideCursor()) - { - QApplication::restoreOverrideCursor(); - } - return true; } @@ -2385,11 +2380,6 @@ namespace AzQtComponents */ void FancyDocking::dropDockWidget(QDockWidget* dock, QWidget* onto, Qt::DockWidgetArea area) { - if (QApplication::overrideCursor()) - { - QApplication::restoreOverrideCursor(); - } - // If the dock widget we are dropping is currently a tab, we need to retrieve it from // the tab widget, and remove it as a tab. We also need to remove its item from our // cache of widget <-> tab container since we are moving it somewhere else. @@ -3573,6 +3563,11 @@ namespace AzQtComponents */ void FancyDocking::clearDraggingState() { + if (QApplication::overrideCursor()) + { + QApplication::restoreOverrideCursor(); + } + m_ghostWidget->hide(); // Release the mouse and keyboard from our main window since we grab them when we start dragging diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp index 121f35db61..a0006d7979 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp @@ -464,6 +464,11 @@ namespace AzQtComponents { if (mouseEvent->buttons() & Qt::LeftButton) { + if (!QApplication::overrideCursor() || *QApplication::overrideCursor() != m_dragCursor) + { + QApplication::setOverrideCursor(m_dragCursor); + } + m_lastMousePress = mouseEvent->pos(); } @@ -478,6 +483,7 @@ namespace AzQtComponents // selected tab is moved around. The close button is not explicitly rendered for the // moved tab during this operation. We need to make sure not to set it visible again // while the tab is moving. This flag makes sure it happens. + m_movingTab = true; } From 2f4120cdfbbd736d18fdc5f3187a94f6640ed28b Mon Sep 17 00:00:00 2001 From: puvvadar Date: Mon, 3 May 2021 13:07:11 -0700 Subject: [PATCH 009/231] Update Ctrl+G logic to account for prefab processing status and timing --- .../PrefabEditorEntityOwnershipInterface.h | 2 + .../PrefabEditorEntityOwnershipService.cpp | 5 ++ .../PrefabEditorEntityOwnershipService.h | 2 + Gems/Multiplayer/Code/CMakeLists.txt | 1 + .../Code/Include/IMultiplayerTools.h | 39 ++++++++++++ .../MultiplayerEditorSystemComponent.cpp | 63 ++++++++++++------- .../Editor/MultiplayerEditorSystemComponent.h | 12 +++- .../Code/Source/MultiplayerToolsModule.cpp | 35 ++++------- .../Code/Source/MultiplayerToolsModule.h | 27 ++++++++ .../Pipeline/NetworkPrefabProcessor.cpp | 3 + .../Code/multiplayer_tools_files.cmake | 1 + 11 files changed, 142 insertions(+), 48 deletions(-) create mode 100644 Gems/Multiplayer/Code/Include/IMultiplayerTools.h diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h index 19c236f509..4476876b59 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h @@ -46,6 +46,8 @@ namespace AzToolsFramework virtual Prefab::InstanceOptionalReference GetRootPrefabInstance() = 0; + virtual const AZStd::vector>& GetPlayInEditorAssetData() = 0; + virtual bool LoadFromStream(AZ::IO::GenericStream& stream, AZStd::string_view filename) = 0; virtual bool SaveToStream(AZ::IO::GenericStream& stream, AZStd::string_view filename) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 81233069a9..e81d6bf08e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -321,6 +321,11 @@ namespace AzToolsFramework return *m_rootInstance; } + const AZStd::vector>& PrefabEditorEntityOwnershipService::GetPlayInEditorAssetData() + { + return m_playInEditorData.m_assets; + } + void PrefabEditorEntityOwnershipService::OnEntityRemoved(AZ::EntityId entityId) { AzFramework::SliceEntityRequestBus::MultiHandler::BusDisconnect(entityId); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h index 9c483e61c5..cf62220e67 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h @@ -195,6 +195,8 @@ namespace AzToolsFramework AZ::IO::PathView filePath, Prefab::InstanceOptionalReference instanceToParentUnder) override; Prefab::InstanceOptionalReference GetRootPrefabInstance() override; + + const AZStd::vector>& GetPlayInEditorAssetData() override; ////////////////////////////////////////////////////////////////////////// void OnEntityRemoved(AZ::EntityId entityId); diff --git a/Gems/Multiplayer/Code/CMakeLists.txt b/Gems/Multiplayer/Code/CMakeLists.txt index 4eeee15c47..46f56ef315 100644 --- a/Gems/Multiplayer/Code/CMakeLists.txt +++ b/Gems/Multiplayer/Code/CMakeLists.txt @@ -119,6 +119,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) BUILD_DEPENDENCIES PRIVATE Gem::Multiplayer.Editor.Static + Gem::Multiplayer.Tools ) endif() diff --git a/Gems/Multiplayer/Code/Include/IMultiplayerTools.h b/Gems/Multiplayer/Code/Include/IMultiplayerTools.h new file mode 100644 index 0000000000..c621808f7a --- /dev/null +++ b/Gems/Multiplayer/Code/Include/IMultiplayerTools.h @@ -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. +* +*/ + +#pragma once + +#include + +namespace Multiplayer +{ + //! IMultiplayer provides insight into the Multiplayer session and its Agents + class IMultiplayerTools + { + public: + // NetworkPrefabProcessor is the only class that should be setting process network prefab status + friend class NetworkPrefabProcessor; + + AZ_RTTI(IMultiplayerTools, "{E8A80EAB-29CB-4E3B-A0B2-FFCB37060FB0}"); + + virtual ~IMultiplayerTools() = default; + + //! Returns if network prefab processing has created currently active or pending spawnables + //! @return If network prefab processing has created currently active or pending spawnables + virtual bool DidProcessNetworkPrefabs() = 0; + + private: + //! Sets if network prefab processing has created currently active or pending spawnables + //! @param didProcessNetPrefabs if network prefab processing has created currently active or pending spawnables + virtual void SetDidProcessNetworkPrefabs(bool didProcessNetPrefabs) = 0; + }; +} diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp index aec3e7870f..0850b858a2 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp @@ -10,12 +10,14 @@ * */ +#include #include #include #include #include #include #include +#include namespace Multiplayer { @@ -57,12 +59,14 @@ namespace Multiplayer void MultiplayerEditorSystemComponent::Activate() { + AzFramework::GameEntityContextEventBus::Handler::BusConnect(); AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); } void MultiplayerEditorSystemComponent::Deactivate() { AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); + AzFramework::GameEntityContextEventBus::Handler::BusDisconnect(); } void MultiplayerEditorSystemComponent::NotifyRegisterViews() @@ -77,11 +81,42 @@ namespace Multiplayer { switch (event) { - case eNotify_OnBeginGameMode: - { + case eNotify_OnQuit: + AZ_Warning("Multiplayer Editor", m_editor != nullptr, "Multiplayer Editor received On Quit without an Editor pointer."); + if (m_editor) + { + m_editor->UnregisterNotifyListener(this); + m_editor = nullptr; + } + [[fallthrough]]; + case eNotify_OnEndGameMode: + AZ::TickBus::Handler::BusDisconnect(); + // Kill the configured server if it's active + if (m_serverProcess) + { + m_serverProcess->TerminateProcess(0); + m_serverProcess = nullptr; + } + break; + } + } + + void MultiplayerEditorSystemComponent::OnGameEntitiesStarted() + { + // BeginGameMode and Prefab Processing have completed at this point + IMultiplayerTools* mpTools = AZ::Interface::Get(); + if (editorsv_enabled && mpTools != nullptr && mpTools->DidProcessNetworkPrefabs()) + { AZ::TickBus::Handler::BusConnect(); - if (editorsv_enabled) + auto prefabEditorEntityOwnershipInterface = AZ::Interface::Get(); + if (!prefabEditorEntityOwnershipInterface) + { + AZ_Error("MultiplayerEditor", prefabEditorEntityOwnershipInterface != nullptr, "PrefabEditorEntityOwnershipInterface unavailable"); + } + const AZStd::vector>& assetData = prefabEditorEntityOwnershipInterface->GetPlayInEditorAssetData(); + + if (assetData.size() > 0) { // Assemble the server's path AZ::CVarFixedString serverProcess = editorsv_process; @@ -111,33 +146,13 @@ namespace Multiplayer // Start the configured server if it's available AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; - processLaunchInfo.m_commandlineParameters = - AZStd::string::format("\"%s\"", serverPath.c_str()); + processLaunchInfo.m_commandlineParameters = AZStd::string::format("\"%s\"", serverPath.c_str()); processLaunchInfo.m_showWindow = true; processLaunchInfo.m_processPriority = AzFramework::ProcessPriority::PROCESSPRIORITY_NORMAL; m_serverProcess = AzFramework::ProcessWatcher::LaunchProcess( processLaunchInfo, AzFramework::ProcessCommunicationType::COMMUNICATOR_TYPE_NONE); } - break; - } - case eNotify_OnQuit: - AZ_Warning("Multiplayer Editor", m_editor != nullptr, "Multiplayer Editor received On Quit without an Editor pointer."); - if (m_editor) - { - m_editor->UnregisterNotifyListener(this); - m_editor = nullptr; - } - [[fallthrough]]; - case eNotify_OnEndGameMode: - AZ::TickBus::Handler::BusDisconnect(); - // Kill the configured server if it's active - if (m_serverProcess) - { - m_serverProcess->TerminateProcess(0); - m_serverProcess = nullptr; - } - break; } } diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.h b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.h index 8c18a2e57a..31ecdf83a3 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.h @@ -19,6 +19,7 @@ #include #include +#include #include #include @@ -34,6 +35,7 @@ namespace Multiplayer class MultiplayerEditorSystemComponent final : public AZ::Component , private AZ::TickBus::Handler + , private AzFramework::GameEntityContextEventBus::Handler , private AzToolsFramework::EditorEvents::Bus::Handler , private IEditorNotifyListener { @@ -66,8 +68,16 @@ namespace Multiplayer void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; int GetTickOrder() override; //! @} - //! + + //! EditorEvents::Handler overrides + //! @{ void OnEditorNotifyEvent(EEditorNotifyEvent event) override; + //! @} + + //! GameEntityContextEventBus::Handler overrides + //! @{ + void OnGameEntitiesStarted() override; + //! @} IEditor* m_editor = nullptr; AzFramework::ProcessWatcher* m_serverProcess = nullptr; diff --git a/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.cpp b/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.cpp index 5a223d6214..a5df3c1dc5 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.cpp @@ -18,32 +18,21 @@ namespace Multiplayer { - //! Multiplayer Tools system component provides serialize context reflection for tools-only systems. - class MultiplayerToolsSystemComponent final - : public AZ::Component + + void MultiplayerToolsSystemComponent::Reflect(AZ::ReflectContext* context) { - public: - AZ_COMPONENT(MultiplayerToolsSystemComponent, "{65AF5342-0ECE-423B-B646-AF55A122F72B}"); + NetworkPrefabProcessor::Reflect(context); + } - static void Reflect(AZ::ReflectContext* context) - { - NetworkPrefabProcessor::Reflect(context); - } + bool MultiplayerToolsSystemComponent::DidProcessNetworkPrefabs() + { + return m_didProcessNetPrefabs; + } - MultiplayerToolsSystemComponent() = default; - ~MultiplayerToolsSystemComponent() override = default; - - /// AZ::Component overrides. - void Activate() override - { - - } - - void Deactivate() override - { - - } - }; + void MultiplayerToolsSystemComponent::SetDidProcessNetworkPrefabs(bool didProcessNetPrefabs) + { + m_didProcessNetPrefabs = didProcessNetPrefabs; + } MultiplayerToolsModule::MultiplayerToolsModule() : AZ::Module() diff --git a/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.h b/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.h index 823bd63a1d..82d0415c5a 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.h @@ -12,10 +12,37 @@ #pragma once +#include #include +#include namespace Multiplayer { + class MultiplayerToolsSystemComponent final + : public AZ::Component + , public IMultiplayerTools + { + public: + AZ_COMPONENT(MultiplayerToolsSystemComponent, "{65AF5342-0ECE-423B-B646-AF55A122F72B}"); + + static void Reflect(AZ::ReflectContext* context); + + MultiplayerToolsSystemComponent() = default; + ~MultiplayerToolsSystemComponent() override = default; + + /// AZ::Component overrides. + void Activate() override {}; + + void Deactivate() override {}; + + bool DidProcessNetworkPrefabs() override; + + private: + void SetDidProcessNetworkPrefabs(bool didProcessNetPrefabs) override; + + bool m_didProcessNetPrefabs = false; + }; + class MultiplayerToolsModule : public AZ::Module { diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp index 2006272135..8528b3d564 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -29,6 +30,8 @@ namespace Multiplayer void NetworkPrefabProcessor::Process(PrefabProcessorContext& context) { + IMultiplayerTools* mpTools = AZ::Interface::Get(); + mpTools->SetDidProcessNetworkPrefabs(false); context.ListPrefabs([&context](AZStd::string_view prefabName, PrefabDom& prefab) { ProcessPrefab(context, prefabName, prefab); }); diff --git a/Gems/Multiplayer/Code/multiplayer_tools_files.cmake b/Gems/Multiplayer/Code/multiplayer_tools_files.cmake index 1be02fd999..12f12479ba 100644 --- a/Gems/Multiplayer/Code/multiplayer_tools_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_tools_files.cmake @@ -10,6 +10,7 @@ # set(FILES + Include/IMultiplayerTools.h Source/Multiplayer_precompiled.cpp Source/Multiplayer_precompiled.h Source/Pipeline/NetworkPrefabProcessor.cpp From f5414050e36906541cad6fcf1377918f602ecae6 Mon Sep 17 00:00:00 2001 From: darapan Date: Wed, 5 May 2021 00:37:53 -0700 Subject: [PATCH 010/231] smoke test cases migration --- .../Gem/PythonTests/CMakeLists.txt | 15 ++ .../smoke/Editor_NewExistingLevels.py | 155 ++++++++++++++++++ .../Gem/PythonTests/smoke/ImportPathHelper.py | 16 ++ .../Gem/PythonTests/smoke/__init__.py | 10 ++ .../PythonTests/smoke/test_AssetBuilder.py | 44 +++++ .../smoke/test_AssetProcessorBatch.py | 43 +++++ .../PythonTests/smoke/test_AzTestRunner.py | 46 ++++++ .../smoke/test_Editor_NewExistingLevels.py | 34 ++++ .../smoke/test_PythonBindingsExample.py | 45 +++++ .../smoke/test_SerializeContextTools.py | 44 +++++ .../smoke/test_Statictool_Scripts.py | 48 ++++++ 11 files changed, 500 insertions(+) create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels.py create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/ImportPathHelper.py create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/__init__.py create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/test_AssetBuilder.py create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/test_AssetProcessorBatch.py create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/test_AzTestRunner.py create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels.py create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/test_PythonBindingsExample.py create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/test_SerializeContextTools.py create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 6d3727195e..26c425fd79 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -307,3 +307,18 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) #) endif() +## Smoke ## +if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_pytest( + NAME AutomatedTesting::SmokeTest_Periodic + TEST_SUITE periodic + TEST_SERIAL + PATH ${CMAKE_CURRENT_LIST_DIR}/smoke + TIMEOUT 3600 + RUNTIME_DEPENDENCIES + AZ::AssetProcessor + AZ::PythonBindingsExample + Legacy::Editor + AutomatedTesting.GameLauncher + AutomatedTesting.Assets + diff --git a/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels.py b/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels.py new file mode 100644 index 0000000000..4e4a037ec9 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels.py @@ -0,0 +1,155 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: LY-123945 +Test Case Title: Create Test for UI apps- Editor +URL of the test case: https://jira.agscollab.com/browse/LY-123945 +""" + + +# fmt: off +class Tests(): + level_created = ("Level created", "Failed to create level") + entity_found = ("New Entity created in level", "Failed to create New Entity in level") + mesh_added = ("Mesh Component added", "Failed to add Mesh Component") + enter_game_mode = ("Game Mode successfully entered", "Failed to enter in Game Mode") + exit_game_mode = ("Game Mode successfully exited", "Failed to exit in Game Mode") + level_opened = ("Level opened successfully", "Failed to open level") + level_exported = ("Level exported successfully", "Failed to export level") + mesh_removed = ("Mesh Component removed", "Failed to remove Mesh Component") + entity_deleted = ("Entity deleted", "Failed to delete Entity") + level_edits_present = ("Level edits persist after saving", "Failed to save level edits after saving") +# fmt: on + + +def Editor_NewExistingLevels(): + """ + Summary: Perform the below operations on Editor + + 1) Launch & Close editor + 2) Create new level + 3) Saving and loading levels + 4) Level edits persist after saving + 5) Export Level + 6) Can switch to play mode (ctrl+g) and exit that + 7) Run editor python bindings test + 8) Create an Entity + 9) Delete an Entity + 10) Add a component to an Entity + + Expected Behavior: + All operations succeed and do not cause a crash + + Test Steps: + 1) Launch editor and Create a new level + 2) Create a new entity + 3) Add Mesh component + 4) Verify enter/exit game mode + 5) Save, Load and Export level + 6) Remove Mesh component + 7) Delete entity + 8) Open an existing level + 9) Create a new entity in an existing level + 10) Save, Load and Export an existing level and close editor + + Note: + - This test file must be called from the Lumberyard 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 + import hydra_editor_utils as hydra + from utils import TestHelper as helper + from utils import Report + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.math as math + + # 1) Launch editor and Create a new level + helper.init_idle() + test_level_name = "temp_level" + general.create_level_no_prompt(test_level_name, 128, 1, 128, False) + general.idle_wait(2.0) + Report.result(Tests.level_created, general.get_current_level_name() == test_level_name) + + # 2) Create a new entity + entity_position = math.Vector3(200.0, 200.0, 38.0) + new_entity = hydra.Entity("Entity1") + new_entity.create_entity(entity_position, []) + test_entity = hydra.find_entity_by_name("Entity1") + Report.result(Tests.entity_found, test_entity.IsValid()) + + # 3) Add Mesh component + new_entity.add_component("Mesh") + Report.result(Tests.mesh_added, hydra.has_components(new_entity.id, ["Mesh"])) + + # 4) Verify enter/exit game mode + helper.enter_game_mode(Tests.enter_game_mode) + helper.exit_game_mode(Tests.exit_game_mode) + + # 5) Save, Load and Export level + # Save Level + general.save_level() + # Open Level + general.open_level(test_level_name) + Report.result(Tests.level_opened, general.get_current_level_name() == test_level_name) + # Export Level + general.idle_wait(1.0) + general.export_to_engine() + level_pak_file = os.path.join("AutomatedTesting", "Levels", test_level_name, "level.pak") + Report.result(Tests.level_exported, os.path.exists(level_pak_file)) + + # 6) Remove Mesh component + new_entity.remove_component("Mesh") + Report.result(Tests.mesh_removed, not hydra.has_components(new_entity.id, ["Mesh"])) + + # 7) Delete entity + editor.ToolsApplicationRequestBus(bus.Broadcast, "DeleteEntityById", new_entity.id) + test_entity = hydra.find_entity_by_name("Entity1") + Report.result(Tests.entity_deleted, len(test_entity) == 0) + + # 8) Open an existing level + general.open_level(test_level_name) + Report.result(Tests.level_opened, general.get_current_level_name() == test_level_name) + + # 9) Create a new entity in an existing level + entity_position = math.Vector3(200.0, 200.0, 38.0) + new_entity_2 = hydra.Entity("Entity2") + new_entity_2.create_entity(entity_position, []) + test_entity = hydra.find_entity_by_name("Entity2") + Report.result(Tests.entity_found, test_entity.IsValid()) + + # 10) Save, Load and Export an existing level + # Save Level + general.save_level() + # Open Level + general.open_level(test_level_name) + Report.result(Tests.level_opened, general.get_current_level_name() == test_level_name) + entity_id = hydra.find_entity_by_name(new_entity_2.name) + Report.result(Tests.level_edits_present, entity_id == new_entity_2.id) + # Export Level + general.export_to_engine() + level_pak_file = os.path.join("AutomatedTesting", "Levels", test_level_name, "level.pak") + Report.result(Tests.level_exported, os.path.exists(level_pak_file)) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(Editor_NewExistingLevels) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/smoke/ImportPathHelper.py new file mode 100644 index 0000000000..70bed6e526 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/ImportPathHelper.py @@ -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. +""" + +def init(): + import os + import sys + sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') + sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../EditorPythonTestTools/editor_python_test_tools') diff --git a/AutomatedTesting/Gem/PythonTests/smoke/__init__.py b/AutomatedTesting/Gem/PythonTests/smoke/__init__.py new file mode 100644 index 0000000000..6ed3dc4bda --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/__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. +""" \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_AssetBuilder.py b/AutomatedTesting/Gem/PythonTests/smoke/test_AssetBuilder.py new file mode 100644 index 0000000000..da2abff50f --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_AssetBuilder.py @@ -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. +""" + +""" +LY-124059 : CLI tool - AssetBuilder +Launch AssetBuilder and Verify the help message +""" + +import os +import pytest +import subprocess +import ly_test_tools.environment.process_utils as process_utils + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.usefixtures("automatic_process_killer") +@pytest.mark.SUITE_smoke +class TestAssetBuilder(object): + @pytest.fixture(autouse=True) + def setup_teardown(self, request): + def teardown(): + process_utils.kill_processes_named("AssetBuilder", True) + + request.addfinalizer(teardown) + + @pytest.mark.test_case_id("LY-124059") + def test_AssetBuilder(self, request, editor, build_directory): + file_path = os.path.join(build_directory, "AssetBuilder") + help_message = "AssetBuilder is part of the Asset Processor" + # Launch AssetBuilder + output = subprocess.run([file_path, "-help"], capture_output=True) + assert ( + len(output.stderr) == 0 and output.returncode == 0 + ), f"Error occurred while launching {file_path}: {output.stderr}" + # Verify help message + assert help_message in str(output.stdout), f"Help Message: {help_message} is not present" diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_AssetProcessorBatch.py b/AutomatedTesting/Gem/PythonTests/smoke/test_AssetProcessorBatch.py new file mode 100644 index 0000000000..ab541b94c1 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_AssetProcessorBatch.py @@ -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. +""" + +""" +LY-124061 : CLI tool - AssetProcessorBatch +Launch AssetProcessorBatch and Shutdown AssetProcessorBatch without any crash +""" + + +# Import builtin libraries +import pytest +import os +import sys + +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../assetpipeline/") + +# Import fixtures +from ap_fixtures.asset_processor_fixture import asset_processor as asset_processor + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.usefixtures("automatic_process_killer") +@pytest.mark.usefixtures("asset_processor") +@pytest.mark.SUITE_smoke +class TestsAssetProcessorBatchs(object): + @pytest.mark.test_case_id("LY-124061") + def test_AssetProcessorBatch(self, asset_processor): + """ + Test Launching AssetProcessorBatch and verifies that is shuts down without issue + """ + # Create a sample asset root so we don't process every asset for every platform + asset_processor.create_temp_asset_root() + # Launch AssetProcessorBatch, assert batch processing success + result, _ = asset_processor.batch_process() + assert result, "AP Batch failed" diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_AzTestRunner.py b/AutomatedTesting/Gem/PythonTests/smoke/test_AzTestRunner.py new file mode 100644 index 0000000000..d1bc44fe2f --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_AzTestRunner.py @@ -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. +""" + +""" +LY-124062 : CLI tool - AzTestRunner +Launch AzTestRunner and Verify the help message +""" + +import os +import pytest +import subprocess +import ly_test_tools.environment.process_utils as process_utils + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.usefixtures("automatic_process_killer") +@pytest.mark.SUITE_smoke +class TestAzTestRunner(object): + @pytest.fixture(autouse=True) + def setup_teardown(self, request): + def teardown(): + process_utils.kill_processes_named("AzTestRunner", True) + + request.addfinalizer(teardown) + + @pytest.mark.test_case_id("LY-124062") + def test_AzTestRunner(self, request, editor, build_directory): + file_path = os.path.join(build_directory, "AzTestRunner") + help_message = "OKAY Symbol found: AzRunUnitTests" + # Launch AzTestRunner + output = subprocess.run( + [file_path, "AzTestRunner.Tests", "AzRunUnitTests", "--gtest_list_tests"], capture_output=True + ) + assert ( + len(output.stderr) == 0 and output.returncode == 0 + ), f"Error occurred while launching {file_path}: {output.stderr}" + # Verify help message + assert help_message in str(output.stdout), f"Help Message: {help_message} is not present" diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels.py b/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels.py new file mode 100644 index 0000000000..85d53d098d --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels.py @@ -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. +""" + +import pytest +import os +import sys + +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../automatedtesting_shared") + +from automatedtesting_shared.base import TestAutomationBase +import ly_test_tools.environment.file_system as file_system + + +@pytest.mark.SUITE_smoke +@pytest.mark.parametrize("launcher_platform", ["windows_editor"]) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("level", ["temp_level"]) +class TestAutomation(TestAutomationBase): + def test_Editor_NewExistingLevels(self, request, workspace, editor, level, project, launcher_platform): + def teardown(): + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) + + from . import Editor_NewExistingLevels as test_module + self._run_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_PythonBindingsExample.py b/AutomatedTesting/Gem/PythonTests/smoke/test_PythonBindingsExample.py new file mode 100644 index 0000000000..140e76fc96 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_PythonBindingsExample.py @@ -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. +""" + +""" +LY-124064 : CLI tool - PythonBindingsExample +Launch PythonBindingsExample and Verify the help message +""" + +import os +import pytest +import subprocess +import ly_test_tools.environment.process_utils as process_utils + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.usefixtures("automatic_process_killer") +@pytest.mark.SUITE_smoke +class TestPythonBindingsExample(object): + @pytest.fixture(autouse=True) + def setup_teardown(self, request): + def teardown(): + process_utils.kill_processes_named("PythonBindingsExample", True) + + request.addfinalizer(teardown) + + @pytest.mark.test_case_id("LY-124064") + def test_PythonBindingsExample(self, request, editor, build_directory): + file_path = os.path.join(build_directory, "PythonBindingsExample") + help_message = "--help Prints the help text" + # Launch PythonBindingsExample + output = subprocess.run([file_path, "-help"], capture_output=True) + assert ( + len(output.stderr) == 0 and output.returncode == 1 + ), f"Error occurred while launching {file_path}: {output.stderr}" + # Verify help message + assert help_message in str(output.stdout), f"Help Message: {help_message} is not present" + diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_SerializeContextTools.py b/AutomatedTesting/Gem/PythonTests/smoke/test_SerializeContextTools.py new file mode 100644 index 0000000000..763d84625d --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_SerializeContextTools.py @@ -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. +""" + +""" +LY-124066 : CLI tool - SerializeContextTools +Launch SerializeContextTools and Verify the help message +""" + +import os +import pytest +import subprocess +import ly_test_tools.environment.process_utils as process_utils + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.usefixtures("automatic_process_killer") +@pytest.mark.SUITE_smoke +class TestSerializeContextTools(object): + @pytest.fixture(autouse=True) + def setup_teardown(self, request): + def teardown(): + process_utils.kill_processes_named("SerializeContextTools", True) + + request.addfinalizer(teardown) + + @pytest.mark.test_case_id("LY-124066") + def test_SerializeContextTools(self, request, editor, build_directory): + file_path = os.path.join(build_directory, "SerializeContextTools") + help_message = "Converts a file with an ObjectStream to the new JSON" + # Launch SerializeContextTools + output = subprocess.run([file_path, "-help"], capture_output=True) + assert ( + len(output.stderr) == 0 and output.returncode == 0 + ), f"Error occurred while launching {file_path}: {output.stderr}" + # Verify help message + assert help_message in str(output.stdout), f"Help Message: {help_message} is not present" diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py b/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py new file mode 100644 index 0000000000..d1ae1d4ee0 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py @@ -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. +""" + +""" +LY-124058: Static tool scripts +Launch Static tool and Verify the help message +""" + +import os +import pytest +import subprocess +import sys + + +def verify_help_message(static_tool): + help_message = ["--help", "show this help message and exit"] + output = subprocess.run([sys.executable, static_tool, "-h"], capture_output=True) + assert ( + len(output.stderr) == 0 and output.returncode == 0 + ), f"Error occurred while launching {static_tool}: {output.stderr}" + # verify help message + for message in help_message: + assert message in str(output.stdout), f"Help Message: {message} is not present" + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.usefixtures("automatic_process_killer") +@pytest.mark.SUITE_smoke +class TestStatictoolScripts(object): + @pytest.mark.test_case_id("LY-124058") + def test_Statictool_Scripts(self, request, editor): + static_tools = [ + os.path.join(editor.workspace.paths.engine_root(), "scripts", "bundler", "gen_shaders.py"), + os.path.join(editor.workspace.paths.engine_root(), "scripts", "bundler", "get_shader_list.py"), + os.path.join(editor.workspace.paths.engine_root(), "scripts", "bundler", "pak_shaders.py"), + ] + + for tool in static_tools: + verify_help_message(tool) + \ No newline at end of file From 4ce7e117a9347e5dc2fc8204bc8ffd6d44530920 Mon Sep 17 00:00:00 2001 From: darapan Date: Wed, 5 May 2021 00:51:06 -0700 Subject: [PATCH 011/231] "Updating cmakelist.txt to remove extra intendation" --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 4 ++-- .../Gem/PythonTests/smoke/test_Statictool_Scripts.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 26c425fd79..e6fff224d3 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -316,9 +316,9 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) PATH ${CMAKE_CURRENT_LIST_DIR}/smoke TIMEOUT 3600 RUNTIME_DEPENDENCIES - AZ::AssetProcessor + AZ::AssetProcessor AZ::PythonBindingsExample Legacy::Editor AutomatedTesting.GameLauncher AutomatedTesting.Assets - + \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py b/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py index d1ae1d4ee0..86f5d67478 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py @@ -45,4 +45,4 @@ class TestStatictoolScripts(object): for tool in static_tools: verify_help_message(tool) - \ No newline at end of file + \ No newline at end of file From 7eb6cc10b6559511927028d9f6c5514b973a99bb Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Wed, 5 May 2021 08:57:39 +0100 Subject: [PATCH 012/231] Made change affect all modifiable containers. --- .../Serialization/EditContextConstants.inl | 2 -- .../UI/PropertyEditor/PropertyRowWidget.cpp | 22 +++++++++++++------ .../UI/PropertyEditor/PropertyRowWidget.hxx | 5 +++-- Gems/Vegetation/Code/Source/Descriptor.cpp | 2 -- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl b/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl index 481ae5a91c..90b9ba5afd 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl +++ b/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl @@ -62,8 +62,6 @@ namespace AZ const static AZ::Crc32 ButtonTooltip = AZ_CRC("ButtonTooltip", 0x1605a7d2); const static AZ::Crc32 CheckboxTooltip = AZ_CRC("CheckboxTooltip", 0x1159eb78); const static AZ::Crc32 CheckboxDefaultValue = AZ_CRC("CheckboxDefaultValue", 0x03f117e6); - //! Emboldens the text and adds a line above this item within the RPE. - const static AZ::Crc32 RPESectionSeparator = AZ_CRC("RPESectionSeparator", 0xc6249a95); //! Affects the display order of a node relative to it's parent/children. Higher values display further down (after) lower values. Default is 0, negative values are allowed. Must be applied as an attribute to the EditorData element const static AZ::Crc32 DisplayOrder = AZ_CRC("DisplayOrder", 0x23660ec2); //! Specifies whether the UI should support multi-edit for aggregate instances of this property diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index 5b02e81e6d..faeae0a06d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -315,8 +315,6 @@ namespace AzToolsFramework } } - m_isSectionSeparator = false; - RefreshAttributesFromNode(true); // --------------------- HANDLER discovery: @@ -962,10 +960,6 @@ namespace AzToolsFramework { HandleChangeNotifyAttribute(reader, m_sourceNode ? m_sourceNode->GetParent() : nullptr, m_editingCompleteNotifiers); } - else if (attributeName == AZ::Edit::Attributes::RPESectionSeparator) - { - m_isSectionSeparator = true; - } } void PropertyRowWidget::SetReadOnlyQueryFunction(const ReadOnlyQueryFunction& readOnlyQueryFunction) @@ -1340,7 +1334,7 @@ namespace AzToolsFramework bool PropertyRowWidget::IsSectionSeparator() const { - return m_isSectionSeparator; + return CanBeReordered(); } bool PropertyRowWidget::GetAppendDefaultLabelToName() @@ -1686,6 +1680,20 @@ namespace AzToolsFramework m_nameLabel->setFilter(m_currentFilterString); } + bool PropertyRowWidget::CanChildrenBeReordered() const + { + return m_containerEditable; + } + + bool PropertyRowWidget::CanBeReordered() const + { + if (!m_parentRow) + { + return false; + } + + return m_parentRow->CanChildrenBeReordered(); + } } #include "UI/PropertyEditor/moc_PropertyRowWidget.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx index 2fb695fca5..b6c94dc98b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx @@ -149,6 +149,9 @@ namespace AzToolsFramework QLabel* GetNameLabel() { return m_nameLabel; } void SetIndentSize(int w); void SetAsCustom(bool custom) { m_custom = custom; } + + bool CanChildrenBeReordered() const; + bool CanBeReordered() const; protected: int CalculateLabelWidth() const; @@ -232,8 +235,6 @@ namespace AzToolsFramework int m_treeIndentation = 14; int m_leafIndentation = 16; - bool m_isSectionSeparator = false; - QIcon m_iconOpen; QIcon m_iconClosed; diff --git a/Gems/Vegetation/Code/Source/Descriptor.cpp b/Gems/Vegetation/Code/Source/Descriptor.cpp index 45ec25038d..ecda8415e7 100644 --- a/Gems/Vegetation/Code/Source/Descriptor.cpp +++ b/Gems/Vegetation/Code/Source/Descriptor.cpp @@ -170,8 +170,6 @@ namespace Vegetation { edit->Class( "Vegetation Descriptor", "Details used to create vegetation instances") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::RPESectionSeparator, true) // For this ComboBox to actually work, there is a PropertyHandler registration in EditorVegetationSystemComponent.cpp ->DataElement(AZ::Edit::UIHandlers::ComboBox, &Descriptor::m_spawnerType, "Instance Spawner", "The type of instances to spawn") ->Attribute(AZ::Edit::Attributes::GenericValueList, &Descriptor::GetSpawnerTypeList) From 0e666d046c37a305fa89bb335f7bc43bd4a89356 Mon Sep 17 00:00:00 2001 From: darapan Date: Wed, 5 May 2021 00:57:51 -0700 Subject: [PATCH 013/231] "Adding new line" --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 1 + AutomatedTesting/Gem/PythonTests/smoke/__init__.py | 2 +- .../Gem/PythonTests/smoke/test_Statictool_Scripts.py | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index e6fff224d3..8dfac40c43 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -321,4 +321,5 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::Editor AutomatedTesting.GameLauncher AutomatedTesting.Assets + \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/smoke/__init__.py b/AutomatedTesting/Gem/PythonTests/smoke/__init__.py index 6ed3dc4bda..79f8fa4422 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/__init__.py @@ -7,4 +7,4 @@ 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. -""" \ No newline at end of file +""" diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py b/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py index 86f5d67478..92be4abeb9 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py @@ -45,4 +45,5 @@ class TestStatictoolScripts(object): for tool in static_tools: verify_help_message(tool) + \ No newline at end of file From 2f153f994e2b5be015f661bf81d99e96c3947bab Mon Sep 17 00:00:00 2001 From: darapan Date: Wed, 5 May 2021 01:12:38 -0700 Subject: [PATCH 014/231] "Adding new line" --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 1 - AutomatedTesting/Gem/PythonTests/smoke/__init__.py | 2 +- .../Gem/PythonTests/smoke/test_Statictool_Scripts.py | 2 -- 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 8dfac40c43..e6fff224d3 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -321,5 +321,4 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::Editor AutomatedTesting.GameLauncher AutomatedTesting.Assets - \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/smoke/__init__.py b/AutomatedTesting/Gem/PythonTests/smoke/__init__.py index 79f8fa4422..6ed3dc4bda 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/__init__.py @@ -7,4 +7,4 @@ 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. -""" +""" \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py b/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py index 92be4abeb9..8eac2ff099 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py @@ -45,5 +45,3 @@ class TestStatictoolScripts(object): for tool in static_tools: verify_help_message(tool) - - \ No newline at end of file From 2f0ed6cfb21aac2b99b6b5f303286bccba3ea814 Mon Sep 17 00:00:00 2001 From: darapan Date: Wed, 5 May 2021 01:17:20 -0700 Subject: [PATCH 015/231] "" --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 1 - AutomatedTesting/Gem/PythonTests/smoke/__init__.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index e6fff224d3..400dca33ce 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -321,4 +321,3 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::Editor AutomatedTesting.GameLauncher AutomatedTesting.Assets - \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/smoke/__init__.py b/AutomatedTesting/Gem/PythonTests/smoke/__init__.py index 6ed3dc4bda..79f8fa4422 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/__init__.py @@ -7,4 +7,4 @@ 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. -""" \ No newline at end of file +""" From 682bdf684743ddc094cf32ab02a5246b63191eef Mon Sep 17 00:00:00 2001 From: darapan Date: Wed, 5 May 2021 08:50:34 -0700 Subject: [PATCH 016/231] "Changing testsuite" --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 400dca33ce..92dcc7dc7f 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -310,8 +310,8 @@ endif() ## Smoke ## if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_pytest( - NAME AutomatedTesting::SmokeTest_Periodic - TEST_SUITE periodic + NAME AutomatedTesting::SmokeTest + TEST_SUITE smoke TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/smoke TIMEOUT 3600 From 2b511b68a2538326b199a088d7a4d4cfa94581c4 Mon Sep 17 00:00:00 2001 From: darapan Date: Wed, 5 May 2021 10:26:11 -0700 Subject: [PATCH 017/231] "Adding AssetBundlerBatch test" --- .../smoke/test_AssetBundlerBatch.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/test_AssetBundlerBatch.py diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_AssetBundlerBatch.py b/AutomatedTesting/Gem/PythonTests/smoke/test_AssetBundlerBatch.py new file mode 100644 index 0000000000..d361c62f5f --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_AssetBundlerBatch.py @@ -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. +""" + +""" +LY-124060 : CLI tool - AssetBundlerBatch +Launch AssetBundlerBatch and Verify the help message +""" + +import os +import pytest +import subprocess +import ly_test_tools.environment.process_utils as process_utils + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.usefixtures("automatic_process_killer") +@pytest.mark.SUITE_smoke +class TestAssetBundlerBatch(object): + @pytest.fixture(autouse=True) + def setup_teardown(self, request): + def teardown(): + process_utils.kill_processes_named("AssetBundlerBatch", True) + + request.addfinalizer(teardown) + + @pytest.mark.test_case_id("LY-124060") + def test_AssetBundlerBatch(self, request, editor, build_directory): + file_path = os.path.join(build_directory, "AssetBundlerBatch") + help_message = "Specifies the Seed List file to operate on by path" + # Launch AssetBundlerBatch + output = subprocess.run([file_path, "--help"], capture_output=True) + assert ( + len(output.stderr) == 0 and output.returncode == 0 + ), f"Error occurred while launching {file_path}: {output.stderr}" + # Verify help message + assert help_message in str(output.stdout), f"Help Message: {help_message} is not present" From 076371b026e3288a39e1ed858d315a40895a6ca2 Mon Sep 17 00:00:00 2001 From: zsolleci Date: Thu, 6 May 2021 14:20:07 -0500 Subject: [PATCH 018/231] Removed references to JIRA/TestRail; fixed typos and formatting mistakes --- .../Gem/PythonTests/CMakeLists.txt | 2 +- .../AssetEditor_CreateScriptEventFile.py | 5 -- .../scripting/AssetEditor_NewScriptEvent.py | 11 +--- .../Debugging_TargetMultipleEntities.py | 10 +--- .../Debugging_TargetMultipleGraphs.py | 11 +--- .../Gem/PythonTests/scripting/Docking_Pane.py | 19 ++---- .../scripting/EditMenu_UndoRedo.py | 20 ++----- .../Entity_AddScriptCanvasComponent.py | 9 +-- .../scripting/FileMenu_New_Open.py | 18 ++---- .../scripting/GraphClose_SavePrompt.py | 18 ++---- .../scripting/Graph_ZoomInZoomOut.py | 13 +---- .../PythonTests/scripting/ImportPathHelper.py | 7 ++- .../scripting/NodeInspector_RenameVariable.py | 14 ++--- .../scripting/NodePalette_ClearSelection.py | 14 ++--- .../scripting/NodePalette_SelectNode.py | 16 ++--- ...EntityActivatedDeactivated_PrintMessage.py | 58 +++++++++++-------- .../scripting/Opening_Closing_Pane.py | 10 +--- .../scripting/Pane_RetainOnSCRestart.py | 39 +++++-------- .../PythonTests/scripting/Resizing_Pane.py | 15 ++--- .../scripting/ScriptCanvas_ChangingAssets.py | 7 --- .../scripting/ScriptCanvas_TwoComponents.py | 6 +- .../scripting/ScriptCanvas_TwoEntities.py | 11 ++-- .../ScriptEvents_SendReceiveAcrossMultiple.py | 22 +++---- .../ScriptEvents_SendReceiveSuccessfully.py | 5 -- .../PythonTests/scripting/TestSuite_Active.py | 26 --------- .../scripting/Toggle_ScriptCanvasTools.py | 17 +----- .../scripting/UnDockedPane_CloseSCWindow.py | 11 +--- .../VariableManager_CreateDeleteVars.py | 13 +---- 28 files changed, 124 insertions(+), 303 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 31afab87ed..2423bd5b06 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -68,7 +68,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE periodic TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/scripting/TestSuite_Active.py - TIMEOUT 3000 + TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py index dcbbf47f0c..72144ebc0e 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py @@ -7,10 +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. - -Test case ID: T92569013 -Test Case Title: Script Event file can be created -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569013 """ @@ -118,7 +114,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(CreateScriptEventFile) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py index 1f801d4eeb..acc0880a73 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py @@ -7,12 +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. - - -Test case ID: T92568942 -Test Case Title: Clicking the "+" button and selecting "New Script Event" opens the -Asset Editor with a new Script Event asset -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568942 """ from PySide2 import QtWidgets @@ -36,11 +30,10 @@ GENERAL_WAIT = 0.5 # seconds class TestAssetEditor_NewScriptEvent: """ Summary: - Clicking the "+" button in Node Palette and creating New Script Event opens Asset Editor + Verifying logic flow of the "+" button on the Script Canvas pane's Node Palette is as expected Expected Behavior: - Clicking the "+" button and selecting "New Script Event" opens the Asset Editor with a - new Script Event asset + Clicking the "+" button and selecting "New Script Event" opens the Asset Editor with a new Script Event asset Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py index a26cb4f923..71e24139f4 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py @@ -7,11 +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. - - -Test case ID: T92568856 -Test Case Title: Multiple Entities can be targeted in the Debugger tool -URLs of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568856 """ @@ -32,14 +27,14 @@ def Debugging_TargetMultipleEntities(): Multiple Entities can be targeted in the Debugger tool Expected Behavior: - Selected files can be checked for logging. + Multiple selected files can be checked for logging. Upon checking, checkboxes of the parent folders change to either full or partial check. Test Steps: 1) Create temp level 2) Create two entities with scriptcanvas components 3) Set values for scriptcanvas - 4) Open Script Canvas window and get sc opbject + 4) Open Script Canvas window and get sc object 5) Open Debugging(Logging) window 6) Click on Entities tab in logging window 7) Verify if the scriptcanvas exist under entities @@ -54,7 +49,6 @@ def Debugging_TargetMultipleEntities(): :return: None """ - from PySide2 import QtWidgets from PySide2.QtCore import Qt import azlmbr.legacy.general as general diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py index 4aa5c822a7..342f8f3cd4 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py @@ -7,17 +7,12 @@ 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. - - -Test case ID: T92569137 -Test Case Title: Multiple Graphs can be targeted in the Debugger tool -URLs of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569137 """ # fmt: off class Tests(): - select_multiple_targets = ("Multiple targets are selected", "Multiple targets are not selected") + select_multiple_targets = ("Multiple targets are selected", "Multiple targets are not selected") # fmt: on @@ -30,7 +25,7 @@ def Debugging_TargetMultipleGraphs(): Multiple Graphs can be targeted in the Debugger tool Expected Behavior: - Selected files can be checked for logging. + Multiple elected files can be checked for logging. Upon checking, checkboxes of the parent folders change to either full or partial check. Test Steps: @@ -50,7 +45,6 @@ def Debugging_TargetMultipleGraphs(): :return: None """ - from PySide2 import QtWidgets from PySide2.QtCore import Qt import azlmbr.legacy.general as general @@ -107,7 +101,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(Debugging_TargetMultipleGraphs) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py index 4fa1e1257f..da9dc125bc 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py @@ -7,25 +7,21 @@ 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. - -Test case ID: C1702824 -Test Case Title: Docking -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702824 """ # fmt: off class Tests(): - pane_opened = ("Pane is opened successfully", "Failed to open pane") - dock_pane = ("Pane is docked successfully", "Failed to dock Pane into one or more allowed area") + pane_opened = ("Pane is opened successfully", "Failed to open pane") + dock_pane = ("Pane is docked successfully", "Failed to dock Pane into one or more allowed area") # fmt: on def Docking_Pane(): """ Summary: - The Script Canvas window is opened to verify if Script canvas panes can be docked into - every possible area of Script Canvas main window. + The Script Canvas window is opened to verify if Script canvas panes can be docked into every + possible area of Script Canvas main window. (top, bottom, right and left sides of the window) Expected Behavior: The pane docks successfully. @@ -44,12 +40,6 @@ def Docking_Pane(): :return: None """ - - # Helper imports - import ImportPathHelper as imports - - imports.init() - from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper import editor_python_test_tools.pyside_utils as pyside_utils @@ -111,7 +101,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from editor_python_test_tools.utils import Report Report.start_test(Docking_Pane) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py index a87d9e9be9..246a8894ba 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py @@ -7,14 +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. - - -Test case ID: T92569049 -Test Case Title: Edit > Undo undoes the last action -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569049 -Test case ID: T92569051 -Test Case Title: Edit > Redo redoes the last undone action -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569051 """ @@ -35,8 +27,8 @@ def EditMenu_UndoRedo(): redo it and verify if the variable is created again. Expected Behavior: - The last action is undone. - The last undone action is redone. + The last action is undone upon selecting Undo. + The last undone action is redone upon selecting Redo. Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) @@ -46,7 +38,7 @@ def EditMenu_UndoRedo(): 5) Create new variable 6) Verify if the variable is created initially 7) Trigger Undo action and verify if variable is removed in Variable Manager - 8) Trigger Redo action and verify if variable is readded in Variable Manager + 8) Trigger Redo action and verify if variable is re-added in Variable Manager 9) Close SC window Note: @@ -56,13 +48,12 @@ def EditMenu_UndoRedo(): :return: None """ - from PySide2 import QtWidgets, QtCore - import azlmbr.legacy.general as general - import pyside_utils + import azlmbr.legacy.general as general + # 1) Open Script Canvas window general.idle_enable(True) general.open_pane("Script Canvas") @@ -117,7 +108,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(EditMenu_UndoRedo) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py b/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py index fd8e9b1173..4e8576d892 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py @@ -7,10 +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. - -Test case ID: T92562978 -Test Case Title: Script Canvas Component can be added to an entity -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562978 """ @@ -27,10 +23,10 @@ class Tests(): def Entity_AddScriptCanvasComponent(): """ Summary: - verify if Script Canvas component can be added to Entity without any issue + Script Canvas Component can be added to an entity Expected Behavior: - Script Canvas Component is added to the entity successfully without issue. + Script Canvas Component is added to the entity successfully without issue Test Steps: 1) Create temp level @@ -47,7 +43,6 @@ def Entity_AddScriptCanvasComponent(): :return: None """ - from utils import TestHelper as helper from utils import Tracer from editor_entity_utils import EditorEntity diff --git a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py index f72ac8ea01..094598e51d 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py @@ -7,24 +7,15 @@ 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. - - -Test case ID: T92569037 -Test Case Title: File > New Script creates a new script -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569037 -Test case ID: T92569039 -Test Case Title: File > Open opens the Open... dialog -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569039 """ - -import os -import sys from PySide2 import QtWidgets -import azlmbr.legacy.general as general import editor_python_test_tools.pyside_utils as pyside_utils from editor_python_test_tools.utils import Report +import azlmbr.legacy.general as general + + # fmt: off class Tests(): new_action = "File->New action working as expected" @@ -38,7 +29,8 @@ GENERAL_WAIT = 0.5 # seconds class TestFileMenuNewOpen: """ Summary: - When clicked on File->New, new script opens and File->Open should open the FileBrowser + When clicked on File->New, new script opens + File->Open should open the FileBrowser Expected Behavior: New and Open actions should work as expected. diff --git a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py index ce610b159b..b2a4b22056 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py @@ -7,26 +7,17 @@ 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. - - -Test case ID: T92563070 -Test Case Title: Graphs can be closed by clicking X on the Graph name tab -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563070 -Test case ID: T92563068 -Test Case Title: Save Prompt: User is prompted to save a graph on close after -creating a new graph -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563068 """ -import os -import sys from PySide2 import QtWidgets -import azlmbr.legacy.general as general import editor_python_test_tools.pyside_utils as pyside_utils from editor_python_test_tools.utils import TestHelper as helper from editor_python_test_tools.utils import Report +import azlmbr.legacy.general as general + + # fmt: off class Tests(): new_graph = "New graph created" @@ -45,7 +36,8 @@ class TestGraphCloseSavePrompt: Save Prompt is opened before closing. Expected Behavior: - New and Open actions should work as expected. + The Graph is closed. + Upon closing the graph, User is prompted whether or not to save changes. Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py b/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py index a93b6e61d1..754a0ae686 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py @@ -7,14 +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. - - -Test case ID: T92569079 -Test Case Title: View > Zoom In zooms the graph in -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569079 -Test case ID: T92569081 -Test Case Title: View > Zoom In zooms the graph out -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569081 """ @@ -93,7 +85,7 @@ def Graph_ZoomInZoomOut(): zin = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_ZoomIn", "type": QtWidgets.QAction}) zin.trigger() result = helper.wait_for_condition( - lambda: curr_m11 < graphics_view.transform().m11() and curr_m22 < graphics_view.transform().m22(), GENERAL_WAIT, + lambda: curr_m11 < graphics_view.transform().m11() and curr_m22 < graphics_view.transform().m22(), GENERAL_WAIT ) Report.result(Tests.zoom_in, result) @@ -102,7 +94,7 @@ def Graph_ZoomInZoomOut(): zout = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_ZoomOut", "type": QtWidgets.QAction}) zout.trigger() result = helper.wait_for_condition( - lambda: curr_m11 > graphics_view.transform().m11() and curr_m22 > graphics_view.transform().m22(), GENERAL_WAIT, + lambda: curr_m11 > graphics_view.transform().m11() and curr_m22 > graphics_view.transform().m22(), GENERAL_WAIT ) Report.result(Tests.zoom_out, result) @@ -114,7 +106,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(Graph_ZoomInZoomOut) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py index a45024cebf..ef794433f0 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py @@ -9,9 +9,10 @@ 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. """ + def init(): import os import sys - sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') - sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../EditorPythonTestTools/editor_python_test_tools') - \ No newline at end of file + + sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../automatedtesting_shared") + sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../EditorPythonTestTools/editor_python_test_tools") diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py index 33d3f4137a..7351e45212 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py @@ -7,10 +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. - -Test case ID: T92568982 -Test Case Title: Renaming variables in the Node Inspector -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568982 """ @@ -51,16 +47,16 @@ def NodeInspector_RenameVariable(): :return: None """ - - TEST_NAME = "test name" - from PySide2 import QtWidgets, QtCore, QtTest from PySide2.QtCore import Qt - import azlmbr.legacy.general as general import pyside_utils from utils import TestHelper as helper + import azlmbr.legacy.general as general + + TEST_NAME = "test name" + def open_tool(sc, dock_widget_name, pane_name): if sc.findChild(QtWidgets.QDockWidget, dock_widget_name) is None: action = pyside_utils.find_child_by_pattern(sc, {"text": pane_name, "type": QtWidgets.QAction}) @@ -121,12 +117,10 @@ def NodeInspector_RenameVariable(): general.close_pane("Script Canvas") - if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(NodeInspector_RenameVariable) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py index de30e46767..87a08346d0 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py @@ -7,10 +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. - -Test case ID: T92562993 -Test Case Title: Clicking the X button on the Search Box clears the currently entered string -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562993 """ @@ -24,11 +20,11 @@ class Tests(): def NodePalette_ClearSelection(): """ Summary: - We enter some string in the Node Palette Search box, and click on the X button to verify if the - search string got cleared. + Clicking the X button on the Search Box clears the currently entered string Expected Behavior: - Clicking the X button on the Search Box clears the currently entered string + After entering a string value into the Node Palette's search box and click on + the X button, the search box should be cleared Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) @@ -45,15 +41,13 @@ def NodePalette_ClearSelection(): :return: None """ - from PySide2 import QtWidgets + import pyside_utils from utils import TestHelper as helper import azlmbr.legacy.general as general - import pyside_utils - TEST_STRING = "Test String" # 1) Open Script Canvas window (Tools > Script Canvas) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py index 2ab76071a6..dfe1064a92 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py @@ -7,18 +7,13 @@ 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. - - -Test case ID: T92568940 -Test Case Title: Categories and Nodes can be selected -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568940 """ # fmt: off class Tests(): - category_selected = ("Category can be selected", "Category cannot be selected") - node_selected = ("Node can be selected", "Node cannot be selected") + category_selected = ("Category can be selected", "Category cannot be selected") + node_selected = ("Node can be selected", "Node cannot be selected") # fmt: on @@ -31,7 +26,8 @@ def NodePalette_SelectNode(): Categories and Nodes can be selected Expected Behavior: - When clicked on Node Palette, nodes and categories can be selected. + A category can be selected inside the Node Palette + A Node can be selected inside the Node Palette Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) @@ -54,11 +50,12 @@ def NodePalette_SelectNode(): NODE = "Find Path To Entity" from PySide2 import QtWidgets - import azlmbr.legacy.general as general import pyside_utils from utils import TestHelper as helper + import azlmbr.legacy.general as general + # 1) Open Script Canvas window (Tools > Script Canvas) general.idle_enable(True) general.open_pane("Script Canvas") @@ -98,7 +95,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(NodePalette_SelectNode) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py index 51b63c4268..c331157e82 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py @@ -7,30 +7,26 @@ 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. - -Test case ID: T92569253 // T92569254 -Test Case Title: On Entity Activated // On Entity Deactivated -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569253 // https://testrail.agscollab.com/index.php?/tests/view/92569254 """ # fmt: off class Tests(): - level_created = ("Successfully created temp level", "Failed to create temp level") - controller_exists = ("Successfully found controller entity", "Failed to find controller entity") - activated_exists = ("Successfully found activated entity", "Failed to find activated entity") - deactivated_exists = ("Successfully found deactivated entity","Failed to find deactivated entity") - start_states_correct = ("Start states set up successfully", "Start states set up incorrectly") - game_mode_entered = ("Successfully entered game mode" "Failed to enter game mode") - lines_found = ("Successfully found expected prints", "Failed to find expected prints") - game_mode_exited = ("Successfully exited game mode" "Failed to exit game mode") + level_created = ("Successfully created temp level", "Failed to create temp level") + controller_exists = ("Successfully found controller entity", "Failed to find controller entity") + activated_exists = ("Successfully found activated entity", "Failed to find activated entity") + deactivated_exists = ("Successfully found deactivated entity", "Failed to find deactivated entity") + start_states_correct = ("Start states set up successfully", "Start states set up incorrectly") + game_mode_entered = ("Successfully entered game mode" "Failed to enter game mode") + lines_found = ("Successfully found expected prints", "Failed to find expected prints") + game_mode_exited = ("Successfully exited game mode" "Failed to exit game mode") # fmt: on def OnEntityActivatedDeactivated_PrintMessage(): """ Summary: - Verify that the On Entity Activation node is working as expected + Verify that the On Entity Activated/On Entity Deactivated nodes are working as expected Expected Behavior: Upon entering game mode, the Controller entity will wait 1 second and then activate the ActivationTest @@ -55,9 +51,9 @@ def OnEntityActivatedDeactivated_PrintMessage(): """ import os - from utils import TestHelper as helper from editor_entity_utils import EditorEntity as Entity from utils import Report + from utils import TestHelper as helper from utils import Tracer import azlmbr.legacy.general as general @@ -69,33 +65,45 @@ def OnEntityActivatedDeactivated_PrintMessage(): controller_dict = { "name": "Controller", "status": "active", - "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "controller.scriptcanvas") + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "controller.scriptcanvas"), } activated_dict = { "name": "ActivationTest", "status": "inactive", - "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "activator.scriptcanvas") + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "activator.scriptcanvas"), } deactivated_dict = { "name": "DeactivationTest", "status": "active", - "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "deactivator.scriptcanvas") + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "deactivator.scriptcanvas"), } def get_asset(asset_path): - return azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False) + return azlmbr.asset.AssetCatalogRequestBus( + azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False + ) def setup_level(): - def create_editor_entity(entity_dict:dict, entity_to_activate:EditorEntity=None, entity_to_deactivate:EditorEntity=None) -> EditorEntity: + def create_editor_entity( + entity_dict: dict, entity_to_activate: EditorEntity = None, entity_to_deactivate: EditorEntity = None + ) -> EditorEntity: entity = Entity.create_editor_entity(entity_dict["name"]) entity.set_start_status(entity_dict["status"]) sc_component = entity.add_component("Script Canvas") - sc_component.set_component_property_value("Script Canvas Asset|Script Canvas Asset", get_asset(entity_dict["path"])) + sc_component.set_component_property_value( + "Script Canvas Asset|Script Canvas Asset", get_asset(entity_dict["path"]) + ) if entity_dict["name"] == "Controller": sc_component.get_property_tree() - sc_component.set_component_property_value("Properties|Variable Fields|Variables|[0]|Name,Value|Datum|Datum|EntityToActivate", entity_to_activate.id) - sc_component.set_component_property_value("Properties|Variable Fields|Variables|[1]|Name,Value|Datum|Datum|EntityToDeactivate", entity_to_deactivate.id) + sc_component.set_component_property_value( + "Properties|Variable Fields|Variables|[0]|Name,Value|Datum|Datum|EntityToActivate", + entity_to_activate.id, + ) + sc_component.set_component_property_value( + "Properties|Variable Fields|Variables|[1]|Name,Value|Datum|Datum|EntityToDeactivate", + entity_to_deactivate.id, + ) return entity activated = create_editor_entity(activated_dict) @@ -111,7 +119,7 @@ def OnEntityActivatedDeactivated_PrintMessage(): Report.critical_result(test_tuple, entity.id.IsValid()) return entity - def validate_start_state(entity:EditorEntity, expected_state:str): + def validate_start_state(entity: EditorEntity, expected_state: str): """ Validate that the starting state of the entity is correct, if it isn't then attempt to rectify and recheck. :return: bool: Whether state is set as expected @@ -177,8 +185,8 @@ def OnEntityActivatedDeactivated_PrintMessage(): if __name__ == "__main__": import ImportPathHelper as imports - imports.init() + imports.init() from utils import Report - + Report.start_test(OnEntityActivatedDeactivated_PrintMessage) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py index 666f052240..a72a302760 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py @@ -7,11 +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. - -Test case ID: C1702834 // C1702823 -Test Case Title: Opening pane // Closing pane -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702834 and - https://testrail.agscollab.com/index.php?/cases/view/1702823 """ @@ -26,10 +21,10 @@ class Tests(): def Opening_Closing_Pane(): """ Summary: - The Script Canvas window is opened to verify if Script canvas panes can be opened and closed. + The Script Canvas window is opened to verify if Script Canvas panes can be opened and closed. Expected Behavior: - The pane opens and closes successfully. + The panes open and close successfully. Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) @@ -115,7 +110,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from editor_python_test_tools.utils import Report Report.start_test(Opening_Closing_Pane) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py index fa5e9e6068..746efa500c 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py @@ -7,24 +7,19 @@ 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. - -Test case ID: C1702821 // C1702832 -Test Case Title: Retain visibility, size and location upon Script Canvas restart -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702821 and - https://testrail.agscollab.com/index.php?/cases/view/1702832 """ # fmt: off class Tests(): - relaunch_sc = ("Script Canvas window is relaunched", "Failed to relaunch Script Canvas window") - test_panes_visible = ("All the test panes are opened", "Failed to open one or more test panes") - close_pane_1 = ("Test pane 1 is closed", "Failed to close test pane 1") - visiblity_retained = ("Test pane retained its visiblity on SC restart", "Failed to retain visiblity of test pane on SC restart") - resize_pane_3 = ("Test pane 3 resized successfully", "Failed to resize Test pane 3") - size_retained = ("Test pane retained its size on SC restart", "Failed to retain size of test pane on SC restart") - location_changed = ("Location of test pane 2 changed successfully", "Failed to change locatio of test pane 2") - location_retained = ("Test pane retained its location on SC restart", "Failed to retain location of test pane on SC restart") + relaunch_sc = ("Script Canvas window is relaunched", "Failed to relaunch Script Canvas window") + test_panes_visible = ("All the test panes are opened", "Failed to open one or more test panes") + close_pane_1 = ("Test pane 1 is closed", "Failed to close test pane 1") + visibility_retained = ("Test pane retained its visibility on SC restart", "Failed to retain visibility of test pane on SC restart") + resize_pane_3 = ("Test pane 3 resized successfully", "Failed to resize Test pane 3") + size_retained = ("Test pane retained its size on SC restart", "Failed to retain size of test pane on SC restart") + location_changed = ("Location of test pane 2 changed successfully", "Failed to change location of test pane 2") + location_retained = ("Test pane retained its location on SC restart", "Failed to retain location of test pane on SC restart") # fmt: on @@ -35,7 +30,7 @@ def Pane_RetainOnSCRestart(): upon ScriptCanvas restart. Expected Behavior: - The ScriptCanvas pane retain it's visiblity, size and location upon ScriptCanvas restart. + The ScriptCanvas pane retain it's visibility, size and location upon ScriptCanvas restart. Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) @@ -44,7 +39,7 @@ def Pane_RetainOnSCRestart(): 4) Change dock location of test pane 2 5) Resize test pane 3 6) Relaunch Script Canvas - 7) Verify if test pane 1 retain its visiblity + 7) Verify if test pane 1 retain its visibility 8) Verify if location of test pane 2 is retained 9) Verify if size of test pane 3 is retained 10) Restore default layout and close SC window @@ -57,6 +52,10 @@ def Pane_RetainOnSCRestart(): :return: None """ + # Pyside imports + from PySide2 import QtCore, QtWidgets + from PySide2.QtCore import Qt + # Helper imports from utils import Report from utils import TestHelper as helper @@ -65,11 +64,6 @@ def Pane_RetainOnSCRestart(): # Open 3D Engine Imports import azlmbr.legacy.general as general - # Pyside imports - from PySide2 import QtCore, QtWidgets - from PySide2.QtCore import Qt - - # Constants TEST_PANE_1 = "NodePalette" # test visibility TEST_PANE_2 = "VariableManager" # test location TEST_PANE_3 = "NodeInspector" # test size @@ -130,10 +124,10 @@ def Pane_RetainOnSCRestart(): sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) Report.result(Tests.relaunch_sc, sc_visible) - # 7) Verify if test pane 1 retain its visiblity + # 7) Verify if test pane 1 retain its visibility editor_window = pyside_utils.get_editor_main_window() sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") - Report.result(Tests.visiblity_retained, not find_pane(sc, TEST_PANE_1).isVisible()) + Report.result(Tests.visibility_retained, not find_pane(sc, TEST_PANE_1).isVisible()) # 8) Verify if location of test pane 2 is retained sc_main = sc.findChild(QtWidgets.QMainWindow) @@ -158,7 +152,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(Pane_RetainOnSCRestart) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py index 180f577953..a870bea86f 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py @@ -7,10 +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. - -Test case ID: C1702829 -Test Case Title: Resizing pane -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702829 """ @@ -24,7 +20,7 @@ class Tests(): def Resizing_Pane(): """ Summary: - The Script Canvas window is opened to verify if Script canvas panes can be resized and scaled + The Script Canvas window is opened to verify if Script Canvas panes can be resized and scaled Expected Behavior: The pane is resized and scaled appropriately. @@ -33,7 +29,7 @@ def Resizing_Pane(): 1) Open Script Canvas window (Tools > Script Canvas) 2) Restore default layout 3) Make sure pane is opened - 4) Resize pane + 4) Resize pane and verify change 5) Restore default layout 6) Close Script Canvas window @@ -45,6 +41,8 @@ def Resizing_Pane(): :return: None """ + 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 @@ -52,9 +50,6 @@ def Resizing_Pane(): # Open 3D Engine imports import azlmbr.legacy.general as general - # Pyside imports - from PySide2 import QtWidgets - PANE_WIDGET = "NodePalette" SCALE_INT = 10 @@ -87,7 +82,7 @@ def Resizing_Pane(): Report.result(Tests.open_pane, pane.isVisible()) - # 4) Resize pane + # 4) Resize pane and verify change initial_size = pane.frameSize() pane.resize(initial_size.width() + SCALE_INT, initial_size.height() + SCALE_INT) new_size = pane.frameSize() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py index 38d60ad871..a1e177f5ec 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py @@ -7,11 +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. - -Test case ID: T92562986 -Test Case Title: Changing the assigned Script Canvas Asset on an entity properly updates -level functionality -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562986 """ @@ -58,7 +53,6 @@ def ScriptCanvas_ChangingAssets(): import azlmbr.math as math import azlmbr.asset as asset import azlmbr.bus as bus - import azlmbr.paths as paths LEVEL_NAME = "tmp_level" ASSET_1 = os.path.join("scriptcanvas", "ScriptCanvas_TwoComponents0.scriptcanvas") @@ -84,7 +78,6 @@ def ScriptCanvas_ChangingAssets(): Report.result(Tests.found_lines, find_expected_line(EXP_LINE)) helper.exit_game_mode(Tests.game_mode_exited) - # 1) Create temp level general.idle_enable(True) result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py index 896bee96e5..5117069b64 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py @@ -7,10 +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. - -Test case ID: T92563190 -Test Case Title: A single Entity with two Script Canvas components works properly -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563190 """ @@ -58,6 +54,7 @@ def ScriptCanvas_TwoComponents(): import hydra_editor_utils as hydra from utils import Report from utils import Tracer + import azlmbr.legacy.general as general import azlmbr.math as math import azlmbr.asset as asset @@ -112,7 +109,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(ScriptCanvas_TwoComponents) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py index 401e6c0271..53b3951c1a 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py @@ -7,16 +7,12 @@ 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. - -Test case ID: T92563191 -Test Case Title: Two Entities can use the same Graph asset successfully at RunTime -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563191 """ # fmt: off class Tests(): - level_created = ("New level created", "New level not created") + level_created = ("New level created successfully", "New level failed to create") game_mode_entered = ("Game Mode successfully entered", "Game mode failed to enter") game_mode_exited = ("Game Mode successfully exited", "Game mode failed to exited") found_lines = ("Expected log lines were found", "Expected log lines were not found") @@ -27,7 +23,7 @@ def ScriptCanvas_TwoEntities(): """ Summary: Two Entities can use the same Graph asset successfully at RunTime. The script canvas asset - attached to the enties will print the respective entity names. + attached to the entities will print the respective entity names. Expected Behavior: When game mode is entered, respective strings of different entities should be printed. @@ -49,9 +45,10 @@ def ScriptCanvas_TwoEntities(): import os + import hydra_editor_utils as hydra from utils import TestHelper as helper from utils import Tracer - import hydra_editor_utils as hydra + import azlmbr.legacy.general as general import azlmbr.math as math import azlmbr.asset as asset diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py index d671229cdf..f58d6007a1 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py @@ -7,10 +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. - -Test case ID: T92567321 -Test Case Title: Script Events: Can send and receive a script event across multiple entities successfully -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92567321 """ @@ -28,7 +24,8 @@ class Tests(): def ScriptEvents_SendReceiveAcrossMultiple(): """ Summary: - EntityA and EntityB will be created in a level. Attached to both will be a Script Canvas component. The Script Event created for the test will be sent from EntityA to EntityB. + EntityA and EntityB will be created in a level. Attached to both will be a Script Canvas component. + The Script Event created for the test will be sent from EntityA to EntityB. Expected Behavior: The output of the Script Event should be printed to the console @@ -50,7 +47,7 @@ def ScriptEvents_SendReceiveAcrossMultiple(): :return: None """ import os - + from editor_entity_utils import EditorEntity as Entity from utils import Report from utils import TestHelper as helper @@ -66,20 +63,19 @@ def ScriptEvents_SendReceiveAcrossMultiple(): "assetA": os.path.join("ScriptCanvas", f"{ASSET_PREFIX}A.scriptcanvas"), "assetB": os.path.join("ScriptCanvas", f"{ASSET_PREFIX}B.scriptcanvas"), } - sc_for_entities = { - "EntityA": asset_paths["assetA"], - "EntityB": asset_paths["assetB"] - } + sc_for_entities = {"EntityA": asset_paths["assetA"], "EntityB": asset_paths["assetB"]} EXPECTED_LINES = ["Incoming Message Received"] def get_asset(asset_path): - return azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False) + return azlmbr.asset.AssetCatalogRequestBus( + azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False + ) def create_editor_entity(name, sc_asset): entity = Entity.create_editor_entity(name) sc_comp = entity.add_component("Script Canvas") sc_comp.set_component_property_value("Script Canvas Asset|Script Canvas Asset", get_asset(sc_asset)) - Report.critical_result(Tests.__dict__[name.lower()+"_created"], entity.id.isValid()) + Report.critical_result(Tests.__dict__[name.lower() + "_created"], entity.id.isValid()) def locate_expected_lines(line_list: list): found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] @@ -113,8 +109,8 @@ def ScriptEvents_SendReceiveAcrossMultiple(): if __name__ == "__main__": import ImportPathHelper as imports - imports.init() + imports.init() from utils import Report Report.start_test(ScriptEvents_SendReceiveAcrossMultiple) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py index b5e26d14ae..3f343221b0 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py @@ -7,10 +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. - -Test case ID: T92567320 -Test Case Title: Script Events: Can send and receive a script event successfully -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92567320 """ @@ -104,7 +100,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(ScriptEvents_SendReceiveSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index d87f2986bf..24e8eeda11 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -29,22 +29,18 @@ TEST_DIRECTORY = os.path.dirname(__file__) @pytest.mark.parametrize("launcher_platform", ['windows_editor']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) class TestAutomation(TestAutomationBase): - @pytest.mark.test_case_id("C1702834", "C1702823") def test_Opening_Closing_Pane(self, request, workspace, editor, launcher_platform): from . import Opening_Closing_Pane as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("C1702824") def test_Docking_Pane(self, request, workspace, editor, launcher_platform): from . import Docking_Pane as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("C1702829") def test_Resizing_Pane(self, request, workspace, editor, launcher_platform): from . import Resizing_Pane as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92563190") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptCanvas_TwoComponents(self, request, workspace, editor, launcher_platform, level): def teardown(): @@ -54,7 +50,6 @@ class TestAutomation(TestAutomationBase): from . import ScriptCanvas_TwoComponents as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92562986") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptCanvas_ChangingAssets(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -64,18 +59,14 @@ class TestAutomation(TestAutomationBase): from . import ScriptCanvas_ChangingAssets as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569079", "T92569081") def test_Graph_ZoomInZoomOut(self, request, workspace, editor, launcher_platform): from . import Graph_ZoomInZoomOut as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92568940") def test_NodePalette_SelectNode(self, request, workspace, editor, launcher_platform): from . import NodePalette_SelectNode as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569253") - @pytest.mark.test_case_id("T92569254") @pytest.mark.parametrize("level", ["tmp_level"]) def test_OnEntityActivatedDeactivated_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -85,12 +76,10 @@ class TestAutomation(TestAutomationBase): from . import OnEntityActivatedDeactivated_PrintMessage as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92562993") def test_NodePalette_ClearSelection(self, request, workspace, editor, launcher_platform, project): from . import NodePalette_ClearSelection as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92563191") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptCanvas_TwoEntities(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -100,7 +89,6 @@ class TestAutomation(TestAutomationBase): from . import ScriptCanvas_TwoEntities as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569013") def test_AssetEditor_CreateScriptEventFile(self, request, workspace, editor, launcher_platform, project): def teardown(): file_system.delete( @@ -113,22 +101,18 @@ class TestAutomation(TestAutomationBase): from . import AssetEditor_CreateScriptEventFile as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569165", "T92569167", "T92569168", "T92569170") def test_Toggle_ScriptCanvasTools(self, request, workspace, editor, launcher_platform): from . import Toggle_ScriptCanvasTools as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92568982") def test_NodeInspector_RenameVariable(self, request, workspace, editor, launcher_platform, project): from . import NodeInspector_RenameVariable as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569137") def test_Debugging_TargetMultipleGraphs(self, request, workspace, editor, launcher_platform, project): from . import Debugging_TargetMultipleGraphs as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92568856") @pytest.mark.parametrize("level", ["tmp_level"]) def test_Debugging_TargetMultipleEntities(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -138,17 +122,14 @@ class TestAutomation(TestAutomationBase): from . import Debugging_TargetMultipleEntities as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569049", "T92569051") def test_EditMenu_UndoRedo(self, request, workspace, editor, launcher_platform, project): from . import EditMenu_UndoRedo as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("C1702825", "C1702831") def test_UnDockedPane_CloseSCWindow(self, request, workspace, editor, launcher_platform): from . import UnDockedPane_CloseSCWindow as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92562978") @pytest.mark.parametrize("level", ["tmp_level"]) def test_Entity_AddScriptCanvasComponent(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -158,12 +139,10 @@ class TestAutomation(TestAutomationBase): from . import Entity_AddScriptCanvasComponent as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("C1702821", "C1702832") def test_Pane_RetainOnSCRestart(self, request, workspace, editor, launcher_platform): from . import Pane_RetainOnSCRestart as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92567321") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptEvents_SendReceiveAcrossMultiple(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -173,7 +152,6 @@ class TestAutomation(TestAutomationBase): from . import ScriptEvents_SendReceiveAcrossMultiple as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92567320") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptEvents_SendReceiveSuccessfully(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -193,7 +171,6 @@ class TestScriptCanvasTests(object): The following tests use hydra_test_utils.py to launch the editor and validate the results. """ - @pytest.mark.test_case_id("T92569037", "T92569039") def test_FileMenu_New_Open(self, request, editor, launcher_platform): expected_lines = [ "File->New action working as expected: True", @@ -203,7 +180,6 @@ class TestScriptCanvasTests(object): request, TEST_DIRECTORY, editor, "FileMenu_New_Open.py", expected_lines, auto_test_mode=False, timeout=60, ) - @pytest.mark.test_case_id("T92568942") def test_AssetEditor_NewScriptEvent(self, request, editor, launcher_platform): expected_lines = [ "New Script event action found: True", @@ -221,7 +197,6 @@ class TestScriptCanvasTests(object): timeout=60, ) - @pytest.mark.test_case_id("T92563068", "T92563070") def test_GraphClose_SavePrompt(self, request, editor, launcher_platform): expected_lines = [ "New graph created: True", @@ -238,7 +213,6 @@ class TestScriptCanvasTests(object): timeout=60, ) - @pytest.mark.test_case_id("T92564789", "T92568873") def test_VariableManager_CreateDeleteVars(self, request, editor, launcher_platform): var_types = ["Boolean", "Color", "EntityID", "Number", "String", "Transform", "Vector2", "Vector3", "Vector4"] expected_lines = [f"Success: {var_type} variable is created" for var_type in var_types] diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py b/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py index 4024e28277..2b935a74b3 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py @@ -7,17 +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. - -Test case ID: C92569165, C92569167, C92569168, C92569170 -Test Case Title: Tools > Node Palette toggles the Node Palette - Tools > Node Inspector toggles the Node Inspector - Tools > Bookmarks toggles the Bookmarks - Tools > Variable Manager toggles the Variable Manager - -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/92569165 - https://testrail.agscollab.com/index.php?/cases/view/92569167 - https://testrail.agscollab.com/index.php?/cases/view/92569168 - https://testrail.agscollab.com/index.php?/cases/view/92569170 """ @@ -63,6 +52,8 @@ def Toggle_ScriptCanvasTools(): :return: None """ + from PySide2 import QtWidgets + from utils import Report from utils import TestHelper as helper import pyside_utils @@ -70,9 +61,6 @@ def Toggle_ScriptCanvasTools(): # Open 3D Engine imports import azlmbr.legacy.general as general - # Pyside imports - from PySide2 import QtWidgets - def click_menu_option(window, option_text): action = pyside_utils.find_child_by_pattern(window, {"text": option_text, "type": QtWidgets.QAction}) action.trigger() @@ -131,7 +119,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(Toggle_ScriptCanvasTools) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py b/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py index 875f28ec95..fbdba8fb38 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py @@ -7,11 +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. - -Test case ID: C1702825 // C1702831 -Test Case Title: Undocking // Closing script canvas with the pane floating -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702825 & - https://testrail.agscollab.com/index.php?/cases/view/1702831 """ @@ -47,6 +42,8 @@ def UnDockedPane_CloseSCWindow(): :return: None """ + from PySide2 import QtWidgets + # Helper imports from utils import Report from utils import TestHelper as helper @@ -55,9 +52,6 @@ def UnDockedPane_CloseSCWindow(): # Open 3D Engine imports import azlmbr.legacy.general as general - # Pyside imports - from PySide2 import QtWidgets - TEST_PANE = "NodePalette" # Chosen most commonly used pane def click_menu_option(window, option_text): @@ -122,7 +116,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(UnDockedPane_CloseSCWindow) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py index 6facc324d4..8f7557c01e 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py @@ -7,20 +7,13 @@ 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. - -Test case ID: T92564789 -Test Case Title: Each Variable type can be created -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92564789 -Test case ID: T92568873 -Test Case Title: Each Variable type can be deleted -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568873 """ def VariableManager_CreateDeleteVars(): """ Summary: - Each variable type can be created and deleted in variable manager. + Creating and deleting each type of variable in the Variable Manager pane Expected Behavior: Each variable type can be created and deleted in variable manager. @@ -43,15 +36,13 @@ def VariableManager_CreateDeleteVars(): """ from PySide2 import QtWidgets, QtCore, QtTest - from PySide2.QtCore import Qt from utils import TestHelper as helper + import pyside_utils import azlmbr.legacy.general as general - import pyside_utils - def generate_test_tuple(var_type, action): return (f"{var_type} variable is {action}d", f"{var_type} variable is not {action}d") From aa51233536a55816324da9d41fff6afe4e3970c9 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Thu, 6 May 2021 16:18:13 -0700 Subject: [PATCH 019/231] Add Asset serialization for Ctrl+G and related net interfaces --- .../AzNetworking/TcpTransport/TcpSocket.cpp | 4 +- .../AutoGen/Multiplayer.AutoPackets.xml | 6 ++ .../MultiplayerEditorSystemComponent.cpp | 93 +++++++++++++++++-- .../Editor/MultiplayerEditorSystemComponent.h | 2 + .../Source/MultiplayerSystemComponent.cpp | 21 +++++ .../Code/Source/MultiplayerSystemComponent.h | 4 +- .../Code/Source/MultiplayerToolsModule.cpp | 10 ++ .../Code/Source/MultiplayerToolsModule.h | 5 +- 8 files changed, 132 insertions(+), 13 deletions(-) diff --git a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpSocket.cpp b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpSocket.cpp index 78020cb09d..e8c30d0816 100644 --- a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpSocket.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpSocket.cpp @@ -116,8 +116,8 @@ namespace AzNetworking int32_t TcpSocket::Receive(uint8_t* outData, uint32_t size) const { - AZ_Assert(size > 0, "Invalid data size for send"); - AZ_Assert(outData != nullptr, "NULL data pointer passed to send"); + AZ_Assert(size > 0, "Invalid data size for receive"); + AZ_Assert(outData != nullptr, "NULL data pointer passed to receive"); if (!IsOpen()) { return SocketOpResultErrorNotOpen; diff --git a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml index 5de466899c..21faefa880 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml @@ -57,4 +57,10 @@ + + + + + + diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp index 0850b858a2..15f00bdf80 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp @@ -10,23 +10,32 @@ * */ +#include #include +#include +#include #include #include +#include #include #include #include #include +#include #include namespace Multiplayer { + static const AZStd::string_view s_networkInterfaceName("MultiplayerEditorServerInterface"); + using namespace AzNetworking; AZ_CVAR(bool, editorsv_enabled, false, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Whether Editor launching a local server to connect to is supported"); AZ_CVAR(AZ::CVarFixedString, editorsv_process, "", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The server executable that should be run. Empty to use the current project's ServerLauncher"); + AZ_CVAR(AZ::CVarFixedString, sv_serveraddr, "127.0.0.1", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The address of the server to connect to"); + AZ_CVAR(uint16_t, sv_port, 30091, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The port that the multiplayer editor gem will bind to for traffic"); void MultiplayerEditorSystemComponent::Reflect(AZ::ReflectContext* context) { @@ -61,6 +70,16 @@ namespace Multiplayer { AzFramework::GameEntityContextEventBus::Handler::BusConnect(); AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); + + // Setup a network interface handled by MultiplayerSystemComponent + if (m_editorNetworkInterface == nullptr) + { + AZ::Entity* systemEntity = this->GetEntity(); + MultiplayerSystemComponent* mpSysComponent = systemEntity->FindComponent(); + + m_editorNetworkInterface = AZ::Interface::Get()->CreateNetworkInterface( + AZ::Name(s_networkInterfaceName), ProtocolType::Tcp, TrustZone::ExternalClientToServer, *mpSysComponent); + } } void MultiplayerEditorSystemComponent::Deactivate() @@ -97,25 +116,52 @@ namespace Multiplayer m_serverProcess->TerminateProcess(0); m_serverProcess = nullptr; } + if (m_editorNetworkInterface) + { + // Disconnect the interface, connection management will clean it up + m_editorNetworkInterface->Disconnect(m_editorConnId, AzNetworking::DisconnectReason::TerminatedByUser); + m_editorConnId = AzNetworking::InvalidConnectionId; + } break; } } void MultiplayerEditorSystemComponent::OnGameEntitiesStarted() { + auto prefabEditorEntityOwnershipInterface = AZ::Interface::Get(); + if (!prefabEditorEntityOwnershipInterface) + { + AZ_Error("MultiplayerEditor", prefabEditorEntityOwnershipInterface != nullptr, "PrefabEditorEntityOwnershipInterface unavailable"); + } + const AZStd::vector>& assetData = prefabEditorEntityOwnershipInterface->GetPlayInEditorAssetData(); + + AZStd::vector buffer; + AZ::IO::ByteContainerStream byteStream(&buffer); + + // Serialize Asset information and AssetData into a potentially large buffer + for (auto asset : assetData) + { + AZ::Data::AssetId assetId = asset.GetId(); + AZ::Data::AssetType assetType = asset.GetType(); + const AZStd::string& assetHint = asset.GetHint(); + AZ::IO::SizeType assetHintSize = assetHint.size(); + AZ::Data::AssetLoadBehavior assetLoadBehavior = asset.GetAutoLoadBehavior(); + + byteStream.Write(sizeof(AZ::Data::AssetId), reinterpret_cast(&assetId)); + byteStream.Write(sizeof(AZ::Data::AssetType), reinterpret_cast(&assetType)); + byteStream.Write(sizeof(assetHintSize), reinterpret_cast(&assetHintSize)); + byteStream.Write(assetHint.size(), assetHint.c_str()); + byteStream.Write(sizeof(AZ::Data::AssetLoadBehavior), reinterpret_cast(&assetLoadBehavior)); + + AZ::Utils::SaveObjectToStream(byteStream, AZ::DataStream::ST_BINARY, asset.GetData(), asset.GetData()->GetType()); + } + // BeginGameMode and Prefab Processing have completed at this point IMultiplayerTools* mpTools = AZ::Interface::Get(); if (editorsv_enabled && mpTools != nullptr && mpTools->DidProcessNetworkPrefabs()) { AZ::TickBus::Handler::BusConnect(); - auto prefabEditorEntityOwnershipInterface = AZ::Interface::Get(); - if (!prefabEditorEntityOwnershipInterface) - { - AZ_Error("MultiplayerEditor", prefabEditorEntityOwnershipInterface != nullptr, "PrefabEditorEntityOwnershipInterface unavailable"); - } - const AZStd::vector>& assetData = prefabEditorEntityOwnershipInterface->GetPlayInEditorAssetData(); - if (assetData.size() > 0) { // Assemble the server's path @@ -154,6 +200,39 @@ namespace Multiplayer processLaunchInfo, AzFramework::ProcessCommunicationType::COMMUNICATOR_TYPE_NONE); } } + + // Now that the server has launched, attempt to connect the NetworkInterface + const AZ::CVarFixedString remoteAddress = sv_serveraddr; + m_editorConnId = m_editorNetworkInterface->Connect( + AzNetworking::IpAddress(remoteAddress.c_str(), sv_port, AzNetworking::ProtocolType::Tcp)); + + // Read the buffer into EditorServerInit packets until we've flushed the whole thing + byteStream.Seek(0, AZ::IO::GenericStream::SeekMode::ST_SEEK_BEGIN); + + while (byteStream.GetCurPos() < byteStream.GetLength()) + { + MultiplayerPackets::EditorServerInit packet; + AzNetworking::TcpPacketEncodingBuffer& outBuffer = packet.ModifyAssetData(); + + // Size the packet's buffer appropriately + size_t readSize = TcpPacketEncodingBuffer::GetCapacity(); + size_t byteStreamSize = byteStream.GetLength() - byteStream.GetCurPos(); + if (byteStreamSize < readSize) + { + readSize = byteStreamSize; + } + + outBuffer.Resize(readSize); + byteStream.Read(readSize, outBuffer.GetBuffer()); + + // If we've run out of buffer, mark that we're done + if (byteStream.GetCurPos() == byteStream.GetLength()) + { + packet.SetLastUpdate(true); + } + m_editorNetworkInterface->SendReliablePacket(m_editorConnId, packet); + } + } void MultiplayerEditorSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.h b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.h index 31ecdf83a3..d43d8747b9 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.h @@ -81,5 +81,7 @@ namespace Multiplayer IEditor* m_editor = nullptr; AzFramework::ProcessWatcher* m_serverProcess = nullptr; + AzNetworking::ConnectionId m_editorConnId; + AzNetworking::INetworkInterface* m_editorNetworkInterface = nullptr; }; } diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 03c661ab03..3c1e142d96 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -57,7 +57,9 @@ namespace Multiplayer using namespace AzNetworking; static const AZStd::string_view s_networkInterfaceName("MultiplayerNetworkInterface"); + static const AZStd::string_view s_networkEditorInterfaceName("MultiplayerEditorNetworkInterface"); static constexpr uint16_t DefaultServerPort = 30090; + static constexpr uint16_t DefaultServerEditorPort = 30091; AZ_CVAR(uint16_t, cl_clientport, 0, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The port to bind to for game traffic when connecting to a remote host, a value of 0 will select any available port"); AZ_CVAR(AZ::CVarFixedString, cl_serveraddr, "127.0.0.1", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The address of the remote server or host to connect to"); @@ -397,6 +399,19 @@ namespace Multiplayer return false; } + bool MultiplayerSystemComponent::HandleRequest + ( + [[maybe_unused]] AzNetworking::IConnection* connection, + [[maybe_unused]] const IPacketHeader& packetHeader, + [[maybe_unused]] MultiplayerPackets::EditorServerInit& packet + ) + { +#if !defined(_RELEASE) + // Support Editor Server Init for all non-release targets +#endif + return true; + } + ConnectResult MultiplayerSystemComponent::ValidateConnect ( [[maybe_unused]] const IpAddress& remoteAddress, @@ -492,6 +507,12 @@ namespace Multiplayer { if (multiplayerType == MultiplayerAgentType::ClientServer || multiplayerType == MultiplayerAgentType::DedicatedServer) { +#if !defined(_RELEASE) + m_networkEditorInterface = AZ::Interface::Get()->CreateNetworkInterface( + AZ::Name(s_networkEditorInterfaceName), ProtocolType::Tcp, TrustZone::ExternalClientToServer, *this); + m_networkEditorInterface->Listen(DefaultServerEditorPort); +#endif + m_initEvent.Signal(m_networkInterface); const AZ::Aabb worldBounds = AZ::Aabb::CreateFromMinMax(AZ::Vector3(-16384.0f), AZ::Vector3(16384.0f)); diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index f25e530b61..e77fa129b0 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -72,7 +72,8 @@ namespace Multiplayer bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerPackets::NotifyClientMigration& packet); bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerPackets::EntityMigration& packet); bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerPackets::ReadyForEntityUpdates& packet); - + bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerPackets::EditorServerInit& packet); + //! IConnectionListener interface //! @{ AzNetworking::ConnectResult ValidateConnect(const AzNetworking::IpAddress& remoteAddress, const AzNetworking::IPacketHeader& packetHeader, AzNetworking::ISerializer& serializer) override; @@ -109,6 +110,7 @@ namespace Multiplayer AZ_CONSOLEFUNC(MultiplayerSystemComponent, DumpStats, AZ::ConsoleFunctorFlags::Null, "Dumps stats for the current multiplayer session"); AzNetworking::INetworkInterface* m_networkInterface = nullptr; + AzNetworking::INetworkInterface* m_networkEditorInterface = nullptr; AZ::ConsoleCommandInvokedEvent::Handler m_consoleCommandHandler; AZ::ThreadSafeDeque m_cvarCommands; diff --git a/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.cpp b/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.cpp index a5df3c1dc5..ae91999a0c 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.cpp @@ -24,6 +24,16 @@ namespace Multiplayer NetworkPrefabProcessor::Reflect(context); } + void MultiplayerToolsSystemComponent::Activate() + { + AZ::Interface::Register(this); + } + + void MultiplayerToolsSystemComponent::Deactivate() + { + AZ::Interface::Unregister(this); + } + bool MultiplayerToolsSystemComponent::DidProcessNetworkPrefabs() { return m_didProcessNetPrefabs; diff --git a/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.h b/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.h index 82d0415c5a..181a971150 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerToolsModule.h @@ -31,9 +31,8 @@ namespace Multiplayer ~MultiplayerToolsSystemComponent() override = default; /// AZ::Component overrides. - void Activate() override {}; - - void Deactivate() override {}; + void Activate() override; + void Deactivate() override; bool DidProcessNetworkPrefabs() override; From 6f3b46dc29fd54bf781c05024263e38e6c5596ea Mon Sep 17 00:00:00 2001 From: Peng Date: Thu, 6 May 2021 16:36:13 -0700 Subject: [PATCH 020/231] ATOM-15266 [RHI][Vulkan][Android] Use warning on fragment pool error due to recreation of the memory pool in subsequent step JIRA: https://jira.agscollab.com/browse/ATOM-15266 --- .../Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp | 11 ++++++++++- Gems/Atom/RHI/Vulkan/Code/Source/RHI/Vulkan.cpp | 2 ++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp index 8eee7ef726..8769aaa1f9 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp @@ -239,7 +239,16 @@ namespace AZ allocInfo.pSetLayouts = &nativeLayout; VkResult result = vkAllocateDescriptorSets(descriptor.m_device->GetNativeDevice(), &allocInfo, &m_nativeDescriptorSet); - AssertSuccess(result); + if (result == VK_ERROR_FRAGMENTED_POOL) + { + // fragmented pool will be re-created subsequently, so warning only + AZ_Warning("Vulkan RHI", false, "Fragmented pool"); + } + else + { + AssertSuccess(result); + } + if (result != VK_SUCCESS) { return result; diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Vulkan.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Vulkan.cpp index 90a4c2f9c2..311d3436de 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Vulkan.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Vulkan.cpp @@ -96,6 +96,8 @@ namespace AZ return "Validation failed"; case VK_ERROR_OUT_OF_POOL_MEMORY: return "Pool is out of memory"; + case VK_ERROR_FRAGMENTED_POOL: + return "Fragmented pool"; default: return "Unknown error"; } From be0f69d081a5643a7c298f84eb4f256709c05092 Mon Sep 17 00:00:00 2001 From: zsolleci Date: Fri, 7 May 2021 11:47:39 -0500 Subject: [PATCH 021/231] updated files to fit name convention --- ...ugger_HappyPath_TargetMultipleEntities.py} | 4 +- ...ebugger_HappyPath_TargetMultipleGraphs.py} | 4 +- ...doRedo.py => EditMenu_Default_UndoRedo.py} | 4 +- ...ity_HappyPath_AddScriptCanvasComponent.py} | 4 +- ...Open.py => FileMenu_Default_NewAndOpen.py} | 4 +- ...pt.py => GraphClose_Default_SavePrompt.py} | 4 +- ...ut.py => Graph_HappyPath_ZoomInZoomOut.py} | 4 +- ...entButton_HappyPath_ContainsSCCategory.py} | 0 ...odeInspector_HappyPath_VariableRenames.py} | 4 +- ...=> NodePalette_HappyPath_CanSelectNode.py} | 4 +- ...> NodePalette_HappyPath_ClearSelection.py} | 4 +- ...atedDeactivated_HappyPath_PrintMessage.py} | 4 +- ...t.py => Pane_Default_RetainOnSCRestart.py} | 4 +- ...ane.py => Pane_HappyPath_DocksProperly.py} | 4 +- ...> Pane_HappyPath_OpenCloseSuccessfully.py} | 4 +- ...e.py => Pane_HappyPath_ResizesProperly.py} | 4 +- ...py => Pane_Undocked_ClosesSuccessfully.py} | 4 +- ...iptCanvasTools_Toggle_OpenCloseSuccess.py} | 4 +- ...tCanvas_ChangingAssets_ComponentStable.py} | 4 +- ...vas_TwoComponents_InteractSuccessfully.py} | 4 +- ...ptCanvas_TwoEntities_UseSimultaneously.py} | 4 +- ...iptEvent_HappyPath_CreatedWithoutError.py} | 0 ...Events_Default_SendReceiveSuccessfully.py} | 4 +- ...ts_HappyPath_SendReceiveAcrossMultiple.py} | 4 +- .../PythonTests/scripting/TestSuite_Active.py | 104 +++++++++--------- ...riableManager_Default_CreateDeleteVars.py} | 4 +- 26 files changed, 98 insertions(+), 98 deletions(-) rename AutomatedTesting/Gem/PythonTests/scripting/{Debugging_TargetMultipleEntities.py => Debugger_HappyPath_TargetMultipleEntities.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{Debugging_TargetMultipleGraphs.py => Debugger_HappyPath_TargetMultipleGraphs.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{EditMenu_UndoRedo.py => EditMenu_Default_UndoRedo.py} (98%) rename AutomatedTesting/Gem/PythonTests/scripting/{Entity_AddScriptCanvasComponent.py => Entity_HappyPath_AddScriptCanvasComponent.py} (96%) rename AutomatedTesting/Gem/PythonTests/scripting/{FileMenu_New_Open.py => FileMenu_Default_NewAndOpen.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{GraphClose_SavePrompt.py => GraphClose_Default_SavePrompt.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{Graph_ZoomInZoomOut.py => Graph_HappyPath_ZoomInZoomOut.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{AssetEditor_NewScriptEvent.py => NewScriptEventButton_HappyPath_ContainsSCCategory.py} (100%) rename AutomatedTesting/Gem/PythonTests/scripting/{NodeInspector_RenameVariable.py => NodeInspector_HappyPath_VariableRenames.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{NodePalette_SelectNode.py => NodePalette_HappyPath_CanSelectNode.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{NodePalette_ClearSelection.py => NodePalette_HappyPath_ClearSelection.py} (96%) rename AutomatedTesting/Gem/PythonTests/scripting/{OnEntityActivatedDeactivated_PrintMessage.py => OnEntityActivatedDeactivated_HappyPath_PrintMessage.py} (98%) rename AutomatedTesting/Gem/PythonTests/scripting/{Pane_RetainOnSCRestart.py => Pane_Default_RetainOnSCRestart.py} (98%) rename AutomatedTesting/Gem/PythonTests/scripting/{Docking_Pane.py => Pane_HappyPath_DocksProperly.py} (97%) mode change 100755 => 100644 rename AutomatedTesting/Gem/PythonTests/scripting/{Opening_Closing_Pane.py => Pane_HappyPath_OpenCloseSuccessfully.py} (97%) mode change 100755 => 100644 rename AutomatedTesting/Gem/PythonTests/scripting/{Resizing_Pane.py => Pane_HappyPath_ResizesProperly.py} (97%) mode change 100755 => 100644 rename AutomatedTesting/Gem/PythonTests/scripting/{UnDockedPane_CloseSCWindow.py => Pane_Undocked_ClosesSuccessfully.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{Toggle_ScriptCanvasTools.py => ScriptCanvasTools_Toggle_OpenCloseSuccess.py} (98%) rename AutomatedTesting/Gem/PythonTests/scripting/{ScriptCanvas_ChangingAssets.py => ScriptCanvas_ChangingAssets_ComponentStable.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{ScriptCanvas_TwoComponents.py => ScriptCanvas_TwoComponents_InteractSuccessfully.py} (96%) rename AutomatedTesting/Gem/PythonTests/scripting/{ScriptCanvas_TwoEntities.py => ScriptCanvas_TwoEntities_UseSimultaneously.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{AssetEditor_CreateScriptEventFile.py => ScriptEvent_HappyPath_CreatedWithoutError.py} (100%) rename AutomatedTesting/Gem/PythonTests/scripting/{ScriptEvents_SendReceiveSuccessfully.py => ScriptEvents_Default_SendReceiveSuccessfully.py} (96%) rename AutomatedTesting/Gem/PythonTests/scripting/{ScriptEvents_SendReceiveAcrossMultiple.py => ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{VariableManager_CreateDeleteVars.py => VariableManager_Default_CreateDeleteVars.py} (97%) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleEntities.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py rename to AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleEntities.py index 71e24139f4..2c36062acf 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleEntities.py @@ -21,7 +21,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -def Debugging_TargetMultipleEntities(): +def Debugger_HappyPath_TargetMultipleEntities(): """ Summary: Multiple Entities can be targeted in the Debugger tool @@ -135,4 +135,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Debugging_TargetMultipleEntities) + Report.start_test(Debugger_HappyPath_TargetMultipleEntities) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleGraphs.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py rename to AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleGraphs.py index 342f8f3cd4..906c198d43 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleGraphs.py @@ -19,7 +19,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -def Debugging_TargetMultipleGraphs(): +def Debugger_HappyPath_TargetMultipleGraphs(): """ Summary: Multiple Graphs can be targeted in the Debugger tool @@ -103,4 +103,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Debugging_TargetMultipleGraphs) + Report.start_test(Debugger_HappyPath_TargetMultipleGraphs) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_Default_UndoRedo.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py rename to AutomatedTesting/Gem/PythonTests/scripting/EditMenu_Default_UndoRedo.py index 246a8894ba..34345cf36b 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_Default_UndoRedo.py @@ -18,7 +18,7 @@ class Tests(): # fmt: on -def EditMenu_UndoRedo(): +def EditMenu_Default_UndoRedo(): """ Summary: Edit > Undo undoes the last action @@ -110,4 +110,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(EditMenu_UndoRedo) + Report.start_test(EditMenu_Default_UndoRedo) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py b/AutomatedTesting/Gem/PythonTests/scripting/Entity_HappyPath_AddScriptCanvasComponent.py similarity index 96% rename from AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py rename to AutomatedTesting/Gem/PythonTests/scripting/Entity_HappyPath_AddScriptCanvasComponent.py index 4e8576d892..22530c90c1 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Entity_HappyPath_AddScriptCanvasComponent.py @@ -20,7 +20,7 @@ class Tests(): # fmt: on -def Entity_AddScriptCanvasComponent(): +def Entity_HappyPath_AddScriptCanvasComponent(): """ Summary: Script Canvas Component can be added to an entity @@ -80,4 +80,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Entity_AddScriptCanvasComponent) + Report.start_test(Entity_HappyPath_AddScriptCanvasComponent) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_Default_NewAndOpen.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py rename to AutomatedTesting/Gem/PythonTests/scripting/FileMenu_Default_NewAndOpen.py index 094598e51d..4771a95ab7 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_Default_NewAndOpen.py @@ -26,7 +26,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -class TestFileMenuNewOpen: +class TestFileMenuDefaultNewOpen: """ Summary: When clicked on File->New, new script opens @@ -86,5 +86,5 @@ class TestFileMenuNewOpen: general.close_pane("Script Canvas") -test = TestFileMenuNewOpen() +test = TestFileMenuDefaultNewOpen() test.run_test() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_Default_SavePrompt.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py rename to AutomatedTesting/Gem/PythonTests/scripting/GraphClose_Default_SavePrompt.py index b2a4b22056..9720c846c7 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_Default_SavePrompt.py @@ -29,7 +29,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -class TestGraphCloseSavePrompt: +class TestGraphClose_Default_SavePrompt: """ Summary: The graph is closed when x button is clicked. @@ -98,5 +98,5 @@ class TestGraphCloseSavePrompt: general.close_pane("Script Canvas") -test = TestGraphCloseSavePrompt() +test = TestGraphClose_Default_SavePrompt() test.run_test() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py b/AutomatedTesting/Gem/PythonTests/scripting/Graph_HappyPath_ZoomInZoomOut.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py rename to AutomatedTesting/Gem/PythonTests/scripting/Graph_HappyPath_ZoomInZoomOut.py index 754a0ae686..11c83bb779 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Graph_HappyPath_ZoomInZoomOut.py @@ -20,7 +20,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -def Graph_ZoomInZoomOut(): +def Graph_HappyPath_ZoomInZoomOut(): """ Summary: The graph can be zoomed in and zoomed out. @@ -108,4 +108,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Graph_ZoomInZoomOut) + Report.start_test(Graph_HappyPath_ZoomInZoomOut) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py b/AutomatedTesting/Gem/PythonTests/scripting/NewScriptEventButton_HappyPath_ContainsSCCategory.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py rename to AutomatedTesting/Gem/PythonTests/scripting/NewScriptEventButton_HappyPath_ContainsSCCategory.py diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_HappyPath_VariableRenames.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py rename to AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_HappyPath_VariableRenames.py index 7351e45212..c235db6256 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_HappyPath_VariableRenames.py @@ -21,7 +21,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -def NodeInspector_RenameVariable(): +def NodeInspector_HappyPath_VariableRenames(): """ Summary: Renaming variables in the Node Inspector, renames the actual variable. @@ -123,4 +123,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(NodeInspector_RenameVariable) + Report.start_test(NodeInspector_HappyPath_VariableRenames) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_CanSelectNode.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py rename to AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_CanSelectNode.py index dfe1064a92..2fb1830b8f 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_CanSelectNode.py @@ -20,7 +20,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -def NodePalette_SelectNode(): +def NodePalette_HappyPath_CanSelectNode(): """ Summary: Categories and Nodes can be selected @@ -97,4 +97,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(NodePalette_SelectNode) + Report.start_test(NodePalette_HappyPath_CanSelectNode) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_ClearSelection.py similarity index 96% rename from AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py rename to AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_ClearSelection.py index 87a08346d0..93254dd377 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_ClearSelection.py @@ -17,7 +17,7 @@ class Tests(): # fmt: on -def NodePalette_ClearSelection(): +def NodePalette_HappyPath_ClearSelection(): """ Summary: Clicking the X button on the Search Box clears the currently entered string @@ -85,4 +85,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(NodePalette_ClearSelection) + Report.start_test(NodePalette_HappyPath_ClearSelection) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py rename to AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py index c331157e82..721ab53d8e 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py @@ -23,7 +23,7 @@ class Tests(): # fmt: on -def OnEntityActivatedDeactivated_PrintMessage(): +def OnEntityActivatedDeactivated_HappyPath_PrintMessage(): """ Summary: Verify that the On Entity Activated/On Entity Deactivated nodes are working as expected @@ -189,4 +189,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(OnEntityActivatedDeactivated_PrintMessage) + Report.start_test(OnEntityActivatedDeactivated_HappyPath_PrintMessage) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Default_RetainOnSCRestart.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py rename to AutomatedTesting/Gem/PythonTests/scripting/Pane_Default_RetainOnSCRestart.py index 746efa500c..626b1cf0bd 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Default_RetainOnSCRestart.py @@ -23,7 +23,7 @@ class Tests(): # fmt: on -def Pane_RetainOnSCRestart(): +def Pane_Default_RetainOnSCRestart(): """ Summary: The Script Canvas window is opened to verify if Script canvas panes can retain its visibility, size and location @@ -154,4 +154,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Pane_RetainOnSCRestart) + Report.start_test(Pane_Default_RetainOnSCRestart) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_DocksProperly.py old mode 100755 new mode 100644 similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py rename to AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_DocksProperly.py index da9dc125bc..2186a8a54a --- a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_DocksProperly.py @@ -17,7 +17,7 @@ class Tests(): # fmt: on -def Docking_Pane(): +def Pane_HappyPath_DocksProperly(): """ Summary: The Script Canvas window is opened to verify if Script canvas panes can be docked into every @@ -103,4 +103,4 @@ if __name__ == "__main__": imports.init() from editor_python_test_tools.utils import Report - Report.start_test(Docking_Pane) + Report.start_test(Pane_HappyPath_DocksProperly) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_OpenCloseSuccessfully.py old mode 100755 new mode 100644 similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py rename to AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_OpenCloseSuccessfully.py index a72a302760..cedd68cd87 --- a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_OpenCloseSuccessfully.py @@ -18,7 +18,7 @@ class Tests(): # fmt: on -def Opening_Closing_Pane(): +def Pane_HappyPath_OpenCloseSuccessfully(): """ Summary: The Script Canvas window is opened to verify if Script Canvas panes can be opened and closed. @@ -112,4 +112,4 @@ if __name__ == "__main__": imports.init() from editor_python_test_tools.utils import Report - Report.start_test(Opening_Closing_Pane) + Report.start_test(Pane_HappyPath_OpenCloseSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_ResizesProperly.py old mode 100755 new mode 100644 similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py rename to AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_ResizesProperly.py index a870bea86f..36d734049d --- a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_ResizesProperly.py @@ -17,7 +17,7 @@ class Tests(): # fmt: on -def Resizing_Pane(): +def Pane_HappyPath_ResizesProperly(): """ Summary: The Script Canvas window is opened to verify if Script Canvas panes can be resized and scaled @@ -105,4 +105,4 @@ if __name__ == "__main__": imports.init() from editor_python_test_tools.utils import Report - Report.start_test(Resizing_Pane) + Report.start_test(Pane_HappyPath_ResizesProperly) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Undocked_ClosesSuccessfully.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py rename to AutomatedTesting/Gem/PythonTests/scripting/Pane_Undocked_ClosesSuccessfully.py index fbdba8fb38..0ddbe7e34f 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Undocked_ClosesSuccessfully.py @@ -18,7 +18,7 @@ class Tests(): # fmt: on -def UnDockedPane_CloseSCWindow(): +def Pane_Undocked_ClosesSuccessfully(): """ Summary: The Script Canvas window is opened with one of the pane undocked. @@ -118,4 +118,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(UnDockedPane_CloseSCWindow) + Report.start_test(Pane_Undocked_ClosesSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasTools_Toggle_OpenCloseSuccess.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasTools_Toggle_OpenCloseSuccess.py index 2b935a74b3..a105f1ef18 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasTools_Toggle_OpenCloseSuccess.py @@ -27,7 +27,7 @@ class Tests(): # fmt: on -def Toggle_ScriptCanvasTools(): +def ScriptCanvasTools_Toggle_OpenCloseSuccess(): """ Summary: Toggle Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas. @@ -121,4 +121,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Toggle_ScriptCanvasTools) + Report.start_test(ScriptCanvasTools_Toggle_OpenCloseSuccess) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets_ComponentStable.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets_ComponentStable.py index a1e177f5ec..d39c3d2590 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets_ComponentStable.py @@ -20,7 +20,7 @@ class Tests(): # fmt: on -def ScriptCanvas_ChangingAssets(): +def ScriptCanvas_ChangingAssets_ComponentStable(): """ Summary: Changing the assigned Script Canvas Asset on an entity properly updates level functionality @@ -106,4 +106,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(ScriptCanvas_ChangingAssets) + Report.start_test(ScriptCanvas_ChangingAssets_ComponentStable) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents_InteractSuccessfully.py similarity index 96% rename from AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents_InteractSuccessfully.py index 5117069b64..9bbda9bdbd 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents_InteractSuccessfully.py @@ -23,7 +23,7 @@ class LogLines: expected_lines = ["Greetings from the first script", "Greetings from the second script"] -def ScriptCanvas_TwoComponents(): +def ScriptCanvas_TwoComponents_InteractSuccessfully(): """ Summary: A test entity contains two Script Canvas components with different unique script canvas files. @@ -111,4 +111,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(ScriptCanvas_TwoComponents) + Report.start_test(ScriptCanvas_TwoComponents_InteractSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities_UseSimultaneously.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities_UseSimultaneously.py index 53b3951c1a..d25ef64c4a 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities_UseSimultaneously.py @@ -19,7 +19,7 @@ class Tests(): # fmt: on -def ScriptCanvas_TwoEntities(): +def ScriptCanvas_TwoEntities_UseSimultaneously(): """ Summary: Two Entities can use the same Graph asset successfully at RunTime. The script canvas asset @@ -101,4 +101,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(ScriptCanvas_TwoEntities) + Report.start_test(ScriptCanvas_TwoEntities_UseSimultaneously) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_HappyPath_CreatedWithoutError.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_HappyPath_CreatedWithoutError.py diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_Default_SendReceiveSuccessfully.py similarity index 96% rename from AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_Default_SendReceiveSuccessfully.py index 3f343221b0..e0730b284c 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_Default_SendReceiveSuccessfully.py @@ -20,7 +20,7 @@ class Tests(): # fmt: on -def ScriptEvents_SendReceiveSuccessfully(): +def ScriptEvents_Default_SendReceiveSuccessfully(): """ Summary: An entity exists in the level that contains a Script Canvas component. In the graph is both a Send Event @@ -102,4 +102,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(ScriptEvents_SendReceiveSuccessfully) + Report.start_test(ScriptEvents_Default_SendReceiveSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py index f58d6007a1..be2665899f 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py @@ -21,7 +21,7 @@ class Tests(): # fmt: on -def ScriptEvents_SendReceiveAcrossMultiple(): +def ScriptEvents_HappyPath_SendReceiveAcrossMultiple(): """ Summary: EntityA and EntityB will be created in a level. Attached to both will be a Script Canvas component. @@ -113,4 +113,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(ScriptEvents_SendReceiveAcrossMultiple) + Report.start_test(ScriptEvents_HappyPath_SendReceiveAcrossMultiple) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index 24e8eeda11..a225ebd845 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -29,67 +29,67 @@ TEST_DIRECTORY = os.path.dirname(__file__) @pytest.mark.parametrize("launcher_platform", ['windows_editor']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) class TestAutomation(TestAutomationBase): - def test_Opening_Closing_Pane(self, request, workspace, editor, launcher_platform): - from . import Opening_Closing_Pane as test_module + def test_Pane_HappyPath_OpenCloseSuccessfully(self, request, workspace, editor, launcher_platform): + from . import Pane_HappyPath_OpenCloseSuccessfully as test_module self._run_test(request, workspace, editor, test_module) - def test_Docking_Pane(self, request, workspace, editor, launcher_platform): - from . import Docking_Pane as test_module + def test_Pane_HappyPath_DocksProperly(self, request, workspace, editor, launcher_platform): + from . import Pane_HappyPath_DocksProperly as test_module self._run_test(request, workspace, editor, test_module) - def test_Resizing_Pane(self, request, workspace, editor, launcher_platform): - from . import Resizing_Pane as test_module + def test_Pane_HappyPath_ResizesProperly(self, request, workspace, editor, launcher_platform): + from . import Pane_HappyPath_ResizesProperly as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_ScriptCanvas_TwoComponents(self, request, workspace, editor, launcher_platform, level): + def test_ScriptCanvas_TwoComponents_InteractSuccessfully(self, request, workspace, editor, launcher_platform, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import ScriptCanvas_TwoComponents as test_module + from . import ScriptCanvas_TwoComponents_InteractSuccessfully as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_ScriptCanvas_ChangingAssets(self, request, workspace, editor, launcher_platform, project, level): + def test_ScriptCanvas_ChangingAssets_ComponentStable(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import ScriptCanvas_ChangingAssets as test_module + from . import ScriptCanvas_ChangingAssets_ComponentStable as test_module self._run_test(request, workspace, editor, test_module) - def test_Graph_ZoomInZoomOut(self, request, workspace, editor, launcher_platform): - from . import Graph_ZoomInZoomOut as test_module + def test_Graph_HappyPath_ZoomInZoomOut(self, request, workspace, editor, launcher_platform): + from . import Graph_HappyPath_ZoomInZoomOut as test_module self._run_test(request, workspace, editor, test_module) - def test_NodePalette_SelectNode(self, request, workspace, editor, launcher_platform): - from . import NodePalette_SelectNode as test_module + def test_NodePalette_HappyPath_CanSelectNode(self, request, workspace, editor, launcher_platform): + from . import NodePalette_HappyPath_CanSelectNode as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_OnEntityActivatedDeactivated_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): + def test_OnEntityActivatedDeactivated_HappyPath_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import OnEntityActivatedDeactivated_PrintMessage as test_module + from . import OnEntityActivatedDeactivated_HappyPath_PrintMessage as test_module self._run_test(request, workspace, editor, test_module) - - def test_NodePalette_ClearSelection(self, request, workspace, editor, launcher_platform, project): - from . import NodePalette_ClearSelection as test_module + + def test_NodePalette_HappyPath_ClearSelection(self, request, workspace, editor, launcher_platform, project): + from . import NodePalette_HappyPath_ClearSelection as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_ScriptCanvas_TwoEntities(self, request, workspace, editor, launcher_platform, project, level): + def test_ScriptCanvas_TwoEntities_UseSimultaneously(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import ScriptCanvas_TwoEntities as test_module + from . import ScriptCanvas_TwoEntities_UseSimultaneously as test_module self._run_test(request, workspace, editor, test_module) - def test_AssetEditor_CreateScriptEventFile(self, request, workspace, editor, launcher_platform, project): + def test_ScriptEvent_HappyPath_CreatedWithoutError(self, request, workspace, editor, launcher_platform, project): def teardown(): file_system.delete( [os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True @@ -98,67 +98,67 @@ class TestAutomation(TestAutomationBase): file_system.delete( [os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True ) - from . import AssetEditor_CreateScriptEventFile as test_module + from . import ScriptEvent_HappyPath_CreatedWithoutError as test_module self._run_test(request, workspace, editor, test_module) - def test_Toggle_ScriptCanvasTools(self, request, workspace, editor, launcher_platform): - from . import Toggle_ScriptCanvasTools as test_module + def test_ScriptCanvasTools_Toggle_OpenCloseSuccess(self, request, workspace, editor, launcher_platform): + from . import ScriptCanvasTools_Toggle_OpenCloseSuccess as test_module self._run_test(request, workspace, editor, test_module) - def test_NodeInspector_RenameVariable(self, request, workspace, editor, launcher_platform, project): - from . import NodeInspector_RenameVariable as test_module + def test_NodeInspector_HappyPath_VariableRenames(self, request, workspace, editor, launcher_platform, project): + from . import NodeInspector_HappyPath_VariableRenames 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 + + def test_Debugger_HappyPath_TargetMultipleGraphs(self, request, workspace, editor, launcher_platform, project): + from . import Debugger_HappyPath_TargetMultipleGraphs as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_Debugging_TargetMultipleEntities(self, request, workspace, editor, launcher_platform, project, level): + def test_Debugger_HappyPath_TargetMultipleEntities(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import Debugging_TargetMultipleEntities as test_module + from . import Debugger_HappyPath_TargetMultipleEntities as test_module self._run_test(request, workspace, editor, test_module) - def test_EditMenu_UndoRedo(self, request, workspace, editor, launcher_platform, project): - from . import EditMenu_UndoRedo as test_module + def test_EditMenu_Default_UndoRedo(self, request, workspace, editor, launcher_platform, project): + from . import EditMenu_Default_UndoRedo as test_module self._run_test(request, workspace, editor, test_module) - def test_UnDockedPane_CloseSCWindow(self, request, workspace, editor, launcher_platform): - from . import UnDockedPane_CloseSCWindow as test_module + def test_Pane_Undocked_ClosesSuccessfully(self, request, workspace, editor, launcher_platform): + from . import Pane_Undocked_ClosesSuccessfully as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_Entity_AddScriptCanvasComponent(self, request, workspace, editor, launcher_platform, project, level): + def test_Entity_HappyPath_AddScriptCanvasComponent(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import Entity_AddScriptCanvasComponent as test_module + from . import Entity_HappyPath_AddScriptCanvasComponent as test_module self._run_test(request, workspace, editor, test_module) - def test_Pane_RetainOnSCRestart(self, request, workspace, editor, launcher_platform): - from . import Pane_RetainOnSCRestart as test_module + def test_Pane_Default_RetainOnSCRestart(self, request, workspace, editor, launcher_platform): + from . import Pane_Default_RetainOnSCRestart as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_ScriptEvents_SendReceiveAcrossMultiple(self, request, workspace, editor, launcher_platform, project, level): + def test_ScriptEvents_HappyPath_SendReceiveAcrossMultiple(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import ScriptEvents_SendReceiveAcrossMultiple as test_module + from . import ScriptEvents_HappyPath_SendReceiveAcrossMultiple as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_ScriptEvents_SendReceiveSuccessfully(self, request, workspace, editor, launcher_platform, project, level): + def test_ScriptEvents_Default_SendReceiveSuccessfully(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import ScriptEvents_SendReceiveSuccessfully as test_module + from . import ScriptEvents_Default_SendReceiveSuccessfully as test_module self._run_test(request, workspace, editor, test_module) # NOTE: We had to use hydra_test_utils.py, as TestAutomationBase run_test method @@ -171,16 +171,16 @@ class TestScriptCanvasTests(object): The following tests use hydra_test_utils.py to launch the editor and validate the results. """ - def test_FileMenu_New_Open(self, request, editor, launcher_platform): + def test_FileMenu_Default_NewAndOpen(self, request, editor, launcher_platform): expected_lines = [ "File->New action working as expected: True", "File->Open action working as expected: True", ] hydra.launch_and_validate_results( - request, TEST_DIRECTORY, editor, "FileMenu_New_Open.py", expected_lines, auto_test_mode=False, timeout=60, + request, TEST_DIRECTORY, editor, "FileMenu_Default_NewAndOpen.py", expected_lines, auto_test_mode=False, timeout=60, ) - def test_AssetEditor_NewScriptEvent(self, request, editor, launcher_platform): + def test_NewScriptEventButton_HappyPath_ContainsSCCategory(self, request, editor, launcher_platform): expected_lines = [ "New Script event action found: True", "Asset Editor opened: True", @@ -191,13 +191,13 @@ class TestScriptCanvasTests(object): request, TEST_DIRECTORY, editor, - "AssetEditor_NewScriptEvent.py", + "NewScriptEventButton_HappyPath_ContainsSCCategory.py", expected_lines, auto_test_mode=False, timeout=60, ) - def test_GraphClose_SavePrompt(self, request, editor, launcher_platform): + def test_GraphClose_Default_SavePrompt(self, request, editor, launcher_platform): expected_lines = [ "New graph created: True", "Save prompt opened as expected: True", @@ -207,13 +207,13 @@ class TestScriptCanvasTests(object): request, TEST_DIRECTORY, editor, - "GraphClose_SavePrompt.py", + "GraphClose_Default_SavePrompt.py", expected_lines, auto_test_mode=False, timeout=60, ) - def test_VariableManager_CreateDeleteVars(self, request, editor, launcher_platform): + def test_VariableManager_Default_CreateDeleteVars(self, request, editor, launcher_platform): var_types = ["Boolean", "Color", "EntityID", "Number", "String", "Transform", "Vector2", "Vector3", "Vector4"] expected_lines = [f"Success: {var_type} variable is created" for var_type in var_types] expected_lines.extend([f"Success: {var_type} variable is deleted" for var_type in var_types]) @@ -221,7 +221,7 @@ class TestScriptCanvasTests(object): request, TEST_DIRECTORY, editor, - "VariableManager_CreateDeleteVars.py", + "VariableManager_Default_CreateDeleteVars.py", expected_lines, auto_test_mode=False, timeout=60, diff --git a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_Default_CreateDeleteVars.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py rename to AutomatedTesting/Gem/PythonTests/scripting/VariableManager_Default_CreateDeleteVars.py index 8f7557c01e..e53939172e 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_Default_CreateDeleteVars.py @@ -10,7 +10,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ -def VariableManager_CreateDeleteVars(): +def VariableManager_Default_CreateDeleteVars(): """ Summary: Creating and deleting each type of variable in the Variable Manager pane @@ -111,4 +111,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(VariableManager_CreateDeleteVars) + Report.start_test(VariableManager_Default_CreateDeleteVars) From 1f3d0beb387a68ac5ac87c63aafa5105d1f253b6 Mon Sep 17 00:00:00 2001 From: antonmic Date: Fri, 7 May 2021 18:51:20 -0700 Subject: [PATCH 022/231] work in progress --- .../Materials/Types/StandardPBR.materialtype | 15 + .../Types/StandardPBR_ForwardPass.azsl | 15 +- .../Types/StandardPBR_LowEndForward.azsl | 15 + .../Types/StandardPBR_LowEndForward.shader | 53 +++ .../StandardPBR_LowEndForward_EDS.shader | 53 +++ .../Feature/Common/Assets/Passes/Forward.pass | 16 - .../Assets/Passes/LightAdaptationParent.pass | 146 ++++++++ .../Common/Assets/Passes/LowEndForward.pass | 133 +++++++ .../Common/Assets/Passes/LowEndPipeline.pass | 344 ++++++++++++++++++ .../Common/Assets/Passes/OpaqueParent.pass | 11 +- .../Assets/Passes/PassTemplates.azasset | 12 + .../Assets/Passes/PostProcessParent.pass | 90 +---- .../Feature/Common/Assets/Passes/SkyBox.pass | 5 - .../Atom/Features/PBR/ForwardPassOutput.azsli | 17 + .../PBR/LowEndForwardPassOutput.azsli | 32 ++ .../Atom/Features/ShaderQualityOptions.azsli | 24 ++ .../Reflections/ReflectionComposite.azsl | 15 +- .../Common/Assets/Shaders/SkyBox/SkyBox.azsl | 2 - .../atom_feature_common_asset_files.cmake | 10 + 19 files changed, 887 insertions(+), 121 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.azsl create mode 100644 Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.shader create mode 100644 Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward_EDS.shader create mode 100644 Gems/Atom/Feature/Common/Assets/Passes/LightAdaptationParent.pass create mode 100644 Gems/Atom/Feature/Common/Assets/Passes/LowEndForward.pass create mode 100644 Gems/Atom/Feature/Common/Assets/Passes/LowEndPipeline.pass create mode 100644 Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/LowEndForwardPassOutput.azsli create mode 100644 Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index e071a793a5..fa5c94c606 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -77,6 +77,13 @@ ], "properties": { "general": [ + { + "id": "useLowEndShader", + "displayName": "Use Low End", + "description": "Whether to use the low end shader.", + "type": "Bool", + "defaultValue": false + }, { "id": "applySpecularAA", "displayName": "Apply Specular AA", @@ -1175,6 +1182,14 @@ "file": "./StandardPBR_ForwardPass_EDS.shader", "tag": "ForwardPass_EDS" }, + { + "file": "./StandardPBR_LowEndForward.shader", + "tag": "LowEndForward" + }, + { + "file": "./StandardPBR_LowEndForward_EDS.shader", + "tag": "LowEndForward_EDS" + }, { "file": "Shaders/Shadow/Shadowmap.shader", "tag": "Shadowmap" 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 d3bc72d162..bb4e4cdaab 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -10,6 +10,8 @@ * */ +#include "Atom/Features/ShaderQualityOptions.azsli" + #include "StandardPBR_Common.azsli" // SRGs @@ -306,13 +308,18 @@ ForwardPassOutputWithDepth StandardPbr_ForwardPassPS(VSOutput IN, bool isFrontFa PbrLightingOutput lightingOutput = ForwardPassPS_Common(IN, isFrontFace, depth); +#ifdef UNIFIED_FORWARD_OUTPUT + OUT.m_color.rgb = lightingOutput.m_diffuseColor.rgb + lightingOutput.m_specularColor.rgb; + OUT.m_color.a = 1.0f; + OUT.m_depth = depth; +#else OUT.m_diffuseColor = lightingOutput.m_diffuseColor; OUT.m_specularColor = lightingOutput.m_specularColor; OUT.m_specularF0 = lightingOutput.m_specularF0; OUT.m_albedo = lightingOutput.m_albedo; OUT.m_normal = lightingOutput.m_normal; OUT.m_depth = depth; - +#endif return OUT; } @@ -324,12 +331,16 @@ ForwardPassOutput StandardPbr_ForwardPassPS_EDS(VSOutput IN, bool isFrontFace : PbrLightingOutput lightingOutput = ForwardPassPS_Common(IN, isFrontFace, depth); +#ifdef UNIFIED_FORWARD_OUTPUT + OUT.m_color.rgb = lightingOutput.m_diffuseColor.rgb + lightingOutput.m_specularColor.rgb; + OUT.m_color.a = 1.0f; +#else OUT.m_diffuseColor = lightingOutput.m_diffuseColor; OUT.m_specularColor = lightingOutput.m_specularColor; OUT.m_specularF0 = lightingOutput.m_specularF0; OUT.m_albedo = lightingOutput.m_albedo; OUT.m_normal = lightingOutput.m_normal; - +#endif return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.azsl new file mode 100644 index 0000000000..a690cbf84a --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.azsl @@ -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. +* +*/ + +#define QUALITY_LOW_END 1 + +#include "StandardPBR_ForwardPass.azsl" diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.shader b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.shader new file mode 100644 index 0000000000..19538e5db3 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.shader @@ -0,0 +1,53 @@ +{ + "Source" : "./StandardPBR_LowEndForward.azsl", + + "DepthStencilState" : + { + "Depth" : + { + "Enable" : true, + "CompareFunc" : "GreaterEqual" + }, + "Stencil" : + { + "Enable" : true, + "ReadMask" : "0x00", + "WriteMask" : "0xFF", + "FrontFace" : + { + "Func" : "Always", + "DepthFailOp" : "Keep", + "FailOp" : "Keep", + "PassOp" : "Replace" + }, + "BackFace" : + { + "Func" : "Always", + "DepthFailOp" : "Keep", + "FailOp" : "Keep", + "PassOp" : "Replace" + } + } + }, + + "CompilerHints" : { + "DisableOptimizations" : false + }, + + "ProgramSettings": + { + "EntryPoints": + [ + { + "name": "StandardPbr_ForwardPassVS", + "type": "Vertex" + }, + { + "name": "StandardPbr_ForwardPassPS", + "type": "Fragment" + } + ] + }, + + "DrawList" : "lowEndForward" +} diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward_EDS.shader b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward_EDS.shader new file mode 100644 index 0000000000..1b5f014d0e --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward_EDS.shader @@ -0,0 +1,53 @@ +{ + "Source" : "./StandardPBR_LowEndForward.azsl", + + "DepthStencilState" : + { + "Depth" : + { + "Enable" : true, + "CompareFunc" : "GreaterEqual" + }, + "Stencil" : + { + "Enable" : true, + "ReadMask" : "0x00", + "WriteMask" : "0xFF", + "FrontFace" : + { + "Func" : "Always", + "DepthFailOp" : "Keep", + "FailOp" : "Keep", + "PassOp" : "Replace" + }, + "BackFace" : + { + "Func" : "Always", + "DepthFailOp" : "Keep", + "FailOp" : "Keep", + "PassOp" : "Replace" + } + } + }, + + "CompilerHints" : { + "DisableOptimizations" : false + }, + + "ProgramSettings": + { + "EntryPoints": + [ + { + "name": "StandardPbr_ForwardPassVS", + "type": "Vertex" + }, + { + "name": "StandardPbr_ForwardPassPS_EDS", + "type": "Fragment" + } + ] + }, + + "DrawList" : "lowEndForward" +} diff --git a/Gems/Atom/Feature/Common/Assets/Passes/Forward.pass b/Gems/Atom/Feature/Common/Assets/Passes/Forward.pass index 31a8ed1879..3dcc90ac5c 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/Forward.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/Forward.pass @@ -148,22 +148,6 @@ }, "LoadAction": "Clear" } - }, - { - "Name": "ScatterDistanceOutput", - "SlotType": "Output", - "ScopeAttachmentUsage": "RenderTarget", - "LoadStoreAction": { - "ClearValue": { - "Value": [ - 0.0, - 0.0, - 0.0, - 0.0 - ] - }, - "LoadAction": "Clear" - } } ], "ImageAttachments": [ diff --git a/Gems/Atom/Feature/Common/Assets/Passes/LightAdaptationParent.pass b/Gems/Atom/Feature/Common/Assets/Passes/LightAdaptationParent.pass new file mode 100644 index 0000000000..3e804d23e2 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Passes/LightAdaptationParent.pass @@ -0,0 +1,146 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "PassAsset", + "ClassData": { + "PassTemplate": { + "Name": "LightAdaptationParentTemplate", + "PassClass": "ParentPass", + "Slots": [ + // Inputs... + { + "Name": "LightingInput", + "SlotType": "Input" + }, + // SwapChain here is only used to reference the frame height and format + { + "Name": "SwapChainOutput", + "SlotType": "InputOutput" + }, + // Outputs... + { + "Name": "Output", + "SlotType": "Output" + }, + // Debug Outputs... + { + "Name": "LuminanceMipChainOutput", + "SlotType": "Output" + } + ], + "Connections": [ + { + "LocalSlot": "Output", + "AttachmentRef": { + "Pass": "DisplayMapperPass", + "Attachment": "Output" + } + }, + { + "LocalSlot": "LuminanceMipChainOutput", + "AttachmentRef": { + "Pass": "DownsampleLuminanceMipChain", + "Attachment": "MipChainInputOutput" + } + } + ], + "PassRequests": [ + { + "Name": "DownsampleLuminanceMinAvgMax", + "TemplateName": "DownsampleLuminanceMinAvgMaxCS", + "Connections": [ + { + "LocalSlot": "Input", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "LightingInput" + } + } + ] + }, + { + "Name": "DownsampleLuminanceMipChain", + "TemplateName": "DownsampleMipChainTemplate", + "Connections": [ + { + "LocalSlot": "MipChainInputOutput", + "AttachmentRef": { + "Pass": "DownsampleLuminanceMinAvgMax", + "Attachment": "Output" + } + } + ], + "PassData": { + "$type": "DownsampleMipChainPassData", + "ShaderAsset": { + "FilePath": "Shaders/PostProcessing/DownsampleMinAvgMaxCS.shader" + } + } + }, + { + "Name": "EyeAdaptationPass", + "TemplateName": "EyeAdaptationTemplate", + "Enabled": false, + "Connections": [ + { + "LocalSlot": "SceneLuminanceInput", + "AttachmentRef": { + "Pass": "DownsampleLuminanceMipChain", + "Attachment": "MipChainInputOutput" + } + } + ] + }, + { + "Name": "LookModificationTransformPass", + "TemplateName": "LookModificationTransformTemplate", + "Enabled": true, + "Connections": [ + { + "LocalSlot": "Input", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "LightingInput" + } + }, + { + "LocalSlot": "EyeAdaptationDataInput", + "AttachmentRef": { + "Pass": "EyeAdaptationPass", + "Attachment": "EyeAdaptationDataInputOutput" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "DisplayMapperPass", + "TemplateName": "DisplayMapperTemplate", + "Enabled": true, + "Connections": [ + { + "LocalSlot": "Input", + "AttachmentRef": { + "Pass": "LookModificationTransformPass", + "Attachment": "Output" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + } + ] + } + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Passes/LowEndForward.pass b/Gems/Atom/Feature/Common/Assets/Passes/LowEndForward.pass new file mode 100644 index 0000000000..4b865fcb6d --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Passes/LowEndForward.pass @@ -0,0 +1,133 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "PassAsset", + "ClassData": { + "PassTemplate": { + "Name": "LowEndForwardPassTemplate", + "PassClass": "RasterPass", + "Slots": [ + // Inputs... + { + "Name": "BRDFTextureInput", + "ShaderInputName": "m_brdfMap", + "SlotType": "Input", + "ScopeAttachmentUsage": "Shader" + }, + { + "Name": "DirectionalLightShadowmap", + "ShaderInputName": "m_directionalLightShadowmap", + "SlotType": "Input", + "ScopeAttachmentUsage": "Shader", + "ImageViewDesc": { + "IsArray": 1 + } + }, + { + "Name": "ExponentialShadowmapDirectional", + "ShaderInputName": "m_directionalLightExponentialShadowmap", + "SlotType": "Input", + "ScopeAttachmentUsage": "Shader", + "ImageViewDesc": { + "IsArray": 1 + } + }, + { + "Name": "ProjectedShadowmap", + "ShaderInputName": "m_projectedShadowmaps", + "SlotType": "Input", + "ScopeAttachmentUsage": "Shader", + "ImageViewDesc": { + "IsArray": 1 + } + }, + { + "Name": "ExponentialShadowmapProjected", + "ShaderInputName": "m_projectedExponentialShadowmap", + "SlotType": "Input", + "ScopeAttachmentUsage": "Shader", + "ImageViewDesc": { + "IsArray": 1 + } + }, + { + "Name": "TileLightData", + "SlotType": "Input", + "ShaderInputName": "m_tileLightData", + "ScopeAttachmentUsage": "Shader" + }, + { + "Name": "LightListRemapped", + "SlotType": "Input", + "ShaderInputName": "m_lightListRemapped", + "ScopeAttachmentUsage": "Shader" + }, + // Input/Outputs... + { + "Name": "DepthStencilInputOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "DepthStencil" + }, + // Outputs... + { + "Name": "LightingOutput", + "SlotType": "Output", + "ScopeAttachmentUsage": "RenderTarget", + "LoadStoreAction": { + "ClearValue": { + "Value": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "LoadAction": "Clear" + } + } + ], + "ImageAttachments": [ + { + "Name": "LightingAttachment", + "SizeSource": { + "Source": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + }, + "MultisampleSource": { + "Pass": "This", + "Attachment": "DepthStencilInputOutput" + }, + "ImageDescriptor": { + "Format": "R16G16B16A16_FLOAT", + "SharedQueueMask": "Graphics" + } + }, + { + "Name": "BRDFTexture", + "Lifetime": "Imported", + "AssetRef": { + "FilePath": "Textures/BRDFTexture.attimage" + } + } + ], + "Connections": [ + { + "LocalSlot": "LightingOutput", + "AttachmentRef": { + "Pass": "This", + "Attachment": "LightingAttachment" + } + }, + { + "LocalSlot": "BRDFTextureInput", + "AttachmentRef": { + "Pass": "This", + "Attachment": "BRDFTexture" + } + } + ] + } + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Passes/LowEndPipeline.pass b/Gems/Atom/Feature/Common/Assets/Passes/LowEndPipeline.pass new file mode 100644 index 0000000000..b19569fb9d --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Passes/LowEndPipeline.pass @@ -0,0 +1,344 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "PassAsset", + "ClassData": { + "PassTemplate": { + "Name": "LowEndPipelineTemplate", + "PassClass": "ParentPass", + "Slots": [ + { + "Name": "SwapChainOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "RenderTarget" + } + ], + "PassRequests": [ + { + "Name": "MorphTargetPass", + "TemplateName": "MorphTargetPassTemplate" + }, + { + "Name": "SkinningPass", + "TemplateName": "SkinningPassTemplate", + "Connections": [ + { + "LocalSlot": "SkinnedMeshOutputStream", + "AttachmentRef": { + "Pass": "MorphTargetPass", + "Attachment": "MorphTargetDeltaOutput" + } + } + ] + }, + { + "Name": "DepthPrePass", + "TemplateName": "DepthMSAAParentTemplate", + "Connections": [ + { + "LocalSlot": "SkinnedMeshes", + "AttachmentRef": { + "Pass": "SkinningPass", + "Attachment": "SkinnedMeshOutputStream" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "LightCullingPass", + "TemplateName": "LightCullingParentTemplate", + "Connections": [ + { + "LocalSlot": "SkinnedMeshes", + "AttachmentRef": { + "Pass": "SkinningPass", + "Attachment": "SkinnedMeshOutputStream" + } + }, + { + "LocalSlot": "DepthMSAA", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "DepthMSAA" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "ShadowPass", + "TemplateName": "ShadowParentTemplate", + "Connections": [ + { + "LocalSlot": "SkinnedMeshes", + "AttachmentRef": { + "Pass": "SkinningPass", + "Attachment": "SkinnedMeshOutputStream" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "ForwardPass", + "TemplateName": "LowEndForwardPassTemplate", + "Connections": [ + // Inputs... + { + "LocalSlot": "DirectionalLightShadowmap", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "DirectionalShadowmap" + } + }, + { + "LocalSlot": "ExponentialShadowmapDirectional", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "DirectionalESM" + } + }, + { + "LocalSlot": "ProjectedShadowmap", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "ProjectedShadowmap" + } + }, + { + "LocalSlot": "ExponentialShadowmapProjected", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "ProjectedESM" + } + }, + { + "LocalSlot": "TileLightData", + "AttachmentRef": { + "Pass": "LightCullingPass", + "Attachment": "TileLightData" + } + }, + { + "LocalSlot": "LightListRemapped", + "AttachmentRef": { + "Pass": "LightCullingPass", + "Attachment": "LightListRemapped" + } + }, + // Input/Outputs... + { + "LocalSlot": "DepthStencilInputOutput", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "DepthMSAA" + } + } + ], + "PassData": { + "$type": "RasterPassData", + "DrawListTag": "lowEndForward", + "PipelineViewTag": "MainCamera", + "PassSrgAsset": { + "FilePath": "shaderlib/atom/features/pbr/forwardpasssrg.azsli:PassSrg" + } + } + }, + { + "Name": "SkyBoxPass", + "TemplateName": "SkyBoxTemplate", + "Enabled": true, + "Connections": [ + { + "LocalSlot": "SpecularInputOutput", + "AttachmentRef": { + "Pass": "ForwardPass", + "Attachment": "LightingOutput" + } + }, + { + "LocalSlot": "SkyBoxDepth", + "AttachmentRef": { + "Pass": "ForwardPass", + "Attachment": "DepthStencilInputOutput" + } + } + ] + }, + { + "Name": "MSAAResolvePass", + "TemplateName": "MSAAResolveColorTemplate", + "Connections": [ + { + "LocalSlot": "Input", + "AttachmentRef": { + "Pass": "SkyBoxPass", + "Attachment": "SpecularInputOutput" + } + } + ] + }, + { + "Name": "TransparentPass", + "TemplateName": "TransparentParentTemplate", + "Connections": [ + { + "LocalSlot": "DirectionalShadowmap", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "DirectionalShadowmap" + } + }, + { + "LocalSlot": "DirectionalESM", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "DirectionalESM" + } + }, + { + "LocalSlot": "ProjectedShadowmap", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "ProjectedShadowmap" + } + }, + { + "LocalSlot": "ProjectedESM", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "ProjectedESM" + } + }, + { + "LocalSlot": "TileLightData", + "AttachmentRef": { + "Pass": "LightCullingPass", + "Attachment": "TileLightData" + } + }, + { + "LocalSlot": "LightListRemapped", + "AttachmentRef": { + "Pass": "LightCullingPass", + "Attachment": "LightListRemapped" + } + }, + { + "LocalSlot": "DepthStencil", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "Depth" + } + }, + { + "LocalSlot": "InputOutput", + "AttachmentRef": { + "Pass": "MSAAResolvePass", + "Attachment": "Output" + } + } + ] + }, + { + "Name": "LightAdaptation", + "TemplateName": "LightAdaptationParentTemplate", + "Connections": [ + { + "LocalSlot": "LightingInput", + "AttachmentRef": { + "Pass": "TransparentPass", + "Attachment": "InputOutput" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "AuxGeomPass", + "TemplateName": "AuxGeomPassTemplate", + "Enabled": true, + "Connections": [ + { + "LocalSlot": "ColorInputOutput", + "AttachmentRef": { + "Pass": "LightAdaptation", + "Attachment": "Output" + } + }, + { + "LocalSlot": "DepthInputOutput", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "Depth" + } + } + ], + "PassData": { + "$type": "RasterPassData", + "DrawListTag": "auxgeom", + "PipelineViewTag": "MainCamera" + } + }, + { + "Name": "UIPass", + "TemplateName": "UIParentTemplate", + "Connections": [ + { + "LocalSlot": "InputOutput", + "AttachmentRef": { + "Pass": "AuxGeomPass", + "Attachment": "ColorInputOutput" + } + } + ] + }, + { + "Name": "CopyToSwapChain", + "TemplateName": "FullscreenCopyTemplate", + "Connections": [ + { + "LocalSlot": "Input", + "AttachmentRef": { + "Pass": "UIPass", + "Attachment": "InputOutput" + } + }, + { + "LocalSlot": "Output", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + } + ] + } + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Passes/OpaqueParent.pass b/Gems/Atom/Feature/Common/Assets/Passes/OpaqueParent.pass index dda120e164..40d6a51e77 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/OpaqueParent.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/OpaqueParent.pass @@ -315,13 +315,6 @@ "Attachment": "SpecularInputOutput" } }, - { - "LocalSlot": "ReflectionInputOutput", - "AttachmentRef": { - "Pass": "ReflectionsPass", - "Attachment": "ReflectionOutput" - } - }, { "LocalSlot": "SkyBoxDepth", "AttachmentRef": { @@ -338,8 +331,8 @@ { "LocalSlot": "ReflectionInput", "AttachmentRef": { - "Pass": "SkyBoxPass", - "Attachment": "ReflectionInputOutput" + "Pass": "ReflectionsPass", + "Attachment": "ReflectionOutput" } }, { diff --git a/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset b/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset index b83ab65ff2..2421d7fbe7 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset +++ b/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset @@ -483,6 +483,18 @@ { "Name": "UIParentTemplate", "Path": "Passes/UIParent.pass" + }, + { + "Name": "LightAdaptationParentTemplate", + "Path": "Passes/LightAdaptationParent.pass" + }, + { + "Name": "LowEndForwardPassTemplate", + "Path": "Passes/LowEndForward.pass" + }, + { + "Name": "LowEndPipelineTemplate", + "Path": "Passes/LowEndPipeline.pass" } ] } diff --git a/Gems/Atom/Feature/Common/Assets/Passes/PostProcessParent.pass b/Gems/Atom/Feature/Common/Assets/Passes/PostProcessParent.pass index 37b1ee5c5a..36f7f1e985 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/PostProcessParent.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/PostProcessParent.pass @@ -40,7 +40,7 @@ { "LocalSlot": "Output", "AttachmentRef": { - "Pass": "DisplayMapperPass", + "Pass": "LightAdaptation", "Attachment": "Output" } }, @@ -54,8 +54,8 @@ { "LocalSlot": "LuminanceMipChainOutput", "AttachmentRef": { - "Pass": "DownsampleLuminanceMipChain", - "Attachment": "MipChainInputOutput" + "Pass": "LightAdaptation", + "Attachment": "LuminanceMipChainOutput" } } ], @@ -115,94 +115,16 @@ } ] }, - // Everything before this point deals in raw lighting values - // --------------------------------------------------------- - // Everything after starts to map to values we see on screen { - "Name": "DownsampleLuminanceMinAvgMax", - "TemplateName": "DownsampleLuminanceMinAvgMaxCS", + "Name": "LightAdaptation", + "TemplateName": "LightAdaptationParentTemplate", "Connections": [ { - "LocalSlot": "Input", + "LocalSlot": "LightingInput", "AttachmentRef": { "Pass": "BloomPass", "Attachment": "InputOutput" } - } - ] - }, - { - "Name": "DownsampleLuminanceMipChain", - "TemplateName": "DownsampleMipChainTemplate", - "Connections": [ - { - "LocalSlot": "MipChainInputOutput", - "AttachmentRef": { - "Pass": "DownsampleLuminanceMinAvgMax", - "Attachment": "Output" - } - } - ], - "PassData": { - "$type": "DownsampleMipChainPassData", - "ShaderAsset": { - "FilePath": "Shaders/PostProcessing/DownsampleMinAvgMaxCS.shader" - } - } - }, - { - "Name": "EyeAdaptationPass", - "TemplateName": "EyeAdaptationTemplate", - "Enabled": false, - "Connections": [ - { - "LocalSlot": "SceneLuminanceInput", - "AttachmentRef": { - "Pass": "DownsampleLuminanceMipChain", - "Attachment": "MipChainInputOutput" - } - } - ] - }, - { - "Name": "LookModificationTransformPass", - "TemplateName": "LookModificationTransformTemplate", - "Enabled": true, - "Connections": [ - { - "LocalSlot": "Input", - "AttachmentRef": { - "Pass": "BloomPass", - "Attachment": "InputOutput" - } - }, - { - "LocalSlot": "EyeAdaptationDataInput", - "AttachmentRef": { - "Pass": "EyeAdaptationPass", - "Attachment": "EyeAdaptationDataInputOutput" - } - }, - { - "LocalSlot": "SwapChainOutput", - "AttachmentRef": { - "Pass": "Parent", - "Attachment": "SwapChainOutput" - } - } - ] - }, - { - "Name": "DisplayMapperPass", - "TemplateName": "DisplayMapperTemplate", - "Enabled": true, - "Connections": [ - { - "LocalSlot": "Input", - "AttachmentRef": { - "Pass": "LookModificationTransformPass", - "Attachment": "Output" - } }, { "LocalSlot": "SwapChainOutput", diff --git a/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass b/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass index 57f442e5de..fb16271ba7 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass @@ -12,11 +12,6 @@ "SlotType": "InputOutput", "ScopeAttachmentUsage": "RenderTarget" }, - { - "Name": "ReflectionInputOutput", - "SlotType": "InputOutput", - "ScopeAttachmentUsage": "RenderTarget" - }, { "Name": "SkyBoxDepth", "SlotType": "InputOutput", diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/ForwardPassOutput.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/ForwardPassOutput.azsli index acc215f1c9..5821deb3b1 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/ForwardPassOutput.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/ForwardPassOutput.azsli @@ -10,6 +10,21 @@ * */ +#ifdef UNIFIED_FORWARD_OUTPUT + +struct ForwardPassOutput +{ + float4 m_color : SV_Target0; +}; + +struct ForwardPassOutputWithDepth +{ + float4 m_color : SV_Target0; + float m_depth : SV_Depth; +}; + +#else + struct ForwardPassOutput { float4 m_diffuseColor : SV_Target0; //!< RGB = Diffuse Lighting, A = Blend Alpha (for blended surfaces) OR A = special encoding of surfaceScatteringFactor, m_subsurfaceScatteringQuality, o_enableSubsurfaceScattering @@ -30,3 +45,5 @@ struct ForwardPassOutputWithDepth float4 m_normal : SV_Target4; float m_depth : SV_Depth; }; + +#endif diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/LowEndForwardPassOutput.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/LowEndForwardPassOutput.azsli new file mode 100644 index 0000000000..acc215f1c9 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/LowEndForwardPassOutput.azsli @@ -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. +* +*/ + +struct ForwardPassOutput +{ + float4 m_diffuseColor : SV_Target0; //!< RGB = Diffuse Lighting, A = Blend Alpha (for blended surfaces) OR A = special encoding of surfaceScatteringFactor, m_subsurfaceScatteringQuality, o_enableSubsurfaceScattering + float4 m_specularColor : SV_Target1; //!< RGB = Specular Lighting, A = Unused + float4 m_albedo : SV_Target2; //!< RGB = Surface albedo pre-multiplied by other factors that will be multiplied later by diffuse GI, A = specularOcclusion + float4 m_specularF0 : SV_Target3; //!< RGB = Specular F0, A = roughness + float4 m_normal : SV_Target4; //!< RGB10 = EncodeNormalSignedOctahedron(worldNormal), A2 = multiScatterCompensationEnabled +}; + +struct ForwardPassOutputWithDepth +{ + // See above for descriptions of special encodings + + float4 m_diffuseColor : SV_Target0; + float4 m_specularColor : SV_Target1; + float4 m_albedo : SV_Target2; + float4 m_specularF0 : SV_Target3; + float4 m_normal : SV_Target4; + float m_depth : SV_Depth; +}; diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli new file mode 100644 index 0000000000..907e67ada5 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli @@ -0,0 +1,24 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or 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 + +// These are a list of quality options to specify as macros (either in azsl or in shader files) +// +// QUALITY_LOW_END + +#ifdef QUALITY_LOW_END + +#define UNIFIED_FORWARD_OUTPUT 1 + +#endif + diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionComposite.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionComposite.azsl index 92f8c3f638..865d657d85 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionComposite.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionComposite.azsl @@ -53,13 +53,22 @@ PSOutput MainPS(VSOutput IN) uint width, height, samples; PassSrg::m_reflection.GetDimensions(width, height, samples); + float nonZeroSamples = 0.0f; for (uint sampleIndex = 0; sampleIndex < samples; ++sampleIndex) { - reflection += PassSrg::m_reflection.Load(IN.m_position.xy, sampleIndex).rgb; + float3 reflectionSample = PassSrg::m_reflection.Load(IN.m_position.xy, sampleIndex).rgb; + if(any(reflectionSample)) + { + reflection += reflectionSample; + nonZeroSamples += 1.0f; + } + } + + if(nonZeroSamples != 0.0f) + { + reflection /= nonZeroSamples; } - reflection /= samples; - PSOutput OUT; OUT.m_color = float4(reflection, 1.0f); return OUT; diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl index 1ee30a4f98..a7de426374 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl @@ -102,7 +102,6 @@ float3 GetCubemapCoords(float3 original) struct PSOutput { float4 m_specular : SV_Target0; - float4 m_reflection : SV_Target1; }; PSOutput MainPS(VSOutput input) @@ -163,6 +162,5 @@ PSOutput MainPS(VSOutput input) PSOutput OUT; OUT.m_specular = float4(color, 1.0); - OUT.m_reflection = float4(color, 1.0); return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake index f14fb4f4a0..6902d456ff 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 @@ -52,6 +52,8 @@ set(FILES Materials/Types/StandardPBR_ForwardPass_EDS.shader Materials/Types/StandardPBR_HandleOpacityDoubleSided.lua Materials/Types/StandardPBR_HandleOpacityMode.lua + Materials/Types/StandardPBR_LowEndForward.azsl + Materials/Types/StandardPBR_LowEndForward.shader Materials/Types/StandardPBR_ParallaxState.lua Materials/Types/StandardPBR_Roughness.lua Materials/Types/StandardPBR_ShaderEnable.lua @@ -116,6 +118,7 @@ set(FILES Passes/DiffuseProbeGridBlendDistance.pass Passes/DiffuseProbeGridBlendIrradiance.pass Passes/DiffuseProbeGridBorderUpdate.pass + Passes/DiffuseProbeGridClassification.pass Passes/DiffuseProbeGridDownsample.pass Passes/DiffuseProbeGridRayTracing.pass Passes/DiffuseProbeGridRelocation.pass @@ -144,6 +147,7 @@ set(FILES Passes/FullscreenCopy.pass Passes/FullscreenOutputOnly.pass Passes/ImGui.pass + Passes/LightAdaptationParent.pass Passes/LightCulling.pass Passes/LightCullingHeatmap.pass Passes/LightCullingParent.pass @@ -152,6 +156,8 @@ set(FILES Passes/LightCullingTilePrepareMSAA.pass Passes/LookModificationComposite.pass Passes/LookModificationTransform.pass + Passes/LowEndForward.pass + Passes/LowEndPipeline.pass Passes/LuminanceHeatmap.pass Passes/LuminanceHistogramGenerator.pass Passes/MainPipeline.pass @@ -179,8 +185,10 @@ set(FILES Passes/ReflectionScreenSpace.pass Passes/ReflectionScreenSpaceBlur.pass Passes/ReflectionScreenSpaceBlurHorizontal.pass + Passes/ReflectionScreenSpaceBlurMobile.pass Passes/ReflectionScreenSpaceBlurVertical.pass Passes/ReflectionScreenSpaceComposite.pass + Passes/ReflectionScreenSpaceMobile.pass Passes/ReflectionScreenSpaceTrace.pass Passes/Reflections_nomsaa.pass Passes/ShadowParent.pass @@ -205,6 +213,7 @@ set(FILES ShaderLib/Atom/Features/IndirectRendering.azsli ShaderLib/Atom/Features/MatrixUtility.azsli ShaderLib/Atom/Features/ParallaxMapping.azsli + ShaderLib/Atom/Features/ShaderQualityOptions.azsli ShaderLib/Atom/Features/SphericalHarmonicsUtility.azsli ShaderLib/Atom/Features/SrgSemantics.azsli ShaderLib/Atom/Features/ColorManagement/TransformColor.azsli @@ -234,6 +243,7 @@ set(FILES ShaderLib/Atom/Features/PBR/Hammersley.azsli ShaderLib/Atom/Features/PBR/LightingOptions.azsli ShaderLib/Atom/Features/PBR/LightingUtils.azsli + ShaderLib/Atom/Features/PBR/LowEndForwardPassOutput.azsli ShaderLib/Atom/Features/PBR/TransparentPassSrg.azsli ShaderLib/Atom/Features/PBR/Lighting/DualSpecularLighting.azsli ShaderLib/Atom/Features/PBR/Lighting/EnhancedLighting.azsli From 24aa0f852179f94bce8ae354b66c6804628bd1b7 Mon Sep 17 00:00:00 2001 From: antonmic Date: Fri, 7 May 2021 20:56:40 -0700 Subject: [PATCH 023/231] skybox pass separation for single vs double output --- .../Common/Assets/Passes/OpaqueParent.pass | 13 ++++-- .../Assets/Passes/PassTemplates.azasset | 4 ++ .../Feature/Common/Assets/Passes/SkyBox.pass | 5 +++ .../Assets/Passes/SkyBox_TwoOutputs.pass | 43 +++++++++++++++++++ .../Reflections/ReflectionComposite.azsl | 15 ++----- .../Common/Assets/Shaders/SkyBox/SkyBox.azsl | 11 +++++ .../Shaders/SkyBox/SkyBox_TwoOutputs.azsl | 15 +++++++ .../Shaders/SkyBox/SkyBox_TwoOutputs.shader | 22 ++++++++++ 8 files changed, 113 insertions(+), 15 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Assets/Passes/SkyBox_TwoOutputs.pass create mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.azsl create mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.shader diff --git a/Gems/Atom/Feature/Common/Assets/Passes/OpaqueParent.pass b/Gems/Atom/Feature/Common/Assets/Passes/OpaqueParent.pass index 40d6a51e77..a691fe2534 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/OpaqueParent.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/OpaqueParent.pass @@ -305,7 +305,7 @@ }, { "Name": "SkyBoxPass", - "TemplateName": "SkyBoxTemplate", + "TemplateName": "SkyBoxTwoOutputsTemplate", "Enabled": true, "Connections": [ { @@ -315,6 +315,13 @@ "Attachment": "SpecularInputOutput" } }, + { + "LocalSlot": "ReflectionInputOutput", + "AttachmentRef": { + "Pass": "ReflectionsPass", + "Attachment": "ReflectionOutput" + } + }, { "LocalSlot": "SkyBoxDepth", "AttachmentRef": { @@ -331,8 +338,8 @@ { "LocalSlot": "ReflectionInput", "AttachmentRef": { - "Pass": "ReflectionsPass", - "Attachment": "ReflectionOutput" + "Pass": "SkyBoxPass", + "Attachment": "ReflectionInputOutput" } }, { diff --git a/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset b/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset index 2421d7fbe7..c56e8932b1 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset +++ b/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset @@ -92,6 +92,10 @@ "Name": "SkyBoxTemplate", "Path": "Passes/SkyBox.pass" }, + { + "Name": "SkyBoxTwoOutputsTemplate", + "Path": "Passes/SkyBox_TwoOutputs.pass" + }, { "Name": "UIPassTemplate", "Path": "Passes/UI.pass" diff --git a/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass b/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass index fb16271ba7..57f442e5de 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass @@ -12,6 +12,11 @@ "SlotType": "InputOutput", "ScopeAttachmentUsage": "RenderTarget" }, + { + "Name": "ReflectionInputOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "RenderTarget" + }, { "Name": "SkyBoxDepth", "SlotType": "InputOutput", diff --git a/Gems/Atom/Feature/Common/Assets/Passes/SkyBox_TwoOutputs.pass b/Gems/Atom/Feature/Common/Assets/Passes/SkyBox_TwoOutputs.pass new file mode 100644 index 0000000000..0ed7b39288 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Passes/SkyBox_TwoOutputs.pass @@ -0,0 +1,43 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "PassAsset", + "ClassData": { + "PassTemplate": { + "Name": "SkyBoxTwoOutputsTemplate", + "PassClass": "FullScreenTriangle", + "Slots": [ + { + "Name": "SpecularInputOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "RenderTarget" + }, + { + "Name": "ReflectionInputOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "RenderTarget" + }, + { + "Name": "SkyBoxDepth", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "DepthStencil" + } + ], + "PassData": { + "$type": "FullscreenTrianglePassData", + "ShaderAsset": { + "FilePath": "shaders/skybox/skybox_twooutputs.shader" + }, + "PipelineViewTag": "MainCamera", + "ShaderDataMappings": { + "FloatMappings": [ + { + "Name": "m_sunIntensityMultiplier", + "Value": 1.0 + } + ] + } + } + } + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionComposite.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionComposite.azsl index 865d657d85..92f8c3f638 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionComposite.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionComposite.azsl @@ -53,22 +53,13 @@ PSOutput MainPS(VSOutput IN) uint width, height, samples; PassSrg::m_reflection.GetDimensions(width, height, samples); - float nonZeroSamples = 0.0f; for (uint sampleIndex = 0; sampleIndex < samples; ++sampleIndex) { - float3 reflectionSample = PassSrg::m_reflection.Load(IN.m_position.xy, sampleIndex).rgb; - if(any(reflectionSample)) - { - reflection += reflectionSample; - nonZeroSamples += 1.0f; - } - } - - if(nonZeroSamples != 0.0f) - { - reflection /= nonZeroSamples; + reflection += PassSrg::m_reflection.Load(IN.m_position.xy, sampleIndex).rgb; } + reflection /= samples; + PSOutput OUT; OUT.m_color = float4(reflection, 1.0f); return OUT; diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl index a7de426374..4b3e9536b7 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl @@ -10,6 +10,11 @@ * */ +// Static Options: +// +// SKYBOX_TWO_OUTPUTS - Allows the skybox to render to two rendertargets instead of one + + #include #include #include @@ -102,6 +107,9 @@ float3 GetCubemapCoords(float3 original) struct PSOutput { float4 m_specular : SV_Target0; +#ifdef SKYBOX_TWO_OUTPUTS + float4 m_reflection : SV_Target1; +#endif }; PSOutput MainPS(VSOutput input) @@ -162,5 +170,8 @@ PSOutput MainPS(VSOutput input) PSOutput OUT; OUT.m_specular = float4(color, 1.0); +#ifdef SKYBOX_TWO_OUTPUTS + OUT.m_reflection = float4(color, 1.0); +#endif return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.azsl new file mode 100644 index 0000000000..99d7b45e4c --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.azsl @@ -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. +* +*/ + +#define SKYBOX_TWO_OUTPUTS + +#include "SkyBox.azsl" diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.shader b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.shader new file mode 100644 index 0000000000..ec80d4a20e --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.shader @@ -0,0 +1,22 @@ +{ + "Source" : "SkyBox_TwoOutputs", + + "DepthStencilState" : { + "Depth" : { "Enable" : true, "CompareFunc" : "GreaterEqual" } + }, + + "ProgramSettings": + { + "EntryPoints": + [ + { + "name": "MainVS", + "type": "Vertex" + }, + { + "name": "MainPS", + "type": "Fragment" + } + ] + } +} From cb245730a1f214c4891817b11bb617166f73c7b7 Mon Sep 17 00:00:00 2001 From: antonmic Date: Sun, 9 May 2021 23:01:24 -0700 Subject: [PATCH 024/231] work in progress --- .../Types/StandardPBR_LowEndForward.azsl | 2 ++ .../Feature/Common/Assets/Passes/Forward.pass | 20 ------------------- .../Feature/Common/Assets/Passes/SkyBox.pass | 5 ----- .../Shaders/SkyBox/SkyBox_TwoOutputs.azsl | 2 ++ .../atom_feature_common_asset_files.cmake | 4 ++++ 5 files changed, 8 insertions(+), 25 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.azsl index a690cbf84a..c87faffcbe 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_LowEndForward.azsl @@ -10,6 +10,8 @@ * */ +// NOTE: This file is a temporary workaround until .shader files can #define macros for their .azsl files + #define QUALITY_LOW_END 1 #include "StandardPBR_ForwardPass.azsl" diff --git a/Gems/Atom/Feature/Common/Assets/Passes/Forward.pass b/Gems/Atom/Feature/Common/Assets/Passes/Forward.pass index 3dcc90ac5c..b66e3bb4e1 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/Forward.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/Forward.pass @@ -222,19 +222,6 @@ "AssetRef": { "FilePath": "Textures/BRDFTexture.attimage" } - }, - { - "Name": "ScatterDistanceImage", - "SizeSource": { - "Source": { - "Pass": "Parent", - "Attachment": "SwapChainOutput" - } - }, - "ImageDescriptor": { - "Format": "R11G11B10_FLOAT", - "SharedQueueMask": "Graphics" - } } ], "Connections": [ @@ -279,13 +266,6 @@ "Pass": "This", "Attachment": "BRDFTexture" } - }, - { - "LocalSlot": "ScatterDistanceOutput", - "AttachmentRef": { - "Pass": "This", - "Attachment": "ScatterDistanceImage" - } } ] } diff --git a/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass b/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass index 57f442e5de..fb16271ba7 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/SkyBox.pass @@ -12,11 +12,6 @@ "SlotType": "InputOutput", "ScopeAttachmentUsage": "RenderTarget" }, - { - "Name": "ReflectionInputOutput", - "SlotType": "InputOutput", - "ScopeAttachmentUsage": "RenderTarget" - }, { "Name": "SkyBoxDepth", "SlotType": "InputOutput", diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.azsl index 99d7b45e4c..feacd2f44f 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox_TwoOutputs.azsl @@ -10,6 +10,8 @@ * */ +// NOTE: This file is a temporary workaround until .shader files can #define macros for their .azsl files + #define SKYBOX_TWO_OUTPUTS #include "SkyBox.azsl" 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 6902d456ff..7419c1e669 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 @@ -54,6 +54,7 @@ set(FILES Materials/Types/StandardPBR_HandleOpacityMode.lua Materials/Types/StandardPBR_LowEndForward.azsl Materials/Types/StandardPBR_LowEndForward.shader + Materials/Types/StandardPBR_LowEndForward_EDS.shader Materials/Types/StandardPBR_ParallaxState.lua Materials/Types/StandardPBR_Roughness.lua Materials/Types/StandardPBR_ShaderEnable.lua @@ -194,6 +195,7 @@ set(FILES Passes/ShadowParent.pass Passes/Skinning.pass Passes/SkyBox.pass + Passes/SkyBox_TwoOutputs.pass Passes/SMAA1xApplyLinearHDRColor.pass Passes/SMAA1xApplyPerceptualColor.pass Passes/SMAABlendingWeightCalculation.pass @@ -483,4 +485,6 @@ set(FILES Shaders/SkinnedMesh/LinearSkinningPassSRG.azsli Shaders/SkyBox/SkyBox.azsl Shaders/SkyBox/SkyBox.shader + Shaders/SkyBox/SkyBox_TwoOutputs.azsl + Shaders/SkyBox/SkyBox_TwoOutputs.shader ) From 23194376271a4f486495e890aa048e41836dac51 Mon Sep 17 00:00:00 2001 From: zsolleci Date: Mon, 10 May 2021 10:17:05 -0500 Subject: [PATCH 025/231] changed file name per review feedback --- ...vasComponent_OnEntityActivatedDeactivated_PrintMessage.py} | 4 ++-- .../Gem/PythonTests/scripting/TestSuite_Active.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) rename AutomatedTesting/Gem/PythonTests/scripting/{OnEntityActivatedDeactivated_HappyPath_PrintMessage.py => ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py} (98%) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py index 721ab53d8e..14e0c849e3 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py @@ -23,7 +23,7 @@ class Tests(): # fmt: on -def OnEntityActivatedDeactivated_HappyPath_PrintMessage(): +def ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage(): """ Summary: Verify that the On Entity Activated/On Entity Deactivated nodes are working as expected @@ -189,4 +189,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(OnEntityActivatedDeactivated_HappyPath_PrintMessage) + Report.start_test(ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index a225ebd845..1c52aa18fe 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -68,12 +68,12 @@ class TestAutomation(TestAutomationBase): self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_OnEntityActivatedDeactivated_HappyPath_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): + def test_ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import OnEntityActivatedDeactivated_HappyPath_PrintMessage as test_module + from . import ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage as test_module self._run_test(request, workspace, editor, test_module) def test_NodePalette_HappyPath_ClearSelection(self, request, workspace, editor, launcher_platform, project): From 521a486ee45f373a4cf7d0f9fece8ac54086e02f Mon Sep 17 00:00:00 2001 From: moudgils Date: Mon, 10 May 2021 09:13:15 -0700 Subject: [PATCH 026/231] Fixes to ios build --- .../Code/Source/ImageBuilderComponent.cpp | 2 +- .../Source/Processing/ImageAssetProducer.cpp | 12 ++++-------- .../Atom/RHI.Reflect/ImageSubresource.h | 11 ++++++++++- .../Source/RHI.Reflect/ImageSubresource.cpp | 12 ++++++++++-- .../Code/Source/RHI/AsyncUploadQueue.cpp | 14 +++++++++++--- .../Shader/ShaderVariantTreeAsset.cpp | 19 ++++++++----------- 6 files changed, 44 insertions(+), 26 deletions(-) diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp index ccba00f15f..59c799a601 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp @@ -79,7 +79,7 @@ namespace ImageProcessingAtom builderDescriptor.m_busId = azrtti_typeid(); builderDescriptor.m_createJobFunction = AZStd::bind(&ImageBuilderWorker::CreateJobs, &m_imageBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); builderDescriptor.m_processJobFunction = AZStd::bind(&ImageBuilderWorker::ProcessJob, &m_imageBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); - builderDescriptor.m_version = 22; // [ATOM-14765] + builderDescriptor.m_version = 23; // [ATOM-14022] builderDescriptor.m_analysisFingerprint = ImageProcessingAtom::BuilderSettingManager::Instance()->GetAnalysisFingerprint(); m_imageBuilder.BusConnect(builderDescriptor.m_busId); AssetBuilderSDK::AssetBuilderBus::Broadcast(&AssetBuilderSDK::AssetBuilderBusTraits::RegisterBuilderInformation, builderDescriptor); diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageAssetProducer.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageAssetProducer.cpp index 9c02894b7c..2448f501af 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageAssetProducer.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageAssetProducer.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include @@ -238,14 +239,9 @@ namespace ImageProcessingAtom uint8_t* mipBuffer; uint32_t pitch; m_imageObject->GetImagePointer(mip, mipBuffer, pitch); - uint32_t mipBufferSize = m_imageObject->GetMipBufSize(mip); - - RHI::ImageSubresourceLayout layout; - layout.m_bytesPerImage = mipBufferSize / arraySize; - layout.m_rowCount = layout.m_bytesPerImage / pitch; - layout.m_size = RHI::Size(m_imageObject->GetWidth(mip), m_imageObject->GetHeight(mip) / arraySize, 1); - layout.m_bytesPerRow = pitch; - + RHI::Format format = Utils::PixelFormatToRHIFormat(m_imageObject->GetPixelFormat(), m_imageObject->HasImageFlags(EIF_SRGBRead)); + + RHI::ImageSubresourceLayout layout = RHI::GetImageSubresourceLayout(RHI::Size(m_imageObject->GetWidth(mip), m_imageObject->GetHeight(mip) / arraySize, 1), format); builder.BeginMip(layout); for (uint32_t arrayIndex = 0; arrayIndex < arraySize; ++arrayIndex) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ImageSubresource.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ImageSubresource.h index b536ed5524..d81ffc006c 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ImageSubresource.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ImageSubresource.h @@ -100,7 +100,9 @@ namespace AZ Size size, uint32_t rowCount, uint32_t bytesPerRow, - uint32_t bytesPerImage); + uint32_t bytesPerImage, + uint32_t numBlocksWidth, + uint32_t numBlocksHeight); /// The size of the image subresource in pixels. Certain formats have alignment requirements. /// Block compressed formats are 4 pixel aligned. Other non-standard formats may be 2 pixel aligned. @@ -114,6 +116,13 @@ namespace AZ /// The number of bytes in a single image slice. 3D textures are comprised of m_size.m_depth image slices. uint32_t m_bytesPerImage = 0; + + /// The number of blocks in width based on the texture fomat + uint32_t m_numBlocksWidth = 1; + + /// The number of blocks in height based on the texture fomat + uint32_t m_numBlocksHeight = 1; + }; struct ImageSubresourceLayoutPlaced : ImageSubresourceLayout diff --git a/Gems/Atom/RHI/Code/Source/RHI.Reflect/ImageSubresource.cpp b/Gems/Atom/RHI/Code/Source/RHI.Reflect/ImageSubresource.cpp index 4e34fe2b32..a956a13d1b 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Reflect/ImageSubresource.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Reflect/ImageSubresource.cpp @@ -102,11 +102,13 @@ namespace AZ if (auto* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) + ->Version(1) ->Field("m_size", &ImageSubresourceLayout::m_size) ->Field("m_rowCount", &ImageSubresourceLayout::m_rowCount) ->Field("m_bytesPerRow", &ImageSubresourceLayout::m_bytesPerRow) ->Field("m_bytesPerImage", &ImageSubresourceLayout::m_bytesPerImage) + ->Field("m_numBlocksWidth", &ImageSubresourceLayout::m_numBlocksWidth) + ->Field("m_numBlocksHeight", &ImageSubresourceLayout::m_numBlocksHeight) ; } } @@ -115,11 +117,15 @@ namespace AZ Size size, uint32_t rowCount, uint32_t bytesPerRow, - uint32_t bytesPerImage) + uint32_t bytesPerImage, + uint32_t numBlocksWidth, + uint32_t numBlocksHeight) : m_size{size} , m_rowCount{rowCount} , m_bytesPerRow{bytesPerRow} , m_bytesPerImage{bytesPerImage} + , m_numBlocksWidth{numBlocksWidth} + , m_numBlocksHeight{numBlocksHeight} {} ImageSubresourceLayoutPlaced::ImageSubresourceLayoutPlaced(const ImageSubresourceLayout& subresourceLayout, size_t offset) @@ -316,6 +322,8 @@ namespace AZ subresourceLayout.m_rowCount = numBlocksHigh; subresourceLayout.m_size.m_width = imageSize.m_width; subresourceLayout.m_size.m_height = imageSize.m_height; + subresourceLayout.m_numBlocksWidth = numBlocks; + subresourceLayout.m_numBlocksHeight = numBlocks; } else if (isPacked) { diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/AsyncUploadQueue.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/AsyncUploadQueue.cpp index 891f9ea2f3..d9a8f8aa3b 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/AsyncUploadQueue.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/AsyncUploadQueue.cpp @@ -190,8 +190,8 @@ namespace AZ const uint32_t stagingRowPitch = RHI::AlignUp(subresourceLayout.m_bytesPerRow, bufferOffsetAlign); const uint32_t stagingSlicePitch = RHI::AlignUp(subresourceLayout.m_rowCount * stagingRowPitch, bufferOffsetAlign); const uint32_t rowsPerSplit = static_cast(m_descriptor.m_stagingSizeInBytes) / stagingRowPitch; - const uint32_t compressedTexelBlockSizeHeight = subresourceLayout.m_size.m_height / subresourceLayout.m_rowCount; - + const uint32_t compressedTexelBlockSizeHeight = subresourceLayout.m_numBlocksHeight; + // ImageHeight must be bigger than or equal to the Image's row count. Images with a RowCount that is less than the ImageHeight indicates a block compression. // Images with a RowCount which is higher than the ImageHeight indicates a planar image, which is not supported for streaming images. if (subresourceLayout.m_size.m_height < subresourceLayout.m_rowCount) @@ -281,7 +281,7 @@ namespace AZ const uint32_t endRow = AZStd::min(startRow + rowsPerSplit, subresourceLayout.m_rowCount); // Calculate the blocksize for BC formatted images; the copy command works in texels. - const uint32_t heightToCopy = (endRow - startRow) * compressedTexelBlockSizeHeight; + uint32_t heightToCopy = (endRow - startRow) * compressedTexelBlockSizeHeight; // Copy subresource data to staging memory. uint8_t* stagingDataStart = framePacket->m_stagingResourceData + framePacket->m_dataOffset; @@ -293,6 +293,14 @@ namespace AZ const uint32_t bytesCopied = (endRow - startRow) * stagingRowPitch; Platform::SynchronizeBufferOnCPU(framePacket->m_stagingResource, framePacket->m_dataOffset, bytesCopied); + //Clamp heightToCopy to match subresourceLayout.m_size.m_height as it is possible to go over + //if subresourceLayout.m_size.m_height is not perfectly divisible by compressedTexelBlockSizeHeight + if(destHeight+heightToCopy > subresourceLayout.m_size.m_height) + { + uint32_t HeightDiff = (destHeight + heightToCopy) - subresourceLayout.m_size.m_height; + heightToCopy -= HeightDiff; + } + const RHI::Size sourceSize = RHI::Size(subresourceLayout.m_size.m_width, heightToCopy, 1); const RHI::Origin sourceOrigin = RHI::Origin(0, destHeight, depth); CopyBufferToImage(framePacket, image, stagingRowPitch, bytesCopied, diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantTreeAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantTreeAsset.cpp index 25ba5aa837..f550a6f2ca 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantTreeAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantTreeAsset.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include @@ -40,15 +41,12 @@ namespace AZ Data::AssetId ShaderVariantTreeAsset::GetShaderVariantTreeAssetIdFromShaderAssetId(const Data::AssetId& shaderAssetId) { //From the shaderAssetId We can deduce the path of the shader asset, and from the path of the shader asset we can deduce the path of the ShaderVariantTreeAsset. - AZStd::string shaderAssetPath; - AZ::Data::AssetCatalogRequestBus::BroadcastResult(shaderAssetPath - , &AZ::Data::AssetCatalogRequests::GetAssetPathById - , shaderAssetId); - - AZStd::string shaderAssetPathRoot; - AZStd::string shaderAssetPathName; - AzFramework::StringFunc::Path::Split(shaderAssetPath.c_str(), nullptr /*drive*/, &shaderAssetPathRoot, &shaderAssetPathName, nullptr /*extension*/); - + AZ::IO::FixedMaxPath shaderAssetPath; + AZ::Data::AssetCatalogRequestBus::BroadcastResult(shaderAssetPath.Native(), &AZ::Data::AssetCatalogRequests::GetAssetPathById + , shaderAssetId); + AZ::IO::FixedMaxPath shaderAssetPathRoot = shaderAssetPath.ParentPath(); + AZ::IO::FixedMaxPath shaderAssetPathName = shaderAssetPath.Stem(); + AZStd::string shaderVariantTreeAssetDir; AzFramework::StringFunc::Path::Join(ShaderVariantTreeAsset::CommonSubFolderLowerCase, shaderAssetPathRoot.c_str(), shaderVariantTreeAssetDir); AZStd::string shaderVariantTreeAssetFilename = AZStd::string::format("%s.%s", shaderAssetPathName.c_str(), ShaderVariantTreeAsset::Extension); @@ -63,8 +61,7 @@ namespace AZ { // If the game project did not customize the shadervariantlist, let's see if the original author of the .shader file // provided a shadervariantlist. - shaderVariantTreeAssetDir = shaderAssetPathRoot; - AzFramework::StringFunc::Path::Join(shaderVariantTreeAssetDir.c_str(), shaderVariantTreeAssetFilename.c_str(), shaderVariantTreeAssetPath); + AzFramework::StringFunc::Path::Join(shaderAssetPathRoot.c_str(), shaderVariantTreeAssetFilename.c_str(), shaderVariantTreeAssetPath); AZ::Data::AssetCatalogRequestBus::BroadcastResult(shaderVariantTreeAssetId, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath , shaderVariantTreeAssetPath.c_str(), AZ::Data::s_invalidAssetType, false); } From d1eae23347c095333ed5c83a934a407de192d9c2 Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Mon, 10 May 2021 17:26:46 +0100 Subject: [PATCH 027/231] reduced cursor size. --- .../Components/FancyDocking.cpp | 2 +- .../Components/Widgets/TabWidget.cpp | 4 +- .../img/UI20/Cursors/Grab_release.svg | 40 +++++++++---------- .../Components/img/UI20/Cursors/Grabbing.svg | 40 +++++++++++-------- 4 files changed, 47 insertions(+), 39 deletions(-) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp index b89a220b1a..1a7512a4fc 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp @@ -160,7 +160,7 @@ namespace AzQtComponents QObject::connect(m_dropZoneHoverFadeInTimer, &QTimer::timeout, this, &FancyDocking::onDropZoneHoverFadeInUpdate); m_dropZoneHoverFadeInTimer->setInterval(g_FancyDockingConstants.dropZoneHoverFadeUpdateIntervalMS); QIcon dragIcon = QIcon(QStringLiteral(":/Cursors/Grabbing.svg")); - m_dragCursor = QCursor(dragIcon.pixmap(32), 10, 5); + m_dragCursor = QCursor(dragIcon.pixmap(16), 5, 2); } FancyDocking::~FancyDocking() diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp index a0006d7979..48fb47d7e6 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TabWidget.cpp @@ -422,10 +422,10 @@ namespace AzQtComponents AzQtComponents::Style::addClass(this, g_emptyStyleClass); QIcon icon = QIcon(QStringLiteral(":/Cursors/Grab_release.svg")); - m_hoverCursor = QCursor(icon.pixmap(32), 10, 5); + m_hoverCursor = QCursor(icon.pixmap(16), 5, 2); icon = QIcon(QStringLiteral(":/Cursors/Grabbing.svg")); - m_dragCursor = QCursor(icon.pixmap(32), 10, 5); + m_dragCursor = QCursor(icon.pixmap(16), 5, 2); this->setCursor(m_hoverCursor); } diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg index c0da9b802f..ad89e7d1b1 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grab_release.svg @@ -1,5 +1,5 @@ - + diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg index e70be77d51..96de4e997b 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/Cursors/Grabbing.svg @@ -1,23 +1,31 @@ - + - - - - - + + + + + + + + + From 92ef82f9331dee683f3d4df7869c27d913321420 Mon Sep 17 00:00:00 2001 From: pereslav Date: Mon, 10 May 2021 19:52:23 +0100 Subject: [PATCH 028/231] Added handling parented net entities --- .../EntityReplicationManager.cpp | 6 ++--- .../NetworkEntity/NetworkEntityManager.cpp | 26 ++++++++++++++++++- .../Pipeline/NetworkPrefabProcessor.cpp | 4 +++ 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 74bdcd5cf0..64eb3fcc6a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -550,10 +550,10 @@ namespace Multiplayer { replicatorEntity = entityList[0]; } - - AZ_Assert(replicatorEntity != nullptr, "Failed to create entity from prefab %s", prefabEntityId.m_prefabName.GetCStr()); - if (replicatorEntity == nullptr) + else { + AZ_Assert(false, "There should be exactly one created entity out of prefab %s, index %d. Got: %d", + prefabEntityId.m_prefabName.GetCStr(), prefabEntityId.m_entityOffset, entityList.size()); return false; } } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index ce55f66caa..3bcd613d8b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -334,15 +334,39 @@ namespace Multiplayer const AzFramework::Spawnable::EntityList& entities = spawnable.GetEntities(); size_t entitiesSize = entities.size(); + using EntityIdMap = AZStd::unordered_map; + EntityIdMap originalToCloneIdMap; + for (size_t i = 0; i < entitiesSize; ++i) { - AZ::Entity* clone = serializeContext->CloneObject(entities[i].get()); + AZ::Entity* originalEntity = entities[i].get(); + AZ::Entity* clone = serializeContext->CloneObject(originalEntity); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); + clone->SetId(AZ::Entity::MakeId()); + originalToCloneIdMap[originalEntity->GetId()] = clone->GetId(); + NetBindComponent* netBindComponent = clone->FindComponent(); if (netBindComponent != nullptr) { + // Update TransformComponent parent Id. It is guaranteed for the entities array to be sorted from parent->child here. + auto* transformComponent = clone->FindComponent(); + AZ::EntityId parentId = transformComponent->GetParentId(); + if (parentId.IsValid()) + { + auto it = originalToCloneIdMap.find(parentId); + if (it != originalToCloneIdMap.end()) + { + transformComponent->SetParentRelative(it->second); + } + else + { + AZ_Warning("NetworkEntityManager", false, "Entity %s doesn't have the parent entity %s present in network.spawnable", + clone->GetName().c_str(), parentId.ToString().data()); + } + } + PrefabEntityId prefabEntityId; prefabEntityId.m_prefabName = m_networkPrefabLibrary.GetPrefabNameFromAssetId(spawnable.GetId()); prefabEntityId.m_entityOffset = aznumeric_cast(i); diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp index 4962d16fb4..56201bd5fd 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp @@ -59,6 +59,7 @@ namespace Multiplayer return result; } + void NetworkPrefabProcessor::ProcessPrefab(PrefabProcessorContext& context, AZStd::string_view prefabName, PrefabDom& prefab) { using namespace AzToolsFramework::Prefab; @@ -175,6 +176,9 @@ namespace Multiplayer (*it)->InvalidateDependencies(); (*it)->EvaluateDependencies(); } + + SpawnableUtils::SortEntitiesByTransformHierarchy(*networkSpawnable); + context.GetProcessedObjects().push_back(AZStd::move(object)); } else From f856bd26b08cb63bf67e14800ff42d2a25f5f6cb Mon Sep 17 00:00:00 2001 From: moudgils Date: Mon, 10 May 2021 13:58:43 -0700 Subject: [PATCH 029/231] Propogated fixes to other RHI backends --- .../RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp | 12 ++++++++++-- .../RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp | 10 +++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp index f816a7ae04..ec18b985ff 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp @@ -267,7 +267,7 @@ namespace AZ // Staging sizes uint32_t stagingRowPitch = RHI::AlignUp(subresourceLayout.m_bytesPerRow, DX12_TEXTURE_DATA_PITCH_ALIGNMENT); uint32_t stagingSlicePitch = RHI::AlignUp(subresourceLayout.m_rowCount*stagingRowPitch, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); - const uint32_t compressedTexelBlockSizeHeight = subresourceLayout.m_size.m_height / subresourceLayout.m_rowCount; + const uint32_t compressedTexelBlockSizeHeight = subresourceLayout.m_numBlocksHeight; // ImageHeight must be bigger than or equal to the Image's row count. Images with a RowCount that is less than the ImageHeight indicates a block compression. // Images with a RowCount which is higher than the ImageHeight indicates a planar image, which is not supported for streaming images. @@ -382,7 +382,7 @@ namespace AZ const uint32_t numRowsToCopy = endRow - startRow; // Calculate the blocksize for BC formatted images; the copy command works in texels. - const uint32_t heightToCopy = (endRow - startRow) * compressedTexelBlockSizeHeight; + uint32_t heightToCopy = (endRow - startRow) * compressedTexelBlockSizeHeight; // Copy subresource data to staging memory { @@ -398,6 +398,14 @@ namespace AZ } } + //Clamp heightToCopy to match subresourceLayout.m_size.m_height as it is possible to go over + //if subresourceLayout.m_size.m_height is not perfectly divisible by compressedTexelBlockSizeHeight + if(destHeight+heightToCopy > subresourceLayout.m_size.m_height) + { + uint32_t HeightDiff = (destHeight + heightToCopy) - subresourceLayout.m_size.m_height; + heightToCopy -= HeightDiff; + } + // Add copy command to copy image subresource from staging memory to image gpu resource // Source location diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp index a6e7ff082f..08d8fca9b3 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp @@ -214,7 +214,7 @@ namespace AZ const uint32_t stagingRowPitch = RHI::AlignUp(subresourceLayout.m_bytesPerRow, bufferOffsetAlign); const uint32_t stagingSlicePitch = subresourceLayout.m_rowCount * stagingRowPitch; const uint32_t rowsPerSplit = static_cast(m_descriptor.m_stagingSizeInBytes) / stagingRowPitch; - const uint32_t compressedTexelBlockSizeHeight = subresourceLayout.m_size.m_height / subresourceLayout.m_rowCount; + const uint32_t compressedTexelBlockSizeHeight = subresourceLayout.m_numBlocksHeight; // ImageHeight must be bigger than or equal to the Image's row count. Images with a RowCount that is less than the ImageHeight indicates a block compression. // Images with a RowCount which is higher than the ImageHeight indicates a planar image, which is not supported for streaming images. @@ -348,6 +348,14 @@ namespace AZ framePacket->m_stagingBuffer->GetBufferMemoryView()->Unmap(RHI::HostMemoryAccess::Write); } + //Clamp heightToCopy to match subresourceLayout.m_size.m_height as it is possible to go over + //if subresourceLayout.m_size.m_height is not perfectly divisible by compressedTexelBlockSizeHeight + if(destHeight+heightToCopy > subresourceLayout.m_size.m_height) + { + uint32_t HeightDiff = (destHeight + heightToCopy) - subresourceLayout.m_size.m_height; + heightToCopy -= HeightDiff; + } + // Add copy command to copy image subresource from staging memory to image GPU resource. copyDescriptor.m_destinationOrigin.m_top = destHeight; copyDescriptor.m_sourceSize.m_height = heightToCopy; From 3c315df36f5bc086806efda05b8cdec0131ecbd6 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Wed, 5 May 2021 16:47:44 -0700 Subject: [PATCH 030/231] Fix Camera transform property notifications. Moves transform notification logic from CComponentEntityObject::InvalidateTM (which will eventually go away) to AzToolsFramework::TransformComponent::OnTransformChanged. We also specifically make sure PropertyEditorEntityChangeNotifications::OnEntityComponentPropertyChanged fires, which is used by Track View to detect camera position changes. --- .../ToolsComponents/TransformComponent.cpp | 19 ++++++++++++++++++- .../Objects/ComponentEntityObject.cpp | 8 -------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index f8d02b6581..6ce797c3ee 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -253,7 +253,7 @@ namespace AzToolsFramework m_localTransformDirty = true; m_worldTransformDirty = true; - if (GetEntity()) + if (const AZ::Entity* entity = GetEntity()) { SetDirty(); @@ -265,6 +265,23 @@ namespace AzToolsFramework AZ::TransformNotificationBus::Event( GetEntityId(), &TransformNotification::OnTransformChanged, localTM, worldTM); + + // Fire a property changed notification for this component + if (const AZ::Component* component = entity->FindComponent()) + { + PropertyEditorEntityChangeNotificationBus::Event( + GetEntityId(), &PropertyEditorEntityChangeNotifications::OnEntityComponentPropertyChanged, component->GetId()); + } + + // Refresh the property editor if we're selected + bool selected = false; + ToolsApplicationRequestBus::BroadcastResult( + selected, &AzToolsFramework::ToolsApplicationRequests::IsSelected, GetEntityId()); + if (selected) + { + ToolsApplicationEvents::Bus::Broadcast( + &ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_Values); + } } } diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp index c85ed1248f..20ae0a74cd 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp @@ -609,14 +609,6 @@ void CComponentEntityObject::InvalidateTM(int nWhyFlags) { Matrix34 worldTransform = GetWorldTM(); EBUS_EVENT_ID(m_entityId, AZ::TransformBus, SetWorldTM, LYTransformToAZTransform(worldTransform)); - - // When transformed via the editor, make sure the entity is marked dirty for undo capture. - EBUS_EVENT(AzToolsFramework::ToolsApplicationRequests::Bus, AddDirtyEntity, m_entityId); - - if (CheckFlags(OBJFLAG_SELECTED)) - { - EBUS_EVENT(AzToolsFramework::ToolsApplicationEvents::Bus, InvalidatePropertyDisplay, AzToolsFramework::Refresh_Values); - } } } } From dca2294b362538a03f4566dd9e4d76634d16c9b1 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Wed, 5 May 2021 16:51:49 -0700 Subject: [PATCH 031/231] Move GetCameraTransform into RPI::View. --- Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h | 2 ++ Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp | 9 +++++++++ Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp | 7 +------ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h index d6146d3760..aad099dc23 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h @@ -91,6 +91,8 @@ namespace AZ const AZ::Matrix4x4& GetViewToWorldMatrix() const; const AZ::Matrix4x4& GetViewToClipMatrix() const; const AZ::Matrix4x4& GetWorldToClipMatrix() const; + //! Get the camera's world transform, converted from the viewToWorld matrix's native y-up to z-up + AZ::Transform GetCameraTransform() const; //! Finalize draw lists in this view. This function should only be called when all //! draw packets for current frame are added. diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index e3f41cbda9..85216707a8 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -110,6 +110,15 @@ namespace AZ InvalidateSrg(); } + AZ::Transform View::GetCameraTransform() const + { + const Quaternion zUpToYUp = Quaternion::CreateRotationX(-AZ::Constants::HalfPi); + return AZ::Transform::CreateFromQuaternionAndTranslation( + Quaternion::CreateFromMatrix4x4(m_worldToViewMatrix) * zUpToYUp, + m_worldToViewMatrix.GetTranslation() + ).GetOrthogonalized(); + } + void View::SetCameraTransform(const AZ::Matrix3x4& cameraTransform) { m_position = cameraTransform.GetTranslation(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp index b5d3f815fe..b2f9acb855 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp @@ -192,12 +192,7 @@ namespace AZ AZ::Transform ViewportContext::GetCameraTransform() const { - const Matrix4x4& worldToViewMatrix = GetDefaultView()->GetViewToWorldMatrix(); - const Quaternion zUpToYUp = Quaternion::CreateRotationX(-AZ::Constants::HalfPi); - return AZ::Transform::CreateFromQuaternionAndTranslation( - Quaternion::CreateFromMatrix4x4(worldToViewMatrix) * zUpToYUp, - worldToViewMatrix.GetTranslation() - ).GetOrthogonalized(); + return GetDefaultView()->GetCameraTransform(); } void ViewportContext::SetCameraTransform(const AZ::Transform& transform) From 5d9c99436a81cabeff5758a22f86522acfc63265 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Wed, 5 May 2021 16:54:31 -0700 Subject: [PATCH 032/231] Ensure CameraComponentController entities get synced with Atom camera changes. This ensures the camera entity's transform gets correctly set if the RPI::View (or ViewportContext) is directly used instead of adjusting the entity transform, for e.g. camera controllers. --- .../Code/Source/CameraComponentController.cpp | 18 ++++++++++++++++++ .../Code/Source/CameraComponentController.h | 3 +++ 2 files changed, 21 insertions(+) diff --git a/Gems/Camera/Code/Source/CameraComponentController.cpp b/Gems/Camera/Code/Source/CameraComponentController.cpp index 2799d897d6..3dcee68169 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.cpp +++ b/Gems/Camera/Code/Source/CameraComponentController.cpp @@ -160,6 +160,17 @@ namespace Camera incompatible.push_back(AZ_CRC("CameraService", 0x1dd1caa4)); } + void CameraComponentController::Init() + { + m_onViewMatrixChanged = AZ::Event::Handler([this](const AZ::Matrix4x4&) + { + if (!m_updatingTransformFromEntity) + { + AZ::TransformBus::Event(m_entityId, &AZ::TransformInterface::SetWorldTM, m_atomCamera->GetCameraTransform()); + } + }); + } + void CameraComponentController::Activate(AZ::EntityId entityId) { m_entityId = entityId; @@ -218,6 +229,8 @@ namespace Camera } } AZ::RPI::ViewProviderBus::Handler::BusConnect(m_entityId); + + m_atomCamera->ConnectWorldToViewMatrixChangedHandler(m_onViewMatrixChanged); } UpdateCamera(); @@ -258,6 +271,7 @@ namespace Camera if (atomViewportRequests) { AZ::RPI::ViewProviderBus::Handler::BusDisconnect(m_entityId); + m_onViewMatrixChanged.Disconnect(); } DeactivateAtomView(); @@ -376,7 +390,9 @@ namespace Camera if (m_atomCamera) { + m_updatingTransformFromEntity = true; m_atomCamera->SetCameraTransform(AZ::Matrix3x4::CreateFromTransform(world.GetOrthogonalized())); + m_updatingTransformFromEntity = false; } } @@ -425,7 +441,9 @@ namespace Camera m_config.m_nearClipDistance, m_config.m_farClipDistance, true); + m_updatingTransformFromEntity = true; m_atomCamera->SetViewToClipMatrix(viewToClipMatrix); + m_updatingTransformFromEntity = false; } } diff --git a/Gems/Camera/Code/Source/CameraComponentController.h b/Gems/Camera/Code/Source/CameraComponentController.h index 92e1354f17..cae6ad4663 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.h +++ b/Gems/Camera/Code/Source/CameraComponentController.h @@ -77,6 +77,7 @@ namespace Camera static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + void Init(); void Activate(AZ::EntityId entityId); void Deactivate(); void SetConfiguration(const CameraComponentConfig& config); @@ -121,6 +122,8 @@ namespace Camera // Atom integration AZ::RPI::ViewPtr m_atomCamera; AZ::RPI::AuxGeomDrawPtr m_atomAuxGeom; + AZ::Event::Handler m_onViewMatrixChanged; + bool m_updatingTransformFromEntity = false; // Cry view integration IView* m_view = nullptr; From ccfb232e93bf0c9298a8d2852496862aff794efd Mon Sep 17 00:00:00 2001 From: moudgils Date: Mon, 10 May 2021 15:19:37 -0700 Subject: [PATCH 033/231] Missed a change --- Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp index 08d8fca9b3..6b16110c12 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp @@ -333,7 +333,7 @@ namespace AZ const uint32_t endRow = AZStd::min(startRow + rowsPerSplit, subresourceLayout.m_rowCount); // Calculate the blocksize for BC formatted images; the copy command works in texels. - const uint32_t heightToCopy = (endRow - startRow) * compressedTexelBlockSizeHeight; + uint32_t heightToCopy = (endRow - startRow) * compressedTexelBlockSizeHeight; // Copy subresource data to staging memory. { From 64d53d1fabc4aa9d2fcad9c7506ce9dc78b26ec8 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Mon, 10 May 2021 15:53:11 -0700 Subject: [PATCH 034/231] Fix View::GetCameraTransform --- Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index 85216707a8..21a46693d5 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -112,10 +112,10 @@ namespace AZ AZ::Transform View::GetCameraTransform() const { - const Quaternion zUpToYUp = Quaternion::CreateRotationX(-AZ::Constants::HalfPi); + static const Quaternion yUpToZUp = Quaternion::CreateRotationX(-AZ::Constants::HalfPi); return AZ::Transform::CreateFromQuaternionAndTranslation( - Quaternion::CreateFromMatrix4x4(m_worldToViewMatrix) * zUpToYUp, - m_worldToViewMatrix.GetTranslation() + Quaternion::CreateFromMatrix4x4(m_viewToWorldMatrix) * yUpToZUp, + m_viewToWorldMatrix.GetTranslation() ).GetOrthogonalized(); } @@ -127,7 +127,7 @@ namespace AZ // is in a Z-up world and an identity matrix means that it faces along the positive-Y axis and Z is up. // An identity view matrix on the other hand looks along the negative Z-axis. // So we adjust for this by rotating the camera world matrix by 90 degrees around the X axis. - AZ::Matrix3x4 zUpToYUp = AZ::Matrix3x4::CreateRotationX(AZ::Constants::HalfPi); + static AZ::Matrix3x4 zUpToYUp = AZ::Matrix3x4::CreateRotationX(AZ::Constants::HalfPi); AZ::Matrix3x4 yUpWorld = cameraTransform * zUpToYUp; float viewToWorldMatrixRaw[16] = { From 7276253c4225dd09dc0208693815abffe7ac672c Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Tue, 11 May 2021 08:20:44 +0100 Subject: [PATCH 035/231] renamed function --- .../AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp | 4 ++-- .../AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index faeae0a06d..85784d61e0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -126,7 +126,7 @@ namespace AzToolsFramework { QStylePainter p(this); - if (IsSectionSeparator()) + if (IsReorderableRow()) { const QPen linePen(QColor(0x3B3E3F)); p.setPen(linePen); @@ -1332,7 +1332,7 @@ namespace AzToolsFramework return canBeTopLevel(this); } - bool PropertyRowWidget::IsSectionSeparator() const + bool PropertyRowWidget::IsReorderableRow() const { return CanBeReordered(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx index b6c94dc98b..58bf3bb9f0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx @@ -83,7 +83,7 @@ namespace AzToolsFramework PropertyRowWidget* GetParentRow() const { return m_parentRow; } int GetLevel() const; bool IsTopLevel() const; - bool IsSectionSeparator() const; + bool IsReorderableRow() const; // Remove the default label and append the text to the name label. bool GetAppendDefaultLabelToName(); From 8e4d0d73dcea7f50d05a9318011de9a07e0d88e6 Mon Sep 17 00:00:00 2001 From: antonmic Date: Tue, 11 May 2021 01:29:53 -0700 Subject: [PATCH 036/231] Good working state, but material always emmits low end draw item --- .../Materials/Types/StandardPBR.materialtype | 24 ++-- .../Atom/Features/PBR/Lights/Ibl.azsli | 108 ++++++------------ .../Atom/Features/ShaderQualityOptions.azsli | 3 +- .../Code/Include/Atom/RPI.Public/Pass/Pass.h | 1 + .../RPI/Code/Source/RPI.Public/Pass/Pass.cpp | 4 +- 5 files changed, 59 insertions(+), 81 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index 1612bf43b0..47d8a9d9d5 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -1304,9 +1304,11 @@ "textureProperty": "baseColor.textureMap", "useTextureProperty": "baseColor.useTexture", "dependentProperties": ["baseColor.textureMapUv", "baseColor.textureBlendMode"], - "shaderTags": [ + "shaderTags": [ "ForwardPass", - "ForwardPass_EDS" + "ForwardPass_EDS", + "LowEndForward", + "LowEndForward_EDS" ], "shaderOption": "o_baseColor_useTexture" } @@ -1317,9 +1319,11 @@ "textureProperty": "metallic.textureMap", "useTextureProperty": "metallic.useTexture", "dependentProperties": ["metallic.textureMapUv"], - "shaderTags": [ + "shaderTags": [ "ForwardPass", - "ForwardPass_EDS" + "ForwardPass_EDS", + "LowEndForward", + "LowEndForward_EDS" ], "shaderOption": "o_metallic_useTexture" } @@ -1330,9 +1334,11 @@ "textureProperty": "specularF0.textureMap", "useTextureProperty": "specularF0.useTexture", "dependentProperties": ["specularF0.textureMapUv"], - "shaderTags": [ + "shaderTags": [ "ForwardPass", - "ForwardPass_EDS" + "ForwardPass_EDS", + "LowEndForward", + "LowEndForward_EDS" ], "shaderOption": "o_specularF0_useTexture" } @@ -1343,9 +1349,11 @@ "textureProperty": "normal.textureMap", "useTextureProperty": "normal.useTexture", "dependentProperties": ["normal.textureMapUv", "normal.factor", "normal.flipX", "normal.flipY"], - "shaderTags": [ + "shaderTags": [ "ForwardPass", - "ForwardPass_EDS" + "ForwardPass_EDS", + "LowEndForward", + "LowEndForward_EDS" ], "shaderOption": "o_normal_useTexture" } diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/Ibl.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/Ibl.azsli index 7400005508..721c48835d 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/Ibl.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/Ibl.azsli @@ -18,32 +18,30 @@ #include #include -void ApplyIblDiffuse( +float3 GetIblDiffuse( float3 normal, float3 albedo, - float3 diffuseResponse, - out float3 outDiffuse) + float3 diffuseResponse) { float3 irradianceDir = MultiplyVectorQuaternion(normal, SceneSrg::m_iblOrientation); float3 diffuseSample = SceneSrg::m_diffuseEnvMap.Sample(SceneSrg::m_samplerEnv, GetCubemapCoords(irradianceDir)).rgb; - outDiffuse = diffuseResponse * albedo * diffuseSample; + return diffuseResponse * albedo * diffuseSample; } -void ApplyIblSpecular( +float3 GetIblSpecular( float3 position, float3 normal, float3 specularF0, float roughnessLinear, float3 dirToCamera, - float2 brdf, - out float3 outSpecular) + float2 brdf) { float3 reflectDir = reflect(-dirToCamera, normal); reflectDir = MultiplyVectorQuaternion(reflectDir, SceneSrg::m_iblOrientation); // global - outSpecular = SceneSrg::m_specularEnvMap.SampleLevel(SceneSrg::m_samplerEnv, GetCubemapCoords(reflectDir), GetRoughnessMip(roughnessLinear)).rgb; + float3 outSpecular = SceneSrg::m_specularEnvMap.SampleLevel(SceneSrg::m_samplerEnv, GetCubemapCoords(reflectDir), GetRoughnessMip(roughnessLinear)).rgb; outSpecular *= (specularF0 * brdf.x + brdf.y); // reflection probe @@ -72,86 +70,54 @@ void ApplyIblSpecular( outSpecular = lerp(outSpecular, probeSpecular, blendAmount); } + return outSpecular; } void ApplyIBL(Surface surface, inout LightingData lightingData) { - if (o_opacity_mode == OpacityMode::Blended || o_opacity_mode == OpacityMode::TintedTransparent) +#ifdef FORCE_IBL_IN_FORWARD_PASS + bool useDiffuseIbl = true; + bool useSpecularIbl = true; + bool useIbl = true; +#else + bool useDiffuseIbl = (o_opacity_mode == OpacityMode::Blended || o_opacity_mode == OpacityMode::TintedTransparent); + bool useSpecularIbl = (useDiffuseIbl || o_meshUseForwardPassIBLSpecular || o_materialUseForwardPassIBLSpecular); + bool useIbl = o_enableIBL && (useDiffuseIbl || useSpecularIbl); +#endif + + if(useIbl) { - // transparencies currently require IBL in the forward pass - if (o_enableIBL) + float iblExposureFactor = pow(2.0, SceneSrg::m_iblExposure); + + if(useDiffuseIbl) { - float3 iblDiffuse = 0.0f; - ApplyIblDiffuse( - surface.normal, - surface.albedo, - lightingData.diffuseResponse, - iblDiffuse); - - float3 iblSpecular = 0.0f; - ApplyIblSpecular( - surface.position, - surface.normal, - surface.specularF0, - surface.roughnessLinear, - lightingData.dirToCamera, - lightingData.brdf, - iblSpecular); - - // Adjust IBL lighting by exposure. - float iblExposureFactor = pow(2.0, SceneSrg::m_iblExposure); + float3 iblDiffuse = GetIblDiffuse(surface.normal, surface.albedo, lightingData.diffuseResponse); lightingData.diffuseLighting += (iblDiffuse * iblExposureFactor * lightingData.diffuseAmbientOcclusion); - lightingData.specularLighting += (iblSpecular * iblExposureFactor); } - } - else if (o_meshUseForwardPassIBLSpecular || o_materialUseForwardPassIBLSpecular) - { - if (o_enableIBL) - { - float3 iblSpecular = 0.0f; - ApplyIblSpecular( - surface.position, - surface.normal, - surface.specularF0, - surface.roughnessLinear, - lightingData.dirToCamera, - lightingData.brdf, - iblSpecular); + if(useSpecularIbl) + { + float3 iblSpecular = GetIblSpecular(surface.position, surface.normal, surface.specularF0, surface.roughnessLinear, lightingData.dirToCamera, lightingData.brdf); iblSpecular *= lightingData.multiScatterCompensation; - if (o_clearCoat_feature_enabled) + if (o_clearCoat_feature_enabled && surface.clearCoat.factor > 0.0f) { - if (surface.clearCoat.factor > 0.0f) - { - float clearCoatNdotV = saturate(dot(surface.clearCoat.normal, lightingData.dirToCamera)); - clearCoatNdotV = max(clearCoatNdotV, 0.01f); // [GFX TODO][ATOM-4466] This is a current band-aid for specular noise at grazing angles. - float2 clearCoatBrdf = PassSrg::m_brdfMap.Sample(PassSrg::LinearSampler, GetBRDFTexCoords(surface.clearCoat.roughness, clearCoatNdotV)).rg; + float clearCoatNdotV = saturate(dot(surface.clearCoat.normal, lightingData.dirToCamera)); + clearCoatNdotV = max(clearCoatNdotV, 0.01f); // [GFX TODO][ATOM-4466] This is a current band-aid for specular noise at grazing angles. + float2 clearCoatBrdf = PassSrg::m_brdfMap.Sample(PassSrg::LinearSampler, GetBRDFTexCoords(surface.clearCoat.roughness, clearCoatNdotV)).rg; - // clear coat uses fixed IOR = 1.5 represents polyurethane which is the most common material for gloss clear coat - // coat layer assumed to be dielectric thus don't need multiple scattering compensation - float3 clearCoatSpecularF0 = float3(0.04f, 0.04f, 0.04f); - float3 clearCoatIblSpecular = 0.0f; + // clear coat uses fixed IOR = 1.5 represents polyurethane which is the most common material for gloss clear coat + // coat layer assumed to be dielectric thus don't need multiple scattering compensation + float3 clearCoatSpecularF0 = float3(0.04f, 0.04f, 0.04f); + float3 clearCoatIblSpecular = GetIblSpecular(surface.position, surface.clearCoat.normal, clearCoatSpecularF0, surface.clearCoat.roughness, lightingData.dirToCamera, clearCoatBrdf); - ApplyIblSpecular( - surface.position, - surface.clearCoat.normal, - clearCoatSpecularF0, - surface.clearCoat.roughness, - lightingData.dirToCamera, - clearCoatBrdf, - clearCoatIblSpecular); - - clearCoatIblSpecular *= surface.clearCoat.factor; + clearCoatIblSpecular *= surface.clearCoat.factor; - // attenuate base layer energy - float3 clearCoatResponse = FresnelSchlickWithRoughness(clearCoatNdotV, clearCoatSpecularF0, surface.clearCoat.roughness) * surface.clearCoat.factor; - iblSpecular = iblSpecular * (1.0 - clearCoatResponse) * (1.0 - clearCoatResponse) + clearCoatIblSpecular; - } + // attenuate base layer energy + float3 clearCoatResponse = FresnelSchlickWithRoughness(clearCoatNdotV, clearCoatSpecularF0, surface.clearCoat.roughness) * surface.clearCoat.factor; + iblSpecular = iblSpecular * (1.0 - clearCoatResponse) * (1.0 - clearCoatResponse) + clearCoatIblSpecular; } - - float iblExposureFactor = pow(2.0f, SceneSrg::m_iblExposure); lightingData.specularLighting += (iblSpecular * iblExposureFactor); } } diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli index 907e67ada5..d6fb259548 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli @@ -18,7 +18,8 @@ #ifdef QUALITY_LOW_END -#define UNIFIED_FORWARD_OUTPUT 1 +#define UNIFIED_FORWARD_OUTPUT 1 +#define FORCE_IBL_IN_FORWARD_PASS 1 #endif 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 b0d6bd4117..1cba71ae7e 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 @@ -381,6 +381,7 @@ namespace AZ 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; 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 9401d1a9e0..f93d661b0f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp @@ -93,11 +93,12 @@ namespace AZ void Pass::SetEnabled(bool enabled) { m_flags.m_enabled = enabled; + OnHierarchyChange(); } bool Pass::IsEnabled() const { - return m_flags.m_enabled; + return m_flags.m_enabled && (m_flags.m_parentEnabled || m_parent == nullptr); } // --- Error Logging --- @@ -140,6 +141,7 @@ namespace AZ } // Set new tree depth and path + m_flags.m_parentEnabled = m_parent->IsEnabled(); m_treeDepth = m_parent->m_treeDepth + 1; m_path = ConcatPassName(m_parent->m_path, m_name); m_flags.m_partOfHierarchy = m_parent->m_flags.m_partOfHierarchy; From b08643d9da90d0215ed5b22efcc3716fdaa90622 Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Tue, 11 May 2021 11:24:51 +0100 Subject: [PATCH 037/231] Use renamed functions in stylesheet. --- .../AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx | 2 +- Code/Sandbox/Editor/Style/Editor.qss | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx index 58bf3bb9f0..1c17cab69f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx @@ -44,7 +44,7 @@ namespace AzToolsFramework Q_PROPERTY(bool hasChildRows READ HasChildRows); Q_PROPERTY(bool isTopLevel READ IsTopLevel); Q_PROPERTY(int getLevel READ GetLevel); - Q_PROPERTY(bool isSectionSeparator READ IsSectionSeparator); + Q_PROPERTY(bool canBeReordered READ CanBeReordered); Q_PROPERTY(bool appendDefaultLabelToName READ GetAppendDefaultLabelToName WRITE AppendDefaultLabelToName) public: AZ_CLASS_ALLOCATOR(PropertyRowWidget, AZ::SystemAllocator, 0) diff --git a/Code/Sandbox/Editor/Style/Editor.qss b/Code/Sandbox/Editor/Style/Editor.qss index 7887560105..fa7d67dd43 100644 --- a/Code/Sandbox/Editor/Style/Editor.qss +++ b/Code/Sandbox/Editor/Style/Editor.qss @@ -38,7 +38,7 @@ AzToolsFramework--ComponentPaletteWidget > QTreeView background-color: #222222; } -AzToolsFramework--PropertyRowWidget[isSectionSeparator="true"] QLabel#Name +AzToolsFramework--PropertyRowWidget[canBeReordered="true"] QLabel#Name { font-weight: bold; } From dbe16c6a164cf89342749efbbd2d0785d473a37a Mon Sep 17 00:00:00 2001 From: darapan Date: Tue, 11 May 2021 05:07:16 -0700 Subject: [PATCH 038/231] "fixing review comments" --- ...s.py => Editor_NewExistingLevels_Works.py} | 17 +++++--------- .../Gem/PythonTests/smoke/ImportPathHelper.py | 16 ------------- ....py => test_CLITool_AssetBuilder_Works.py} | 7 +++--- ...> test_CLITool_AssetBundlerBatch_Works.py} | 7 +++--- ...test_CLITool_AssetProcessorBatch_Works.py} | 23 +++++-------------- ....py => test_CLITool_AzTestRunner_Works.py} | 7 +++--- ...st_CLITool_PythonBindingsExample_Works.py} | 8 +++---- ...st_CLITool_SerializeContextTools_Works.py} | 7 +++--- ...=> test_Editor_NewExistingLevels_Works.py} | 6 +++-- ...> test_StaticTools_GenPakShaders_Works.py} | 7 +++--- 10 files changed, 34 insertions(+), 71 deletions(-) rename AutomatedTesting/Gem/PythonTests/smoke/{Editor_NewExistingLevels.py => Editor_NewExistingLevels_Works.py} (93%) delete mode 100644 AutomatedTesting/Gem/PythonTests/smoke/ImportPathHelper.py rename AutomatedTesting/Gem/PythonTests/smoke/{test_AssetBuilder.py => test_CLITool_AssetBuilder_Works.py} (89%) rename AutomatedTesting/Gem/PythonTests/smoke/{test_AssetBundlerBatch.py => test_CLITool_AssetBundlerBatch_Works.py} (89%) rename AutomatedTesting/Gem/PythonTests/smoke/{test_AssetProcessorBatch.py => test_CLITool_AssetProcessorBatch_Works.py} (54%) rename AutomatedTesting/Gem/PythonTests/smoke/{test_AzTestRunner.py => test_CLITool_AzTestRunner_Works.py} (90%) rename AutomatedTesting/Gem/PythonTests/smoke/{test_PythonBindingsExample.py => test_CLITool_PythonBindingsExample_Works.py} (87%) rename AutomatedTesting/Gem/PythonTests/smoke/{test_SerializeContextTools.py => test_CLITool_SerializeContextTools_Works.py} (88%) rename AutomatedTesting/Gem/PythonTests/smoke/{test_Editor_NewExistingLevels.py => test_Editor_NewExistingLevels_Works.py} (88%) rename AutomatedTesting/Gem/PythonTests/smoke/{test_Statictool_Scripts.py => test_StaticTools_GenPakShaders_Works.py} (90%) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels.py b/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels_Works.py similarity index 93% rename from AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels.py rename to AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels_Works.py index 4e4a037ec9..ce46da494c 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels_Works.py @@ -9,9 +9,7 @@ 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. -Test case ID: LY-123945 Test Case Title: Create Test for UI apps- Editor -URL of the test case: https://jira.agscollab.com/browse/LY-123945 """ @@ -30,7 +28,7 @@ class Tests(): # fmt: on -def Editor_NewExistingLevels(): +def Editor_NewExistingLevels_Works(): """ Summary: Perform the below operations on Editor @@ -69,9 +67,9 @@ def Editor_NewExistingLevels(): """ import os - import hydra_editor_utils as hydra - from utils import TestHelper as helper - from utils import Report + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import TestHelper as helper + from editor_python_test_tools.utils import Report import azlmbr.bus as bus import azlmbr.editor as editor import azlmbr.legacy.general as general @@ -146,10 +144,7 @@ def Editor_NewExistingLevels(): if __name__ == "__main__": - import ImportPathHelper as imports - imports.init() + from editor_python_test_tools.utils import Report - from utils import Report - - Report.start_test(Editor_NewExistingLevels) + Report.start_test(Editor_NewExistingLevels_Works) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/smoke/ImportPathHelper.py deleted file mode 100644 index 70bed6e526..0000000000 --- a/AutomatedTesting/Gem/PythonTests/smoke/ImportPathHelper.py +++ /dev/null @@ -1,16 +0,0 @@ -""" -All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -its licensors. - -For complete copyright and license terms please see the LICENSE at the root of this -distribution (the "License"). All use of this software is governed by the License, -or, if provided, by the license below or the license accompanying this file. Do not -remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -""" - -def init(): - import os - import sys - sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') - sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../EditorPythonTestTools/editor_python_test_tools') diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_AssetBuilder.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBuilder_Works.py similarity index 89% rename from AutomatedTesting/Gem/PythonTests/smoke/test_AssetBuilder.py rename to AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBuilder_Works.py index da2abff50f..e20809b1b8 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_AssetBuilder.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBuilder_Works.py @@ -10,7 +10,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ """ -LY-124059 : CLI tool - AssetBuilder +CLI tool - AssetBuilder Launch AssetBuilder and Verify the help message """ @@ -23,7 +23,7 @@ import ly_test_tools.environment.process_utils as process_utils @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.usefixtures("automatic_process_killer") @pytest.mark.SUITE_smoke -class TestAssetBuilder(object): +class TestCLIToolAssetBuilderWorks(object): @pytest.fixture(autouse=True) def setup_teardown(self, request): def teardown(): @@ -31,8 +31,7 @@ class TestAssetBuilder(object): request.addfinalizer(teardown) - @pytest.mark.test_case_id("LY-124059") - def test_AssetBuilder(self, request, editor, build_directory): + def test_CLITool_AssetBuilder_Works(self, request, editor, build_directory): file_path = os.path.join(build_directory, "AssetBuilder") help_message = "AssetBuilder is part of the Asset Processor" # Launch AssetBuilder diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_AssetBundlerBatch.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBundlerBatch_Works.py similarity index 89% rename from AutomatedTesting/Gem/PythonTests/smoke/test_AssetBundlerBatch.py rename to AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBundlerBatch_Works.py index d361c62f5f..8a20715b3f 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_AssetBundlerBatch.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBundlerBatch_Works.py @@ -10,7 +10,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ """ -LY-124060 : CLI tool - AssetBundlerBatch +CLI tool - AssetBundlerBatch Launch AssetBundlerBatch and Verify the help message """ @@ -23,7 +23,7 @@ import ly_test_tools.environment.process_utils as process_utils @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.usefixtures("automatic_process_killer") @pytest.mark.SUITE_smoke -class TestAssetBundlerBatch(object): +class TestCLIToolAssetBundlerBatchWorks(object): @pytest.fixture(autouse=True) def setup_teardown(self, request): def teardown(): @@ -31,8 +31,7 @@ class TestAssetBundlerBatch(object): request.addfinalizer(teardown) - @pytest.mark.test_case_id("LY-124060") - def test_AssetBundlerBatch(self, request, editor, build_directory): + def test_CLITool_AssetBundlerBatch_Works(self, request, editor, build_directory): file_path = os.path.join(build_directory, "AssetBundlerBatch") help_message = "Specifies the Seed List file to operate on by path" # Launch AssetBundlerBatch diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_AssetProcessorBatch.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetProcessorBatch_Works.py similarity index 54% rename from AutomatedTesting/Gem/PythonTests/smoke/test_AssetProcessorBatch.py rename to AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetProcessorBatch_Works.py index ab541b94c1..30e681050c 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_AssetProcessorBatch.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetProcessorBatch_Works.py @@ -10,34 +10,23 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ """ -LY-124061 : CLI tool - AssetProcessorBatch +CLI tool - AssetProcessorBatch Launch AssetProcessorBatch and Shutdown AssetProcessorBatch without any crash """ # Import builtin libraries import pytest -import os -import sys - -sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../assetpipeline/") - -# Import fixtures -from ap_fixtures.asset_processor_fixture import asset_processor as asset_processor +from ly_test_tools.o3de.asset_processor import AssetProcessor @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.usefixtures("asset_processor") @pytest.mark.SUITE_smoke -class TestsAssetProcessorBatchs(object): - @pytest.mark.test_case_id("LY-124061") - def test_AssetProcessorBatch(self, asset_processor): +class TestsCLIToolAssetProcessorBatchWorks(object): + def test_CLITool_AssetProcessorBatch_Works(self, workspace): """ Test Launching AssetProcessorBatch and verifies that is shuts down without issue """ - # Create a sample asset root so we don't process every asset for every platform - asset_processor.create_temp_asset_root() - # Launch AssetProcessorBatch, assert batch processing success - result, _ = asset_processor.batch_process() - assert result, "AP Batch failed" + asset_processor = AssetProcessor(workspace) + asset_processor.batch_process() diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_AzTestRunner.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AzTestRunner_Works.py similarity index 90% rename from AutomatedTesting/Gem/PythonTests/smoke/test_AzTestRunner.py rename to AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AzTestRunner_Works.py index d1bc44fe2f..5983cd7496 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_AzTestRunner.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AzTestRunner_Works.py @@ -10,7 +10,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ """ -LY-124062 : CLI tool - AzTestRunner +CLI tool - AzTestRunner Launch AzTestRunner and Verify the help message """ @@ -23,7 +23,7 @@ import ly_test_tools.environment.process_utils as process_utils @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.usefixtures("automatic_process_killer") @pytest.mark.SUITE_smoke -class TestAzTestRunner(object): +class TestCLIToolAzTestRunnerWorks(object): @pytest.fixture(autouse=True) def setup_teardown(self, request): def teardown(): @@ -31,8 +31,7 @@ class TestAzTestRunner(object): request.addfinalizer(teardown) - @pytest.mark.test_case_id("LY-124062") - def test_AzTestRunner(self, request, editor, build_directory): + def test_CLITool_AzTestRunner_Works(self, request, editor, build_directory): file_path = os.path.join(build_directory, "AzTestRunner") help_message = "OKAY Symbol found: AzRunUnitTests" # Launch AzTestRunner diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_PythonBindingsExample.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_PythonBindingsExample_Works.py similarity index 87% rename from AutomatedTesting/Gem/PythonTests/smoke/test_PythonBindingsExample.py rename to AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_PythonBindingsExample_Works.py index 140e76fc96..68d12d0e70 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_PythonBindingsExample.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_PythonBindingsExample_Works.py @@ -10,7 +10,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ """ -LY-124064 : CLI tool - PythonBindingsExample +CLI tool - PythonBindingsExample Launch PythonBindingsExample and Verify the help message """ @@ -23,7 +23,7 @@ import ly_test_tools.environment.process_utils as process_utils @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.usefixtures("automatic_process_killer") @pytest.mark.SUITE_smoke -class TestPythonBindingsExample(object): +class TestCLIToolPythonBindingsExampleWorks(object): @pytest.fixture(autouse=True) def setup_teardown(self, request): def teardown(): @@ -31,8 +31,7 @@ class TestPythonBindingsExample(object): request.addfinalizer(teardown) - @pytest.mark.test_case_id("LY-124064") - def test_PythonBindingsExample(self, request, editor, build_directory): + def test_CLITool_PythonBindingsExample_Works(self, request, editor, build_directory): file_path = os.path.join(build_directory, "PythonBindingsExample") help_message = "--help Prints the help text" # Launch PythonBindingsExample @@ -42,4 +41,3 @@ class TestPythonBindingsExample(object): ), f"Error occurred while launching {file_path}: {output.stderr}" # Verify help message assert help_message in str(output.stdout), f"Help Message: {help_message} is not present" - diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_SerializeContextTools.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_SerializeContextTools_Works.py similarity index 88% rename from AutomatedTesting/Gem/PythonTests/smoke/test_SerializeContextTools.py rename to AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_SerializeContextTools_Works.py index 763d84625d..94178ca9d6 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_SerializeContextTools.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_SerializeContextTools_Works.py @@ -10,7 +10,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ """ -LY-124066 : CLI tool - SerializeContextTools +CLI tool - SerializeContextTools Launch SerializeContextTools and Verify the help message """ @@ -23,7 +23,7 @@ import ly_test_tools.environment.process_utils as process_utils @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.usefixtures("automatic_process_killer") @pytest.mark.SUITE_smoke -class TestSerializeContextTools(object): +class TestCLIToolSerializeContextToolsWorks(object): @pytest.fixture(autouse=True) def setup_teardown(self, request): def teardown(): @@ -31,8 +31,7 @@ class TestSerializeContextTools(object): request.addfinalizer(teardown) - @pytest.mark.test_case_id("LY-124066") - def test_SerializeContextTools(self, request, editor, build_directory): + def test_CLITool_SerializeContextTools_Works(self, request, editor, build_directory): file_path = os.path.join(build_directory, "SerializeContextTools") help_message = "Converts a file with an ObjectStream to the new JSON" # Launch SerializeContextTools diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels.py b/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py similarity index 88% rename from AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels.py rename to AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py index 85d53d098d..510734a4a2 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py @@ -24,11 +24,13 @@ import ly_test_tools.environment.file_system as file_system @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.parametrize("level", ["temp_level"]) class TestAutomation(TestAutomationBase): - def test_Editor_NewExistingLevels(self, request, workspace, editor, level, project, launcher_platform): + def test_Editor_NewExistingLevels_Works(self, request, workspace, editor, level, project, launcher_platform): def teardown(): file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) + request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - from . import Editor_NewExistingLevels as test_module + from . import Editor_NewExistingLevels_Works as test_module + self._run_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py b/AutomatedTesting/Gem/PythonTests/smoke/test_StaticTools_GenPakShaders_Works.py similarity index 90% rename from AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py rename to AutomatedTesting/Gem/PythonTests/smoke/test_StaticTools_GenPakShaders_Works.py index 8eac2ff099..05b91a602d 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_Statictool_Scripts.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_StaticTools_GenPakShaders_Works.py @@ -10,7 +10,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ """ -LY-124058: Static tool scripts +Static tool scripts Launch Static tool and Verify the help message """ @@ -34,9 +34,8 @@ def verify_help_message(static_tool): @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.usefixtures("automatic_process_killer") @pytest.mark.SUITE_smoke -class TestStatictoolScripts(object): - @pytest.mark.test_case_id("LY-124058") - def test_Statictool_Scripts(self, request, editor): +class TestStaticToolsGenPakShadersWorks(object): + def test_StaticTools_GenPakShaders_Works(self, request, editor): static_tools = [ os.path.join(editor.workspace.paths.engine_root(), "scripts", "bundler", "gen_shaders.py"), os.path.join(editor.workspace.paths.engine_root(), "scripts", "bundler", "get_shader_list.py"), From d48df87bda8d653025e4a9c6fc8f45e873cbf443 Mon Sep 17 00:00:00 2001 From: darapan Date: Tue, 11 May 2021 05:20:06 -0700 Subject: [PATCH 039/231] "Updating Cmake" --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 127db8e7e6..2a0a7f8008 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -399,3 +399,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::Editor AutomatedTesting.GameLauncher AutomatedTesting.Assets + COMPONENT + Smoke + ) +endif() \ No newline at end of file From 006f4d2e8294da878161ce9db571e55b84fe2dc9 Mon Sep 17 00:00:00 2001 From: darapan Date: Tue, 11 May 2021 05:34:38 -0700 Subject: [PATCH 040/231] "Adding Ap Test" --- .../Gem/PythonTests/CMakeLists.txt | 2 +- .../test_UIApps_AssetProcessor_CheckIdle.py | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/test_UIApps_AssetProcessor_CheckIdle.py diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 2a0a7f8008..e91190f8e7 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -402,4 +402,4 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) COMPONENT Smoke ) -endif() \ No newline at end of file +endif() diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_UIApps_AssetProcessor_CheckIdle.py b/AutomatedTesting/Gem/PythonTests/smoke/test_UIApps_AssetProcessor_CheckIdle.py new file mode 100644 index 0000000000..0f5f870461 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_UIApps_AssetProcessor_CheckIdle.py @@ -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. +""" + +""" +UI Apps: AssetProcessor +Open AssetProcessor, Wait until AssetProcessor is Idle +Close AssetProcessor. +""" + + +import pytest +from ly_test_tools.o3de.asset_processor import AssetProcessor + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.usefixtures("automatic_process_killer") +@pytest.mark.SUITE_smoke +class TestsUIAppsAssetProcessorCheckIdle(object): + @pytest.fixture(autouse=True) + def setup_teardown(self, request): + self.asset_processor = None + + def teardown(): + self.asset_processor.stop() + + request.addfinalizer(teardown) + + def test_UIApps_AssetProcessor_CheckIdle(self, workspace): + """ + Test Launching AssetProcessorBatch and verifies that is shuts down without issue + """ + self.asset_processor = AssetProcessor(workspace) + self.asset_processor.gui_process() From 3ebf23211f8631c27ebe388830d471651f65ca66 Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Tue, 11 May 2021 09:37:34 -0700 Subject: [PATCH 041/231] Update Mutliplayer Autocomponent to add Get/Set behavior context methods for any Network Properties with GenerateEventBindings=true. Known issues: not tested with container types, some jinja whitespace --- .../Source/AutoGen/AutoComponent_Header.jinja | 1 + .../Source/AutoGen/AutoComponent_Source.jinja | 62 +++++++++++++++---- 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index 14a68cddf1..137a544a34 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -410,6 +410,7 @@ namespace {{ Component.attrib['Namespace'] }} static void Reflect(AZ::ReflectContext* context); static void ReflectToEditContext(AZ::ReflectContext* context); + static void ReflectToBehaviorContext(AZ::ReflectContext* context); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index fb802541ce..6467119b89 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -661,18 +661,42 @@ enum class NetworkProperties {# #} -{% macro DefineNetworkPropertyBehaviorReflection(Component, ReplicateFrom, ReplicateTo, ClassType) %} +{% macro DefineNetworkPropertyBehaviorReflection(Component, ReplicateFrom, ReplicateTo, ClassName) %} {% call(Property) AutoComponentMacros.ParseNetworkProperties(Component, ReplicateFrom, ReplicateTo) %} -{% if (Property.attrib['IsPublic'] | booleanTrue == true) %} -{% if Property.attrib['Container'] == 'Array' %} -->Event("Get{{ Property.attrib['Name'] }}", &{{ ClassType }}Bus::Events::Get{{ Property.attrib['Name'] }}) -{% elif Property.attrib['Container'] == 'Vector' %} -->Event("Get{{ Property.attrib['Name'] }}", &{{ ClassType }}Bus::Events::Get{{ Property.attrib['Name'] }}) -->Event("{{ Property.attrib['Name'] }}GetBack", &{{ ClassType }}Bus::Events::{{ Property.attrib['Name'] }}GetBack) -->Event("{{ Property.attrib['Name'] }}GetSize", &{{ ClassType }}Bus::Events::{{ Property.attrib['Name'] }}GetSize) -{% else %} -->Event("Get{{ Property.attrib['Name'] }}", &{{ ClassType }}Bus::Events::Get{{ Property.attrib['Name'] }}) -{% endif %} +{% if (Property.attrib['IsPublic'] | booleanTrue == true) and (Property.attrib['GenerateEventBindings'] | booleanTrue == true) %} + ->Method("Get{{ UpperFirst(Property.attrib['Name']) }}", [](AZ::EntityId id) -> {{ Property.attrib['Type'] }} + { + AZ::Entity* entity; + AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, id); + + if (entity) + { + if (auto* networkComponent = entity->FindComponent<{{ ClassName }}>()) + { + return networkComponent->Get{{ UpperFirst(Property.attrib['Name']) }}(); + } + } + + return {{ Property.attrib['Type'] }}(); + }) + ->Method("Set{{ UpperFirst(Property.attrib['Name']) }}", [](AZ::EntityId id, const {{ Property.attrib['Type'] }}& {{ LowerFirst(Property.attrib['Name']) }}) -> void + { + AZ::Entity* entity; + AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, id); + + if (entity) + { + return; + } + + if (auto* networkComponent = entity->FindComponent<{{ ClassName }}>()) + { + if (auto* controller = static_cast<{{ ClassName }}Controller*>(networkComponent->GetController())) + { + controller->Set{{ UpperFirst(Property.attrib['Name']) }}({{ LowerFirst(Property.attrib['Name']) }}); + } + } + }) {% endif %} {% endcall -%} {% endmacro %} @@ -805,6 +829,7 @@ m_{{ LowerFirst(Service.attrib['Name']) }} = FindComponent<{{ UpperFirst(Service {% endmacro %} {# + #} {% macro DefineNetworkPropertyEditConstruction(Component, ReplicateFrom, ReplicateTo, ClassName) %} {% call(Property) AutoComponentMacros.ParseNetworkProperties(Component, ReplicateFrom, ReplicateTo) %} @@ -1131,6 +1156,7 @@ namespace {{ Component.attrib['Namespace'] }} {{ DefineArchetypePropertyReflection(Component, ComponentBaseName)|indent(16) }}; } ReflectToEditContext(context); + ReflectToBehaviorContext(context); } void {{ ComponentBaseName }}::{{ ComponentBaseName }}::ReflectToEditContext(AZ::ReflectContext* context) @@ -1155,6 +1181,20 @@ namespace {{ Component.attrib['Namespace'] }} } } + void {{ ComponentBaseName }}::{{ ComponentBaseName }}::ReflectToBehaviorContext(AZ::ReflectContext* context) + { + if (auto* behaviorContext = azrtti_cast(context)) + { + behaviorContext->Class<{{ ComponentName }}>("{{ ComponentName }}") + {{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Authority', ComponentName)|indent(16) -}} +{{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Server', ComponentName)|indent(16) -}} +{{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Client', ComponentName)|indent(16) -}} +{{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Autonomous', ComponentName)|indent(16) -}} +{{ DefineNetworkPropertyBehaviorReflection(Component, 'Autonomous', 'Authority', ComponentName)|indent(16) }} + {{ DefineArchetypePropertyBehaviorReflection(Component, ComponentName)|indent(16) }}; + } + } + void {{ ComponentBaseName }}::{{ ComponentBaseName }}::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { provided.push_back(AZ_CRC_CE("{{ ComponentName }}Service")); From f7641f3d3845dad3acb219b727521a4ab26fc8a1 Mon Sep 17 00:00:00 2001 From: darapan Date: Tue, 11 May 2021 10:56:42 -0700 Subject: [PATCH 042/231] "Changing TIMEOUT in cmakelist.txt" --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index e91190f8e7..a81630b880 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -392,7 +392,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE smoke TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/smoke - TIMEOUT 3600 + TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor AZ::PythonBindingsExample From 7ff5c0e10526a1297e5248f8819c8e5f61604c9d Mon Sep 17 00:00:00 2001 From: nvsickle Date: Tue, 11 May 2021 12:18:04 -0700 Subject: [PATCH 043/231] Add multiline spacing and GetTextSize to Atom Font --- Code/CryEngine/CryCommon/IFont.h | 4 + .../AzFramework/Font/FontInterface.h | 4 + .../AtomLyIntegration/AtomFont/FFont.h | 14 +++ .../AtomFont/Code/Source/FFont.cpp | 93 ++++++++++++------- 4 files changed, 83 insertions(+), 32 deletions(-) diff --git a/Code/CryEngine/CryCommon/IFont.h b/Code/CryEngine/CryCommon/IFont.h index c8634fa854..7d573308aa 100644 --- a/Code/CryEngine/CryCommon/IFont.h +++ b/Code/CryEngine/CryCommon/IFont.h @@ -150,6 +150,7 @@ struct STextDrawContext Vec2 m_size; Vec2i m_requestSize; float m_widthScale; + float m_lineSpacing; float m_clipX; float m_clipY; @@ -180,6 +181,7 @@ struct STextDrawContext , m_size(16.0f, 16.0f) , m_requestSize(static_cast(m_size.x), static_cast(m_size.y)) , m_widthScale(1.0f) + , m_lineSpacing(0.f) , m_clipX(0) , m_clipY(0) , m_clipWidth(0) @@ -214,11 +216,13 @@ struct STextDrawContext void SetTransform(const Matrix34& transform) { m_transform = transform; } void SetBaseState(int baseState) { m_baseState = baseState; } void SetOverrideViewProjMatrices(bool overrideViewProjMatrices) { m_overrideViewProjMatrices = overrideViewProjMatrices; } + void SetLineSpacing(float lineSpacing) { m_lineSpacing = lineSpacing; } float GetCharWidth() const { return m_size.x; } float GetCharHeight() const { return m_size.y; } float GetCharWidthScale() const { return m_widthScale; } int GetFlags() const { return m_drawTextFlags; } + float GetLineSpacing() const { return m_lineSpacing; } bool IsColorOverridden() const { return m_colorOverride.a != 0; } }; diff --git a/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h b/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h index 7c5bcce6d6..48fa5bc2d2 100644 --- a/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h @@ -44,6 +44,7 @@ namespace AzFramework 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::Vector2 m_scale = AZ::Vector2(1.0f); //! font scale + float m_lineSpacing; //! 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_monospace = false; //! disable character proportional spacing @@ -67,6 +68,9 @@ namespace AzFramework virtual void DrawScreenAlignedText3d( const TextDrawParameters& params, const AZStd::string_view& string) = 0; + virtual AZ::Vector2 GetTextSize( + const TextDrawParameters& params, + const AZStd::string_view& string) = 0; }; class FontQueryInterface diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h index fd66534197..83273633be 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h @@ -213,6 +213,10 @@ namespace AZ const AzFramework::TextDrawParameters& params, const AZStd::string_view& string) override; + AZ::Vector2 GetTextSize( + const AzFramework::TextDrawParameters& params, + const AZStd::string_view& string) override; + public: FFont(AtomFont* atomFont, const char* fontName); @@ -282,6 +286,16 @@ namespace AZ RPI::WindowContextSharedPtr GetDefaultWindowContext() const; RPI::ViewportContextPtr GetDefaultViewportContext() const; + struct DrawParameters + { + TextDrawContext m_ctx; + AZ::Vector2 m_position; + AZ::Vector2 m_size; + AZ::RPI::ViewportContext* m_viewportContext; + const AZ::RHI::Viewport* m_viewport; + }; + DrawParameters ExtractDrawParameters(const AzFramework::TextDrawParameters& params, const AZStd::string_view& string, bool forceCalculateSize); + private: static constexpr uint32_t NumBuffers = 2; static constexpr float WindowScaleWidth = 800.0f; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index 40684640d6..48d24f0473 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -505,7 +505,7 @@ Vec2 AZ::FFont::GetTextSizeUInternal( } charX = offset.x; - charY += size.y; + charY += size.y * (1.f + ctx.GetLineSpacing()); if (charY > maxH) { @@ -944,7 +944,7 @@ int AZ::FFont::CreateQuadsForText(const RHI::Viewport& viewport, float x, float case '\n': { charX = baseXY.x + offset.x; - charY += size.y; + charY += size.y * (1.f + ctx.GetLineSpacing()); continue; } break; @@ -1674,47 +1674,47 @@ static void SetCommonContextFlags(AZ::TextDrawContext& ctx, const AzFramework::T } } -void AZ::FFont::DrawScreenAlignedText2d( - const AzFramework::TextDrawParameters& params, - const AZStd::string_view& string) +AZ::FFont::DrawParameters AZ::FFont::ExtractDrawParameters(const AzFramework::TextDrawParameters& params, const AZStd::string_view& string, bool forceCalculateSize) { + DrawParameters internalParams; if (params.m_drawViewportId == AzFramework::InvalidViewportId || string.empty()) { - return; + return internalParams; } //Code mostly duplicated from CRenderer::Draw2dTextWithDepth float posX = params.m_position.GetX(); float posY = params.m_position.GetY(); - AZ::RPI::ViewportContext* viewportContext = AZ::Interface::Get()->GetViewportContextById(params.m_drawViewportId).get(); - const AZ::RHI::Viewport& viewport = viewportContext->GetWindowContext()->GetViewport(); + internalParams.m_viewportContext = AZ::Interface::Get()->GetViewportContextById(params.m_drawViewportId).get(); + const AZ::RHI::Viewport& viewport = internalParams.m_viewportContext->GetWindowContext()->GetViewport(); + internalParams.m_viewport = &viewport; if (params.m_virtual800x600ScreenSize) { posX *= WindowScaleWidth / (viewport.m_maxX - viewport.m_minX); posY *= WindowScaleHeight / (viewport.m_maxY - viewport.m_minY); } - TextDrawContext ctx; - ctx.SetBaseState(GS_NODEPTHTEST); - ctx.SetColor(AZColorToLYColorF(params.m_color)); - ctx.SetCharWidthScale((params.m_monospace || params.m_scaleWithWindow) ? 0.5f : 1.0f); - ctx.EnableFrame(false); - ctx.SetProportional(!params.m_monospace && params.m_scaleWithWindow); - ctx.SetSizeIn800x600(params.m_scaleWithWindow && params.m_virtual800x600ScreenSize); - ctx.SetSize(AZVec2ToLYVec2(UiDraw_TextSizeFactor * params.m_scale)); + internalParams.m_ctx.SetBaseState(GS_NODEPTHTEST); + internalParams.m_ctx.SetColor(AZColorToLYColorF(params.m_color)); + 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.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) + params.m_vAlign != AzFramework::TextVerticalAlignment::Top || + forceCalculateSize) { - Vec2 textSize = GetTextSizeUInternal(viewport, string.data(), params.m_multiline, ctx); - + Vec2 textSize = GetTextSizeUInternal(viewport, string.data(), params.m_multiline, internalParams.m_ctx); // If we're using virtual 800x600 coordinates, convert the text size from // pixels to that before using it as an offset. - if (ctx.m_sizeIn800x600) + if (internalParams.m_ctx.m_sizeIn800x600) { float width = 1.0f; float height = 1.0f; @@ -1740,19 +1740,33 @@ void AZ::FFont::DrawScreenAlignedText2d( { posY -= textSize.y; } + internalParams.m_size = AZ::Vector2{textSize.x, textSize.y}; + } + SetCommonContextFlags(internalParams.m_ctx, params); + internalParams.m_ctx.m_drawTextFlags |= eDrawText_2D; + internalParams.m_position = AZ::Vector2{posX, posY}; + return internalParams; +} + +void AZ::FFont::DrawScreenAlignedText2d( + const AzFramework::TextDrawParameters& params, + const AZStd::string_view& string) +{ + DrawParameters internalParams = ExtractDrawParameters(params, string, false); + if (!internalParams.m_viewportContext) + { + return; } - SetCommonContextFlags(ctx, params); - ctx.m_drawTextFlags |= eDrawText_2D; DrawStringUInternal( - viewport, - viewportContext, - posX, - posY, + *internalParams.m_viewport, + internalParams.m_viewportContext, + internalParams.m_position.GetX(), + internalParams.m_position.GetY(), params.m_position.GetZ(), // Z string.data(), params.m_multiline, - ctx + internalParams.m_ctx ); } @@ -1760,13 +1774,12 @@ void AZ::FFont::DrawScreenAlignedText3d( const AzFramework::TextDrawParameters& params, const AZStd::string_view& string) { - if (params.m_drawViewportId == AzFramework::InvalidViewportId || - string.empty()) + DrawParameters internalParams = ExtractDrawParameters(params, string, false); + if (!internalParams.m_viewportContext) { return; } - AZ::RPI::ViewportContext* viewportContext = AZ::Interface::Get()->GetViewportContextById(params.m_drawViewportId).get(); - AZ::RPI::ViewPtr currentView = viewportContext->GetDefaultView(); + AZ::RPI::ViewPtr currentView = internalParams.m_viewportContext->GetDefaultView(); if (!currentView) { return; @@ -1778,7 +1791,23 @@ void AZ::FFont::DrawScreenAlignedText3d( ); AzFramework::TextDrawParameters param2d = params; param2d.m_position = positionNDC; - DrawScreenAlignedText2d(param2d, string); + + DrawStringUInternal( + *internalParams.m_viewport, + internalParams.m_viewportContext, + internalParams.m_position.GetX(), + internalParams.m_position.GetY(), + params.m_position.GetZ(), // Z + string.data(), + params.m_multiline, + internalParams.m_ctx + ); +} + +AZ::Vector2 AZ::FFont::GetTextSize(const AzFramework::TextDrawParameters& params, const AZStd::string_view& string) +{ + DrawParameters sizeParams = ExtractDrawParameters(params, string, true); + return sizeParams.m_size; } #endif //USE_NULLFONT_ALWAYS From fe2931829338c9e6805050533056417a2f2d2686 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Tue, 11 May 2021 12:18:49 -0700 Subject: [PATCH 044/231] Make ScriptTimePoint::Get const correct --- Code/Framework/AzCore/AzCore/Script/ScriptTimePoint.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/AzCore/Script/ScriptTimePoint.h b/Code/Framework/AzCore/AzCore/Script/ScriptTimePoint.h index 7cb81829ef..08c997de2d 100644 --- a/Code/Framework/AzCore/AzCore/Script/ScriptTimePoint.h +++ b/Code/Framework/AzCore/AzCore/Script/ScriptTimePoint.h @@ -43,7 +43,7 @@ namespace AZ return AZStd::string::format("Time %llu", m_timePoint.time_since_epoch().count()); } - const AZStd::chrono::system_clock::time_point& Get() { return m_timePoint; } + const AZStd::chrono::system_clock::time_point& Get() const { return m_timePoint; } // Returns the time point in seconds double GetSeconds() const From 3c5659668a0cd4343b7b7f86f56a3092328a4714 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Tue, 11 May 2021 12:19:56 -0700 Subject: [PATCH 045/231] Add AZ::RPI::ViewportContextRequests alias for the full interface --- Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContextBus.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContextBus.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContextBus.h index bc7e5a4b1d..377c1d5c4e 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContextBus.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContextBus.h @@ -92,6 +92,8 @@ namespace AZ virtual ViewPtr GetCurrentView(const Name& contextName) const = 0; }; + using ViewportContextRequests = AZ::Interface; + class ViewportContextManagerNotifications : public AZ::EBusTraits { From 85e4f0d65ff5d5b7b6e1ba9759cace1907f60634 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Tue, 11 May 2021 16:24:28 -0500 Subject: [PATCH 046/231] Fix AzFramework::g_defaultSceneEntityDebugDisplayId not working for the AtomDebugDisplayViewportInstance --- Code/Sandbox/Editor/EditorViewportWidget.cpp | 9 +++++ .../Code/Source/AtomBridgeSystemComponent.cpp | 38 +++++++------------ 2 files changed, 23 insertions(+), 24 deletions(-) diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 3803867870..631a93af92 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -452,6 +452,15 @@ void EditorViewportWidget::Update() return; } + static bool sentOnWindowCreated = false; + if (!sentOnWindowCreated && windowHandle()->isActive()) + { + sentOnWindowCreated = true; + AzFramework::WindowSystemNotificationBus::Broadcast( + &AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, + reinterpret_cast(winId())); + } + m_updatingCameraPosition = true; auto transform = LYTransformToAZTransform(m_Camera.GetMatrix()); m_renderViewport->GetViewportContext()->SetCameraTransform(transform); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp index 90731488f4..9148cdba6f 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp @@ -91,13 +91,9 @@ namespace AZ AZ_UNUSED(dependent); } - static const AZ::Crc32 mainViewportEntityDebugDisplayId = AZ_CRC_CE("MainViewportEntityDebugDisplayId"); - void AtomBridgeSystemComponent::Init() { -#if defined(ENABLE_ATOM_DEBUG_DISPLAY) && ENABLE_ATOM_DEBUG_DISPLAY AZ::RPI::ViewportContextManagerNotificationsBus::Handler::BusConnect(); -#endif } void AtomBridgeSystemComponent::Activate() @@ -112,9 +108,7 @@ namespace AZ void AtomBridgeSystemComponent::Deactivate() { -#if defined(ENABLE_ATOM_DEBUG_DISPLAY) && ENABLE_ATOM_DEBUG_DISPLAY AZ::RPI::ViewportContextManagerNotificationsBus::Handler::BusDisconnect(); -#endif RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get(); // Check if scene is emptry since scene might be released already when running AtomSampleViewer if (scene) @@ -193,36 +187,32 @@ namespace AZ renderPipeline = bootstrapScene->GetDefaultRenderPipeline(); renderPipeline->SetDefaultView(m_view); - - auto auxGeomFP = bootstrapScene->GetFeatureProcessor(); - if (auxGeomFP) - { - auxGeomFP->GetOrCreateDrawQueueForView(m_view.get()); - } - -#if defined(ENABLE_ATOM_DEBUG_DISPLAY) && ENABLE_ATOM_DEBUG_DISPLAY - // Make default AtomDebugDisplayViewportInterface for the scene - AZStd::shared_ptr mainEntityDebugDisplay = AZStd::make_shared(mainViewportEntityDebugDisplayId); - m_activeViewportsList[mainViewportEntityDebugDisplayId] = mainEntityDebugDisplay; -#endif } + else + { + m_view = renderPipeline->GetDefaultView(); + } + auto auxGeomFP = bootstrapScene->GetFeatureProcessor(); + if (auxGeomFP) + { + auxGeomFP->GetOrCreateDrawQueueForView(m_view.get()); + } + + // Make default AtomDebugDisplayViewportInterface for the scene + AZStd::shared_ptr mainEntityDebugDisplay = AZStd::make_shared(AzFramework::g_defaultSceneEntityDebugDisplayId); + m_activeViewportsList[AzFramework::g_defaultSceneEntityDebugDisplayId] = mainEntityDebugDisplay; } void AtomBridgeSystemComponent::OnViewportContextAdded(AZ::RPI::ViewportContextPtr viewportContext) { -#if defined(ENABLE_ATOM_DEBUG_DISPLAY) && ENABLE_ATOM_DEBUG_DISPLAY AZStd::shared_ptr viewportDebugDisplay = AZStd::make_shared(viewportContext); m_activeViewportsList[viewportContext->GetId()] = viewportDebugDisplay; -#endif } void AtomBridgeSystemComponent::OnViewportContextRemoved(AzFramework::ViewportId viewportId) { -#if defined(ENABLE_ATOM_DEBUG_DISPLAY) && ENABLE_ATOM_DEBUG_DISPLAY + AZ_Assert(viewportId != AzFramework::g_defaultSceneEntityDebugDisplayId, "Error trying to remove the default scene draw instance"); m_activeViewportsList.erase(viewportId); -#else - AZ_UNUSED(viewportId); -#endif } From 9775822778ec2cf8003ea86f455906f75bce1c14 Mon Sep 17 00:00:00 2001 From: scottr Date: Tue, 11 May 2021 16:09:16 -0700 Subject: [PATCH 047/231] [cpack_installer] remove wxs file ext from lfs filter --- .gitattributes | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index 1755def66a..55b43e4ba7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -115,5 +115,4 @@ *.wav filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text *.wem filter=lfs diff=lfs merge=lfs -text -*.wxs filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text From c777e2e35301cd0054fe39e8fdccb5e632d48a21 Mon Sep 17 00:00:00 2001 From: scottr Date: Tue, 11 May 2021 18:07:19 -0700 Subject: [PATCH 048/231] [cpack_installer] some cpack cleanup and prep for online installer support (pre/post build steps) --- cmake/Packaging.cmake | 38 ++++++++++++------- .../Platform/Windows/PackagingPostBuild.cmake | 12 ++++++ .../Platform/Windows/Packaging_windows.cmake | 8 +++- .../Windows/platform_windows_files.cmake | 1 + 4 files changed, 43 insertions(+), 16 deletions(-) create mode 100644 cmake/Platform/Windows/PackagingPostBuild.cmake diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index 4f6565edc7..e398ea7509 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -13,6 +13,30 @@ if(NOT PAL_TRAIT_BUILD_CPACK_SUPPORTED) return() endif() +# set the common cpack variables first so they are accessible via configure_file +# when the platforms specific properties are applied below +set(LY_INSTALLER_DOWNLOAD_URL "" CACHE PATH "URL embded into the installer to download additional artifacts") + +set(CPACK_PACKAGE_VENDOR "${PROJECT_NAME}") +set(CPACK_PACKAGE_VERSION "${LY_VERSION_STRING}") +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Installation Tool") + +string(TOLOWER ${PROJECT_NAME} _project_name_lower) +set(CPACK_PACKAGE_FILE_NAME "${_project_name_lower}_${LY_VERSION_STRING}_installer") + +set(DEFAULT_LICENSE_NAME "Apache-2.0") +set(DEFAULT_LICENSE_FILE "${CMAKE_SOURCE_DIR}/LICENSE.txt") + +set(CPACK_RESOURCE_FILE_LICENSE ${DEFAULT_LICENSE_FILE}) + +set(CPACK_PACKAGE_INSTALL_DIRECTORY "${CPACK_PACKAGE_VENDOR}/${CPACK_PACKAGE_VERSION}") + +# custom cpack cache variables for use in pre/post build scripts +set(CPACK_SOURCE_DIR ${CMAKE_SOURCE_DIR}/cmake) +set(CPACK_BINARY_DIR ${CMAKE_BINARY_DIR}/installer) +set(CPACK_DOWNLOAD_URL ${LY_INSTALLER_DOWNLOAD_URL}) + +# attempt to apply platform specific settings ly_get_absolute_pal_filename(pal_dir ${CMAKE_SOURCE_DIR}/cmake/Platform/${PAL_HOST_PLATFORM_NAME}) include(${pal_dir}/Packaging_${PAL_HOST_PLATFORM_NAME_LOWERCASE}.cmake) @@ -21,20 +45,6 @@ if(NOT CPACK_GENERATOR) return() endif() -set(CPACK_PACKAGE_VENDOR "${PROJECT_NAME}") -set(CPACK_PACKAGE_VERSION "${LY_VERSION_STRING}") -set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Installation Tool") - -string(TOLOWER ${PROJECT_NAME} _project_name_lower) -set(CPACK_PACKAGE_FILE_NAME "${_project_name_lower}_installer") - -set(DEFAULT_LICENSE_NAME "Apache-2.0") -set(DEFAULT_LICENSE_FILE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE.txt") - -set(CPACK_RESOURCE_FILE_LICENSE ${DEFAULT_LICENSE_FILE}) - -set(CPACK_PACKAGE_INSTALL_DIRECTORY "${CPACK_PACKAGE_VENDOR}/${CPACK_PACKAGE_VERSION}") - # IMPORTANT: required to be included AFTER setting all property overrides include(CPack REQUIRED) diff --git a/cmake/Platform/Windows/PackagingPostBuild.cmake b/cmake/Platform/Windows/PackagingPostBuild.cmake new file mode 100644 index 0000000000..fe57904003 --- /dev/null +++ b/cmake/Platform/Windows/PackagingPostBuild.cmake @@ -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. +# + +message(STATUS "Hello from CPack post build!") diff --git a/cmake/Platform/Windows/Packaging_windows.cmake b/cmake/Platform/Windows/Packaging_windows.cmake index 8aa6f2386d..ba3ce011a4 100644 --- a/cmake/Platform/Windows/Packaging_windows.cmake +++ b/cmake/Platform/Windows/Packaging_windows.cmake @@ -32,7 +32,7 @@ set(CPACK_GENERATOR "WIX") # however, they are unique for each run. instead, let's do the auto generation here and add it to # the cache for run persistence. an additional cache file will be used to store the information on # the original generation so we still have the ability to detect if they are still being used. -set(_guid_cache_file "${CMAKE_BINARY_DIR}/installer/wix_guid_cache.cmake") +set(_guid_cache_file "${CPACK_BINARY_DIR}/wix_guid_cache.cmake") if(NOT EXISTS ${_guid_cache_file}) set(_wix_guid_namespace "6D43F57A-2917-4AD9-B758-1F13CDB08593") @@ -89,4 +89,8 @@ endif() set(CPACK_WIX_PRODUCT_GUID ${LY_WIX_PRODUCT_GUID}) set(CPACK_WIX_UPGRADE_GUID ${LY_WIX_UPGRADE_GUID}) -set(CPACK_WIX_TEMPLATE "${CMAKE_SOURCE_DIR}/cmake/Platform/Windows/PackagingTemplate.wxs.in") +set(CPACK_WIX_TEMPLATE "${CPACK_SOURCE_DIR}/Platform/Windows/PackagingTemplate.wxs.in") + +set(CPACK_POST_BUILD_SCRIPTS + ${CPACK_SOURCE_DIR}/Platform/Windows/PackagingPostBuild.cmake +) diff --git a/cmake/Platform/Windows/platform_windows_files.cmake b/cmake/Platform/Windows/platform_windows_files.cmake index 2fc869b43e..579621d5ea 100644 --- a/cmake/Platform/Windows/platform_windows_files.cmake +++ b/cmake/Platform/Windows/platform_windows_files.cmake @@ -24,5 +24,6 @@ set(FILES PALDetection_windows.cmake Install_windows.cmake Packaging_windows.cmake + PackagingPostBuild.cmake PackagingTemplate.wxs.in ) From cdca18ca2590ddd46217398a3d63c5a5ffac7328 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Tue, 11 May 2021 18:26:05 -0700 Subject: [PATCH 049/231] Use a smart viewport context pointer in AtomFont to avoid a crash --- .../Code/Include/AtomLyIntegration/AtomFont/FFont.h | 4 ++-- Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h index 83273633be..84d53a5446 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h @@ -237,7 +237,7 @@ namespace AZ void Prepare(const char* str, bool updateTexture, const AtomFont::GlyphSize& glyphSize = AtomFont::defaultGlyphSize); void DrawStringUInternal( const RHI::Viewport& viewport, - RPI::ViewportContext* viewportContext, + RPI::ViewportContextPtr viewportContext, float x, float y, float z, @@ -291,7 +291,7 @@ namespace AZ TextDrawContext m_ctx; AZ::Vector2 m_position; AZ::Vector2 m_size; - AZ::RPI::ViewportContext* m_viewportContext; + AZ::RPI::ViewportContextPtr m_viewportContext; const AZ::RHI::Viewport* m_viewport; }; DrawParameters ExtractDrawParameters(const AzFramework::TextDrawParameters& params, const AZStd::string_view& string, bool forceCalculateSize); diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index 48d24f0473..faeed52fb0 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -280,7 +280,7 @@ void AZ::FFont::DrawString(float x, float y, const char* str, const bool asciiMu return; } - DrawStringUInternal(GetDefaultWindowContext()->GetViewport(), GetDefaultViewportContext().get(), x, y, 1.0f, str, asciiMultiLine, ctx); + DrawStringUInternal(GetDefaultWindowContext()->GetViewport(), GetDefaultViewportContext(), x, y, 1.0f, str, asciiMultiLine, ctx); } void AZ::FFont::DrawString(float x, float y, float z, const char* str, const bool asciiMultiLine, const TextDrawContext& ctx) @@ -290,12 +290,12 @@ void AZ::FFont::DrawString(float x, float y, float z, const char* str, const boo return; } - DrawStringUInternal(GetDefaultWindowContext()->GetViewport(), GetDefaultViewportContext().get(), x, y, z, str, asciiMultiLine, ctx); + DrawStringUInternal(GetDefaultWindowContext()->GetViewport(), GetDefaultViewportContext(), x, y, z, str, asciiMultiLine, ctx); } void AZ::FFont::DrawStringUInternal( const RHI::Viewport& viewport, - RPI::ViewportContext* viewportContext, + RPI::ViewportContextPtr viewportContext, float x, float y, float z, @@ -1686,7 +1686,7 @@ AZ::FFont::DrawParameters AZ::FFont::ExtractDrawParameters(const AzFramework::Te //Code mostly duplicated from CRenderer::Draw2dTextWithDepth float posX = params.m_position.GetX(); float posY = params.m_position.GetY(); - internalParams.m_viewportContext = AZ::Interface::Get()->GetViewportContextById(params.m_drawViewportId).get(); + internalParams.m_viewportContext = AZ::Interface::Get()->GetViewportContextById(params.m_drawViewportId); const AZ::RHI::Viewport& viewport = internalParams.m_viewportContext->GetWindowContext()->GetViewport(); internalParams.m_viewport = &viewport; if (params.m_virtual800x600ScreenSize) From 6fcd5c7817a3a78172c8f98058056be710a52eb6 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Tue, 11 May 2021 18:27:47 -0700 Subject: [PATCH 050/231] Restore Viewport debug text Adds the AtomViewportDisplayInfo Gem which renders debug text to the default viewport context depending on the value of r_DisplayInfo. The gem is flagged as a dependency of AtomBridge, so all Atom projects will consume it by default. --- .../AtomBridge/Code/CMakeLists.txt | 4 + .../AtomViewportDisplayInfo/CMakeLists.txt | 12 + .../Code/CMakeLists.txt | 50 +++ ...AtomViewportDisplayInfoSystemComponent.cpp | 289 ++++++++++++++++++ .../AtomViewportDisplayInfoSystemComponent.h | 79 +++++ .../Code/Source/Module.cpp | 51 ++++ .../Code/Source/Tests/test_Main.cpp | 20 ++ .../Code/atomviewportdisplayinfo_files.cmake | 16 + .../atomviewportdisplayinfo_test_files.cmake | 14 + .../AtomViewportDisplayInfo/gem.json | 32 ++ Gems/AtomLyIntegration/CMakeLists.txt | 1 + 11 files changed, 568 insertions(+) create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/CMakeLists.txt create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/Module.cpp create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/Tests/test_Main.cpp create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/atomviewportdisplayinfo_files.cmake create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/atomviewportdisplayinfo_test_files.cmake create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt index b684e445b3..885f0d1a25 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt @@ -29,6 +29,8 @@ ly_add_target( Gem::Atom_RPI.Public Gem::Atom_Bootstrap.Headers Legacy::CryCommon + RUNTIME_DEPENDENCIES + Gem::AtomViewportDisplayInfo ) ly_add_target( @@ -68,5 +70,7 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AssetBuilderSDK Gem::Atom_Utils.Static Gem::Atom_AtomBridge.Static + RUNTIME_DEPENDENCIES + Gem::AtomViewportDisplayInfo ) endif() diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/CMakeLists.txt b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/CMakeLists.txt new file mode 100644 index 0000000000..20a680bce9 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/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/AtomViewportDisplayInfo/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt new file mode 100644 index 0000000000..395cc22d47 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt @@ -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. +# + +ly_add_target( + NAME AtomViewportDisplayInfo GEM_MODULE + NAMESPACE Gem + FILES_CMAKE + atomviewportdisplayinfo_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Source + BUILD_DEPENDENCIES + PRIVATE + AZ::AzCore + AZ::AtomCore + Legacy::CryCommon + Gem::Atom_RHI.Reflect + Gem::Atom_RPI.Public +) + +################################################################################ +# Tests +################################################################################ +if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) + ly_add_target( + NAME AtomViewportDisplayInfo.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAMESPACE Gem + FILES_CMAKE + atomviewportdisplayinfo_test_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Include + Tests + BUILD_DEPENDENCIES + PRIVATE + AZ::AzTest + ) + ly_add_googletest( + NAME Gem::AtomViewportDisplayInfo.Tests + ) +endif() + diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp new file mode 100644 index 0000000000..394923071e --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp @@ -0,0 +1,289 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or 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 "AtomViewportDisplayInfoSystemComponent.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +AZ_CVAR(float, r_fpsInterval, 1.0f, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, + "The time period over which to calculate the framerate for r_displayInfo"); + +namespace AZ::Render +{ + static constexpr int DisplayInfoLevelNone = 0; + static constexpr int DisplayInfoLevelNormal = 1; + static constexpr int DisplayInfoLevelFull = 2; + static constexpr int DisplayInfoLevelCompact = 3; + + void AtomViewportDisplayInfoSystemComponent::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 Info", "Manages debug viewport information through r_DisplayInfo") + ->ClassElement(Edit::ClassElements::EditorData, "") + ->Attribute(Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) + ->Attribute(Edit::Attributes::AutoExpand, true) + ; + } + } + } + + void AtomViewportDisplayInfoSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC("ViewportDisplayInfoService")); + } + + void AtomViewportDisplayInfoSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC("ViewportDisplayInfoService")); + } + + void AtomViewportDisplayInfoSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + required.push_back(AZ_CRC("RPISystem", 0xf2add773)); + } + + void AtomViewportDisplayInfoSystemComponent::GetDependentServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + } + + void AtomViewportDisplayInfoSystemComponent::Activate() + { + AZ::Name apiName = AZ::RHI::Factory::Get().GetName(); + if (!apiName.IsEmpty()) + { + m_rendererDescription = AZStd::string::format("Atom using %s RHI", apiName.GetCStr()); + } + + CrySystemEventBus::Handler::BusConnect(); + AZ::RPI::ViewportContextNotificationBus::Handler::BusConnect( + AZ::RPI::ViewportContextRequests::Get()->GetDefaultViewportContextName()); + } + + void AtomViewportDisplayInfoSystemComponent::Deactivate() + { + AZ::RPI::ViewportContextNotificationBus::Handler::BusDisconnect(); + CrySystemEventBus::Handler::BusDisconnect(); + } + + AZ::RPI::ViewportContextPtr AtomViewportDisplayInfoSystemComponent::GetViewportContext() const + { + return AZ::RPI::ViewportContextRequests::Get()->GetDefaultViewportContext(); + } + + void AtomViewportDisplayInfoSystemComponent::DrawLine(AZStd::string_view line, AZ::Color color) + { + m_drawParams.m_color = color; + AzFramework::FontDrawInterface* fontDrawInterface = + AZ::Interface::Get()->GetDefaultFontDrawInterface(); + AZ::Vector2 textSize = fontDrawInterface->GetTextSize(m_drawParams, line); + fontDrawInterface->DrawScreenAlignedText2d(m_drawParams, line); + m_drawParams.m_position.SetY(m_drawParams.m_position.GetY() + textSize.GetY() + m_lineSpacing); + } + + void AtomViewportDisplayInfoSystemComponent::OnRenderTick() + { + AzFramework::FontDrawInterface* fontDrawInterface = + AZ::Interface::Get()->GetDefaultFontDrawInterface(); + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + + if (!fontDrawInterface || !viewportContext || !viewportContext->GetRenderScene()) + { + return; + } + + m_fpsInterval = AZStd::chrono::seconds(r_fpsInterval); + + UpdateFramerate(); + + if (!m_displayInfoCVar) + { + return; + } + int displayLevel = m_displayInfoCVar->GetIVal(); + if (displayLevel == DisplayInfoLevelNone) + { + return; + } + + m_drawParams.m_drawViewportId = viewportContext->GetId(); + auto viewportSize = viewportContext->GetViewportSize(); + m_drawParams.m_position = AZ::Vector3(viewportSize.m_width, 0.f, 1.f); + m_drawParams.m_color = AZ::Colors::White; + m_drawParams.m_scale = AZ::Vector2(0.7f); + 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_scaleWithWindow = false; + m_drawParams.m_multiline = true; + m_drawParams.m_lineSpacing = 0.5f; + + // Calculate line spacing based on the font's actual line height + const float lineHeight = fontDrawInterface->GetTextSize(m_drawParams, " ").GetY(); + m_lineSpacing = lineHeight * m_drawParams.m_lineSpacing; + + DrawRendererInfo(); + if (displayLevel != DisplayInfoLevelCompact) + { + DrawCameraInfo(); + DrawMemoryInfo(); + } + DrawFramerate(); + } + + void AtomViewportDisplayInfoSystemComponent::OnCrySystemInitialized(ISystem& system, [[maybe_unused]]const SSystemInitParams& initParams) + { + m_displayInfoCVar = system.GetGlobalEnvironment()->pConsole->GetCVar("r_DisplayInfo"); + } + + void AtomViewportDisplayInfoSystemComponent::OnCrySystemShutdown([[maybe_unused]]ISystem& system) + { + m_displayInfoCVar = nullptr; + } + + void AtomViewportDisplayInfoSystemComponent::DrawRendererInfo() + { + DrawLine(m_rendererDescription, AZ::Colors::Yellow); + } + + void AtomViewportDisplayInfoSystemComponent::DrawCameraInfo() + { + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + AZ::RPI::ViewPtr currentView = viewportContext->GetDefaultView(); + if (currentView == nullptr) + { + return; + } + + auto viewportSize = viewportContext->GetViewportSize(); + AzFramework::CameraState cameraState; + AzFramework::SetCameraClippingVolumeFromPerspectiveFovMatrixRH(cameraState, currentView->GetViewToClipMatrix()); + const AZ::Transform transform = currentView->GetCameraTransform(); + const AZ::Vector3 translation = transform.GetTranslation(); + const AZ::Vector3 rotation = transform.GetEulerDegrees(); + DrawLine(AZStd::string::format( + "CamPos=%.2f %.2f %.2f Angl=%3.0f %3.0f %4.0f ZN=%.2f ZF=%.0f", + translation.GetX(), translation.GetY(), translation.GetZ(), + rotation.GetX(), rotation.GetY(), rotation.GetZ(), + cameraState.m_nearClip, cameraState.m_farClip + )); + } + + void AtomViewportDisplayInfoSystemComponent::DrawMemoryInfo() + { + static IMemoryManager::SProcessMemInfo processMemInfo; + + // Throttle memory usage updates to avoid potentially expensive memory usage API calls every tick. + constexpr AZStd::chrono::duration memoryUpdateInterval = AZStd::chrono::seconds(0.5); + AZStd::chrono::time_point currentTime = m_fpsHistory.back().Get(); + if (m_lastMemoryUpdate.has_value()) + { + if (currentTime - m_lastMemoryUpdate.value() > memoryUpdateInterval) + { + if (auto memoryManager = GetISystem()->GetIMemoryManager()) + { + memoryManager->GetProcessMemInfo(processMemInfo); + } + } + } + m_lastMemoryUpdate = currentTime; + + + int peakUsageMB = aznumeric_cast(processMemInfo.PeakPagefileUsage >> 20); + int currentUsageMB = aznumeric_cast(processMemInfo.PagefileUsage >> 20); + DrawLine(AZStd::string::format("Mem=%d Peak=%d", currentUsageMB, peakUsageMB)); + } + + void AtomViewportDisplayInfoSystemComponent::UpdateFramerate() + { + if (!m_tickRequests) + { + m_tickRequests = AZ::TickRequestBus::FindFirstHandler(); + } + if (!m_tickRequests) + { + return; + } + + AZ::ScriptTimePoint currentTime = m_tickRequests->GetTimeAtCurrentTick(); + // Only keep as much sampling data is is required by our FPS history. + while (!m_fpsHistory.empty() && (currentTime.Get() - m_fpsHistory.front().Get() > m_fpsInterval)) + { + m_fpsHistory.pop_front(); + } + m_fpsHistory.push_back(currentTime); + } + + void AtomViewportDisplayInfoSystemComponent::DrawFramerate() + { + AZStd::chrono::duration actualInterval = AZStd::chrono::seconds(0); + AZStd::optional lastTime; + AZStd::optional minFPS; + AZStd::optional maxFPS; + for (const AZ::ScriptTimePoint& time : m_fpsHistory) + { + if (lastTime.has_value()) + { + AZStd::chrono::duration deltaTime = time.Get() - lastTime.value().Get(); + if (deltaTime.count() == 0.0) + { + continue; + } + double fps = AZStd::chrono::seconds(1) / deltaTime; + if (!minFPS.has_value()) + { + minFPS = fps; + maxFPS = fps; + } + else + { + minFPS = AZStd::min(minFPS.value(), fps); + maxFPS = AZStd::max(maxFPS.value(), fps); + } + actualInterval += deltaTime; + } + lastTime = time; + } + + const double averageFPS = aznumeric_cast(m_fpsHistory.size()) / actualInterval.count(); + const double frameIntervalSeconds = m_fpsInterval.count(); + + DrawLine( + AZStd::string::format( + "FPS %.1f [%.0f..%.0f], frame avg over %.1fs", + averageFPS, + minFPS.value_or(0.0), + maxFPS.value_or(0.0), + frameIntervalSeconds), + AZ::Colors::Yellow); + } +} // namespace AZ::Render diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h new file mode 100644 index 0000000000..5cb6ed3308 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h @@ -0,0 +1,79 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or 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 + +struct ICVar; + +namespace AZ +{ + class TickRequests; + + namespace Render + { + class AtomViewportDisplayInfoSystemComponent + : public AZ::Component + , public AZ::RPI::ViewportContextNotificationBus::Handler + , public CrySystemEventBus::Handler + { + public: + AZ_COMPONENT(AtomViewportDisplayInfoSystemComponent, "{AC32F173-E7E2-4943-8E6C-7C3091978221}"); + + 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; + + // AZ::RPI::ViewportContextNotificationBus::Handler overrides... + void OnRenderTick() override; + + // CrySystemEventBus::Handler overrides... + void OnCrySystemInitialized(ISystem& system, const SSystemInitParams& initParams) override; + void OnCrySystemShutdown(ISystem& system) override; + + private: + AZ::RPI::ViewportContextPtr GetViewportContext() const; + void DrawLine(AZStd::string_view line, AZ::Color color = AZ::Colors::White); + + void UpdateFramerate(); + + void DrawRendererInfo(); + void DrawCameraInfo(); + void DrawMemoryInfo(); + void DrawFramerate(); + + AZStd::string m_rendererDescription; + AzFramework::TextDrawParameters m_drawParams; + float m_lineSpacing; + AZStd::chrono::duration m_fpsInterval = AZStd::chrono::seconds(1); + AZStd::deque m_fpsHistory; + AZStd::optional m_lastMemoryUpdate; + AZ::TickRequests* m_tickRequests = nullptr; + ICVar* m_displayInfoCVar = nullptr; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/Module.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/Module.cpp new file mode 100644 index 0000000000..f67e1bd1f5 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/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 "AtomViewportDisplayInfoSystemComponent.h" + +namespace AZ +{ + namespace Render + { + class AtomViewportDisplayInfoModule + : public AZ::Module + { + public: + AZ_RTTI(AtomViewportDisplayInfoModule, "{B10C0E55-03A1-4A46-AE3E-D3615AEAA659}", AZ::Module); + AZ_CLASS_ALLOCATOR(AtomViewportDisplayInfoModule, AZ::SystemAllocator, 0); + + AtomViewportDisplayInfoModule() + : AZ::Module() + { + m_descriptors.insert(m_descriptors.end(), { + AtomViewportDisplayInfoSystemComponent::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/AtomViewportDisplayInfo/Code/Source/Tests/test_Main.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/Tests/test_Main.cpp new file mode 100644 index 0000000000..b533221bbe --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/Tests/test_Main.cpp @@ -0,0 +1,20 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include + +AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); + +TEST(AtomViewportDisplayInfoSanityTest, Sanity) +{ + EXPECT_EQ(1, 1); +} diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/atomviewportdisplayinfo_files.cmake b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/atomviewportdisplayinfo_files.cmake new file mode 100644 index 0000000000..561971453b --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/atomviewportdisplayinfo_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/AtomViewportDisplayInfoSystemComponent.cpp + Source/AtomViewportDisplayInfoSystemComponent.h + Source/Module.cpp +) diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/atomviewportdisplayinfo_test_files.cmake b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/atomviewportdisplayinfo_test_files.cmake new file mode 100644 index 0000000000..0bc1ee3a50 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/atomviewportdisplayinfo_test_files.cmake @@ -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. +# + +set(FILES + Source/Tests/test_Main.cpp +) diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json new file mode 100644 index 0000000000..a54dc188a7 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/gem.json @@ -0,0 +1,32 @@ +{ + "gem_name": "AtomLyIntegration_AtomViewportDisplayInfo", + "Dependencies": [ + { + "Uuid": "a218db9eb2114477b46600fea4441a6c", + "VersionConstraints": [ + "~>0.1.0" + ], + "_comment": "Atom RPI" + }, + { + "Uuid": "c7ff89ad6e8b4b45b2fadef2bcf12d6e", + "VersionConstraints": [ + "~>0.1.0" + ], + "_comment": "Atom_Bootstrap" + } + ], + "GemFormatVersion": 4, + "Uuid": "7c255c884bae4046b0640abe3c88cc4c", + "Name": "AtomLyIntegration_AtomViewportDisplayInfo", + "DisplayName": "Atom.AtomViewportDisplayInfo", + "Version": "0.1.0", + "Summary": "Provides a diagnostic viewport overlay for the default O3DE Atom viewport.", + "Tags": ["Atom"], + "IconPath": "preview.png", + "Modules": [ + { + "Type": "GameModule" + } + ] +} diff --git a/Gems/AtomLyIntegration/CMakeLists.txt b/Gems/AtomLyIntegration/CMakeLists.txt index 57bb860a9e..35022e643b 100644 --- a/Gems/AtomLyIntegration/CMakeLists.txt +++ b/Gems/AtomLyIntegration/CMakeLists.txt @@ -16,3 +16,4 @@ add_subdirectory(EMotionFXAtom) add_subdirectory(AtomFont) add_subdirectory(TechnicalArt) add_subdirectory(AtomBridge) +add_subdirectory(AtomViewportDisplayInfo) From 7342e62680a8a651df4bd935f9c44ddb11239e8d Mon Sep 17 00:00:00 2001 From: mnaumov Date: Tue, 11 May 2021 19:33:46 -0700 Subject: [PATCH 051/231] Hiding "Open Material" when material asset is assigned --- .../Code/Source/Material/EditorMaterialComponentSlot.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp index 9d63f4a4a9..7ebf25454d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp @@ -269,7 +269,8 @@ namespace AZ QAction* action = nullptr; - menu.addAction("Open Material Editor", [this]() { EditorMaterialSystemComponentRequestBus::Broadcast(&EditorMaterialSystemComponentRequestBus::Events::OpenInMaterialEditor, ""); }); + action = menu.addAction("Open Material Editor...", [this]() { EditorMaterialSystemComponentRequestBus::Broadcast(&EditorMaterialSystemComponentRequestBus::Events::OpenInMaterialEditor, ""); }); + action->setVisible(!m_materialAsset.GetId().IsValid()); action = menu.addAction("Clear", [this]() { Clear(); }); action->setEnabled(m_materialAsset.GetId().IsValid() || !m_propertyOverrides.empty() || !m_matModUvOverrides.empty()); From d98a69199402e0e781748a7f021cf39af7d77254 Mon Sep 17 00:00:00 2001 From: abrmich Date: Tue, 11 May 2021 10:19:30 -0700 Subject: [PATCH 052/231] UI Editor Viewport fixes --- .../Editor/Icons/Viewport}/Anchor_Left.tif | 0 .../Editor/Icons/Viewport}/Anchor_TopLeft.tif | 0 .../Editor/Icons/Viewport}/Anchor_Whole.tif | 0 .../Icons/Viewport}/Border_Selected.tif | 0 .../Icons/Viewport}/Border_Unselected.tif | 0 .../Icons/Viewport}/Canvas_Background.tif | 0 .../Viewport/Canvas_Background.tif.assetinfo | 69 ++++++++++++++ .../Editor/Icons/Viewport}/DottedLine.tif | 0 .../Assets/Editor/Icons/Viewport}/Pivot.tif | 0 .../Transform_Gizmo_Center_Square.tif | 0 .../Viewport}/Transform_Gizmo_Circle.tif | 0 .../Transform_Gizmo_Line_Square_X.tif | 0 .../Transform_Gizmo_Line_Square_Y.tif | 0 .../Transform_Gizmo_Line_Triangle_X.tif | 0 .../Transform_Gizmo_Line_Triangle_Y.tif | 0 Gems/LyShine/Code/Editor/EditorWindow.cpp | 1 - Gems/LyShine/Code/Editor/QtHelpers.cpp | 16 ++++ Gems/LyShine/Code/Editor/QtHelpers.h | 4 + Gems/LyShine/Code/Editor/ViewportAnchor.cpp | 8 +- .../Code/Editor/ViewportCanvasBackground.cpp | 2 +- Gems/LyShine/Code/Editor/ViewportHelpers.h | 1 - .../LyShine/Code/Editor/ViewportHighlight.cpp | 4 +- Gems/LyShine/Code/Editor/ViewportIcon.cpp | 12 ++- Gems/LyShine/Code/Editor/ViewportIcon.h | 15 ++++ .../Code/Editor/ViewportInteraction.cpp | 23 ++--- Gems/LyShine/Code/Editor/ViewportPivot.cpp | 2 +- Gems/LyShine/Code/Editor/ViewportWidget.cpp | 89 +++++++++++-------- Gems/LyShine/Code/Editor/ViewportWidget.h | 5 +- Gems/LyShine/Code/Include/LyShine/Draw2d.h | 19 ++-- Gems/LyShine/Code/Source/Draw2d.cpp | 23 +++-- 30 files changed, 213 insertions(+), 80 deletions(-) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Anchor_Left.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Anchor_TopLeft.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Anchor_Whole.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Border_Selected.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Border_Unselected.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Canvas_Background.tif (100%) create mode 100644 Gems/LyShine/Assets/Editor/Icons/Viewport/Canvas_Background.tif.assetinfo rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/DottedLine.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Pivot.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Transform_Gizmo_Center_Square.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Transform_Gizmo_Circle.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Transform_Gizmo_Line_Square_X.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Transform_Gizmo_Line_Square_Y.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Transform_Gizmo_Line_Triangle_X.tif (100%) rename {Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons => Gems/LyShine/Assets/Editor/Icons/Viewport}/Transform_Gizmo_Line_Triangle_Y.tif (100%) diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Anchor_Left.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Anchor_Left.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Anchor_Left.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Anchor_Left.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Anchor_TopLeft.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Anchor_TopLeft.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Anchor_TopLeft.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Anchor_TopLeft.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Anchor_Whole.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Anchor_Whole.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Anchor_Whole.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Anchor_Whole.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Border_Selected.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Border_Selected.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Border_Selected.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Border_Selected.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Border_Unselected.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Border_Unselected.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Border_Unselected.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Border_Unselected.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Canvas_Background.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Canvas_Background.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Canvas_Background.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Canvas_Background.tif diff --git a/Gems/LyShine/Assets/Editor/Icons/Viewport/Canvas_Background.tif.assetinfo b/Gems/LyShine/Assets/Editor/Icons/Viewport/Canvas_Background.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShine/Assets/Editor/Icons/Viewport/Canvas_Background.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/DottedLine.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/DottedLine.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/DottedLine.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/DottedLine.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Pivot.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Pivot.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Pivot.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Pivot.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Center_Square.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Center_Square.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Center_Square.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Center_Square.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Circle.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Circle.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Circle.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Circle.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Square_X.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Line_Square_X.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Square_X.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Line_Square_X.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Square_Y.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Line_Square_Y.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Square_Y.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Line_Square_Y.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Triangle_X.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Line_Triangle_X.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Triangle_X.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Line_Triangle_X.tif diff --git a/Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Triangle_Y.tif b/Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Line_Triangle_Y.tif similarity index 100% rename from Assets/Editor/Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Triangle_Y.tif rename to Gems/LyShine/Assets/Editor/Icons/Viewport/Transform_Gizmo_Line_Triangle_Y.tif diff --git a/Gems/LyShine/Code/Editor/EditorWindow.cpp b/Gems/LyShine/Code/Editor/EditorWindow.cpp index 4641b02a13..e3810dcbee 100644 --- a/Gems/LyShine/Code/Editor/EditorWindow.cpp +++ b/Gems/LyShine/Code/Editor/EditorWindow.cpp @@ -1451,7 +1451,6 @@ void EditorWindow::OnEditorNotifyEvent(EEditorNotifyEvent ev) { // change skin RefreshEditorMenu(); - m_viewport->UpdateViewportBackground(); break; } case eNotify_OnUpdateViewports: diff --git a/Gems/LyShine/Code/Editor/QtHelpers.cpp b/Gems/LyShine/Code/Editor/QtHelpers.cpp index 9691c2a618..16a5d42327 100644 --- a/Gems/LyShine/Code/Editor/QtHelpers.cpp +++ b/Gems/LyShine/Code/Editor/QtHelpers.cpp @@ -13,6 +13,8 @@ #include "EditorCommon.h" +#include + namespace QtHelpers { AZ::Vector2 QPointFToVector2(const QPointF& point) @@ -34,4 +36,18 @@ namespace QtHelpers return inWidget; } + float GetHighDpiScaleFactor(const QWidget& widget) + { + float dpiScale = QHighDpiScaling::factor(widget.windowHandle()->screen()); + return dpiScale; + } + + QSize GetDpiScaledViewportSize(const QWidget& widget) + { + float dpiScale = GetHighDpiScaleFactor(widget); + float width = ceilf(widget.size().width() * dpiScale); + float height = ceilf(widget.size().height() * dpiScale); + return QSize(width, height); + } + } // namespace QtHelpers diff --git a/Gems/LyShine/Code/Editor/QtHelpers.h b/Gems/LyShine/Code/Editor/QtHelpers.h index f55ffc767e..7af68432d3 100644 --- a/Gems/LyShine/Code/Editor/QtHelpers.h +++ b/Gems/LyShine/Code/Editor/QtHelpers.h @@ -21,4 +21,8 @@ namespace QtHelpers bool IsGlobalPosInWidget(const QWidget* widget, const QPoint& pos); + float GetHighDpiScaleFactor(const QWidget& widget); + + QSize GetDpiScaledViewportSize(const QWidget& widget); + } // namespace QtHelpers diff --git a/Gems/LyShine/Code/Editor/ViewportAnchor.cpp b/Gems/LyShine/Code/Editor/ViewportAnchor.cpp index d61066f4d9..f46a62586d 100644 --- a/Gems/LyShine/Code/Editor/ViewportAnchor.cpp +++ b/Gems/LyShine/Code/Editor/ViewportAnchor.cpp @@ -14,10 +14,10 @@ #include "EditorCommon.h" ViewportAnchor::ViewportAnchor() - : m_anchorWhole(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Anchor_Whole.tif")) - , m_anchorLeft(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Anchor_Left.tif")) - , m_anchorLeftTop(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Anchor_TopLeft.tif")) - , m_dottedLine(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/DottedLine.tif")) + : m_anchorWhole(new ViewportIcon("Editor/Icons/Viewport/Anchor_Whole.tif")) + , m_anchorLeft(new ViewportIcon("Editor/Icons/Viewport/Anchor_Left.tif")) + , m_anchorLeftTop(new ViewportIcon("Editor/Icons/Viewport/Anchor_TopLeft.tif")) + , m_dottedLine(new ViewportIcon("Editor/Icons/Viewport/DottedLine.tif")) { } diff --git a/Gems/LyShine/Code/Editor/ViewportCanvasBackground.cpp b/Gems/LyShine/Code/Editor/ViewportCanvasBackground.cpp index ccc35de305..344e3af9cb 100644 --- a/Gems/LyShine/Code/Editor/ViewportCanvasBackground.cpp +++ b/Gems/LyShine/Code/Editor/ViewportCanvasBackground.cpp @@ -15,7 +15,7 @@ #include "EditorCommon.h" ViewportCanvasBackground::ViewportCanvasBackground() - : m_canvasBackground(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Canvas_Background.tif")) + : m_canvasBackground(new ViewportIcon("Editor/Icons/Viewport/Canvas_Background.tif")) { } diff --git a/Gems/LyShine/Code/Editor/ViewportHelpers.h b/Gems/LyShine/Code/Editor/ViewportHelpers.h index 9a1aadead5..7cb64d01c7 100644 --- a/Gems/LyShine/Code/Editor/ViewportHelpers.h +++ b/Gems/LyShine/Code/Editor/ViewportHelpers.h @@ -17,7 +17,6 @@ namespace ViewportHelpers { //------------------------------------------------------------------------------- - const AZ::Color backgroundColorLight(0.85f, 0.85f, 0.85f, 1.0f); const AZ::Color backgroundColorDark(0.133f, 0.137f, 0.149f, 1.0f); // #222236, RGBA: 34, 35, 38, 255 const AZ::Color selectedColor(1.000f, 1.000f, 1.000f, 1.0f); // #FFFFFF, RGBA: 255, 255, 255, 255 const AZ::Color unselectedColor(0.800f, 0.800f, 0.800f, 0.500f); // #CCCCCC, RGBA: 204, 204, 204, 128 diff --git a/Gems/LyShine/Code/Editor/ViewportHighlight.cpp b/Gems/LyShine/Code/Editor/ViewportHighlight.cpp index c050d55049..e6699615c6 100644 --- a/Gems/LyShine/Code/Editor/ViewportHighlight.cpp +++ b/Gems/LyShine/Code/Editor/ViewportHighlight.cpp @@ -14,8 +14,8 @@ #include "EditorCommon.h" ViewportHighlight::ViewportHighlight() - : m_highlightIconSelected(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Border_Selected.tif")) - , m_highlightIconUnselected(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Border_Unselected.tif")) + : m_highlightIconSelected(new ViewportIcon("Editor/Icons/Viewport/Border_Selected.tif")) + , m_highlightIconUnselected(new ViewportIcon("Editor/Icons/Viewport/Border_Unselected.tif")) { } diff --git a/Gems/LyShine/Code/Editor/ViewportIcon.cpp b/Gems/LyShine/Code/Editor/ViewportIcon.cpp index 81ed5dbcb5..b1866efb00 100644 --- a/Gems/LyShine/Code/Editor/ViewportIcon.cpp +++ b/Gems/LyShine/Code/Editor/ViewportIcon.cpp @@ -17,6 +17,8 @@ #include #include +float ViewportIcon::m_dpiScaleFactor = 1.0f; + ViewportIcon::ViewportIcon(const char* textureFilename) { m_image = CDraw2d::LoadTexture(textureFilename); @@ -31,7 +33,12 @@ AZ::Vector2 ViewportIcon::GetTextureSize() const if (m_image) { AZ::RHI::Size size = m_image->GetDescriptor().m_size; - return AZ::Vector2(size.m_width, size.m_height); + AZ::Vector2 scaledSize(size.m_width, size.m_height); + if (m_applyDpiScaleFactorToSize) + { + scaledSize *= m_dpiScaleFactor; + } + return scaledSize; } return AZ::Vector2(0.0f, 0.0f); @@ -380,5 +387,6 @@ void ViewportIcon::DrawElementRectOutline(Draw2dHelper& draw2d, AZ::EntityId ent rightVec.NormalizeSafe(); downVec.NormalizeSafe(); - draw2d.DrawRectOutlineTextured(m_image, points, rightVec, downVec, color); + uint32_t lineThickness = aznumeric_cast(GetTextureSize().GetY()); + draw2d.DrawRectOutlineTextured(m_image, points, rightVec, downVec, color, lineThickness); } diff --git a/Gems/LyShine/Code/Editor/ViewportIcon.h b/Gems/LyShine/Code/Editor/ViewportIcon.h index 85fd2fe068..b61d0715b6 100644 --- a/Gems/LyShine/Code/Editor/ViewportIcon.h +++ b/Gems/LyShine/Code/Editor/ViewportIcon.h @@ -49,6 +49,21 @@ public: // width of the border (but the texture can have alpha at edges to make it thinner). void DrawElementRectOutline(Draw2dHelper& draw2d, AZ::EntityId entityId, AZ::Color color); + // Set whether to apply high resolution dpi scaling to the icon size + void SetApplyDpiScaleFactorToSize(bool apply) { m_applyDpiScaleFactorToSize = apply; } + + // Get whether to apply high resolution dpi scaling to the icon size + bool GetApplyDpiScaleFactorToSize() { return m_applyDpiScaleFactorToSize; } + + // Set scale factor + static void SetDpiScaleFactor(float scale) { m_dpiScaleFactor = scale; } + + // Get scale factor + static float GetDpiScaleFactor() { return m_dpiScaleFactor; } + private: AZ::Data::Instance m_image; + bool m_applyDpiScaleFactorToSize = true; + + static float m_dpiScaleFactor; }; diff --git a/Gems/LyShine/Code/Editor/ViewportInteraction.cpp b/Gems/LyShine/Code/Editor/ViewportInteraction.cpp index 60b7f4f35b..c846bbb8c3 100644 --- a/Gems/LyShine/Code/Editor/ViewportInteraction.cpp +++ b/Gems/LyShine/Code/Editor/ViewportInteraction.cpp @@ -167,8 +167,8 @@ ViewportInteraction::ViewportInteraction(EditorWindow* editorWindow) : QObject() , m_editorWindow(editorWindow) , m_activeElementId() - , m_anchorWhole(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Anchor_Whole.tif")) - , m_pivotIcon(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Pivot.tif")) + , m_anchorWhole(new ViewportIcon("Editor/Icons/Viewport/Anchor_Whole.tif")) + , m_pivotIcon(new ViewportIcon("Editor/Icons/Viewport/Pivot.tif")) , m_interactionMode(PersistentGetInteractionMode()) , m_interactionType(InteractionType::NONE) , m_coordinateSystem(PersistentGetCoordinateSystem()) @@ -186,13 +186,13 @@ ViewportInteraction::ViewportInteraction(EditorWindow* editorWindow) , m_startAnchors(UiTransform2dInterface::Anchors()) , m_grabbedAnchors(ViewportHelpers::SelectedAnchors()) , m_grabbedGizmoParts(ViewportHelpers::GizmoParts()) - , m_lineTriangleX(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Triangle_X.tif")) - , m_lineTriangleY(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Triangle_Y.tif")) - , m_circle(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Circle.tif")) - , m_lineSquareX(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Square_X.tif")) - , m_lineSquareY(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Line_Square_Y.tif")) - , m_centerSquare(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Transform_Gizmo_Center_Square.tif")) - , m_dottedLine(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/DottedLine.tif")) + , m_lineTriangleX(new ViewportIcon("Editor/Icons/Viewport/Transform_Gizmo_Line_Triangle_X.tif")) + , m_lineTriangleY(new ViewportIcon("Editor/Icons/Viewport/Transform_Gizmo_Line_Triangle_Y.tif")) + , m_circle(new ViewportIcon("Editor/Icons/Viewport/Transform_Gizmo_Circle.tif")) + , m_lineSquareX(new ViewportIcon("Editor/Icons/Viewport/Transform_Gizmo_Line_Square_X.tif")) + , m_lineSquareY(new ViewportIcon("Editor/Icons/Viewport/Transform_Gizmo_Line_Square_Y.tif")) + , m_centerSquare(new ViewportIcon("Editor/Icons/Viewport/Transform_Gizmo_Center_Square.tif")) + , m_dottedLine(new ViewportIcon("Editor/Icons/Viewport/DottedLine.tif")) , m_dragInteraction(nullptr) , m_expanderWatcher(new ViewportInteractionExpanderWatcher(this)) { @@ -908,8 +908,9 @@ void ViewportInteraction::GetScaleToFitTransformProps(const AZ::Vector2* newCanv EBUS_EVENT_ID_RESULT(canvasSize, m_editorWindow->GetCanvas(), UiCanvasBus, GetCanvasSize); } - const int viewportWidth = m_editorWindow->GetViewport()->size().width(); - const int viewportHeight = m_editorWindow->GetViewport()->size().height(); + QSize viewportSize = QtHelpers::GetDpiScaledViewportSize(*m_editorWindow->GetViewport()); + const int viewportWidth = viewportSize.width(); + const int viewportHeight = viewportSize.height(); // We pad the edges of the viewport to allow the user to easily see the borders of // the canvas edges, which is especially helpful if there are anchors sitting on diff --git a/Gems/LyShine/Code/Editor/ViewportPivot.cpp b/Gems/LyShine/Code/Editor/ViewportPivot.cpp index 694cf91515..c264f7093d 100644 --- a/Gems/LyShine/Code/Editor/ViewportPivot.cpp +++ b/Gems/LyShine/Code/Editor/ViewportPivot.cpp @@ -15,7 +15,7 @@ #include "ViewportPivot.h" ViewportPivot::ViewportPivot() - : m_pivot(new ViewportIcon("Plugins/UiCanvasEditor/CanvasIcons/Pivot.tif")) + : m_pivot(new ViewportIcon("Editor/Icons/Viewport/Pivot.tif")) { } diff --git a/Gems/LyShine/Code/Editor/ViewportWidget.cpp b/Gems/LyShine/Code/Editor/ViewportWidget.cpp index 89c5a0bb50..f9464f17c7 100644 --- a/Gems/LyShine/Code/Editor/ViewportWidget.cpp +++ b/Gems/LyShine/Code/Editor/ViewportWidget.cpp @@ -38,6 +38,7 @@ #include #include +#include #define UICANVASEDITOR_SETTINGS_VIEWPORTWIDGET_DRAW_ELEMENT_BORDERS_KEY "ViewportWidget::m_drawElementBordersFlags" #define UICANVASEDITOR_SETTINGS_VIEWPORTWIDGET_DRAW_ELEMENT_BORDERS_DEFAULT ( ViewportWidget::DrawElementBorders_Unselected ) @@ -220,8 +221,6 @@ ViewportWidget::ViewportWidget(EditorWindow* parent) { setAcceptDrops(true); - UpdateViewportBackground(); - InitUiRenderer(); SetupShortcuts(); @@ -299,19 +298,6 @@ void ViewportWidget::ToggleDrawElementBorders(uint32 flags) SetDrawElementBordersFlags(m_drawElementBordersFlags); } -void ViewportWidget::UpdateViewportBackground() -{ - const QColor backgroundColor(ViewportHelpers::backgroundColorDark.GetR8(), - ViewportHelpers::backgroundColorDark.GetG8(), - ViewportHelpers::backgroundColorDark.GetB8(), - ViewportHelpers::backgroundColorDark.GetA8()); - - QPalette pal(palette()); - pal.setColor(QPalette::Window, backgroundColor); - setPalette(pal); - setAutoFillBackground(true); -} - void ViewportWidget::ActiveCanvasChanged() { bool canvasLoaded = m_editorWindow->GetCanvas().IsValid(); @@ -519,6 +505,9 @@ void ViewportWidget::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoin gEnv->pRenderer->SetSrgbWrite(true); #endif + const float dpiScale = QtHelpers::GetHighDpiScaleFactor(*this); + ViewportIcon::SetDpiScaleFactor(dpiScale); + // Set up to render a frame to this viewport's window GetViewportContext()->RenderTick(); @@ -554,7 +543,9 @@ void ViewportWidget::RefreshTick() void ViewportWidget::mousePressEvent(QMouseEvent* ev) { UiEditorMode editorMode = m_editorWindow->GetEditorMode(); - QMouseEvent scaledEvent(ev->type(), WidgetToViewport(ev->localPos()), ev->button(), ev->buttons(), ev->modifiers()); + + QPointF scaledPosition = WidgetToViewport(ev->localPos()); + QMouseEvent scaledEvent(ev->type(), scaledPosition, ev->button(), ev->buttons(), ev->modifiers()); if (editorMode == UiEditorMode::Edit) { // in Edit mode just send input to ViewportInteraction @@ -569,8 +560,7 @@ void ViewportWidget::mousePressEvent(QMouseEvent* ev) if (ev->button() == Qt::LeftButton) { // Send event to this canvas - QPointF scaledPos = WidgetToViewport(ev->localPos()); - const AZ::Vector2 viewportPosition(aznumeric_cast(scaledPos.x()), aznumeric_cast(scaledPos.y())); + const AZ::Vector2 viewportPosition(aznumeric_cast(scaledPosition.x()), aznumeric_cast(scaledPosition.y())); const AzFramework::InputChannel::Snapshot inputSnapshot(AzFramework::InputDeviceMouse::Button::Left, AzFramework::InputDeviceMouse::Id, AzFramework::InputChannel::State::Began); @@ -588,7 +578,9 @@ void ViewportWidget::mousePressEvent(QMouseEvent* ev) void ViewportWidget::mouseMoveEvent(QMouseEvent* ev) { UiEditorMode editorMode = m_editorWindow->GetEditorMode(); - QMouseEvent scaledEvent(ev->type(), WidgetToViewport(ev->localPos()), ev->button(), ev->buttons(), ev->modifiers()); + + QPointF scaledPosition = WidgetToViewport(ev->localPos()); + QMouseEvent scaledEvent(ev->type(), scaledPosition, ev->button(), ev->buttons(), ev->modifiers()); if (editorMode == UiEditorMode::Edit) { @@ -596,7 +588,8 @@ void ViewportWidget::mouseMoveEvent(QMouseEvent* ev) m_viewportInteraction->MouseMoveEvent(&scaledEvent, m_editorWindow->GetHierarchy()->selectedItems()); - SetRulerCursorPositions(ev->globalPos()); + QPointF screenPosition = WidgetToViewport(ev->screenPos()); + SetRulerCursorPositions(screenPosition.toPoint()); } else // if (editorMode == UiEditorMode::Preview) { @@ -604,8 +597,7 @@ void ViewportWidget::mouseMoveEvent(QMouseEvent* ev) AZ::EntityId canvasEntityId = m_editorWindow->GetPreviewModeCanvas(); if (canvasEntityId.IsValid()) { - QPointF scaledPos = WidgetToViewport(ev->localPos()); - const AZ::Vector2 viewportPosition(aznumeric_cast(scaledPos.x()), aznumeric_cast(scaledPos.y())); + const AZ::Vector2 viewportPosition(aznumeric_cast(scaledPosition.x()), aznumeric_cast(scaledPosition.y())); const AzFramework::InputChannelId& channelId = (ev->buttons() & Qt::LeftButton) ? AzFramework::InputDeviceMouse::Button::Left : AzFramework::InputDeviceMouse::SystemCursorPosition; @@ -625,7 +617,9 @@ void ViewportWidget::mouseMoveEvent(QMouseEvent* ev) void ViewportWidget::mouseReleaseEvent(QMouseEvent* ev) { UiEditorMode editorMode = m_editorWindow->GetEditorMode(); - QMouseEvent scaledEvent(ev->type(), WidgetToViewport(ev->localPos()), ev->button(), ev->buttons(), ev->modifiers()); + + QPointF scaledPosition = WidgetToViewport(ev->localPos()); + QMouseEvent scaledEvent(ev->type(), scaledPosition, ev->button(), ev->buttons(), ev->modifiers()); if (editorMode == UiEditorMode::Edit) { // in Edit mode just send input to ViewportInteraction @@ -641,8 +635,7 @@ void ViewportWidget::mouseReleaseEvent(QMouseEvent* ev) if (ev->button() == Qt::LeftButton) { // Send event to this canvas - QPointF scaledPos = WidgetToViewport(ev->localPos()); - const AZ::Vector2 viewportPosition(aznumeric_cast(scaledPos.x()), aznumeric_cast(scaledPos.y())); + const AZ::Vector2 viewportPosition(aznumeric_cast(scaledPosition.x()), aznumeric_cast(scaledPosition.y())); const AzFramework::InputChannel::Snapshot inputSnapshot(AzFramework::InputDeviceMouse::Button::Left, AzFramework::InputDeviceMouse::Id, AzFramework::InputChannel::State::Ended); @@ -726,7 +719,7 @@ bool ViewportWidget::event(QEvent* ev) } } - bool result = QWidget::event(ev); + bool result = RenderViewportWidget::event(ev); return result; } @@ -931,14 +924,16 @@ void ViewportWidget::RenderEditMode(float deltaTime) EBUS_EVENT_ID_RESULT(canvasSize, canvasEntityId, UiCanvasBus, GetCanvasSize); m_draw2d->SetSortKey(backgroundKey); + + // Render a rectangle covering the entire editor viewport area + RenderViewportBackground(); + + // Render a checkerboard background covering the canvas area which represents transparency m_viewportBackground->Draw(draw2d, canvasSize, m_viewportInteraction->GetCanvasToViewportScale(), m_viewportInteraction->GetCanvasToViewportTranslation()); - AZ::Vector2 viewportSize(aznumeric_cast(size().width()), aznumeric_cast(size().height())); - viewportSize *= QHighDpiScaling::factor(windowHandle()->screen()); - #ifdef LYSHINE_ATOM_TODO // clear the stencil buffer before rendering each canvas - required for masking // NOTE: the FRT_CLEAR_IMMEDIATE is required since we will not be setting the render target @@ -953,6 +948,8 @@ void ViewportWidget::RenderEditMode(float deltaTime) EBUS_EVENT_ID(canvasEntityId, UiEditorCanvasBus, UpdateCanvasInEditorViewport, deltaTime, false); // Render this canvas + QSize scaledViewportSize = QtHelpers::GetDpiScaledViewportSize(*this); + AZ::Vector2 viewportSize(scaledViewportSize.width(), scaledViewportSize.height()); EBUS_EVENT_ID(canvasEntityId, UiEditorCanvasBus, RenderCanvasInEditorViewport, false, viewportSize); m_draw2d->SetSortKey(topLayerKey); @@ -1050,6 +1047,9 @@ void ViewportWidget::RenderEditMode(float deltaTime) void ViewportWidget::RenderPreviewMode(float deltaTime) { + // sort keys for different layers + static const int64_t backgroundKey = -0x1000; + AZ::EntityId canvasEntityId = m_editorWindow->GetPreviewModeCanvas(); if (m_fontTextureHasChanged) @@ -1072,10 +1072,10 @@ void ViewportWidget::RenderPreviewMode(float deltaTime) if (canvasEntityId.IsValid()) { - // Get the canvas size - AZ::Vector2 viewportSize(aznumeric_cast(size().width()), aznumeric_cast(size().height())); - viewportSize *= QHighDpiScaling::factor(windowHandle()->screen()); + QSize scaledViewportSize = QtHelpers::GetDpiScaledViewportSize(*this); + AZ::Vector2 viewportSize(scaledViewportSize.width(), scaledViewportSize.height()); + // Get the canvas size AZ::Vector2 canvasSize = m_editorWindow->GetPreviewCanvasSize(); if (canvasSize.GetX() == 0.0f && canvasSize.GetY() == 0.0f) { @@ -1139,7 +1139,7 @@ void ViewportWidget::RenderPreviewMode(float deltaTime) canvasToViewportMatrix.SetTranslation(translation); EBUS_EVENT_ID(canvasEntityId, UiCanvasBus, SetCanvasToViewportMatrix, canvasToViewportMatrix); -#ifdef LYSHINE_ATOM_TODO +#ifdef LYSHINE_ATOM_TODO // mask support with Atom // clear the stencil buffer before rendering each canvas - required for masking // NOTE: the FRT_CLEAR_IMMEDIATE is required since we will not be setting the render target // We also clear the color to a mid grey so that we can see the bounds of the canvas @@ -1147,16 +1147,18 @@ void ViewportWidget::RenderPreviewMode(float deltaTime) gEnv->pRenderer->ClearTargetsImmediately(FRT_CLEAR, viewportBackgroundColor); #endif -#ifdef LYSHINE_ATOM_TODO + m_draw2d->SetSortKey(backgroundKey); + + RenderViewportBackground(); + // Render a black rectangle covering the canvas area. This allows the canvas bounds to be visible when the canvas size is // not exactly the same as the viewport size AZ::Vector2 topLeftInViewportSpace = CanvasHelpers::GetViewportPoint(canvasEntityId, AZ::Vector2(0.0f, 0.0f)); AZ::Vector2 bottomRightInViewportSpace = CanvasHelpers::GetViewportPoint(canvasEntityId, canvasSize); AZ::Vector2 sizeInViewportSpace = bottomRightInViewportSpace - topLeftInViewportSpace; - Draw2dHelper draw2d(m_draw2d.get()) - int texId = gEnv->pRenderer->GetBlackTextureId(); - draw2d.DrawImage(texId, topLeftInViewportSpace, sizeInViewportSpace); -#endif + Draw2dHelper draw2d(m_draw2d.get()); + auto image = AZ::RPI::ImageSystemInterface::Get()->GetSystemImage(AZ::RPI::SystemImage::Black); + draw2d.DrawImage(image, topLeftInViewportSpace, sizeInViewportSpace); // Render this canvas // NOTE: the displayBounds param is always false. If we wanted a debug option to display the bounds @@ -1166,6 +1168,17 @@ void ViewportWidget::RenderPreviewMode(float deltaTime) } } +void ViewportWidget::RenderViewportBackground() +{ + QSize viewportSize = QtHelpers::GetDpiScaledViewportSize(*this); + AZ::Color backgroundColor = ViewportHelpers::backgroundColorDark; + const AZ::Data::Instance& image = AZ::RPI::ImageSystemInterface::Get()->GetSystemImage(AZ::RPI::SystemImage::White); + + Draw2dHelper draw2d(m_draw2d.get()); + draw2d.SetImageColor(backgroundColor.GetAsVector3()); + draw2d.DrawImage(image, AZ::Vector2(0.0f, 0.0f), AZ::Vector2(viewportSize.width(), viewportSize.height())); +} + void ViewportWidget::SetupShortcuts() { // Actions with shortcuts are created instead of direct shortcuts because the shortcut dispatcher only looks for matching actions diff --git a/Gems/LyShine/Code/Editor/ViewportWidget.h b/Gems/LyShine/Code/Editor/ViewportWidget.h index 4d15f3dea4..77f07d7f6e 100644 --- a/Gems/LyShine/Code/Editor/ViewportWidget.h +++ b/Gems/LyShine/Code/Editor/ViewportWidget.h @@ -54,8 +54,6 @@ public: // member functions bool IsDrawingElementBorders(uint32 flags) const; void ToggleDrawElementBorders(uint32 flags); - void UpdateViewportBackground(); - void ActiveCanvasChanged(); void EntityContextChanged(); @@ -154,6 +152,9 @@ private: // member functions //! Render the viewport when in preview mode void RenderPreviewMode(float deltaTime); + //! Fill the entire viewport area with a background color + void RenderViewportBackground(); + //! Create shortcuts for manipulating the viewport void SetupShortcuts(); diff --git a/Gems/LyShine/Code/Include/LyShine/Draw2d.h b/Gems/LyShine/Code/Include/LyShine/Draw2d.h index df61542e25..8270461e73 100644 --- a/Gems/LyShine/Code/Include/LyShine/Draw2d.h +++ b/Gems/LyShine/Code/Include/LyShine/Draw2d.h @@ -131,16 +131,18 @@ public: // member functions //! Draw a rectangular outline with a texture // - //! \param image The texture to be used for drawing the outline - //! \param points The rect's vertices (top left, top right, bottom right, bottom left) - //! \param rightVec Right vector. Specified because the rect's width/height could be 0 - //! \param downVec Down vector. Specified because the rect's width/height could be 0 - //! \param color The color of the outline + //! \param image The texture to be used for drawing the outline + //! \param points The rect's vertices (top left, top right, bottom right, bottom left) + //! \param rightVec Right vector. Specified because the rect's width/height could be 0 + //! \param downVec Down vector. Specified because the rect's width/height could be 0 + //! \param color The color of the outline + //! \param lineThickness The thickness in pixels of the outline. If 0, it will be based on image height void DrawRectOutlineTextured(AZ::Data::Instance image, UiTransformInterface::RectPoints points, AZ::Vector2 rightVec, AZ::Vector2 downVec, - AZ::Color color); + AZ::Color color, + uint32_t lineThickness = 0); //! Get the width and height (in pixels) that would be used to draw the given text string. // @@ -439,11 +441,12 @@ public: // member functions UiTransformInterface::RectPoints points, AZ::Vector2 rightVec, AZ::Vector2 downVec, - AZ::Color color) + AZ::Color color, + uint32_t lineThickness = 0) { if (m_draw2d) { - m_draw2d->DrawRectOutlineTextured(image, points, rightVec, downVec, color); + m_draw2d->DrawRectOutlineTextured(image, points, rightVec, downVec, color, lineThickness); } } diff --git a/Gems/LyShine/Code/Source/Draw2d.cpp b/Gems/LyShine/Code/Source/Draw2d.cpp index 308761ff4e..1a639ea299 100644 --- a/Gems/LyShine/Code/Source/Draw2d.cpp +++ b/Gems/LyShine/Code/Source/Draw2d.cpp @@ -309,7 +309,8 @@ void CDraw2d::DrawRectOutlineTextured(AZ::Data::Instance image, UiTransformInterface::RectPoints points, AZ::Vector2 rightVec, AZ::Vector2 downVec, - AZ::Color color) + AZ::Color color, + uint32_t lineThickness) { // since the rect can be transformed we have to add the offsets by multiplying them // by unit vectors parallel with the edges of the rect. However, the rect could be @@ -325,18 +326,22 @@ void CDraw2d::DrawRectOutlineTextured(AZ::Data::Instance image, float rectWidth = widthVec.GetLength(); float rectHeight = heightVec.GetLength(); - // the outline thickness will be based on the texture height - float textureHeight = image ? aznumeric_cast(image->GetDescriptor().m_size.m_height) : 0.0f; - if (textureHeight <= 0.0f) + if (lineThickness == 0 && image) { - AZ_Assert(false, "Attempting to draw a textured rect outline with an image of zero height."); - return; // avoiding possible divide by zero later + lineThickness = image->GetDescriptor().m_size.m_height; + } + + if (lineThickness == 0) + { + AZ_Assert(false, "Attempting to draw a rect outline with of zero thickness."); + return; } // the outline is centered on the element rect so half the outline is outside // the rect and half is inside the rect - float outerOffset = -textureHeight * 0.5f; - float innerOffset = textureHeight * 0.5f; + float offset = aznumeric_cast(lineThickness); + float outerOffset = -offset * 0.5f; + float innerOffset = offset * 0.5f; float outerV = 0.0f; float innerV = 1.0f; @@ -348,7 +353,7 @@ void CDraw2d::DrawRectOutlineTextured(AZ::Data::Instance image, { float oldInnerOffset = innerOffset; innerOffset = minDimension * 0.5f; - // note oldInnerOffset can't be zero because of early return if textureHeight is zero + // note oldInnerOffset can't be zero because of early return if lineThickness is zero innerV = 0.5f + 0.5f * innerOffset / oldInnerOffset; } From 0867764e5b732074a67985c4d758fab1a53910db Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Tue, 11 May 2021 22:46:21 -0700 Subject: [PATCH 053/231] Updating Autocomponent behavior context property methods to give warnings if a Get/Set fails and how users might go about fixing the issue --- .../Source/AutoGen/AutoComponent_Source.jinja | 49 ++++++++++++------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 423aa57706..576978f75c 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -666,36 +666,46 @@ enum class NetworkProperties {% if (Property.attrib['IsPublic'] | booleanTrue == true) and (Property.attrib['GenerateEventBindings'] | booleanTrue == true) %} ->Method("Get{{ UpperFirst(Property.attrib['Name']) }}", [](AZ::EntityId id) -> {{ Property.attrib['Type'] }} { - AZ::Entity* entity; - AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, id); - - if (entity) + AZ::Entity* entity = AZ::Interface::Get()->FindEntity(id); + if (!entity) { - if (auto* networkComponent = entity->FindComponent<{{ ClassName }}>()) - { - return networkComponent->Get{{ UpperFirst(Property.attrib['Name']) }}(); - } + 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 {{ Property.attrib['Type'] }}(); } - return {{ Property.attrib['Type'] }}(); + {{ 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'] }}(); + } + + return networkComponent->Get{{ UpperFirst(Property.attrib['Name']) }}(); }) ->Method("Set{{ UpperFirst(Property.attrib['Name']) }}", [](AZ::EntityId id, const {{ Property.attrib['Type'] }}& {{ LowerFirst(Property.attrib['Name']) }}) -> void { - AZ::Entity* entity; - AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, id); - - if (entity) + AZ::Entity* entity = AZ::Interface::Get()->FindEntity(id); + if (!entity) { + AZ_Warning("Network Property", false, "{{ ClassName }} Set{{ 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 }} Set{{ UpperFirst(Property.attrib['Name']) }} method 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; } - if (auto* networkComponent = entity->FindComponent<{{ ClassName }}>()) + {{ ClassName }}Controller* controller = static_cast<{{ ClassName }}Controller*>(networkComponent->GetController()); + if (!controller) { - if (auto* controller = static_cast<{{ ClassName }}Controller*>(networkComponent->GetController())) - { - controller->Set{{ UpperFirst(Property.attrib['Name']) }}({{ LowerFirst(Property.attrib['Name']) }}); - } + AZ_Warning("Network Property", false, "{{ ClassName }} Set{{ UpperFirst(Property.attrib['Name']) }} method failed. Entity '%s' (id: %s) {{ ClassName }} is missing the network controller. Network controllers only spawn when some form of write access is available; for example, when you're server authoritatively controlling this entity, or you're a client predictively writing to your player entity. Please check your network context before attempting to set {{ UpperFirst(Property.attrib['Name']) }}.", entity->GetName().c_str(), id.ToString().c_str()) + return; } + + controller->Set{{ UpperFirst(Property.attrib['Name']) }}({{ LowerFirst(Property.attrib['Name']) }}); }) {% endif %} {% endcall -%} @@ -1183,7 +1193,8 @@ namespace {{ Component.attrib['Namespace'] }} void {{ ComponentBaseName }}::{{ ComponentBaseName }}::ReflectToBehaviorContext(AZ::ReflectContext* context) { - if (auto* behaviorContext = azrtti_cast(context)) + AZ::BehaviorContext* behaviorContext = azrtti_cast(context); + if (behaviorContext) { behaviorContext->Class<{{ ComponentName }}>("{{ ComponentName }}") {{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Authority', ComponentName)|indent(16) -}} From 905bdf9627f5c6226624d3343fb2c45f0d707440 Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Mon, 3 May 2021 16:32:18 -0700 Subject: [PATCH 054/231] Fix sprite asset selection in property editor (#384) * Fix sprite asset selection in property editor * Linux compile fix * More fixes for the custom Sprite property handler * PR feedback to use existing constant image extension --- .../Code/Editor/PropertyHandlerSprite.cpp | 26 +++- Gems/LyShine/Code/Source/Sprite.cpp | 125 +++++++++++------- Gems/LyShine/Code/Source/Sprite.h | 8 ++ Gems/LyShine/Code/Source/UiImageComponent.cpp | 3 +- 4 files changed, 106 insertions(+), 56 deletions(-) diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp index 20721d4624..9263210088 100644 --- a/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp +++ b/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp @@ -11,6 +11,7 @@ */ #include "UiCanvasEditor_precompiled.h" #include "EditorCommon.h" +#include "Sprite.h" #include "PropertyHandlerSprite.h" @@ -31,6 +32,8 @@ #include +#include + #include #include @@ -44,6 +47,7 @@ PropertySpriteCtrl::PropertySpriteCtrl(QWidget* parent) [ this ]([[maybe_unused]] AZ::Data::AssetId newAssetID) { EBUS_EVENT(AzToolsFramework::PropertyEditorGUIMessages::Bus, RequestWrite, this); + AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::Bus::Handler::OnEditingFinished, m_propertyAssetCtrl); }); setAcceptDrops(true); @@ -150,7 +154,9 @@ void PropertyHandlerSprite::WriteGUIValuesIntoProperty(size_t index, PropertySpr AZStd::string assetPath; EBUS_EVENT_RESULT(assetPath, AZ::Data::AssetCatalogRequestBus, GetAssetPathById, GUI->GetPropertyAssetCtrl()->GetCurrentAssetID()); - instance.SetAssetPath(assetPath.c_str()); + // Convert streaming image's product path to relative source path to assign to the SimpleAssetReference + AZStd::string sourcePath = CSprite::GetImageSourcePathFromProductPath(assetPath); + instance.SetAssetPath(sourcePath.c_str()); } bool PropertyHandlerSprite::ReadValuesIntoGUI(size_t index, PropertySpriteCtrl* GUI, const property_t& instance, AzToolsFramework::InstanceDataNode* node) @@ -162,12 +168,26 @@ bool PropertyHandlerSprite::ReadValuesIntoGUI(size_t index, PropertySpriteCtrl* ctrl->blockSignals(true); { - ctrl->SetCurrentAssetType(instance.GetAssetType()); + // Set the asset type for the PropertyAssetCtrl. + // Use the hardcoded streaming image asset type instead of the passed in instance's asset type + // since the passed in type is the legacy SimpleAssetReference, and the asset picker + // does not associate this type with streaming images + AZ::Data::AssetType assetType = AZ::AzTypeInfo::Uuid(); + ctrl->SetCurrentAssetType(assetType); AZ::Data::AssetId assetId; if (!instance.GetAssetPath().empty()) { - EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, instance.GetAssetPath().c_str(), instance.GetAssetType(), false); + // Get the image path from the SimpleAssetReference and fix it up since CSprite still + // allows user specified paths that have the .sprite extension or the deprecated .dds extension + AZStd::string sourcePath = CSprite::GetImageSourcePathFromProductPath(instance.GetAssetPath()); + AZStd::string fixedUpSourcePath; + CSprite::FixUpSourceImagePathFromUserDefinedPath(sourcePath, fixedUpSourcePath); + + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetId, &AZ::Data::AssetCatalogRequestBus::Events::GenerateAssetIdTEMP, + fixedUpSourcePath.c_str()); + assetId.m_subId = AZ::RPI::StreamingImageAsset::GetImageAssetSubId(); } ctrl->SetSelectedAssetID(assetId); } diff --git a/Gems/LyShine/Code/Source/Sprite.cpp b/Gems/LyShine/Code/Source/Sprite.cpp index c574a16c0c..26e4056a41 100644 --- a/Gems/LyShine/Code/Source/Sprite.cpp +++ b/Gems/LyShine/Code/Source/Sprite.cpp @@ -26,6 +26,7 @@ namespace { const char* const spriteExtension = "sprite"; + const char* const streamingImageExtension = "streamingimage"; // Increment this when the Sprite Serialize(TSerialize) function // changes to be incompatible with previous data @@ -37,7 +38,7 @@ namespace }; const int numAllowedSpriteTextureExtensions = AZ_ARRAY_SIZE(allowedSpriteTextureExtensions); - bool IsValidSpriteTextureExtension(const AZStd::string& extension) + bool IsValidImageExtension(const AZStd::string& extension) { for (int i = 0; i < numAllowedSpriteTextureExtensions; ++i) { @@ -50,6 +51,13 @@ namespace return false; } + bool IsImageProductPath(const AZStd::string& pathname) + { + AZStd::string extension; + AzFramework::StringFunc::Path::GetExtension(pathname.c_str(), extension, false); + return (extension.compare(streamingImageExtension) == 0); + } + // Check if a file exists. This does not go through the AssetCatalog so that it can identify files that exist but aren't processed yet, // and so that it will work before the AssetCatalog has loaded bool CheckIfFileExists(const AZStd::string& sourceRelativePath, const AZStd::string& cacheRelativePath) @@ -88,61 +96,49 @@ namespace return fileExists; } - bool ReplaceSpriteExtensionWithTextureExtension(const AZStd::string& spritePath, AZStd::string& texturePath) + bool GetSourceAssetPaths(const AZStd::string& pathname, AZStd::string& spritePath, AZStd::string& texturePath) { - for (int i = 0; i < numAllowedSpriteTextureExtensions; ++i) + // Remove product extension from the texture path if it exists + AZStd::string sourcePathname(pathname); + if (IsImageProductPath(pathname)) { - AZStd::string sourceRelativePath(spritePath); - AzFramework::StringFunc::Path::ReplaceExtension(sourceRelativePath, allowedSpriteTextureExtensions[i]); - AZStd::string cacheRelativePath = sourceRelativePath + ".streamingimage"; - - bool textureExists = CheckIfFileExists(sourceRelativePath, cacheRelativePath); - if (textureExists) - { - texturePath = sourceRelativePath; - return true; - } + sourcePathname = CSprite::GetImageSourcePathFromProductPath(pathname); } - return false; - } - - bool GetAssetPaths(const AZStd::string& pathname, AZStd::string& spritePath, AZStd::string& texturePath) - { - // the input string could be in any form. So make it normalized + // the input string could be in any form. So make it normalized (forward slashes and lower case) // NOTE: it should not be a full path at this point. If called from the UI editor it will // have been transformed to a game path. If being called with a hard coded path it should be a // game path already - it is not good for code to be using full paths. - AZStd::string assetPath(pathname); - EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePath, assetPath); + EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePath, sourcePathname); // check the extension and work out the pathname of the sprite file and the texture file // currently it works if the input path is either a sprite file or a texture file AZStd::string extension; - AzFramework::StringFunc::Path::GetExtension(assetPath.c_str(), extension, false); + AzFramework::StringFunc::Path::GetExtension(sourcePathname.c_str(), extension, false); if (extension.compare(spriteExtension) == 0) { - spritePath = assetPath; + // The .sprite file has been specified + spritePath = sourcePathname; // look for a texture file with the same name - if (!ReplaceSpriteExtensionWithTextureExtension(spritePath, texturePath)) + if (!CSprite::FixUpSourceImagePathFromUserDefinedPath(spritePath, texturePath)) { gEnv->pSystem->Warning(VALIDATOR_MODULE_SHINE, VALIDATOR_WARNING, VALIDATOR_FLAG_FILE | VALIDATOR_FLAG_TEXTURE, - assetPath.c_str(), "No texture file found for sprite: %s, no sprite will be used", assetPath.c_str()); + spritePath.c_str(), "No texture file found for sprite: %s, no sprite will be used", spritePath.c_str()); return false; } } - else if (IsValidSpriteTextureExtension(extension)) + else if (IsValidImageExtension(extension)) { - texturePath = assetPath; - spritePath = assetPath; + texturePath = sourcePathname; + spritePath = sourcePathname; AzFramework::StringFunc::Path::ReplaceExtension(spritePath, spriteExtension); } else { gEnv->pSystem->Warning(VALIDATOR_MODULE_SHINE, VALIDATOR_WARNING, VALIDATOR_FLAG_FILE | VALIDATOR_FLAG_TEXTURE, - assetPath.c_str(), "Invalid file extension for sprite: %s, no sprite will be used", assetPath.c_str()); + pathname.c_str(), "Invalid file extension for sprite: %s, no sprite will be used", pathname.c_str()); return false; } @@ -665,7 +661,7 @@ CSprite* CSprite::LoadSprite(const string& pathname) { AZStd::string spritePath; AZStd::string texturePath; - bool validAssetPaths = GetAssetPaths(pathname.c_str(), spritePath, texturePath); + bool validAssetPaths = GetSourceAssetPaths(pathname.c_str(), spritePath, texturePath); if (!validAssetPaths) { @@ -760,7 +756,7 @@ bool CSprite::DoesSpriteTextureAssetExist(const AZStd::string& pathname) { AZStd::string spritePath; AZStd::string texturePath; - bool validAssetPaths = GetAssetPaths(pathname, spritePath, texturePath); + bool validAssetPaths = GetSourceAssetPaths(pathname.c_str(), spritePath, texturePath); if (!validAssetPaths) { @@ -785,8 +781,7 @@ bool CSprite::DoesSpriteTextureAssetExist(const AZStd::string& pathname) } // Check if the texture asset exists - AZStd::string cacheRelativePath = texturePath + ".streamingimage"; - bool textureExists = CheckIfFileExists(texturePath, cacheRelativePath); + bool textureExists = CheckIfFileExists(spritePath, texturePath); return textureExists; } @@ -806,6 +801,48 @@ void CSprite::ReplaceSprite(ISprite** baseSprite, ISprite* newSprite) } } +//////////////////////////////////////////////////////////////////////////////////////////////////// +bool CSprite::FixUpSourceImagePathFromUserDefinedPath(const AZStd::string& userDefinedPath, AZStd::string& sourceImagePath) +{ + static const char* textureExtensions[] = { "png", "tif", "tiff", "tga", "jpg", "jpeg", "bmp", "gif" }; + + AZStd::string sourceRelativePath(userDefinedPath); + AZStd::string cacheRelativePath = AZStd::string::format("%s.%s", sourceRelativePath.c_str(), streamingImageExtension); + bool textureExists = CheckIfFileExists(sourceRelativePath, cacheRelativePath); + + if (textureExists) + { + sourceImagePath = userDefinedPath; + return true; + } + + AZStd::string curSourceImagePath(userDefinedPath); + for (const char* extensionReplacement : textureExtensions) + { + AzFramework::StringFunc::Path::ReplaceExtension(curSourceImagePath, extensionReplacement); + cacheRelativePath = AZStd::string::format("%s.%s", curSourceImagePath.c_str(), streamingImageExtension); + textureExists = CheckIfFileExists(curSourceImagePath, cacheRelativePath); + + if (textureExists) + { + sourceImagePath = curSourceImagePath; + return true; + } + } + + return false; +} + +AZStd::string CSprite::GetImageSourcePathFromProductPath(const AZStd::string& productPathname) +{ + AZStd::string sourcePathname(productPathname); + if (IsImageProductPath(sourcePathname)) + { + AzFramework::StringFunc::Path::StripExtension(sourcePathname); + } + return sourcePathname; +} + //////////////////////////////////////////////////////////////////////////////////////////////////// bool CSprite::LoadTexture(const string& texturePathname, const string& pathname, ITexture*& texture) { @@ -850,7 +887,7 @@ void CSprite::ReleaseTexture(ITexture*& texture) bool CSprite::LoadImage(const AZStd::string& nameTex, AZ::Data::Instance& image) { AZStd::string sourceRelativePath(nameTex); - AZStd::string cacheRelativePath = sourceRelativePath + ".streamingimage"; + AZStd::string cacheRelativePath = AZStd::string::format("%s.%s", sourceRelativePath.c_str(), streamingImageExtension); bool textureExists = CheckIfFileExists(sourceRelativePath, cacheRelativePath); if (!textureExists) @@ -859,27 +896,13 @@ bool CSprite::LoadImage(const AZStd::string& nameTex, AZ::Data::InstanceAttribute(AZ::Edit::Attributes::ChangeNotify, AZ_CRC("RefreshEntireTree", 0xefbc823c)); editInfo->DataElement("Sprite", &UiImageComponent::m_spritePathname, "Sprite path", "The sprite path. Can be overridden by another component such as an interactable.") ->Attribute(AZ::Edit::Attributes::Visibility, &UiImageComponent::IsSpriteTypeAsset) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiImageComponent::OnEditorSpritePathnameChange) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ_CRC("RefreshEntireTree", 0xefbc823c)); + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiImageComponent::OnEditorSpritePathnameChange); editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiImageComponent::m_spriteSheetCellIndex, "Index", "Sprite-sheet index. Defines which cell in a sprite-sheet is displayed.") ->Attribute(AZ::Edit::Attributes::Visibility, &UiImageComponent::IsSpriteTypeSpriteSheet) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiImageComponent::OnIndexChange) From 3219c787ac66bf19dea7040581a27e2a80fa2d77 Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Thu, 6 May 2021 13:27:46 -0700 Subject: [PATCH 055/231] UI cursor Atom conversion (#607) --- Gems/LyShine/Code/CMakeLists.txt | 1 + Gems/LyShine/Code/Source/LyShine.cpp | 69 ++++++++++++++++++---------- Gems/LyShine/Code/Source/LyShine.h | 12 ++++- 3 files changed, 56 insertions(+), 26 deletions(-) diff --git a/Gems/LyShine/Code/CMakeLists.txt b/Gems/LyShine/Code/CMakeLists.txt index 9c46a61236..732bd1cfd4 100644 --- a/Gems/LyShine/Code/CMakeLists.txt +++ b/Gems/LyShine/Code/CMakeLists.txt @@ -93,6 +93,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) PUBLIC Gem::Atom_RPI.Public Gem::Atom_Utils.Static + Gem::Atom_Bootstrap.Headers ) ly_add_target( diff --git a/Gems/LyShine/Code/Source/LyShine.cpp b/Gems/LyShine/Code/Source/LyShine.cpp index bc6a27dac4..679cae3421 100644 --- a/Gems/LyShine/Code/Source/LyShine.cpp +++ b/Gems/LyShine/Code/Source/LyShine.cpp @@ -137,7 +137,6 @@ CLyShine::CLyShine(ISystem* system) , m_draw2d(new CDraw2d) , m_uiRenderer(new UiRenderer) , m_uiCanvasManager(new UiCanvasManager) - , m_uiCursorTexture(nullptr) , m_uiCursorVisibleCounter(0) { // Reflect the Deprecated Lua buses using the behavior context. @@ -170,6 +169,7 @@ CLyShine::CLyShine(ISystem* system) AzFramework::InputTextEventListener::Connect(); UiCursorBus::Handler::BusConnect(); AZ::TickBus::Handler::BusConnect(); + AZ::Render::Bootstrap::NotificationBus::Handler::BusConnect(); // These are internal Amazon components, so register them so that we can send back their names to our metrics collection // IF YOU ARE A THIRDPARTY WRITING A GEM, DO NOT REGISTER YOUR COMPONENTS WITH EditorMetricsComponentRegistrationBus @@ -248,17 +248,12 @@ CLyShine::~CLyShine() AZ::TickBus::Handler::BusDisconnect(); AzFramework::InputTextEventListener::Disconnect(); AzFramework::InputChannelEventListener::Disconnect(); + AZ::Render::Bootstrap::NotificationBus::Handler::BusDisconnect(); UiCanvasComponent::Shutdown(); // must be done after UiCanvasComponent::Shutdown CSprite::Shutdown(); - - if (m_uiCursorTexture) - { - m_uiCursorTexture->Release(); - m_uiCursorTexture = nullptr; - } } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -443,6 +438,9 @@ void CLyShine::Render() // Render all the canvases loaded in game m_uiCanvasManager->RenderLoadedCanvases(); + // Set sort key for draw2d layer to ensure it renders in front of the canvases + static const int64_t topLayerKey = 0x1000000; + m_draw2d->SetSortKey(topLayerKey); m_draw2d->RenderDeferredPrimitives(); // Don't render the UI cursor when in edit mode. For example during UI Preview mode a script could turn on the @@ -558,18 +556,20 @@ bool CLyShine::IsUiCursorVisible() //////////////////////////////////////////////////////////////////////////////////////////////////// void CLyShine::SetUiCursor(const char* cursorImagePath) { - if (m_uiCursorTexture) - { - m_uiCursorTexture->Release(); - m_uiCursorTexture = nullptr; - } + m_uiCursorTexture.reset(); + m_cursorImagePathToLoad.clear(); - if (cursorImagePath && *cursorImagePath && gEnv && gEnv->pRenderer) + if (cursorImagePath && *cursorImagePath) { - m_uiCursorTexture = gEnv->pRenderer->EF_LoadTexture(cursorImagePath, FT_DONT_RELEASE | FT_DONT_STREAM); - if (m_uiCursorTexture) + m_cursorImagePathToLoad = cursorImagePath; + // The cursor image can only be loaded after the RPI has been initialized. + // Note: this check could be avoided if LyShineSystemComponent included the RPISystem + // as a required service. However, LyShineSystempComponent is currently activated for + // tools as well as game and RPIService is not available with all tools such as AP. An + // enhancement would be to break LyShineSystemComponent into a game only component + if (m_uiRenderer->IsReady()) { - m_uiCursorTexture->SetClamp(true); + LoadUiCursor(); } } } @@ -581,8 +581,11 @@ AZ::Vector2 CLyShine::GetUiCursorPosition() AzFramework::InputSystemCursorRequestBus::EventResult(systemCursorPositionNormalized, AzFramework::InputDeviceMouse::Id, &AzFramework::InputSystemCursorRequests::GetSystemCursorPositionNormalized); - return AZ::Vector2(systemCursorPositionNormalized.GetX() * static_cast(gEnv->pRenderer->GetOverlayWidth()), - systemCursorPositionNormalized.GetY() * static_cast(gEnv->pRenderer->GetOverlayHeight())); + + AZ::Vector2 viewportSize = m_uiRenderer->GetViewportSize(); + + return AZ::Vector2(systemCursorPositionNormalized.GetX() * viewportSize.GetX(), + systemCursorPositionNormalized.GetY() * viewportSize.GetY()); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -642,6 +645,7 @@ bool CLyShine::OnInputTextEventFiltered(const AZStd::string& textUTF8) return result; } +//////////////////////////////////////////////////////////////////////////////////////////////////// void CLyShine::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { // Update the loaded UI canvases @@ -651,15 +655,33 @@ void CLyShine::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time Render(); } +//////////////////////////////////////////////////////////////////////////////////////////////////// int CLyShine::GetTickOrder() { return AZ::TICK_UI; } +//////////////////////////////////////////////////////////////////////////////////////////////////// +void CLyShine::OnBootstrapSceneReady([[maybe_unused]] AZ::RPI::Scene* bootstrapScene) +{ + // Load cursor if its path was set before RPI was initialized + LoadUiCursor(); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +void CLyShine::LoadUiCursor() +{ + if (!m_cursorImagePathToLoad.empty()) + { + m_uiCursorTexture = CDraw2d::LoadTexture(m_cursorImagePathToLoad); // LYSHINE_ATOM_TODO - add clamp option to draw2d and set cursor to clamp + m_cursorImagePathToLoad.clear(); + } +} + //////////////////////////////////////////////////////////////////////////////////////////////////// void CLyShine::RenderUiCursor() { - if (!gEnv || !gEnv->pRenderer || !m_uiCursorTexture || !IsUiCursorVisible()) + if (!m_uiCursorTexture || !IsUiCursorVisible()) { return; } @@ -671,13 +693,10 @@ void CLyShine::RenderUiCursor() } const AZ::Vector2 position = GetUiCursorPosition(); - const AZ::Vector2 dimensions(static_cast(m_uiCursorTexture->GetWidth()), static_cast(m_uiCursorTexture->GetHeight())); + AZ::RHI::Size cursorSize = m_uiCursorTexture->GetDescriptor().m_size; + const AZ::Vector2 dimensions(aznumeric_cast(cursorSize.m_width), aznumeric_cast(cursorSize.m_height)); -#ifdef LYSHINE_ATOM_TODO // Convert cursor to Atom image - m_draw2d->BeginDraw2d(); - m_draw2d->DrawImage(m_uiCursorTexture->GetTextureID(), position, dimensions); - m_draw2d->EndDraw2d(); -#endif + m_draw2d->DrawImage(m_uiCursorTexture, position, dimensions); } #ifndef _RELEASE diff --git a/Gems/LyShine/Code/Source/LyShine.h b/Gems/LyShine/Code/Source/LyShine.h index 943f5fa537..4c46b0db19 100644 --- a/Gems/LyShine/Code/Source/LyShine.h +++ b/Gems/LyShine/Code/Source/LyShine.h @@ -19,6 +19,9 @@ #include #include +#include +#include + #if !defined(_RELEASE) #define LYSHINE_INTERNAL_UNIT_TEST #endif @@ -41,6 +44,7 @@ class CLyShine , public AzFramework::InputChannelEventListener , public AzFramework::InputTextEventListener , public AZ::TickBus::Handler + , protected AZ::Render::Bootstrap::NotificationBus::Handler { public: @@ -111,6 +115,10 @@ public: int GetTickOrder() override; // ~TickEvents + // AZ::Render::Bootstrap::NotificationBus + void OnBootstrapSceneReady(AZ::RPI::Scene* bootstrapScene) override; + // ~AZ::Render::Bootstrap::NotificationBus + // Get the UIRenderer for the game (which is owned by CLyShine). This is not exposed outside the gem. UiRenderer* GetUiRenderer(); @@ -128,6 +136,7 @@ private: // member functions AZ_DISABLE_COPY_MOVE(CLyShine); + void LoadUiCursor(); void RenderUiCursor(); private: // static member functions @@ -146,7 +155,8 @@ private: // data std::unique_ptr m_uiCanvasManager; - ITexture* m_uiCursorTexture; + AZStd::string m_cursorImagePathToLoad; + AZ::Data::Instance m_uiCursorTexture; int m_uiCursorVisibleCounter; bool m_updatingLoadedCanvases = false; // guard against nested updates From d9cb61575e5c9afbc1d4f3f10cea3202e85db6b3 Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Fri, 7 May 2021 11:25:57 -0700 Subject: [PATCH 056/231] Fix up particle emitter to work with Atom (#626) * Fix up particle emitter component to work with Atom * PR feedback and disable render target tests until supported --- Code/CryEngine/CryCommon/LyShine/ISprite.h | 6 -- Gems/LyShine/Code/Source/Sprite.cpp | 84 +++---------------- Gems/LyShine/Code/Source/Sprite.h | 7 +- Gems/LyShine/Code/Source/UiImageComponent.cpp | 38 +++++---- .../Code/Source/UiImageSequenceComponent.cpp | 19 ++++- .../Source/UiParticleEmitterComponent.cpp | 27 ++++-- Gems/LyShine/Code/Tests/SpriteTest.cpp | 2 + .../Code/Source/UiCustomImageComponent.cpp | 4 +- 8 files changed, 76 insertions(+), 111 deletions(-) diff --git a/Code/CryEngine/CryCommon/LyShine/ISprite.h b/Code/CryEngine/CryCommon/LyShine/ISprite.h index d2e9a6e039..b9adda6901 100644 --- a/Code/CryEngine/CryCommon/LyShine/ISprite.h +++ b/Code/CryEngine/CryCommon/LyShine/ISprite.h @@ -16,9 +16,6 @@ #include #include -// forward declarations -class ITexture; - //////////////////////////////////////////////////////////////////////////////////////////////////// //! A sprite is a texture with extra information about how it behaves for 2D drawing //! Currently a sprite exists on disk as a side car file next to the texture file. @@ -80,9 +77,6 @@ public: // member functions //! Set the borders of a given cell within the sprite-sheet. virtual void SetCellBorders(int cellIndex, Borders borders) = 0; - //! Get the texture for this sprite - virtual ITexture* GetTexture() = 0; - //! Serialize this object for save/load virtual void Serialize(TSerialize ser) = 0; diff --git a/Gems/LyShine/Code/Source/Sprite.cpp b/Gems/LyShine/Code/Source/Sprite.cpp index 26e4056a41..7abbba4ea2 100644 --- a/Gems/LyShine/Code/Source/Sprite.cpp +++ b/Gems/LyShine/Code/Source/Sprite.cpp @@ -11,7 +11,6 @@ */ #include "LyShine_precompiled.h" #include "Sprite.h" -#include #include #include #include @@ -193,8 +192,7 @@ AZStd::string CSprite::s_emptyString; //////////////////////////////////////////////////////////////////////////////////////////////////// CSprite::CSprite() - : m_texture(nullptr) - , m_numSpriteSheetCellTags(0) + : m_numSpriteSheetCellTags(0) , m_atlas(nullptr) { AddRef(); @@ -204,8 +202,6 @@ CSprite::CSprite() //////////////////////////////////////////////////////////////////////////////////////////////////// CSprite::~CSprite() { - ReleaseTexture(m_texture); - s_loadedSprites->erase(m_pathname); TextureAtlasNamespace::TextureAtlasNotificationBus::Handler::BusDisconnect(); } @@ -250,26 +246,17 @@ void CSprite::SetCellBorders(int cellIndex, Borders borders) } //////////////////////////////////////////////////////////////////////////////////////////////////// -ITexture* CSprite::GetTexture() +AZ::Data::Instance CSprite::GetImage() { // Prioritize usage of an atlas +#ifdef LYSHINE_ATOM_TODO // texture atlas conversion to use Atom if (m_atlas) { return m_atlas->GetTexture(); } +#endif - if (!m_texture && !m_pathname.empty()) - { - // the render target texture may not have existed when the sprite was created - m_texture = gEnv->pRenderer->EF_GetTextureByName(m_pathname.c_str()); - if (m_texture) - { - // increase the reference count to this texture so it doesn't get removed while - // we are using it - m_texture->AddRef(); - } - } - return m_texture; + return m_image; } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -377,31 +364,21 @@ bool CSprite::AreCellBordersZeroWidth(int cellIndex) const //////////////////////////////////////////////////////////////////////////////////////////////////// AZ::Vector2 CSprite::GetSize() { -#ifdef LYSHINE_ATOM_TODO // Convert texture atlases to use Atom - ITexture* texture = GetTexture(); - if (texture) + AZ::Data::Instance image = GetImage(); + if (image) { if (m_atlas) { return AZ::Vector2(static_cast(m_atlasCoordinates.GetWidth()), static_cast(m_atlasCoordinates.GetHeight())); } - return AZ::Vector2(static_cast(texture->GetWidth()), static_cast(texture->GetHeight())); - } - else - { - return AZ::Vector2(0.0f, 0.0f); - } -#else - if (m_image) - { - AZ::RHI::Size size = m_image->GetRHIImage()->GetDescriptor().m_size; + + AZ::RHI::Size size = image->GetRHIImage()->GetDescriptor().m_size; return AZ::Vector2(size.m_width, size.m_height); } else { return AZ::Vector2(0.0f, 0.0f); } -#endif } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -734,6 +711,7 @@ CSprite* CSprite::CreateSprite(const string& renderTargetName) // create Sprite object CSprite* sprite = new CSprite; +#ifdef LYSHINE_ATOM_TODO // render target converstion to use ATom // the render target texture may not exist yet in which case we will need to load it later sprite->m_texture = gEnv->pRenderer->EF_GetTextureByName(renderTargetName.c_str()); if (sprite->m_texture) @@ -742,6 +720,7 @@ CSprite* CSprite::CreateSprite(const string& renderTargetName) // while we are using it sprite->m_texture->AddRef(); } +#endif sprite->m_pathname = renderTargetName; sprite->m_texturePathname.clear(); @@ -833,6 +812,7 @@ bool CSprite::FixUpSourceImagePathFromUserDefinedPath(const AZStd::string& userD return false; } +//////////////////////////////////////////////////////////////////////////////////////////////////// AZStd::string CSprite::GetImageSourcePathFromProductPath(const AZStd::string& productPathname) { AZStd::string sourcePathname(productPathname); @@ -843,46 +823,6 @@ AZStd::string CSprite::GetImageSourcePathFromProductPath(const AZStd::string& pr return sourcePathname; } -//////////////////////////////////////////////////////////////////////////////////////////////////// -bool CSprite::LoadTexture(const string& texturePathname, const string& pathname, ITexture*& texture) -{ - uint32 loadTextureFlags = (FT_USAGE_ALLOWREADSRGB | FT_DONT_STREAM); - texture = gEnv->pRenderer->EF_LoadTexture(texturePathname.c_str(), loadTextureFlags); - - if (!texture || !texture->IsTextureLoaded()) - { - gEnv->pSystem->Warning( - VALIDATOR_MODULE_SHINE, - VALIDATOR_WARNING, - VALIDATOR_FLAG_FILE | VALIDATOR_FLAG_TEXTURE, - texturePathname.c_str(), - "No texture file found for sprite: %s, no sprite will be used. " - "NOTE: File must be in current project or a gem.", - pathname.c_str()); - texture = nullptr; - return false; - } - texture->SetFilter(FILTER_LINEAR); - return true; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -void CSprite::ReleaseTexture(ITexture*& texture) -{ - if (texture) - { - // In order to avoid the texture being deleted while there are still commands on the render - // thread command queue that use it, we queue a command to delete the texture onto the - // command queue. - auto pInfo = AZStd::make_unique(); - pInfo->eClassName = eRCN_Texture; - pInfo->pResource = texture; - gEnv->pRenderer->ReleaseResourceAsync(AZStd::move(pInfo)); - texture = nullptr; - } -} - //////////////////////////////////////////////////////////////////////////////////////////////////// bool CSprite::LoadImage(const AZStd::string& nameTex, AZ::Data::Instance& image) { diff --git a/Gems/LyShine/Code/Source/Sprite.h b/Gems/LyShine/Code/Source/Sprite.h index b3037bf242..026646013e 100644 --- a/Gems/LyShine/Code/Source/Sprite.h +++ b/Gems/LyShine/Code/Source/Sprite.h @@ -41,7 +41,6 @@ public: // member functions Borders GetBorders() const override; void SetBorders(Borders borders) override; void SetCellBorders(int cellIndex, Borders borders) override; - ITexture* GetTexture() override; void Serialize(TSerialize ser) override; bool SaveToXml(const string& pathname) override; bool AreBordersZeroWidth() const override; @@ -71,7 +70,7 @@ public: // member functions // ~TextureAtlasNotifications - AZ::Data::Instance GetImage() { return m_image; } + AZ::Data::Instance GetImage(); public: // static member functions @@ -93,9 +92,6 @@ public: // static member functions static AZStd::string GetImageSourcePathFromProductPath(const AZStd::string& productPathname); private: - static bool LoadTexture(const string& texturePathname, const string& pathname, ITexture*& texture); - static void ReleaseTexture(ITexture*& texture); - static bool LoadImage(const AZStd::string& nameTex, AZ::Data::Instance& image); static void ReleaseImage(AZ::Data::Instance& image); @@ -120,7 +116,6 @@ private: // data string m_pathname; string m_texturePathname; Borders m_borders; - ITexture* m_texture; AZ::Data::Instance m_image; int m_numSpriteSheetCellTags; //!< Number of Cell child-tags in sprite XML; unfortunately needed to help with serialization. diff --git a/Gems/LyShine/Code/Source/UiImageComponent.cpp b/Gems/LyShine/Code/Source/UiImageComponent.cpp index c2294b8a93..9cf923a460 100644 --- a/Gems/LyShine/Code/Source/UiImageComponent.cpp +++ b/Gems/LyShine/Code/Source/UiImageComponent.cpp @@ -34,9 +34,8 @@ #include #include "UiSerialize.h" -#include "Sprite.h" #include "UiLayoutHelpers.h" - +#include "Sprite.h" #include "RenderGraph.h" namespace @@ -281,6 +280,20 @@ namespace 14, 15, 21, 21, 20, 14, // center quad }; + AZ::Data::Instance GetSpriteImage(ISprite* sprite) + { + AZ::Data::Instance image; + if (sprite) + { + CSprite* cSprite = dynamic_cast(sprite); // LYSHINE_ATOM_TODO - find a different solution from downcasting + if (cSprite) + { + image = cSprite->GetImage(); + } + } + + return image; + } } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -471,20 +484,12 @@ void UiImageComponent::Render(LyShine::IRenderGraph* renderGraph) renderGraph->AddPrimitive(&m_cachedPrimitive, texture, isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, m_blendMode); #else - AZ::Data::Instance image; - if (sprite) - { - CSprite* cSprite = static_cast(sprite); // LYSHINE_ATOM_TODO - find a different solution from downcasting - if (cSprite) - { - image = cSprite->GetImage(); - } - } + AZ::Data::Instance image = GetSpriteImage(sprite); bool isClampTextureMode = m_imageType == ImageType::Tiled ? false : true; bool isTextureSRGB = IsSpriteTypeRenderTarget() && m_isRenderTargetSRGB; bool isTexturePremultipliedAlpha = false; // we are not rendering from a render target with alpha in it - LyShine::RenderGraph* lyRenderGraph = static_cast(renderGraph); // LYSHINE_ATOM_TODO - find a different solution from downcasting + LyShine::RenderGraph* lyRenderGraph = dynamic_cast(renderGraph); // LYSHINE_ATOM_TODO - find a different solution from downcasting if (lyRenderGraph) { lyRenderGraph->AddPrimitiveAtom(&m_cachedPrimitive, image, isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, m_blendMode); @@ -880,8 +885,7 @@ float UiImageComponent::GetTargetWidth(float /*maxWidth*/) { float targetWidth = 0.0f; - ITexture* texture = (m_sprite) ? m_sprite->GetTexture() : nullptr; - if (texture) + if (m_sprite) { switch (m_imageType) { @@ -915,8 +919,7 @@ float UiImageComponent::GetTargetHeight(float /*maxHeight*/) { float targetHeight = 0.0f; - ITexture* texture = (m_sprite) ? m_sprite->GetTexture() : nullptr; - if (texture) + if (m_sprite) { switch (m_imageType) { @@ -2363,7 +2366,8 @@ void UiImageComponent::SnapOffsetsToFixedImage() } // if the image has no texture it will not use Fixed rendering so do nothing - if (!m_sprite || !m_sprite->GetTexture()) + AZ::Data::Instance image = GetSpriteImage(m_sprite); + if (!image) { return; } diff --git a/Gems/LyShine/Code/Source/UiImageSequenceComponent.cpp b/Gems/LyShine/Code/Source/UiImageSequenceComponent.cpp index e6cbef8386..df77a003ae 100644 --- a/Gems/LyShine/Code/Source/UiImageSequenceComponent.cpp +++ b/Gems/LyShine/Code/Source/UiImageSequenceComponent.cpp @@ -12,6 +12,9 @@ #include "LyShine_precompiled.h" #include "UiImageSequenceComponent.h" +#include "Sprite.h" +#include "RenderGraph.h" + #include #include #include @@ -100,7 +103,7 @@ void UiImageSequenceComponent::Render(LyShine::IRenderGraph* renderGraph) return; } - ISprite* sprite = m_spriteList[m_sequenceIndex]; + CSprite* sprite = dynamic_cast(m_spriteList[m_sequenceIndex]); // get fade value (tracked by UiRenderer) and compute the desired alpha for the image float fade = renderGraph->GetAlphaFade(); @@ -158,15 +161,23 @@ void UiImageSequenceComponent::Render(LyShine::IRenderGraph* renderGraph) } } - ITexture* texture = (sprite) ? sprite->GetTexture() : nullptr; + AZ::Data::Instance image; + if (sprite) + { + image = sprite->GetImage(); + } bool isClampTextureMode = false; bool isTextureSRGB = false; bool isTexturePremultipliedAlpha = false; LyShine::BlendMode blendMode = LyShine::BlendMode::Normal; // Add the quad to the render graph - renderGraph->AddPrimitive(&m_cachedPrimitive, texture, - isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, blendMode); + LyShine::RenderGraph* lyRenderGraph = dynamic_cast(renderGraph); + if (lyRenderGraph) + { + lyRenderGraph->AddPrimitiveAtom(&m_cachedPrimitive, image, + isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, blendMode); + } } } diff --git a/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp b/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp index e54f61fbfa..3c9a871847 100644 --- a/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp +++ b/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp @@ -13,6 +13,8 @@ #include "UiParticleEmitterComponent.h" #include "EditorPropertyTypes.h" +#include "Sprite.h" +#include "RenderGraph.h" #include #include @@ -21,7 +23,6 @@ #include #include -#include #include #include @@ -764,6 +765,12 @@ void UiParticleEmitterComponent::InGamePostActivate() //////////////////////////////////////////////////////////////////////////////////////////////////// void UiParticleEmitterComponent::Render(LyShine::IRenderGraph* renderGraph) { + AZ::u32 particlesToRender = AZ::GetMin(m_particleContainer.size(), m_particleBufferSize); + if (particlesToRender == 0) + { + return; + } + AZ::Matrix4x4 transform = AZ::Matrix4x4::CreateIdentity(); AZ::Vector2 emitterOffset = AZ::Vector2::CreateZero(); @@ -781,9 +788,15 @@ void UiParticleEmitterComponent::Render(LyShine::IRenderGraph* renderGraph) EBUS_EVENT_ID_RESULT(transform, canvasID, UiCanvasBus, GetCanvasToViewportMatrix); } - AZ::u32 particlesToRender = AZ::GetMin(m_particleContainer.size(), m_particleBufferSize); - - ITexture* texture = (m_sprite) ? m_sprite->GetTexture() : nullptr; + AZ::Data::Instance image; + if (m_sprite) + { + CSprite* sprite = dynamic_cast(m_sprite); + if (sprite) + { + image = sprite->GetImage(); + } + } bool isClampTextureMode = true; bool isTextureSRGB = false; @@ -836,7 +849,11 @@ void UiParticleEmitterComponent::Render(LyShine::IRenderGraph* renderGraph) m_cachedPrimitive.m_numVertices = totalVerticesInserted; m_cachedPrimitive.m_numIndices = totalParticlesInserted * indicesPerParticle; - renderGraph->AddPrimitive(&m_cachedPrimitive, texture, isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, m_blendMode); + LyShine::RenderGraph* lyRenderGraph = dynamic_cast(renderGraph); + if (lyRenderGraph) + { + lyRenderGraph->AddPrimitiveAtom(&m_cachedPrimitive, image, isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, m_blendMode); + } } //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/LyShine/Code/Tests/SpriteTest.cpp b/Gems/LyShine/Code/Tests/SpriteTest.cpp index 1d45a6113c..29ef1eb7f2 100644 --- a/Gems/LyShine/Code/Tests/SpriteTest.cpp +++ b/Gems/LyShine/Code/Tests/SpriteTest.cpp @@ -68,6 +68,7 @@ namespace UnitTest AZStd::unique_ptr m_data; }; +#ifdef LYSHINE_ATOM_TODO // [LYN-3359] - render target support using Atom TEST_F(LyShineSpriteTest, Sprite_CanAcquireRenderTarget) { // initialize to create the static sprite cache @@ -130,6 +131,7 @@ namespace UnitTest CSprite::Shutdown(); delete mockTexture; } +#endif } //namespace UnitTest AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Gems/LyShineExamples/Code/Source/UiCustomImageComponent.cpp b/Gems/LyShineExamples/Code/Source/UiCustomImageComponent.cpp index 1bd2bd10be..b2055f2a0c 100644 --- a/Gems/LyShineExamples/Code/Source/UiCustomImageComponent.cpp +++ b/Gems/LyShineExamples/Code/Source/UiCustomImageComponent.cpp @@ -78,8 +78,9 @@ namespace LyShineExamples } //////////////////////////////////////////////////////////////////////////////////////////////////// - void UiCustomImageComponent::Render(LyShine::IRenderGraph* renderGraph) + void UiCustomImageComponent::Render([[maybe_unused]] LyShine::IRenderGraph* renderGraph) { +#ifdef LYSHINE_ATOM_TODO // [LYN-3635] convert to use Atom // get fade value (tracked by UiRenderer) and compute the desired alpha for the image float fade = renderGraph->GetAlphaFade(); float desiredAlpha = m_overrideAlpha * fade; @@ -126,6 +127,7 @@ namespace LyShineExamples bool isTexturePremultipliedAlpha = false; // we are not rendering from a render target with alpha in it LyShine::BlendMode blendMode = LyShine::BlendMode::Normal; renderGraph->AddPrimitive(&m_cachedPrimitive, texture, m_clamp, isTextureSRGB, isTexturePremultipliedAlpha, blendMode); +#endif } //////////////////////////////////////////////////////////////////////////////////////////////////// From 2558801a247498bb0ed05b7ebaf26d9ccd98a7f0 Mon Sep 17 00:00:00 2001 From: jjjoness <82226755+jjjoness@users.noreply.github.com> Date: Wed, 12 May 2021 08:58:16 +0100 Subject: [PATCH 057/231] Commit before merging main --- Code/Sandbox/Editor/MainWindow.cpp | 4 ++-- Code/Sandbox/Editor/ToolbarManager.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index 5abb780bac..5538df1424 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -1064,8 +1064,8 @@ void MainWindow::InitActions() .SetApplyHoverEffect() .SetCheckable(true) .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdatePlayGame); - am->AddAction(ID_TOOLBAR_WIDGET_PLAYCONSOLE_LABEL, tr("Play Console")) - .SetText(tr("Play Console")); + am->AddAction(ID_TOOLBAR_WIDGET_PLAYCONSOLE_LABEL, tr("Play Controls")) + .SetText(tr("Play Controls")); am->AddAction(ID_SWITCH_PHYSICS, tr("Simulate")) .SetShortcut(tr("Ctrl+P")) .SetToolTip(tr("Simulate (Ctrl+P)")) diff --git a/Code/Sandbox/Editor/ToolbarManager.cpp b/Code/Sandbox/Editor/ToolbarManager.cpp index bbb3ef6790..76fbe92fa8 100644 --- a/Code/Sandbox/Editor/ToolbarManager.cpp +++ b/Code/Sandbox/Editor/ToolbarManager.cpp @@ -613,7 +613,7 @@ AmazonToolbar ToolbarManager::GetObjectToolbar() const AmazonToolbar ToolbarManager::GetPlayConsoleToolbar() const { - AmazonToolbar t = AmazonToolbar("PlayConsole", QObject::tr("Play Console")); + AmazonToolbar t = AmazonToolbar("PlayConsole", QObject::tr("Play Controls")); t.SetMainToolbar(true); t.AddAction(ID_TOOLBAR_WIDGET_SPACER_RIGHT, ORIGINAL_TOOLBAR_VERSION); From 552ebea1350898594de79471e6b683bf51bfbbf1 Mon Sep 17 00:00:00 2001 From: jjjoness <82226755+jjjoness@users.noreply.github.com> Date: Wed, 12 May 2021 11:40:36 +0100 Subject: [PATCH 058/231] Added Simulate button --- .../img/UI20/toolbar/Simulate_Physics.svg | 24 +++++++++++++++++++ .../AzQtComponents/Components/resources.qrc | 1 + Code/Sandbox/Editor/MainWindow.cpp | 3 +++ Code/Sandbox/Editor/ToolbarManager.cpp | 2 ++ 4 files changed, 30 insertions(+) create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Simulate_Physics.svg diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Simulate_Physics.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Simulate_Physics.svg new file mode 100644 index 0000000000..0839be31b1 --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Simulate_Physics.svg @@ -0,0 +1,24 @@ + + + Icon / Toolbar / Play Console / Simulate Physics + + + + + + + + + + + + + + + + + + + + + \ 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 1e8ddb43e0..b995874a41 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc @@ -372,6 +372,7 @@ img/UI20/toolbar/Select.svg img/UI20/toolbar/select_object.svg img/UI20/toolbar/Select_terrain.svg + img/UI20/toolbar/Simulate_Physics.svg img/UI20/toolbar/Simulate_Physics_on_selected_objects.svg img/UI20/toolbar/Terrain.svg img/UI20/toolbar/Terrain_Texture.svg diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index c02b64f8b7..b6aece28e3 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -1023,10 +1023,13 @@ void MainWindow::InitActions() am->AddAction(ID_TOOLBAR_WIDGET_PLAYCONSOLE_LABEL, tr("Play Controls")) .SetText(tr("Play Controls")); am->AddAction(ID_SWITCH_PHYSICS, tr("Simulate")) + .SetIcon(QIcon(":/stylesheet/img/UI20/toolbar/Simulate_Physics.svg")) .SetShortcut(tr("Ctrl+P")) .SetToolTip(tr("Simulate (Ctrl+P)")) .SetCheckable(true) .SetStatusTip(tr("Enable processing of Physics and AI.")) + .SetApplyHoverEffect() + .SetCheckable(true) .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnSwitchPhysicsUpdate); am->AddAction(ID_GAME_SYNCPLAYER, tr("Move Player and Camera Separately")).SetCheckable(true) .SetStatusTip(tr("Move Player and Camera Separately")) diff --git a/Code/Sandbox/Editor/ToolbarManager.cpp b/Code/Sandbox/Editor/ToolbarManager.cpp index 7d7ac5112b..391eabae33 100644 --- a/Code/Sandbox/Editor/ToolbarManager.cpp +++ b/Code/Sandbox/Editor/ToolbarManager.cpp @@ -616,6 +616,8 @@ AmazonToolbar ToolbarManager::GetPlayConsoleToolbar() const t.AddAction(ID_TOOLBAR_SEPARATOR, ORIGINAL_TOOLBAR_VERSION); t.AddAction(ID_TOOLBAR_WIDGET_PLAYCONSOLE_LABEL, ORIGINAL_TOOLBAR_VERSION); t.AddAction(ID_VIEW_SWITCHTOGAME, TOOLBARS_WITH_PLAY_GAME); + t.AddAction(ID_TOOLBAR_SEPARATOR, ORIGINAL_TOOLBAR_VERSION); + t.AddAction(ID_SWITCH_PHYSICS, TOOLBARS_WITH_PLAY_GAME); return t; } From f5e91c6e4284f00e64db5cc4ba4e0678be111b1c Mon Sep 17 00:00:00 2001 From: antonmic Date: Wed, 12 May 2021 10:39:18 -0700 Subject: [PATCH 059/231] Added low end shaders in StandardPBR_ShaderEnable.lua --- .../Assets/Materials/Types/StandardPBR_ShaderEnable.lua | 7 +++++++ 1 file changed, 7 insertions(+) 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 7c3d989c35..2733713122 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ShaderEnable.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ShaderEnable.lua @@ -29,26 +29,33 @@ 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 shadowMapWitPS = context:GetShaderByTag("Shadowmap_WithPS") local forwardPass = context:GetShaderByTag("ForwardPass") + local lowEndForward = context:GetShaderByTag("LowEndForward") if parallaxEnabled and parallaxPdoEnabled then depthPass:SetEnabled(false) shadowMap:SetEnabled(false) forwardPassEDS:SetEnabled(false) + lowEndForwardEDS:SetEnabled(false) depthPassWithPS:SetEnabled(true) shadowMapWitPS:SetEnabled(true) forwardPass:SetEnabled(true) + lowEndForward:SetEnabled(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) shadowMapWitPS:SetEnabled(opacityMode == OpacityMode_Cutout) forwardPass:SetEnabled(opacityMode == OpacityMode_Cutout) + lowEndForward:SetEnabled(opacityMode == OpacityMode_Cutout) end context:GetShaderByTag("DepthPassTransparentMin"):SetEnabled((opacityMode == OpacityMode_Blended) or (opacityMode == OpacityMode_TintedTransparent)) From 92b7099d78953eef8552633201b98d8f07597529 Mon Sep 17 00:00:00 2001 From: antonmic Date: Wed, 12 May 2021 11:10:13 -0700 Subject: [PATCH 060/231] Some clean up --- .../Common/Assets/Materials/Types/StandardPBR.materialtype | 7 ------- .../Assets/Materials/Types/StandardPBR_ForwardPass.azsl | 4 ++-- .../Assets/ShaderLib/Atom/Features/PBR/Lights/Ibl.azsli | 3 +++ .../ShaderLib/Atom/Features/ShaderQualityOptions.azsli | 4 +--- Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl | 6 ++---- 5 files changed, 8 insertions(+), 16 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index 47d8a9d9d5..a9a3e9e09b 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -77,13 +77,6 @@ ], "properties": { "general": [ - { - "id": "useLowEndShader", - "displayName": "Use Low End", - "description": "Whether to use the low end shader.", - "type": "Bool", - "defaultValue": false - }, { "id": "applySpecularAA", "displayName": "Apply Specular AA", 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 1e6fafda9b..7ae5934d4f 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -321,7 +321,7 @@ ForwardPassOutputWithDepth StandardPbr_ForwardPassPS(VSOutput IN, bool isFrontFa #ifdef UNIFIED_FORWARD_OUTPUT OUT.m_color.rgb = lightingOutput.m_diffuseColor.rgb + lightingOutput.m_specularColor.rgb; - OUT.m_color.a = 1.0f; + OUT.m_color.a = lightingOutput.m_diffuseColor.a; OUT.m_depth = depth; #else OUT.m_diffuseColor = lightingOutput.m_diffuseColor; @@ -344,7 +344,7 @@ ForwardPassOutput StandardPbr_ForwardPassPS_EDS(VSOutput IN, bool isFrontFace : #ifdef UNIFIED_FORWARD_OUTPUT OUT.m_color.rgb = lightingOutput.m_diffuseColor.rgb + lightingOutput.m_specularColor.rgb; - OUT.m_color.a = 1.0f; + OUT.m_color.a = lightingOutput.m_diffuseColor.a; #else OUT.m_diffuseColor = lightingOutput.m_diffuseColor; OUT.m_specularColor = lightingOutput.m_specularColor; diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/Ibl.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/Ibl.azsli index 721c48835d..3e3544fe9e 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/Ibl.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/Ibl.azsli @@ -12,6 +12,9 @@ #pragma once +// --- Static Options Available --- +// FORCE_IBL_IN_FORWARD_PASS - forces IBL lighting to be run in the forward pass, used in pipelines that don't have a reflection pass + #include #include diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli index d6fb259548..6e89269f8d 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ShaderQualityOptions.azsli @@ -12,9 +12,7 @@ #pragma once -// These are a list of quality options to specify as macros (either in azsl or in shader files) -// -// QUALITY_LOW_END +// This file translates quality option macros like QUALITY_LOW_END to their relevant settings #ifdef QUALITY_LOW_END diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl index 4b3e9536b7..1bebb2ec47 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/SkyBox/SkyBox.azsl @@ -10,10 +10,8 @@ * */ -// Static Options: -// -// SKYBOX_TWO_OUTPUTS - Allows the skybox to render to two rendertargets instead of one - +// --- Static Options Available --- +// SKYBOX_TWO_OUTPUTS - Skybox renders to two rendertargets instead of one (SkyBox_TwoOutputs.pass writes to specular and reflection targets) #include #include From b52388f5ebfb5af09505a99fe1e416ae12907dd0 Mon Sep 17 00:00:00 2001 From: antonmic Date: Wed, 12 May 2021 11:11:45 -0700 Subject: [PATCH 061/231] Remove unused file --- .../PBR/LowEndForwardPassOutput.azsli | 32 ------------------- 1 file changed, 32 deletions(-) delete mode 100644 Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/LowEndForwardPassOutput.azsli diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/LowEndForwardPassOutput.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/LowEndForwardPassOutput.azsli deleted file mode 100644 index acc215f1c9..0000000000 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/LowEndForwardPassOutput.azsli +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -struct ForwardPassOutput -{ - float4 m_diffuseColor : SV_Target0; //!< RGB = Diffuse Lighting, A = Blend Alpha (for blended surfaces) OR A = special encoding of surfaceScatteringFactor, m_subsurfaceScatteringQuality, o_enableSubsurfaceScattering - float4 m_specularColor : SV_Target1; //!< RGB = Specular Lighting, A = Unused - float4 m_albedo : SV_Target2; //!< RGB = Surface albedo pre-multiplied by other factors that will be multiplied later by diffuse GI, A = specularOcclusion - float4 m_specularF0 : SV_Target3; //!< RGB = Specular F0, A = roughness - float4 m_normal : SV_Target4; //!< RGB10 = EncodeNormalSignedOctahedron(worldNormal), A2 = multiScatterCompensationEnabled -}; - -struct ForwardPassOutputWithDepth -{ - // See above for descriptions of special encodings - - float4 m_diffuseColor : SV_Target0; - float4 m_specularColor : SV_Target1; - float4 m_albedo : SV_Target2; - float4 m_specularF0 : SV_Target3; - float4 m_normal : SV_Target4; - float m_depth : SV_Depth; -}; From 931a127b7b8b42f92f7a391c37cb4ac5c77bc69c Mon Sep 17 00:00:00 2001 From: guthadam Date: Wed, 12 May 2021 13:47:47 -0500 Subject: [PATCH 062/231] ATOM-15223 updating material assignment ID to be portable to other models The bug was reported that copy and paste did not work with the material component. Copy and paste to take the worked fine. All of the material assignments/overrides get mapped using the LOD and asset ID of materials provided with the model. The asset IDs of materials exported by atom builders, using the scene API, are the combination of the same UUID as the model asset ID and the unique sub ID that is now hashed from the material name provided by the DCC tool. If we map material assignments using the entire asset ID that was generated in the model builder then the mapping will only work with that specific model. This change updates the material assignment ID equality operators and hash function to only use the sub ID portion of the asset ID. As long as the sub IDs are generated consistently the material assignment mappings will be portable to models with the same material names. Also moved material assignment structures to atom common features static library so this was to be moved to cpp files --- .../Feature/Material/MaterialAssignment.h | 125 ++++-------------- .../Feature/Material/MaterialAssignmentId.h | 101 +++++--------- .../Source/Material/MaterialAssignment.cpp | 98 +++++++++++++- .../Source/Material/MaterialAssignmentId.cpp | 67 +++++++++- .../Code/atom_feature_common_files.cmake | 4 - ...m_feature_common_staticlibrary_files.cmake | 4 + .../EMotionFXAtom/Code/CMakeLists.txt | 1 + 7 files changed, 232 insertions(+), 168 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignment.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignment.h index 089f4e8c62..58fb2e0f8a 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignment.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignment.h @@ -1,21 +1,21 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 AZ { @@ -31,39 +31,19 @@ namespace AZ MaterialAssignment() = default; - MaterialAssignment(const AZ::Data::AssetId& materialAssetId) - : m_materialInstance() - { - m_materialAsset.Create(materialAssetId); - } + MaterialAssignment(const AZ::Data::AssetId& materialAssetId); - MaterialAssignment(const Data::Asset& asset) - : m_materialAsset(asset) - , m_materialInstance() - { - } + MaterialAssignment(const Data::Asset& asset); - MaterialAssignment(const Data::Asset& asset, const Data::Instance& instance) - : m_materialAsset(asset) - , m_materialInstance(instance) - { - } + MaterialAssignment(const Data::Asset& asset, const Data::Instance& instance); - void RebuildInstance() - { - if (m_materialAsset.IsReady()) - { - m_materialInstance = m_propertyOverrides.empty() ? RPI::Material::FindOrCreate(m_materialAsset) : RPI::Material::Create(m_materialAsset); - AZ_Error("MaterialAssignment", m_materialInstance, "Material instance not initialized"); - } - } + //! Recreates the material instance from the asset if it has been loaded. + //! If amy property overrides have been specified then a unique instance will be created. + //! Otherwise an attempt will be made to find or create a shared instance. + void RebuildInstance(); - AZStd::string ToString() const - { - AZStd::string assetPathString; - AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetPathString, &AZ::Data::AssetCatalogRequests::GetAssetPathById, m_materialAsset.GetId()); - return assetPathString; - } + //! Returns a string composed of the asset path. + AZStd::string ToString() const; Data::Asset m_materialAsset; Data::Instance m_materialInstance; @@ -77,64 +57,15 @@ namespace AZ static const MaterialAssignmentMap DefaultMaterialAssignmentMap; //! Utility function for retrieving a material entry from a MaterialAssignmentMap - AZ_INLINE const MaterialAssignment& GetMaterialAssignmentFromMap(const MaterialAssignmentMap& materials, const MaterialAssignmentId& id) - { - const auto& materialItr = materials.find(id); - return materialItr != materials.end() ? materialItr->second : DefaultMaterialAssignment; - } + const MaterialAssignment& GetMaterialAssignmentFromMap(const MaterialAssignmentMap& materials, const MaterialAssignmentId& id); - //! Utility function for retrieving a material entry from a MaterialAssignmentMap, falling back to defaults for a particular asset or the entire model - AZ_INLINE const MaterialAssignment& GetMaterialAssignmentFromMapWithFallback(const MaterialAssignmentMap& materials, const MaterialAssignmentId& id) - { - const MaterialAssignment& lodAssignment = GetMaterialAssignmentFromMap(materials, id); - if (lodAssignment.m_materialInstance.get()) - { - return lodAssignment; - } - - const MaterialAssignment& assetAssignment = GetMaterialAssignmentFromMap(materials, MaterialAssignmentId::CreateFromAssetOnly(id.m_materialAssetId)); - if (assetAssignment.m_materialInstance.get()) - { - return assetAssignment; - } - - const MaterialAssignment& defaultAssignment = GetMaterialAssignmentFromMap(materials, DefaultMaterialAssignmentId); - if (defaultAssignment.m_materialInstance.get()) - { - return defaultAssignment; - } - - return DefaultMaterialAssignment; - } + //! Utility function for retrieving a material entry from a MaterialAssignmentMap, falling back to defaults for a particular asset + //! or the entire model + const MaterialAssignment& GetMaterialAssignmentFromMapWithFallback( + const MaterialAssignmentMap& materials, const MaterialAssignmentId& id); //! Utility function for generating a set of available material assignments in a model - AZ_INLINE MaterialAssignmentMap GetMaterialAssignmentsFromModel(Data::Instance model) - { - MaterialAssignmentMap materials; - materials[DefaultMaterialAssignmentId] = MaterialAssignment(); - - if (model) - { - size_t lodIndex = 0; - for (const Data::Instance& lod : model->GetLods()) - { - for (const AZ::RPI::ModelLod::Mesh& mesh : lod->GetMeshes()) - { - if (mesh.m_material) - { - const MaterialAssignmentId generalId = MaterialAssignmentId::CreateFromAssetOnly(mesh.m_material->GetAssetId()); - materials[generalId] = MaterialAssignment(mesh.m_material->GetAsset(), mesh.m_material); - - const MaterialAssignmentId specificId = MaterialAssignmentId::CreateFromLodAndAsset(lodIndex, mesh.m_material->GetAssetId()); - materials[specificId] = MaterialAssignment(mesh.m_material->GetAsset(), mesh.m_material); - } - } - ++lodIndex; - } - } - - return materials; - } + MaterialAssignmentMap GetMaterialAssignmentsFromModel(Data::Instance model); } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h index 267e65743a..80de6d8041 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h @@ -1,20 +1,20 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or 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 @@ -26,6 +26,9 @@ namespace AZ { using MaterialAssignmentLodIndex = AZ::u64; + //! MaterialAssignmentId is used to address available and overridable material slots on a model. + //! The LOD and one of the model's original material asset IDs are used as coordinates that identify + //! a specific material slot or a set of slots matching either. struct MaterialAssignmentId final { AZ_RTTI(AZ::Render::MaterialAssignmentId, "{EB603581-4654-4C17-B6DE-AE61E79EDA97}"); @@ -34,69 +37,37 @@ namespace AZ MaterialAssignmentId() = default; - MaterialAssignmentId(MaterialAssignmentLodIndex lodIndex, const AZ::Data::AssetId& materialAssetId) - : m_lodIndex(lodIndex) - , m_materialAssetId(materialAssetId) - { - } + MaterialAssignmentId(MaterialAssignmentLodIndex lodIndex, const AZ::Data::AssetId& materialAssetId); - static MaterialAssignmentId CreateDefault() - { - return MaterialAssignmentId(NonLodIndex, AZ::Data::AssetId()); - } + //! Create an ID that maps to all material slots, regardless of asset ID or LOD, effectively applying to an entire model. + static MaterialAssignmentId CreateDefault(); - static MaterialAssignmentId CreateFromAssetOnly(AZ::Data::AssetId materialAssetId) - { - return MaterialAssignmentId(NonLodIndex, materialAssetId); - } + //! Create an ID that maps to all material slots with a corresponding asset ID, regardless of LOD. + static MaterialAssignmentId CreateFromAssetOnly(AZ::Data::AssetId materialAssetId); - static MaterialAssignmentId CreateFromLodAndAsset(MaterialAssignmentLodIndex lodIndex, AZ::Data::AssetId materialAssetId) - { - return MaterialAssignmentId(lodIndex, materialAssetId); - } + //! Create an ID that maps to a specific material slot with a corresponding asset ID and LOD. + static MaterialAssignmentId CreateFromLodAndAsset(MaterialAssignmentLodIndex lodIndex, AZ::Data::AssetId materialAssetId); - bool IsDefault() const - { - return m_lodIndex == NonLodIndex && !m_materialAssetId.IsValid(); - } + //! Returns true if the asset ID and LOD are invalid + bool IsDefault() const; - bool IsAssetOnly() const - { - return m_lodIndex == NonLodIndex && m_materialAssetId.IsValid(); - } + //! Returns true if the asset ID is valid and LOD is invalid + bool IsAssetOnly() const; - bool IsLodAndAsset() const - { - return m_lodIndex != NonLodIndex && m_materialAssetId.IsValid(); - } + //! Returns true if the asset ID and LOD are both valid + bool IsLodAndAsset() const; + //! Creates a string composed of the asset path and LOD + AZStd::string ToString() const; - AZStd::string ToString() const - { - AZStd::string assetPathString; - AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetPathString, &AZ::Data::AssetCatalogRequests::GetAssetPathById, m_materialAssetId); - AZ::StringFunc::Path::StripPath(assetPathString); - AZ::StringFunc::Path::StripExtension(assetPathString); - return AZStd::string::format("%s:%llu", assetPathString.c_str(), m_lodIndex); - } + //! Creates a hash composed of the asset ID sub ID and LOD + size_t GetHash() const; - size_t GetHash() const - { - size_t seed = 0; - AZStd::hash_combine(seed, m_lodIndex); - AZStd::hash_combine(seed, m_materialAssetId); - return seed; - } + //! Returns true if both asset ID sub IDs and LODs match + bool operator==(const MaterialAssignmentId& rhs) const; - bool operator==(const MaterialAssignmentId& rhs) const - { - return m_lodIndex == rhs.m_lodIndex && m_materialAssetId == rhs.m_materialAssetId; - } - - bool operator!=(const MaterialAssignmentId& rhs) const - { - return m_lodIndex != rhs.m_lodIndex || m_materialAssetId != rhs.m_materialAssetId; - } + //! Returns true if both asset ID sub IDs and LODs do not match + bool operator!=(const MaterialAssignmentId& rhs) const; static constexpr MaterialAssignmentLodIndex NonLodIndex = -1; MaterialAssignmentLodIndex m_lodIndex = NonLodIndex; @@ -116,4 +87,4 @@ namespace AZStd return id.GetHash(); } }; -} //namespace AZStd +} // namespace AZStd diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp index f817e8324b..ffb5469aef 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp @@ -11,8 +11,8 @@ */ #include -#include #include +#include namespace AZ { @@ -67,5 +67,101 @@ namespace AZ } } + + MaterialAssignment::MaterialAssignment(const AZ::Data::AssetId& materialAssetId) + : m_materialInstance() + { + m_materialAsset.Create(materialAssetId); + } + + MaterialAssignment::MaterialAssignment(const Data::Asset& asset) + : m_materialAsset(asset) + , m_materialInstance() + { + } + + MaterialAssignment::MaterialAssignment(const Data::Asset& asset, const Data::Instance& instance) + : m_materialAsset(asset) + , m_materialInstance(instance) + { + } + + void MaterialAssignment::RebuildInstance() + { + if (m_materialAsset.IsReady()) + { + m_materialInstance = + m_propertyOverrides.empty() ? RPI::Material::FindOrCreate(m_materialAsset) : RPI::Material::Create(m_materialAsset); + AZ_Error("MaterialAssignment", m_materialInstance, "Material instance not initialized"); + } + } + + AZStd::string MaterialAssignment::ToString() const + { + AZStd::string assetPathString; + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetPathString, &AZ::Data::AssetCatalogRequests::GetAssetPathById, m_materialAsset.GetId()); + return assetPathString; + } + + const MaterialAssignment& GetMaterialAssignmentFromMap(const MaterialAssignmentMap& materials, const MaterialAssignmentId& id) + { + const auto& materialItr = materials.find(id); + return materialItr != materials.end() ? materialItr->second : DefaultMaterialAssignment; + } + + const MaterialAssignment& GetMaterialAssignmentFromMapWithFallback( + const MaterialAssignmentMap& materials, const MaterialAssignmentId& id) + { + const MaterialAssignment& lodAssignment = GetMaterialAssignmentFromMap(materials, id); + if (lodAssignment.m_materialInstance.get()) + { + return lodAssignment; + } + + const MaterialAssignment& assetAssignment = + GetMaterialAssignmentFromMap(materials, MaterialAssignmentId::CreateFromAssetOnly(id.m_materialAssetId)); + if (assetAssignment.m_materialInstance.get()) + { + return assetAssignment; + } + + const MaterialAssignment& defaultAssignment = GetMaterialAssignmentFromMap(materials, DefaultMaterialAssignmentId); + if (defaultAssignment.m_materialInstance.get()) + { + return defaultAssignment; + } + + return DefaultMaterialAssignment; + } + + MaterialAssignmentMap GetMaterialAssignmentsFromModel(Data::Instance model) + { + MaterialAssignmentMap materials; + materials[DefaultMaterialAssignmentId] = MaterialAssignment(); + + if (model) + { + size_t lodIndex = 0; + for (const Data::Instance& lod : model->GetLods()) + { + for (const AZ::RPI::ModelLod::Mesh& mesh : lod->GetMeshes()) + { + if (mesh.m_material) + { + const MaterialAssignmentId generalId = MaterialAssignmentId::CreateFromAssetOnly(mesh.m_material->GetAssetId()); + materials[generalId] = MaterialAssignment(mesh.m_material->GetAsset(), mesh.m_material); + + const MaterialAssignmentId specificId = + MaterialAssignmentId::CreateFromLodAndAsset(lodIndex, mesh.m_material->GetAssetId()); + materials[specificId] = MaterialAssignment(mesh.m_material->GetAsset(), mesh.m_material); + } + } + ++lodIndex; + } + } + + return materials; + } } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp index 4813136d2e..0fe89d49b8 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp @@ -11,8 +11,8 @@ */ #include -#include #include +#include namespace AZ { @@ -47,5 +47,70 @@ namespace AZ ; } } + + MaterialAssignmentId::MaterialAssignmentId(MaterialAssignmentLodIndex lodIndex, const AZ::Data::AssetId& materialAssetId) + : m_lodIndex(lodIndex) + , m_materialAssetId(materialAssetId) + { + } + + MaterialAssignmentId MaterialAssignmentId::CreateDefault() + { + return MaterialAssignmentId(NonLodIndex, AZ::Data::AssetId()); + } + + MaterialAssignmentId MaterialAssignmentId::CreateFromAssetOnly(AZ::Data::AssetId materialAssetId) + { + return MaterialAssignmentId(NonLodIndex, materialAssetId); + } + + MaterialAssignmentId MaterialAssignmentId::CreateFromLodAndAsset( + MaterialAssignmentLodIndex lodIndex, AZ::Data::AssetId materialAssetId) + { + return MaterialAssignmentId(lodIndex, materialAssetId); + } + + bool MaterialAssignmentId::IsDefault() const + { + return m_lodIndex == NonLodIndex && !m_materialAssetId.IsValid(); + } + + bool MaterialAssignmentId::IsAssetOnly() const + { + return m_lodIndex == NonLodIndex && m_materialAssetId.IsValid(); + } + + bool MaterialAssignmentId::IsLodAndAsset() const + { + return m_lodIndex != NonLodIndex && m_materialAssetId.IsValid(); + } + + AZStd::string MaterialAssignmentId::ToString() const + { + AZStd::string assetPathString; + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetPathString, &AZ::Data::AssetCatalogRequests::GetAssetPathById, m_materialAssetId); + AZ::StringFunc::Path::StripPath(assetPathString); + AZ::StringFunc::Path::StripExtension(assetPathString); + return AZStd::string::format("%s:%llu", assetPathString.c_str(), m_lodIndex); + } + + size_t MaterialAssignmentId::GetHash() const + { + size_t seed = 0; + AZStd::hash_combine(seed, m_lodIndex); + AZStd::hash_combine(seed, m_materialAssetId.m_subId); + return seed; + } + + bool MaterialAssignmentId::operator==(const MaterialAssignmentId& rhs) const + { + return m_lodIndex == rhs.m_lodIndex && m_materialAssetId.m_subId == rhs.m_materialAssetId.m_subId; + } + + bool MaterialAssignmentId::operator!=(const MaterialAssignmentId& rhs) const + { + return m_lodIndex != rhs.m_lodIndex || m_materialAssetId.m_subId != rhs.m_materialAssetId.m_subId; + } } // 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 47000d8a5c..8926b0c19f 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -27,8 +27,6 @@ set(FILES Include/Atom/Feature/ImGui/SystemBus.h Include/Atom/Feature/ImageBasedLights/ImageBasedLightFeatureProcessor.h Include/Atom/Feature/LookupTable/LookupTableAsset.h - Include/Atom/Feature/Material/MaterialAssignment.h - Include/Atom/Feature/Material/MaterialAssignmentId.h Include/Atom/Feature/Mesh/MeshFeatureProcessor.h Include/Atom/Feature/PostProcessing/PostProcessingConstants.h Include/Atom/Feature/PostProcessing/SMAAFeatureProcessorInterface.h @@ -155,8 +153,6 @@ set(FILES Source/LookupTable/LookupTableAsset.cpp Source/Material/ConvertEmissiveUnitFunctor.cpp Source/Material/ConvertEmissiveUnitFunctor.h - Source/Material/MaterialAssignment.cpp - Source/Material/MaterialAssignmentId.cpp Source/Material/ShaderEnableFunctor.cpp Source/Material/ShaderEnableFunctor.h Source/Material/SubsurfaceTransmissionParameterFunctor.cpp 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 d33e861c02..553f307409 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 @@ -10,8 +10,12 @@ # set(FILES + Include/Atom/Feature/Material/MaterialAssignment.h + Include/Atom/Feature/Material/MaterialAssignmentId.h Include/Atom/Feature/Utils/LightingPreset.h Include/Atom/Feature/Utils/ModelPreset.h + Source/Material/MaterialAssignment.cpp + Source/Material/MaterialAssignmentId.cpp Source/Utils/LightingPreset.cpp Source/Utils/ModelPreset.cpp ) diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/CMakeLists.txt b/Gems/AtomLyIntegration/EMotionFXAtom/Code/CMakeLists.txt index dc969d61d3..6492f4f13a 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/CMakeLists.txt @@ -25,6 +25,7 @@ ly_add_target( Gem::Atom_Utils.Static Gem::Atom_Feature_Common Gem::Atom_Feature_Common.Public + Gem::Atom_Feature_Common.Static Gem::Atom_RPI.Public Gem::Atom_RHI.Reflect Gem::AtomLyIntegration_CommonFeatures.Public From 059f69e5e639a006b3cefaaa64b7055770d5c93a Mon Sep 17 00:00:00 2001 From: greerdv Date: Wed, 12 May 2021 21:20:23 +0100 Subject: [PATCH 063/231] tidy up NonUniformScaleService compatibility --- .../Components/NonUniformScaleComponent.cpp | 23 ------------------- .../EditorNonUniformScaleComponent.cpp | 23 ------------------- .../Code/Source/DebugDrawObbComponent.cpp | 2 +- .../Integration/Components/ActorComponent.h | 1 + .../Components/SimpleMotionComponent.h | 1 + .../Components/GradientTransformComponent.cpp | 1 + .../Source/Shape/CapsuleShapeComponent.cpp | 1 + .../Source/Shape/CompoundShapeComponent.h | 1 + .../Source/Shape/CylinderShapeComponent.cpp | 1 + .../Code/Source/Shape/DiskShapeComponent.cpp | 1 + .../Shape/EditorCapsuleShapeComponent.cpp | 6 +++++ .../Shape/EditorCapsuleShapeComponent.h | 2 ++ .../Shape/EditorCompoundShapeComponent.cpp | 6 +++++ .../Shape/EditorCompoundShapeComponent.h | 2 ++ .../Shape/EditorCylinderShapeComponent.cpp | 6 +++++ .../Shape/EditorCylinderShapeComponent.h | 2 ++ .../Source/Shape/EditorDiskShapeComponent.cpp | 6 +++++ .../Source/Shape/EditorDiskShapeComponent.h | 1 + .../Shape/EditorSphereShapeComponent.cpp | 6 +++++ .../Source/Shape/EditorSphereShapeComponent.h | 2 ++ .../Source/Shape/EditorSplineComponent.cpp | 1 + .../Source/Shape/EditorTubeShapeComponent.cpp | 6 +++++ .../Source/Shape/EditorTubeShapeComponent.h | 1 + .../Source/Shape/SphereShapeComponent.cpp | 1 + .../Code/Source/Shape/SplineComponent.h | 1 + .../Code/Source/Shape/TubeShapeComponent.cpp | 1 + .../Components/EditorSequenceComponent.h | 1 + .../Source/Components/SequenceComponent.cpp | 5 ++++ .../Source/Components/SequenceComponent.h | 2 ++ .../Code/Source/Components/ClothComponent.cpp | 5 ++++ .../Code/Source/Components/ClothComponent.h | 1 + .../Components/EditorClothComponent.cpp | 5 ++++ .../Source/Components/EditorClothComponent.h | 1 + .../Code/Source/EditorBallJointComponent.cpp | 5 ++++ .../Code/Source/EditorBallJointComponent.h | 1 + .../Code/Source/EditorFixedJointComponent.cpp | 5 ++++ .../Code/Source/EditorFixedJointComponent.h | 1 + .../Code/Source/EditorHingeJointComponent.cpp | 5 ++++ .../Code/Source/EditorHingeJointComponent.h | 1 + .../Components/CharacterControllerComponent.h | 1 + .../Components/CharacterGameplayComponent.cpp | 1 + .../EditorCharacterControllerComponent.h | 1 + .../EditorCharacterGameplayComponent.cpp | 1 + .../Components/RagdollComponent.h | 1 + .../EditorWhiteBoxColliderComponent.cpp | 5 ++++ .../EditorWhiteBoxColliderComponent.h | 1 + .../Components/WhiteBoxColliderComponent.cpp | 5 ++++ .../Components/WhiteBoxColliderComponent.h | 1 + .../Code/Source/EditorWhiteBoxComponent.cpp | 5 ++++ .../Code/Source/EditorWhiteBoxComponent.h | 1 + 50 files changed, 119 insertions(+), 47 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp index 57f14ddb38..d51f3645d3 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp @@ -37,29 +37,6 @@ namespace AzFramework void NonUniformScaleComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); - - incompatible.push_back(AZ_CRC_CE("DebugDrawObbService")); - incompatible.push_back(AZ_CRC_CE("DebugDrawService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXActorService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXSimpleMotionService")); - incompatible.push_back(AZ_CRC_CE("GradientTransformService")); - incompatible.push_back(AZ_CRC_CE("LegacyMeshService")); - incompatible.push_back(AZ_CRC_CE("LookAtService")); - incompatible.push_back(AZ_CRC_CE("SequenceService")); - incompatible.push_back(AZ_CRC_CE("ClothMeshService")); - incompatible.push_back(AZ_CRC_CE("PhysXJointService")); - incompatible.push_back(AZ_CRC_CE("PhysXCharacterControllerService")); - incompatible.push_back(AZ_CRC_CE("PhysXRagdollService")); - incompatible.push_back(AZ_CRC_CE("WhiteBoxService")); - incompatible.push_back(AZ_CRC_CE("NavigationAreaService")); - incompatible.push_back(AZ_CRC_CE("GeometryService")); - incompatible.push_back(AZ_CRC_CE("CapsuleShapeService")); - incompatible.push_back(AZ_CRC_CE("CompoundShapeService")); - incompatible.push_back(AZ_CRC_CE("CylinderShapeService")); - incompatible.push_back(AZ_CRC_CE("DiskShapeService")); - incompatible.push_back(AZ_CRC_CE("SphereShapeService")); - incompatible.push_back(AZ_CRC_CE("SplineService")); - incompatible.push_back(AZ_CRC_CE("TubeShapeService")); } void NonUniformScaleComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp index 989398f196..a61f042049 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp @@ -63,29 +63,6 @@ namespace AzToolsFramework void EditorNonUniformScaleComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); - - incompatible.push_back(AZ_CRC_CE("DebugDrawObbService")); - incompatible.push_back(AZ_CRC_CE("DebugDrawService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXActorService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXSimpleMotionService")); - incompatible.push_back(AZ_CRC_CE("GradientTransformService")); - incompatible.push_back(AZ_CRC_CE("LegacyMeshService")); - incompatible.push_back(AZ_CRC_CE("LookAtService")); - incompatible.push_back(AZ_CRC_CE("SequenceService")); - incompatible.push_back(AZ_CRC_CE("ClothMeshService")); - incompatible.push_back(AZ_CRC_CE("PhysXJointService")); - incompatible.push_back(AZ_CRC_CE("PhysXCharacterControllerService")); - incompatible.push_back(AZ_CRC_CE("PhysXRagdollService")); - incompatible.push_back(AZ_CRC_CE("WhiteBoxService")); - incompatible.push_back(AZ_CRC_CE("NavigationAreaService")); - incompatible.push_back(AZ_CRC_CE("GeometryService")); - incompatible.push_back(AZ_CRC_CE("CapsuleShapeService")); - incompatible.push_back(AZ_CRC_CE("CompoundShapeService")); - incompatible.push_back(AZ_CRC_CE("CylinderShapeService")); - incompatible.push_back(AZ_CRC_CE("DiskShapeService")); - incompatible.push_back(AZ_CRC_CE("SphereShapeService")); - incompatible.push_back(AZ_CRC_CE("SplineService")); - incompatible.push_back(AZ_CRC_CE("TubeShapeService")); } void EditorNonUniformScaleComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) diff --git a/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp b/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp index df13bb56ce..72bbaba2b7 100644 --- a/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp +++ b/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp @@ -71,7 +71,7 @@ namespace DebugDraw void DebugDrawObbComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { - (void)incompatible; + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void DebugDrawObbComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h index 416705bff4..8188da19b4 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h @@ -136,6 +136,7 @@ namespace EMotionFX { incompatible.push_back(AZ_CRC("EMotionFXActorService", 0xd6e8f48d)); incompatible.push_back(AZ_CRC("MeshService", 0x71d8a455)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h index 5f5066b9bb..6820bfe33f 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h @@ -87,6 +87,7 @@ namespace EMotionFX { incompatible.push_back(AZ_CRC("EMotionFXAnimGraphService", 0x9ec3c819)); incompatible.push_back(AZ_CRC("EMotionFXSimpleMotionService", 0xea7a05d8)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void Reflect(AZ::ReflectContext* /*context*/); diff --git a/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp b/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp index 0b967a6957..f99a8a8dfb 100644 --- a/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp @@ -200,6 +200,7 @@ namespace GradientSignal void GradientTransformComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services) { services.push_back(AZ_CRC("GradientTransformService", 0x8c8c5ecc)); + services.push_back(AZ_CRC_CE("NonUniformScaleService")); } void GradientTransformComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services) diff --git a/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp index 46eb69dbd8..2341f93dbb 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp @@ -32,6 +32,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("CapsuleShapeService", 0x9bc1122c)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CapsuleShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h index 25204cd4c0..1000609cf3 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h @@ -76,6 +76,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("CompoundShapeService", 0x4f7c640a)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void Reflect(AZ::ReflectContext* context); diff --git a/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp index 493cdef3e8..ff4ae9a9c5 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp @@ -31,6 +31,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("CylinderShapeService", 0x507c688e)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CylinderShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp index 2d0673f299..f4a0f778c5 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp @@ -28,6 +28,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("DiskShapeService", 0xd90c482b)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void DiskShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp index 93fdfae29f..6c37d2f1ec 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp @@ -78,6 +78,12 @@ namespace LmbrCentral EditorBaseShapeComponent::Deactivate(); } + void EditorCapsuleShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorCapsuleShapeComponent::DisplayEntityViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h index 6bb34b1b9e..3accb8f29d 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h @@ -40,6 +40,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("CapsuleShapeService", 0x9bc1122c)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // EditorComponentBase void BuildGameEntity(AZ::Entity* gameEntity) override; diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp index c61f54ab08..18957fae36 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp @@ -59,6 +59,12 @@ namespace LmbrCentral } } + void EditorCompoundShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorCompoundShapeComponent::Init() { // setup the contained runtime component so that it can manage the child entities in the editor. diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h index 24f06ee336..c725c2ef34 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h @@ -41,6 +41,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("CompoundShapeService", 0x4f7c640a)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + AZ::u32 ConfigurationChanged(); private: diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp index 89de8410f5..fe5a525fa8 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp @@ -55,6 +55,12 @@ namespace LmbrCentral } } + void EditorCylinderShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorCylinderShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h index a34ec6f548..3bbcf3286b 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h @@ -40,6 +40,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("CylinderShapeService", 0x507c688e)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // EditorComponentBase void BuildGameEntity(AZ::Entity* gameEntity) override; diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp index 3d6181cde6..c1bfc04e7d 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp @@ -55,6 +55,12 @@ namespace LmbrCentral provided.push_back(AZ_CRC("DiskShapeService", 0xd90c482b)); } + void EditorDiskShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorDiskShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h index 1d20f2a338..d936a4a9ec 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h @@ -39,6 +39,7 @@ namespace LmbrCentral protected: static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); private: AZ_DISABLE_COPY_MOVE(EditorDiskShapeComponent) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp index 0d9885191d..0323ec2dfe 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp @@ -60,6 +60,12 @@ namespace LmbrCentral } } + void EditorSphereShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorSphereShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h index f4a80d91ed..48f1d6cb2e 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h @@ -44,6 +44,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("SphereShapeService", 0x90c8dc80)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + private: AZ_DISABLE_COPY_MOVE(EditorSphereShapeComponent) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp index 144713c8ec..212ec49c93 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp @@ -44,6 +44,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("VariableVertexContainerService", 0x70c58740)); incompatible.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void EditorSplineComponent::Reflect(AZ::ReflectContext* context) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp index c8c03e2811..6ffb9e3308 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp @@ -59,6 +59,12 @@ namespace LmbrCentral } } + void EditorTubeShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorTubeShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h index b7b57310e5..6ffe7e9b73 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h @@ -57,6 +57,7 @@ namespace LmbrCentral required.push_back(AZ_CRC("SplineService", 0x2b674d3c)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); private: AZ_DISABLE_COPY_MOVE(EditorTubeShapeComponent) diff --git a/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp index 3bddc9b695..7faa455398 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp @@ -29,6 +29,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("SphereShapeService", 0x90c8dc80)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void SphereShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h b/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h index eaa3fde457..f4cd73574b 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h @@ -103,6 +103,7 @@ namespace LmbrCentral incompatible.push_back(AZ_CRC("SplineService", 0x2b674d3c)); incompatible.push_back(AZ_CRC("VariableVertexContainerService", 0x70c58740)); incompatible.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp index f757da2107..014612daa1 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp @@ -28,6 +28,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("TubeShapeService", 0x3fe791b4)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void TubeShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h b/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h index 294f7b4370..f5689f3f65 100644 --- a/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h +++ b/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h @@ -98,6 +98,7 @@ namespace Maestro { // This guarantees that only one SequenceComponent will ever be on an entity incompatible.push_back(AZ_CRC("SequenceService", 0x7cbe5938)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } // Required Reflect function. diff --git a/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp b/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp index c1470ccf15..f1951c12a3 100644 --- a/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp +++ b/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp @@ -139,6 +139,11 @@ namespace Maestro } } + void SequenceComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void SequenceComponent::ReflectCinematicsLib(AZ::ReflectContext* context) { // The Movie System itself diff --git a/Gems/Maestro/Code/Source/Components/SequenceComponent.h b/Gems/Maestro/Code/Source/Components/SequenceComponent.h index 20e7d22fe3..48cd7f25c9 100644 --- a/Gems/Maestro/Code/Source/Components/SequenceComponent.h +++ b/Gems/Maestro/Code/Source/Components/SequenceComponent.h @@ -97,6 +97,8 @@ namespace Maestro provided.push_back(AZ_CRC("SequenceService", 0x7cbe5938)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // Required Reflect function. static void Reflect(AZ::ReflectContext* context); private: diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp b/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp index ddd2d6fa36..912255c798 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp +++ b/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp @@ -47,6 +47,11 @@ namespace NvCloth required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); } + void ClothComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void ClothComponent::Activate() { // Cloth components do not run on dedicated servers. diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponent.h b/Gems/NvCloth/Code/Source/Components/ClothComponent.h index 9b8458d276..bb7a645b61 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponent.h +++ b/Gems/NvCloth/Code/Source/Components/ClothComponent.h @@ -38,6 +38,7 @@ namespace NvCloth static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); const ClothComponentMesh* GetClothComponentMesh() const { return m_clothComponentMesh.get(); } diff --git a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp index 4705a9f2c2..1254a13cb2 100644 --- a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp +++ b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp @@ -415,6 +415,11 @@ namespace NvCloth required.push_back(AZ_CRC("MeshService", 0x71d8a455)); } + void EditorClothComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + const MeshNodeList& EditorClothComponent::GetMeshNodeList() const { return m_meshNodeList; diff --git a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h index 9727895a43..2ef3123942 100644 --- a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h +++ b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h @@ -39,6 +39,7 @@ namespace NvCloth static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); const MeshNodeList& GetMeshNodeList() const; const AZStd::unordered_set& GetMeshNodesWithBackstopData() const; diff --git a/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp b/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp index f3bdb83325..deb1d0d231 100644 --- a/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp @@ -63,6 +63,11 @@ namespace PhysX required.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); } + void EditorBallJointComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorBallJointComponent::Activate() { EditorJointComponent::Activate(); diff --git a/Gems/PhysX/Code/Source/EditorBallJointComponent.h b/Gems/PhysX/Code/Source/EditorBallJointComponent.h index fbff44b38e..44f96b3fa8 100644 --- a/Gems/PhysX/Code/Source/EditorBallJointComponent.h +++ b/Gems/PhysX/Code/Source/EditorBallJointComponent.h @@ -33,6 +33,7 @@ namespace PhysX static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component void Activate() override; diff --git a/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp b/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp index a2b496672c..1645d8c932 100644 --- a/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp @@ -60,6 +60,11 @@ namespace PhysX required.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); } + void EditorFixedJointComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorFixedJointComponent::Activate() { EditorJointComponent::Activate(); diff --git a/Gems/PhysX/Code/Source/EditorFixedJointComponent.h b/Gems/PhysX/Code/Source/EditorFixedJointComponent.h index c66ba661be..8642f83472 100644 --- a/Gems/PhysX/Code/Source/EditorFixedJointComponent.h +++ b/Gems/PhysX/Code/Source/EditorFixedJointComponent.h @@ -33,6 +33,7 @@ namespace PhysX static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component void Activate() override; diff --git a/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp b/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp index fde1ff980b..6d136e898b 100644 --- a/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp @@ -63,6 +63,11 @@ namespace PhysX required.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); } + void EditorHingeJointComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorHingeJointComponent::Activate() { EditorJointComponent::Activate(); diff --git a/Gems/PhysX/Code/Source/EditorHingeJointComponent.h b/Gems/PhysX/Code/Source/EditorHingeJointComponent.h index 3b3182068b..ef555d145e 100644 --- a/Gems/PhysX/Code/Source/EditorHingeJointComponent.h +++ b/Gems/PhysX/Code/Source/EditorHingeJointComponent.h @@ -33,6 +33,7 @@ namespace PhysX static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component void Activate() override; diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h index 31f5051ac4..a7a1a92ad2 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h @@ -59,6 +59,7 @@ namespace PhysX static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("PhysXCharacterControllerService", 0x428de4fa)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp index 70373f8db2..d557919627 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp @@ -51,6 +51,7 @@ namespace PhysX void CharacterGameplayComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("PhysXCharacterGameplayService", 0xfacd7876)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CharacterGameplayComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h index d42c1c9537..cc2a93d0b8 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h @@ -64,6 +64,7 @@ namespace PhysX incompatible.push_back(AZ_CRC("PhysXCharacterControllerService", 0x428de4fa)); incompatible.push_back(AZ_CRC("LegacyCryPhysicsService", 0xbb370351)); incompatible.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp index 03ff0e0aea..dc67870fb2 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp @@ -23,6 +23,7 @@ namespace PhysX void EditorCharacterGameplayComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("PhysXCharacterGameplayService", 0xfacd7876)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void EditorCharacterGameplayComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h index e7397af877..a02e9c47fb 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h @@ -49,6 +49,7 @@ namespace PhysX { incompatible.push_back(AZ_CRC("PhysXRagdollService", 0x6d889c70)); incompatible.push_back(AZ_CRC("LegacyCryPhysicsService", 0xbb370351)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp index 6e2e4be0a2..97bce7631d 100644 --- a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp @@ -75,6 +75,11 @@ namespace WhiteBox required.push_back(AZ_CRC("WhiteBoxService", 0x2f2f42b8)); } + void EditorWhiteBoxColliderComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorWhiteBoxColliderComponent::Activate() { AzToolsFramework::Components::EditorComponentBase::Activate(); diff --git a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h index 5b46d0b99e..635abbb1bd 100644 --- a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h +++ b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h @@ -46,6 +46,7 @@ namespace WhiteBox private: static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component ... void Activate() override; diff --git a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp index 3179a2cd72..117b175cda 100644 --- a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp @@ -44,6 +44,11 @@ namespace WhiteBox required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); } + void WhiteBoxColliderComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + WhiteBoxColliderComponent::WhiteBoxColliderComponent( const Physics::CookedMeshShapeConfiguration& shapeConfiguration, const Physics::ColliderConfiguration& physicsColliderConfiguration, diff --git a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h index 1ad773652d..0b50c834d8 100644 --- a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h +++ b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h @@ -41,6 +41,7 @@ namespace WhiteBox private: static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component ... void Activate() override; diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp index d4ab543404..e8e03556e2 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp @@ -265,6 +265,11 @@ namespace WhiteBox provided.push_back(AZ_CRC("WhiteBoxService", 0x2f2f42b8)); } + void EditorWhiteBoxComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + EditorWhiteBoxComponent::EditorWhiteBoxComponent() = default; EditorWhiteBoxComponent::~EditorWhiteBoxComponent() diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h index 02b50a9407..c4dd6c2b0b 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h @@ -89,6 +89,7 @@ namespace WhiteBox private: static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // EditorComponentBase overrides ... void BuildGameEntity(AZ::Entity* gameEntity) override; From 7bdf44a0996b93bea061c5146e5627e7abbb8b21 Mon Sep 17 00:00:00 2001 From: srikappa Date: Wed, 12 May 2021 13:38:44 -0700 Subject: [PATCH 064/231] Detect cyclical dependencies in the nested prefabs of the prefab being instantiated --- .../Prefab/PrefabDomUtils.cpp | 37 ++++++++++++++++ .../AzToolsFramework/Prefab/PrefabDomUtils.h | 14 +++++++ .../Prefab/PrefabPublicHandler.cpp | 42 ++++++++++--------- .../Prefab/PrefabPublicHandler.h | 18 ++++---- 4 files changed, 84 insertions(+), 27 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp index 0bffd26be0..145a293ab8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp @@ -199,6 +199,43 @@ namespace AzToolsFramework return true; } + void GetTemplateSourcePaths(const PrefabDomValue& prefabDom, AZStd::unordered_set& templateSourcePaths) + { + PrefabDomValueConstReference findSourceResult = PrefabDomUtils::FindPrefabDomValue(prefabDom, PrefabDomUtils::SourceName); + if (!findSourceResult.has_value() || !(findSourceResult->get().IsString()) || + findSourceResult->get().GetStringLength() == 0) + { + AZ_Assert( + false, + "PrefabDomUtils::GetDependentTemplatePath - Source value of prefab in the provided DOM is not a valid string."); + return; + } + + templateSourcePaths.emplace(findSourceResult->get().GetString()); + PrefabDomValueConstReference instancesReference = GetInstancesValue(prefabDom); + if (instancesReference.has_value()) + { + const PrefabDomValue& instances = instancesReference->get(); + + for (PrefabDomValue::ConstMemberIterator instanceIterator = instances.MemberBegin(); + instanceIterator != instances.MemberEnd(); ++instanceIterator) + { + GetTemplateSourcePaths(instanceIterator->value, templateSourcePaths); + } + } + } + + PrefabDomValueConstReference GetInstancesValue(const PrefabDomValue& prefabDom) + { + PrefabDomValueConstReference findInstancesResult = FindPrefabDomValue(prefabDom, PrefabDomUtils::InstancesName); + if (!findInstancesResult.has_value() || !(findInstancesResult->get().IsObject())) + { + return AZStd::nullopt; + } + + return findInstancesResult->get(); + } + void PrintPrefabDomValue( [[maybe_unused]] const AZStd::string_view printMessage, [[maybe_unused]] const PrefabDomValue& prefabDomValue) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h index c7c2827770..6f7d2fe9b1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h @@ -100,6 +100,20 @@ namespace AzToolsFramework .Append(instanceName); }; + /** + * Gets a set of all the template source paths in the given dom. + * @param prefabDom The DOM to get the template source paths from. + * @param templateSourcePaths The set of template source paths to populate. + */ + void GetTemplateSourcePaths(const PrefabDomValue& prefabDom, AZStd::unordered_set& templateSourcePaths); + + /** + * Gets the instances DOM value from the given prefab DOM. + * + * @return the instances DOM value or AZStd::nullopt if it instances can't be found. + */ + PrefabDomValueConstReference GetInstancesValue(const PrefabDomValue& prefabDom); + /** * Prints the contents of the given prefab DOM value to the debug output console in a readable format. * @param printMessage The message that will be printed before printing the PrefabDomValue diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 14537683ef..e2c616d5d8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -191,25 +191,30 @@ namespace AzToolsFramework auto relativePath = m_prefabLoaderInterface->GetRelativePathToProject(filePath); Prefab::TemplateId templateId = m_prefabSystemComponentInterface->GetTemplateIdFromFilePath(relativePath); - // If the template isn't currently loaded, there's no way for it to be in the hierarchy so we just skip the check. - if (templateId != Prefab::InvalidTemplateId && IsPrefabInInstanceAncestorHierarchy(templateId, instanceToParentUnder->get())) + if (templateId == InvalidTemplateId) { - return AZ::Failure( - AZStd::string::format( - "Instantiate Prefab operation aborted - Cyclical dependency detected\n(%s depends on %s).", - relativePath.Native().c_str(), - instanceToParentUnder->get().GetTemplateSourcePath().Native().c_str() - ) - ); + // Load the template from the file + templateId = m_prefabLoaderInterface->LoadTemplateFromFile(filePath); + AZ_Assert(templateId != InvalidTemplateId, "Template with source path %s couldn't be loaded correctly.", filePath); } - + + const PrefabDom& templateDom = m_prefabSystemComponentInterface->FindTemplateDom(templateId); + AZStd::unordered_set templatePaths; + PrefabDomUtils::GetTemplateSourcePaths(templateDom, templatePaths); + + if (IsCyclicalDependencyFound(instanceToParentUnder->get(), templatePaths)) + { + return AZ::Failure(AZStd::string::format( + "Instantiate Prefab operation aborted - Cyclical dependency detected\n(%s depends on %s).", + relativePath.Native().c_str(), instanceToParentUnder->get().GetTemplateSourcePath().Native().c_str())); + } + { // Initialize Undo Batch object ScopedUndoBatch undoBatch("Instantiate Prefab"); PrefabDom instanceToParentUnderDomBeforeCreate; - m_instanceToTemplateInterface->GenerateDomForInstance( - instanceToParentUnderDomBeforeCreate, instanceToParentUnder->get()); + m_instanceToTemplateInterface->GenerateDomForInstance(instanceToParentUnderDomBeforeCreate, instanceToParentUnder->get()); // Instantiate the Prefab auto instanceToCreate = prefabEditorEntityOwnershipInterface->InstantiatePrefab(relativePath, instanceToParentUnder); @@ -223,8 +228,7 @@ namespace AzToolsFramework PrefabUndoHelpers::UpdatePrefabInstance( instanceToParentUnder->get(), "Update prefab instance", instanceToParentUnderDomBeforeCreate, undoBatch.GetUndoBatch()); - CreateLink({}, instanceToCreate->get(), instanceToParentUnder->get().GetTemplateId(), - undoBatch.GetUndoBatch(), parent); + CreateLink({}, instanceToCreate->get(), instanceToParentUnder->get().GetTemplateId(), undoBatch.GetUndoBatch(), parent); AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); // Apply position @@ -277,17 +281,17 @@ namespace AzToolsFramework return AZ::Success(); } - bool PrefabPublicHandler::IsPrefabInInstanceAncestorHierarchy(TemplateId prefabTemplateId, InstanceOptionalConstReference instance) + bool PrefabPublicHandler::IsCyclicalDependencyFound( + InstanceOptionalConstReference instance, AZStd::unordered_set& templateSourcePaths) { InstanceOptionalConstReference currentInstance = instance; while (currentInstance.has_value()) { - if (currentInstance->get().GetTemplateId() == prefabTemplateId) + if (templateSourcePaths.contains(currentInstance->get().GetTemplateSourcePath())) { return true; } - currentInstance = currentInstance->get().GetParentInstance(); } @@ -966,5 +970,5 @@ namespace AzToolsFramework return true; } - } -} + } // namespace Prefab +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 03b3827328..519c7ca53f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -12,8 +12,8 @@ #pragma once -#include #include +#include #include #include @@ -106,13 +106,15 @@ namespace AzToolsFramework const AZStd::vector& entityIds, EntityList& inputEntityList, EntityList& topLevelEntities, AZ::EntityId& commonRootEntityId, InstanceOptionalReference& commonRootEntityOwningInstance); - /* Detects whether an instance of prefabTemplateId is present in the hierarchy of ancestors of instance. + /* Checks whether the template source path of any of the ancestors in the instance hierarchy matches with one of the + * paths provided in a set. * - * \param prefabTemplateId The template id to test for - * \param instance The instance whose ancestor hierarchy prefabTemplateId will be tested against. - * \return true if an instance of the template of id prefabTemplateId could be found in the ancestor hierarchy of instance, false otherwise. + * \param instance The instance whose ancestor hierarchy the provided set of template source paths will be tested against. + * \param templateSourcePaths The template source paths provided to be checked against the instance ancestor hierarchy. + * \return true if any of the template source paths could be found in the ancestor hierarchy of instance, false otherwise. */ - bool IsPrefabInInstanceAncestorHierarchy(TemplateId prefabTemplateId, InstanceOptionalConstReference instance); + bool IsCyclicalDependencyFound( + InstanceOptionalConstReference instance, AZStd::unordered_set& templateSourcePaths); static Instance* GetParentInstance(Instance* instance); static Instance* GetAncestorOfInstanceThatIsChildOfRoot(const Instance* ancestor, Instance* descendant); @@ -128,5 +130,5 @@ namespace AzToolsFramework uint64_t m_newEntityCounter = 1; }; - } -} + } // namespace Prefab +} // namespace AzToolsFramework From d0b006c209573e0be961b6bc27fd3bde1cbaf3ad Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 13:41:18 -0700 Subject: [PATCH 065/231] Some cleanup to better support backward reconciliation as well as dynamic player spawning on connect --- Code/CryEngine/CrySystem/SystemInit.cpp | 2 +- Gems/Multiplayer/Code/Include/IMultiplayer.h | 79 +++++++++++++++++-- .../Code/Include/INetworkEntityManager.h | 42 +++++----- Gems/Multiplayer/Code/Include/INetworkTime.h | 34 ++------ .../AutoGen/AutoComponentTypes_Source.jinja | 2 +- .../Source/AutoGen/AutoComponent_Source.jinja | 23 ++++-- .../LocalPredictionPlayerInputComponent.cpp | 6 +- .../Source/MultiplayerSystemComponent.cpp | 73 ++++++++++++----- .../Code/Source/MultiplayerSystemComponent.h | 5 ++ .../EntityReplicationManager.cpp | 2 +- .../EntityReplication/EntityReplicator.cpp | 4 +- .../NetworkEntity/NetworkEntityManager.cpp | 29 +++++-- .../NetworkEntity/NetworkEntityManager.h | 19 +++-- .../Source/NetworkInput/NetworkInputChild.cpp | 2 +- .../NetworkInputMigrationVector.cpp | 2 +- .../Code/Source/NetworkTime/NetworkTime.cpp | 52 ++++++++---- .../Code/Source/NetworkTime/NetworkTime.h | 7 +- .../Source/NetworkTime/RewindableObject.inl | 4 +- .../ServerToClientReplicationWindow.cpp | 2 +- .../ServerToClientReplicationWindow.h | 2 +- 20 files changed, 262 insertions(+), 129 deletions(-) diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 8bf2fb8930..6181fde615 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -1247,7 +1247,7 @@ bool CSystem::InitShine([[maybe_unused]] const SSystemInitParams& initParams) 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."); + 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 *_dependencies.cmake."); return false; } return true; diff --git a/Gems/Multiplayer/Code/Include/IMultiplayer.h b/Gems/Multiplayer/Code/Include/IMultiplayer.h index 039b86b2a6..80bdaa68eb 100644 --- a/Gems/Multiplayer/Code/Include/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/IMultiplayer.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -46,6 +47,7 @@ namespace Multiplayer using ConnectionAcquiredEvent = AZ::Event; using SessionInitEvent = AZ::Event; using SessionShutdownEvent = AZ::Event; + using OnConnectFunctor = AZStd::function; //! IMultiplayer provides insight into the Multiplayer session and its Agents class IMultiplayer @@ -55,26 +57,30 @@ namespace Multiplayer virtual ~IMultiplayer() = default; - //! Gets the type of Agent this IMultiplayer impl represents + //! Gets the type of Agent this IMultiplayer impl represents. //! @return The type of agents represented virtual MultiplayerAgentType GetAgentType() const = 0; - //! Sets the type of this Multiplayer connection and calls any related callback + //! Sets the type of this Multiplayer connection and calls any related callback. //! @param state The state of this connection virtual void InitializeMultiplayer(MultiplayerAgentType state) = 0; - //! Adds a ConnectionAcquiredEvent Handler which is invoked when a new endpoint connects to the session + //! Adds a ConnectionAcquiredEvent Handler which is invoked when a new endpoint connects to the session. //! @param handler The SessionInitEvent Handler to add virtual void AddConnectionAcquiredHandler(ConnectionAcquiredEvent::Handler& handler) = 0; - //! Adds a SessionInitEvent Handler which is invoked when a new network session starts + //! Adds a SessionInitEvent Handler which is invoked when a new network session starts. //! @param handler The SessionInitEvent Handler to add virtual void AddSessionInitHandler(SessionInitEvent::Handler& handler) = 0; - //! Adds a SessionShutdownEvent Handler which is invoked when the current network session ends + //! Adds a SessionShutdownEvent Handler which is invoked when the current network session ends. //! @param handler The SessionShutdownEvent handler to add virtual void AddSessionShutdownHandler(SessionShutdownEvent::Handler& handler) = 0; + //! Overrides the default connect behaviour with the provided functor. + //! @param functor the function to invoke during a new connection event + virtual void SetOnConnectFunctor(const OnConnectFunctor& functor) = 0; + //! Sends a packet telling if entity update messages can be sent //! @param readyForEntityUpdates Ready for entity updates or not virtual void SendReadyForEntityUpdates(bool readyForEntityUpdates) = 0; @@ -87,6 +93,14 @@ namespace Multiplayer //! @return the current server time in milliseconds virtual AZ::TimeMs GetCurrentHostTimeMs() const = 0; + //! Returns the network time instance bound to this multiplayer instance. + //! @return pointer to the network time instance bound to this multiplayer instance + virtual INetworkTime* GetNetworkTime() = 0; + + //! Returns the network entity manager instance bound to this multiplayer instance. + //! @return pointer to the network entity manager instance bound to this multiplayer instance + virtual INetworkEntityManager* GetNetworkEntityManager() = 0; + //! Returns the gem name associated with the provided component index. //! @param netComponentId the componentId to return the gem name of //! @return the name of the gem that contains the requested component @@ -117,6 +131,61 @@ namespace Multiplayer MultiplayerStats m_stats; }; + // Convenience helpers + inline IMultiplayer* GetMultiplayer() + { + return AZ::Interface::Get(); + } + + inline INetworkTime* GetNetworkTime() + { + return GetMultiplayer()->GetNetworkTime(); + } + + inline INetworkEntityManager* GetNetworkEntityManager() + { + return GetMultiplayer()->GetNetworkEntityManager(); + } + + inline NetworkEntityTracker* GetNetworkEntityTracker() + { + return GetNetworkEntityManager()->GetNetworkEntityTracker(); + } + + inline NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() + { + return GetNetworkEntityManager()->GetNetworkEntityAuthorityTracker(); + } + + inline MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() + { + return GetNetworkEntityManager()->GetMultiplayerComponentRegistry(); + } + + //! @class ScopedAlterTime + //! @brief This is a wrapper that temporarily adjusts global program time for backward reconciliation purposes. + class ScopedAlterTime final + { + public: + inline ScopedAlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId connectionId) + { + INetworkTime* time = GetNetworkTime(); + m_previousHostFrameId = time->GetHostFrameId(); + m_previousHostTimeMs = time->GetHostTimeMs(); + m_previousRewindConnectionId = time->GetRewindingConnectionId(); + time->AlterTime(frameId, timeMs, connectionId); + } + inline ~ScopedAlterTime() + { + INetworkTime* time = GetNetworkTime(); + time->AlterTime(m_previousHostFrameId, m_previousHostTimeMs, m_previousRewindConnectionId); + } + private: + HostFrameId m_previousHostFrameId = InvalidHostFrameId; + AZ::TimeMs m_previousHostTimeMs = AZ::TimeMs{ 0 }; + AzNetworking::ConnectionId m_previousRewindConnectionId = AzNetworking::InvalidConnectionId; + }; + inline const char* GetEnumString(MultiplayerAgentType value) { switch (value) diff --git a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h b/Gems/Multiplayer/Code/Include/INetworkEntityManager.h index d9b611ece0..ebb95e2281 100644 --- a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Include/INetworkEntityManager.h @@ -59,9 +59,24 @@ namespace Multiplayer //! Creates new entities of the given archetype //! @param prefabEntryId the name of the spawnable to spawn - virtual EntityList CreateEntitiesImmediate( - const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, AutoActivate autoActivate, - const AZ::Transform& transform) = 0; + virtual EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityRole netEntityRole, + const AZ::Transform& transform + ) = 0; + + //! Creates new entities of the given archetype + //! This interface is internally used to spawn replicated entities + //! @param prefabEntryId the name of the spawnable to spawn + virtual EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityId netEntityId, + NetEntityRole netEntityRole, + AutoActivate autoActivate, + const AZ::Transform& transform + ) = 0; //! Returns an ConstEntityPtr for the provided entityId. //! @param netEntityId the netEntityId to get an ConstEntityPtr for @@ -134,25 +149,4 @@ namespace Multiplayer //! @param entityRpcMessage the local rpc message to handle virtual void HandleLocalRpcMessage(NetworkEntityRpcMessage& message) = 0; }; - - // Convenience helpers - inline INetworkEntityManager* GetNetworkEntityManager() - { - return AZ::Interface::Get(); - } - - inline NetworkEntityTracker* GetNetworkEntityTracker() - { - return GetNetworkEntityManager()->GetNetworkEntityTracker(); - } - - inline NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() - { - return GetNetworkEntityManager()->GetNetworkEntityAuthorityTracker(); - } - - inline MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() - { - return GetNetworkEntityManager()->GetMultiplayerComponentRegistry(); - } } diff --git a/Gems/Multiplayer/Code/Include/INetworkTime.h b/Gems/Multiplayer/Code/Include/INetworkTime.h index 5346a0e0d0..1ccf08bbdc 100644 --- a/Gems/Multiplayer/Code/Include/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/INetworkTime.h @@ -47,9 +47,6 @@ namespace Multiplayer //! @return the hosts current timeMs virtual AZ::TimeMs GetHostTimeMs() const = 0; - //! Synchronizes rewindable entity state for the current application time. - virtual void SyncRewindableEntityState() = 0; - //! Get the controlling connection that may be currently altering global game time. //! Note this abstraction is required at a relatively high level to allow for 'don't rewind the shooter' semantics //! @return the ConnectionId of the connection requesting the rewind operation @@ -67,6 +64,13 @@ namespace Multiplayer //! @param rewindConnectionId the rewinding ConnectionId virtual void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) = 0; + //! Syncs all entities contained within a volume to the current rewind state. + //! @param rewindVolume the volume to rewind entities within (needed for physics entities) + virtual void SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) = 0; + + //! Restores all rewound entities to the current application time. + virtual void ClearRewoundEntities() = 0; + AZ_DISABLE_COPY_MOVE(INetworkTime); }; @@ -79,28 +83,4 @@ namespace Multiplayer static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; }; using INetworkTimeRequestBus = AZ::EBus; - - //! @class ScopedAlterTime - //! @brief This is a wrapper that temporarily adjusts global program time for backward reconciliation purposes. - class ScopedAlterTime final - { - public: - inline ScopedAlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId connectionId) - { - INetworkTime* time = AZ::Interface::Get(); - m_previousHostFrameId = time->GetHostFrameId(); - m_previousHostTimeMs = time->GetHostTimeMs(); - m_previousRewindConnectionId = time->GetRewindingConnectionId(); - time->AlterTime(frameId, timeMs, connectionId); - } - inline ~ScopedAlterTime() - { - INetworkTime* time = AZ::Interface::Get(); - time->AlterTime(m_previousHostFrameId, m_previousHostTimeMs, m_previousRewindConnectionId); - } - private: - HostFrameId m_previousHostFrameId = InvalidHostFrameId; - AZ::TimeMs m_previousHostTimeMs = AZ::TimeMs{ 0 }; - AzNetworking::ConnectionId m_previousRewindConnectionId = AzNetworking::InvalidConnectionId; - }; } diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja index 2bae618d94..2acc252729 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja @@ -22,7 +22,7 @@ namespace {{ Namespace }} void RegisterMultiplayerComponents() { Multiplayer::MultiplayerComponentRegistry* multiplayerComponentRegistry = GetMultiplayerComponentRegistry(); - Multiplayer::MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + Multiplayer::MultiplayerStats& stats = GetMultiplayer()->GetStats(); {% for Component in dataFiles %} {% set ComponentName = Component.attrib['Name'] %} {% set ComponentBaseName = ComponentName %} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 6e54ec3d58..d719cbe47b 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -476,7 +476,7 @@ bool {{ ClassName }}::Serialize{{ AutoComponentMacros.GetNetPropertiesSetName(Re {%- if networkPropertyCount.update({'value': networkPropertyCount.value + 1}) %}{% endif -%} {% endcall %} {% if networkPropertyCount.value > 0 %} - MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + MultiplayerStats& stats = 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) %} @@ -1141,16 +1141,23 @@ namespace {{ Component.attrib['Namespace'] }} AZ::EditContext* editContext = serializeContext->GetEditContext(); if (editContext) { - editContext->Class<{{ ComponentName }}>("{{ ComponentName }}", "{{ Component.attrib['Description'] }}") + editContext->Class<{{ ComponentBaseName }}>("{{ ComponentBaseName }}", "{{ Component.attrib['Description'] }}") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) - {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Authority', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Server', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Client', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Autonomous', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Autonomous', 'Authority', ComponentName)|indent(20) }} - {{ DefineArchetypePropertyEditReflection(Component, ComponentName)|indent(20) }}; + {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Authority', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Server', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Client', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Autonomous', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Autonomous', 'Authority', ComponentBaseName)|indent(20) }} + {{ DefineArchetypePropertyEditReflection(Component, ComponentBaseName)|indent(20) }}; +{% if ComponentDerived %} + + editContext->Class<{{ ComponentName }}>("{{ ComponentName }}", "{{ Component.attrib['Description'] }}") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")); +{% endif %} } } } diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp index 90b590d99d..b57c465df2 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp @@ -94,7 +94,7 @@ namespace Multiplayer if (entityIsMigrating == EntityIsMigrating::True) { m_allowMigrateClientInput = true; - m_serverMigrateFrameId = AZ::Interface::Get()->GetHostFrameId(); + m_serverMigrateFrameId = GetNetworkTime()->GetHostFrameId(); } } @@ -492,8 +492,8 @@ namespace Multiplayer const uint32_t maxClientInputs = inputRate > 0.0 ? static_cast(maxRewindHistory / inputRate) : 0; - INetworkTime* networkTime = AZ::Interface::Get(); - IMultiplayer* multiplayer = AZ::Interface::Get(); + IMultiplayer* multiplayer = GetMultiplayer(); + INetworkTime* networkTime = GetNetworkTime(); while (m_moveAccumulator >= inputRate) { m_moveAccumulator -= inputRate; diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index e6fb77eca7..590faa6bad 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -23,6 +23,9 @@ #include #include #include +#include +#include +#include namespace AZ::ConsoleTypeHelpers { @@ -69,6 +72,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::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) { @@ -411,6 +415,11 @@ namespace Multiplayer void MultiplayerSystemComponent::OnConnect(AzNetworking::IConnection* connection) { + MultiplayerAgentDatum datum; + datum.m_id = connection->GetConnectionId(); + datum.m_isInvited = false; + datum.m_agentType = MultiplayerAgentType::Client; + if (connection->GetConnectionRole() == ConnectionRole::Connector) { AZLOG_INFO("New outgoing connection to remote address: %s", connection->GetRemoteAddress().GetString().c_str()); @@ -419,36 +428,45 @@ namespace Multiplayer else { AZLOG_INFO("New incoming connection from remote address: %s", connection->GetRemoteAddress().GetString().c_str()); - MultiplayerAgentDatum datum; - datum.m_id = connection->GetConnectionId(); - datum.m_isInvited = false; - datum.m_agentType = MultiplayerAgentType::Client; m_connAcquiredEvent.Signal(datum); } - if (GetAgentType() == MultiplayerAgentType::ClientServer - || GetAgentType() == MultiplayerAgentType::DedicatedServer) + if (m_onConnectFunctor) { - // TODO: This needs to be set to the players autonomous proxy ------------v - NetworkEntityHandle controlledEntity = GetNetworkEntityTracker()->Get(NetEntityId{ 0 }); - 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)); - } - - AZStd::unique_ptr window = AZStd::make_unique(controlledEntity, connection); - reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetReplicationWindow(AZStd::move(window)); } else { - if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so + if (GetAgentType() == MultiplayerAgentType::ClientServer + || GetAgentType() == MultiplayerAgentType::DedicatedServer) { - connection->SetUserData(new ClientToServerConnectionData(connection, *this)); - } + PrefabEntityId playerPrefabEntityId(AZ::Name(static_cast(sv_defaultPlayerSpawnAsset).c_str()), 1); + INetworkEntityManager::EntityList entityList = m_networkEntityManager.CreateEntitiesImmediate(playerPrefabEntityId, NetEntityRole::Authority, AZ::Transform::CreateIdentity()); - AZStd::unique_ptr window = AZStd::make_unique(); - reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetEntityActivationTimeSliceMs(cl_defaultNetworkEntityActivationTimeSliceMs); + NetworkEntityHandle controlledEntity; + if (entityList.size() > 0) + { + controlledEntity = entityList[0]; + } + + 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)); + } + + AZStd::unique_ptr window = AZStd::make_unique(controlledEntity, connection); + reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetReplicationWindow(AZStd::move(window)); + } + else + { + if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so + { + connection->SetUserData(new ClientToServerConnectionData(connection, *this)); + } + + AZStd::unique_ptr window = AZStd::make_unique(); + reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetEntityActivationTimeSliceMs(cl_defaultNetworkEntityActivationTimeSliceMs); + } } } @@ -521,6 +539,11 @@ namespace Multiplayer handler.Connect(m_shutdownEvent); } + void MultiplayerSystemComponent::SetOnConnectFunctor(const OnConnectFunctor& functor) + { + m_onConnectFunctor = functor; + } + void MultiplayerSystemComponent::SendReadyForEntityUpdates(bool readyForEntityUpdates) { IConnectionSet& connectionSet = m_networkInterface->GetConnectionSet(); @@ -542,6 +565,16 @@ namespace Multiplayer } } + INetworkTime* MultiplayerSystemComponent::GetNetworkTime() + { + return &m_networkTime; + } + + INetworkEntityManager* MultiplayerSystemComponent::GetNetworkEntityManager() + { + return &m_networkEntityManager; + } + const char* MultiplayerSystemComponent::GetComponentGemName(NetComponentId netComponentId) const { return GetMultiplayerComponentRegistry()->GetComponentGemName(netComponentId); diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index 477745e6b5..1de8fccb50 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -89,8 +89,11 @@ namespace Multiplayer void AddConnectionAcquiredHandler(ConnectionAcquiredEvent::Handler& handler) override; void AddSessionInitHandler(SessionInitEvent::Handler& handler) override; void AddSessionShutdownHandler(SessionShutdownEvent::Handler& handler) override; + void SetOnConnectFunctor(const OnConnectFunctor& functor) override; void SendReadyForEntityUpdates(bool readyForEntityUpdates) override; AZ::TimeMs GetCurrentHostTimeMs() const override; + INetworkTime* GetNetworkTime() override; + INetworkEntityManager* GetNetworkEntityManager() override; const char* GetComponentGemName(NetComponentId netComponentId) const override; const char* GetComponentName(NetComponentId netComponentId) const override; const char* GetComponentPropertyName(NetComponentId netComponentId, PropertyIndex propertyIndex) const override; @@ -121,6 +124,8 @@ namespace Multiplayer SessionShutdownEvent m_shutdownEvent; ConnectionAcquiredEvent m_connAcquiredEvent; + OnConnectFunctor m_onConnectFunctor = nullptr; + AZ::TimeMs m_lastReplicatedHostTimeMs = AZ::TimeMs{ 0 }; HostFrameId m_lastReplicatedHostFrameId = InvalidHostFrameId; }; diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 1e7649f561..65df4f1464 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -824,7 +824,7 @@ namespace Multiplayer { if (entityReplicator == nullptr) { - IMultiplayer* multiplayer = AZ::Interface::Get(); + IMultiplayer* multiplayer = GetMultiplayer(); AZLOG_INFO ( "EntityReplicationManager: Dropping remote RPC message for component %s of rpc index %s, entityId %u has already been deleted", diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index 7431b95a22..197d83a48c 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -448,7 +448,7 @@ namespace Multiplayer void EntityReplicator::DeferRpcMessage(NetworkEntityRpcMessage& entityRpcMessage) { // Received rpc metrics, log rpc sent, number of bytes, and the componentId/rpcId for bandwidth metrics - MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + MultiplayerStats& stats = GetMultiplayer()->GetStats(); stats.RecordRpcSent(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); m_replicationManager.AddDeferredRpcMessage(entityRpcMessage); @@ -631,7 +631,7 @@ namespace Multiplayer bool EntityReplicator::HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetworkEntityRpcMessage& entityRpcMessage) { // Received rpc metrics, log rpc received, time spent, number of bytes, and the componentId/rpcId for bandwidth metrics - MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + MultiplayerStats& stats = GetMultiplayer()->GetStats(); stats.RecordRpcReceived(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); if (!m_netBindComponent) diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index 1c7fb5f7af..7ee4d45e93 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -38,7 +38,6 @@ namespace Multiplayer , m_onSpawnedHandler([this](AZ::Data::Asset spawnable) { this->OnSpawned(spawnable); }) , m_onDespawnedHandler([this](AZ::Data::Asset spawnable) { this->OnDespawned(spawnable); }) { - AZ::Interface::Register(this); AzFramework::RootSpawnableNotificationBus::Handler::BusConnect(); AzFramework::SpawnableEntitiesInterface::Get()->AddOnSpawnedHandler(m_onSpawnedHandler); @@ -48,7 +47,6 @@ namespace Multiplayer NetworkEntityManager::~NetworkEntityManager() { AzFramework::RootSpawnableNotificationBus::Handler::BusDisconnect(); - AZ::Interface::Unregister(this); } void NetworkEntityManager::Initialize(HostId hostId, AZStd::unique_ptr entityDomain) @@ -365,9 +363,24 @@ namespace Multiplayer return returnList; } - INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate( - const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, - AutoActivate autoActivate, const AZ::Transform& transform) + INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityRole netEntityRole, + const AZ::Transform& transform + ) + { + return CreateEntitiesImmediate(prefabEntryId, NextId(), netEntityRole, AutoActivate::Activate, transform); + } + + INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityId netEntityId, + NetEntityRole netEntityRole, + AutoActivate autoActivate, + const AZ::Transform& transform + ) { INetworkEntityManager::EntityList returnList; @@ -436,7 +449,7 @@ namespace Multiplayer void NetworkEntityManager::OnRootSpawnableAssigned( [[maybe_unused]] AZ::Data::Asset rootSpawnable, [[maybe_unused]] uint32_t generation) { - auto* multiplayer = AZ::Interface::Get(); + auto* multiplayer = GetMultiplayer(); const auto agentType = multiplayer->GetAgentType(); if (agentType == MultiplayerAgentType::Client) @@ -448,7 +461,7 @@ namespace Multiplayer void NetworkEntityManager::OnRootSpawnableReleased([[maybe_unused]] uint32_t generation) { // TODO: Do we need to clear all entities here? - auto* multiplayer = AZ::Interface::Get(); + auto* multiplayer = GetMultiplayer(); const auto agentType = multiplayer->GetAgentType(); if (agentType == MultiplayerAgentType::Client) @@ -494,7 +507,7 @@ namespace Multiplayer return; } - auto* multiplayer = AZ::Interface::Get(); + auto* multiplayer = GetMultiplayer(); const auto agentType = multiplayer->GetAgentType(); const bool spawnImmediately = diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h index ae2cb0dd9e..ba71eaf780 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h @@ -47,10 +47,20 @@ namespace Multiplayer ConstNetworkEntityHandle GetEntity(NetEntityId netEntityId) const override; EntityList CreateEntitiesImmediate(const AzFramework::Spawnable& spawnable, NetEntityRole netEntityRole); - - EntityList CreateEntitiesImmediate( - const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, - AutoActivate autoActivate, const AZ::Transform& transform) override; + EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityRole netEntityRole, + const AZ::Transform& transform + ) override; + EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityId netEntityId, + NetEntityRole netEntityRole, + AutoActivate autoActivate, + const AZ::Transform& transform + ) override; uint32_t GetEntityCount() const override; NetworkEntityHandle AddEntityToEntityMap(NetEntityId netEntityId, AZ::Entity* entity) override; @@ -81,7 +91,6 @@ namespace Multiplayer private: void RemoveEntities(); - NetEntityId NextId(); void OnSpawned(AZ::Data::Asset spawnable); diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp index 8f70f7e1fa..114c3e3b43 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp index dee72156ed..c6eed626a9 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index 9a0e784d36..c0200c9e6d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -11,19 +11,12 @@ */ #include +#include +#include +#include namespace Multiplayer { - NetworkTime::NetworkTime() - { - AZ::Interface::Register(this); - } - - NetworkTime::~NetworkTime() - { - AZ::Interface::Unregister(this); - } - bool NetworkTime::IsTimeRewound() const { return m_rewindingConnectionId != AzNetworking::InvalidConnectionId; @@ -51,11 +44,6 @@ namespace Multiplayer return m_hostTimeMs; } - void NetworkTime::SyncRewindableEntityState() - { - - } - AzNetworking::ConnectionId NetworkTime::GetRewindingConnectionId() const { return m_rewindingConnectionId; @@ -72,4 +60,38 @@ namespace Multiplayer m_hostTimeMs = timeMs; m_rewindingConnectionId = rewindConnectionId; } + + void NetworkTime::SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) + { + // TODO: extrude rewind volume for initial gather + AZStd::vector gatheredEntries; + AZ::Interface::Get()->GetDefaultVisibilityScene()->Enumerate(rewindVolume, [&gatheredEntries](const AzFramework::IVisibilityScene::NodeData& nodeData) + { + gatheredEntries.reserve(gatheredEntries.size() + nodeData.m_entries.size()); + for (AzFramework::VisibilityEntry* visEntry : nodeData.m_entries) + { + if (visEntry->m_typeFlags & AzFramework::VisibilityEntry::TypeFlags::TYPE_Entity) + { + // TODO: offset aabb for exact rewound position and check against the non-extruded rewind volume + gatheredEntries.push_back(visEntry); + } + } + }); + + for (AzFramework::VisibilityEntry* visEntry : gatheredEntries) + { + AZ::Entity* entity = static_cast(visEntry->m_userData); + [[maybe_unused]] NetBindComponent* entryNetBindComponent = entity->template FindComponent(); + if (entryNetBindComponent != nullptr) + { + // TODO: invoke the sync to rewind event on the netBindComponent and add the entity to the rewound entity set + } + } + } + + void NetworkTime::ClearRewoundEntities() + { + AZ_Assert(!IsTimeRewound(), "Cannot clear rewound entity state while still within scoped rewind"); + // TODO: iterate all rewound entities, signal them to sync rewind state, and clear the rewound entity set + } } diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 06e758b349..47f557a11f 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -23,8 +23,8 @@ namespace Multiplayer : public INetworkTime { public: - NetworkTime(); - virtual ~NetworkTime(); + NetworkTime() = default; + virtual ~NetworkTime() = default; //! INetworkTime overrides. //! @{ @@ -33,10 +33,11 @@ namespace Multiplayer HostFrameId GetUnalteredHostFrameId() const override; void IncrementHostFrameId() override; AZ::TimeMs GetHostTimeMs() const override; - void SyncRewindableEntityState() override; AzNetworking::ConnectionId GetRewindingConnectionId() const override; HostFrameId GetHostFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const override; void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) override; + void SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) override; + void ClearRewoundEntities() override; //! @} private: diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl b/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl index 0835421ebd..2e67d42ede 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl +++ b/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl @@ -47,7 +47,7 @@ namespace Multiplayer template inline RewindableObject &RewindableObject::operator =(const RewindableObject& rhs) { - INetworkTime* networkTime = AZ::Interface::Get(); + INetworkTime* networkTime = GetNetworkTime(); SetValueForTime(rhs.GetValueForTime(networkTime->GetHostFrameId()), GetCurrentTimeForProperty()); return *this; } @@ -115,7 +115,7 @@ namespace Multiplayer template inline HostFrameId RewindableObject::GetCurrentTimeForProperty() const { - INetworkTime* networkTime = AZ::Interface::Get(); + INetworkTime* networkTime = GetNetworkTime(); return networkTime->GetHostFrameIdForRewindingConnection(m_owningConnectionId); } diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp index c54a610de2..a51bdc4acc 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp @@ -65,7 +65,7 @@ namespace Multiplayer { AZ::Entity* entity = m_controlledEntity.GetEntity(); AZ_Assert(entity, "Invalid controlled entity provided to replication window"); - m_controlledEntityTransform = entity->GetTransform(); + m_controlledEntityTransform = entity ? entity->GetTransform() : nullptr; AZ_Assert(m_controlledEntityTransform, "Controlled player entity must have a transform"); //// this one is optional diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h index 55a6a4b56e..b4e4427945 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include #include From 293e0057f4c0a74642e331dd052b3ae0d0468264 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 13:58:53 -0700 Subject: [PATCH 066/231] Actually invoke the override OnConnect handler --- Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 590faa6bad..15b6b48631 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -433,7 +433,8 @@ namespace Multiplayer if (m_onConnectFunctor) { - + // Default OnConnect behaviour has been overridden, + m_onConnectFunctor(connection, datum); } else { From 655d71e0ddfd69834537da5e2febd1f8a40fc59f Mon Sep 17 00:00:00 2001 From: greerdv Date: Wed, 12 May 2021 22:16:14 +0100 Subject: [PATCH 067/231] update compatibility of atom components with NonUniformScaleService --- .../Atom/Component/DebugCamera/CameraControllerComponent.h | 3 ++- .../Component/DebugCamera/Code/Source/CameraComponent.cpp | 1 + .../DebugCamera/Code/Source/CameraControllerComponent.cpp | 7 ++++++- .../AtomBridge/Code/Source/FlyCameraInputComponent.cpp | 6 ++++++ .../AtomBridge/Code/Source/FlyCameraInputComponent.h | 1 + .../Code/Source/Animation/AttachmentComponent.h | 1 + .../CoreLights/DirectionalLightComponentController.cpp | 1 + .../DiffuseProbeGridComponentController.cpp | 1 + .../ReflectionProbe/ReflectionProbeComponentController.cpp | 1 + .../Code/Source/SkyBox/HDRiSkyboxComponentController.cpp | 1 + .../Code/Source/SkyBox/PhysicalSkyComponentController.cpp | 1 + 11 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h b/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h index 4b2b19cff0..225952302a 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h +++ b/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h @@ -41,7 +41,8 @@ namespace AZ static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // CameraControllerRequestBus::Handler overrides void Enable(TypeId typeId) override final; void Reset() override final; diff --git a/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp b/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp index fbda0924e6..cbaa70929c 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp +++ b/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp @@ -69,6 +69,7 @@ namespace AZ void CameraComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("CameraService", 0x1dd1caa4)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CameraComponent::Activate() diff --git a/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp b/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp index 69e8469a56..e5a88dd409 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp +++ b/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp @@ -32,12 +32,17 @@ namespace AZ required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); required.push_back(AZ_CRC("CameraService", 0x1dd1caa4)); } - + void CameraControllerComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { provided.push_back(AZ_CRC("CameraControllerService", 0xc35788f9)); } + void CameraControllerComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void CameraControllerComponent::Enable(TypeId typeId) { // Enable this controller if type id matches, otherwise disable this controller diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp index 54e3a6ce59..3ad8bbae99 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp @@ -78,6 +78,12 @@ void FlyCameraInputComponent::GetProvidedServices(AZ::ComponentDescriptor::Depen provided.push_back(AZ_CRC("InputService", 0xd41af40c)); } +////////////////////////////////////////////////////////////////////////////// +void FlyCameraInputComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) +{ + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); +} + ////////////////////////////////////////////////////////////////////////////// void FlyCameraInputComponent::Reflect(AZ::ReflectContext* reflection) { diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h index 03fb3c421e..6c0232f358 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h @@ -30,6 +30,7 @@ namespace AZ public: static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); static void Reflect(AZ::ReflectContext* reflection); AZ_COMPONENT(FlyCameraInputComponent, "{7AE0D6AD-691C-41B6-9DD5-F23F78B1A02E}"); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h index ac03663f22..855c5494b3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h @@ -163,6 +163,7 @@ namespace AZ static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("AttachmentService", 0x5aaa7b63)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp index 310e6e6eca..6bff558268 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp @@ -121,6 +121,7 @@ namespace AZ void DirectionalLightComponentController::GetIncompatibleServices(ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("DirectionalLightService", 0x5270619f)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleComponent")); } void DirectionalLightComponentController::GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp index 8a0bd86965..0ddace1f87 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp @@ -73,6 +73,7 @@ namespace AZ void DiffuseProbeGridComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("DiffuseProbeGridService", 0x63d32042)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void DiffuseProbeGridComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp index 91040885f1..9b0ff29bb8 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp @@ -80,6 +80,7 @@ namespace AZ void ReflectionProbeComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("ReflectionProbeService", 0xa5b919ce)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void ReflectionProbeComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp index f343a68f79..2c44124564 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp @@ -51,6 +51,7 @@ namespace AZ void HDRiSkyboxComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("SkyBoxService", 0x8169a709)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void HDRiSkyboxComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp index 867a81eefe..4a6b1608a4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp @@ -58,6 +58,7 @@ namespace AZ void PhysicalSkyComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("SkyBoxService", 0x8169a709)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void PhysicalSkyComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) From 9a4884ff0bc1577a4947d3c835ec144e195d5a53 Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Wed, 12 May 2021 14:19:18 -0700 Subject: [PATCH 068/231] Exposing Multiplayer integral types (just wrapped ints) to bevahior context so that Network Properties using these type can be Get/Set from Script Canvas --- .../Code/Include/MultiplayerTypes.h | 11 ++++++++++ .../Source/AutoGen/AutoComponent_Source.jinja | 20 +++++++++++++++++++ .../Source/MultiplayerSystemComponent.cpp | 11 ++++++++++ 3 files changed, 42 insertions(+) diff --git a/Gems/Multiplayer/Code/Include/MultiplayerTypes.h b/Gems/Multiplayer/Code/Include/MultiplayerTypes.h index 1bee9867e3..e9f3865563 100644 --- a/Gems/Multiplayer/Code/Include/MultiplayerTypes.h +++ b/Gems/Multiplayer/Code/Include/MultiplayerTypes.h @@ -130,3 +130,14 @@ AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::PropertyIndex); AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::RpcIndex); AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::ClientInputId); AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::HostFrameId); + +namespace AZ +{ + AZ_TYPE_INFO_SPECIALIZE(Multiplayer::HostId, "{D04B3363-8E1B-4193-8B2B-D2140389C9D5}"); + AZ_TYPE_INFO_SPECIALIZE(Multiplayer::NetEntityId, "{05E4C08B-3A1B-4390-8144-3767D8E56A81}"); + AZ_TYPE_INFO_SPECIALIZE(Multiplayer::NetComponentId, "{8AF3B382-F187-4323-9014-B380638767E3}"); + AZ_TYPE_INFO_SPECIALIZE(Multiplayer::PropertyIndex, "{F4460210-024D-4B3B-A10A-04B669C34230}"); + AZ_TYPE_INFO_SPECIALIZE(Multiplayer::RpcIndex, "{EBB1C475-FA03-4111-8C84-985377434B9B}"); + AZ_TYPE_INFO_SPECIALIZE(Multiplayer::ClientInputId, "{35BF3504-CEC9-4406-A275-C633A17FBEFB}"); + AZ_TYPE_INFO_SPECIALIZE(Multiplayer::HostFrameId, "{DF17F6F3-48C6-4B4A-BBD9-37DA03162864}"); +} // namespace AZ diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 576978f75c..a3eef99b20 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -707,6 +707,26 @@ enum class NetworkProperties controller->Set{{ UpperFirst(Property.attrib['Name']) }}({{ LowerFirst(Property.attrib['Name']) }}); }) + ->Method("GetOn{{ UpperFirst(Property.attrib['Name']) }}ChangedEvent", [](AZ::EntityId id) -> AZ::Event<{{ Property.attrib['Type'] }}>* + { + AZ::Entity* entity = AZ::Interface::Get()->FindEntity(id); + if (!entity) + { + AZ_Warning("Network Property", false, "{{ ClassName }} GetOn{{ UpperFirst(Property.attrib['Name']) }}ChangedEvent 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']) }} 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; + } + + return &networkComponent->m_{{ LowerFirst(Property.attrib['Name']) }}Event; + }) + ->Attribute(AZ::Script::Attributes::AzEventDescription, AZ::BehaviorAzEventDescription{ "On {{ UpperFirst(Property.attrib['Name']) }} Changed Event", {"New {{ UpperFirst(Property.attrib['Name']) }}"} }) + {% endif %} {% endcall -%} {% endmacro %} diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index e6fb77eca7..9f45122c1d 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -78,6 +78,17 @@ namespace Multiplayer ->Version(1); } + if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) + { + behaviorContext->Class("HostId"); + behaviorContext->Class("NetEntityId"); + behaviorContext->Class("NetComponentId"); + behaviorContext->Class("PropertyIndex"); + behaviorContext->Class ("RpcIndex"); + behaviorContext->Class ("ClientInputId"); + behaviorContext->Class ("HostFrameId"); + } + MultiplayerComponent::Reflect(context); } From 9b1f4c04e65e8ae29053d1070eacc67a18be7768 Mon Sep 17 00:00:00 2001 From: mriegger Date: Wed, 12 May 2021 14:54:33 -0700 Subject: [PATCH 069/231] Removing the old hack code --- .../Code/Source/Decals/AsyncLoadTracker.h | 18 ++++++++++-------- .../DecalTextureArrayFeatureProcessor.cpp | 18 +++++------------- .../Decals/DecalTextureArrayFeatureProcessor.h | 3 --- 3 files changed, 15 insertions(+), 24 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h b/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h index ec35c4b51f..a3fff7b91e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h @@ -23,7 +23,9 @@ namespace AZ { public: - void TrackAssetLoad(const FeatureProcessorHandle handle, const AZ::Data::AssetId asset) + using MaterialAssetPtr = AZ::Data::Asset; + + void TrackAssetLoad(const FeatureProcessorHandle handle, const MaterialAssetPtr asset) { if (IsAssetLoading(handle)) { @@ -77,12 +79,12 @@ namespace AZ { const auto asset = EraseFromInFlightHandles(handle); - AZ_Assert(m_inFlightHandlesByAsset.count(asset) > 0, "AsyncLoadTracker in a bad state"); - auto& handleList = m_inFlightHandlesByAsset[asset]; + AZ_Assert(m_inFlightHandlesByAsset.count(asset.GetId()) > 0, "AsyncLoadTracker in a bad state"); + auto& handleList = m_inFlightHandlesByAsset[asset.GetId()]; EraseFromVector(handleList, handle); if (handleList.empty()) { - m_inFlightHandlesByAsset.erase(asset); + m_inFlightHandlesByAsset.erase(asset.GetId()); } } @@ -104,14 +106,14 @@ namespace AZ vec.pop_back(); } - void Add(const FeatureProcessorHandle handle, const AZ::Data::AssetId asset) + void Add(const FeatureProcessorHandle handle, const MaterialAssetPtr asset) { AZ_Assert(m_inFlightHandles.count(handle) == 0, "AsyncLoadTracker::Add() - told to add a handle that was already being tracked."); - m_inFlightHandlesByAsset[asset].push_back(handle); + m_inFlightHandlesByAsset[asset.GetId()].push_back(handle); m_inFlightHandles[handle] = asset; } - AZ::Data::AssetId EraseFromInFlightHandles(const FeatureProcessorHandle handle) + MaterialAssetPtr EraseFromInFlightHandles(const FeatureProcessorHandle handle) { const auto iter = m_inFlightHandles.find(handle); AZ_Assert(iter != m_inFlightHandles.end(), "Told to remove handle that was not present"); @@ -125,7 +127,7 @@ namespace AZ // Hash table that tracks the reverse of the m_inFlightHandlesByAsset hash table. // i.e. for each object, it stores what asset that it needs. - AZStd::unordered_map m_inFlightHandles; + AZStd::unordered_map m_inFlightHandles; }; } } diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp index 4000df646d..24857f8d65 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp @@ -85,7 +85,6 @@ namespace AZ m_decalData.Clear(); m_decalBufferHandler.Release(); - m_materialAssets.clear(); } DecalTextureArrayFeatureProcessor::DecalHandle DecalTextureArrayFeatureProcessor::AcquireDecal() @@ -410,7 +409,7 @@ namespace AZ int iter = m_textureArrayList.begin(); while (iter != -1) { - const auto packedTexture = m_textureArrayList[iter].second.GetPackedTexture(); + const auto& packedTexture = m_textureArrayList[iter].second.GetPackedTexture(); view->GetShaderResourceGroup()->SetImage(m_decalTextureArrayIndices[iter], packedTexture); iter = m_textureArrayList.next(iter); } @@ -482,22 +481,15 @@ namespace AZ return material; } - void DecalTextureArrayFeatureProcessor::QueueMaterialLoadForDecal(const AZ::Data::AssetId material, const DecalHandle handle) + void DecalTextureArrayFeatureProcessor::QueueMaterialLoadForDecal(const AZ::Data::AssetId materialId, const DecalHandle handle) { - // Note that another decal might have already queued this material for loading - if (m_materialLoadTracker.IsAssetLoading(material)) - { - m_materialLoadTracker.TrackAssetLoad(handle, material); - return; - } + const auto materialAsset = QueueMaterialAssetLoad(materialId); - const auto materialAsset = QueueMaterialAssetLoad(material); - m_materialAssets.emplace(material, materialAsset); - m_materialLoadTracker.TrackAssetLoad(handle, material); + m_materialLoadTracker.TrackAssetLoad(handle, materialAsset); if (materialAsset.IsLoading()) { - AZ::Data::AssetBus::MultiHandler::BusConnect(material); + AZ::Data::AssetBus::MultiHandler::BusConnect(materialId); } else if (materialAsset.IsReady()) { diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h index 825e461fc2..5301fcc61b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h @@ -136,11 +136,8 @@ namespace AZ GpuBufferHandler m_decalBufferHandler; AsyncLoadTracker m_materialLoadTracker; - AZStd::unordered_map< AZ::Data::AssetId, DecalLocationAndUseCount> m_materialToTextureArrayLookupTable; - AZStd::unordered_map> m_materialAssets; - bool m_deviceBufferNeedsUpdate = false; }; } // namespace Render From 84216f04793e17c923b744e2531c3e7d0feca27d Mon Sep 17 00:00:00 2001 From: nvsickle Date: Wed, 12 May 2021 15:58:28 -0700 Subject: [PATCH 070/231] Add API for ViewportInfoDisplayState, add some minor RHI integration --- .../Code/CMakeLists.txt | 2 + .../AtomViewportInfoDisplayBus.h | 61 ++++++++++ ...AtomViewportDisplayInfoSystemComponent.cpp | 107 +++++++++++++----- .../AtomViewportDisplayInfoSystemComponent.h | 14 +-- 4 files changed, 150 insertions(+), 34 deletions(-) create mode 100644 Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Include/AtomLyIntegration/AtomViewportDisplayInfo/AtomViewportInfoDisplayBus.h diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt index 395cc22d47..de4ee9b4b5 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/CMakeLists.txt @@ -17,6 +17,8 @@ ly_add_target( INCLUDE_DIRECTORIES PRIVATE Source + PUBLIC + Include BUILD_DEPENDENCIES PRIVATE AZ::AzCore diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Include/AtomLyIntegration/AtomViewportDisplayInfo/AtomViewportInfoDisplayBus.h b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Include/AtomLyIntegration/AtomViewportDisplayInfo/AtomViewportInfoDisplayBus.h new file mode 100644 index 0000000000..ae9359d9d3 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Include/AtomLyIntegration/AtomViewportDisplayInfo/AtomViewportInfoDisplayBus.h @@ -0,0 +1,61 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or 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 AtomBridge + { + //! The level of information to display in the viewport info display overlay. + enum class ViewportInfoDisplayState : int + { + NoInfo = 0, + NormalInfo = 1, + FullInfo = 2, + CompactInfo = 3, + Invalid + }; + + //! This bus is used to request changes to the viewport info display overlay. + class AtomViewportInfoDisplayRequests + : public AZ::EBusTraits + { + public: + static const AZ::EBusHandlerPolicy HandlerPolicy = EBusHandlerPolicy::Single; + static const AZ::EBusAddressPolicy AddressPolicy = EBusAddressPolicy::Single; + + //! Gets the current viewport info overlay state. + virtual ViewportInfoDisplayState GetDisplayState() const = 0; + //! Sets the current viewport info overlay state. + //! The overlay will be drawn to the default viewport context every frame, if enabled. + virtual void SetDisplayState(ViewportInfoDisplayState state) = 0; + }; + + using AtomViewportInfoDisplayRequestBus = AZ::EBus; + + //! This bus is used to listen for state changes in the viewport info display overlay. + class AtomViewportInfoDisplayNotifications + : public AZ::EBusTraits + { + public: + static const AZ::EBusHandlerPolicy HandlerPolicy = EBusHandlerPolicy::Multiple; + static const AZ::EBusAddressPolicy AddressPolicy = EBusAddressPolicy::Single; + + //! Called when the ViewportInfoDisplayState (via the r_displayInfo CVar) has changed. + virtual void OnViewportInfoDisplayStateChanged([[maybe_unused]]ViewportInfoDisplayState state){} + }; + + using AtomViewportInfoDisplayNotificationBus = AZ::EBus; + } +} diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp index 394923071e..c9128c001f 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp @@ -21,21 +21,30 @@ #include #include #include +#include #include #include #include #include -AZ_CVAR(float, r_fpsInterval, 1.0f, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, - "The time period over which to calculate the framerate for r_displayInfo"); - namespace AZ::Render { - static constexpr int DisplayInfoLevelNone = 0; - static constexpr int DisplayInfoLevelNormal = 1; - static constexpr int DisplayInfoLevelFull = 2; - static constexpr int DisplayInfoLevelCompact = 3; + AZ_CVAR(int, r_displayInfo, 1, [](const int& newDisplayInfoVal)->void + { + // Forward this event to the system component so it can update accordingly. + // This callback only gets triggered by console commands, so this will not recurse. + AtomBridge::AtomViewportInfoDisplayRequestBus::Broadcast( + &AtomBridge::AtomViewportInfoDisplayRequestBus::Events::SetDisplayState, + static_cast(newDisplayInfoVal) + ); + }, AZ::ConsoleFunctorFlags::DontReplicate, + "Toggles debugging information display.\n" + "Usage: r_displayInfo [0=off/1=show/2=enhanced/3=compact]" + ); + AZ_CVAR(float, r_fpsCalcInterval, 1.0f, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, + "The time period over which to calculate the framerate for r_displayInfo." + ); void AtomViewportDisplayInfoSystemComponent::Reflect(AZ::ReflectContext* context) { @@ -47,7 +56,7 @@ namespace AZ::Render if (AZ::EditContext* ec = serialize->GetEditContext()) { - ec->Class("Viewport Display Info", "Manages debug viewport information through r_DisplayInfo") + ec->Class("Viewport Display Info", "Manages debug viewport information through r_displayInfo") ->ClassElement(Edit::ClassElements::EditorData, "") ->Attribute(Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) ->Attribute(Edit::Attributes::AutoExpand, true) @@ -83,15 +92,15 @@ namespace AZ::Render m_rendererDescription = AZStd::string::format("Atom using %s RHI", apiName.GetCStr()); } - CrySystemEventBus::Handler::BusConnect(); AZ::RPI::ViewportContextNotificationBus::Handler::BusConnect( AZ::RPI::ViewportContextRequests::Get()->GetDefaultViewportContextName()); + AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Handler::BusConnect(); } void AtomViewportDisplayInfoSystemComponent::Deactivate() { + AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Handler::BusDisconnect(); AZ::RPI::ViewportContextNotificationBus::Handler::BusDisconnect(); - CrySystemEventBus::Handler::BusDisconnect(); } AZ::RPI::ViewportContextPtr AtomViewportDisplayInfoSystemComponent::GetViewportContext() const @@ -111,8 +120,13 @@ namespace AZ::Render void AtomViewportDisplayInfoSystemComponent::OnRenderTick() { + auto fontQueryInterface = AZ::Interface::Get(); + if (!fontQueryInterface) + { + return; + } AzFramework::FontDrawInterface* fontDrawInterface = - AZ::Interface::Get()->GetDefaultFontDrawInterface(); + fontQueryInterface->GetDefaultFontDrawInterface(); AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); if (!fontDrawInterface || !viewportContext || !viewportContext->GetRenderScene()) @@ -120,18 +134,23 @@ namespace AZ::Render return; } - m_fpsInterval = AZStd::chrono::seconds(r_fpsInterval); + m_fpsInterval = AZStd::chrono::seconds(r_fpsCalcInterval); UpdateFramerate(); - if (!m_displayInfoCVar) + const AtomBridge::ViewportInfoDisplayState displayLevel = GetDisplayState(); + if (displayLevel == AtomBridge::ViewportInfoDisplayState::NoInfo) { return; } - int displayLevel = m_displayInfoCVar->GetIVal(); - if (displayLevel == DisplayInfoLevelNone) + + if (m_updateRootPassQuery) { - return; + if (auto rootPass = AZ::RPI::PassSystemInterface::Get()->GetRootPass()) + { + rootPass->SetPipelineStatisticsQueryEnabled(displayLevel == AtomBridge::ViewportInfoDisplayState::FullInfo); + m_updateRootPassQuery = false; + } } m_drawParams.m_drawViewportId = viewportContext->GetId(); @@ -152,22 +171,30 @@ namespace AZ::Render m_lineSpacing = lineHeight * m_drawParams.m_lineSpacing; DrawRendererInfo(); - if (displayLevel != DisplayInfoLevelCompact) + if (displayLevel == AtomBridge::ViewportInfoDisplayState::FullInfo) { DrawCameraInfo(); + DrawPassInfo(); + } + if (displayLevel != AtomBridge::ViewportInfoDisplayState::CompactInfo) + { DrawMemoryInfo(); } DrawFramerate(); } - void AtomViewportDisplayInfoSystemComponent::OnCrySystemInitialized(ISystem& system, [[maybe_unused]]const SSystemInitParams& initParams) + AtomBridge::ViewportInfoDisplayState AtomViewportDisplayInfoSystemComponent::GetDisplayState() const { - m_displayInfoCVar = system.GetGlobalEnvironment()->pConsole->GetCVar("r_DisplayInfo"); + return static_cast(r_displayInfo.operator int()); } - void AtomViewportDisplayInfoSystemComponent::OnCrySystemShutdown([[maybe_unused]]ISystem& system) + void AtomViewportDisplayInfoSystemComponent::SetDisplayState(AtomBridge::ViewportInfoDisplayState state) { - m_displayInfoCVar = nullptr; + r_displayInfo = static_cast(state); + AtomBridge::AtomViewportInfoDisplayNotificationBus::Broadcast( + &AtomBridge::AtomViewportInfoDisplayNotificationBus::Events::OnViewportInfoDisplayStateChanged, + state); + m_updateRootPassQuery = true; } void AtomViewportDisplayInfoSystemComponent::DrawRendererInfo() @@ -198,6 +225,31 @@ namespace AZ::Render )); } + void AtomViewportDisplayInfoSystemComponent::DrawPassInfo() + { + auto rootPass = AZ::RPI::PassSystemInterface::Get()->GetRootPass(); + const RPI::PipelineStatisticsResult stats = rootPass->GetLatestPipelineStatisticsResult(); + AZStd::function)> containingPassCount = [&containingPassCount](const AZ::RPI::Ptr pass) + { + int count = 1; + if (auto passAsParent = pass->AsParent()) + { + for (const auto child : passAsParent->GetChildren()) + { + count += containingPassCount(child); + } + } + return count; + }; + const int numPasses = containingPassCount(rootPass); + DrawLine(AZStd::string::format( + "Total Passes: %d Vertex Count: %d Primitive Count: %d", + numPasses, + stats.m_vertexCount, + stats.m_primitiveCount + )); + } + void AtomViewportDisplayInfoSystemComponent::DrawMemoryInfo() { static IMemoryManager::SProcessMemInfo processMemInfo; @@ -236,11 +288,16 @@ namespace AZ::Render AZ::ScriptTimePoint currentTime = m_tickRequests->GetTimeAtCurrentTick(); // Only keep as much sampling data is is required by our FPS history. - while (!m_fpsHistory.empty() && (currentTime.Get() - m_fpsHistory.front().Get() > m_fpsInterval)) + while (!m_fpsHistory.empty() && (currentTime.Get() - m_fpsHistory.front().Get()) > m_fpsInterval) { m_fpsHistory.pop_front(); } - m_fpsHistory.push_back(currentTime); + + // Discard entries with a zero time-delta (can happen when we don't have window focus). + if (m_fpsHistory.empty() || (currentTime.Get() - m_fpsHistory.back().Get()) != AZStd::chrono::seconds(0)) + { + m_fpsHistory.push_back(currentTime); + } } void AtomViewportDisplayInfoSystemComponent::DrawFramerate() @@ -254,10 +311,6 @@ namespace AZ::Render if (lastTime.has_value()) { AZStd::chrono::duration deltaTime = time.Get() - lastTime.value().Get(); - if (deltaTime.count() == 0.0) - { - continue; - } double fps = AZStd::chrono::seconds(1) / deltaTime; if (!minFPS.has_value()) { diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h index 5cb6ed3308..ac6c2bab65 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h @@ -19,8 +19,7 @@ #include #include #include - -struct ICVar; +#include namespace AZ { @@ -31,7 +30,7 @@ namespace AZ class AtomViewportDisplayInfoSystemComponent : public AZ::Component , public AZ::RPI::ViewportContextNotificationBus::Handler - , public CrySystemEventBus::Handler + , public AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Handler { public: AZ_COMPONENT(AtomViewportDisplayInfoSystemComponent, "{AC32F173-E7E2-4943-8E6C-7C3091978221}"); @@ -51,9 +50,9 @@ namespace AZ // AZ::RPI::ViewportContextNotificationBus::Handler overrides... void OnRenderTick() override; - // CrySystemEventBus::Handler overrides... - void OnCrySystemInitialized(ISystem& system, const SSystemInitParams& initParams) override; - void OnCrySystemShutdown(ISystem& system) override; + // AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Handler overrides... + AtomBridge::ViewportInfoDisplayState GetDisplayState() const override; + void SetDisplayState(AtomBridge::ViewportInfoDisplayState state) override; private: AZ::RPI::ViewportContextPtr GetViewportContext() const; @@ -63,6 +62,7 @@ namespace AZ void DrawRendererInfo(); void DrawCameraInfo(); + void DrawPassInfo(); void DrawMemoryInfo(); void DrawFramerate(); @@ -73,7 +73,7 @@ namespace AZ AZStd::deque m_fpsHistory; AZStd::optional m_lastMemoryUpdate; AZ::TickRequests* m_tickRequests = nullptr; - ICVar* m_displayInfoCVar = nullptr; + bool m_updateRootPassQuery = true; }; } // namespace Render } // namespace AZ From cb09d542d1207e437dfca27b68cd2133776c78f9 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Wed, 12 May 2021 15:59:21 -0700 Subject: [PATCH 071/231] Use the new Atom API instead of the removed r_displayInfo for ViewportTitleDlg --- Code/Sandbox/Editor/CMakeLists.txt | 1 + Code/Sandbox/Editor/ViewportTitleDlg.cpp | 75 ++++++++++++++++++++---- Code/Sandbox/Editor/ViewportTitleDlg.h | 4 +- 3 files changed, 64 insertions(+), 16 deletions(-) diff --git a/Code/Sandbox/Editor/CMakeLists.txt b/Code/Sandbox/Editor/CMakeLists.txt index 7d89717391..2be48777d3 100644 --- a/Code/Sandbox/Editor/CMakeLists.txt +++ b/Code/Sandbox/Editor/CMakeLists.txt @@ -124,6 +124,7 @@ ly_add_target( Gem::Atom_RPI.Public Gem::Atom_Feature_Common.Static Gem::AtomToolsFramework.Static + Gem::AtomViewportDisplayInfo ${additional_dependencies} PUBLIC 3rdParty::AWSNativeSDK::Core diff --git a/Code/Sandbox/Editor/ViewportTitleDlg.cpp b/Code/Sandbox/Editor/ViewportTitleDlg.cpp index 95531e117c..159fccfd64 100644 --- a/Code/Sandbox/Editor/ViewportTitleDlg.cpp +++ b/Code/Sandbox/Editor/ViewportTitleDlg.cpp @@ -13,7 +13,7 @@ // Description : CViewportTitleDlg implementation file - +#if !defined(Q_MOC_RUN) #include "EditorDefs.h" #include "ViewportTitleDlg.h" @@ -36,10 +36,13 @@ #include "UsedResources.h" #include "Include/IObjectManager.h" +#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 @@ -63,6 +66,32 @@ inline namespace Helpers } } +namespace +{ + class CViewportTitleDlgDisplayInfoHelper + : public QObject + , public AZ::AtomBridge::AtomViewportInfoDisplayNotificationBus::Handler + { + Q_OBJECT + + public: + CViewportTitleDlgDisplayInfoHelper(CViewportTitleDlg* parent) + : QObject(parent) + { + AZ::AtomBridge::AtomViewportInfoDisplayNotificationBus::Handler::BusConnect(); + } + + signals: + void ViewportInfoStatusUpdated(int newIndex); + + private: + void OnViewportInfoDisplayStateChanged(AZ::AtomBridge::ViewportInfoDisplayState state) + { + emit ViewportInfoStatusUpdated(static_cast(state)); + } + }; +} //end anonymous namespace + CViewportTitleDlg::CViewportTitleDlg(QWidget* pParent) : QWidget(pParent) , m_ui(new Ui::ViewportTitleDlg) @@ -115,14 +144,11 @@ void CViewportTitleDlg::OnInitDialog() m_ui->m_toggleHelpersBtn->setChecked(GetIEditor()->GetDisplaySettings()->IsDisplayHelpers()); - ICVar* pDisplayInfo(gEnv->pConsole->GetCVar("r_displayInfo")); - if (pDisplayInfo) - { - SFunctor oFunctor; - oFunctor.Set(OnChangedDisplayInfo, pDisplayInfo, m_ui->m_toggleDisplayInfoBtn); - m_displayInfoCallbackIndex = pDisplayInfo->AddOnChangeFunctor(oFunctor); - OnChangedDisplayInfo(pDisplayInfo, m_ui->m_toggleDisplayInfoBtn); - } + + // 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); @@ -156,6 +182,32 @@ void CViewportTitleDlg::OnToggleHelpers() ////////////////////////////////////////////////////////////////////////// void CViewportTitleDlg::OnToggleDisplayInfo() { + AZ::AtomBridge::ViewportInfoDisplayState state = AZ::AtomBridge::ViewportInfoDisplayState::NoInfo; + AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::BroadcastResult( + state, + &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::GetDisplayState + ); + state = static_cast(static_cast(state)+1); + if (state == AZ::AtomBridge::ViewportInfoDisplayState::Invalid) + { + state = AZ::AtomBridge::ViewportInfoDisplayState::NoInfo; + } + // 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); } ////////////////////////////////////////////////////////////////////////// @@ -544,10 +596,6 @@ void CViewportTitleDlg::UpdateCustomPresets(const QString& text, QStringList& cu } } -void CViewportTitleDlg::OnChangedDisplayInfo([[maybe_unused]] ICVar* pDisplayInfo, [[maybe_unused]] QAbstractButton* pDisplayInfoButton) -{ -} - bool CViewportTitleDlg::eventFilter(QObject* object, QEvent* event) { bool consumeEvent = false; @@ -609,4 +657,5 @@ namespace AzToolsFramework } } +#include "ViewportTitleDlg.moc" #include diff --git a/Code/Sandbox/Editor/ViewportTitleDlg.h b/Code/Sandbox/Editor/ViewportTitleDlg.h index 55741636b3..ce2f116d97 100644 --- a/Code/Sandbox/Editor/ViewportTitleDlg.h +++ b/Code/Sandbox/Editor/ViewportTitleDlg.h @@ -60,7 +60,6 @@ public: static void LoadCustomPresets(const QString& section, const QString& keyName, QStringList& outCustompresets); static void SaveCustomPresets(const QString& section, const QString& keyName, const QStringList& custompresets); static void UpdateCustomPresets(const QString& text, QStringList& custompresets); - static void OnChangedDisplayInfo(ICVar* pDisplayInfo, QAbstractButton* pDisplayInfoButton); bool eventFilter(QObject* object, QEvent* event) override; @@ -77,6 +76,7 @@ protected: void OnMaximize(); void OnToggleHelpers(); void OnToggleDisplayInfo(); + void UpdateDisplayInfo(); QString m_title; @@ -87,8 +87,6 @@ protected: QStringList m_customFOVPresets; QStringList m_customAspectRatioPresets; - uint64 m_displayInfoCallbackIndex; - void OnMenuFOVCustom(); void CreateFOVMenu(); From 254ad165c15b3d433b852cb05a06f563ccb4fff4 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 16:01:59 -0700 Subject: [PATCH 072/231] A bunch of work to get external multiplayer components to actually work --- .../{ => Multiplayer}/IConnectionData.h | 2 +- .../Include/{ => Multiplayer}/IEntityDomain.h | 2 +- .../Include/{ => Multiplayer}/IMultiplayer.h | 6 +-- .../IMultiplayerComponentInput.h | 2 +- .../{ => Multiplayer}/INetworkEntityManager.h | 4 +- .../Multiplayer/INetworkPlayerSpawner.h | 0 .../Include/{ => Multiplayer}/INetworkTime.h | 2 +- .../{ => Multiplayer}/IReplicationWindow.h | 4 +- .../Multiplayer}/MultiplayerComponent.h | 6 +-- .../MultiplayerComponentRegistry.h | 2 +- .../Multiplayer}/MultiplayerController.h | 8 +--- .../{ => Multiplayer}/MultiplayerStats.cpp | 2 +- .../{ => Multiplayer}/MultiplayerStats.h | 2 +- .../{ => Multiplayer}/MultiplayerTypes.h | 0 .../Multiplayer}/NetBindComponent.h | 11 ++--- .../{ => Multiplayer}/NetworkEntityHandle.h | 4 +- .../{ => Multiplayer}/NetworkEntityHandle.inl | 0 .../Multiplayer}/NetworkEntityRpcMessage.h | 2 +- .../Multiplayer}/NetworkEntityUpdateMessage.h | 2 +- .../Multiplayer}/NetworkInput.h | 6 +-- .../Multiplayer}/ReplicationRecord.h | 2 +- .../Multiplayer}/RewindableObject.h | 4 +- .../Multiplayer}/RewindableObject.inl | 0 .../AutoGen/AutoComponentTypes_Header.jinja | 2 +- .../AutoGen/AutoComponentTypes_Source.jinja | 8 ++-- .../Source/AutoGen/AutoComponent_Header.jinja | 26 +++++------ .../Source/AutoGen/AutoComponent_Source.jinja | 10 ++-- ...tionPlayerInputComponent.AutoComponent.xml | 4 +- .../AutoGen/Multiplayer.AutoPackets.xml | 8 ++-- ...etworkTransformComponent.AutoComponent.xml | 2 +- .../LocalPredictionPlayerInputComponent.h | 2 +- .../Components/MultiplayerComponent.cpp | 4 +- .../MultiplayerComponentRegistry.cpp | 2 +- .../Components/MultiplayerController.cpp | 6 +-- .../Source/Components/NetBindComponent.cpp | 29 +++--------- .../ClientToServerConnectionData.h | 2 +- .../ServerToClientConnectionData.h | 2 +- .../EntityDomains/FullOwnershipEntityDomain.h | 2 +- .../Code/Source/MultiplayerGem.cpp | 2 +- .../Source/MultiplayerSystemComponent.cpp | 2 +- .../Code/Source/MultiplayerSystemComponent.h | 2 +- .../EntityReplicationManager.cpp | 14 +++--- .../EntityReplicationManager.h | 10 ++-- .../EntityReplication/EntityReplicator.cpp | 6 +-- .../EntityReplication/EntityReplicator.h | 4 +- .../EntityReplication/PropertyPublisher.h | 2 +- .../EntityReplication/PropertySubscriber.cpp | 2 +- .../EntityReplication/ReplicationRecord.cpp | 2 +- .../NetworkEntityAuthorityTracker.cpp | 4 +- .../NetworkEntity/NetworkEntityHandle.cpp | 8 ++-- .../NetworkEntity/NetworkEntityManager.cpp | 5 +- .../NetworkEntity/NetworkEntityManager.h | 8 ++-- .../NetworkEntity/NetworkEntityRpcMessage.cpp | 2 +- .../NetworkEntity/NetworkEntityTracker.cpp | 2 +- .../NetworkEntity/NetworkEntityTracker.h | 4 +- .../NetworkEntityUpdateMessage.cpp | 2 +- .../Code/Source/NetworkInput/NetworkInput.cpp | 4 +- .../Source/NetworkInput/NetworkInputArray.cpp | 2 +- .../Source/NetworkInput/NetworkInputArray.h | 4 +- .../Source/NetworkInput/NetworkInputChild.cpp | 2 +- .../Source/NetworkInput/NetworkInputChild.h | 2 +- .../Source/NetworkInput/NetworkInputHistory.h | 2 +- .../NetworkInputMigrationVector.cpp | 2 +- .../NetworkInputMigrationVector.h | 4 +- .../Code/Source/NetworkTime/NetworkTime.cpp | 4 +- .../Code/Source/NetworkTime/NetworkTime.h | 2 +- .../NullReplicationWindow.h | 2 +- .../ServerToClientReplicationWindow.cpp | 2 +- .../ServerToClientReplicationWindow.h | 6 +-- Gems/Multiplayer/Code/multiplayer_files.cmake | 46 +++++++++---------- 70 files changed, 162 insertions(+), 185 deletions(-) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IConnectionData.h (97%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IEntityDomain.h (97%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IMultiplayer.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IMultiplayerComponentInput.h (96%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/INetworkEntityManager.h (98%) create mode 100644 Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/INetworkTime.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IReplicationWindow.h (94%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/MultiplayerComponent.h (97%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/MultiplayerComponentRegistry.h (98%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/MultiplayerController.h (90%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/MultiplayerStats.cpp (99%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/MultiplayerStats.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/MultiplayerTypes.h (100%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/NetBindComponent.h (95%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/NetworkEntityHandle.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/NetworkEntityHandle.inl (100%) rename Gems/Multiplayer/Code/{Source/NetworkEntity => Include/Multiplayer}/NetworkEntityRpcMessage.h (99%) rename Gems/Multiplayer/Code/{Source/NetworkEntity => Include/Multiplayer}/NetworkEntityUpdateMessage.h (99%) rename Gems/Multiplayer/Code/{Source/NetworkInput => Include/Multiplayer}/NetworkInput.h (95%) rename Gems/Multiplayer/Code/{Source/NetworkEntity/EntityReplication => Include/Multiplayer}/ReplicationRecord.h (98%) rename Gems/Multiplayer/Code/{Source/NetworkTime => Include/Multiplayer}/RewindableObject.h (98%) rename Gems/Multiplayer/Code/{Source/NetworkTime => Include/Multiplayer}/RewindableObject.inl (100%) diff --git a/Gems/Multiplayer/Code/Include/IConnectionData.h b/Gems/Multiplayer/Code/Include/Multiplayer/IConnectionData.h similarity index 97% rename from Gems/Multiplayer/Code/Include/IConnectionData.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IConnectionData.h index dcc2c940ef..39fdb61435 100644 --- a/Gems/Multiplayer/Code/Include/IConnectionData.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IConnectionData.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Include/IEntityDomain.h b/Gems/Multiplayer/Code/Include/Multiplayer/IEntityDomain.h similarity index 97% rename from Gems/Multiplayer/Code/Include/IEntityDomain.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IEntityDomain.h index 6571797d05..70215612b0 100644 --- a/Gems/Multiplayer/Code/Include/IEntityDomain.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IEntityDomain.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Include/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h similarity index 98% rename from Gems/Multiplayer/Code/Include/IMultiplayer.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index 80bdaa68eb..665661b55b 100644 --- a/Gems/Multiplayer/Code/Include/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -15,9 +15,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include namespace AzNetworking { diff --git a/Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerComponentInput.h similarity index 96% rename from Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerComponentInput.h index b5df01a1a8..b26feadc4f 100644 --- a/Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerComponentInput.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkEntityManager.h similarity index 98% rename from Gems/Multiplayer/Code/Include/INetworkEntityManager.h rename to Gems/Multiplayer/Code/Include/Multiplayer/INetworkEntityManager.h index ebb95e2281..17224e64cb 100644 --- a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkEntityManager.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Gems/Multiplayer/Code/Include/INetworkTime.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h similarity index 98% rename from Gems/Multiplayer/Code/Include/INetworkTime.h rename to Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h index 1ccf08bbdc..c228e135ee 100644 --- a/Gems/Multiplayer/Code/Include/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h @@ -14,7 +14,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Include/IReplicationWindow.h b/Gems/Multiplayer/Code/Include/Multiplayer/IReplicationWindow.h similarity index 94% rename from Gems/Multiplayer/Code/Include/IReplicationWindow.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IReplicationWindow.h index eb34a2f87d..d0192e8aa4 100644 --- a/Gems/Multiplayer/Code/Include/IReplicationWindow.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IReplicationWindow.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponent.h similarity index 97% rename from Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponent.h index 0f64221dde..29348a698a 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponent.h @@ -15,9 +15,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include //! Macro to declare bindings for a multiplayer component inheriting from MultiplayerComponent #define AZ_MULTIPLAYER_COMPONENT(ComponentClass, Guid, Base) \ diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponentRegistry.h similarity index 98% rename from Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponentRegistry.h index e16f942100..d06362ed4b 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponentRegistry.h @@ -14,7 +14,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerController.h similarity index 90% rename from Gems/Multiplayer/Code/Source/Components/MultiplayerController.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerController.h index de07e39e66..89c47c40d4 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerController.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer @@ -84,12 +84,6 @@ namespace Multiplayer //! Returns the input priority ordering for determining the order of ProcessInput or CreateInput functions. virtual InputPriorityOrder GetInputOrder() const = 0; - //! Queries the rewind system to determine what volume is relevent for a given input, this is very important for performance at scale. - //! @param networkInput input structure to process - //! @param deltaTime amount of time the provided input would be integrated over - //! @return a world-space aabb representing the volume relevent to the provided input - virtual AZ::Aabb GetRewindBoundsForInput(const NetworkInput& networkInput, float deltaTime) const = 0; - //! Base execution for ProcessInput packet, do not call directly. //! @param networkInput input structure to process //! @param deltaTime amount of time to integrate the provided inputs over diff --git a/Gems/Multiplayer/Code/Include/MultiplayerStats.cpp b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.cpp similarity index 99% rename from Gems/Multiplayer/Code/Include/MultiplayerStats.cpp rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.cpp index 7672997ad5..1f063b749d 100644 --- a/Gems/Multiplayer/Code/Include/MultiplayerStats.cpp +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.cpp @@ -10,7 +10,7 @@ * */ -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Include/MultiplayerStats.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h similarity index 98% rename from Gems/Multiplayer/Code/Include/MultiplayerStats.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h index dc266a14bf..5d00c4d205 100644 --- a/Gems/Multiplayer/Code/Include/MultiplayerStats.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace AzNetworking { diff --git a/Gems/Multiplayer/Code/Include/MultiplayerTypes.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h similarity index 100% rename from Gems/Multiplayer/Code/Include/MultiplayerTypes.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetBindComponent.h similarity index 95% rename from Gems/Multiplayer/Code/Source/Components/NetBindComponent.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetBindComponent.h index 0885e44aa4..464333e3b2 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetBindComponent.h @@ -20,11 +20,11 @@ #include #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include namespace Multiplayer @@ -73,7 +73,6 @@ namespace Multiplayer bool IsProcessingInput() const; void CreateInput(NetworkInput& networkInput, float deltaTime); void ProcessInput(NetworkInput& networkInput, float deltaTime); - AZ::Aabb GetRewindBoundsForInput(const NetworkInput& networkInput, float deltaTime) const; bool HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetEntityRole remoteRole, NetworkEntityRpcMessage& message); bool HandlePropertyChangeMessage(AzNetworking::ISerializer& serializer, bool notifyChanges = true); diff --git a/Gems/Multiplayer/Code/Include/NetworkEntityHandle.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.h similarity index 98% rename from Gems/Multiplayer/Code/Include/NetworkEntityHandle.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.h index 9b8546ef2c..813589fac6 100644 --- a/Gems/Multiplayer/Code/Include/NetworkEntityHandle.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.h @@ -13,7 +13,7 @@ #pragma once #include -#include +#include namespace Multiplayer { @@ -138,4 +138,4 @@ namespace Multiplayer }; } -#include +#include diff --git a/Gems/Multiplayer/Code/Include/NetworkEntityHandle.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.inl similarity index 100% rename from Gems/Multiplayer/Code/Include/NetworkEntityHandle.inl rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.inl diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityRpcMessage.h similarity index 99% rename from Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityRpcMessage.h index 08b1960172..f6a7ff2c65 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityRpcMessage.h @@ -14,7 +14,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityUpdateMessage.h similarity index 99% rename from Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityUpdateMessage.h index 9ca539d75d..e96191262a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityUpdateMessage.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput.h similarity index 95% rename from Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput.h index b2b0fa12c6..9c6d2ce66a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput.h @@ -12,9 +12,9 @@ #pragma once -#include -#include -#include +#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.h b/Gems/Multiplayer/Code/Include/Multiplayer/ReplicationRecord.h similarity index 98% rename from Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.h rename to Gems/Multiplayer/Code/Include/Multiplayer/ReplicationRecord.h index 83721a5539..f6eb93c4ba 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/ReplicationRecord.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.h similarity index 98% rename from Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h rename to Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.h index 4e830d4480..9e1655aec7 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include #include @@ -115,4 +115,4 @@ namespace AZ AZ_TYPE_INFO_TEMPLATE(Multiplayer::RewindableObject, "{B2937B44-FEE1-4277-B1E0-863DE76D363F}", AZ_TYPE_INFO_TYPENAME, AZ_TYPE_INFO_AUTO); } -#include +#include diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl similarity index 100% rename from Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl rename to Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja index fc2860ebe7..849b4245e2 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja @@ -1,7 +1,7 @@ #pragma once #include -#include +#include namespace AZ { diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja index 2acc252729..453d74c907 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja @@ -1,6 +1,6 @@ #include -#include -#include +#include +#include {% for Component in dataFiles %} {% set ComponentDerived = Component.attrib['OverrideComponent']|booleanTrue %} {% set ControllerDerived = Component.attrib['OverrideController']|booleanTrue %} @@ -21,8 +21,8 @@ namespace {{ Namespace }} { void RegisterMultiplayerComponents() { - Multiplayer::MultiplayerComponentRegistry* multiplayerComponentRegistry = GetMultiplayerComponentRegistry(); - Multiplayer::MultiplayerStats& stats = GetMultiplayer()->GetStats(); + Multiplayer::MultiplayerComponentRegistry* multiplayerComponentRegistry = Multiplayer::GetMultiplayerComponentRegistry(); + Multiplayer::MultiplayerStats& stats = Multiplayer::GetMultiplayer()->GetStats(); {% for Component in dataFiles %} {% set ComponentName = Component.attrib['Name'] %} {% set ComponentBaseName = ComponentName %} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index faaa009e34..c22945c983 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -221,13 +221,14 @@ AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] } #include #include #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include {% call(Include) AutoComponentMacros.ParseIncludes(Component) %} #include <{{ Include.attrib['File'] }}> {% endcall %} @@ -359,7 +360,6 @@ namespace {{ Component.attrib['Namespace'] }} //! MultiplayerController interface //! @{ Multiplayer::MultiplayerController::InputPriorityOrder GetInputOrder() const override { return Multiplayer::MultiplayerController::InputPriorityOrder::Default; } - AZ::Aabb GetRewindBoundsForInput([[maybe_unused]] const NetworkInput& networkInput, [[maybe_unused]] float deltaTime) const override { return AZ::Aabb::CreateNull(); } void CreateInput([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) override {} void ProcessInput([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) override {} //! @} @@ -434,12 +434,12 @@ namespace {{ Component.attrib['Namespace'] }} //! MultiplayerComponent interface //! @{ - NetComponentId GetNetComponentId() const override; + Multiplayer::NetComponentId GetNetComponentId() const override; bool HandleRpcMessage(AzNetworking::IConnection* invokingConnection, Multiplayer::NetEntityRole remoteRole, Multiplayer::NetworkEntityRpcMessage& rpcMessage) override; bool SerializeStateDeltaMessage(Multiplayer::ReplicationRecord& replicationRecord, AzNetworking::ISerializer& serializer) override; void NotifyStateDeltaChanges(Multiplayer::ReplicationRecord& replicationRecord) override; bool HasController() const override; - MultiplayerController* GetController() override; + Multiplayer::MultiplayerController* GetController() override; protected: void ConstructController() override; @@ -484,8 +484,8 @@ namespace {{ Component.attrib['Namespace'] }} void NotifyChangesAutonomousToAuthorityProperties(const {{ RecordName }}& replicationRecord) const; //! Debug name helpers - static const char* GetNetworkPropertyName(PropertyIndex propertyIndex); - static const char* GetRpcName(RpcIndex rpcIndex); + static const char* GetNetworkPropertyName(Multiplayer::PropertyIndex propertyIndex); + static const char* GetRpcName(Multiplayer::RpcIndex rpcIndex); AZStd::unique_ptr<{{ RecordName }}> m_currentRecord; AZStd::unique_ptr<{{ ControllerName }}> m_controller; @@ -517,7 +517,7 @@ namespace {{ Component.attrib['Namespace'] }} {{ Type }}* {{ Name }} = nullptr; {% endcall %} - static NetComponentId s_netComponentId; + static Multiplayer::NetComponentId s_netComponentId; friend void RegisterMultiplayerComponents(); }; } diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index d719cbe47b..1bc6dc3994 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -902,8 +902,8 @@ m_{{ LowerFirst(Property.attrib['Name']) }} = m_{{ LowerFirst(Property.attrib['N #include #include #include -#include -#include +#include +#include {% if ComponentDerived or ControllerDerived %} #include <{{ Component.attrib['OverrideInclude'] }}> {% endif %} @@ -915,7 +915,7 @@ m_{{ LowerFirst(Property.attrib['Name']) }} = m_{{ LowerFirst(Property.attrib['N namespace {{ Component.attrib['Namespace'] }} { - NetComponentId {{ UpperFirst(ComponentBaseName) }}::s_netComponentId = InvalidNetComponentId; + Multiplayer::NetComponentId {{ UpperFirst(ComponentBaseName) }}::s_netComponentId = Multiplayer::InvalidNetComponentId; namespace {{ UpperFirst(Component.attrib['Name']) }}Internal { @@ -1408,7 +1408,7 @@ namespace {{ Component.attrib['Namespace'] }} } {% endif %} - const char* {{ ComponentBaseName }}::GetNetworkPropertyName([[maybe_unused]] PropertyIndex propertyIndex) + const char* {{ ComponentBaseName }}::GetNetworkPropertyName([[maybe_unused]] Multiplayer::PropertyIndex propertyIndex) { {% if NetworkPropertyCount > 0 %} const {{ UpperFirst(Component.attrib['Name']) }}Internal::NetworkProperties propertyId = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::NetworkProperties>(propertyIndex); @@ -1423,7 +1423,7 @@ namespace {{ Component.attrib['Namespace'] }} return "Unknown network property"; } - const char* {{ ComponentBaseName }}::GetRpcName([[maybe_unused]] RpcIndex rpcIndex) + const char* {{ ComponentBaseName }}::GetRpcName([[maybe_unused]] Multiplayer::RpcIndex rpcIndex) { {% if RpcCount > 0 %} const {{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure rpcId = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure>(rpcIndex); diff --git a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml index 44edcaf505..a5a7e8decd 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml @@ -10,8 +10,8 @@ - - + + diff --git a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml index daf55c3d92..1260075cba 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml @@ -2,10 +2,10 @@ - - - - + + + + diff --git a/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml index 46065b386f..e76ac75edc 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml @@ -10,7 +10,7 @@ - + diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h index 15a4f3a048..924fd78391 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h @@ -13,7 +13,7 @@ #pragma once #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp index fcdad87416..ae6fc50f5a 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp @@ -10,8 +10,8 @@ * */ -#include -#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp index de1782cc59..648b28633e 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp @@ -10,7 +10,7 @@ * */ -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp b/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp index 737ecc10cc..9b8f41d5bc 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp @@ -10,9 +10,9 @@ * */ -#include -#include -#include +#include +#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp index eba09734a9..6dc661415e 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp @@ -10,13 +10,13 @@ * */ -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -177,21 +177,6 @@ namespace Multiplayer } } - AZ::Aabb NetBindComponent::GetRewindBoundsForInput(const NetworkInput& networkInput, float deltaTime) const - { - AZ_Assert(m_netEntityRole == NetEntityRole::Authority, "Incorrect network role for computing rewind bounds"); - AZ::Aabb bounds = AZ::Aabb::CreateNull(); - for (MultiplayerComponent* multiplayerComponent : m_multiplayerInputComponentVector) - { - const AZ::Aabb componentBounds = multiplayerComponent->GetController()->GetRewindBoundsForInput(networkInput, deltaTime); - if (componentBounds.IsValid()) - { - bounds.AddAabb(componentBounds); - } - } - return bounds; - } - bool NetBindComponent::HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetEntityRole remoteRole, NetworkEntityRpcMessage& message) { auto findIt = m_multiplayerComponentMap.find(message.GetComponentId()); diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h index b72a6aad2b..449ffafe45 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h index b02e6de9aa..6274a6ba31 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h b/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h index c1abbe74cd..3bf6eb554f 100644 --- a/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h +++ b/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp b/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp index cafdbf2a09..aef3e546ad 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp @@ -13,10 +13,10 @@ #include #include #include -#include #include #include #include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 15b6b48631..715d9a8527 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -11,13 +11,13 @@ */ #include -#include #include #include #include #include #include #include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index 1de8fccb50..ba59a82eae 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 65df4f1464..6eefeaf5fe 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -14,14 +14,14 @@ #include #include #include -#include -#include -#include #include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h index 4fc14e210f..50a4ad43d4 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h @@ -13,11 +13,11 @@ #pragma once #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index 197d83a48c..15293d518d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -16,11 +16,11 @@ #include #include #include -#include -#include #include #include -#include +#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h index 93494ab07c..3587c28975 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h @@ -18,8 +18,8 @@ #include #include #include -#include -#include +#include +#include namespace AzNetworking { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h index 238e665a00..be8ac1b65b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace AzNetworking diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp index 7b8c3e6094..4994884364 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp index 5f8dae8ff4..6aa6c10b11 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp @@ -10,7 +10,7 @@ * */ -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp index 797d67e3ef..ecfd416380 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp @@ -11,8 +11,8 @@ */ #include -#include -#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp index ca0275d20b..0dd7292d25 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp @@ -10,11 +10,11 @@ * */ -#include +#include +#include +#include +#include #include -#include -#include -#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index 7ee4d45e93..28b72abf25 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -11,7 +11,6 @@ */ #include - #include #include #include @@ -22,9 +21,9 @@ #include #include #include -#include +#include +#include #include -#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h index ba71eaf780..e763e7ebca 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h @@ -17,11 +17,11 @@ #include #include #include -#include -#include -#include #include -#include +#include +#include +#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp index 4bfc753f75..d58c192162 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp index 69f715317a..42104e79fd 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h index 4cfb242154..34f5d03f2f 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp index 27c39ea135..5ece0c7157 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp index 0ab1d5ffcc..eafd4375e7 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp @@ -10,8 +10,8 @@ * */ -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp index 0f5a0d7c0c..82e5cea0c4 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h index 504992fecb..d5cbcbbed3 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp index 114c3e3b43..c6b8e8d7ef 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h index 18b518f19f..fa4ab1e4e9 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h index ad406ffd8b..c5f0a70fd3 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp index c6eed626a9..4395ff5b7d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h index c6ea425fec..454cef4e0a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index c0200c9e6d..ab5988444b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -11,8 +11,8 @@ */ #include -#include -#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 47f557a11f..18adc00140 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h index 1922e65941..5cb9c0de70 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp index a51bdc4acc..bf370c1952 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h index b4e4427945..25fbfd481d 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h @@ -12,9 +12,9 @@ #pragma once -#include -#include -#include +#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index 1f4e57ae43..bea88af10c 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -10,18 +10,28 @@ # set(FILES - Include/IConnectionData.h - Include/IEntityDomain.h - Include/IMultiplayer.h - Include/IMultiplayerComponentInput.h - Include/INetworkEntityManager.h - Include/INetworkTime.h - Include/IReplicationWindow.h - Include/MultiplayerStats.cpp - Include/MultiplayerStats.h - Include/MultiplayerTypes.h - Include/NetworkEntityHandle.h - Include/NetworkEntityHandle.inl + Include/Multiplayer/IConnectionData.h + Include/Multiplayer/IEntityDomain.h + Include/Multiplayer/IMultiplayer.h + Include/Multiplayer/IMultiplayerComponentInput.h + Include/Multiplayer/INetworkEntityManager.h + Include/Multiplayer/INetworkTime.h + Include/Multiplayer/IReplicationWindow.h + Include/Multiplayer/MultiplayerComponent.h + Include/Multiplayer/MultiplayerController.h + Include/Multiplayer/MultiplayerComponentRegistry.h + Include/Multiplayer/MultiplayerStats.cpp + Include/Multiplayer/MultiplayerStats.h + Include/Multiplayer/MultiplayerTypes.h + Include/Multiplayer/NetBindComponent.h + Include/Multiplayer/NetworkEntityRpcMessage.h + Include/Multiplayer/NetworkEntityUpdateMessage.h + Include/Multiplayer/NetworkEntityHandle.h + Include/Multiplayer/NetworkEntityHandle.inl + Include/Multiplayer/NetworkInput.h + Include/Multiplayer/ReplicationRecord.h + Include/Multiplayer/RewindableObject.h + Include/Multiplayer/RewindableObject.inl Source/Multiplayer_precompiled.cpp Source/Multiplayer_precompiled.h Source/MultiplayerSystemComponent.cpp @@ -36,14 +46,10 @@ set(FILES Source/AutoGen/NetworkTransformComponent.AutoComponent.xml Source/Components/LocalPredictionPlayerInputComponent.cpp Source/Components/LocalPredictionPlayerInputComponent.h - Source/Components/MultiplayerComponentRegistry.cpp - Source/Components/MultiplayerComponentRegistry.h Source/Components/MultiplayerComponent.cpp - Source/Components/MultiplayerComponent.h Source/Components/MultiplayerController.cpp - Source/Components/MultiplayerController.h + Source/Components/MultiplayerComponentRegistry.cpp Source/Components/NetBindComponent.cpp - Source/Components/NetBindComponent.h Source/Components/NetworkTransformComponent.cpp Source/Components/NetworkTransformComponent.h Source/ConnectionData/ClientToServerConnectionData.cpp @@ -64,7 +70,6 @@ set(FILES Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp Source/NetworkEntity/EntityReplication/PropertySubscriber.h Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp - Source/NetworkEntity/EntityReplication/ReplicationRecord.h Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp Source/NetworkEntity/NetworkEntityAuthorityTracker.h Source/NetworkEntity/NetworkEntityHandle.cpp @@ -73,14 +78,11 @@ set(FILES Source/NetworkEntity/NetworkSpawnableLibrary.cpp Source/NetworkEntity/NetworkSpawnableLibrary.h Source/NetworkEntity/NetworkEntityRpcMessage.cpp - Source/NetworkEntity/NetworkEntityRpcMessage.h Source/NetworkEntity/NetworkEntityTracker.cpp Source/NetworkEntity/NetworkEntityTracker.h Source/NetworkEntity/NetworkEntityTracker.inl Source/NetworkEntity/NetworkEntityUpdateMessage.cpp - Source/NetworkEntity/NetworkEntityUpdateMessage.h Source/NetworkInput/NetworkInput.cpp - Source/NetworkInput/NetworkInput.h Source/NetworkInput/NetworkInputArray.cpp Source/NetworkInput/NetworkInputArray.h Source/NetworkInput/NetworkInputChild.cpp @@ -91,8 +93,6 @@ set(FILES Source/NetworkInput/NetworkInputMigrationVector.h Source/NetworkTime/NetworkTime.cpp Source/NetworkTime/NetworkTime.h - Source/NetworkTime/RewindableObject.h - Source/NetworkTime/RewindableObject.inl Source/Pipeline/NetBindMarkerComponent.cpp Source/Pipeline/NetBindMarkerComponent.h Source/Pipeline/NetworkSpawnableHolderComponent.cpp From 8bb425709b38d2f574de0eafe842f3a0cffea8dc Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 16:04:44 -0700 Subject: [PATCH 073/231] unit test fix --- Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp index 367b7ee0de..9f1b879856 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp @@ -10,7 +10,8 @@ * */ -#include +#include +#include #include #include #include From 8fd5c30e136e62887842916b26491c691a625e26 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Wed, 12 May 2021 17:47:10 -0700 Subject: [PATCH 074/231] Address some build/review feedback --- Code/Sandbox/Editor/ViewportTitleDlg.cpp | 7 ++-- .../AtomFont/Code/Source/FFont.cpp | 1 - ...AtomViewportDisplayInfoSystemComponent.cpp | 32 +++++++++---------- .../AtomViewportDisplayInfoSystemComponent.h | 1 + 4 files changed, 19 insertions(+), 22 deletions(-) diff --git a/Code/Sandbox/Editor/ViewportTitleDlg.cpp b/Code/Sandbox/Editor/ViewportTitleDlg.cpp index 159fccfd64..d7c8929540 100644 --- a/Code/Sandbox/Editor/ViewportTitleDlg.cpp +++ b/Code/Sandbox/Editor/ViewportTitleDlg.cpp @@ -187,11 +187,8 @@ void CViewportTitleDlg::OnToggleDisplayInfo() state, &AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Events::GetDisplayState ); - state = static_cast(static_cast(state)+1); - if (state == AZ::AtomBridge::ViewportInfoDisplayState::Invalid) - { - state = AZ::AtomBridge::ViewportInfoDisplayState::NoInfo; - } + state = static_cast( + (static_cast(state)+1) % static_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, diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index be0f87100a..cc14014e48 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -1684,7 +1684,6 @@ AZ::FFont::DrawParameters AZ::FFont::ExtractDrawParameters(const AzFramework::Te return internalParams; } - //Code mostly duplicated from CRenderer::Draw2dTextWithDepth float posX = params.m_position.GetX(); float posY = params.m_position.GetY(); internalParams.m_viewportContext = AZ::Interface::Get()->GetViewportContextById(params.m_drawViewportId); diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp index c9128c001f..ed6b910b76 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp @@ -111,25 +111,26 @@ namespace AZ::Render void AtomViewportDisplayInfoSystemComponent::DrawLine(AZStd::string_view line, AZ::Color color) { m_drawParams.m_color = color; - AzFramework::FontDrawInterface* fontDrawInterface = - AZ::Interface::Get()->GetDefaultFontDrawInterface(); - AZ::Vector2 textSize = fontDrawInterface->GetTextSize(m_drawParams, line); - fontDrawInterface->DrawScreenAlignedText2d(m_drawParams, line); + AZ::Vector2 textSize = m_fontDrawInterface->GetTextSize(m_drawParams, line); + m_fontDrawInterface->DrawScreenAlignedText2d(m_drawParams, line); m_drawParams.m_position.SetY(m_drawParams.m_position.GetY() + textSize.GetY() + m_lineSpacing); } void AtomViewportDisplayInfoSystemComponent::OnRenderTick() { - auto fontQueryInterface = AZ::Interface::Get(); - if (!fontQueryInterface) + if (!m_fontDrawInterface) { - return; + auto fontQueryInterface = AZ::Interface::Get(); + if (!fontQueryInterface) + { + return; + } + m_fontDrawInterface = + fontQueryInterface->GetDefaultFontDrawInterface(); } - AzFramework::FontDrawInterface* fontDrawInterface = - fontQueryInterface->GetDefaultFontDrawInterface(); AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); - if (!fontDrawInterface || !viewportContext || !viewportContext->GetRenderScene()) + if (!m_fontDrawInterface || !viewportContext || !viewportContext->GetRenderScene()) { return; } @@ -167,7 +168,7 @@ namespace AZ::Render m_drawParams.m_lineSpacing = 0.5f; // Calculate line spacing based on the font's actual line height - const float lineHeight = fontDrawInterface->GetTextSize(m_drawParams, " ").GetY(); + const float lineHeight = m_fontDrawInterface->GetTextSize(m_drawParams, " ").GetY(); m_lineSpacing = lineHeight * m_drawParams.m_lineSpacing; DrawRendererInfo(); @@ -234,7 +235,7 @@ namespace AZ::Render int count = 1; if (auto passAsParent = pass->AsParent()) { - for (const auto child : passAsParent->GetChildren()) + for (const auto& child : passAsParent->GetChildren()) { count += containingPassCount(child); } @@ -243,10 +244,10 @@ namespace AZ::Render }; const int numPasses = containingPassCount(rootPass); DrawLine(AZStd::string::format( - "Total Passes: %d Vertex Count: %d Primitive Count: %d", + "Total Passes: %d Vertex Count: %lld Primitive Count: %lld", numPasses, - stats.m_vertexCount, - stats.m_primitiveCount + aznumeric_cast(stats.m_vertexCount), + aznumeric_cast(stats.m_primitiveCount) )); } @@ -269,7 +270,6 @@ namespace AZ::Render } m_lastMemoryUpdate = currentTime; - int peakUsageMB = aznumeric_cast(processMemInfo.PeakPagefileUsage >> 20); int currentUsageMB = aznumeric_cast(processMemInfo.PagefileUsage >> 20); DrawLine(AZStd::string::format("Mem=%d Peak=%d", currentUsageMB, peakUsageMB)); diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h index ac6c2bab65..08bec4a1d2 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h @@ -68,6 +68,7 @@ namespace AZ AZStd::string m_rendererDescription; AzFramework::TextDrawParameters m_drawParams; + AzFramework::FontDrawInterface* m_fontDrawInterface = nullptr; float m_lineSpacing; AZStd::chrono::duration m_fpsInterval = AZStd::chrono::seconds(1); AZStd::deque m_fpsHistory; From 1fe81c1533c9e1bbf15f5a6ffff1afb9468759f4 Mon Sep 17 00:00:00 2001 From: Peng Date: Wed, 12 May 2021 17:51:30 -0700 Subject: [PATCH 075/231] ATOM-15266 added location in the assert message where the descriptor set will be re-created --- Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp index 8769aaa1f9..634f5a51ac 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/DescriptorSet.cpp @@ -241,8 +241,8 @@ namespace AZ VkResult result = vkAllocateDescriptorSets(descriptor.m_device->GetNativeDevice(), &allocInfo, &m_nativeDescriptorSet); if (result == VK_ERROR_FRAGMENTED_POOL) { - // fragmented pool will be re-created subsequently, so warning only - AZ_Warning("Vulkan RHI", false, "Fragmented pool"); + // fragmented pool will be re-created subsequently in DescriptorSetAllocator, so warning only + AZ_Warning("Vulkan RHI", false, "Fragmented pool, will be recreated in DescriptorSetAllocator afterward"); } else { From e7722658718b4c705b688ca88c54cb17c603b417 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:09:27 -0700 Subject: [PATCH 076/231] Build fixes for gem reorganization --- .../Code/Source/Debug/MultiplayerDebugSystemComponent.cpp | 2 +- .../Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index aec8d8520e..1ae4bffd07 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp index 4962d16fb4..805a982506 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include From eea0660d2140c1e84f63b484f2e89e87a9ec4930 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:26:08 -0700 Subject: [PATCH 077/231] A couple more fixes --- .../Code/Include/Multiplayer/RewindableObject.inl | 4 ++-- .../Code/Source/AutoGen/AutoComponent_Source.jinja | 4 ++-- Gems/Multiplayer/Code/multiplayer_files.cmake | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl index 2e67d42ede..20f52ffcb0 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl +++ b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl @@ -47,7 +47,7 @@ namespace Multiplayer template inline RewindableObject &RewindableObject::operator =(const RewindableObject& rhs) { - INetworkTime* networkTime = GetNetworkTime(); + INetworkTime* networkTime = Multiplayer::GetNetworkTime(); SetValueForTime(rhs.GetValueForTime(networkTime->GetHostFrameId()), GetCurrentTimeForProperty()); return *this; } @@ -115,7 +115,7 @@ namespace Multiplayer template inline HostFrameId RewindableObject::GetCurrentTimeForProperty() const { - INetworkTime* networkTime = GetNetworkTime(); + INetworkTime* networkTime = Multiplayer::GetNetworkTime(); return networkTime->GetHostFrameIdForRewindingConnection(m_owningConnectionId); } diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 1bc6dc3994..200d38910b 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -1143,7 +1143,7 @@ namespace {{ Component.attrib['Namespace'] }} { editContext->Class<{{ ComponentBaseName }}>("{{ ComponentBaseName }}", "{{ Component.attrib['Description'] }}") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") + ->Attribute(AZ::Edit::Attributes::Category, "{{ Component.attrib['Namespace'] }}") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Authority', ComponentBaseName)|indent(20) -}} {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Server', ComponentBaseName)|indent(20) -}} @@ -1155,7 +1155,7 @@ namespace {{ Component.attrib['Namespace'] }} editContext->Class<{{ ComponentName }}>("{{ ComponentName }}", "{{ Component.attrib['Description'] }}") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") + ->Attribute(AZ::Edit::Attributes::Category, "{{ Component.attrib['Namespace'] }}") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")); {% endif %} } diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index bea88af10c..5eba7dd144 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -24,12 +24,12 @@ set(FILES Include/Multiplayer/MultiplayerStats.h Include/Multiplayer/MultiplayerTypes.h Include/Multiplayer/NetBindComponent.h - Include/Multiplayer/NetworkEntityRpcMessage.h + Include/Multiplayer/NetworkEntityRpcMessage.h Include/Multiplayer/NetworkEntityUpdateMessage.h Include/Multiplayer/NetworkEntityHandle.h Include/Multiplayer/NetworkEntityHandle.inl Include/Multiplayer/NetworkInput.h - Include/Multiplayer/ReplicationRecord.h + Include/Multiplayer/ReplicationRecord.h Include/Multiplayer/RewindableObject.h Include/Multiplayer/RewindableObject.inl Source/Multiplayer_precompiled.cpp @@ -48,7 +48,7 @@ set(FILES Source/Components/LocalPredictionPlayerInputComponent.h Source/Components/MultiplayerComponent.cpp Source/Components/MultiplayerController.cpp - Source/Components/MultiplayerComponentRegistry.cpp + Source/Components/MultiplayerComponentRegistry.cpp Source/Components/NetBindComponent.cpp Source/Components/NetworkTransformComponent.cpp Source/Components/NetworkTransformComponent.h From 601dd30452f9f052bf93fc48413e831259e2297d Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:41:53 -0700 Subject: [PATCH 078/231] Various build and test fixes --- .../Code/Include/Multiplayer/IMultiplayer.h | 14 +++++++++----- .../EntityReplication/EntityReplicationManager.cpp | 6 +++++- .../Code/Source/NetworkTime/NetworkTime.cpp | 10 ++++++++++ .../Code/Source/NetworkTime/NetworkTime.h | 4 ++-- .../Code/Tests/RewindableObjectTests.cpp | 6 +++--- 5 files changed, 29 insertions(+), 11 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index 665661b55b..eda5b71b52 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -139,27 +139,31 @@ namespace Multiplayer inline INetworkTime* GetNetworkTime() { - return GetMultiplayer()->GetNetworkTime(); + return AZ::Interface::Get(); } inline INetworkEntityManager* GetNetworkEntityManager() { - return GetMultiplayer()->GetNetworkEntityManager(); + IMultiplayer* multiplayer = GetMultiplayer(); + return (multiplayer != nullptr) ? multiplayer->GetNetworkEntityManager() : nullptr; } inline NetworkEntityTracker* GetNetworkEntityTracker() { - return GetNetworkEntityManager()->GetNetworkEntityTracker(); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + return (networkEntityManager != nullptr) ? networkEntityManager->GetNetworkEntityTracker() : nullptr; } inline NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() { - return GetNetworkEntityManager()->GetNetworkEntityAuthorityTracker(); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + return (networkEntityManager != nullptr) ? networkEntityManager->GetNetworkEntityAuthorityTracker() : nullptr; } inline MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() { - return GetNetworkEntityManager()->GetMultiplayerComponentRegistry(); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + return (networkEntityManager != nullptr) ? networkEntityManager->GetMultiplayerComponentRegistry() : nullptr; } //! @class ScopedAlterTime diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 6eefeaf5fe..286090ca74 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -60,7 +60,11 @@ namespace Multiplayer // Start window update events m_updateWindow.Enqueue(AZ::TimeMs{ 0 }, true); - GetNetworkEntityManager()->AddEntityExitDomainHandler(m_entityExitDomainEventHandler); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + if (networkEntityManager != nullptr) + { + networkEntityManager->AddEntityExitDomainHandler(m_entityExitDomainEventHandler); + } } void EntityReplicationManager::SetRemoteHostId(HostId hostId) diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index ab5988444b..d991e59d05 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -17,6 +17,16 @@ namespace Multiplayer { + NetworkTime::NetworkTime() + { + AZ::Interface::Register(this); + } + + NetworkTime::~NetworkTime() + { + AZ::Interface::Unregister(this); + } + bool NetworkTime::IsTimeRewound() const { return m_rewindingConnectionId != AzNetworking::InvalidConnectionId; diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 18adc00140..ff2da0f759 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -23,8 +23,8 @@ namespace Multiplayer : public INetworkTime { public: - NetworkTime() = default; - virtual ~NetworkTime() = default; + NetworkTime(); + virtual ~NetworkTime(); //! INetworkTime overrides. //! @{ diff --git a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp index 9f1b879856..f614dc2690 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp @@ -38,7 +38,7 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementHostFrameId(); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); } for (uint32_t i = 0; i < 16; ++i) @@ -51,7 +51,7 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementHostFrameId(); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); } for (uint32_t i = 16; i < 48; ++i) @@ -69,7 +69,7 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementHostFrameId(); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); } { From 77899c5d96c4119d6b855648282752ee0e05e342 Mon Sep 17 00:00:00 2001 From: Gene Walters Date: Wed, 12 May 2021 20:45:58 -0700 Subject: [PATCH 079/231] Updated network property behavior context category so they are grouped nicer in the Script Canvas palette --- .../Code/Source/AutoGen/AutoComponent_Source.jinja | 4 +++- .../Code/Source/MultiplayerSystemComponent.cpp | 14 +++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index a3eef99b20..5b53145024 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -725,7 +725,7 @@ enum class NetworkProperties return &networkComponent->m_{{ LowerFirst(Property.attrib['Name']) }}Event; }) - ->Attribute(AZ::Script::Attributes::AzEventDescription, AZ::BehaviorAzEventDescription{ "On {{ UpperFirst(Property.attrib['Name']) }} Changed Event", {"New {{ UpperFirst(Property.attrib['Name']) }}"} }) + ->Attribute(AZ::Script::Attributes::AzEventDescription, AZ::BehaviorAzEventDescription{ "On {{ UpperFirst(Property.attrib['Name']) }} Changed Event", {"New {{ Property.attrib['Type'] }}"} }) {% endif %} {% endcall -%} @@ -1217,6 +1217,8 @@ namespace {{ Component.attrib['Namespace'] }} if (behaviorContext) { behaviorContext->Class<{{ ComponentName }}>("{{ ComponentName }}") + ->Attribute(AZ::Script::Attributes::Module, "{{ LowerFirst(Component.attrib['Namespace']) }}") + ->Attribute(AZ::Script::Attributes::Category, "{{ UpperFirst(Component.attrib['Namespace']) }}") {{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Authority', ComponentName)|indent(16) -}} {{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Server', ComponentName)|indent(16) -}} {{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Client', ComponentName)|indent(16) -}} diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 9f45122c1d..7d74f5e071 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -80,13 +80,13 @@ namespace Multiplayer if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->Class("HostId"); - behaviorContext->Class("NetEntityId"); - behaviorContext->Class("NetComponentId"); - behaviorContext->Class("PropertyIndex"); - behaviorContext->Class ("RpcIndex"); - behaviorContext->Class ("ClientInputId"); - behaviorContext->Class ("HostFrameId"); + behaviorContext->Class(); + behaviorContext->Class(); + behaviorContext->Class(); + behaviorContext->Class(); + behaviorContext->Class(); + behaviorContext->Class(); + behaviorContext->Class(); } MultiplayerComponent::Reflect(context); From 124ca1618a2e463e98ca4e7c5d3aa67793c4676a Mon Sep 17 00:00:00 2001 From: mriegger Date: Wed, 12 May 2021 20:51:56 -0700 Subject: [PATCH 080/231] Making shadow res of 1024 and bicubic pcf the default --- .../CommonFeatures/CoreLights/AreaLightComponentConfig.h | 2 +- .../CoreLights/DirectionalLightComponentConfig.h | 4 ++-- .../Code/Source/CoreLights/EditorAreaLightComponent.cpp | 6 +++--- .../Source/CoreLights/EditorDirectionalLightComponent.cpp | 6 +++--- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h index fe40cabc12..31cdb34ddd 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h @@ -62,7 +62,7 @@ namespace AZ bool m_enableShadow = false; ShadowmapSize m_shadowmapMaxSize = ShadowmapSize::Size256; ShadowFilterMethod m_shadowFilterMethod = ShadowFilterMethod::None; - PcfMethod m_pcfMethod = PcfMethod::BoundarySearch; + PcfMethod m_pcfMethod = PcfMethod::Bicubic; float m_boundaryWidthInDegrees = 0.25f; uint16_t m_predictionSampleCount = 4; uint16_t m_filteringSampleCount = 12; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h index 7de2857541..237c1f3016 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h @@ -61,7 +61,7 @@ namespace AZ float m_shadowFarClipDistance = 100.f; //! Width/Height of shadowmap images. - ShadowmapSize m_shadowmapSize = MaxShadowmapImageSize; + ShadowmapSize m_shadowmapSize = ShadowmapSize::Size1024; //! Number of cascades. uint32_t m_cascadeCount = 4; @@ -117,7 +117,7 @@ namespace AZ //! It is used only when the pixel is predicted as on the boundary. uint16_t m_filteringSampleCount = 32; - PcfMethod m_pcfMethod = PcfMethod::BoundarySearch; + PcfMethod m_pcfMethod = PcfMethod::Bicubic; bool IsSplitManual() const; bool IsSplitAutomatic() const; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp index a77bcfdd12..69bec21a6c 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp @@ -173,10 +173,10 @@ namespace AZ ->DataElement( Edit::UIHandlers::ComboBox, &AreaLightComponentConfig::m_pcfMethod, "Pcf method", "Type of PCF to use.\n" - " Boundary search: do several taps to first determine if we are on a shadow boundary\n" - " Bicubic: a smooth, fixed-size kernel \n") - ->EnumAttribute(PcfMethod::BoundarySearch, "Boundary search") + " Bicubic: a smooth, fixed-size kernel \n" + " Boundary search: do several taps to first determine if we are on a shadow boundary\n") ->EnumAttribute(PcfMethod::Bicubic, "Bicubic") + ->EnumAttribute(PcfMethod::BoundarySearch, "Boundary search") ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->Attribute(Edit::Attributes::Visibility, &AreaLightComponentConfig::SupportsShadows) ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::IsShadowPcfDisabled); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp index 35c5522c4e..a40557f2f1 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp @@ -163,10 +163,10 @@ namespace AZ ->DataElement( Edit::UIHandlers::ComboBox, &DirectionalLightComponentConfig::m_pcfMethod, "Pcf Method", "Type of Pcf to use.\n" - " Boundary search: do several taps to first determine if we are on a shadow boundary\n" - " Bicubic: a smooth, fixed-size kernel \n") - ->EnumAttribute(PcfMethod::BoundarySearch, "Boundary Search") + " Bicubic: a smooth, fixed-size kernel \n" + " Boundary search: do several taps to first determine if we are on a shadow boundary\n") ->EnumAttribute(PcfMethod::Bicubic, "Bicubic") + ->EnumAttribute(PcfMethod::BoundarySearch, "Boundary Search") ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->Attribute(Edit::Attributes::ReadOnly, &DirectionalLightComponentConfig::IsShadowPcfDisabled); ; From cb8016bde5f7c63c3054b4992705b9011fce502e Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:52:02 -0700 Subject: [PATCH 081/231] Fix for validator failing on empty files --- .../Multiplayer/INetworkPlayerSpawner.h | 18 ++++++++++++++++++ .../Code/Source/MultiplayerSystemComponent.cpp | 2 +- Gems/Multiplayer/Code/multiplayer_files.cmake | 1 + 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h index e69de29bb2..f50d60e82d 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h @@ -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. +* +*/ + +#pragma once + +namespace Multiplayer +{ + +} diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 715d9a8527..80a09d7d48 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -433,7 +433,7 @@ namespace Multiplayer if (m_onConnectFunctor) { - // Default OnConnect behaviour has been overridden, + // Default OnConnect behaviour has been overridden m_onConnectFunctor(connection, datum); } else diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index 5eba7dd144..26909cbfd3 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -15,6 +15,7 @@ set(FILES Include/Multiplayer/IMultiplayer.h Include/Multiplayer/IMultiplayerComponentInput.h Include/Multiplayer/INetworkEntityManager.h + Include/Multiplayer/INetworkPlayerSpawner.h Include/Multiplayer/INetworkTime.h Include/Multiplayer/IReplicationWindow.h Include/Multiplayer/MultiplayerComponent.h From c0d9a3c423b61747656842a931f9c127dceba8d7 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:55:03 -0700 Subject: [PATCH 082/231] Fix for clang not being lazy about template expansion --- Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h | 5 ----- Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h | 6 ++++++ 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index eda5b71b52..4931fb167f 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -137,11 +137,6 @@ namespace Multiplayer return AZ::Interface::Get(); } - inline INetworkTime* GetNetworkTime() - { - return AZ::Interface::Get(); - } - inline INetworkEntityManager* GetNetworkEntityManager() { IMultiplayer* multiplayer = GetMultiplayer(); diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h index c228e135ee..240eed270a 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h @@ -83,4 +83,10 @@ namespace Multiplayer static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; }; using INetworkTimeRequestBus = AZ::EBus; + + // Convenience helpers + inline INetworkTime* GetNetworkTime() + { + return AZ::Interface::Get(); + } } From bcea9f29a82eadf15d63daaa6184744d77c308f2 Mon Sep 17 00:00:00 2001 From: mriegger Date: Wed, 12 May 2021 22:11:49 -0700 Subject: [PATCH 083/231] Improved variable name --- .../Assets/ShaderLib/Atom/Features/LightCulling/NVLC.azsli | 6 +++--- .../Shaders/LightCulling/LightCullingTilePrepare.azsl | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/NVLC.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/NVLC.azsli index 8bcd21b19b..60d5bf38f2 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/NVLC.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/NVLC.azsli @@ -26,7 +26,7 @@ // //---------------------------------------------------------------------------------- -#define Depth_to_Z(d, unprojectZ) (unprojectZ.x / (d + unprojectZ.y)) +#define DepthBufferToViewSpace(d, unprojectZ) (unprojectZ.x / (d + unprojectZ.y)) #define NVLC_MAX_POSSIBLE_LIGHTS_PER_BIN 256 @@ -187,7 +187,7 @@ float4 RemapZToUnit(float4 z, float2 minmaxz) uint DepthSamplesToBinMask2x(float2 d, float2 minmaxz, float2 unprojectZ) { - float2 z = Depth_to_Z(d, unprojectZ); + float2 z = DepthBufferToViewSpace(d, unprojectZ); // Tile_UnitValueToBit will convert that 0 to 1 value into 0.0 to 31.99999 float2 bit = Tile_UnitValueToBit(RemapZToUnit(z, minmaxz)); @@ -207,7 +207,7 @@ uint DepthSamplesToBinMask2x(float2 d, float2 minmaxz, float2 unprojectZ) uint DepthSamplesToBinMask4x(float4 d, float2 minmaxz, float2 unprojectZ) { - float4 z = Depth_to_Z(d, unprojectZ); + float4 z = DepthBufferToViewSpace(d, unprojectZ); // Tile_UnitValueToBit will convert that 0 to 1 value into 0.0 to 31.99999 float4 bit = Tile_UnitValueToBit(RemapZToUnit(z, minmaxz)); diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingTilePrepare.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingTilePrepare.azsl index fba2175c9b..a8b2ab76db 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingTilePrepare.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingTilePrepare.azsl @@ -150,7 +150,7 @@ uint ComputeTransparentBitMask(float2 minmaxZ) return 0; } - float2 minmaxZ_transparent = Depth_to_Z(minmaxDepth_transparent, PassSrg::m_constantData.m_unprojectZ); + float2 minmaxZ_transparent = DepthBufferToViewSpace(minmaxDepth_transparent, PassSrg::m_constantData.m_unprojectZ); float2 minmaxUnit_transparent = RemapZToUnit(minmaxZ_transparent, minmaxZ); @@ -295,7 +295,7 @@ void MainCS( float2 minmaxDepth_opaque = ComputeDepthMinMaxFrom2Samples(opaqueDepthSamples); minmaxDepth_both = ExpandMinMax(minmaxDepth_opaque, minmaxDepth_transparent); UpdateMinMaxFromAllThreads(minmaxDepth_both, minmaxDepth_transparent, isPixelOnScreen); - minmaxDepth_both = Depth_to_Z(minmaxDepth_both, PassSrg::m_constantData.m_unprojectZ); + minmaxDepth_both = DepthBufferToViewSpace(minmaxDepth_both, PassSrg::m_constantData.m_unprojectZ); // if zNear == zFar we want to map z == zNear to 0-bit, so we have to keep zNear without modifications minmaxDepth_both.y = IncrementULP(minmaxDepth_both.y); @@ -313,7 +313,7 @@ void MainCS( float2 minmaxDepth_opaque = ComputeDepthMinMaxFrom4Samples(opaqueDepthSamples); minmaxDepth_both = ExpandMinMax(minmaxDepth_opaque, minmaxDepth_transparent); UpdateMinMaxFromAllThreads(minmaxDepth_both, minmaxDepth_transparent, isPixelOnScreen); - minmaxDepth_both = Depth_to_Z(minmaxDepth_both, PassSrg::m_constantData.m_unprojectZ); + minmaxDepth_both = DepthBufferToViewSpace(minmaxDepth_both, PassSrg::m_constantData.m_unprojectZ); // if zNear == zFar we want to map z == zNear to 0-bit, so we have to keep zNear without modifications minmaxDepth_both.y = IncrementULP(minmaxDepth_both.y); From d85e0500d5d33c215dc96898b0269a9c1138c884 Mon Sep 17 00:00:00 2001 From: guthadam Date: Thu, 13 May 2021 00:55:29 -0500 Subject: [PATCH 084/231] PR feedback --- .../Common/Code/Source/Material/MaterialAssignmentId.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp index 0fe89d49b8..59de229445 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp @@ -110,7 +110,7 @@ namespace AZ bool MaterialAssignmentId::operator!=(const MaterialAssignmentId& rhs) const { - return m_lodIndex != rhs.m_lodIndex || m_materialAssetId.m_subId != rhs.m_materialAssetId.m_subId; + return !(*this == rhs); } } // namespace Render } // namespace AZ From 36a79aca8a353316f560f3079ff2b66cb5120996 Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Thu, 13 May 2021 10:56:39 +0100 Subject: [PATCH 085/231] Remove redundant function. --- .../UI/PropertyEditor/PropertyRowWidget.cpp | 7 +------ .../UI/PropertyEditor/PropertyRowWidget.hxx | 1 - 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index 85784d61e0..890253b528 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -126,7 +126,7 @@ namespace AzToolsFramework { QStylePainter p(this); - if (IsReorderableRow()) + if (CanBeReordered()) { const QPen linePen(QColor(0x3B3E3F)); p.setPen(linePen); @@ -1332,11 +1332,6 @@ namespace AzToolsFramework return canBeTopLevel(this); } - bool PropertyRowWidget::IsReorderableRow() const - { - return CanBeReordered(); - } - bool PropertyRowWidget::GetAppendDefaultLabelToName() { return false; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx index 1c17cab69f..79121403c9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx @@ -83,7 +83,6 @@ namespace AzToolsFramework PropertyRowWidget* GetParentRow() const { return m_parentRow; } int GetLevel() const; bool IsTopLevel() const; - bool IsReorderableRow() const; // Remove the default label and append the text to the name label. bool GetAppendDefaultLabelToName(); From d690c3fee4810a49da588a71da4a95ab603918c9 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Thu, 13 May 2021 11:59:22 +0100 Subject: [PATCH 086/231] static rigid body and rigid body component use Handles instead of pointers (#662) --- .../Configuration/RigidBodyConfiguration.cpp | 8 +- .../Configuration/RigidBodyConfiguration.h | 1 - .../Physics/SimulatedBodies/RigidBody.h | 2 +- .../Code/Source/Family/BlastFamilyImpl.cpp | 2 +- Gems/Blast/Code/Tests/Mocks/BlastMocks.h | 2 +- .../Code/Source/EditorRigidBodyComponent.cpp | 98 +++--- .../Code/Source/EditorRigidBodyComponent.h | 7 +- Gems/PhysX/Code/Source/RigidBody.cpp | 8 +- Gems/PhysX/Code/Source/RigidBody.h | 2 +- Gems/PhysX/Code/Source/RigidBodyComponent.cpp | 278 ++++++++++++++---- Gems/PhysX/Code/Source/RigidBodyComponent.h | 3 +- Gems/PhysX/Code/Source/Scene/PhysXScene.cpp | 18 +- .../Code/Source/StaticRigidBodyComponent.cpp | 42 ++- .../Code/Source/StaticRigidBodyComponent.h | 1 - Gems/PhysX/Code/Source/System/PhysXSystem.cpp | 3 + Gems/PhysX/Code/Tests/PhysXTestCommon.cpp | 12 + 16 files changed, 358 insertions(+), 129 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp index 80434e5dee..0d5d5ca841 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp @@ -99,6 +99,11 @@ namespace AzPhysics classElement.RemoveElementByName(AZ_CRC_CE("Property Visibility Flags")); } + if (classElement.GetVersion() <= 4) + { + classElement.RemoveElementByName(AZ_CRC_CE("Simulated")); + } + return true; } } @@ -110,7 +115,7 @@ namespace AzPhysics if (auto serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(4, &Internal::RigidBodyVersionConverter) + ->Version(5, &Internal::RigidBodyVersionConverter) ->Field("Initial linear velocity", &RigidBodyConfiguration::m_initialLinearVelocity) ->Field("Initial angular velocity", &RigidBodyConfiguration::m_initialAngularVelocity) ->Field("Linear damping", &RigidBodyConfiguration::m_linearDamping) @@ -119,7 +124,6 @@ namespace AzPhysics ->Field("Start Asleep", &RigidBodyConfiguration::m_startAsleep) ->Field("Interpolate Motion", &RigidBodyConfiguration::m_interpolateMotion) ->Field("Gravity Enabled", &RigidBodyConfiguration::m_gravityEnabled) - ->Field("Simulated", &RigidBodyConfiguration::m_simulated) ->Field("Kinematic", &RigidBodyConfiguration::m_kinematic) ->Field("CCD Enabled", &RigidBodyConfiguration::m_ccdEnabled) ->Field("Compute Mass", &RigidBodyConfiguration::m_computeMass) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h index 5c43118f3d..ecf7e023c5 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h @@ -57,7 +57,6 @@ namespace AzPhysics bool m_startAsleep = false; bool m_interpolateMotion = false; bool m_gravityEnabled = true; - bool m_simulated = true; bool m_kinematic = false; bool m_ccdEnabled = false; //!< Whether continuous collision detection is enabled. float m_ccdMinAdvanceCoefficient = 0.15f; //!< Coefficient affecting how granularly time is subdivided in CCD. diff --git a/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h b/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h index 5b18887d43..0f43aaaf4a 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h @@ -62,7 +62,7 @@ namespace AzPhysics virtual void SetLinearVelocity(const AZ::Vector3& velocity) = 0; virtual AZ::Vector3 GetAngularVelocity() const = 0; virtual void SetAngularVelocity(const AZ::Vector3& angularVelocity) = 0; - virtual AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) = 0; + virtual AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const = 0; virtual void ApplyLinearImpulse(const AZ::Vector3& impulse) = 0; virtual void ApplyLinearImpulseAtWorldPoint(const AZ::Vector3& impulse, const AZ::Vector3& worldPoint) = 0; virtual void ApplyAngularImpulse(const AZ::Vector3& angularImpulse) = 0; diff --git a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp index d276486548..87865d0e08 100644 --- a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp +++ b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp @@ -241,7 +241,7 @@ namespace Blast configuration.m_orientation = transform.GetRotation(); configuration.m_scale = transform.GetScale(); configuration.m_ccdEnabled = m_actorConfiguration.m_isCcdEnabled; - configuration.m_simulated = m_actorConfiguration.m_isSimulated; + configuration.m_startSimulationEnabled = m_actorConfiguration.m_isSimulated; configuration.m_initialAngularVelocity = AZ::Vector3::CreateZero(); BlastActorDesc actorDesc; diff --git a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h index a1e57a6917..1ae87e2282 100644 --- a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h +++ b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h @@ -424,7 +424,7 @@ namespace Blast void SetAngularVelocity([[maybe_unused]] const AZ::Vector3& angularVelocity) override {} - AZ::Vector3 GetLinearVelocityAtWorldPoint([[maybe_unused]] const AZ::Vector3& worldPoint) override + AZ::Vector3 GetLinearVelocityAtWorldPoint([[maybe_unused]] const AZ::Vector3& worldPoint) const override { return {}; } diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp index b6517b0499..f97e7c6cbd 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp @@ -282,9 +282,8 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { - sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - m_editorBody = nullptr; + sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); + m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } @@ -342,12 +341,15 @@ namespace PhysX [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - if (m_editorBody && m_config.m_centerOfMassDebugDraw) + if (m_config.m_centerOfMassDebugDraw) { - debugDisplay.DepthTestOff(); - debugDisplay.SetColor(m_centerOfMassDebugColor); - debugDisplay.DrawBall(m_editorBody->GetCenterOfMassWorld(), m_centerOfMassDebugSize); - debugDisplay.DepthTestOn(); + if (const AzPhysics::RigidBody* body = GetRigidBody()) + { + debugDisplay.DepthTestOff(); + debugDisplay.SetColor(m_centerOfMassDebugColor); + debugDisplay.DrawBall(body->GetCenterOfMassWorld(), m_centerOfMassDebugSize); + debugDisplay.DepthTestOn(); + } } } @@ -366,29 +368,30 @@ namespace PhysX AZ::Transform colliderTransform = GetWorldTM(); colliderTransform.ExtractScale(); - AzPhysics::RigidBodyConfiguration configuration; + AzPhysics::RigidBodyConfiguration configuration = m_config; configuration.m_orientation = colliderTransform.GetRotation(); configuration.m_position = colliderTransform.GetTranslation(); configuration.m_entityId = GetEntityId(); configuration.m_debugName = GetEntity()->GetName(); - configuration.m_centerOfMassOffset = m_config.m_centerOfMassOffset; - configuration.m_computeCenterOfMass = m_config.m_computeCenterOfMass; - configuration.m_computeInertiaTensor = m_config.m_computeInertiaTensor; - configuration.m_inertiaTensor = m_config.m_inertiaTensor; - configuration.m_simulated = false; - configuration.m_kinematic = m_config.m_kinematic; + configuration.m_startSimulationEnabled = false; configuration.m_colliderAndShapeData = Internal::GetCollisionShapes(GetEntity()); + if (auto* sceneInterface = AZ::Interface::Get()) { - m_rigidBodyHandle = sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); - m_editorBody = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_rigidBodyHandle)); + m_editorRigidBodyHandle = sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); + if (auto* body = azdynamic_cast( + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle) + )) + { + // AddSimulatedBody may update mass / CoM / Inertia tensor based on the config, so grab the updated values. + m_config.m_mass = body->GetMass(); + m_config.m_centerOfMassOffset = body->GetCenterOfMassLocal(); + m_config.m_inertiaTensor = body->GetInverseInertiaLocal(); + } } - - m_editorBody->UpdateMassProperties(m_config.GetMassComputeFlags(), &m_config.m_centerOfMassOffset, &m_config.m_inertiaTensor, &m_config.m_mass); - m_config.m_mass = m_editorBody->GetMass(); - m_config.m_centerOfMassOffset = m_editorBody->GetCenterOfMassLocal(); - m_config.m_inertiaTensor = m_editorBody->GetInverseInertiaLocal(); + AZ_Error("EditorRigidBodyComponent", + m_editorRigidBodyHandle != AzPhysics::InvalidSimulatedBodyHandle, "Failed to create editor rigid body"); } void EditorRigidBodyComponent::OnColliderChanged() @@ -424,9 +427,8 @@ namespace PhysX { if (auto* sceneInterface = AZ::Interface::Get()) { - sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - m_editorBody = nullptr; + sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); + m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; CreateEditorWorldRigidBody(); } @@ -436,46 +438,65 @@ namespace PhysX void EditorRigidBodyComponent::EnablePhysics() { - if (!IsPhysicsEnabled()) + if (auto* sceneInterface = AZ::Interface::Get()) { - m_editorBody->SetSimulationEnabled(true); + sceneInterface->EnableSimulationOfBody(m_editorSceneHandle, m_editorRigidBodyHandle); } } void EditorRigidBodyComponent::DisablePhysics() { - m_editorBody->SetSimulationEnabled(false); + if (auto* sceneInterface = AZ::Interface::Get()) + { + sceneInterface->DisableSimulationOfBody(m_editorSceneHandle, m_editorRigidBodyHandle); + } } bool EditorRigidBodyComponent::IsPhysicsEnabled() const { - return m_editorBody && m_editorBody->m_simulating; + if (auto* sceneInterface = AZ::Interface::Get()) + { + if (AzPhysics::SimulatedBody* body = + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle)) + { + return body->m_simulating; + } + } + return false; } AZ::Aabb EditorRigidBodyComponent::GetAabb() const { - if (m_editorBody) + if (auto* sceneInterface = AZ::Interface::Get()) { - return m_editorBody->GetAabb(); + if (AzPhysics::SimulatedBody* body = + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle)) + { + return body->GetAabb(); + } } return AZ::Aabb::CreateNull(); } AzPhysics::SimulatedBody* EditorRigidBodyComponent::GetSimulatedBody() { - return m_editorBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle); + } + return nullptr; } AzPhysics::SimulatedBodyHandle EditorRigidBodyComponent::GetSimulatedBodyHandle() const { - return m_rigidBodyHandle; + return m_editorRigidBodyHandle; } AzPhysics::SceneQueryHit EditorRigidBodyComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_editorBody) + if (AzPhysics::SimulatedBody* body = GetSimulatedBody()) { - return m_editorBody->RayCast(request); + return body->RayCast(request); } return AzPhysics::SceneQueryHit(); } @@ -488,7 +509,12 @@ namespace PhysX const AzPhysics::RigidBody* EditorRigidBodyComponent::GetRigidBody() const { - return m_editorBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return azdynamic_cast( + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle)); + } + return nullptr; } void EditorRigidBodyComponent::SetShouldBeRecreated() diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h index b2b199e6be..72d34bb0d0 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h @@ -33,8 +33,8 @@ namespace PhysX struct EditorRigidBodyConfiguration : public AzPhysics::RigidBodyConfiguration { - AZ_CLASS_ALLOCATOR(EditorRigidBodyConfiguration, AZ::SystemAllocator, 0); - AZ_RTTI(EditorRigidBodyConfiguration, "{27297024-5A99-4C58-8614-4EF18137CE69}", AzPhysics::RigidBodyConfiguration); + AZ_CLASS_ALLOCATOR(PhysX::EditorRigidBodyConfiguration, AZ::SystemAllocator, 0); + AZ_RTTI(PhysX::EditorRigidBodyConfiguration, "{27297024-5A99-4C58-8614-4EF18137CE69}", AzPhysics::RigidBodyConfiguration); static void Reflect(AZ::ReflectContext* context); @@ -127,8 +127,7 @@ namespace PhysX Debug::DebugDisplayDataChangedEvent::Handler m_debugDisplayDataChangeHandler; EditorRigidBodyConfiguration m_config; - AzPhysics::SimulatedBodyHandle m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - AzPhysics::RigidBody* m_editorBody = nullptr; + AzPhysics::SimulatedBodyHandle m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; AzPhysics::SceneHandle m_editorSceneHandle = AzPhysics::InvalidSceneHandle; AZ::Color m_centerOfMassDebugColor = AZ::Colors::White; diff --git a/Gems/PhysX/Code/Source/RigidBody.cpp b/Gems/PhysX/Code/Source/RigidBody.cpp index 6d1ece6a82..7fda0a1912 100644 --- a/Gems/PhysX/Code/Source/RigidBody.cpp +++ b/Gems/PhysX/Code/Source/RigidBody.cpp @@ -82,12 +82,8 @@ namespace PhysX SetName(configuration.m_debugName); SetGravityEnabled(configuration.m_gravityEnabled); - SetSimulationEnabled(configuration.m_simulated); SetCCDEnabled(configuration.m_ccdEnabled); - - AzPhysics::MassComputeFlags flags = configuration.GetMassComputeFlags(); - UpdateMassProperties(flags, &configuration.m_centerOfMassOffset, &configuration.m_inertiaTensor, - &configuration.m_mass); + SetKinematic(configuration.m_kinematic); if (configuration.m_customUserData) { @@ -459,7 +455,7 @@ namespace PhysX } } - AZ::Vector3 RigidBody::GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) + AZ::Vector3 RigidBody::GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const { return m_pxRigidActor ? GetLinearVelocity() + GetAngularVelocity().Cross(worldPoint - GetCenterOfMassWorld()) : diff --git a/Gems/PhysX/Code/Source/RigidBody.h b/Gems/PhysX/Code/Source/RigidBody.h index c9f171b261..07df60d649 100644 --- a/Gems/PhysX/Code/Source/RigidBody.h +++ b/Gems/PhysX/Code/Source/RigidBody.h @@ -63,7 +63,7 @@ namespace PhysX void SetLinearVelocity(const AZ::Vector3& velocity) override; AZ::Vector3 GetAngularVelocity() const override; void SetAngularVelocity(const AZ::Vector3& angularVelocity) override; - AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) override; + AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const override; void ApplyLinearImpulse(const AZ::Vector3& impulse) override; void ApplyLinearImpulseAtWorldPoint(const AZ::Vector3& impulse, const AZ::Vector3& worldPoint) override; void ApplyAngularImpulse(const AZ::Vector3& angularImpulse) override; diff --git a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp index cf2e306cc7..58b0749d0f 100644 --- a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp @@ -185,7 +185,6 @@ namespace PhysX { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_rigidBodyHandle); m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - m_rigidBody = nullptr; } Physics::RigidBodyRequestBus::Handler::BusDisconnect(); @@ -232,20 +231,33 @@ namespace PhysX // User sets kinematic Target ---> Update transform // User sets transform ---> Update kinematic target - if (!IsPhysicsEnabled() || (m_rigidBody->IsKinematic() && !m_isLastMovementFromKinematicSource)) + if (!IsPhysicsEnabled() || (IsKinematic() && !m_isLastMovementFromKinematicSource)) { return; } + auto* sceneInterface = AZ::Interface::Get(); + if (sceneInterface == nullptr) + { + AZ_Error("RigidBodyComponent", false, "PostPhysicsTick, SceneInterface is null"); + return; + } + + AzPhysics::SimulatedBody* rigidBody = + sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle); + if (rigidBody == nullptr) + { + AZ_Error("RigidBodyComponent", false, "Unable to retrieve simulated rigid body"); + return; + } + + AZ::Transform transform = rigidBody->GetTransform(); if (m_configuration.m_interpolateMotion) { - AZ::Transform transform = m_rigidBody->GetTransform(); - m_interpolator->SetTarget(transform.GetTranslation(), m_rigidBody->GetOrientation(), fixedDeltaTime); + m_interpolator->SetTarget(transform.GetTranslation(), rigidBody->GetOrientation(), fixedDeltaTime); } else { - AZ::Transform transform = m_rigidBody->GetTransform(); - // Maintain scale (this must be precise). AZ::Transform entityTransform = AZ::Transform::Identity(); AZ::TransformBus::EventResult(entityTransform, GetEntityId(), &AZ::TransformInterface::GetWorldTM); @@ -261,13 +273,17 @@ namespace PhysX // Note: OnTransformChanged is not safe at the moment due to TransformComponent design flaw. // It is called when the parent entity is activated after the children causing rigid body // to move through the level instantly. - if (IsPhysicsEnabled() && (m_rigidBody->IsKinematic() && !m_isLastMovementFromKinematicSource)) + if (AzPhysics::RigidBody* body = GetRigidBody()) { - m_rigidBody->SetKinematicTarget(world); - } - else if (!IsPhysicsEnabled()) - { - m_rigidBodyTransformNeedsUpdateOnPhysReEnable = true; + if (body->m_simulating && + (body->IsKinematic() && !m_isLastMovementFromKinematicSource)) + { + body->SetKinematicTarget(world); + } + else if (!body->m_simulating) + { + m_rigidBodyTransformNeedsUpdateOnPhysReEnable = true; + } } } @@ -290,16 +306,9 @@ namespace PhysX auto* sceneInterface = AZ::Interface::Get(); if (sceneInterface != nullptr) { + m_configuration.m_startSimulationEnabled = false; //enable physics will enable this when called. m_rigidBodyHandle = sceneInterface->AddSimulatedBody(m_attachedSceneHandle, &m_configuration); - m_rigidBody = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle)); - //disable simulating the body until EnablePhysics is called. - sceneInterface->DisableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); } - m_rigidBody->SetKinematic(m_configuration.m_kinematic); - - AzPhysics::MassComputeFlags flags = m_configuration.GetMassComputeFlags(); - m_rigidBody->UpdateMassProperties(flags, &m_configuration.m_centerOfMassOffset, &m_configuration.m_inertiaTensor, - &m_configuration.m_mass); // Listen to the PhysX system for events concerning this entity. if (sceneInterface != nullptr) @@ -319,16 +328,23 @@ namespace PhysX return; } - if (auto* sceneInterface = AZ::Interface::Get()) + auto* sceneInterface = AZ::Interface::Get(); + if (sceneInterface == nullptr) { - sceneInterface->EnableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); + AZ_Error("RigidBodyComponent", false, "Unable to enable physics, SceneInterface is null"); + return; } + SetSimulationEnabled(true); AZ::Transform transform = AZ::Transform::CreateIdentity(); AZ::TransformBus::EventResult(transform, GetEntityId(), &AZ::TransformInterface::GetWorldTM); if (m_rigidBodyTransformNeedsUpdateOnPhysReEnable) { - m_rigidBody->SetTransform(transform); + if (AzPhysics::SimulatedBody* body = + sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle)) + { + body->SetTransform(transform); + } m_rigidBodyTransformNeedsUpdateOnPhysReEnable = false; } @@ -345,188 +361,322 @@ namespace PhysX void RigidBodyComponent::DisablePhysics() { - if (auto* sceneInterface = AZ::Interface::Get()) - { - sceneInterface->DisableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); - } + SetSimulationEnabled(false); Physics::RigidBodyNotificationBus::Event(GetEntityId(), &Physics::RigidBodyNotificationBus::Events::OnPhysicsDisabled); } bool RigidBodyComponent::IsPhysicsEnabled() const { - return m_rigidBody != nullptr && m_rigidBody->m_simulating; + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->m_simulating; + } + return false; } void RigidBodyComponent::ApplyLinearImpulse(const AZ::Vector3& impulse) { - m_rigidBody->ApplyLinearImpulse(impulse); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ApplyLinearImpulse(impulse); + } } void RigidBodyComponent::ApplyLinearImpulseAtWorldPoint(const AZ::Vector3& impulse, const AZ::Vector3& worldSpacePoint) { - m_rigidBody->ApplyLinearImpulseAtWorldPoint(impulse, worldSpacePoint); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ApplyLinearImpulseAtWorldPoint(impulse, worldSpacePoint); + } } void RigidBodyComponent::ApplyAngularImpulse(const AZ::Vector3& impulse) { - m_rigidBody->ApplyAngularImpulse(impulse); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ApplyAngularImpulse(impulse); + } } AZ::Vector3 RigidBodyComponent::GetLinearVelocity() const { - return m_rigidBody->GetLinearVelocity(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetLinearVelocity(); + } + return AZ::Vector3::CreateZero(); } void RigidBodyComponent::SetLinearVelocity(const AZ::Vector3& velocity) { - m_rigidBody->SetLinearVelocity(velocity); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetLinearVelocity(velocity); + } } AZ::Vector3 RigidBodyComponent::GetAngularVelocity() const { - return m_rigidBody->GetAngularVelocity(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetAngularVelocity(); + } + return AZ::Vector3::CreateZero(); } void RigidBodyComponent::SetAngularVelocity(const AZ::Vector3& angularVelocity) { - m_rigidBody->SetAngularVelocity(angularVelocity); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetAngularVelocity(angularVelocity); + } } AZ::Vector3 RigidBodyComponent::GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const { - return m_rigidBody->GetLinearVelocityAtWorldPoint(worldPoint); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetLinearVelocityAtWorldPoint(worldPoint); + } + return AZ::Vector3::CreateZero(); } AZ::Vector3 RigidBodyComponent::GetCenterOfMassWorld() const { - return m_rigidBody->GetCenterOfMassWorld(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetCenterOfMassWorld(); + } + return AZ::Vector3::CreateZero(); } AZ::Vector3 RigidBodyComponent::GetCenterOfMassLocal() const { - return m_rigidBody->GetCenterOfMassLocal(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetCenterOfMassLocal(); + } + return AZ::Vector3::CreateZero(); } AZ::Matrix3x3 RigidBodyComponent::GetInverseInertiaWorld() const { - return m_rigidBody->GetInverseInertiaWorld(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetInverseInertiaWorld(); + } + return AZ::Matrix3x3::CreateZero(); } AZ::Matrix3x3 RigidBodyComponent::GetInverseInertiaLocal() const { - return m_rigidBody->GetInverseInertiaLocal(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetInverseInertiaLocal(); + } + return AZ::Matrix3x3::CreateZero(); } float RigidBodyComponent::GetMass() const { - return m_rigidBody->GetMass(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetMass(); + } + return 0.0f; } float RigidBodyComponent::GetInverseMass() const { - return m_rigidBody->GetInverseMass(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetInverseMass(); + } + return 0.0f; } void RigidBodyComponent::SetMass(float mass) { - m_rigidBody->SetMass(mass); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetMass(mass); + } } void RigidBodyComponent::SetCenterOfMassOffset(const AZ::Vector3& comOffset) { - m_rigidBody->SetCenterOfMassOffset(comOffset); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetCenterOfMassOffset(comOffset); + } } float RigidBodyComponent::GetLinearDamping() const { - return m_rigidBody->GetLinearDamping(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetLinearDamping(); + } + return 0.0f; } void RigidBodyComponent::SetLinearDamping(float damping) { - m_rigidBody->SetLinearDamping(damping); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetLinearDamping(damping); + } } float RigidBodyComponent::GetAngularDamping() const { - return m_rigidBody->GetAngularDamping(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetAngularDamping(); + } + return 0.0f; } void RigidBodyComponent::SetAngularDamping(float damping) { - m_rigidBody->SetAngularDamping(damping); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetAngularDamping(damping); + } } bool RigidBodyComponent::IsAwake() const { - return m_rigidBody->IsAwake(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->IsAwake(); + } + return false; } void RigidBodyComponent::ForceAsleep() { - m_rigidBody->ForceAsleep(); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ForceAsleep(); + } } void RigidBodyComponent::ForceAwake() { - m_rigidBody->ForceAwake(); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ForceAwake(); + } } bool RigidBodyComponent::IsKinematic() const { - return m_rigidBody->IsKinematic(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->IsKinematic(); + } + return false; } void RigidBodyComponent::SetKinematic(bool kinematic) { - m_rigidBody->SetKinematic(kinematic); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetKinematic(kinematic); + } } void RigidBodyComponent::SetKinematicTarget(const AZ::Transform& targetPosition) { m_isLastMovementFromKinematicSource = true; - m_rigidBody->SetKinematicTarget(targetPosition); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetKinematicTarget(targetPosition); + } } bool RigidBodyComponent::IsGravityEnabled() const { - return m_rigidBody->IsGravityEnabled(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->IsGravityEnabled(); + } + return false; } void RigidBodyComponent::SetGravityEnabled(bool enabled) { - m_rigidBody->SetGravityEnabled(enabled); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetGravityEnabled(enabled); + } } void RigidBodyComponent::SetSimulationEnabled(bool enabled) { - m_rigidBody->SetSimulationEnabled(enabled); + if (auto* sceneInterface = AZ::Interface::Get()) + { + if (enabled) + { + sceneInterface->EnableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); + } + else + { + sceneInterface->DisableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); + } + } } float RigidBodyComponent::GetSleepThreshold() const { - return m_rigidBody->GetSleepThreshold(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetSleepThreshold(); + } + return 0.0f; } void RigidBodyComponent::SetSleepThreshold(float threshold) { - m_rigidBody->SetSleepThreshold(threshold); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetSleepThreshold(threshold); + } } AZ::Aabb RigidBodyComponent::GetAabb() const { - return m_rigidBody->GetAabb(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetAabb(); + } + return AZ::Aabb::CreateNull(); } AzPhysics::RigidBody* RigidBodyComponent::GetRigidBody() { - return m_rigidBody; + return azdynamic_cast(GetSimulatedBody()); } AzPhysics::SimulatedBody* RigidBodyComponent::GetSimulatedBody() { - return m_rigidBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle); + } + return nullptr; + } + + const AzPhysics::RigidBody* RigidBodyComponent::GetRigidBodyConst() const + { + if (auto* sceneInterface = AZ::Interface::Get()) + { + return azdynamic_cast( + sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle)); + } + return nullptr; } AzPhysics::SimulatedBodyHandle RigidBodyComponent::GetSimulatedBodyHandle() const @@ -536,9 +686,9 @@ namespace PhysX AzPhysics::SceneQueryHit RigidBodyComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_rigidBody) + if (AzPhysics::RigidBody* body = GetRigidBody()) { - return m_rigidBody->RayCast(request); + return body->RayCast(request); } return AzPhysics::SceneQueryHit(); } diff --git a/Gems/PhysX/Code/Source/RigidBodyComponent.h b/Gems/PhysX/Code/Source/RigidBodyComponent.h index 12c4d3f5ff..7b2a34cf37 100644 --- a/Gems/PhysX/Code/Source/RigidBodyComponent.h +++ b/Gems/PhysX/Code/Source/RigidBodyComponent.h @@ -153,11 +153,12 @@ namespace PhysX void InitPhysicsTickHandler(); void PostPhysicsTick(float fixedDeltaTime); + const AzPhysics::RigidBody* GetRigidBodyConst() const; + std::unique_ptr m_interpolator; AzPhysics::RigidBodyConfiguration m_configuration; AzPhysics::SimulatedBodyHandle m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - AzPhysics::RigidBody* m_rigidBody = nullptr; AzPhysics::SceneHandle m_attachedSceneHandle = AzPhysics::InvalidSceneHandle; AZ::Vector3 m_initialScale = AZ::Vector3::CreateOne(); diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp index 03bbac9fd4..96e2d8a9bb 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp @@ -189,6 +189,22 @@ namespace PhysX return newBody; } + AzPhysics::SimulatedBody* CreateRigidBody(const AzPhysics::RigidBodyConfiguration* configuration, AZ::Crc32& crc) + { + RigidBody* newBody = aznew RigidBody(*configuration); + if (!AZStd::holds_alternative(configuration->m_colliderAndShapeData)) + { + const bool shapeAdded = AddShape(newBody, configuration->m_colliderAndShapeData); + AZ_Warning("PhysXScene", shapeAdded, "No Collider or Shape information found when creating Rigid body [%s]", configuration->m_debugName.c_str()); + } + const AzPhysics::MassComputeFlags& flags = configuration->GetMassComputeFlags(); + newBody->UpdateMassProperties(flags, &configuration->m_centerOfMassOffset, + &configuration->m_inertiaTensor, &configuration->m_mass); + + crc = AZ::Crc32(newBody, sizeof(*newBody)); + return newBody; + } + AzPhysics::SimulatedBody* CreateCharacterBody(PhysXScene* scene, const Physics::CharacterConfiguration* characterConfig) { @@ -617,7 +633,7 @@ namespace PhysX AZ::Crc32 newBodyCrc; if (azrtti_istypeof(simulatedBodyConfig)) { - newBody = Internal::CreateSimulatedBody( + newBody = Internal::CreateRigidBody( azdynamic_cast(simulatedBodyConfig), newBodyCrc); } else if (azrtti_istypeof(simulatedBodyConfig)) diff --git a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp index 79e5ea8204..881fb29750 100644 --- a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp @@ -100,7 +100,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { m_staticRigidBodyHandle = sceneInterface->AddSimulatedBody(m_attachedSceneHandle, &configuration); - m_staticRigidBody = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle)); } } @@ -119,16 +118,18 @@ namespace PhysX { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_staticRigidBodyHandle); m_staticRigidBodyHandle = AzPhysics::InvalidSceneHandle; - m_staticRigidBody = nullptr; } AzPhysics::SimulatedBodyComponentRequestsBus::Handler::BusDisconnect(); AZ::TransformNotificationBus::Handler::BusDisconnect(); } - void StaticRigidBodyComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) + void StaticRigidBodyComponent::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) { - m_staticRigidBody->SetTransform(world); + if (AzPhysics::SimulatedBody* body = GetSimulatedBody()) + { + body->SetTransform(world); + } } void StaticRigidBodyComponent::EnablePhysics() @@ -153,12 +154,31 @@ namespace PhysX bool StaticRigidBodyComponent::IsPhysicsEnabled() const { - return m_staticRigidBody != nullptr && m_staticRigidBody->m_simulating; + if (m_staticRigidBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) + { + if (auto* sceneInterface = AZ::Interface::Get(); + sceneInterface != nullptr && + sceneInterface->IsEnabled(m_attachedSceneHandle))//check if the scene is enabled + { + if (AzPhysics::SimulatedBody* body = sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle)) + { + return body->m_simulating; + } + } + } + return false; } AZ::Aabb StaticRigidBodyComponent::GetAabb() const { - return m_staticRigidBody->GetAabb(); + if (auto* sceneInterface = AZ::Interface::Get()) + { + if (AzPhysics::SimulatedBody* body = sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle)) + { + return body->GetAabb(); + } + } + return AZ::Aabb::CreateNull(); } AzPhysics::SimulatedBodyHandle StaticRigidBodyComponent::GetSimulatedBodyHandle() const @@ -168,14 +188,18 @@ namespace PhysX AzPhysics::SimulatedBody* StaticRigidBodyComponent::GetSimulatedBody() { - return m_staticRigidBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle); + } + return nullptr; } AzPhysics::SceneQueryHit StaticRigidBodyComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_staticRigidBody) + if (auto* body = azdynamic_cast(GetSimulatedBody())) { - return m_staticRigidBody->RayCast(request); + return body->RayCast(request); } return AzPhysics::SceneQueryHit(); } diff --git a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h index 660521ab7a..0f5bf1a4b2 100644 --- a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h +++ b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h @@ -65,7 +65,6 @@ namespace PhysX void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; AzPhysics::SimulatedBodyHandle m_staticRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - PhysX::StaticRigidBody* m_staticRigidBody = nullptr; AzPhysics::SceneHandle m_attachedSceneHandle = AzPhysics::InvalidSceneHandle; }; } // namespace PhysX diff --git a/Gems/PhysX/Code/Source/System/PhysXSystem.cpp b/Gems/PhysX/Code/Source/System/PhysXSystem.cpp index 1d925570c5..1622d04aae 100644 --- a/Gems/PhysX/Code/Source/System/PhysXSystem.cpp +++ b/Gems/PhysX/Code/Source/System/PhysXSystem.cpp @@ -140,6 +140,9 @@ namespace PhysX } }; + AZ_Warning("PhysXSystem", deltaTime <= m_systemConfig.m_maxTimestep, + "Frame delta time of [%.6f seconds] exceeds Physics max frame timestep, physics timestep will be clamped to [%.6f seconds].", + deltaTime, m_systemConfig.m_maxTimestep); deltaTime = AZ::GetClamp(deltaTime, 0.0f, m_systemConfig.m_maxTimestep); AZ_Assert(m_systemConfig.m_fixedTimestep >= 0.0f, "PhysXSystem - fixed timestep is negitive."); diff --git a/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp b/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp index 2404a60e0d..93ad7704c9 100644 --- a/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp +++ b/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp @@ -415,6 +415,10 @@ namespace PhysX Physics::SphereShapeConfiguration shapeConfiguration; shapeConfiguration.m_radius = radius; AzPhysics::RigidBodyConfiguration rigidBodySettings; + rigidBodySettings.m_computeMass = false; + rigidBodySettings.m_computeInertiaTensor = false; + rigidBodySettings.m_computeCenterOfMass = false; + rigidBodySettings.m_mass = 1.0f; rigidBodySettings.m_position = position; rigidBodySettings.m_linearDamping = 0.0f; rigidBodySettings.m_colliderAndShapeData = AZStd::make_pair(&colliderConfig, &shapeConfiguration); @@ -437,6 +441,10 @@ namespace PhysX Physics::CapsuleShapeConfiguration shapeConfig(height, radius); rigidBodySettings.m_colliderAndShapeData = AZStd::make_pair(&colliderConfig, &shapeConfig); rigidBodySettings.m_position = position; + rigidBodySettings.m_computeMass = false; + rigidBodySettings.m_computeInertiaTensor = false; + rigidBodySettings.m_computeCenterOfMass = false; + rigidBodySettings.m_mass = 1.0f; if (auto* sceneInterface = AZ::Interface::Get()) { @@ -455,6 +463,10 @@ namespace PhysX shapeConfiguration.m_dimensions = dimensions; AzPhysics::RigidBodyConfiguration rigidBodySettings; + rigidBodySettings.m_computeMass = false; + rigidBodySettings.m_computeInertiaTensor = false; + rigidBodySettings.m_computeCenterOfMass = false; + rigidBodySettings.m_mass = 1.0f; rigidBodySettings.m_position = position; rigidBodySettings.m_linearDamping = 0.0f; rigidBodySettings.m_colliderAndShapeData = AZStd::make_pair(&colliderConfig, &shapeConfiguration); From a13c9e8d531c25d2c490e127f63d2964b3ba9c08 Mon Sep 17 00:00:00 2001 From: Hasareej <82398396+Hasareej@users.noreply.github.com> Date: Thu, 13 May 2021 14:23:31 +0100 Subject: [PATCH 087/231] Hasareej lyn 2301 cluster space (#717) ViewportUi widget anchoring & alignment update. --- .../EditorTransformComponentSelection.cpp | 2 +- .../ViewportUi/ViewportUiDisplay.cpp | 30 ++++++++++++++++--- .../ViewportUi/ViewportUiDisplay.h | 4 +-- .../ViewportUi/ViewportUiManager.cpp | 8 ++--- .../ViewportUi/ViewportUiManager.h | 4 +-- .../ViewportUi/ViewportUiRequestBus.h | 15 ++++++++-- .../Tests/Viewport/ViewportUiDisplayTests.cpp | 10 +++---- .../Tests/Viewport/ViewportUiManagerTests.cpp | 12 ++++---- .../Code/Editor/ColliderComponentMode.cpp | 2 +- .../Source/EditorWhiteBoxComponentMode.cpp | 2 +- 10 files changed, 61 insertions(+), 28 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index c6450d03c7..1766e65276 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -2526,7 +2526,7 @@ namespace AzToolsFramework // create the cluster for changing transform mode ViewportUi::ViewportUiRequestBus::EventResult( m_transformModeClusterId, ViewportUi::DefaultViewportId, - &ViewportUi::ViewportUiRequestBus::Events::CreateCluster); + &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"); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp index e67ac46f62..e9e7dcc1cc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp @@ -41,6 +41,28 @@ namespace AzToolsFramework::ViewportUi::Internal } } + static Qt::Alignment GetQtAlignment(Alignment align) + { + switch (align) + { + case Alignment::TopRight: + return Qt::AlignTop | Qt::AlignRight; + case Alignment::TopLeft: + return Qt::AlignTop | Qt::AlignLeft; + case Alignment::BottomRight: + return Qt::AlignBottom | Qt::AlignRight; + case Alignment::BottomLeft: + return Qt::AlignBottom | Qt::AlignLeft; + case Alignment::Top: + return Qt::AlignTop; + case Alignment::Bottom: + return Qt::AlignBottom; + } + + AZ_Assert(false, "ViewportUI", "Unhandled ViewportUI Alignment %d", static_cast(align)); + return Qt::AlignTop; + } + ViewportUiDisplay::ViewportUiDisplay(QWidget* parent, QWidget* renderOverlay) : m_renderOverlay(renderOverlay) , m_uiMainWindow(parent) @@ -56,7 +78,7 @@ namespace AzToolsFramework::ViewportUi::Internal UnparentWidgets(m_viewportUiElements); } - void ViewportUiDisplay::AddCluster(AZStd::shared_ptr buttonGroup) + void ViewportUiDisplay::AddCluster(AZStd::shared_ptr buttonGroup, const Alignment align) { if (!buttonGroup.get()) { @@ -66,7 +88,7 @@ namespace AzToolsFramework::ViewportUi::Internal auto viewportUiCluster = AZStd::make_shared(buttonGroup); auto id = AddViewportUiElement(viewportUiCluster); buttonGroup->SetViewportUiElementId(id); - PositionViewportUiElementAnchored(id, Qt::AlignTop | Qt::AlignLeft); + PositionViewportUiElementAnchored(id, GetQtAlignment(align)); } void ViewportUiDisplay::AddClusterButton( @@ -94,7 +116,7 @@ namespace AzToolsFramework::ViewportUi::Internal } } - void ViewportUiDisplay::AddSwitcher(AZStd::shared_ptr buttonGroup) + void ViewportUiDisplay::AddSwitcher(AZStd::shared_ptr buttonGroup, const Alignment align) { if (!buttonGroup.get()) { @@ -104,7 +126,7 @@ namespace AzToolsFramework::ViewportUi::Internal auto viewportUiSwitcher = AZStd::make_shared(buttonGroup); auto id = AddViewportUiElement(viewportUiSwitcher); buttonGroup->SetViewportUiElementId(id); - PositionViewportUiElementAnchored(id, Qt::AlignTop | Qt::AlignLeft); + PositionViewportUiElementAnchored(id, GetQtAlignment(align)); } void ViewportUiDisplay::AddSwitcherButton(const ViewportUiElementId clusterId, Button* button) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h index 7ef81986c0..d46e01c978 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h @@ -56,12 +56,12 @@ namespace AzToolsFramework::ViewportUi::Internal ViewportUiDisplay(QWidget* parent, QWidget* renderOverlay); ~ViewportUiDisplay(); - void AddCluster(AZStd::shared_ptr buttonGroup); + void AddCluster(AZStd::shared_ptr buttonGroup, Alignment align); void AddClusterButton(ViewportUiElementId clusterId, Button* button); void RemoveClusterButton(ViewportUiElementId clusterId, ButtonId buttonId); void UpdateCluster(const ViewportUiElementId clusterId); - void AddSwitcher(AZStd::shared_ptr buttonGroup); + void AddSwitcher(AZStd::shared_ptr buttonGroup, Alignment align); void AddSwitcherButton(ViewportUiElementId switcherId, Button* button); void RemoveSwitcherButton(ViewportUiElementId switcherId, ButtonId buttonId); void UpdateSwitcher(ViewportUiElementId switcherId); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp index 6eb97adb93..12c3b5c9bb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp @@ -30,18 +30,18 @@ namespace AzToolsFramework::ViewportUi ViewportUiRequestBus::Handler::BusDisconnect(); } - const ClusterId ViewportUiManager::CreateCluster() + const ClusterId ViewportUiManager::CreateCluster(const Alignment align) { auto buttonGroup = AZStd::make_shared(); - m_viewportUi->AddCluster(buttonGroup); + m_viewportUi->AddCluster(buttonGroup, align); return RegisterNewCluster(buttonGroup); } - const SwitcherId ViewportUiManager::CreateSwitcher() + const SwitcherId ViewportUiManager::CreateSwitcher(const Alignment align) { auto buttonGroup = AZStd::make_shared(); - m_viewportUi->AddSwitcher(buttonGroup); + m_viewportUi->AddSwitcher(buttonGroup, align); return RegisterNewSwitcher(buttonGroup); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h index 1b350bbd64..04a58cef65 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h @@ -31,8 +31,8 @@ namespace AzToolsFramework::ViewportUi ~ViewportUiManager() = default; // ViewportUiRequestBus ... - const ClusterId CreateCluster() override; - const SwitcherId CreateSwitcher() override; + const ClusterId CreateCluster(Alignment align) override; + const SwitcherId CreateSwitcher(Alignment align) override; void SetClusterActiveButton(ClusterId clusterId, ButtonId buttonId) override; void SetSwitcherActiveButton(SwitcherId switcherId, ButtonId buttonId) override; const ButtonId CreateClusterButton(ClusterId clusterId, const AZStd::string& icon) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h index 5041f28656..3879817ccb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h @@ -41,15 +41,26 @@ namespace AzToolsFramework::ViewportUi String }; + //! Used to anchor widgets to a specific side of the viewport. + enum class Alignment + { + TopRight, + TopLeft, + BottomRight, + BottomLeft, + Top, + Bottom + }; + //! Viewport requests to interact with the Viewport UI. Viewport UI refers to the entire UI overlay (one per viewport). //! Each widget on the Viewport UI is referred to as an element. class ViewportUiRequests { public: //! Creates and registers a cluster with the Viewport UI system. - virtual const ClusterId CreateCluster() = 0; + virtual const ClusterId CreateCluster(Alignment align) = 0; //! Creates and registers a switcher with the Viewport UI system. - virtual const SwitcherId CreateSwitcher() = 0; + virtual const SwitcherId CreateSwitcher(Alignment align) = 0; //! Sets the active button of the cluster. This is the button which will display as highlighted. virtual void SetClusterActiveButton(ClusterId clusterId, ButtonId buttonId) = 0; //! Sets the active button of the switcher. This is the button which has a text label. diff --git a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp index a1ce868569..5fd102b450 100644 --- a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp @@ -72,7 +72,7 @@ namespace UnitTest TEST_F(ViewportUiDisplayTestFixture, RemoveViewportUiElementRemovesElementFromViewportUi) { ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); auto widget = viewportUi.GetViewportUiElement(m_buttonGroup->GetViewportUiElementId()); EXPECT_TRUE(widget.get() != nullptr); @@ -89,7 +89,7 @@ namespace UnitTest ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); viewportUi.InitializeUiOverlay(); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.Update(); viewportUi.ShowViewportUiElement(m_buttonGroup->GetViewportUiElementId()); @@ -102,7 +102,7 @@ namespace UnitTest ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); viewportUi.InitializeUiOverlay(); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.HideViewportUiElement(m_buttonGroup->GetViewportUiElementId()); EXPECT_FALSE(viewportUi.IsViewportUiElementVisible(m_buttonGroup->GetViewportUiElementId())); @@ -112,7 +112,7 @@ namespace UnitTest { ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); viewportUi.InitializeUiOverlay(); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.Update(); auto widget = viewportUi.GetViewportUiElement(m_buttonGroup->GetViewportUiElementId()); @@ -129,7 +129,7 @@ namespace UnitTest auto buttonGroup = AZStd::make_shared(); buttonGroup->AddButton(""); - viewportUi.AddCluster(buttonGroup); + viewportUi.AddCluster(buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.Update(); EXPECT_TRUE(viewportUi.GetUiMainWindow()->isVisible()); diff --git a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp index 396bde3fdd..9babd0fe6d 100644 --- a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp @@ -101,7 +101,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, CreateClusterAddsNewClusterAndReturnsId) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); EXPECT_TRUE(clusterEntry != m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().end()); @@ -110,7 +110,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, CreateClusterButtonAddsNewButtonAndReturnsId) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); @@ -120,7 +120,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, SetClusterActiveButtonSetsButtonStateToActive) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); @@ -133,7 +133,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, RegisterClusterEventHandlerConnectsHandlerToClusterEvent) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); // create a handler which will be triggered by the cluster @@ -159,7 +159,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, RemoveClusterRemovesClusterFromViewportUi) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); m_viewportManagerWrapper.GetViewportManager()->RemoveCluster(clusterId); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); @@ -171,7 +171,7 @@ namespace UnitTest { m_viewportManagerWrapper.GetMockRenderOverlay()->setVisible(true); - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); m_viewportManagerWrapper.GetViewportManager()->Update(); diff --git a/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp b/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp index 9aece90d90..7caa497344 100644 --- a/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp @@ -240,7 +240,7 @@ namespace PhysX // create the cluster for changing transform mode AzToolsFramework::ViewportUi::ViewportUiRequestBus::EventResult( m_modeSelectionClusterId, AzToolsFramework::ViewportUi::DefaultViewportId, - &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster); + &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster, AzToolsFramework::ViewportUi::Alignment::TopLeft); // create and register the buttons m_dimensionsModeButtonId = RegisterClusterButton(m_modeSelectionClusterId, "Scale"); diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp index 7677ee69f4..0772851cba 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp @@ -482,7 +482,7 @@ namespace WhiteBox // create the cluster for changing transform mode AzToolsFramework::ViewportUi::ViewportUiRequestBus::EventResult( m_modeSelectionClusterId, AzToolsFramework::ViewportUi::DefaultViewportId, - &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster); + &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster, AzToolsFramework::ViewportUi::Alignment::TopLeft); // create and register the buttons m_defaultModeButtonId = RegisterClusterButton(m_modeSelectionClusterId, "SketchMode"); From 7f79cc879698118c05dba138270e5e36955c94c2 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Thu, 13 May 2021 15:04:00 +0100 Subject: [PATCH 088/231] RemoveSimulatedBody automatically updates the requested handle to be invalid once removed. (#740) --- .../AzFramework/Physics/PhysicsScene.h | 16 ++++++++-------- Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h | 4 ++-- .../Code/Source/EditorColliderComponent.cpp | 4 ---- .../Code/Source/EditorRigidBodyComponent.cpp | 2 -- .../Code/Source/EditorShapeColliderComponent.cpp | 2 -- .../PhysXCharacters/API/CharacterController.cpp | 1 - .../Source/PhysXCharacters/API/RagdollNode.cpp | 1 - Gems/PhysX/Code/Source/RigidBodyComponent.cpp | 1 - Gems/PhysX/Code/Source/Scene/PhysXScene.cpp | 6 ++++-- Gems/PhysX/Code/Source/Scene/PhysXScene.h | 4 ++-- .../Code/Source/Scene/PhysXSceneInterface.cpp | 4 ++-- .../Code/Source/Scene/PhysXSceneInterface.h | 4 ++-- .../Code/Source/StaticRigidBodyComponent.cpp | 1 - .../Benchmarks/PhysXBenchmarkWashingMachine.cpp | 2 -- .../Tests/Benchmarks/PhysXJointBenchmarks.cpp | 5 +---- .../Benchmarks/PhysXRigidBodyBenchmarks.cpp | 15 +++------------ Gems/PhysX/Code/Tests/PhysXSceneTests.cpp | 9 +++++++-- Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp | 1 - .../Code/Tests/ScriptCanvasPhysicsTest.cpp | 4 ++-- .../EditorWhiteBoxColliderComponent.cpp | 1 - .../Components/WhiteBoxColliderComponent.cpp | 1 - 21 files changed, 33 insertions(+), 55 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h b/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h index db3ec15c83..58e53b0b0d 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h @@ -88,13 +88,13 @@ namespace AzPhysics //! Remove a simulated body from the Scene.z //! @param sceneHandle A handle to the scene to remove the requested simulated body. - //! @param bodyHandle A handle to the simulated body being removed. - virtual void RemoveSimulatedBody(SceneHandle sceneHandle, SimulatedBodyHandle bodyHandle) = 0; + //! @param bodyHandle A handle to the simulated body being removed. This will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBody(SceneHandle sceneHandle, SimulatedBodyHandle& bodyHandle) = 0; //! Remove a list of simulated bodies from the Scene. //! @param sceneHandle A handle to the scene to remove the simulated bodies from. - //! @param bodyHandles A list of simulated body handles to be removed. - virtual void RemoveSimulatedBodies(SceneHandle sceneHandle, const SimulatedBodyHandleList& bodyHandles) = 0; + //! @param bodyHandles A list of simulated body handles to be removed. All handles will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBodies(SceneHandle sceneHandle, SimulatedBodyHandleList& bodyHandles) = 0; //! Enable / Disable simulation of the requested body. By default all bodies added are enabled. //! Disabling simulation the body will no longer be affected by any forces, collisions, or found with scene queries. @@ -286,12 +286,12 @@ namespace AzPhysics virtual SimulatedBodyList GetSimulatedBodiesFromHandle(const SimulatedBodyHandleList& bodyHandles) = 0; //! Remove a simulated body from the Scene. - //! @param bodyHandle A handle to the simulated body being removed. - virtual void RemoveSimulatedBody(SimulatedBodyHandle bodyHandle) = 0; + //! @param bodyHandle A handle to the simulated body being removed. This will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBody(SimulatedBodyHandle& bodyHandle) = 0; //! Remove a list of simulated bodies from the Scene. - //! @param bodyHandles A list of simulated body handles to be removed. - virtual void RemoveSimulatedBodies(const SimulatedBodyHandleList& bodyHandles) = 0; + //! @param bodyHandles A list of simulated body handles to be removed. All handles will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBodies(SimulatedBodyHandleList& bodyHandles) = 0; //! Enable / Disable simulation of the requested body. By default all bodies added are enabled. //! Disabling simulation the body will no longer be affected by any forces, collisions, or found with scene queries. diff --git a/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h b/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h index 1219e34448..22102fd38a 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h @@ -92,10 +92,10 @@ namespace Physics [[maybe_unused]] bool enable) override {} void RemoveSimulatedBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandle& bodyHandle) override {} void RemoveSimulatedBodies( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] const AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} void EnableSimulationOfBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 2cf5835a1f..18bb06ba74 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -405,7 +405,6 @@ namespace PhysX if (m_sceneInterface) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } @@ -579,7 +578,6 @@ namespace PhysX if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } return; } @@ -634,7 +632,6 @@ namespace PhysX if (m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } m_editorBodyHandle = m_sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); @@ -1051,7 +1048,6 @@ namespace PhysX if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp index f97e7c6cbd..efd65181da 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp @@ -283,7 +283,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); - m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } @@ -428,7 +427,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); - m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; CreateEditorWorldRigidBody(); } diff --git a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp index b71bd47288..58b8995281 100644 --- a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp @@ -271,7 +271,6 @@ namespace PhysX if (m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } m_editorBodyHandle = m_sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); @@ -681,7 +680,6 @@ namespace PhysX if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp index 9e5f92aa72..08df8c0601 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp @@ -343,7 +343,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_sceneOwner, m_shadowBodyHandle); - m_shadowBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; m_shadowBody = nullptr; } } diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp index 6e3b97212b..0f9c7644cd 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp @@ -163,7 +163,6 @@ namespace PhysX sceneInterface->RemoveSimulatedBody(m_sceneOwner, m_rigidBodyHandle); } m_rigidBody = nullptr; - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; m_sceneOwner = AzPhysics::InvalidSceneHandle; } } diff --git a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp index 58b0749d0f..f770f8408c 100644 --- a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp @@ -184,7 +184,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } Physics::RigidBodyRequestBus::Handler::BusDisconnect(); diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp index 96e2d8a9bb..79aa767959 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp @@ -729,7 +729,7 @@ namespace PhysX return results; } - void PhysXScene::RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle bodyHandle) + void PhysXScene::RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle& bodyHandle) { if (bodyHandle == AzPhysics::InvalidSimulatedBodyHandle) { @@ -751,10 +751,12 @@ namespace PhysX m_deferredDeletions.push_back(m_simulatedBodies[index].second); m_simulatedBodies[index] = AZStd::make_pair(AZ::Crc32(), nullptr); m_freeSceneSlots.push(index); + + bodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } - void PhysXScene::RemoveSimulatedBodies(const AzPhysics::SimulatedBodyHandleList& bodyHandles) + void PhysXScene::RemoveSimulatedBodies(AzPhysics::SimulatedBodyHandleList& bodyHandles) { for (auto& handle: bodyHandles) { diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.h b/Gems/PhysX/Code/Source/Scene/PhysXScene.h index 8bf20fca55..2e257283f0 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.h +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.h @@ -48,8 +48,8 @@ namespace PhysX AzPhysics::SimulatedBodyHandleList AddSimulatedBodies(const AzPhysics::SimulatedBodyConfigurationList& simulatedBodyConfigs) override; AzPhysics::SimulatedBody* GetSimulatedBodyFromHandle(AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SimulatedBodyList GetSimulatedBodiesFromHandle(const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; - void RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle bodyHandle) override; - void RemoveSimulatedBodies(const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; + void RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle& bodyHandle) override; + void RemoveSimulatedBodies(AzPhysics::SimulatedBodyHandleList& bodyHandles) override; void EnableSimulationOfBody(AzPhysics::SimulatedBodyHandle bodyHandle) override; void DisableSimulationOfBody(AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SceneQueryHits QueryScene(const AzPhysics::SceneQueryRequest* request) override; diff --git a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp index 948529a5c8..3b3ab2f0f8 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp @@ -112,7 +112,7 @@ namespace PhysX return {}; //return an empty list } - void PhysXSceneInterface::RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) + void PhysXSceneInterface::RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle& bodyHandle) { if (AzPhysics::Scene* scene = m_physxSystem->GetScene(sceneHandle)) { @@ -120,7 +120,7 @@ namespace PhysX } } - void PhysXSceneInterface::RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyHandleList& bodyHandles) + void PhysXSceneInterface::RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandleList& bodyHandles) { if (AzPhysics::Scene* scene = m_physxSystem->GetScene(sceneHandle)) { diff --git a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h index 3bc08d641c..2edfbd8457 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h +++ b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h @@ -40,8 +40,8 @@ namespace PhysX AzPhysics::SimulatedBodyHandleList AddSimulatedBodies(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyConfigurationList& simulatedBodyConfigs) override; AzPhysics::SimulatedBody* GetSimulatedBodyFromHandle(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SimulatedBodyList GetSimulatedBodiesFromHandle(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; - void RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; - void RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; + void RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle& bodyHandle) override; + void RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandleList& bodyHandles) override; void EnableSimulationOfBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; void DisableSimulationOfBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SceneQueryHits QueryScene(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SceneQueryRequest* request) override; diff --git a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp index 881fb29750..bb1dfc4293 100644 --- a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp @@ -117,7 +117,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_staticRigidBodyHandle); - m_staticRigidBodyHandle = AzPhysics::InvalidSceneHandle; } AzPhysics::SimulatedBodyComponentRequestsBus::Handler::BusDisconnect(); diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp index 463aea2f71..adc910e8c8 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp @@ -129,10 +129,8 @@ namespace PhysX::Benchmarks for (int i = 0; i < NumCylinderSide; i++) { sceneInterface->RemoveSimulatedBody(m_sceneHandle, m_cylinder[i]); - m_cylinder[i] = AzPhysics::InvalidSimulatedBodyHandle; } sceneInterface->RemoveSimulatedBody(m_sceneHandle, m_blade); - m_blade = AzPhysics::InvalidSimulatedBodyHandle; } m_sceneHandle = AzPhysics::InvalidSceneHandle; } diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp index 7143f08626..7d650d6bef 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp @@ -404,10 +404,7 @@ namespace PhysX::Benchmarks } subTickTracker.Stop(); - for (auto handle : snakeRigidBodyHandles) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(snakeRigidBodyHandles); snakeRigidBodyHandles.clear(); //sort the frame times and get the P50, P90, P99 percentiles diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp index 54f7d2219c..e295916554 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp @@ -233,10 +233,7 @@ namespace PhysX::Benchmarks subTickTracker.Stop(); //object clean up - for (auto handle : rigidBodies) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(rigidBodies); rigidBodies.clear(); //sort the frame times and get the P50, P90, P99 percentiles @@ -310,10 +307,7 @@ namespace PhysX::Benchmarks //object clean up washingMachine.TearDownWashingMachine(); - for (auto handle : rigidBodies) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(rigidBodies); rigidBodies.clear(); //sort the frame times and get the P50, P90, P99 percentiles @@ -465,10 +459,7 @@ namespace PhysX::Benchmarks //object clean up collisionHandlers.clear(); washingMachine.TearDownWashingMachine(); - for (auto handle : rigidBodies) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(rigidBodies); rigidBodies.clear(); //sort the frame times and get the P50, P90, P99 percentiles diff --git a/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp b/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp index 2a30fad32d..2a38e1b867 100644 --- a/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp @@ -237,13 +237,17 @@ namespace PhysX //select 1 to remove AzPhysics::SimulatedBodyHandle removedSelection = simBodyHandles[simBodyHandles.size() / 2]; + const AzPhysics::SimulatedBodyIndex removedIndex = AZStd::get(removedSelection); sceneInterface->RemoveSimulatedBody(m_testSceneHandle, removedSelection); + // The removedSelection handle should be set to invalid in RemoveSimulatedBody + EXPECT_EQ(removedSelection, AzPhysics::InvalidSimulatedBodyHandle); + //add a new one. AzPhysics::SimulatedBodyHandle newSimBodyHandle = sceneInterface->AddSimulatedBody(m_testSceneHandle, &config); //The old and new handle should share an index as the freed slot will be used - EXPECT_EQ(AZStd::get(removedSelection), + EXPECT_EQ(removedIndex, AZStd::get(newSimBodyHandle)); } @@ -287,9 +291,10 @@ namespace PhysX EXPECT_EQ(simBodyHandle, addEventSimBodyHandle); //remove the body + const AzPhysics::SimulatedBodyHandle removedHandle = simBodyHandle; //copy the handle as RemoveSimulatedBody will mark it invalid. sceneInterface->RemoveSimulatedBody(m_testSceneHandle, simBodyHandle); EXPECT_TRUE(removedTriggered); - EXPECT_EQ(simBodyHandle, removeEventSimBodyHandle); + EXPECT_EQ(removedHandle, removeEventSimBodyHandle); } TEST_F(PhysXSceneFixture, StartFinishSimulationEvents_triggerAsExpected) diff --git a/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp b/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp index 8e4da0fe4b..74c88d0b46 100644 --- a/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp +++ b/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp @@ -882,7 +882,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_testSceneHandle, rigidBodyHandle); - rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } rigidBody = nullptr; } diff --git a/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp b/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp index c74030d6df..4b04434e13 100644 --- a/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp +++ b/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp @@ -90,10 +90,10 @@ namespace ScriptCanvasPhysicsTests [[maybe_unused]] bool enable) override {} void RemoveSimulatedBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandle& bodyHandle) override {} void RemoveSimulatedBodies( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] const AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} void EnableSimulationOfBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} diff --git a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp index 97bce7631d..c8b189942e 100644 --- a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp @@ -163,7 +163,6 @@ namespace WhiteBox if (m_sceneInterface) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } diff --git a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp index 117b175cda..41d0a4c5e3 100644 --- a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp @@ -132,7 +132,6 @@ namespace WhiteBox sceneInterface->RemoveSimulatedBody(defaultScene, m_simulatedBodyHandle); } } - m_simulatedBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } void WhiteBoxColliderComponent::OnTransformChanged( From 4aff32e719c604b59ccdef7e21ce3dcd9923a8dc Mon Sep 17 00:00:00 2001 From: bosnichd Date: Thu, 13 May 2021 08:55:36 -0600 Subject: [PATCH 089/231] More red code (#732) Remove: - Code/CryEngine/CryCommon/Platform - Some unused Code/CryEngine/CryCommon/Mock files - Code/Tools/CryXML and almost all of Code/Tools/CryCommonTools - Code/Tools/TestBed/ResourceCompilerImage - Tools/DeepBandwidthToExcel - Various .p4ignore files --- Code/.p4ignore | 6 - Code/CryEngine/CryCommon/CMakeLists.txt | 8 - .../CryCommon/Mocks/IMemoryManagerMock.h | 43 - Code/CryEngine/CryCommon/Mocks/INetworkMock.h | 47 - .../CryCommon/Mocks/MockCGFContent.h | 29 - .../Platform/Android/crycommon_android.cmake | 11 - .../Android/crycommon_android_files.cmake | 14 - ...ycommon_enginesettings_android_files.cmake | 13 - .../Platform/AppleTV/crycommon_appletv.cmake | 11 - ...crycommon_enginesettings_linux_files.cmake | 13 - .../Platform/Linux/crycommon_linux.cmake | 11 - .../Linux/crycommon_linux_files.cmake | 14 - .../Platform/Mac/crycommon_mac.cmake | 11 - .../Platform/Mac/crycommon_mac_files.cmake | 14 - .../Platform/Windows/crycommon_windows.cmake | 11 - .../Windows/crycommon_windows_files.cmake | 13 - .../crycommon_enginesettings_ios_files.cmake | 13 - .../Platform/iOS/crycommon_ios.cmake | 11 - .../Platform/iOS/crycommon_ios_files.cmake | 14 - .../CryCommon/Terrain/Bus/HeightmapDataBus.h | 102 - .../CryCommon/Terrain/Bus/TerrainBus.h | 56 - .../Terrain/Bus/TerrainProviderBus.h | 82 - .../Terrain/Bus/TerrainRendererBus.h | 37 - .../Terrain/Bus/WorldMaterialRequestsBus.h | 122 - Code/CryEngine/CryCommon/WinBase.cpp | 3 + .../CryEngine/CryCommon/crycommon_files.cmake | 7 +- .../CryCommon/crycommon_linux_files.cmake | 13 - .../CryCommon/crycommon_testing_files.cmake | 2 - .../CryEngine/CryCommon/stl/STLAlignedAlloc.h | 115 - .../CrySystem/Tests/Test_CryPrimitives.cpp | 16 - Code/Framework/AtomCore/.p4ignore | 1 - Code/Framework/AzCore/.p4ignore | 1 - Code/Sandbox/.p4ignore | 5 - Code/Tools/CMakeLists.txt | 1 - Code/Tools/CryCommonTools/CMakeLists.txt | 26 - Code/Tools/CryCommonTools/ColladaShared.h | 18 - Code/Tools/CryCommonTools/Decompose.cpp | 514 ---- Code/Tools/CryCommonTools/Decompose.h | 30 - Code/Tools/CryCommonTools/Exceptions.h | 43 - Code/Tools/CryCommonTools/FileUtil.cpp | 175 -- Code/Tools/CryCommonTools/FileUtil.h | 311 --- .../CryCommonTools/FileXmlBufferSource.h | 48 - Code/Tools/CryCommonTools/ILogger.h | 53 - Code/Tools/CryCommonTools/IPakSystem.h | 49 - Code/Tools/CryCommonTools/ISettings.h | 57 - Code/Tools/CryCommonTools/LocaleChanger.cpp | 27 - Code/Tools/CryCommonTools/LocaleChanger.h | 30 - Code/Tools/CryCommonTools/LogFile.cpp | 79 - Code/Tools/CryCommonTools/LogFile.h | 40 - Code/Tools/CryCommonTools/MathHelpers.h | 72 - Code/Tools/CryCommonTools/ModuleHelpers.cpp | 44 - Code/Tools/CryCommonTools/ModuleHelpers.h | 31 - Code/Tools/CryCommonTools/PakSystem.cpp | 380 --- Code/Tools/CryCommonTools/PakSystem.h | 69 - .../CryCommonTools/PakXmlFileBufferSource.h | 74 - Code/Tools/CryCommonTools/PathHelpers.cpp | 621 ----- Code/Tools/CryCommonTools/PathHelpers.h | 110 - .../UnixLike/ZipDir/ZipDir_Traits_UnixLike.h | 15 - .../Linux/ZipDir/ZipDir_Traits_Linux.h | 16 - .../Linux/ZipDir/ZipDir_Traits_Platform.h | 15 - .../Platform/Linux/platform_linux_files.cmake | 16 - .../Platform/Mac/ZipDir/ZipDir_Traits_Mac.h | 16 - .../Mac/ZipDir/ZipDir_Traits_Platform.h | 14 - .../Platform/Mac/platform_mac_files.cmake | 16 - .../Windows/ZipDir/ZipDir_Traits_Platform.h | 14 - .../Windows/ZipDir/ZipDir_Traits_Windows.h | 16 - .../Windows/platform_windows_files.cmake | 15 - Code/Tools/CryCommonTools/ProgressRange.h | 89 - Code/Tools/CryCommonTools/PropertyHelpers.cpp | 125 - Code/Tools/CryCommonTools/PropertyHelpers.h | 28 - Code/Tools/CryCommonTools/STLHelpers.cpp | 14 - Code/Tools/CryCommonTools/STLHelpers.h | 54 - Code/Tools/CryCommonTools/SimpleBitmap.h | 508 ---- Code/Tools/CryCommonTools/SimpleStringPool.h | 249 -- .../CryCommonTools/StealingThreadPool.cpp | 580 ----- .../Tools/CryCommonTools/StealingThreadPool.h | 123 - Code/Tools/CryCommonTools/SuffixUtil.h | 59 - .../CryCommonTools/SummedAreaFilterKernel.cpp | 442 ---- .../CryCommonTools/SummedAreaFilterKernel.h | 112 - .../CryCommonTools/TempFilePakExtraction.cpp | 129 - .../CryCommonTools/TempFilePakExtraction.h | 50 - Code/Tools/CryCommonTools/ThreadUtils.cpp | 171 -- Code/Tools/CryCommonTools/ThreadUtils.h | 288 --- Code/Tools/CryCommonTools/UI/log_icons.bmp | 3 - .../UnitTests/PathHelpersUnitTests.cpp | 807 ------- .../UnitTests/StringHelpersUnitTests.cpp | 1056 --------- Code/Tools/CryCommonTools/WeightFilterSet.cpp | 36 - Code/Tools/CryCommonTools/WeightFilterSet.h | 96 - Code/Tools/CryCommonTools/XMLPakFileSink.cpp | 55 - Code/Tools/CryCommonTools/XMLPakFileSink.h | 39 - Code/Tools/CryCommonTools/XMLWriter.cpp | 261 -- Code/Tools/CryCommonTools/XMLWriter.h | 185 -- Code/Tools/CryCommonTools/ZipDir/ZipDir.h | 30 - .../CryCommonTools/ZipDir/ZipDirCache.cpp | 298 --- .../Tools/CryCommonTools/ZipDir/ZipDirCache.h | 140 -- .../ZipDir/ZipDirCacheFactory.cpp | 804 ------- .../ZipDir/ZipDirCacheFactory.h | 143 -- .../CryCommonTools/ZipDir/ZipDirCacheRW.cpp | 2100 ----------------- .../CryCommonTools/ZipDir/ZipDirCacheRW.h | 283 --- .../CryCommonTools/ZipDir/ZipDirFind.cpp | 246 -- Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h | 109 - .../CryCommonTools/ZipDir/ZipDirFindRW.cpp | 253 -- .../CryCommonTools/ZipDir/ZipDirFindRW.h | 110 - .../CryCommonTools/ZipDir/ZipDirList.cpp | 174 -- Code/Tools/CryCommonTools/ZipDir/ZipDirList.h | 138 -- .../ZipDir/ZipDirStructures.cpp | 670 ------ .../CryCommonTools/ZipDir/ZipDirTree.cpp | 356 --- Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h | 103 - Code/Tools/CryCommonTools/ZipDir/ZipFile.h | 19 - .../CryCommonTools/ZipDir/ZipFileFormat.h | 388 --- .../ZipDir/ZipFileFormat_info.h | 112 - .../CryCommonTools/ZipDir/zipdirstructures.h | 426 ---- .../CryCommonTools/crycommontools_files.cmake | 39 - .../crycommontools_tests_files.cmake | 15 - Code/Tools/CryCommonTools/zlibstatd64.lib | 3 - Code/Tools/CryXML/CMakeLists.txt | 32 - Code/Tools/CryXML/CryXML.cpp | 105 - Code/Tools/CryXML/CryXML.def | 3 - Code/Tools/CryXML/CryXML_precompiled.cpp | 14 - Code/Tools/CryXML/CryXML_precompiled.h | 32 - Code/Tools/CryXML/ICryXML.h | 34 - Code/Tools/CryXML/IXMLSerializer.h | 68 - Code/Tools/CryXML/XML/xml.cpp | 1400 ----------- Code/Tools/CryXML/XML/xml.h | 471 ---- Code/Tools/CryXML/XMLSerializer.cpp | 40 - Code/Tools/CryXML/XMLSerializer.h | 31 - Code/Tools/CryXML/cryxml_files.cmake | 22 - .../Input/Bump2NormalHighQ.tif.exportsettings | 1 - ...usehighQWithAlpha256512.tif.exportsettings | 1 - ...usehighQWithAlpha512256.tif.exportsettings | 1 - .../Input/LuminanceOnly.tif.exportsettings | 1 - .../Input/NoPreset3DC_ddn.tif.exportsettings | 1 - .../Input/NoPresetX8R8G8B8.tif.exportsettings | 1 - ...PresetX8R8G8B8WithAlpha.tif.exportsettings | 1 - .../NoPresetX8R8G8B8_bump.tif.exportsettings | 1 - .../NoPresetX8R8G8B8_ddn.tif.exportsettings | 1 - .../Input/NoTIFSettings.tif.exportsettings | 1 - .../NoTIFSettings300400.tif.exportsettings | 1 - ...oTIFSettingsGrey_DDNDIF.tif.exportsettings | 1 - .../NoTIFSettings_DDNDIF.tif.exportsettings | 1 - .../Input/NormalmapLowQ.tif.exportsettings | 1 - ...ormalmapLowQReduce1_ddn.tif.exportsettings | 1 - .../NormalmapLowQ_ddn.tif.exportsettings | 1 - .../TestColorChart_cch.tif.exportsettings | 1 - .../diamand_plate_ddn.tif.exportsettings | 1 - Gems/Blast/Assets/.p4ignore | 1 - Tools/AnimationTest/assetImportTest.bat | 31 - Tools/DeepBandwidthToExcel/7z.exe | 3 - .../DeepBandwidthToExcel.exe | 3 - .../Template/[Content_Types].xml | 2 - .../DeepBandwidthToExcel/Template/_rels/.rels | 2 - .../Template/docProps/app.xml | 2 - .../Template/docProps/core.xml | 2 - .../Template/xl/_rels/workbook.xml.rels | 2 - .../Template/xl/calcChain.xml | 2 - .../Template/xl/charts/chart1.xml | 2 - .../Template/xl/charts/chart2.xml | 2 - .../Template/xl/charts/chart3.xml | 2 - .../Template/xl/charts/chart4.xml | 2 - .../Template/xl/charts/chart5.xml | 93 - .../Template/xl/charts/chart6.xml | 78 - .../Template/xl/charts/chart7.xml | 84 - .../Template/xl/charts/chart8.xml | 83 - .../xl/drawings/_rels/drawing1.xml.rels | 2 - .../xl/drawings/_rels/drawing2.xml.rels | 2 - .../xl/drawings/_rels/drawing3.xml.rels | 2 - .../xl/drawings/_rels/drawing4.xml.rels | 2 - .../xl/drawings/_rels/drawing5.xml.rels | 2 - .../xl/drawings/_rels/drawing6.xml.rels | 2 - .../xl/drawings/_rels/drawing7.xml.rels | 2 - .../xl/drawings/_rels/drawing8.xml.rels | 2 - .../Template/xl/drawings/drawing1.xml | 2 - .../Template/xl/drawings/drawing2.xml | 2 - .../Template/xl/drawings/drawing3.xml | 2 - .../Template/xl/drawings/drawing4.xml | 2 - .../Template/xl/drawings/drawing5.xml | 2 - .../Template/xl/drawings/drawing6.xml | 2 - .../Template/xl/drawings/drawing7.xml | 2 - .../Template/xl/drawings/drawing8.xml | 2 - .../Template/xl/sharedStrings.xml | 2 - .../Template/xl/styles.xml | 2 - .../Template/xl/theme/theme1.xml | 2 - .../Template/xl/workbook.xml | 2 - .../xl/worksheets/_rels/sheet1.xml.rels | 2 - .../xl/worksheets/_rels/sheet2.xml.rels | 2 - .../xl/worksheets/_rels/sheet3.xml.rels | 2 - .../xl/worksheets/_rels/sheet4.xml.rels | 2 - .../xl/worksheets/_rels/sheet5.xml.rels | 2 - .../xl/worksheets/_rels/sheet6.xml.rels | 2 - .../xl/worksheets/_rels/sheet7.xml.rels | 2 - .../xl/worksheets/_rels/sheet8.xml.rels | 2 - .../Template/xl/worksheets/sheet1.xml | 2 - .../Template/xl/worksheets/sheet2.xml | 2 - .../Template/xl/worksheets/sheet3.xml | 2 - .../Template/xl/worksheets/sheet4.xml | 19 - .../Template/xl/worksheets/sheet5.xml | 17 - .../Template/xl/worksheets/sheet6.xml | 18 - .../Template/xl/worksheets/sheet7.xml | 18 - .../Template/xl/worksheets/sheet8.xml | 18 - .../Template/xl/worksheets/sheet9.xml | 16 - .../Windows/package_filelists/atom.json | 11 - 201 files changed, 4 insertions(+), 19283 deletions(-) delete mode 100644 Code/.p4ignore delete mode 100644 Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h delete mode 100644 Code/CryEngine/CryCommon/Mocks/INetworkMock.h delete mode 100644 Code/CryEngine/CryCommon/Mocks/MockCGFContent.h delete mode 100644 Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h delete mode 100644 Code/CryEngine/CryCommon/crycommon_linux_files.cmake delete mode 100644 Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h delete mode 100644 Code/Framework/AtomCore/.p4ignore delete mode 100644 Code/Framework/AzCore/.p4ignore delete mode 100644 Code/Sandbox/.p4ignore delete mode 100644 Code/Tools/CryCommonTools/ColladaShared.h delete mode 100644 Code/Tools/CryCommonTools/Decompose.cpp delete mode 100644 Code/Tools/CryCommonTools/Decompose.h delete mode 100644 Code/Tools/CryCommonTools/Exceptions.h delete mode 100644 Code/Tools/CryCommonTools/FileUtil.cpp delete mode 100644 Code/Tools/CryCommonTools/FileUtil.h delete mode 100644 Code/Tools/CryCommonTools/FileXmlBufferSource.h delete mode 100644 Code/Tools/CryCommonTools/ILogger.h delete mode 100644 Code/Tools/CryCommonTools/IPakSystem.h delete mode 100644 Code/Tools/CryCommonTools/ISettings.h delete mode 100644 Code/Tools/CryCommonTools/LocaleChanger.cpp delete mode 100644 Code/Tools/CryCommonTools/LocaleChanger.h delete mode 100644 Code/Tools/CryCommonTools/LogFile.cpp delete mode 100644 Code/Tools/CryCommonTools/LogFile.h delete mode 100644 Code/Tools/CryCommonTools/MathHelpers.h delete mode 100644 Code/Tools/CryCommonTools/ModuleHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/ModuleHelpers.h delete mode 100644 Code/Tools/CryCommonTools/PakSystem.cpp delete mode 100644 Code/Tools/CryCommonTools/PakSystem.h delete mode 100644 Code/Tools/CryCommonTools/PakXmlFileBufferSource.h delete mode 100644 Code/Tools/CryCommonTools/PathHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/PathHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake delete mode 100644 Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake delete mode 100644 Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake delete mode 100644 Code/Tools/CryCommonTools/ProgressRange.h delete mode 100644 Code/Tools/CryCommonTools/PropertyHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/PropertyHelpers.h delete mode 100644 Code/Tools/CryCommonTools/STLHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/STLHelpers.h delete mode 100644 Code/Tools/CryCommonTools/SimpleBitmap.h delete mode 100644 Code/Tools/CryCommonTools/SimpleStringPool.h delete mode 100644 Code/Tools/CryCommonTools/StealingThreadPool.cpp delete mode 100644 Code/Tools/CryCommonTools/StealingThreadPool.h delete mode 100644 Code/Tools/CryCommonTools/SuffixUtil.h delete mode 100644 Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp delete mode 100644 Code/Tools/CryCommonTools/SummedAreaFilterKernel.h delete mode 100644 Code/Tools/CryCommonTools/TempFilePakExtraction.cpp delete mode 100644 Code/Tools/CryCommonTools/TempFilePakExtraction.h delete mode 100644 Code/Tools/CryCommonTools/ThreadUtils.cpp delete mode 100644 Code/Tools/CryCommonTools/ThreadUtils.h delete mode 100644 Code/Tools/CryCommonTools/UI/log_icons.bmp delete mode 100644 Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp delete mode 100644 Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp delete mode 100644 Code/Tools/CryCommonTools/WeightFilterSet.cpp delete mode 100644 Code/Tools/CryCommonTools/WeightFilterSet.h delete mode 100644 Code/Tools/CryCommonTools/XMLPakFileSink.cpp delete mode 100644 Code/Tools/CryCommonTools/XMLPakFileSink.h delete mode 100644 Code/Tools/CryCommonTools/XMLWriter.cpp delete mode 100644 Code/Tools/CryCommonTools/XMLWriter.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDir.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirList.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipFile.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h delete mode 100644 Code/Tools/CryCommonTools/crycommontools_tests_files.cmake delete mode 100644 Code/Tools/CryCommonTools/zlibstatd64.lib delete mode 100644 Code/Tools/CryXML/CMakeLists.txt delete mode 100644 Code/Tools/CryXML/CryXML.cpp delete mode 100644 Code/Tools/CryXML/CryXML.def delete mode 100644 Code/Tools/CryXML/CryXML_precompiled.cpp delete mode 100644 Code/Tools/CryXML/CryXML_precompiled.h delete mode 100644 Code/Tools/CryXML/ICryXML.h delete mode 100644 Code/Tools/CryXML/IXMLSerializer.h delete mode 100644 Code/Tools/CryXML/XML/xml.cpp delete mode 100644 Code/Tools/CryXML/XML/xml.h delete mode 100644 Code/Tools/CryXML/XMLSerializer.cpp delete mode 100644 Code/Tools/CryXML/XMLSerializer.h delete mode 100644 Code/Tools/CryXML/cryxml_files.cmake delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings delete mode 100644 Gems/Blast/Assets/.p4ignore delete mode 100644 Tools/AnimationTest/assetImportTest.bat delete mode 100644 Tools/DeepBandwidthToExcel/7z.exe delete mode 100644 Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe delete mode 100644 Tools/DeepBandwidthToExcel/Template/[Content_Types].xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/_rels/.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/docProps/app.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/docProps/core.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/styles.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/workbook.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml diff --git a/Code/.p4ignore b/Code/.p4ignore deleted file mode 100644 index f0b9f1ea6b..0000000000 --- a/Code/.p4ignore +++ /dev/null @@ -1,6 +0,0 @@ -#Ignore these directories -SDKs - -#ColinB (8/26)- I know there are depot files that this will ignore... But these files should not be -#here, they should all be in 3rdParty... so we will ignore them until I can move them, it should -#be OK for now because they shouldn't change at all anyway. diff --git a/Code/CryEngine/CryCommon/CMakeLists.txt b/Code/CryEngine/CryCommon/CMakeLists.txt index 5105ff1a5b..3a1eb90d9d 100644 --- a/Code/CryEngine/CryCommon/CMakeLists.txt +++ b/Code/CryEngine/CryCommon/CMakeLists.txt @@ -9,23 +9,15 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) -ly_get_pal_tool_dirs(pal_tool_dirs ${CMAKE_CURRENT_LIST_DIR}/Platform) - ly_add_target( NAME CryCommon STATIC NAMESPACE Legacy FILES_CMAKE crycommon_files.cmake - ${pal_dir}/crycommon_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - PLATFORM_INCLUDE_FILES - ${pal_dir}/crycommon_${PAL_PLATFORM_NAME_LOWERCASE}.cmake INCLUDE_DIRECTORIES PUBLIC . # Lots of code without CryCommon/ .. # Dangerous since exports CryEngine's path (client code can do CrySystem/ without depending on that target) - ${pal_dir} - ${pal_tool_dirs} BUILD_DEPENDENCIES PUBLIC AZ::AzCore diff --git a/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h b/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h deleted file mode 100644 index 63df006e14..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once -#include - -class MemoryManagerMock - : public IMemoryManager -{ -public: - MOCK_METHOD1(GetProcessMemInfo, - bool(SProcessMemInfo& minfo)); - MOCK_METHOD3(TraceDefineHeap, - HeapHandle(const char* heapName, size_t size, const void* pBase)); - MOCK_METHOD6(TraceHeapAlloc, - void(HeapHandle heap, void* mem, size_t size, size_t blockSize, const char* sUsage, const char* sNameHint)); - MOCK_METHOD3(TraceHeapFree, - void(HeapHandle heap, void* mem, size_t blockSize)); - MOCK_METHOD1(TraceHeapSetColor, - void(uint32 color)); - MOCK_METHOD0(TraceHeapGetColor, - uint32()); - MOCK_METHOD1(TraceHeapSetLabel, - void(const char* sLabel)); - MOCK_METHOD1(CreateCustomMemoryHeapInstance, - ICustomMemoryHeap* const (EAllocPolicy const eAllocPolicy)); - MOCK_METHOD3(CreateGeneralExpandingMemoryHeap, - IGeneralMemoryHeap* (size_t upperLimit, size_t reserveSize, const char* sUsage)); - MOCK_METHOD3(CreateGeneralMemoryHeap, - IGeneralMemoryHeap* (void* base, size_t sz, const char* sUsage)); - MOCK_METHOD2(ReserveAddressRange, - IMemoryAddressRange* (size_t capacity, const char* sName)); - MOCK_METHOD2(CreatePageMappingHeap, - IPageMappingHeap* (size_t addressSpace, const char* sName)); -}; diff --git a/Code/CryEngine/CryCommon/Mocks/INetworkMock.h b/Code/CryEngine/CryCommon/Mocks/INetworkMock.h deleted file mode 100644 index b627f927bc..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/INetworkMock.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -struct NetworkMock : public INetwork -{ - NetworkMock() : m_gridMate(nullptr) - { - } - GridMate::IGridMate* m_gridMate; - - void Release() override {} - void GetMemoryStatistics([[maybe_unused]] ICrySizer* pSizer) override {} - void GetBandwidthStatistics([[maybe_unused]] SBandwidthStats* const pStats) override {} - void GetPerformanceStatistics([[maybe_unused]] SNetworkPerformance* pSizer) override {} - void GetProfilingStatistics([[maybe_unused]] SNetworkProfilingStats* const pStats) override {} - void SyncWithGame([[maybe_unused]] ENetworkGameSync syncType) override {} - const char* GetHostName() override { return "testhostname"; } - GridMate::IGridMate* GetGridMate() override - { - return m_gridMate; - } - ChannelId GetChannelIdForSessionMember([[maybe_unused]] GridMate::GridMember* member) const override { return ChannelId(); } - ChannelId GetServerChannelId() const override { return ChannelId(); } - ChannelId GetLocalChannelId() const override { return ChannelId(); } - CTimeValue GetSessionTime() override { return CTimeValue(); } - void ChangedAspects([[maybe_unused]] EntityId id, [[maybe_unused]] NetworkAspectType aspectBits) override {} - void SetDelegatableAspectMask([[maybe_unused]] NetworkAspectType aspectBits) override {} - void SetObjectDelegatedAspectMask([[maybe_unused]] EntityId entityId, [[maybe_unused]] NetworkAspectType aspects, [[maybe_unused]] bool set) override {} - void DelegateAuthorityToClient([[maybe_unused]] EntityId entityId, [[maybe_unused]] ChannelId clientChannelId) override {} - void InvokeActorRMI([[maybe_unused]] EntityId entityId, [[maybe_unused]] uint8 actorExtensionId, [[maybe_unused]] ChannelId targetChannelFilter, [[maybe_unused]] IActorRMIRep& rep) override {} - void InvokeScriptRMI([[maybe_unused]] ISerializable* serializable, [[maybe_unused]] bool isServerRMI, [[maybe_unused]] ChannelId toChannelId = kInvalidChannelId, [[maybe_unused]] ChannelId avoidChannelId = kInvalidChannelId) override {} - void RegisterActorRMI([[maybe_unused]] IActorRMIRep* rep) override {} - void UnregisterActorRMI([[maybe_unused]] IActorRMIRep* rep) override {} - EntityId LocalEntityIdToServerEntityId([[maybe_unused]] EntityId localId) const override { return EntityId(); } - EntityId ServerEntityIdToLocalEntityId([[maybe_unused]] EntityId serverId, [[maybe_unused]] bool allowForcedEstablishment = false) const override { return EntityId(); } -}; diff --git a/Code/CryEngine/CryCommon/Mocks/MockCGFContent.h b/Code/CryEngine/CryCommon/Mocks/MockCGFContent.h deleted file mode 100644 index 8047a863f6..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/MockCGFContent.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include - -#include - -class MockIAssetWriter - : public IAssetWriter -{ -public: - ~MockIAssetWriter() override = default; - MOCK_METHOD1(WriteCGF, - bool(CContentCGF* content)); - MOCK_METHOD2(WriteCHR, - bool(CContentCGF* content, IConvertContext* convertContext)); - MOCK_METHOD3(WriteSKIN, - bool(CContentCGF* content, IConvertContext* convertContext, bool exportMorphTargets)); -}; diff --git a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake b/Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or 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/Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake b/Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.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(FILES - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake b/Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.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(FILES -) diff --git a/Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake b/Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or 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/Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake b/Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.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(FILES -) diff --git a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake b/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or 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/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake b/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.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(FILES - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake b/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or 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/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake b/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.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(FILES - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake b/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or 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/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake b/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.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(FILES -) diff --git a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake b/Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.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(FILES -) diff --git a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake b/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or 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/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake b/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.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(FILES - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h deleted file mode 100644 index 93065e1196..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h +++ /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. -* -*/ - -#pragma once - -#include -#include - -namespace Terrain -{ - class Viewport2D - { - public: - int m_topLeftX = 0; - int m_topLeftY = 0; - int m_width = 0; - int m_height = 0; - - Viewport2D() = default; - Viewport2D(const Viewport2D&) = default; - Viewport2D& operator=(const Viewport2D&) = default; - - Viewport2D(int topLeftX, int topLeftY, int width, int height) - : m_topLeftX(topLeftX) - , m_topLeftY(topLeftY) - , m_width(width) - , m_height(height) - { - } - }; - - // External height map data requests - class HeightmapDataRequestInfo - { - public: - HeightmapDataRequestInfo() = default; - HeightmapDataRequestInfo(const HeightmapDataRequestInfo& rhs) = default; - HeightmapDataRequestInfo& operator=(const HeightmapDataRequestInfo& rhs) = default; - - HeightmapDataRequestInfo(int viewportTopLeftX, int viewportTopLeftY, int viewportWidth, int viewportHeight, float metersPerPixel, AZ::Vector2 worldMin, AZ::Vector2 worldMax) - : m_viewport(viewportTopLeftX, viewportTopLeftY, viewportWidth, viewportHeight) - , m_metersPerPixel(metersPerPixel) - , m_worldMin(worldMin) - , m_worldMax(worldMax) - { - } - - float GetMetersPerPixel() const - { - return m_metersPerPixel; - } - - AZ::Vector2 GetWorldMin() const - { - return m_worldMin; - } - - AZ::Vector2 GetWorldMax() const - { - return m_worldMax; - } - - AZ::Vector2 GetWorldWidth() const - { - return (m_worldMax - m_worldMin); - } - - Viewport2D GetViewport() const - { - return m_viewport; - } - - private: - Viewport2D m_viewport; - AZ::Vector2 m_worldMin = AZ::Vector2(0.0f, 0.0f); - AZ::Vector2 m_worldMax = AZ::Vector2(0.0f, 0.0f); - float m_metersPerPixel = 1.0f; - }; - - class HeightmapDataNotifications - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - virtual void OnTerrainHeightDataChanged(const AZ::Aabb& dirtyRegion) = 0; - }; - using HeightmapDataNotificationBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h deleted file mode 100644 index 2cfb5134c9..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.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 - -#include -#include - -class CShader; - -namespace Terrain -{ - class TerrainDataRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - virtual float GetHeightSynchronous(float x, float y) = 0; - virtual AZ::Vector3 GetNormalSynchronous(float x, float y) = 0; - - virtual CShader* GetTerrainHeightGeneratorShader() const = 0; - virtual CShader* GetTerrainMaterialCompositingShader() const = 0; - }; - using TerrainDataRequestBus = AZ::EBus; - - class TerrainShaderRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - virtual void RefreshShader(const AZStd::string_view name, CShader* shader) = 0; - virtual void ReleaseShader(CShader* shader) const = 0; - }; - using TerrainShaderRequestBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h deleted file mode 100644 index 6c1aca6ea7..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h +++ /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. -* -*/ - -#pragma once - -#include -#include -#include - -#include - -#include "HeightmapDataBus.h" - -class CShader; - -namespace Terrain -{ - // This interface defines how the renderer can access the terrain system to set up state and gather information before rendering height maps - class TerrainProviderRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - // world properties - virtual AZ::Vector3 GetWorldSize() = 0; - virtual AZ::Vector3 GetRegionSize() = 0; - virtual AZ::Vector3 GetWorldOrigin() = 0; - virtual AZ::Vector2 GetHeightRange() = 0; - - // utility - virtual void GetRegionIndex(const AZ::Vector2& worldMin, const AZ::Vector2& worldMax, int& regionIndexX, int& regionIndexY) = 0; - - virtual float GetHeightAtIndexedPosition([[maybe_unused]] int ix, [[maybe_unused]] int iy) { return 64.0f; } - virtual float GetHeightAtWorldPosition([[maybe_unused]] float fx, [[maybe_unused]] float fy) { return 64.0f; } - virtual unsigned char GetSurfaceTypeAtIndexedPosition([[maybe_unused]] int ix, [[maybe_unused]] int iy) { return 0; } - }; - using TerrainProviderRequestBus = AZ::EBus; - - // This class exists for the terrain system to inject data into the renderer for generating the GPU-side terrain height map - struct CRETerrainContext - { - // Tract map - virtual void OnTractVersionUpdate() = 0; - - CShader* m_currentShader = nullptr; - }; - - class TerrainProviderNotifications - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - // interface to be implemented by the game, invoked by the terrain render element - - // pull settings from the world cache, so the next accessors are accurate - virtual void SynchronizeSettings(CRETerrainContext* context) = 0; - }; - using TerrainProviderNotificationBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h deleted file mode 100644 index ea644f5653..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include - -namespace Terrain -{ - class TerrainRendererRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - - // Query state of the terrain renderer - // Returns true once the terrain renderer has fulfilled most data requests and is ready for rendering - virtual bool IsReady() = 0; - }; - using TerrainRendererRequestBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h deleted file mode 100644 index 3fb80f5f11..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h +++ /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. -* -*/ - -#pragma once - -#include -#include -#include - -struct IMaterial; -class ITexture; - -namespace Terrain -{ - struct MacroMaterial - { - // Textures - _smart_ptr m_macroColorMap = nullptr; - _smart_ptr m_macroGlossMap = nullptr; - _smart_ptr m_macroNormalMap = nullptr; - - // Material Params - AZ::Color m_macroColorMapColor; - float m_macroGlossMapScale = 1.0f; - float m_macroNormalMapScale = 1.0f; - float m_macroSpecReflectance = 0.03f; - - void Clear() - { - m_macroColorMap = nullptr; - m_macroGlossMap = nullptr; - m_macroNormalMap = nullptr; - - m_macroColorMapColor = AZ::Color(1.0f); - m_macroGlossMapScale = 1.0f; - m_macroNormalMapScale = 1.0f; - m_macroSpecReflectance = 0.03f; - } - }; - - struct TerrainMaterialLayer - { - _smart_ptr m_material = nullptr; - _smart_ptr m_splatTexture = nullptr; - - TerrainMaterialLayer(_smart_ptr material, _smart_ptr splatTexture) - : m_material(material) - , m_splatTexture(splatTexture) - { - } - }; - - struct RegionMaterials - { - MacroMaterial m_macroMaterial; - - AZStd::vector m_materialLayers; - _smart_ptr m_defaultMaterial = nullptr; - - RegionMaterials& operator=(const RegionMaterials& rhs) = default; - - void Clear() - { - m_materialLayers.clear(); - m_defaultMaterial = nullptr; - m_macroMaterial.Clear(); - } - }; - - const AZ::u32 kMaxRegionsPerTerrainMaterialRequest = 16; - typedef AZStd::pair RegionIndex; - typedef AZStd::fixed_vector RegionIndexVector; - typedef AZStd::fixed_vector RegionMaterialVector; - - enum class RequestResult - { - NoAssetsForRegion, - Loading, - Success - }; - - class WorldMaterialRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - - virtual void LoadWorld(const AZStd::string& worldName, int regionSize) = 0; - - virtual RequestResult RequestRegionMaterials(const RegionIndexVector& regions, RegionMaterialVector& outRegionMaterials) = 0; - - // Parameters: - // int tileX, tileY : Region tile indices - // Returns: - // bool : If true, region material data is loaded and exists. outMacroMaterial will be modified with the respective macro material data - // If false, no region material data has been loaded or exists for the given tile (may still have invalid material layers). - virtual RequestResult GetMacroMaterial(int tileX, int tileY, MacroMaterial& outMacroMaterial) = 0; - - virtual void GetTerrainPOMParameters(float& pomHeightBias, float& pomDisplacement, float& selfShadowStrength) = 0; - - //Get the surface type at a given position. If not loaded yet, returns "loadingMaterial". - virtual AZStd::string_view GetSurfaceTypeAtPosition(AZ::Vector2 position) = 0; - }; - using WorldMaterialRequestBus = AZ::EBus; -} // namespace Terrain - diff --git a/Code/CryEngine/CryCommon/WinBase.cpp b/Code/CryEngine/CryCommon/WinBase.cpp index e6ea1cd4a8..47cb943240 100644 --- a/Code/CryEngine/CryCommon/WinBase.cpp +++ b/Code/CryEngine/CryCommon/WinBase.cpp @@ -12,6 +12,7 @@ // Original file Copyright Crytek GMBH or its affiliates, used under license. // Description : Linux/Mac port support for Win32API calls +#if !defined(WIN32) #include "platform.h" // Note: This should be first to get consistent debugging definitions @@ -1667,3 +1668,5 @@ __finddata64_t::~__finddata64_t() } } #endif //defined(APPLE) || defined(LINUX) + +#endif // !defined(WIN32) diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index 77b51825f1..dff4ca66e7 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -249,7 +249,6 @@ set(FILES platform_impl.cpp Win32specific.h Win64specific.h - stl/STLAlignedAlloc.h LyShine/IDraw2d.h LyShine/ILyShine.h LyShine/ISprite.h @@ -341,11 +340,7 @@ set(FILES Maestro/Types/AssetBlendKey.h Maestro/Types/AssetBlends.h Maestro/Types/SequenceType.h - Terrain/Bus/WorldMaterialRequestsBus.h - Terrain/Bus/TerrainBus.h - Terrain/Bus/TerrainRendererBus.h - Terrain/Bus/HeightmapDataBus.h - Terrain/Bus/TerrainProviderBus.h StaticInstance.h Pak/CryPakUtils.h + WinBase.cpp ) diff --git a/Code/CryEngine/CryCommon/crycommon_linux_files.cmake b/Code/CryEngine/CryCommon/crycommon_linux_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/crycommon_linux_files.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(FILES -) diff --git a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake index d20a33f791..b94be27c3b 100644 --- a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake @@ -14,12 +14,10 @@ set(FILES Mocks/IConsoleMock.h Mocks/ICryPakMock.h Mocks/ILogMock.h - Mocks/IMemoryManagerMock.h Mocks/ISystemMock.h Mocks/ITimerMock.h Mocks/ICVarMock.h Mocks/IRendererMock.h Mocks/ITextureMock.h Mocks/IRemoteConsoleMock.h - Mocks/MockCGFContent.h ) diff --git a/Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h b/Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h deleted file mode 100644 index dc21cead81..0000000000 --- a/Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Implements an aligned allocator for STL -// based on the Mallocator (http://blogs.msdn.com/b/vcblog/archive/2008/08/28/the-mallocator.aspx) - -#pragma once - -#include // Required for size_t and ptrdiff_t and NULL - -#include - -namespace stl -{ - template - class AlignedAllocator - : public AZ::SimpleSchemaAllocator> - { - public: - AZ_TYPE_INFO(AlignedAllocator, "{DF152D8A-36ED-4A2A-9FA6-734F212716C6}"); - using Base = AZ::SimpleSchemaAllocator>; - using Descriptor = Base::Descriptor; - using Schema = AZ::ChildAllocatorSchema; - - AlignedAllocator() - : Base("AlignedAllocator", "Legacy Cry Aligned Allocator") - { - } - - pointer_type Allocate(size_type byteSize, size_type /*alignment*/, int flags /* = 0 */, const char* name /* = 0 */, const char* fileName /* = 0 */, int lineNum /* = 0 */, unsigned int suppressStackRecord /* = 0 */) override - { - return Base::Allocate(byteSize, Alignment, flags, name, fileName, lineNum, suppressStackRecord); - } - - void DeAllocate(pointer_type ptr, size_type byteSize, [[maybe_unused]] size_type alignment) override - { - return Base::DeAllocate(ptr, byteSize, Alignment); - } - - pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type /*newAlignment*/) override - { - return Base::ReAllocate(ptr, newSize, Alignment); - } - }; - - template - using aligned_alloc = AZ::AZStdAlloc>; - - ////////////////////////////////////////////////////////////////////////// - // Defines aligned vector type - ////////////////////////////////////////////////////////////////////////// - template - class aligned_vector - : public AZStd::vector > - { - public: - typedef aligned_alloc MyAlloc; - typedef AZStd::vector MySuperClass; - typedef aligned_vector MySelf; - typedef size_t size_type; - - aligned_vector() {} - explicit aligned_vector(const MyAlloc& _Al) - : MySuperClass(_Al) {} - explicit aligned_vector(size_type _Count) - : MySuperClass(_Count) {}; - aligned_vector(size_type _Count, const T& _Val) - : MySuperClass(_Count, _Val) {} - aligned_vector(size_type _Count, const T& _Val, const MyAlloc& _Al) - : MySuperClass(_Count, _Val) {} - aligned_vector(const MySelf& _Right) - : MySuperClass(_Right) {}; - - - template - aligned_vector(_Iter _First, _Iter _Last) - : MySuperClass(_First, _Last) {}; - - template - aligned_vector(_Iter _First, _Iter _Last, const MyAlloc& _Al) - : MySuperClass(_First, _Last, _Al) {}; - }; - - template - inline size_t size_of_aligned_vector(const Vec& c) - { - if (!c.empty()) - { - // Not really correct as not taking alignment into the account - return c.capacity() * sizeof(typename Vec::value_type); - } - return 0; - } -} // namespace stl - -// Specialize for the AlignedAllocator to provide one per module that does not use the -// environment for its storage. Since this allocator just uses LegacyAllocator -// to do the real work, it's fine if there is one of these per cry module -namespace AZ -{ - template - class AllocatorInstance> : public Internal::AllocatorInstanceBase, AllocatorStorage::ModuleStoragePolicy>> - { - }; -} diff --git a/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp b/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp index 2e6e646548..26d12ffd8c 100644 --- a/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp +++ b/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp @@ -12,7 +12,6 @@ #include "CrySystem_precompiled.h" #include #include -#include TEST(StringTests, CUT_Strings) { @@ -424,21 +423,6 @@ TEST_F(CryPrimitives, CUT_FixedString) EXPECT_EQ("0123", str5); } -////////////////////////////////////////////////////////////////////////// -// Unit Testing of aligned_vector -////////////////////////////////////////////////////////////////////////// -TEST_F(CryPrimitives, CUT_AlignedVector) -{ - stl::aligned_vector vec; - - vec.push_back(1); - vec.push_back(2); - vec.push_back(3); - - EXPECT_TRUE(vec.size() == 3); - EXPECT_TRUE(((INT_PTR)(&vec[0]) % 16) == 0); -} - TEST_F(CryPrimitives, CUT_DynArray) { LegacyDynArray a; diff --git a/Code/Framework/AtomCore/.p4ignore b/Code/Framework/AtomCore/.p4ignore deleted file mode 100644 index 6722cd96e7..0000000000 --- a/Code/Framework/AtomCore/.p4ignore +++ /dev/null @@ -1 +0,0 @@ -*.xml diff --git a/Code/Framework/AzCore/.p4ignore b/Code/Framework/AzCore/.p4ignore deleted file mode 100644 index 6722cd96e7..0000000000 --- a/Code/Framework/AzCore/.p4ignore +++ /dev/null @@ -1 +0,0 @@ -*.xml diff --git a/Code/Sandbox/.p4ignore b/Code/Sandbox/.p4ignore deleted file mode 100644 index 9c6b6fcd91..0000000000 --- a/Code/Sandbox/.p4ignore +++ /dev/null @@ -1,5 +0,0 @@ -#Ignore these directories -SDKs - -#ignore these files -*.user diff --git a/Code/Tools/CMakeLists.txt b/Code/Tools/CMakeLists.txt index db5476756b..278474819c 100644 --- a/Code/Tools/CMakeLists.txt +++ b/Code/Tools/CMakeLists.txt @@ -15,7 +15,6 @@ add_subdirectory(AWSNativeSDKInit) add_subdirectory(AzTestRunner) add_subdirectory(CrashHandler) add_subdirectory(CryCommonTools) -add_subdirectory(CryXML) add_subdirectory(News) add_subdirectory(PythonBindingsExample) add_subdirectory(RemoteConsole) diff --git a/Code/Tools/CryCommonTools/CMakeLists.txt b/Code/Tools/CryCommonTools/CMakeLists.txt index 0188506e97..63f535b1af 100644 --- a/Code/Tools/CryCommonTools/CMakeLists.txt +++ b/Code/Tools/CryCommonTools/CMakeLists.txt @@ -13,44 +13,18 @@ if (NOT PAL_TRAIT_BUILD_HOST_TOOLS) return() endif() -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) - ly_add_target( NAME CryCommonTools STATIC NAMESPACE Legacy FILES_CMAKE crycommontools_files.cmake - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake INCLUDE_DIRECTORIES PUBLIC . - ${pal_dir} BUILD_DEPENDENCIES PRIVATE - 3rdParty::lz4 - 3rdParty::zlib - 3rdParty::zstd AZ::AzCore PUBLIC Legacy::CryCommon AZ::AzFramework ) - -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) - ly_add_target( - NAME CryCommonTools.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} - NAMESPACE Legacy - FILES_CMAKE - crycommontools_tests_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - UnitTests - BUILD_DEPENDENCIES - PRIVATE - Legacy::CryCommonTools - AZ::AzTest - ) - ly_add_googletest( - NAME Legacy::CryCommonTools.Tests - ) -endif() diff --git a/Code/Tools/CryCommonTools/ColladaShared.h b/Code/Tools/CryCommonTools/ColladaShared.h deleted file mode 100644 index edc8341fe1..0000000000 --- a/Code/Tools/CryCommonTools/ColladaShared.h +++ /dev/null @@ -1,18 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_COLLADASHARED_H -#define CRYINCLUDE_CRYCOMMONTOOLS_COLLADASHARED_H -#pragma once - -static const char* g_LumberyardExportNodeTag = "LumberyardExportNode"; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_COLLADASHARED_H diff --git a/Code/Tools/CryCommonTools/Decompose.cpp b/Code/Tools/CryCommonTools/Decompose.cpp deleted file mode 100644 index 3cf88db251..0000000000 --- a/Code/Tools/CryCommonTools/Decompose.cpp +++ /dev/null @@ -1,514 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include - -// Taken from http://tog.acm.org/GraphicsGems/gemsiv/polar_decomp/Decompose.c - -/**** Decompose.c ****/ -/* Ken Shoemake, 1993 */ -#include -#include "Decompose.h" - -#pragma warning(disable:4244) // conversion from 'double' to 'float', possible loss of data -#pragma warning(disable:4305) // 'initializing' : truncation from 'double' to 'float' - -namespace decomp { - - /******* Matrix Preliminaries *******/ - - /** Fill out 3x3 matrix to 4x4 **/ -#define mat_pad(A) (A[W][X]=A[X][W]=A[W][Y]=A[Y][W]=A[W][Z]=A[Z][W]=0,A[W][W]=1) - -/** Copy nxn matrix A to C using "gets" for assignment **/ -#define mat_copy(C,gets,A,n) {int i,j; for(i=0;i= 0.0) { - s = sqrt(tr + mat[W][W]); - qu.w = s * 0.5; - s = 0.5 / s; - qu.x = (mat[Z][Y] - mat[Y][Z]) * s; - qu.y = (mat[X][Z] - mat[Z][X]) * s; - qu.z = (mat[Y][X] - mat[X][Y]) * s; - } else { - int h = X; - if (mat[Y][Y] > mat[X][X]) h = Y; - if (mat[Z][Z] > mat[h][h]) h = Z; - switch (h) { -#define caseMacro(i,j,k,I,J,K) \ - case I:\ - s = sqrt( (mat[I][I] - (mat[J][J]+mat[K][K])) + mat[W][W] );\ - qu.i = s*0.5;\ - s = 0.5 / s;\ - qu.j = (mat[I][J] + mat[J][I]) * s;\ - qu.k = (mat[K][I] + mat[I][K]) * s;\ - qu.w = (mat[K][J] - mat[J][K]) * s;\ - break - caseMacro(x, y, z, X, Y, Z); - caseMacro(y, z, x, Y, Z, X); - caseMacro(z, x, y, Z, X, Y); - } - } - if (mat[W][W] != 1.0) qu = Qt_Scale(qu, 1 / sqrt(mat[W][W])); - return (qu); - } - /******* Decomp Auxiliaries *******/ - - static HMatrix mat_id = { {1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1} }; - - /** Compute either the 1 or infinity norm of M, depending on tpose **/ - float mat_norm(HMatrix M, int tpose) - { - int i; - float sum, max; - max = 0.0; - for (i = 0; i < 3; i++) { - if (tpose) sum = fabs(M[0][i]) + fabs(M[1][i]) + fabs(M[2][i]); - else sum = fabs(M[i][0]) + fabs(M[i][1]) + fabs(M[i][2]); - if (max < sum) max = sum; - } - return max; - } - - float norm_inf(HMatrix M) { return mat_norm(M, 0); } - float norm_one(HMatrix M) { return mat_norm(M, 1); } - - /** Return index of column of M containing maximum abs entry, or -1 if M=0 **/ - int find_max_col(HMatrix M) - { - float abs, max; - int i, j, col; - max = 0.0; col = -1; - for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { - abs = M[i][j]; if (abs < 0.0) abs = -abs; - if (abs > max) { max = abs; col = j; } - } - return col; - } - - /** Setup u for Household reflection to zero all v components but first **/ - void make_reflector(float* v, float* u) - { - float s = sqrt(vdot(v, v)); - u[0] = v[0]; u[1] = v[1]; - u[2] = v[2] + ((v[2] < 0.0) ? -s : s); - s = sqrt(2.0 / vdot(u, u)); - u[0] = u[0] * s; u[1] = u[1] * s; u[2] = u[2] * s; - } - - /** Apply Householder reflection represented by u to column vectors of M **/ - void reflect_cols(HMatrix M, float* u) - { - int i, j; - for (i = 0; i < 3; i++) { - float s = u[0] * M[0][i] + u[1] * M[1][i] + u[2] * M[2][i]; - for (j = 0; j < 3; j++) M[j][i] -= u[j] * s; - } - } - /** Apply Householder reflection represented by u to row vectors of M **/ - void reflect_rows(HMatrix M, float* u) - { - int i, j; - for (i = 0; i < 3; i++) { - float s = vdot(u, M[i]); - for (j = 0; j < 3; j++) M[i][j] -= u[j] * s; - } - } - - /** Find orthogonal factor Q of rank 1 (or less) M **/ - void do_rank1(HMatrix M, HMatrix Q) - { - float v1[3], v2[3], s; - int col; - mat_copy(Q, =, mat_id, 4); - /* If rank(M) is 1, we should find a non-zero column in M */ - col = find_max_col(M); - if (col < 0) return; /* Rank is 0 */ - v1[0] = M[0][col]; v1[1] = M[1][col]; v1[2] = M[2][col]; - make_reflector(v1, v1); reflect_cols(M, v1); - v2[0] = M[2][0]; v2[1] = M[2][1]; v2[2] = M[2][2]; - make_reflector(v2, v2); reflect_rows(M, v2); - s = M[2][2]; - if (s < 0.0) Q[2][2] = -1.0; - reflect_cols(Q, v1); reflect_rows(Q, v2); - } - - /** Find orthogonal factor Q of rank 2 (or less) M using adjoint transpose **/ - void do_rank2(HMatrix M, HMatrix MadjT, HMatrix Q) - { - float v1[3], v2[3]; - float w, x, y, z, c, s, d; - int col; - /* If rank(M) is 2, we should find a non-zero column in MadjT */ - col = find_max_col(MadjT); - if (col < 0) { do_rank1(M, Q); return; } /* Rank<2 */ - v1[0] = MadjT[0][col]; v1[1] = MadjT[1][col]; v1[2] = MadjT[2][col]; - make_reflector(v1, v1); reflect_cols(M, v1); - vcross(M[0], M[1], v2); - make_reflector(v2, v2); reflect_rows(M, v2); - w = M[0][0]; x = M[0][1]; y = M[1][0]; z = M[1][1]; - if (w * z > x* y) { - c = z + w; s = y - x; d = sqrt(c * c + s * s); c = c / d; s = s / d; - Q[0][0] = Q[1][1] = c; Q[0][1] = -(Q[1][0] = s); - } else { - c = z - w; s = y + x; d = sqrt(c * c + s * s); c = c / d; s = s / d; - Q[0][0] = -(Q[1][1] = c); Q[0][1] = Q[1][0] = s; - } - Q[0][2] = Q[2][0] = Q[1][2] = Q[2][1] = 0.0; Q[2][2] = 1.0; - reflect_cols(Q, v1); reflect_rows(Q, v2); - } - - - /******* Polar Decomposition *******/ - - /* Polar Decomposition of 3x3 matrix in 4x4, - * M = QS. See Nicholas Higham and Robert S. Schreiber, - * Fast Polar Decomposition of An Arbitrary Matrix, - * Technical Report 88-942, October 1988, - * Department of Computer Science, Cornell University. - */ - float polar_decomp(HMatrix M, HMatrix Q, HMatrix S) - { -#define TOL 1.0e-6 - HMatrix Mk, MadjTk, Ek; - float det, M_one, M_inf, MadjT_one, MadjT_inf, E_one, gamma, g1, g2; - int i, j; - mat_tpose(Mk, =, M, 3); - M_one = norm_one(Mk); M_inf = norm_inf(Mk); - do { - adjoint_transpose(Mk, MadjTk); - det = vdot(Mk[0], MadjTk[0]); - if (det == 0.0) { do_rank2(Mk, MadjTk, Mk); break; } - MadjT_one = norm_one(MadjTk); MadjT_inf = norm_inf(MadjTk); - gamma = sqrt(sqrt((MadjT_one * MadjT_inf) / (M_one * M_inf)) / fabs(det)); - g1 = gamma * 0.5; - g2 = 0.5 / (gamma * det); - mat_copy(Ek, =, Mk, 3); - mat_binop(Mk, =, g1 * Mk, +, g2 * MadjTk, 3); - mat_copy(Ek, -=, Mk, 3); - E_one = norm_one(Ek); - M_one = norm_one(Mk); M_inf = norm_inf(Mk); - } while (E_one > (M_one * TOL)); - mat_tpose(Q, =, Mk, 3); mat_pad(Q); - mat_mult(Mk, M, S); mat_pad(S); - for (i = 0; i < 3; i++) for (j = i; j < 3; j++) - S[i][j] = S[j][i] = 0.5 * (S[i][j] + S[j][i]); - return (det); - } - - - - - - - - - - - - - - - - - - /******* Spectral Decomposition *******/ - - /* Compute the spectral decomposition of symmetric positive semi-definite S. - * Returns rotation in U and scale factors in result, so that if K is a diagonal - * matrix of the scale factors, then S = U K (U transpose). Uses Jacobi method. - * See Gene H. Golub and Charles F. Van Loan. Matrix Computations. Hopkins 1983. - */ - HVect spect_decomp(HMatrix S, HMatrix U) - { - HVect kv; - double Diag[3], OffD[3]; /* OffD is off-diag (by omitted index) */ - double g, h, fabsh, fabsOffDi, t, theta, c, s, tau, ta, OffDq, a, b; - static char nxt[] = { Y,Z,X }; - int sweep, i, j; - mat_copy(U, =, mat_id, 4); - Diag[X] = S[X][X]; Diag[Y] = S[Y][Y]; Diag[Z] = S[Z][Z]; - OffD[X] = S[Y][Z]; OffD[Y] = S[Z][X]; OffD[Z] = S[X][Y]; - for (sweep = 20; sweep > 0; sweep--) { - float sm = fabs(OffD[X]) + fabs(OffD[Y]) + fabs(OffD[Z]); - if (sm == 0.0) break; - for (i = Z; i >= X; i--) { - int p = nxt[i]; int q = nxt[p]; - fabsOffDi = fabs(OffD[i]); - g = 100.0 * fabsOffDi; - if (fabsOffDi > 0.0) { - h = Diag[q] - Diag[p]; - fabsh = fabs(h); - if (fabsh + g == fabsh) { - t = OffD[i] / h; - } else { - theta = 0.5 * h / OffD[i]; - t = 1.0 / (fabs(theta) + sqrt(theta * theta + 1.0)); - if (theta < 0.0) t = -t; - } - c = 1.0 / sqrt(t * t + 1.0); s = t * c; - tau = s / (c + 1.0); - ta = t * OffD[i]; OffD[i] = 0.0; - Diag[p] -= ta; Diag[q] += ta; - OffDq = OffD[q]; - OffD[q] -= s * (OffD[p] + tau * OffD[q]); - OffD[p] += s * (OffDq - tau * OffD[p]); - for (j = Z; j >= X; j--) { - a = U[j][p]; b = U[j][q]; - U[j][p] -= s * (b + tau * a); - U[j][q] += s * (a - tau * b); - } - } - } - } - kv.x = Diag[X]; kv.y = Diag[Y]; kv.z = Diag[Z]; kv.w = 1.0; - return (kv); - } - - /******* Spectral Axis Adjustment *******/ - - /* Given a unit quaternion, q, and a scale vector, k, find a unit quaternion, p, - * which permutes the axes and turns freely in the plane of duplicate scale - * factors, such that q p has the largest possible w component, i.e. the - * smallest possible angle. Permutes k's components to go with q p instead of q. - * See Ken Shoemake and Tom Duff. Matrix Animation and Polar Decomposition. - * Proceedings of Graphics Interface 1992. Details on p. 262-263. - */ - Quat snuggle(Quat q, HVect* k) - { -#define SQRTHALF (0.7071067811865475244f) -#define sgn(n,v) ((n)?-(v):(v)) -#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];} - Quat p; - float ka[4]; - int i, turn = -1; - ka[X] = k->x; ka[Y] = k->y; ka[Z] = k->z; - if (ka[X] == ka[Y]) { if (ka[X] == ka[Z]) turn = W; else turn = Z; } - else { if (ka[X] == ka[Z]) turn = Y; else if (ka[Y] == ka[Z]) turn = X; } - if (turn >= 0) { - Quat qtoz, qp; - unsigned neg[3], win; - double mag[3], t; - static Quat qxtoz = { 0,SQRTHALF,0,SQRTHALF }; - static Quat qytoz = { SQRTHALF,0,0,SQRTHALF }; - static Quat qppmm = { 0.5, 0.5,-0.5,-0.5 }; - static Quat qpppp = { 0.5, 0.5, 0.5, 0.5 }; - static Quat qmpmm = { -0.5, 0.5,-0.5,-0.5 }; - static Quat qpppm = { 0.5, 0.5, 0.5,-0.5 }; - static Quat q0001 = { 0.0, 0.0, 0.0, 1.0 }; - static Quat q1000 = { 1.0, 0.0, 0.0, 0.0 }; - switch (turn) { - default: return (Qt_Conj(q)); - case X: q = Qt_Mul(q, qtoz = qxtoz); swap(ka, X, Z) break; - case Y: q = Qt_Mul(q, qtoz = qytoz); swap(ka, Y, Z) break; - case Z: qtoz = q0001; break; - } - q = Qt_Conj(q); - mag[0] = (double)q.z * q.z + (double)q.w * q.w - 0.5; - mag[1] = (double)q.x * q.z - (double)q.y * q.w; - mag[2] = (double)q.y * q.z + (double)q.x * q.w; - for (i = 0; i < 3; i++) if (neg[i] = (mag[i] < 0.0)) mag[i] = -mag[i]; - if (mag[0] > mag[1]) { if (mag[0] > mag[2]) win = 0; else win = 2; } - else { if (mag[1] > mag[2]) win = 1; else win = 2; } - switch (win) { - case 0: if (neg[0]) p = q1000; else p = q0001; break; - case 1: if (neg[1]) p = qppmm; else p = qpppp; cycle(ka, 0) break; - case 2: if (neg[2]) p = qmpmm; else p = qpppm; cycle(ka, 1) break; - } - qp = Qt_Mul(q, p); - t = sqrt(mag[win] + 0.5); - p = Qt_Mul(p, Qt_(0.0, 0.0, -qp.z / t, qp.w / t)); - p = Qt_Mul(qtoz, Qt_Conj(p)); - } else { - float qa[4], pa[4]; - unsigned lo, hi, neg[4], par = 0; - double all, big, two; - qa[0] = q.x; qa[1] = q.y; qa[2] = q.z; qa[3] = q.w; - for (i = 0; i < 4; i++) { - pa[i] = 0.0; - if (neg[i] = (qa[i] < 0.0)) qa[i] = -qa[i]; - par ^= neg[i]; - } - /* Find two largest components, indices in hi and lo */ - if (qa[0] > qa[1]) lo = 0; else lo = 1; - if (qa[2] > qa[3]) hi = 2; else hi = 3; - if (qa[lo] > qa[hi]) { - if (qa[lo ^ 1] > qa[hi]) { hi = lo; lo ^= 1; } - else { hi ^= lo; lo ^= hi; hi ^= lo; } - } else {if (qa[hi^1]>qa[lo]) lo = hi^1;} - all = (qa[0] + qa[1] + qa[2] + qa[3]) * 0.5; - two = (qa[hi] + qa[lo]) * SQRTHALF; - big = qa[hi]; - if (all > two) { - if (all > big) {/*all*/ - {int i; for (i = 0; i < 4; i++) pa[i] = sgn(neg[i], 0.5); } - cycle(ka, par) - } else {/*big*/ pa[hi] = sgn(neg[hi],1.0);} - } else { - if (two > big) {/*two*/ - pa[hi] = sgn(neg[hi], SQRTHALF); pa[lo] = sgn(neg[lo], SQRTHALF); - if (lo > hi) { hi ^= lo; lo ^= hi; hi ^= lo; } - if (hi == W) { hi = "\001\002\000"[lo]; lo = 3 - hi - lo; } - swap(ka, hi, lo) - } else {/*big*/ pa[hi] = sgn(neg[hi],1.0);} - } - p.x = -pa[0]; p.y = -pa[1]; p.z = -pa[2]; p.w = pa[3]; - } - k->x = ka[X]; k->y = ka[Y]; k->z = ka[Z]; - return (p); - } - - - - - - - - - - - - /******* Decompose Affine Matrix *******/ - - /* Decompose 4x4 affine matrix A as TFRUK(U transpose), where t contains the - * translation components, q contains the rotation R, u contains U, k contains - * scale factors, and f contains the sign of the determinant. - * Assumes A transforms column vectors in right-handed coordinates. - * See Ken Shoemake and Tom Duff. Matrix Animation and Polar Decomposition. - * Proceedings of Graphics Interface 1992. - */ - void decomp_affine(HMatrix A, AffineParts* parts) - { - HMatrix Q, S, U; - Quat p; - float det; - parts->t = Qt_(A[X][W], A[Y][W], A[Z][W], 0); - det = polar_decomp(A, Q, S); - if (det < 0.0) { - mat_copy(Q, =, -Q, 3); - parts->f = -1; - } else parts->f = 1; - parts->q = Qt_FromMatrix(Q); - parts->k = spect_decomp(S, U); - parts->u = Qt_FromMatrix(U); - p = snuggle(parts->u, &parts->k); - parts->u = Qt_Mul(parts->u, p); - } - - /******* Invert Affine Decomposition *******/ - - /* Compute inverse of affine decomposition. - */ - void invert_affine(AffineParts* parts, AffineParts* inverse) - { - Quat t, p; - inverse->f = parts->f; - inverse->q = Qt_Conj(parts->q); - inverse->u = Qt_Mul(parts->q, parts->u); - inverse->k.x = (parts->k.x == 0.0) ? 0.0 : 1.0 / parts->k.x; - inverse->k.y = (parts->k.y == 0.0) ? 0.0 : 1.0 / parts->k.y; - inverse->k.z = (parts->k.z == 0.0) ? 0.0 : 1.0 / parts->k.z; - inverse->k.w = parts->k.w; - t = Qt_(-parts->t.x, -parts->t.y, -parts->t.z, 0); - t = Qt_Mul(Qt_Conj(inverse->u), Qt_Mul(t, inverse->u)); - t = Qt_(inverse->k.x * t.x, inverse->k.y * t.y, inverse->k.z * t.z, 0); - p = Qt_Mul(inverse->q, inverse->u); - t = Qt_Mul(p, Qt_Mul(t, Qt_Conj(p))); - inverse->t = (inverse->f > 0.0) ? t : Qt_(-t.x, -t.y, -t.z, 0); - } - -} diff --git a/Code/Tools/CryCommonTools/Decompose.h b/Code/Tools/CryCommonTools/Decompose.h deleted file mode 100644 index 88e04737b6..0000000000 --- a/Code/Tools/CryCommonTools/Decompose.h +++ /dev/null @@ -1,30 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -namespace decomp { -// Taken from http://tog.acm.org/GraphicsGems/gemsiv/polar_decomp/Decompose.h - -/**** Decompose.h - Basic declarations ****/ -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H -#pragma once - -typedef struct {float x, y, z, w;} Quat; /* Quaternion */ -enum QuatPart {X, Y, Z, W}; -typedef Quat HVect; /* Homogeneous 3D vector */ -typedef float HMatrix[4][4]; /* Right-handed, for column vectors */ -typedef struct { - HVect t; /* Translation components */ - Quat q; /* Essential rotation */ - Quat u; /* Stretch rotation */ - HVect k; /* Stretch factors */ - float f; /* Sign of determinant */ -} AffineParts; -float polar_decomp(HMatrix M, HMatrix Q, HMatrix S); -HVect spect_decomp(HMatrix S, HMatrix U); -Quat snuggle(Quat q, HVect *k); -void decomp_affine(HMatrix A, AffineParts *parts); -void invert_affine(AffineParts *parts, AffineParts *inverse); - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H - -} diff --git a/Code/Tools/CryCommonTools/Exceptions.h b/Code/Tools/CryCommonTools/Exceptions.h deleted file mode 100644 index cc8830f0dd..0000000000 --- a/Code/Tools/CryCommonTools/Exceptions.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H -#pragma once - - -#include -#include - -class BaseException - : public std::exception -{ -public: - BaseException(const string& msg) - : msg(msg) {} - virtual const char* what() const throw () {return msg.c_str(); } - -private: - string msg; -}; - -template -class Exception - : public BaseException -{ -public: - Exception(const string& msg) - : BaseException(msg) {} -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H diff --git a/Code/Tools/CryCommonTools/FileUtil.cpp b/Code/Tools/CryCommonTools/FileUtil.cpp deleted file mode 100644 index d42a60bcc2..0000000000 --- a/Code/Tools/CryCommonTools/FileUtil.cpp +++ /dev/null @@ -1,175 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "FileUtil.h" -#include "PathHelpers.h" -#include "StringHelpers.h" - -#include -#include - - -////////////////////////////////////////////////////////////////////////// -// returns true if 'dir' is a subdirectory of 'baseDir' or same directory as 'baseDir' -// note: returns false in case of wrong names passed -static bool IsSubdirOrSameDir(const char* dir, const char* baseDir) -{ - - AZ::IO::LocalFileIO localFileIO; - - char szFullPathDir[AZ_MAX_PATH_LEN]; - if(!localFileIO.ConvertToAbsolutePath(dir, szFullPathDir, sizeof(szFullPathDir))) - { - return false; - } - - char szFullPathBaseDir[2 * 1024]; - if(!localFileIO.ConvertToAbsolutePath(baseDir, szFullPathBaseDir, sizeof(szFullPathBaseDir))) - { - return false; - } - - const char* p = szFullPathDir; - const char* q = szFullPathBaseDir; - for (;; ++p, ++q) - { - if (tolower(*p) == tolower(*q)) - { - if (*p == 0) - { - // dir is exactly same as baseDir - return true; - } - continue; - } - - if ((*p == '/' || *p == '\\') && (*q == '/' || *q == '\\')) - { - continue; - } - - if (*p == 0) - { - // dir length is shorter than baseDir length. so it's not a subdir - return false; - } - - if (*q == 0) - { - // baseDir is shorter than dir. so may be it's a subdir. - const bool isSubdir = (*p == '/' || *p == '\\'); - return isSubdir; - } - - return false; - } -} - -////////////////////////////////////////////////////////////////////////// -// the paths must have trailing slash -static bool ScanDirectoryRecursive(const string& root, const string& path, const string& file, std::vector& files, bool recursive, const string& dirToIgnore) -{ - bool anyFound = false; - if (!dirToIgnore.empty()) - { - if (IsSubdirOrSameDir(root.c_str(), dirToIgnore.c_str())) - { - return anyFound; - } - } - - AZ::IO::LocalFileIO localFileIO; - localFileIO.FindFiles(root.c_str(), file.c_str(), [&](const char* filePath) -> bool - { - bool isDir = localFileIO.IsDirectory(filePath); - if (!isDir) - { - const string foundFilename(filePath); - if (StringHelpers::MatchesWildcardsIgnoreCase(foundFilename, file)) - { - anyFound = true; - files.push_back(PathHelpers::Join(path, PathHelpers::GetFilename(filePath))); - } - } - - return true; // Keep iterating - }); - - if (recursive) - { - localFileIO.FindFiles(root.c_str(), "*", [&](const char* filePath) -> bool - { - bool isDir = localFileIO.IsDirectory(filePath); - // If recursive. - if (isDir && strcmp(filePath, ".") && strcmp(filePath, "..")) - { - if (ScanDirectoryRecursive(filePath, PathHelpers::Join(path, PathHelpers::GetFilename(filePath)), file, files, recursive, dirToIgnore)) - { - anyFound = true; - } - } - return true; // Keep iterating - }); - } - - return anyFound; -} - -////////////////////////////////////////////////////////////////////////// - -bool FileUtil::ScanDirectory(const string& path, const string& file, std::vector& files, bool recursive, const string& dirToIgnore) -{ - return ScanDirectoryRecursive(path, "", file, files, recursive, dirToIgnore); -} - - -bool FileUtil::EnsureDirectoryExists(const char* szPathIn) -{ - if (!szPathIn || !szPathIn[0]) - { - return true; - } - - if (DirectoryExists(szPathIn)) - { - return true; - } - - std::vector path(szPathIn, szPathIn + strlen(szPathIn) + 1); - char* p = &path[0]; - - // Skip '/' and '//' in the beginning - while (*p == '/' || *p == '\\') - { - ++p; - } - - for (;; ) - { - while (*p != '/' && *p != '\\' && *p) - { - ++p; - } - const char saved = *p; - *p = 0; - AZ::IO::LocalFileIO().CreatePath(&path[0]); - *p++ = saved; - if (saved == 0) - { - break; - } - } - - return DirectoryExists(szPathIn); -} diff --git a/Code/Tools/CryCommonTools/FileUtil.h b/Code/Tools/CryCommonTools/FileUtil.h deleted file mode 100644 index cf258c074b..0000000000 --- a/Code/Tools/CryCommonTools/FileUtil.h +++ /dev/null @@ -1,311 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_FILEUTIL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_FILEUTIL_H -#pragma once - -#include -#include - -#include - -#if AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) -#include -#endif -#if defined(AZ_PLATFORM_LINUX) -#include "Linux64Specific.h" -#endif // defined(AZ_PLATFORM_LINUX) - -#include -#include - -namespace FileUtil -{ - // Magic number explanation: - // Both epochs are Gregorian. 1970 - 1601 = 369. Assuming a leap - // year every four years, 369 / 4 = 92. However, 1700, 1800, and 1900 - // were NOT leap years, so 89 leap years, 280 non-leap years. - // 89 * 366 + 280 * 365 = 134744 days between epochs. Of course - // 60 * 60 * 24 = 86400 seconds per day, so 134744 * 86400 = - // 11644473600 = SECS_BETWEEN_EPOCHS. - // - // This result is also confirmed in the MSDN documentation on how - // to convert a time_t value to a win32 FILETIME. - #define SECS_BETWEEN_EPOCHS 11644473600ll - /* 10^7 */ - #define SECS_TO_100NS 10000000ll - - // Find all files matching filespec. - bool ScanDirectory(const string& path, const string& filespec, std::vector& files, bool recursive, const string& dirToIgnore); - - // Ensures that directory specified by szPathIn exists by creating all needed (sub-)directories. - // Returns false in case of a failure. - // Example: "c:\temp\test" ("c:\temp\test\" also works) - ensures that "c:\temp\test" exists. - bool EnsureDirectoryExists(const char* szPathIn); - - // converts the FILETIME to the C Timestamp (compatible with dbghelp.dll) - inline DWORD FiletimeToUnixTime(const FILETIME& ft) - { - return (DWORD)((((int64&)ft) / SECS_TO_100NS) - SECS_BETWEEN_EPOCHS); - } - - // converts the FILETIME to 64bit C timestamp - inline AZ::u64 FiletimeTo64BitUnixTime(const FILETIME& fileTime) - { - const AZ::u64 time = static_cast(fileTime.dwHighDateTime) << 32 | fileTime.dwLowDateTime; - return ((time / SECS_TO_100NS) - SECS_BETWEEN_EPOCHS); - } - - // converts the C Timestamp (compatible with dbghelp.dll) to FILETIME - inline FILETIME UnixTimeToFiletime(DWORD nCTime) - { - const int64 time = (nCTime + SECS_BETWEEN_EPOCHS) * SECS_TO_100NS; - return (FILETIME&)time; - } - - //converts the 64 bit C Timestamp to FILETIME - inline void UnixTime64BitToFiletime(AZ::u64 nCTime, FILETIME& fileTime) - { - const AZ::u64 time = (nCTime + SECS_BETWEEN_EPOCHS) * SECS_TO_100NS; - fileTime.dwLowDateTime = static_cast(time); - fileTime.dwHighDateTime = static_cast(time >> 32); - } - - inline FILETIME GetInvalidFileTime() - { - FILETIME fileTime; - fileTime.dwLowDateTime = 0; - fileTime.dwHighDateTime = 0; - return fileTime; - } - - // returns file time stamps -#if defined(AZ_PLATFORM_WINDOWS) - inline bool GetFileTimes(const char* filename, FILETIME* ftimeCreate = nullptr, FILETIME* ftimeAccess = nullptr, FILETIME* ftimeModify = nullptr) - { - WIN32_FIND_DATAA FindFileData; - const HANDLE hFind = FindFirstFileA(filename, &FindFileData); - if (hFind == INVALID_HANDLE_VALUE) - { - return false; - } - - if (ftimeModify == nullptr && ftimeCreate == nullptr && ftimeAccess == nullptr) - { - FindClose(hFind); - return true; - } - - FindClose(hFind); - if (ftimeCreate) - { - ftimeCreate->dwLowDateTime = FindFileData.ftCreationTime.dwLowDateTime; - ftimeCreate->dwHighDateTime = FindFileData.ftCreationTime.dwHighDateTime; - } - if (ftimeModify) - { - ftimeModify->dwLowDateTime = FindFileData.ftLastWriteTime.dwLowDateTime; - ftimeModify->dwHighDateTime = FindFileData.ftLastWriteTime.dwHighDateTime; - } - if (ftimeAccess) - { - ftimeAccess->dwLowDateTime = FindFileData.ftLastAccessTime.dwLowDateTime; - ftimeAccess->dwHighDateTime = FindFileData.ftCreationTime.dwHighDateTime; - } - return true; - } -#else - inline bool GetFileTimes(const char* filename, AZ::u64* timeCreate = nullptr, AZ::u64* timeAccess = nullptr, AZ::u64* timeModify = nullptr) - { - - struct stat statResult; - if (stat(filename, &statResult) != 0) - { - return false; - } - - if (timeCreate) - { - *timeCreate =static_cast(statResult.st_ctime); - } - if (timeModify) - { - *timeModify =static_cast(statResult.st_mtime); - } - if (timeAccess) - { - *timeAccess =static_cast(statResult.st_atime); - } - return true; - } -#endif - - - - inline FILETIME GetLastWriteFileTime(const char* filename) - { - FILETIME timeModify = GetInvalidFileTime(); -#if defined(AZ_PLATFORM_WINDOWS) - GetFileTimes(filename, nullptr, nullptr, &timeModify); -#else - AZ::u64 modTime = 0; - GetFileTimes(filename, nullptr, nullptr, &modTime); - if(modTime != 0) - { - UnixTime64BitToFiletime(modTime, timeModify); - } -#endif - return timeModify; - } - - inline bool FileTimesAreEqual(const FILETIME& fileTime0, const FILETIME& fileTime1) - { - return - (fileTime0.dwLowDateTime == fileTime1.dwLowDateTime) && - (fileTime0.dwHighDateTime == fileTime1.dwHighDateTime); - } - - inline bool FileTimesAreEqual(const char* const srcfilename, const char* const targetfilename) - { - FILETIME ftSource = FileUtil::GetLastWriteFileTime(srcfilename); - FILETIME ftTarget = FileUtil::GetLastWriteFileTime(targetfilename); - return FileTimesAreEqual(ftSource, ftTarget); - } - - inline bool FileTimeIsValid(const FILETIME& fileTime) - { - return !FileTimesAreEqual(GetInvalidFileTime(), fileTime); - } - - inline bool SetFileTimes(const char* const filename, const FILETIME& creationFileTime, const FILETIME& accessFileTime, const FILETIME& modifcationFileTime) - { -#if defined(AZ_PLATFORM_WINDOWS) - const HANDLE hf = CreateFileA(filename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); - if (hf != INVALID_HANDLE_VALUE) - { - if (SetFileTime(hf, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - if (CloseHandle(hf)) - { - return true; - } - } - - CloseHandle(hf); - } -#else - AZ::u64 creationTime = FiletimeTo64BitUnixTime(creationFileTime); - AZ::u64 modificationTime = FiletimeTo64BitUnixTime(modifcationFileTime); - - struct utimbuf puttime; - puttime.modtime = modificationTime; - puttime.actime = creationTime; - - if (utime(filename, &puttime) == 0) - { - return true; - } - -#endif - return false; - } - - inline bool SetFileTimes(const char* const filename, const FILETIME& fileTime) - { -#if defined(AZ_PLATFORM_WINDOWS) - const HANDLE hf = CreateFileA(filename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); - if (hf != INVALID_HANDLE_VALUE) - { - if (SetFileTime(hf, &fileTime, &fileTime, &fileTime)) - { - if (CloseHandle(hf)) - { - return true; - } - } - - CloseHandle(hf); - } -#else - - AZ::u64 newTime = FiletimeTo64BitUnixTime(fileTime); - - struct utimbuf puttime; - puttime.modtime = newTime; - puttime.actime = newTime; - - if (utime(filename, &puttime) == 0) - { - return true; - } -#endif - return false; - } - - inline bool SetFileTimes(const char* const srcfilename, const char* const targetfilename) - { -#if defined(AZ_PLATFORM_WINDOWS) - FILETIME creationFileTime, accessFileTime, modifcationFileTime; - if (GetFileTimes(srcfilename, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - const HANDLE hf = CreateFileA(targetfilename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); - if (hf != INVALID_HANDLE_VALUE) - { - if (SetFileTime(hf, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - if (CloseHandle(hf)) - { - return true; - } - } - - CloseHandle(hf); - } - } -#else - AZ::u64 creationFileTime, accessFileTime, modifcationFileTime; - if (GetFileTimes(srcfilename, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - struct utimbuf puttime; - puttime.modtime = modifcationFileTime; - puttime.actime = accessFileTime; - - if (utime(targetfilename, &puttime) == 0) - { - return true; - } - } -#endif - return false; - } - - inline uint64 GetFileSize(const char* const filename) - { - AZ::u64 fileSize = AZ::IO::SystemFile::Length(filename); - return fileSize >= 0? fileSize : -1; - - } - - inline bool FileExists(const char* szPath) - { - return AZ::IO::LocalFileIO().Exists(szPath); - } - - inline bool DirectoryExists(const char* szPath) - { - return AZ::IO::LocalFileIO().IsDirectory(szPath); - } -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_FILEUTIL_H diff --git a/Code/Tools/CryCommonTools/FileXmlBufferSource.h b/Code/Tools/CryCommonTools/FileXmlBufferSource.h deleted file mode 100644 index de802a3311..0000000000 --- a/Code/Tools/CryCommonTools/FileXmlBufferSource.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H -#pragma once - - -class FileXmlBufferSource - : public IXmlBufferSource -{ -public: - FileXmlBufferSource(const char* path) - { - file = std::fopen(path, "r"); - } - ~FileXmlBufferSource() - { - if (file) - { - std::fclose(file); - } - } - - virtual int Read(void* buffer, int size) const - { - if (!file) - { - return 0; - } - return std::fread(buffer, 1, size, file); - } - -private: - mutable std::FILE* file; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H diff --git a/Code/Tools/CryCommonTools/ILogger.h b/Code/Tools/CryCommonTools/ILogger.h deleted file mode 100644 index cbcbae3094..0000000000 --- a/Code/Tools/CryCommonTools/ILogger.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H -#pragma once - - -#include -#include - -class ILogger -{ -public: - enum ESeverity - { - eSeverity_Debug, - eSeverity_Info, - eSeverity_Warning, - eSeverity_Error - }; - - virtual ~ILogger() - { - } - - void Log(ESeverity eSeverity, const char* const format, ...) - { - char buffer[2048]; - { - va_list args; - va_start(args, format); - _vsnprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, format, args); - va_end(args); - } - LogImpl(eSeverity, buffer); - } - -protected: - virtual void LogImpl(ESeverity eSeverity, const char* text) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H diff --git a/Code/Tools/CryCommonTools/IPakSystem.h b/Code/Tools/CryCommonTools/IPakSystem.h deleted file mode 100644 index d8646c3a2c..0000000000 --- a/Code/Tools/CryCommonTools/IPakSystem.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H -#define CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H -#pragma once - -#include - -struct PakSystemFile; -struct PakSystemArchive; -struct IPakSystem -{ - virtual PakSystemFile* Open(const char* filename, const char* mode) = 0; - virtual bool ExtractNoOverwrite(const char* filename, const char* extractToFile = 0) = 0; - virtual void Close(PakSystemFile* file) = 0; - virtual int GetLength(PakSystemFile* file) const = 0; - virtual int Read(PakSystemFile* file, void* buffer, int size) = 0; - virtual bool EoF(PakSystemFile* file) = 0; - - virtual PakSystemArchive* OpenArchive(const char* path, size_t fileAlignment = 1, bool encrypted = false, const uint32 encryptionKey[4] = 0) = 0; - virtual void CloseArchive(PakSystemArchive* archive) = 0; - - // Summary: - // Adds a new file to the pak or update an existing one. - // Adds a directory (creates several nested directories if needed) - // Arguments: - // path - relative path inside archive - // data, size - file content - // modTime - modification timestamp of the file - // compressionLevel - level of compression (correnponds to zlib-levels): - // -1 or [0-9] where -1=default compression, 0=no compression, 9=best compression - virtual void AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel = -1) = 0; - - virtual bool DeleteFromArchive(PakSystemArchive* archive, const char* path) = 0; - virtual bool CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H diff --git a/Code/Tools/CryCommonTools/ISettings.h b/Code/Tools/CryCommonTools/ISettings.h deleted file mode 100644 index bba3100215..0000000000 --- a/Code/Tools/CryCommonTools/ISettings.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_ISETTINGS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ISETTINGS_H -#pragma once - - -class ISettings -{ -public: - virtual bool GetSettingString(char* buffer, int bufferSizeInBytes, const char* key) = 0; - virtual bool GetSettingInt(int& value, const char* key) = 0; -}; - -inline bool GetSettingByRef(ISettings* settings, const string& key, string& value) -{ - char buffer[1024]; - bool success = false; - if (settings) - { - success = settings->GetSettingString(buffer, sizeof(buffer), key.c_str()); - } - if (success) - { - value = buffer; - } - return success; -} - -inline bool GetSettingByRef(ISettings* settings, const string& key, int& value) -{ - return settings->GetSettingInt(value, key.c_str()); -} - -template -inline T GetSetting(ISettings* settings, const string& key, const T& dflt) -{ - T value; - if (!GetSettingByRef(settings, key, value)) - { - value = dflt; - } - return value; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ISETTINGS_H diff --git a/Code/Tools/CryCommonTools/LocaleChanger.cpp b/Code/Tools/CryCommonTools/LocaleChanger.cpp deleted file mode 100644 index 3a9edee30a..0000000000 --- a/Code/Tools/CryCommonTools/LocaleChanger.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "LocaleChanger.h" -#include - -LocaleChanger::LocaleChanger(int category, const char* newLocale) -{ - m_category = category; - m_oldLocale = setlocale(category, newLocale); -} - -LocaleChanger::~LocaleChanger() -{ - setlocale(m_category, m_oldLocale.c_str()); -} diff --git a/Code/Tools/CryCommonTools/LocaleChanger.h b/Code/Tools/CryCommonTools/LocaleChanger.h deleted file mode 100644 index 3b85c462a2..0000000000 --- a/Code/Tools/CryCommonTools/LocaleChanger.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H -#pragma once - - -class LocaleChanger -{ -public: - LocaleChanger(int category, const char* newLocale); - ~LocaleChanger(); - -private: - int m_category; - string m_oldLocale; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H diff --git a/Code/Tools/CryCommonTools/LogFile.cpp b/Code/Tools/CryCommonTools/LogFile.cpp deleted file mode 100644 index ef98be776b..0000000000 --- a/Code/Tools/CryCommonTools/LogFile.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "LogFile.h" - -LogFile::LogFile(const char* const filename) - : m_file(0) - , m_hasWarnings(false) - , m_hasErrors(false) -{ - m_file = std::fopen(filename, "w"); -} - -LogFile::~LogFile() -{ - if (m_file) - { - fclose(m_file); - } -} - -bool LogFile::IsOpen() const -{ - return m_file != 0; -} - -bool LogFile::HasWarningsOrErrors() const -{ - return m_hasWarnings || m_hasErrors; -} - -void LogFile::LogImpl(ESeverity eSeverity, const char* const text) -{ - const char* severityMessage = 0; - switch (eSeverity) - { - case eSeverity_Debug: - severityMessage = " "; - break; - case eSeverity_Info: - severityMessage = " "; - break; - case eSeverity_Warning: - severityMessage = "W: "; - break; - case eSeverity_Error: - severityMessage = "E: "; - break; - default: - severityMessage = "?: "; - break; - } - - if (eSeverity == eSeverity_Warning) - { - m_hasWarnings = true; - } - if (eSeverity == eSeverity_Error) - { - m_hasErrors = true; - } - - if (m_file) - { - fprintf(m_file, "%s%s\n", severityMessage, text); - fflush(m_file); - } -} diff --git a/Code/Tools/CryCommonTools/LogFile.h b/Code/Tools/CryCommonTools/LogFile.h deleted file mode 100644 index d26c457165..0000000000 --- a/Code/Tools/CryCommonTools/LogFile.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H -#pragma once - - -#include "ILogger.h" - -class LogFile - : public ILogger -{ -public: - LogFile(const char* filename); - ~LogFile(); - - bool IsOpen() const; - bool HasWarningsOrErrors() const; - - // ILogger - virtual void LogImpl(ESeverity eSeverity, const char* message); - -private: - std::FILE* m_file; - bool m_hasWarnings; - bool m_hasErrors; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H diff --git a/Code/Tools/CryCommonTools/MathHelpers.h b/Code/Tools/CryCommonTools/MathHelpers.h deleted file mode 100644 index d21c14aa6c..0000000000 --- a/Code/Tools/CryCommonTools/MathHelpers.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_MATHHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_MATHHELPERS_H -#pragma once - - -#include -#if (_M_IX86_FP > 0) -#include -#endif - -namespace MathHelpers -{ -#if (_M_IX86_FP > 0) - inline int FastRoundFloatTowardZero(float f) - { - return _mm_cvtt_ss2si(_mm_set_ss(f)); - } -#else - inline int FastRoundFloatTowardZero(float f) - { - return int(f); - } -#endif - -#if defined(AZ_PLATFORM_WINDOWS) - - inline unsigned int EnableFloatingPointExceptions(unsigned int mask) - { - _clearfp(); - unsigned int oldMask; - _controlfp_s(&oldMask, 0, 0); - unsigned int newMask; - _controlfp_s(&newMask, ~mask, _MCW_EM); - return ~oldMask; - } - - class AutoFloatingPointExceptions - { - public: - AutoFloatingPointExceptions(const unsigned int mask) - : m_mask(EnableFloatingPointExceptions(mask)) - { - } - - ~AutoFloatingPointExceptions() - { - EnableFloatingPointExceptions(m_mask); - } - - private: - unsigned int m_mask; - }; - -#endif //AZ_PLATFORM_WINDOWS -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_MATHHELPERS_H - - diff --git a/Code/Tools/CryCommonTools/ModuleHelpers.cpp b/Code/Tools/CryCommonTools/ModuleHelpers.cpp deleted file mode 100644 index 2ce5c2639a..0000000000 --- a/Code/Tools/CryCommonTools/ModuleHelpers.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "ModuleHelpers.h" - -HMODULE ModuleHelpers::GetCurrentModule(CurrentModuleSpecifier moduleSpecifier) -{ - switch (moduleSpecifier) - { - case CurrentModuleSpecifier_Executable: - return GetModuleHandle(0); - - case CurrentModuleSpecifier_Library: - MEMORY_BASIC_INFORMATION mbi; - static int dummy; - VirtualQuery(&dummy, &mbi, sizeof(mbi)); - HMODULE instance = reinterpret_cast(mbi.AllocationBase); - return instance; - } - - return 0; -} - -std::basic_string ModuleHelpers::GetCurrentModulePath(CurrentModuleSpecifier moduleSpecifier) -{ - // Here's a trick that will get you the handle of the module - // you're running in without any a-priori knowledge: - // http://www.dotnet247.com/247reference/msgs/13/65259.aspx - HMODULE instance = GetCurrentModule(moduleSpecifier); - TCHAR moduleNameBuffer[MAX_PATH]; - GetModuleFileName(instance, moduleNameBuffer, sizeof(moduleNameBuffer) / sizeof(moduleNameBuffer[0])); - return moduleNameBuffer; -} diff --git a/Code/Tools/CryCommonTools/ModuleHelpers.h b/Code/Tools/CryCommonTools/ModuleHelpers.h deleted file mode 100644 index cb9049e89b..0000000000 --- a/Code/Tools/CryCommonTools/ModuleHelpers.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_MODULEHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_MODULEHELPERS_H -#pragma once - - -namespace ModuleHelpers -{ - enum CurrentModuleSpecifier - { - CurrentModuleSpecifier_Executable, - CurrentModuleSpecifier_Library - }; - - HMODULE GetCurrentModule(CurrentModuleSpecifier moduleSpecifier); - std::basic_string GetCurrentModulePath(CurrentModuleSpecifier moduleSpecifier); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_MODULEHELPERS_H diff --git a/Code/Tools/CryCommonTools/PakSystem.cpp b/Code/Tools/CryCommonTools/PakSystem.cpp deleted file mode 100644 index 42a129c5e6..0000000000 --- a/Code/Tools/CryCommonTools/PakSystem.cpp +++ /dev/null @@ -1,380 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include "PakSystem.h" -#include "PathHelpers.h" -#include "StringHelpers.h" -#include "ZipDir/ZipDir.h" - -#include -#include -#include - - - -PakSystemFile::PakSystemFile() -{ - type = PakSystemFileType_Unknown; - file = NULL; - zip = NULL; - fileEntry = NULL; - data = NULL; - dataPosition = 0; -} - -PakSystem::PakSystem() -{ -} - -PakSystemFile* PakSystem::Open(const char* a_path, const char* a_mode) -{ - string normalPath = a_path; - - string const zipExt = ".zip"; - bool bZip = StringHelpers::EndsWithIgnoreCase(normalPath, zipExt); - - if (bZip) - { - // If it's a .zip file, then we'll try to look for a file without .zip extension inside of the .zip file - normalPath.erase(normalPath.length() - zipExt.length(), zipExt.length()); - } - - string zipPath = normalPath + zipExt; - string filename = PathHelpers::GetFilename(normalPath); - - if (!normalPath.empty() && normalPath[0] == '@') - { - // File is inside pak file. - int splitter = normalPath.find_first_of("|;,"); - if (splitter >= 0) - { - zipPath = normalPath.substr(1, splitter - 1); - filename = StringHelpers::MakeLowerCase(normalPath.substr(splitter + 1)); - bZip = true; - } - else - { - return 0; - } - } - - if (!bZip) - { - // Try to open the file. - FILE* f = nullptr; - azfopen(&f, normalPath.c_str(), a_mode); - if (f) - { - std::unique_ptr file(new PakSystemFile()); - file->type = PakSystemFileType_File; - file->file = f; - - return file.release(); - } - } - - // if it's simple and read-only, it's assumed it's read-only - unsigned const nFactoryFlags = ZipDir::CacheFactory::FLAGS_DONT_COMPACT | ZipDir::CacheFactory::FLAGS_READ_ONLY; - - bool bFileExists = false; - const uint32* decryptionKey = 0; // use default one - - if (bZip) - { - // a caller asked to open a .zip file. check if the .zip file on disk exist - FILE* f = nullptr; - azfopen(&f, zipPath.c_str(), "rb"); - if (f) - { - fclose(f); - bFileExists = true; - } - } - else - { - // a caller specified normal file. we already failed to find it on disk, - // so the file could be within a .pak file. let's find all 'potential' - // pak files and look within these for a matching file - - std::vector foundFileCountainer; // pak files found - - for (string dirToSearch = normalPath;; ) - { - dirToSearch = PathHelpers::GetDirectory(dirToSearch); - - AZ::IO::LocalFileIO localFileIO; - localFileIO.FindFiles(dirToSearch.c_str(), "*.pak", [&](const char* filePath) -> bool - { - const string foundFilename(filePath); - if (StringHelpers::EqualsIgnoreCase(PathHelpers::FindExtension(foundFilename), "pak")) - { - foundFileCountainer.push_back(foundFilename); - } - return true; // continue iterating - }); - - if (PathHelpers::GetFilename(dirToSearch).empty()) - { - // We've reached the top of the path - break; - } - } - - // iterate through found containers and look for relevant files within them - for (int iFile = 0; iFile < foundFileCountainer.size(); ++iFile) - { - zipPath = foundFileCountainer[ iFile ]; - string pathToZip = PathHelpers::GetDirectory(zipPath); - - // construct filename by removing path to zip from path to filename - string pathToFile = PathHelpers::GetDirectory(string(normalPath)); - string pureFileName = PathHelpers::GetFilename(string(normalPath)); - if (pathToFile.length() != pathToZip.length() && pathToZip.length() > 0) - { - pathToFile = pathToFile.substr(pathToZip.length() + 1); - } - filename = pathToFile.empty() - ? pureFileName - : pathToFile + "\\" + pureFileName; - - ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags); - ZipDir::CachePtr testZip = factory.New(zipPath.c_str(), decryptionKey); - ZipDir::FileEntry* testFileEntry = (testZip ? testZip->FindFile(filename.c_str()) : 0); - - // break out if we have a testFileEntry, as we've found our first (and best) candidate. - if (testFileEntry) - { - bFileExists = true; - break; - } - } - } - - { - ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags); - ZipDir::CachePtr zip = (bFileExists ? factory.New(zipPath.c_str(), decryptionKey) : 0); - ZipDir::FileEntry* fileEntry = (zip ? zip->FindFile(filename.c_str()) : 0); - - if (fileEntry) - { - std::unique_ptr file(new PakSystemFile()); - file->type = PakSystemFileType_PakFile; - file->zip = zip; - file->fileEntry = fileEntry; - file->data = zip->AllocAndReadFile(file->fileEntry); - file->dataPosition = 0; - return file.release(); - } - } - - return 0; -} - - -//Extracts archived file to disk without overwriting any files -//returns true on success, false on failure (due to potential overwrite or no file -//in archive -bool PakSystem::ExtractNoOverwrite(const char* fileToExtract, const char* extractToFile) -{ - if (0 == extractToFile) - { - extractToFile = fileToExtract; - } - - //open file using pak system - PakSystemFile* fileZip = Open(fileToExtract, "r"); - if (!fileZip) - { - return false; - } - - // Try to open a writable file - FILE* fFileOnDisk = nullptr; - azfopen(&fFileOnDisk, extractToFile, "wb"); - if (!fFileOnDisk) - { - Close(fileZip); - return false; - } - - fwrite(fileZip->data, fileZip->fileEntry->desc.lSizeUncompressed, 1, fFileOnDisk); - fclose(fFileOnDisk); - - Close(fileZip); - - return true; -} - - -void PakSystem::Close(PakSystemFile* file) -{ - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - fclose(file->file); - break; - - case PakSystemFileType_PakFile: - file->zip->Free(file->data); - break; - } - delete file; - } -} - - -int PakSystem::GetLength(PakSystemFile* file) const -{ - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - { - if (file->file) - { - long pos = ftell(file->file); - fseek(file->file, 0, SEEK_END); - int result = ftell(file->file); - fseek(file->file, pos, SEEK_SET); - return result; - } - break; - } - case PakSystemFileType_PakFile: - { - if (file->fileEntry) - { - return file->fileEntry->desc.lSizeUncompressed; - } - break; - } - default: - { - break; - } - } - } - return 0; -} - - -int PakSystem::Read(PakSystemFile* file, void* buffer, int size) -{ - int readBytes = 0; - - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - { - readBytes = fread(buffer, 1, size, file->file); - } - break; - - case PakSystemFileType_PakFile: - { - int fileSize = file->fileEntry->desc.lSizeUncompressed; - readBytes = (fileSize - file->dataPosition > size ? size : fileSize - file->dataPosition); - memcpy(buffer, static_cast(file->data) + file->dataPosition, readBytes); - file->dataPosition += readBytes; - } - break; - } - } - - return readBytes; -} - -bool PakSystem::EoF(PakSystemFile* file) -{ - bool EoF = true; - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - { - EoF = (0 != feof(file->file)); - } - break; - - case PakSystemFileType_PakFile: - { - int fileSize = file->fileEntry->desc.lSizeUncompressed; - EoF = (file->dataPosition >= fileSize); - } - break; - } - } - - return EoF; -} - -PakSystemArchive* PakSystem::OpenArchive(const char* path, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]) -{ - //unsigned nFactoryFlags = ZipDir::CacheFactory::FLAGS_DONT_COMPACT | ZipDir::CacheFactory::FLAGS_CREATE_NEW; - unsigned nFactoryFlags = 0; - ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags); - ZipDir::CacheRWPtr cache = factory.NewRW(path, fileAlignment, encrypted, encryptionKey); - PakSystemArchive* archive = (cache ? new PakSystemArchive() : 0); - if (archive) - { - archive->zip = cache; - } - return archive; -} - -void PakSystem::CloseArchive(PakSystemArchive* archive) -{ - if (archive) - { - archive->zip->Close(); - delete archive; - } -} - -void PakSystem::AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel) -{ - int compressionMethod = ZipFile::METHOD_DEFLATE; - if (compressionLevel == 0) - { - compressionMethod = ZipFile::METHOD_STORE; - } - archive->zip->UpdateFile(path, data, size, compressionMethod, compressionLevel, modTime); -} - -////////////////////////////////////////////////////////////////////////// -bool PakSystem::CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime) -{ - assert(archive); - - ZipDir::FileEntry* pFileEntry = archive->zip->FindFile(path); - if (pFileEntry) - { - return pFileEntry->CompareFileTimeNTFS(modTime); - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool PakSystem::DeleteFromArchive(PakSystemArchive* archive, const char* path) -{ - ZipDir::ErrorEnum err = archive->zip->RemoveFile(path); - return ZipDir::ZD_ERROR_SUCCESS == err; -} diff --git a/Code/Tools/CryCommonTools/PakSystem.h b/Code/Tools/CryCommonTools/PakSystem.h deleted file mode 100644 index ba57f26d4d..0000000000 --- a/Code/Tools/CryCommonTools/PakSystem.h +++ /dev/null @@ -1,69 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_PAKSYSTEM_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H -#pragma once - - -#include "IPakSystem.h" -#include "ZipDir/ZipDir.h" // TODO: get rid of thid include - -enum PakSystemFileType -{ - PakSystemFileType_Unknown, - PakSystemFileType_File, - PakSystemFileType_PakFile -}; -struct PakSystemFile -{ - PakSystemFile(); - PakSystemFileType type; - - // PakSystemFileType_File - FILE* file; - - // PakSystemFileType_PakFile - ZipDir::CachePtr zip; - ZipDir::FileEntry* fileEntry; - void* data; - int dataPosition; -}; - -struct PakSystemArchive -{ - ZipDir::CacheRWPtr zip; -}; - -class PakSystem - : public IPakSystem -{ -public: - PakSystem(); - - // IPakSystem - virtual PakSystemFile* Open(const char* filename, const char* mode); - virtual bool ExtractNoOverwrite(const char* filename, const char* extractToFile = 0); - virtual void Close(PakSystemFile* file); - virtual int GetLength(PakSystemFile* file) const; - virtual int Read(PakSystemFile* file, void* buffer, int size); - virtual bool EoF(PakSystemFile* file); - - virtual PakSystemArchive* OpenArchive(const char* path, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]); - virtual void CloseArchive(PakSystemArchive* archive); - virtual void AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel); - virtual bool DeleteFromArchive(PakSystemArchive* archive, const char* path); - virtual bool CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H diff --git a/Code/Tools/CryCommonTools/PakXmlFileBufferSource.h b/Code/Tools/CryCommonTools/PakXmlFileBufferSource.h deleted file mode 100644 index cd9aa9d211..0000000000 --- a/Code/Tools/CryCommonTools/PakXmlFileBufferSource.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H -#pragma once - - -#include "../CryXML/IXMLSerializer.h" -#include "IPakSystem.h" - -class PakXmlFileBufferSource - : public IXmlBufferSource -{ -public: - PakXmlFileBufferSource(IPakSystem* pakSystem, const char* path) - : pakSystem(pakSystem) - { - file = pakSystem->Open(path, "r"); - } - ~PakXmlFileBufferSource() - { - if (file) - { - pakSystem->Close(file); - } - } - - virtual int Read(void* buffer, int size) const - { - return pakSystem->Read(file, buffer, size); - }; - - IPakSystem* pakSystem; - PakSystemFile* file; -}; - -class PakXmlBufferSource - : public IXmlBufferSource -{ -public: - PakXmlBufferSource(const char* buffer, size_t length) - : position(buffer) - , end(buffer + length) - { - } - - virtual int Read(void* output, int size) const - { - size_t bytesLeft = end - position; - size_t bytesToCopy = size < bytesLeft ? size : bytesLeft; - if (bytesToCopy > 0) - { - memcpy(output, position, bytesToCopy); - position += bytesToCopy; - } - return bytesToCopy; - }; - - mutable const char* position; - const char* end; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H diff --git a/Code/Tools/CryCommonTools/PathHelpers.cpp b/Code/Tools/CryCommonTools/PathHelpers.cpp deleted file mode 100644 index 4abd28183e..0000000000 --- a/Code/Tools/CryCommonTools/PathHelpers.cpp +++ /dev/null @@ -1,621 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include "PathHelpers.h" -#include "StringHelpers.h" -#include "Util.h" - -#include -#include -#include -#include -#include - - -// Returns position of last extension in last name (string::npos if not found) -// note: returns string::npos for names starting from '.' and having no -// '.' later (for example 'aaa/.ccc', 'a:.abc', '.rc') -template -static inline size_t findExtensionPosition_Tpl(const TS& path) -{ - const size_t dotPos = path.rfind('.'); - if (dotPos == TS::npos) - { - return TS::npos; - } - - static const typename TS::value_type separators[] = { '\\', '/', ':', 0 }; - const size_t separatorPos = path.find_last_of(separators); - if (separatorPos != TS::npos) - { - if (separatorPos + 1 >= dotPos) - { - return TS::npos; - } - } - else if (dotPos == 0) - { - return TS::npos; - } - - return dotPos + 1; -} - -static size_t findExtensionPosition(const string& path) -{ - return findExtensionPosition_Tpl(path); -} - -static size_t findExtensionPosition(const wstring& path) -{ - return findExtensionPosition_Tpl(path); -} - - -string PathHelpers::FindExtension(const string& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == string::npos) ? string() : path.substr(extPos, string::npos); -} - -wstring PathHelpers::FindExtension(const wstring& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == wstring::npos) ? wstring() : path.substr(extPos, wstring::npos); -} - - -template -static inline TS ReplaceExtension_Tpl(const TS& path, const TS& newExtension) -{ - if (path.empty()) - { - return TS(); - } - - if (newExtension.empty()) - { - return PathHelpers::RemoveExtension(path); - } - - const typename TS::value_type last = path[path.length() - 1]; - if ((last == '\\') || (last == '/') || (last == ':') || (last == '.')) - { - return path; - } - - const size_t extPos = findExtensionPosition(path); - static const typename TS::value_type dot[] = { '.', 0 }; - return ((extPos == TS::npos) ? path + dot : path.substr(0, extPos)) + newExtension; -} - -string PathHelpers::ReplaceExtension(const string& path, const string& newExtension) -{ - return ReplaceExtension_Tpl(path, newExtension); -} - -wstring PathHelpers::ReplaceExtension(const wstring& path, const wstring& newExtension) -{ - return ReplaceExtension_Tpl(path, newExtension); -} - - -string PathHelpers::RemoveExtension(const string& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == string::npos) ? path : path.substr(0, extPos - 1); -} - -wstring PathHelpers::RemoveExtension(const wstring& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == wstring::npos) ? path : path.substr(0, extPos - 1); -} - - -template -static inline TS GetDirectory_Tpl(const TS& path) -{ - static const typename TS::value_type separators[] = { '/', '\\', ':', 0 }; - const size_t pos = path.find_last_of(separators); - - if (pos == TS::npos) - { - return TS(); - } - - if (path[pos] == ':' || pos == 0 || path[pos - 1] == ':') - { - return path.substr(0, pos + 1); - } - - // Handle paths like "\\machine" - if (pos == 1 && (path[0] == '/' || path[0] == '\\')) - { - return path; - } - - return path.substr(0, pos); -} - -string PathHelpers::GetDirectory(const string& path) -{ - return GetDirectory_Tpl(path); -} - -wstring PathHelpers::GetDirectory(const wstring& path) -{ - return GetDirectory_Tpl(path); -} - - -template -static inline TS GetFilename_Tpl(const TS& path) -{ - static const typename TS::value_type separators[] = { '/', '\\', ':', 0 }; - const size_t pos = path.find_last_of(separators); - - if (pos == TS::npos) - { - return path; - } - - // Handle paths like "\\machine" - if (pos == 1 && (path[0] == '/' || path[0] == '\\')) - { - return TS(); - } - - return path.substr(pos + 1, TS::npos); -} - -string PathHelpers::GetFilename(const string& path) -{ - return GetFilename_Tpl(path); -} - -wstring PathHelpers::GetFilename(const wstring& path) -{ - return GetFilename_Tpl(path); -} - - -template -static inline TS AddSeparator_Tpl(const TS& path) -{ - if (path.empty()) - { - return TS(); - } - const typename TS::value_type last = path[path.length() - 1]; - if (last == '/' || last == '\\' || last == ':') - { - return path; - } -#if defined(AZ_PLATFORM_WINDOWS) - static const typename TS::value_type separator[] = { '\\', 0 }; -#else - static const typename TS::value_type separator[] = { '/', 0 }; -#endif - return path + separator; -} - -string PathHelpers::AddSeparator(const string& path) -{ - return AddSeparator_Tpl(path); -} - -wstring PathHelpers::AddSeparator(const wstring& path) -{ - return AddSeparator_Tpl(path); -} - - -template -static inline TS RemoveSeparator_Tpl(const TS& path) -{ - if (path.empty()) - { - return TS(); - } - const typename TS::value_type last = path[path.length() - 1]; - if ((last == '/' || last == '\\') && path.length() > 1 && path[path.length() - 2] != ':') - { - return path.substr(0, path.length() - 1); - } - return path; -} - -string PathHelpers::RemoveSeparator(const string& path) -{ - return RemoveSeparator_Tpl(path); -} - -wstring PathHelpers::RemoveSeparator(const wstring& path) -{ - return RemoveSeparator_Tpl(path); -} - - -template -static inline TS RemoveDuplicateSeparators_Tpl(const TS& path) -{ - if (path.length() <= 1) - { - return path; - } - - TS ret; - ret.reserve(path.length()); - - const typename TS::value_type* p = path.c_str(); - - // We start from the second char just to avoid damaging UNC paths with double backslash at the beginning (e.g. "\\Server04\file.txt") - ret += *p++; - - while (*p) - { - ret += *p++; - if (p[-1] == '\\' || p[-1] == '/') - { - while (*p == '\\' || *p == '/') - { - ++p; - } - } - } - - return ret; -} - -string PathHelpers::RemoveDuplicateSeparators(const string& path) -{ - return RemoveDuplicateSeparators_Tpl(path); -} - -wstring PathHelpers::RemoveDuplicateSeparators(const wstring& path) -{ - return RemoveDuplicateSeparators_Tpl(path); -} - - -template -static inline TS Join_Tpl(const TS& path1, const TS& path2) -{ - if (path1.empty()) - { - return path2; - } - if (path2.empty()) - { - return path1; - } - - if (!PathHelpers::IsRelative(path2)) - { - assert(0 && "Join(): path2 is not relative"); - return TS(); - } - - const typename TS::value_type last = path1[path1.length() - 1]; - if (last == '/' || last == '\\' || last == ':') - { - return path1 + path2; - } -#if defined(AZ_PLATFORM_WINDOWS) - static const typename TS::value_type separator[] = { '\\', 0 }; -#else - static const typename TS::value_type separator[] = { '/', 0 }; -#endif - return path1 + separator + path2; -} - - -string PathHelpers::Join(const string& path1, const string& path2) -{ - return Join_Tpl(path1, path2); -} - -wstring PathHelpers::Join(const wstring& path1, const wstring& path2) -{ - return Join_Tpl(path1, path2); -} - - -template -static inline bool IsRelative_Tpl(const TS& path) -{ - if (path.empty()) - { - return true; - } - return path[0] != '/' && path[0] != '\\' && path.find(':') == TS::npos; -} - -bool PathHelpers::IsRelative(const string& path) -{ - return IsRelative_Tpl(path); -} - -bool PathHelpers::IsRelative(const wstring& path) -{ - return IsRelative_Tpl(path); -} - - -string PathHelpers::ToUnixPath(const string& path) -{ - return StringHelpers::Replace(path, '\\', '/'); -} - -wstring PathHelpers::ToUnixPath(const wstring& path) -{ - wstring s(path); - std::replace(s.begin(), s.end(), L'\\', L'/'); - return s; -} - - -string PathHelpers::ToDosPath(const string& path) -{ - return StringHelpers::Replace(path, '/', '\\'); -} - -wstring PathHelpers::ToDosPath(const wstring& path) -{ - wstring s(path); - std::replace(s.begin(), s.end(), L'/', L'\\'); - return s; -} - -string PathHelpers::ToPlatformPath(const string& path) -{ -#if defined(AZ_PLATFORM_WINDOWS) - return ToDosPath(path); -#else - return ToUnixPath(path); -#endif -} - -wstring PathHelpers::ToPlatformPath(const wstring& path) -{ -#if defined(AZ_PLATFORM_WINDOWS) - return ToDosPath(path); -#else - return ToUnixPath(path); -#endif -} - - -string PathHelpers::GetAsciiPath(const char* pPath) -{ - AZStd::wstring wstr; - AZStd::to_wstring(wstr, pPath); - return GetAsciiPath(wstr.c_str()); -} - -string PathHelpers::GetAsciiPath(const wchar_t* pPath) -{ - if (!pPath[0]) - { - return string(); - } - - wstring w = ToPlatformPath(RemoveSeparator(wstring(pPath))); - - if (StringHelpers::Utf16ContainsAsciiOnly(w.c_str())) - { - return StringHelpers::ConvertAsciiUtf16ToAscii(w.c_str()); - } - - // The path is non-ASCII, so let's resort to using short - // filenames where needed (short names are always ASCII-only) - - // Long names components - std::vector p0; - StringHelpers::Split(w, wstring(L"\\"), true, p0); - - // find last component that is not in ASCII char set - int lastNonAscii; - for (lastNonAscii = (int)p0.size() - 1; lastNonAscii >= 0; --lastNonAscii) - { - if (!StringHelpers::Utf16ContainsAsciiOnly(p0[lastNonAscii].c_str())) - { - break; - } - } - assert(lastNonAscii >= 0); - - string res; - res.reserve(w.length()); - - w.clear(); - for (int i = 0; i <= lastNonAscii; ++i) - { - w.append(p0[i]); - if (i < lastNonAscii) - { - w.push_back('\\'); - } - } - - enum - { - kBufferLen = AZ_MAX_PATH_LEN - }; - wchar_t bufferWchars[kBufferLen]; - -#if defined(AZ_PLATFORM_WINDOWS) - const int charCount = GetShortPathNameW(w.c_str(), bufferWchars, kBufferLen); -#else - const int charCount = w.length(); - wcsncpy(bufferWchars, w.c_str(), kBufferLen); -#endif - if (charCount <= 0 || charCount >= kBufferLen) - { - return string(); - } -#if defined(AZ_PLATFORM_WINDOWS) - // Paranoid - if (!StringHelpers::Utf16ContainsAsciiOnly(bufferWchars)) - { - assert(0); - return string(); - } -#endif - - // Short names components - std::vector p1; - StringHelpers::Split(wstring(bufferWchars), wstring(L"\\"), true, p1); - - for (size_t i = 0; i < (int)p0.size(); ++i) - { - if (!p0[i].empty()) - { - const wstring& p = - (i > lastNonAscii || StringHelpers::Utf16ContainsAsciiOnly(p0[i].c_str())) - ? p0[i] - : p1[i]; - res.append(StringHelpers::ConvertAsciiUtf16ToAscii(p.c_str())); - } - if (i + 1 < (int)p0.size()) - { - res.push_back('\\'); - } - } - - return res; -} - - -string PathHelpers::GetAbsoluteAsciiPath(const char* pPath) -{ - char fullPath[AZ_MAX_PATH_LEN]; - AZ::IO::LocalFileIO localFileIO; - - AZStd::string normalizedPath(pPath); - AzFramework::StringFunc::Path::Normalize(normalizedPath); - - localFileIO.ConvertToAbsolutePath(normalizedPath.c_str(), fullPath, AZ_MAX_PATH_LEN); - fullPath[sizeof(fullPath) - 1] = '\0'; - - AZStd::wstring wstr; - AZStd::to_wstring(wstr, fullPath); - return GetAsciiPath(wstr.c_str()); -} - -string PathHelpers::GetAbsoluteAsciiPath(const wchar_t* pPath) -{ - AZStd::string str; - AZStd::to_string(str, pPath); - - AzFramework::StringFunc::Path::Normalize(str); - - char fullPath[AZ_MAX_PATH_LEN]; - AZ::IO::LocalFileIO localFileIO; - localFileIO.ConvertToAbsolutePath(str.c_str(), fullPath, AZ_MAX_PATH_LEN); - fullPath[sizeof(fullPath) - 1] = '\0'; - - AZStd::wstring wstr; - AZStd::to_wstring(wstr, fullPath); - return GetAsciiPath(wstr.c_str()); -} - - -string PathHelpers::GetShortestRelativeAsciiPath(const string& baseFolder, const string& dependentPath) -{ - const string d = GetAbsoluteAsciiPath(dependentPath.c_str()); - if (d.empty()) - { - return PathHelpers::CanonicalizePath(dependentPath); - } - - const string b = GetAbsoluteAsciiPath(baseFolder.c_str()); - if (b.empty()) - { - return PathHelpers::CanonicalizePath(dependentPath); - } - - const string b2 = AddSeparator(b); - if (StringHelpers::StartsWithIgnoreCase(d, b2)) - { - const size_t len = d.length() - b2.length(); - // note: len == 0 is possible in case of "C:\" and "C:\". - return (len == 0) ? string(".") : d.substr(b2.length(), len); - } - - std::vector p0; - StringHelpers::Split(b2, string("\\"), true, p0); - std::vector p1; - StringHelpers::Split(d, string("\\"), true, p1); - - if (!StringHelpers::EqualsIgnoreCase(p0[0], p1[0])) - { - // got different drive letters - return PathHelpers::CanonicalizePath(dependentPath); - } - - if (StringHelpers::EqualsIgnoreCase(d, b)) - { - // exactly same path - return string("."); - } - - // Search for first non-matching component - for (int i = 1; i < (int)p0.size(); ++i) - { - if (StringHelpers::EqualsIgnoreCase(p0[i], p1[i])) - { - continue; - } - - string s; - s.reserve(Util::getMax(d.length(), b.length())); - for (int j = i; j < (int)p0.size(); ++j) - { - if (!p0[j].empty()) - { - s.append("..\\"); - } - } - for (int j = i; j < (int)p1.size(); ++j) - { - s.append(p1[j]); - if (j + 1 < (int)p1.size()) - { - s.push_back('\\'); - } - } - return s; - } - - assert(0); - return string(); -} - - -string PathHelpers::CanonicalizePath(const string& path) -{ - string result = RemoveSeparator(path); - // remove .\ or ./ at the path beginning. - if (result.length() > 2) - { - if (result[0] == '.' && (result[1] == '\\' || result[1] == '/')) - { - result = result.substr(2); - } - } - - return result; -} diff --git a/Code/Tools/CryCommonTools/PathHelpers.h b/Code/Tools/CryCommonTools/PathHelpers.h deleted file mode 100644 index 4cf509d876..0000000000 --- a/Code/Tools/CryCommonTools/PathHelpers.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_PATHHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PATHHELPERS_H -#pragma once - -#include - -namespace PathHelpers -{ - // checks to see what the extension is in a string path - // returns the extension if found or an empty string if not found - string FindExtension(const string& path); - wstring FindExtension(const wstring& path); - - // replace an extension of a string path with a new specified extension - // returns a string with the replaced extension or the original string if unable to replace the extension - string ReplaceExtension(const string& path, const string& newExtension); - wstring ReplaceExtension(const wstring& path, const wstring& newExtension); - - // removes the extension of a specified string path - // returns a string with the extension removed or the original string if no extension was found - string RemoveExtension(const string& path); - wstring RemoveExtension(const wstring& path); - - // "abc/def/ghi" -> "abc/def" - // "abc/def/ghi/" -> "abc/def/ghi" - // "/" -> "/" - // gets the directory path out of a specified string path - // returns a string of the directory path - string GetDirectory(const string& path); - wstring GetDirectory(const wstring& path); - - // gets the file name out of a specified string path - // returns a string of the file name - string GetFilename(const string& path); - wstring GetFilename(const wstring& path); - - // add a backslash to a specified path if it doesn't already have a separator - // returns a path with the appended backslash unless there was already a separator - string AddSeparator(const string& path); - wstring AddSeparator(const wstring& path); - - // removes a forward slash or backslash from the end of a specified string path if found - // returns a string with the separator removed - string RemoveSeparator(const string& path); - wstring RemoveSeparator(const wstring& path); - - // removes extra forward slashes and backslashes if they're contained within the string path - // returns a string with the extra forward slashes and backslashes removed - string RemoveDuplicateSeparators(const string& path); - wstring RemoveDuplicateSeparators(const wstring& path); - - // It's not allowed to pass an absolute path in path2. - // Join(GetDirectory(fname), GetFilename(fname)) returns fname. - // merges two string paths together into one - // returns the merged string paths - string Join(const string& path1, const string& path2); - wstring Join(const wstring& path1, const wstring& path2); - - // checks to see if the path is a relative path - // returns true if it is or false if it is not - bool IsRelative(const string& path); - bool IsRelative(const wstring& path); - - // converts a string path to a unix path format - // returns the path in unix format - string ToUnixPath(const string& path); - wstring ToUnixPath(const wstring& path); - - // converts a string path to a dos path format - // returns the path in dos format - string ToDosPath(const string& path); - wstring ToDosPath(const wstring& path); - - // converts a string to the platform's path format. - // returns the path in the platform's path format. - string ToPlatformPath(const string& path); - wstring ToPlatformPath(const wstring& path); - - // char* pPath: in ASCII or UTF-8 encoding - // wchar_t* pPath: in UTF-16 encoding - // Non-ASCII components of pPath (everything from &pPath[0] to last non-ASCII - // part, inclusively) should exist on disk, otherwise an empty string is returned. - string GetAsciiPath(const char* pPath); - string GetAsciiPath(const wchar_t* pPath); - - // pPath passed should be in ASCII or UTF-8 encoding - string GetAbsoluteAsciiPath(const char* pPath); - // pPath passed should be in UTF-16 encoding - string GetAbsoluteAsciiPath(const wchar_t* pPath); - - // baseFolder and dependentPath passed should be in ASCII or UTF-8 encoding - string GetShortestRelativeAsciiPath(const string& baseFolder, const string& dependentPath); - - string CanonicalizePath(const string& path); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PATHHELPERS_H diff --git a/Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h b/Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h deleted file mode 100644 index 03a0b4ff38..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h +++ /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. -* -*/ -#pragma once - -#define AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(file, offset, s) fseek(file, offset, s) -#define AZ_TRAIT_CRYCOMMONTOOLS_FTELL(file) ftell(file) diff --git a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h b/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h deleted file mode 100644 index 81a38177c2..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h +++ /dev/null @@ -1,16 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h> - -#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 0 diff --git a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h b/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h deleted file mode 100644 index 6232c6462b..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h +++ /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. -* -*/ -#pragma once - -#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h> -#include diff --git a/Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake b/Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake deleted file mode 100644 index 9c71b39bf1..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ZipDir/ZipDir_Traits_Platform.h - ZipDir/ZipDir_Traits_Linux.h - ../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h -) diff --git a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h b/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h deleted file mode 100644 index 111a31dc55..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h +++ /dev/null @@ -1,16 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h> - -#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 1 diff --git a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h b/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h deleted file mode 100644 index e601614c59..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h +++ /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. -* -*/ -#pragma once - -#include diff --git a/Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake b/Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake deleted file mode 100644 index b1fb3fa9a1..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ZipDir/ZipDir_Traits_Platform.h - ZipDir/ZipDir_Traits_Mac.h - ../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h -) diff --git a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h b/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h deleted file mode 100644 index 1d177a5c8c..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h +++ /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. -* -*/ -#pragma once - -#include diff --git a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h b/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h deleted file mode 100644 index 6d9c5314e4..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h +++ /dev/null @@ -1,16 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#define AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(file, offset, s) _fseeki64(file, (__int64)offset, s) -#define AZ_TRAIT_CRYCOMMONTOOLS_FTELL(file) (size_t)_ftelli64(file) -#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 1 diff --git a/Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake b/Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake deleted file mode 100644 index 252842e917..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ZipDir/ZipDir_Traits_Platform.h - ZipDir/ZipDir_Traits_Windows.h -) diff --git a/Code/Tools/CryCommonTools/ProgressRange.h b/Code/Tools/CryCommonTools/ProgressRange.h deleted file mode 100644 index 297d862980..0000000000 --- a/Code/Tools/CryCommonTools/ProgressRange.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_PROGRESSRANGE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PROGRESSRANGE_H -#pragma once - - -class ProgressRange -{ -public: - template - ProgressRange(T* object, void (T::* setter)(float progress)) - : m_target(new MethodTarget(object, setter)) - , m_progress(0.0f) - , m_start(0.0f) - , m_scale(1.0f) - { - m_target->Set(m_start); - } - - ProgressRange(ProgressRange& parent, float scale) - : m_target(new ParentRangeTarget(parent)) - , m_progress(0.0f) - , m_start(parent.m_progress) - , m_scale(scale) - { - m_target->Set(m_start); - } - - ~ProgressRange() - { - m_target->Set(m_start + m_scale); - delete m_target; - } - - void SetProgress(float progress) - { - assert(progress > -0.01f && progress < 1.1f); - m_progress = progress; - m_target->Set(m_start + m_scale * progress); - } - -private: - struct ITarget - { - virtual ~ITarget() {} - virtual void Set(float progress) = 0; - }; - - struct ParentRangeTarget - : public ITarget - { - ParentRangeTarget(ProgressRange& range) - : range(range) {} - virtual void Set(float progress) {range.SetProgress(progress); } - ProgressRange& range; - }; - - template - struct MethodTarget - : public ITarget - { - typedef void (T::* Setter)(float progress); - MethodTarget(T* object, Setter setter) - : object(object) - , setter(setter) {} - virtual void Set(float progress) {(object->*setter)(progress); } - T* object; - Setter setter; - }; - - ITarget* m_target; - float m_progress; - float m_start; - float m_scale; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PROGRESSRANGE_H diff --git a/Code/Tools/CryCommonTools/PropertyHelpers.cpp b/Code/Tools/CryCommonTools/PropertyHelpers.cpp deleted file mode 100644 index aaaa1df309..0000000000 --- a/Code/Tools/CryCommonTools/PropertyHelpers.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include "PropertyHelpers.h" -#include "StringHelpers.h" - - -bool PropertyHelpers::GetPropertyValue(const string& a_propertiesString, const char* a_propertyName, string& a_value) -{ - if ((a_propertyName == 0) || (a_propertyName[0] == 0)) - { - return false; - } - - const char* lineStart = a_propertiesString.c_str(); - - while (*lineStart) - { - string key; - string value; - - const size_t lineEndPosition = strcspn(lineStart, "\n"); - const size_t equalPosition = strcspn(lineStart, "="); - - if (equalPosition < lineEndPosition) - { - key = string(lineStart, equalPosition); - value = string(lineStart + equalPosition + 1, lineEndPosition - equalPosition - 1); - } - else - { - key = string(lineStart, lineEndPosition); - value = ""; - } - - key = StringHelpers::Trim(key); - - if (_stricmp(key.c_str(), a_propertyName) == 0) - { - a_value = StringHelpers::Trim(value); - return true; - } - - lineStart += lineEndPosition; - if (*lineStart) - { - ++lineStart; - } - } - - return false; -} - -void PropertyHelpers::SetPropertyValue(string& a_propertiesString, const char* a_propertyName, const char* a_value) -{ - if ((a_propertyName == 0) || (a_propertyName[0] == 0)) - { - return; - } - - const string newValue = StringHelpers::Trim(string(a_value)); - - const char* lineStart = a_propertiesString.c_str(); - - while (*lineStart) - { - const size_t lineEndPosition = strcspn(lineStart, "\n"); - const size_t equalPosition = strcspn(lineStart, "="); - - const string key = StringHelpers::Trim(string(lineStart, ((equalPosition < lineEndPosition) ? equalPosition : lineEndPosition))); - - if (_stricmp(key.c_str(), a_propertyName) == 0) - { - const size_t prefixSz = lineStart - a_propertiesString.c_str(); - const size_t expressionSz = lineEndPosition; - - if (newValue.empty()) - { - a_propertiesString = a_propertiesString.substr(0, prefixSz) + string(a_propertyName) + a_propertiesString.substr(prefixSz + expressionSz, string::npos); - } - else - { - a_propertiesString = a_propertiesString.substr(0, prefixSz) + string(a_propertyName) + string("=") + newValue + a_propertiesString.substr(prefixSz + expressionSz, string::npos); - } - return; - } - - lineStart += lineEndPosition; - if (*lineStart) - { - ++lineStart; - } - } - - if (a_propertiesString.empty() || (a_propertiesString[a_propertiesString.size() - 1] != '\n')) - { - a_propertiesString += string("\r\n"); - } - - if (newValue.empty()) - { - a_propertiesString += string(a_propertyName); - } - else - { - a_propertiesString += string(a_propertyName) + string("=") + newValue; - } -} - -bool PropertyHelpers::HasProperty(const string& a_propertiesString, const char* a_propertyName) -{ - string value; - return PropertyHelpers::GetPropertyValue(a_propertiesString, a_propertyName, value); -} diff --git a/Code/Tools/CryCommonTools/PropertyHelpers.h b/Code/Tools/CryCommonTools/PropertyHelpers.h deleted file mode 100644 index 0a2f428cc8..0000000000 --- a/Code/Tools/CryCommonTools/PropertyHelpers.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H -#pragma once - - -namespace PropertyHelpers -{ - bool GetPropertyValue(const string& propertiesString, const char* propertyName, string& value); - void SetPropertyValue(string& a_propertiesString, const char* propertyName, const char* value); - bool HasProperty(const string& propertiesString, const char* propertyName); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H - - diff --git a/Code/Tools/CryCommonTools/STLHelpers.cpp b/Code/Tools/CryCommonTools/STLHelpers.cpp deleted file mode 100644 index c1b65f25b2..0000000000 --- a/Code/Tools/CryCommonTools/STLHelpers.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/Code/Tools/CryCommonTools/STLHelpers.h b/Code/Tools/CryCommonTools/STLHelpers.h deleted file mode 100644 index 6fbf0c7d11..0000000000 --- a/Code/Tools/CryCommonTools/STLHelpers.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H -#pragma once - - -#include - -namespace STLHelpers -{ - template - inline const char* constchar_cast(const Type& type) - { - return type; - } - - template <> - inline const char* constchar_cast(const std::string& type) - { - return type.c_str(); - } - - template - struct less_strcmp - { - bool operator()(const Type& left, const Type& right) const - { - return strcmp(constchar_cast(left), constchar_cast(right)) < 0; - } - }; - - template - struct less_stricmp - { - bool operator()(const Type& left, const Type& right) const - { - return _stricmp(constchar_cast(left), constchar_cast(right)) < 0; - } - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H diff --git a/Code/Tools/CryCommonTools/SimpleBitmap.h b/Code/Tools/CryCommonTools/SimpleBitmap.h deleted file mode 100644 index ce4e93c626..0000000000 --- a/Code/Tools/CryCommonTools/SimpleBitmap.h +++ /dev/null @@ -1,508 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H - -#include -#include // STL vector -#include "platform.h" // uint32 -#include "Cry_Math.h" // uint32 -#include "Util.h" // getMin() - -enum EImageFilteringMode -{ - eifm2DBorder = 0, - eifmCubemapFilter = 1, -}; - -namespace -{ - enum ECubeFace - { - ecfPosX = 0, - ecfNegX = 1, - ecfPosY = 2, - ecfNegY = 3, - ecfPosZ = 4, - ecfNegZ = 5, - ecfUnknown = -1, - }; - - struct JumpEntry - { - ECubeFace face; - int rot; - }; - - static const JumpEntry XJmpTable[] = - { - {ecfNegZ, 0}, {ecfPosZ, 2}, // ecfPosXa - {ecfPosZ, 0}, {ecfNegZ, 2}, // ecfNegXa - {ecfPosX, 1}, {ecfNegX, 3}, // ecfPosYa - {ecfPosX, 3}, {ecfNegX, 1}, // ecfNegYa - {ecfPosX, 0}, {ecfNegX, 0}, // ecfPosZa - {ecfPosX, 2}, {ecfNegX, 2} // ecfNegZa - }; - - static const JumpEntry YJmpTable[] = - { - {ecfPosY, 3}, {ecfNegY, 1}, // ecfPosXa - {ecfPosY, 1}, {ecfNegY, 3}, // ecfNegXa - {ecfNegZ, 2}, {ecfPosZ, 0}, // ecfPosYa - {ecfPosZ, 0}, {ecfNegZ, 2}, // ecfNegYa - {ecfNegY, 0}, {ecfPosY, 2}, // ecfPosZa - {ecfNegY, 2}, {ecfPosY, 0} // ecfNegZa - }; -} - -//! memory block used as bitmap -//! if you might need mipmaps please consider using ImageObject instead -template -class CSimpleBitmap -{ -public: - - CSimpleBitmap() - : m_dwWidth(0) - , m_dwHeight(0) - { - } - - ~CSimpleBitmap() - { - } - - // copy constructor - CSimpleBitmap(const CSimpleBitmap& rhs) - : m_dwWidth(0) - , m_dwHeight(0) - { - *this = rhs; // call assignment operator - } - - // assignment operator - CSimpleBitmap& operator=(const CSimpleBitmap& rhs) - { - if (&rhs != this) - { - m_data = rhs.m_data; - m_dwWidth = rhs.m_dwWidth; - m_dwHeight = rhs.m_dwHeight; - } - return *this; - } - - //! free all the memory resources - void FreeData() - { - m_data = std::vector(); - m_dwWidth = 0; - m_dwHeight = 0; - } - - //! /return true=success, false=failed because of low memory - bool SetSize(const uint32 indwWidth, const uint32 indwHeight) - { - if (m_dwWidth * m_dwHeight != indwWidth * indwHeight) - { - FreeData(); - m_data.resize(indwWidth * indwHeight); - m_dwWidth = indwWidth; - m_dwHeight = indwHeight; - } - return true; - } - -private: - ECubeFace JumpX(const ECubeFace srcFace, const bool isdXPos, int* rotCoords) const - { - int index = (int)srcFace * 2 + (isdXPos ? 0 : 1); - assert(index < sizeof(XJmpTable)); - const JumpEntry& jmp = XJmpTable[index]; - (*rotCoords) += jmp.rot; - return jmp.face; - } - - ECubeFace JumpY(const ECubeFace srcFace, const bool isdYPos, int* rotCoords) const - { - int index = (int)srcFace * 2 + (isdYPos ? 0 : 1); - assert(index < sizeof(YJmpTable)); - const JumpEntry& jmp = YJmpTable[index]; - (*rotCoords) += jmp.rot; - return jmp.face; - } - - // table that shows to which face we jump - ECubeFace JumpTable(const ECubeFace srcFace, int isdXPos, int isdYPos, int* rotCoords) const - { - if (isdXPos != 0) // recursive jump until dx==0 - { - int newSwap = 0; - ECubeFace newFace = JumpX(srcFace, isdXPos > 0, &newSwap); - (*rotCoords) += newSwap; - isdXPos -= ((isdXPos > 0) ? 1 : -1); - RotateCoord(&isdXPos, &isdYPos, newSwap); - return JumpTable(newFace, isdXPos, isdYPos, rotCoords); - } - if (isdYPos != 0) // recursive jump until dy==0 - { - int newSwap = 0; - ECubeFace newFace = JumpY(srcFace, isdYPos > 0, &newSwap); - (*rotCoords) += newSwap; - isdYPos -= ((isdYPos > 0) ? 1 : -1); - RotateCoord(&isdXPos, &isdYPos, newSwap); - return JumpTable(newFace, isdXPos, isdYPos, rotCoords); - } - assert(isdXPos == 0 && isdYPos == 0); - return srcFace; - } - - void RotateCoord(int* x, int* y, int mode) const - { - if (mode != 0) - { - if (mode == 2) // 180 degrees - { - (*x) = -(*x); - (*y) = -(*y); - } - else - { - if (mode == 1) // 90 dergees - { - int tmp = (*y); - (*y) = (*x); - (*x) = -tmp; - } - else // 270 degrees - { - assert(mode == 3); - int tmp = (*y); - (*y) = -(*x); - (*x) = tmp; - } - } - } - } - -public: - //! works only within the Bitmap for filter kernels - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param outValue - //! /return pointer to the raster element value if position was in the bitmap, NULL otherwise - const RasterElement* GetForFiltering_2D(const int inX, const int inY) const - { - return Get(inX, inY); - } - - //! works only within the Bitmap for filter kernels - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param outValue - //! /return pointer to the raster element value if position was in the bitmap, NULL otherwise - const RasterElement* GetForFiltering_Cubemap(const int inX, const int inY, const int srcX, const int srcY) const - { - if (m_data.empty()) - { - return false; - } - - assert(m_dwWidth == m_dwHeight * 6); - assert(srcX >= 0 && srcX < m_dwWidth); - assert(srcY >= 0 && srcY < m_dwHeight); - - const int sideSize = m_dwHeight; - - ECubeFace srcFace = (ECubeFace)(srcX / sideSize); - - if (inX >= 0 && inX < m_dwWidth && inY >= 0 && inY < m_dwHeight) // if we're inside the cubemap - { - ECubeFace destFace = (ECubeFace)(inX / sideSize); - if (destFace == srcFace) // we have the same face as src texel - { - return &m_data[inY * m_dwWidth + inX]; - } - } - const int halfSideSize = Util::getMax(1, sideSize / 2); - - // ternary logic - const int isdXPositive = int(floorf((float)inX / sideSize) - floorf((float)srcX / sideSize)); - const int isdYPositive = int(floorf((float)inY / sideSize) - floorf((float)srcY / sideSize)); - //if(isdXPositive==0&&isdYPositive<0&&srcFace==ecfPosY) - //{ - // int tmp = 0; - //} - assert(isdXPositive != 0 || isdYPositive != 0); - int rotCoords = 0; // quadrants to rotate coords - ECubeFace destFace = JumpTable(srcFace, isdXPositive, isdYPositive, &rotCoords); - rotCoords = ((rotCoords % 4) + 4) % 4; - int destX = inX - srcFace * sideSize; - int destY = inY; - - // rotate coords - destX -= halfSideSize; // center coords - destY -= halfSideSize; - RotateCoord(&destX, &destY, rotCoords); - destX += halfSideSize; // shift back - destY += halfSideSize; - - destX = ((destX + sideSize) % sideSize + sideSize) % sideSize; // tile in the face - destY = ((destY + sideSize) % sideSize + sideSize) % sideSize; - - destX = Util::getMin(destX, sideSize - 1); - destY = Util::getMin(destY, sideSize - 1); - destX += sideSize * destFace; - - assert(destX < m_dwWidth); - assert((ECubeFace)(destX / sideSize) == destFace); - - return &m_data[destY * m_dwWidth + destX]; - } - - const RasterElement* GetForFiltering(const Vec3& inDir) const - { - Vec3 vcAbsDir(fabsf(inDir.x), fabsf(inDir.y), fabsf(inDir.z)); - ECubeFace face; - int rotQuadrant = 0; - Vec2 texCoord; - if (vcAbsDir.x > vcAbsDir.y && vcAbsDir.x > vcAbsDir.z) - { - if (inDir.x > 0) - { - rotQuadrant = 3; - face = ecfPosX; - } - else - { - rotQuadrant = 1; - face = ecfNegX; - } - texCoord = Vec2(inDir.y, inDir.z) / vcAbsDir.x; - } - else if (vcAbsDir.y > vcAbsDir.x && vcAbsDir.y > vcAbsDir.z) - { - if (inDir.y > 0) - { - rotQuadrant = 2; - face = ecfPosY; - } - else - { - rotQuadrant = 0; - face = ecfNegY; - } - texCoord = Vec2(inDir.x, inDir.z) / vcAbsDir.y; - } - else - { - assert(vcAbsDir.z >= vcAbsDir.x && vcAbsDir.z >= vcAbsDir.y); - if (inDir.z > 0) - { - rotQuadrant = 1; - face = ecfPosZ; - } - else - { - rotQuadrant = 3; - face = ecfNegZ; - } - texCoord = Vec2(inDir.x, inDir.y) / vcAbsDir.z; - } - - texCoord = texCoord * .5f + Vec2(.5f, .5f); - assert(texCoord.x <= 1.f && texCoord.x >= 0); - assert(texCoord.y <= 1.f && texCoord.y >= 0); - - Vec2i texelPos(texCoord.x * (m_dwHeight - 1), texCoord.y * (m_dwHeight - 1)); - - texelPos.x += face * m_dwHeight; // plus face - return &m_data[texelPos.y * m_dwWidth + texelPos.x]; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param outValue - //! /return pointer to raster element value if position was in the bitmap, NULL otherwise - const RasterElement* Get(const uint32 inX, const uint32 inY) const - { - if (m_data.empty()) - { - return 0; - } - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return 0; - } - return &m_data[inY * m_dwWidth + inX]; - } - - - //! bilinear, works only well within 0..1 - bool GetFiltered(const float infX, const float infY, RasterElement& outValue) const - { - float fIX = floorf(infX), fIY = floorf(infY); - float fFX = infX - fIX, fFY = infY - fIY; - int iXa = (int)fIX, iYa = (int)fIY; - int iXb = iXa + 1, iYb = iYa + 1; - - if (iXb == m_dwWidth) - { - iXb = 0; - } - - if (iYb == m_dwHeight) - { - iYb = 0; - } - - const RasterElement* p[4]; - - if ((p[0] = Get(iXa, iYa)) && (p[1] = Get(iXb, iYa)) && (p[2] = Get(iXa, iYb)) && (p[3] = Get(iXb, iYb))) - { - outValue = - (*p[0]) * ((1.0f - fFX) * (1.0f - fFY)) + // left top - (*p[1]) * ((fFX) * (1.0f - fFY)) + // right top - (*p[2]) * ((1.0f - fFX) * (fFY)) + // left bottom - (*p[3]) * ((fFX) * (fFY)); // right bottom - - return true; - } - - return false; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - const RasterElement& GetRef(const uint32 inX, const uint32 inY) const - { - assert(!m_data.empty()); - assert(inX < m_dwWidth && inY < m_dwHeight); - return m_data[inY * m_dwWidth + inX]; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - RasterElement& GetRef(const uint32 inX, const uint32 inY) - { - assert(!m_data.empty()); - assert(inX < m_dwWidth && inY < m_dwHeight); - return m_data[inY * m_dwWidth + inX]; - } - - //! works even outside of the Bitmap (tiled) - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - RasterElement& GetTiledRef(const uint32 inX, const uint32 inY) - { - assert(!m_data.empty()); - const uint32 x = inX % m_dwWidth; - const uint32 y = inY % m_dwHeight; - return m_data[y * m_dwWidth + x]; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param inValue - bool Set(const uint32 inX, const uint32 inY, const RasterElement& inValue) - { - if (m_data.empty()) - { - assert(!m_data.empty()); - return false; - } - - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return false; - } - - m_data[inY * m_dwWidth + inX] = inValue; - - return true; - } - - uint32 GetWidth() const - { - return m_dwWidth; - } - - uint32 GetHeight() const - { - return m_dwHeight; - } - - // Returns size of one line in bytes - size_t GetPitch() const - { - return m_dwWidth * sizeof(RasterElement); - } - - uint32 GetBitmapSizeInBytes() const - { - return m_dwWidth * m_dwHeight * sizeof(RasterElement); - } - - //! /return could be 0 if the pixel is outside the bitmap - const RasterElement* GetPointer(const uint32 inX = 0, const uint32 inY = 0) const - { - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return 0; - } - return &m_data[inY * m_dwWidth + inX]; - } - - //! /return could be 0 if the pixel is outside the bitmap - RasterElement* GetPointer(const uint32 inX = 0, const uint32 inY = 0) - { - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return 0; - } - return &m_data[inY * m_dwWidth + inX]; - } - - void Fill(const RasterElement& inValue) - { - const uint32 n = m_dwHeight * m_dwWidth; - for (uint32 i = 0; i < n; ++i) - { - m_data[i] = inValue; - } - } - - bool IsValid() const - { - return !m_data.empty(); - } - -protected: // ------------------------------------------------------ - - std::vector m_data; //!< [m_dwWidth * m_dwHeight] - - uint32 m_dwWidth; - uint32 m_dwHeight; -}; - - - - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H diff --git a/Code/Tools/CryCommonTools/SimpleStringPool.h b/Code/Tools/CryCommonTools/SimpleStringPool.h deleted file mode 100644 index 4e65ce1be6..0000000000 --- a/Code/Tools/CryCommonTools/SimpleStringPool.h +++ /dev/null @@ -1,249 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H -#pragma once - -#include - -///////////////////////////////////////////////////////////////////// -// String pool implementation. -// Inspired by expat implementation. -///////////////////////////////////////////////////////////////////// -class CSimpleStringPool -{ -public: - enum - { - STD_BLOCK_SIZE = 4096 - }; - struct BLOCK - { - BLOCK* next; - int size; - char s[1]; - }; - unsigned int m_blockSize; - BLOCK* m_blocks; - BLOCK* m_free_blocks; - const char* m_end; - char* m_ptr; - char* m_start; - int nUsedSpace; - int nUsedBlocks; - - CSimpleStringPool() - { - m_blockSize = STD_BLOCK_SIZE; - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - nUsedBlocks = 0; - m_free_blocks = 0; - } - ~CSimpleStringPool() - { - BLOCK* pBlock = m_blocks; - while (pBlock) - { - BLOCK* temp = pBlock->next; - //nFree++; - free(pBlock); - pBlock = temp; - } - pBlock = m_free_blocks; - while (pBlock) - { - BLOCK* temp = pBlock->next; - //nFree++; - free(pBlock); - pBlock = temp; - } - m_blocks = 0; - m_ptr = 0; - m_start = 0; - m_end = 0; - } - void SetBlockSize(unsigned int nBlockSize) - { - if (nBlockSize > 1024 * 1024) - { - nBlockSize = 1024 * 1024; - } - unsigned int size = 512; - while (size < nBlockSize) - { - size *= 2; - } - - m_blockSize = size - offsetof(BLOCK, s); - } - void Clear() - { - if (m_free_blocks) - { - BLOCK* pLast = m_blocks; - while (pLast) - { - BLOCK* temp = pLast->next; - if (!temp) - { - break; - } - pLast = temp; - } - if (pLast) - { - pLast->next = m_free_blocks; - } - } - m_free_blocks = m_blocks; - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - } - char* Append(const char* ptr, int nStrLen) - { - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = (std::max)(nStrLen + 1, (int)m_blockSize); - AllocBlock(nNewBlockSize, nStrLen + 1); - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } - char* ReplaceString(const char* str1, const char* str2) - { - int nStrLen1 = check_cast(strlen(str1)); - int nStrLen2 = check_cast(strlen(str2)); - - // undo ptr1 add. - if (m_ptr != m_start) - { - m_ptr = m_ptr - nStrLen1 - 1; - } - - assert(m_ptr == str1); - - int nStrLen = nStrLen1 + nStrLen2; - - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = (std::max)(nStrLen + 1, check_cast(m_blockSize)); - if (m_ptr == m_start) - { - ReallocBlock(nNewBlockSize * 2); // Reallocate current block. - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - else - { - AllocBlock(nNewBlockSize, nStrLen + 1); - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } -private: - void AllocBlock(int blockSize, int nMinBlockSize) - { - if (m_free_blocks) - { - BLOCK* pBlock = m_free_blocks; - BLOCK* pPrev = 0; - while (pBlock) - { - if (pBlock->size >= nMinBlockSize) - { - // Reuse free block - if (pPrev) - { - pPrev->next = pBlock->next; - } - else - { - m_free_blocks = pBlock->next; - } - - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + pBlock->size; - return; - } - pPrev = pBlock; - pBlock = pBlock->next; - } - } - size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char); - //nMallocs++; - BLOCK* pBlock = (BLOCK*)malloc(nMallocSize); - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - nUsedBlocks++; - } - void ReallocBlock(int blockSize) - { - BLOCK* pThisBlock = m_blocks; - BLOCK* pPrevBlock = m_blocks->next; - m_blocks = pPrevBlock; - - size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char); - - //nMallocs++; - BLOCK* pBlock = (BLOCK*)realloc(pThisBlock, nMallocSize); - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - } -}; - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H diff --git a/Code/Tools/CryCommonTools/StealingThreadPool.cpp b/Code/Tools/CryCommonTools/StealingThreadPool.cpp deleted file mode 100644 index e4a6f87243..0000000000 --- a/Code/Tools/CryCommonTools/StealingThreadPool.cpp +++ /dev/null @@ -1,580 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "StealingThreadPool.h" -#include "ThreadUtils.h" -#include -#include -#include - -namespace ThreadUtils { - class StealingWorker - { - public: - StealingWorker(StealingThreadPool* pool, int index, bool trace, AZStd::condition_variable& jobsCV) - : m_pool(pool) - , m_index(index) - , m_tracingEnabled(trace) - , m_lastStartTime(0) - , m_exitFlag(0) - , m_jobsCV(jobsCV) - { - } - - static unsigned int __stdcall ThreadFunc(void* param) - { - StealingWorker* self = (StealingWorker*)(param); - self->Work(); - return 0; - } - - void Start(int startTime) - { - m_lastStartTime = startTime; - - string threadName; - threadName.Format("StealingWorker %d", m_index); - - AZStd::thread_desc threadDesc; - threadDesc.m_name = threadName.c_str(); - m_thread = AZStd::thread(AZStd::bind(StealingWorker::ThreadFunc, (void*)this), &threadDesc); - - } - - bool GetJobLockless(Job& job) - { - if (m_jobs.empty()) - { - return false; - } - job = m_jobs.front(); - m_jobs.pop_front(); - - return true; - } - - bool GetJob(Job& job) - { - AZStd::lock_guard lock(m_lockJobs); - return GetJobLockless(job); - } - - void ExecuteJob(Job& job) - { - --m_pool->m_numJobsWaitingForExecution; - job.Run(); - - if (m_tracingEnabled) - { - int time = (int)GetTickCount(); - - JobTrace trace; - trace.m_job = job; - trace.m_duration = time - m_lastStartTime; - m_traces.push_back(trace); - - m_lastStartTime = time; - } - - --m_pool->m_numJobs; - m_pool->m_jobFinishedCV.notify_all(); - } - - bool TryToStealJob(Job& job) - { - while (true) - { - StealingWorker* victim = m_pool->FindBestVictim(m_index); - if (!victim) - { - return false; - } - if (StealJobs(job, victim)) - { - return true; - } - } - } - - void Work() - { - Job job; - - while (true) - { - AZStd::mutex loadMutex; - AZStd::unique_lock loadLock(loadMutex, AZStd::defer_lock_t()); - - while (m_pool->m_numJobsWaitingForExecution == 0) - { - - m_jobsCV.wait(loadLock); - - if (m_exitFlag == 1) - { - return; - } - } - - if (GetJob(job)) - { - ExecuteJob(job); - } - else if (TryToStealJob(job)) - { - ExecuteJob(job); - } - } - } - - // Called from different worker thread - bool StealJobs(Job& job, StealingWorker* victim) - { - if (victim == this) - { - assert(0 && "Trying to steal own jobs"); - return false; - } - - bool order = m_index < victim->m_index; - AZStd::lock_guard lock1(order ? m_lockJobs : victim->m_lockJobs); - AZStd::lock_guard lock2(order ? victim->m_lockJobs : m_lockJobs); - - if (victim->m_jobs.empty()) - { - return false; - } - - int numJobs = (int)victim->m_jobs.size(); - size_t stealUntil = numJobs - numJobs / 2; - Jobs::iterator begin = victim->m_jobs.begin(); - Jobs::iterator end = victim->m_jobs.begin() + stealUntil; - - m_jobs.insert(m_jobs.end(), begin, end); - victim->m_jobs.erase(begin, end); - - return GetJobLockless(job); - } - - // Called from any thread - void Submit(const Job& job) - { - AZStd::lock_guard lock(m_lockJobs); - - m_jobs.push_back(job); - m_jobs.back().m_debugInitialThread = m_index; - - m_jobsCV.notify_one(); - } - - // Called from any thread - void Submit(const Jobs& jobs) - { - const size_t numJobs = jobs.size(); - - AZStd::lock_guard lock(m_lockJobs); - - m_jobs.insert(m_jobs.begin(), jobs.begin(), jobs.end()); - for (size_t i = 0; i < numJobs; ++i) - { - m_jobs[i].m_debugInitialThread = m_index; - } - - m_jobsCV.notify_one(); - } - - long NumJobsPending() const - { - AZStd::lock_guard lock(m_lockJobs); - return m_jobs.size(); - } - - // Called from main thread - void SignalExit() - { - CryInterlockedCompareExchange(&m_exitFlag, 1, 0); - } - - void GetTraces(JobTraces& traces) - { - if (m_tracingEnabled) - { - m_traces.swap(traces); - } - } - - private: - StealingThreadPool* m_pool; - AZStd::thread m_thread; - int m_index; - bool m_tracingEnabled; - int m_lastStartTime; - JobTraces m_traces; - - Jobs m_jobs; - mutable AZStd::mutex m_lockJobs; - AZStd::condition_variable& m_jobsCV; - - LONG m_exitFlag; - friend class StealingThreadPool; - }; - - // --------------------------------------------------------------------------- - - StealingThreadPool::StealingThreadPool(int numThreads, bool enableTracing) - : m_numThreads(numThreads) - , m_numJobs(0) - , m_numJobsWaitingForExecution(0) - , m_enableTracing(enableTracing) - { - m_workers.resize(numThreads); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i] = new StealingWorker(this, i, m_enableTracing, m_jobsCV); - } - } - - StealingThreadPool::~StealingThreadPool() - { - WaitAllJobs(); - - size_t numThreads = m_workers.size(); - for (size_t i = 0; i < numThreads; ++i) - { - m_workers[i]->SignalExit(); - } - m_jobsCV.notify_all(); - - m_threadTraces.resize(numThreads); - for (size_t i = 0; i < numThreads; ++i) - { - m_workers[i]->GetTraces(m_threadTraces[i]); - } - } - - void StealingThreadPool::Start() - { - int startTime = (int)GetTickCount(); - size_t numThreads = m_workers.size(); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i]->Start(startTime); - } - } - - void StealingThreadPool::WaitAllJobs() - { - AZStd::mutex loadMutex; - AZStd::unique_lock loadLock(loadMutex, AZStd::defer_lock_t()); - - while (m_numJobs > 0) - { - m_jobsCV.wait(loadLock); - } - } - - // Called from any thread - void StealingThreadPool::Submit(const Job& job) - { - ++m_numJobs; - ++m_numJobsWaitingForExecution; - - if (StealingWorker* worker = FindWorstWorker()) - { - worker->Submit(job); - } - } - - // Called from any thread - void StealingThreadPool::Submit(const Jobs& jobs) - { - m_numJobs += jobs.size(); - m_numJobsWaitingForExecution += jobs.size(); - if (StealingWorker* worker = FindWorstWorker()) - { - worker->Submit(jobs); - } - } - - JobGroup* StealingThreadPool::CreateJobGroup(JobFunc func, void* data) - { - return new JobGroup(this, func, data); - } - - StealingWorker* StealingThreadPool::FindBestVictim(int exceptFor) const - { - int maxJobs = 0; - StealingWorker* bestVictim = 0; - for (size_t i = 0; i < m_workers.size(); ++i) - { - if (i == exceptFor) - { - continue; - } - StealingWorker* worker = m_workers[i]; - long numJobs = worker->NumJobsPending(); - if (numJobs > maxJobs) - { - maxJobs = numJobs; - bestVictim = worker; - } - } - return bestVictim; - } - - StealingWorker* StealingThreadPool::FindWorstWorker() const - { - if (m_workers.empty()) - { - return 0; - } - - int minJobs = INT_MAX; - StealingWorker* worstWorker = m_workers[0]; - for (size_t i = 0; i < m_workers.size(); ++i) - { - StealingWorker* worker = m_workers[i]; - long numJobs = worker->NumJobsPending(); - if (numJobs < minJobs) - { - minJobs = numJobs; - worstWorker = worker; - } - } - return worstWorker; - } - - static bool WriteString(FILE* f, const char* str) - { - return fwrite(str, strlen(str), 1, f) == 1; - } - - static int Interpolate(int a, int b, float phase) - { - return int(float(a) + float(b - a) * phase); - } - - static int InterpolateColor(int c1, int c2, float phase) - { - const int r1 = (c1 & 0x0000ff); - const int g1 = (c1 & 0x00ff00) >> 8; - const int b1 = (c1 & 0xff0000) >> 16; - const int r2 = (c2 & 0x0000ff); - const int g2 = (c2 & 0x00ff00) >> 8; - const int b2 = (c2 & 0xff0000) >> 16; - - const int r = min(255, max(0, Interpolate(r1, r2, phase))); - const int g = min(255, max(0, Interpolate(g1, g2, phase))); - const int b = min(255, max(0, Interpolate(b1, b2, phase))); - - return r + (g << 8) + (b << 16); - } - - static const int g_animColors[] = { - 0xff0000, 0x0000ff, 0x00ff00, - 0xffff00, 0xff00ff, 0x00ffff, - 0xff8080, 0x8080ff, 0x80ff80, - 0xffff80, 0xff80ff, 0x80ffff - }; - - static int ColorizeJobTrace(const ThreadUtils::JobTrace& trace) - { - const int numColors = sizeof(g_animColors) / sizeof(g_animColors[0]); - const int initialThread = trace.m_job.m_debugInitialThread; - const int index = initialThread % numColors; - const float brightness = aznumeric_cast(pow(0.5f, initialThread / numColors)); - return InterpolateColor(0, InterpolateColor(g_animColors[index], 0xffffff, 0.5f), brightness); - } - - bool StealingThreadPool::SaveTracesGraph(const char* filename) - { - if (!m_enableTracing) - { - return false; - } - - const float screenWidth = 1240.0f; - - float duration = 0; - for (size_t t = 0; t < m_threadTraces.size(); ++t) - { - float threadDuration = 0; - const JobTraces& traces = m_threadTraces[t]; - for (int i = 0; i < traces.size(); ++i) - { - threadDuration += traces[i].m_duration; - } - duration = max(threadDuration, duration); - } - - const float padding = 10.0f; - const float rowHeight = 60.0f; - const float xScale = fabsf(duration) > FLT_EPSILON ? (screenWidth - padding * 2.0f) / duration : 1.0f; - - const float width = screenWidth; - const float height = (m_threadTraces.size() + 0.5f) * rowHeight; - - FILE* f = nullptr; - azfopen(&f, filename, "wt"); - if (!f) - { - return false; - } - - char buf[4096]; - azsnprintf(buf, sizeof(buf), - "\n" - "\n", - width, height - ); - - if (!WriteString(f, buf)) - { - return false; - } - - for (size_t t = 0; t < m_threadTraces.size(); ++t) - { - float x = padding; - float y = rowHeight * 0.5f + rowHeight * t; - - azsnprintf(buf, sizeof(buf), - " Thread %i\n", - x, y, x, y, static_cast(t + 1)); - - if (!WriteString(f, buf)) - { - return false; - } - - - y += padding; - - const ThreadUtils::JobTraces& traces = m_threadTraces[t]; - for (int i = 0; i < traces.size(); ++i) - { - const float width2 = traces[i].m_duration * xScale; - const float height2 = rowHeight * 0.5f; - - const int color = ColorizeJobTrace(traces[i]); - const int strokeColor = 0; - azsnprintf(buf, sizeof(buf), - " \n", - color, strokeColor, width2, height2, x, y); - - if (!WriteString(f, buf)) - { - return false; - } - - x += width2; - } - - y += rowHeight; - } - - if (!WriteString(f, "\n\n")) - { - return false; - } - - fclose(f); - return true; - } - - // --------------------------------------------------------------------------- - - void JobGroup::Process(JobGroup::GroupInfo* info) - { - info->m_job.Run(); - - long jobsLeft = --info->m_group->m_numJobsRunning; - assert(jobsLeft >= 0); - if (jobsLeft == 0) - { - info->m_group->m_finishJob.Run(); - delete info->m_group; - } - } - - JobGroup::JobGroup(StealingThreadPool* pool, JobFunc func, void* data) - : m_pool(pool) - , m_numJobsRunning(0) - , m_finishJob(func, data) - , m_submited(false) - { - } - - void JobGroup::Submit() - { - if (m_submited) - { - assert(0); - return; - } - - if (m_numJobsRunning == 0) - { - m_pool->Submit(m_finishJob); - return; - } - - Jobs jobs; - jobs.resize(m_infos.size()); - for (size_t i = 0; i < m_infos.size(); ++i) - { - jobs[i] = Job((JobFunc) & JobGroup::Process, &m_infos[i]); - } - - m_pool->Submit(jobs); - } - - void JobGroup::Add(JobFunc func, void* data) - { - if (m_submited) - { - assert(0); - return; - } - - GroupInfo info; - info.m_job = Job(func, data); - info.m_group = this; - - m_infos.push_back(info); - ++m_numJobsRunning; - } -} diff --git a/Code/Tools/CryCommonTools/StealingThreadPool.h b/Code/Tools/CryCommonTools/StealingThreadPool.h deleted file mode 100644 index 8576ed0416..0000000000 --- a/Code/Tools/CryCommonTools/StealingThreadPool.h +++ /dev/null @@ -1,123 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H -#pragma once - - -#include "ThreadUtils.h" -#include -#include -#include -#include -#if AZ_TRAIT_OS_PLATFORM_APPLE -#include "AppleSpecific.h" -#endif - -namespace ThreadUtils { - class StealingWorker; - class JobGroup; - - // Simple stealing thread pool - class StealingThreadPool - { - public: - explicit StealingThreadPool(int numThreads, bool enableTracing = false); - ~StealingThreadPool(); - - void Start(); - void WaitAllJobs(); - - const std::vector& Traces() const{ return m_threadTraces; } - bool SaveTracesGraph(const char* filename); - - // Submits single independent job - template - void Submit(void(* jobFunc)(T*), T* data) - { - Submit(Job((JobFunc)jobFunc, data)); - } - - // Create a group of jobs. A group of jobs can be followed by one "finishing" job. - // It is a way to express dependencies between jobs. - template - JobGroup* CreateJobGroup(void(* jobFunc)(T*), T* data) - { - return CreateJobGroup((JobFunc)jobFunc, (void*)data); - } - - uint GetNumThreads() const { return aznumeric_cast(m_numThreads); } - - private: - StealingWorker* FindBestVictim(int exceptFor) const; - StealingWorker* FindWorstWorker() const; - - void Submit(const Job& job); - void Submit(const Jobs& jobs); - JobGroup* CreateJobGroup(JobFunc, void* data); - - size_t m_numThreads; - typedef std::vector ThreadWorkers; - ThreadWorkers m_workers; - - bool m_enableTracing; - std::vector m_threadTraces; - - AZStd::atomic_long m_numJobsWaitingForExecution; - AZStd::atomic_long m_numJobs; - AZStd::condition_variable m_jobsCV; - AZStd::condition_variable m_jobFinishedCV; - - - friend class JobGroup; - friend class StealingWorker; - }; - - - // JobGroup represents a group of jobs that can be followed by one "finishing" - // job. This is a way to express dependencies between jobs. - class JobGroup - { - public: - template - void Add(void(* jobFunc)(T*), T* data) - { - Add((JobFunc)jobFunc, data); - } - - // Submits group to thread pool - void Submit(); - private: - struct GroupInfo - { - Job m_job; - JobGroup* m_group; - }; - typedef std::vector GroupInfos; - - JobGroup(StealingThreadPool* pool, JobFunc func, void* data); - - static void Process(JobGroup::GroupInfo* job); - void Add(JobFunc func, void* data); - - volatile LONG m_numJobsRunning; - StealingThreadPool* m_pool; - GroupInfos m_infos; - Job m_finishJob; - bool m_submited; - friend class StealingThreadPool; - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H diff --git a/Code/Tools/CryCommonTools/SuffixUtil.h b/Code/Tools/CryCommonTools/SuffixUtil.h deleted file mode 100644 index 632e86525f..0000000000 --- a/Code/Tools/CryCommonTools/SuffixUtil.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_SUFFIXUTIL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SUFFIXUTIL_H -#pragma once - - -// convenience class to work with suffixes in filenames, like in like dirt_ddn.dds -class SuffixUtil -{ -public: - - // filename allowed to have many suffixes (e.g. "test_ddn_bump.dds" has "bump" and "ddn" - // as suffixes (assuming that suffixSeparator is '_'). - // suffixes in file extension are also considered (e.g. "test_abc.my_data" has "abc" and "data" as suffixes) - // suffixes in path part are also considered. if it's not what you want - remove path before calling this function. - // comparison is case insensitive - static bool HasSuffix(const char* const filename, const char suffixSeparator, const char* const suffix) - { - assert(filename); - assert(suffix && suffix[0]); - - const size_t suffixLen = strlen(suffix); - - for (const char* p = filename; *p; ++p) - { - if (p[0] != suffixSeparator) - { - continue; - } - - if (azmemicmp(&p[1], suffix, suffixLen) != 0) - { - continue; - } - - const char c = p[1 + suffixLen]; - if ((c == 0) || (c == suffixSeparator) || (c == '.')) - { - return true; - } - } - - return false; - } -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SUFFIXUTIL_H diff --git a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp b/Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp deleted file mode 100644 index 3ee26df3bd..0000000000 --- a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp +++ /dev/null @@ -1,442 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include -#include // assert() -#include // floorf() -#include "SummedAreaFilterKernel.h" // CSummedAreaFilterKernel - -CSummedAreaFilterKernel::CSummedAreaFilterKernel() -{ - m_eFilterType = eEmpty; - m_fCorrectionFactor = 0.0f; -} - -// http://www.sixsigma.de/english/sixsigma/6s_e_gauss.htm -bool CSummedAreaFilterKernel::CreateFromGauss(const unsigned long indwSize) -{ - assert(indwSize > 2); - - int iInit = 0; - - if (!Alloc(indwSize, indwSize, &iInit)) - { - return false; - } - - for (unsigned long y = 0; y < indwSize; y++) - { - for (unsigned long x = 0; x < indwSize; x++) - { - float fX = (float)(x) - (float)(indwSize) * 0.5f; - float fY = (float)(y) - (float)(indwSize) * 0.5f; - - double r1 = sqrt(fX * fX + fY * fY) / (indwSize * 0.5 - 2.0); - - if (r1 > 1) - { - m_pData[y * indwSize + x] = 0; - } - else - { - double fSigma = 1.0 / 3.0; // we aim for 6*sigma = 99,99996 of all values - - double fWeight = exp(-r1 * r1 / (2 * fSigma * fSigma)); - - fWeight -= (1.0 - 0.9999996); - - m_pData[y * indwSize + x] = (int)(255.0f * fWeight); - } - } - } - - m_eFilterType = eGaussBlur; - _SumUpTableAndNormalize(); - return true; -} - - -// create summed area table -void CSummedAreaFilterKernel::_SumUpTableAndNormalize() -{ - for (unsigned long y = 0; y < m_dwHeight; y++) - { - int iFromLeft = 0; - - for (unsigned long x = 0; x < m_dwWidth; x++) - { - iFromLeft += m_pData[y * m_dwWidth + x]; - - if (y != 0) - { - m_pData[y * m_dwWidth + x] = iFromLeft + m_pData[(y - 1) * m_dwWidth + x]; - } - else - { - m_pData[y * m_dwWidth + x] = iFromLeft; - } - } - } - - m_fCorrectionFactor = 1.0f / ((float)m_pData[m_dwHeight * m_dwWidth - 1]); -} - - -// windows size 16x16 = radius 8 -bool CSummedAreaFilterKernel::CreateFromSincCalc(const unsigned long indwSize) -{ - assert(indwSize > 2); - - int iInit = 0; - - if (!Alloc(indwSize, indwSize, &iInit)) - { - return false; - } - - for (unsigned long y = 0; y < indwSize; y++) - { - for (unsigned long x = 0; x < indwSize; x++) - { - float fX = (float)(x - indwSize * 0.5f); - float fY = (float)(y - indwSize * 0.5f); - - float r1 = sqrtf(fX * fX + fY * fY) / (indwSize * 0.5f - 2.0f); - - if (r1 > 1.0f) - { - m_pData[y * indwSize + x] = 0; - } - else - { - r1 *= 3.1415926535897932384626433832795f; - - float r2 = r1 * 8.0f; - - // http://home.no.net/dmaurer/~dersch/interpolator/interpolator.html - // weight = [ sin(x*pi) / (x*pi) ] * [ sin(x*pi / 8) / (x*pi/8) ] - - // http://www.binbooks.com/books/photo/i/l/57186AF8DE - // sinc(x) = sin(pi * x) / (pi * x) - // L8interp(x) = sinc(x) * sinc(x/8) if abs(x) <= 8 - // = 0 if abs(x) > 8 - - float fWeight = (sinf(r1) * sinf(r2)) / (r1 * r2); - - m_pData[y * indwSize + x] = (int)(255.0f * fWeight); - } - } - } - - m_eFilterType = eSinc; - _SumUpTableAndNormalize(); - - return true; -} - - - - - -bool CSummedAreaFilterKernel::CreateFromRAWFile(const char* filename, const unsigned long indwSize, const int iniMidValue) -{ - assert(iniMidValue >= 0 && iniMidValue < 255); - - int iInit = 0; - - if (!Alloc(indwSize, indwSize, &iInit)) - { - return false; - } - - FILE* in = fopen(filename, "rb"); - if (!in) - { - return false; - } - - for (unsigned long y = 0; y < m_dwHeight; y++) - { - for (unsigned long x = 0; x < m_dwWidth; x++) - { - unsigned char val; - - if (fread(&val, 1, 1, in) != 1) - { - fclose(in); - return false; - } - - m_pData[y * m_dwWidth + x] = (int)val - iniMidValue; - } - } - - fclose(in); - - m_eFilterType = eRAW; - _SumUpTableAndNormalize(); - - return true; -} - - -std::string CSummedAreaFilterKernel::GetInfoString(void) const -{ - std::string sRet = "FilterKernel("; - - switch (m_eFilterType) - { - case eEmpty: - sRet += "Empty"; - break; - case eSinc: - sRet += "Sinc16x16"; - break; - case eRAW: - sRet += "RAW"; - break; - case eGaussBlur: - sRet += "GaussBlur"; - break; - case eGaussSharp: - sRet += "GaussSharp"; - break; - default: - assert(0); - } - - sRet += ")"; - - return(sRet); -} - -float CSummedAreaFilterKernel::GetAreaNonAA(float infAx, float infAy, float infDx, float infDy) const -{ - assert(m_eFilterType != eEmpty); - - int ax = (int)floorf(infAx * 127.5f + 127.5f); - int ay = (int)floorf(infAy * 127.5f + 127.5f); - int dx = (int)floorf(infDx * 127.5f + 127.5f); - int dy = (int)floorf(infDy * 127.5f + 127.5f); - - if (ax < 0) - { - ax = 0; - } - else if (ax > 255) - { - ax = 255; - } - if (dx < 0) - { - dx = 0; - } - else if (dx > 255) - { - dx = 255; - } - if (ay < 0) - { - ay = 0; - } - else if (ay > 255) - { - ay = 255; - } - if (dy < 0) - { - dy = 0; - } - else if (dy > 255) - { - dy = 255; - } - - unsigned long area = m_pData[dy * m_dwWidth + dx] - m_pData[dy * m_dwWidth + ax] - m_pData[ay * m_dwWidth + dx] + m_pData[ay * m_dwWidth + ax]; - - return(m_fCorrectionFactor * (float)area); -} - - - -// optimizable -float CSummedAreaFilterKernel::GetAreaAA(float infAx, float infAy, float infDx, float infDy) const -{ - assert(m_eFilterType != eEmpty); - - infAx = infAx * 127.5f + 127.5f; - infAy = infAy * 127.5f + 127.5f; - infDx = infDx * 127.5f + 127.5f; - infDy = infDy * 127.5f + 127.5f; - - float fSum = _GetBilinearFiltered(infDx, infDy) - - _GetBilinearFiltered(infAx, infDy) - - _GetBilinearFiltered(infDx, infAy) - + _GetBilinearFiltered(infAx, infAy); - - return(fSum * m_fCorrectionFactor); -} - - -float CSummedAreaFilterKernel::_GetBilinearFiltered(const float infX, const float infY) const -{ - float fIX = floorf(infX), fIY = floorf(infY); - float fFX = infX - fIX, fFY = infY - fIY; - int iX = (int)fIX, iY = (int)fIY; - - if (iX < 0) - { - iX = 0; - } - else if (iX > 254) - { - iX = 254; - } - if (iY < 0) - { - iY = 0; - } - else if (iY > 254) - { - iY = 254; - } - - float fArea = m_pData[ iY * m_dwWidth + iX ] * ((1.0f - fFX) * (1.0f - fFY)) // left top - + m_pData[ iY * m_dwWidth + iX + 1 ] * ((fFX) * (1.0f - fFY)) // right top - + m_pData[(iY + 1) * m_dwWidth + iX ] * ((1.0f - fFX) * (fFY)) // left bottom - + m_pData[ iY * m_dwWidth + iX + 257] * ((fFX) * (fFY)); // right bottom - - return(fArea); -} - - - -bool CSummedAreaFilterKernel::CreateWeightFilter(CSimpleBitmap& outFilter, const float infX, const float infY, - const float infWeight, const float infR) const -{ - assert(infX >= 0.0f); - assert(infX < 1.0f); - assert(infY >= 0.0f); - assert(infY < 1.0f); - assert(infWeight >= 0.0f); - assert(infR > 0.0f); - - float fLeftTop = ceilf(infR); - int iSide = 2 * (int)fLeftTop + 1; - - float fInit = 0.0f; - - if (!outFilter.Alloc(iSide, iSide, &fInit)) - { - return false; - } - - AddWeights(outFilter, infX + fLeftTop, infY + fLeftTop, infWeight, infR); - - return true; -} - - -bool CSummedAreaFilterKernel::CreateWeightFilterBlock(CSimpleBitmap& outFilter, const unsigned long indwSideLength, - const float infR) const -{ - assert(indwSideLength >= 0); - assert(infR > 0.0f); - - float fLeftTop = ceilf(infR); - int iSide = 2 * (int)fLeftTop + 1; - - float fInit = 0.0f; - - if (!outFilter.Alloc(iSide, iSide, &fInit)) - { - return false; - } - - float fStep = 1.0f / (float)indwSideLength; - float fHalf = fStep * 0.5f; - - float fWeight = fStep * fStep; - - for (float y = fHalf; y < 1.0f; y += fStep) - { - for (float x = fHalf; x < 1.0f; x += fStep) - { - AddWeights(outFilter, x + fLeftTop, y + fLeftTop, fWeight, infR); - } - } - - // check -#ifdef _DEBUG - float fSum = 0.0f; - for (int y = 0; y < iSide; y++) - { - for (int x = 0; x < iSide; x++) - { - float f; - - outFilter.Get(x, y, f); - fSum += f; - } - } - assert(fSum >= 0.98f); - assert(fSum <= 1.02f); -#endif - - return true; -} - - -void CSummedAreaFilterKernel::AddWeights(CSimpleBitmap& inoutFilter, const float infX, const float infY, - const float infWeight, const float infR) const -{ - assert(infWeight >= 0.0f); - assert(infR > 0.0f); - - if (infWeight <= 0.0f) - { - return; - } - - float fInvR = 1.0f / infR; - float sx = floorf(infX - infR); - float sy = floorf(infY - infR); - - int iax = (int)sx; - int iay = (int)sy; - int iex = (int)ceilf(infX + infR); - int iey = (int)ceilf(infY + infR); - - float x, y; - int ix, iy; - - for (iy = iay, y = (sy - infY) * fInvR; iy <= iey; iy++, y += fInvR) - { - for (ix = iax, x = (sx - infX) * fInvR; ix <= iex; ix++, x += fInvR) - { - float fArea = GetAreaAA(x, y, x + fInvR, y + fInvR); // better quality - // float fArea=m_Filter.GetAreaNonAA(x,y,x+fInvR,y+fInvR); // faster - - // assert(fArea<=1.0f); // may be wrong if we use sharpening filter - - float fOldVal; - - inoutFilter.Get(ix, iy, fOldVal); - inoutFilter.Set(ix, iy, fOldVal + fArea * infWeight); - } - } -} - - - diff --git a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.h b/Code/Tools/CryCommonTools/SummedAreaFilterKernel.h deleted file mode 100644 index 55af94f12c..0000000000 --- a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H - -#include // STL string -#include "SimpleBitmap.h" // SimpleBitmap<> - -// squared of any size (summed area tables limit the size and/or values) -// normalized(sum=1) - -// optimized for high quality, not speed -// for faster filter kernels extract the neccessary size and use this 1:1 - -// based on summed area tables - -class CSummedAreaFilterKernel - : public CSimpleBitmap -{ -public: - - //! constructor init is eEmpty - CSummedAreaFilterKernel(); - - //! load 8 bit photoshop 256x256 raw image - slow - //! typical filtersize for a gaussian filter kernel is 1.44 - //! /param iniMidValue [0..255[ this enables sharpening - sharpening may expand the result range - bool CreateFromRAWFile(const char* filename, const unsigned long indwSize = 256, const int iniMidValue = 0); - - //! sharpest possible result - filter diameter size has to be 16*pixelsize (256 samples per pixel) - //! theory: http://home.no.net/dmaurer/~dersch/interpolator/interpolator.html - //! /param indwSize >2 - bool CreateFromSincCalc(const unsigned long indwSize = 256); - - //! shttp://www.sixsigma.de/english/sixsigma/6s_e_gauss.htm - //! /param indwSize >2 - bool CreateFromGauss(const unsigned long indwSize = 256); - - //! optimizable O(k*1) with high k - //! bokeh is in the range ([-1..1],[-1..1]) - //! return normalized result - float GetAreaAA(float infAx, float infAy, float infDx, float infDy) const; - - //! O(k*1) with low k - //! bokeh is in the range ([-1..1],[-1..1]) - //! return normalized result - float GetAreaNonAA(float infAx, float infAy, float infDx, float infDy) const; - - //! - //! /return e.g. "FilterKernel(Sinc16x16)" - std::string GetInfoString(void) const; - - //! /param infX [0..1[ - //! /param infY [0..1[ - //! /param infWeight [0..[ - //! /param infR >0, radius - bool CreateWeightFilter(CSimpleBitmap& outFilter, const float infX, const float infY, - const float infWeight, const float infR) const; - - //! weight for the whole block is 1.0 - //! /param indwSideLength [1,..[ e.g. 3 for 3x3 block - //! /param infR >0, radius - bool CreateWeightFilterBlock(CSimpleBitmap& outFilter, const unsigned long indwSideLength, const float infR) const; - - //! with user filter kernel - //! /param infX - //! /param infY - //! /param infWeight [0..[ - //! /param infR >0, radius - void AddWeights(CSimpleBitmap& inoutFilter, const float infX, const float infY, - const float infWeight, const float infR) const; - -private: // -------------------------------------------------------------------- - - enum EFilterState - { - eEmpty, //!< after calling constructor - eSinc, //!< from CreateFromSincCalc - eRAW, //!< from CreateFromRAWFile - eGaussBlur, //!< from CreateFromGauss - eDisc, //!< not implemented - eGaussSharp //!< not implemented - }; - - EFilterState m_eFilterType; //!< for error checks and GetInfoString() - float m_fCorrectionFactor; //!< to get the normalized (whole kernel has sum of 1) result - - //! optimizable - //! bokeh is in the range ([0..255],[0..255]) - //! /param infX - //! /param infY - //! /return not normalized result - float _GetBilinearFiltered(const float infX, const float infY) const; - - //! sum the stored values in the bitmap together - //! calculate m_fCorrectionFactor - void _SumUpTableAndNormalize(void); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H diff --git a/Code/Tools/CryCommonTools/TempFilePakExtraction.cpp b/Code/Tools/CryCommonTools/TempFilePakExtraction.cpp deleted file mode 100644 index 52aa6896d6..0000000000 --- a/Code/Tools/CryCommonTools/TempFilePakExtraction.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Opens a temporary file for read only access, where the file could be -// located in a zip or pak file. Note that if the file specified -// already exists it does not delete it when finished. - - -#include "TempFilePakExtraction.h" -#include "FileUtil.h" -#include "PathHelpers.h" -#include "IPakSystem.h" - - -TempFilePakExtraction::TempFilePakExtraction(const char* filename, const char* tempPath, IPakSystem* pPakSystem) - : m_strOriginalFileName(filename) - , m_strTempFileName(filename) -{ - if (!pPakSystem || !tempPath) - { - return; - } - - { - FILE* fileOnDisk = nullptr; - azfopen(&fileOnDisk, m_strOriginalFileName.c_str(), "rb"); - if (fileOnDisk) - { - fclose(fileOnDisk); - return; - } - } - - // Choose the name for the temporary file. - string tempFullFileName; - { - uint32 tempNumber = 0; - { - LARGE_INTEGER performanceCount; - if (QueryPerformanceCounter(&performanceCount)) - { - tempNumber = performanceCount.u.LowPart; - } - } - - string tempName; - { - // CryEngine's pak system supports filenames in format "@pakFilename|fileInPak", - // so let's handle such cases by using fileInPak part of the filename. - const size_t pos = m_strOriginalFileName.find_last_of('|'); - if (pos != string::npos) - { - tempName = m_strOriginalFileName.substr(pos + 1, string::npos); - if (tempName.empty()) - { - tempName = "BadFilenameSyntax"; - } - } - else - { - tempName = m_strOriginalFileName; - } - tempName = PathHelpers::GetFilename(tempName); - } - - int tryCount = 2000; - while (--tryCount >= 0) - { - tempFullFileName.Format("%sRC%04x_%s", tempPath, (tempNumber & 0xFFFF), tempName.c_str()); - - if (!FileUtil::FileExists(tempFullFileName.c_str())) - { - FILE* f = nullptr; - azfopen(&f, tempFullFileName.c_str(), "wb"); - if (f) - { - fclose(f); - break; - } - } - - tempFullFileName.clear(); - ++tempNumber; - } - - if (tempFullFileName.empty()) - { - return; - } - } - - if (pPakSystem->ExtractNoOverwrite(m_strOriginalFileName.c_str(), tempFullFileName.c_str())) - { - m_strTempFileName = tempFullFileName; - AZ::IO::SystemFile::SetWritable(m_strTempFileName.c_str(), false); - } - else - { - AZ::IO::LocalFileIO().Remove(tempFullFileName.c_str()); - } -} - - -TempFilePakExtraction::~TempFilePakExtraction() -{ - if (HasTempFile()) - { -#if defined(AZ_PLATFORM_WINDOWS) - SetFileAttributesA(m_strTempFileName.c_str(), FILE_ATTRIBUTE_ARCHIVE); -#endif - AZ::IO::LocalFileIO().Remove(m_strTempFileName.c_str()); - } -} - - -bool TempFilePakExtraction::HasTempFile() const -{ - return (m_strOriginalFileName != m_strTempFileName); -} diff --git a/Code/Tools/CryCommonTools/TempFilePakExtraction.h b/Code/Tools/CryCommonTools/TempFilePakExtraction.h deleted file mode 100644 index c0fbb44b8a..0000000000 --- a/Code/Tools/CryCommonTools/TempFilePakExtraction.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Opens a temporary file for read only access, where the file could be -// located in a zip or pak file. Note that if the file specified -// already exists it does not delete it when finished. - - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H -#define CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H -#pragma once - -#include - -struct IPakSystem; - -class TempFilePakExtraction -{ -public: - TempFilePakExtraction(const char* filename, const char* tempPath, IPakSystem* pPakSystem); - ~TempFilePakExtraction(); - - const string& GetTempName() const - { - return m_strTempFileName; - } - - const string& GetOriginalName() const - { - return m_strOriginalFileName; - } - - bool HasTempFile() const; - -private: - string m_strTempFileName; - string m_strOriginalFileName; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H diff --git a/Code/Tools/CryCommonTools/ThreadUtils.cpp b/Code/Tools/CryCommonTools/ThreadUtils.cpp deleted file mode 100644 index b3dfcd6117..0000000000 --- a/Code/Tools/CryCommonTools/ThreadUtils.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include "ThreadUtils.h" -#include -#include -#include -#include - -namespace ThreadUtils -{ - class SimpleWorker - { - public: - SimpleWorker(SimpleThreadPool* pool, int index, bool trace) - : m_pool(pool) - , m_index(index) - , m_trace(trace) - { - } - - void Start(int startTime) - { - m_lastStartTime = startTime; - m_handle = AZStd::thread(AZStd::bind(SimpleWorker::ThreadFunc, (void*)this)); - } - - static unsigned int __stdcall ThreadFunc(void* param) - { - SimpleWorker* self = (SimpleWorker*)(param); - self->Work(); - return 0; - } - - void ExecuteJob(Job& job) - { - job.Run(); - if (m_trace) - { - int time = (int)GetTickCount(); - - JobTrace trace; - trace.m_job = job; - trace.m_duration = time - m_lastStartTime; - m_traces.push_back(trace); - - m_lastStartTime = time; - } - } - - void Work() - { - Job job; - for (;; ) - { - if (m_pool->GetJob(job, m_index)) - { - ExecuteJob(job); - } - else - { - return; - } - } - } - - // Called from main thread - void Join(JobTraces& traces) - { - if(m_handle.joinable()) - { - m_handle.join(); - } - - if (m_trace) - { - m_traces.swap(traces); - } - } - - private: - SimpleThreadPool* m_pool; - AZStd::thread m_handle; - int m_index; - bool m_trace; - int m_lastStartTime; - JobTraces m_traces; - friend SimpleThreadPool; - }; - - // --------------------------------------------------------------------------- - - SimpleThreadPool::SimpleThreadPool(bool trace) - : m_trace(trace) - , m_started(false) - , m_numProcessedJobs(0) - { - } - - SimpleThreadPool::~SimpleThreadPool() - { - WaitAllJobs(); - } - - void SimpleThreadPool::Start(int numThreads) - { - m_workers.resize(numThreads); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i] = new SimpleWorker(this, i, m_trace); - } - - m_started = true; - - int startTime = (int)GetTickCount(); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i]->Start(startTime); - } - } - - - void SimpleThreadPool::WaitAllJobs() - { - size_t numThreads = m_workers.size(); - m_threadTraces.resize(numThreads); - for (size_t i = 0; i < numThreads; ++i) - { - m_workers[i]->Join(m_threadTraces[i]); - } - - for (size_t i = 0; i < numThreads; ++i) - { - delete m_workers[i]; - } - m_workers.clear(); - - m_started = false; - } - - void SimpleThreadPool::Submit(const Job& job) - { - assert(!m_started); - m_jobs.push_back(job); - } - - bool SimpleThreadPool::GetJob(Job& job, [[maybe_unused]] int threadIndex) - { - AZStd::lock_guard lock(m_lockJobs); - - if (m_numProcessedJobs >= m_jobs.size()) - { - return false; - } - - job = m_jobs[m_numProcessedJobs]; - ++m_numProcessedJobs; - return true; - } -} diff --git a/Code/Tools/CryCommonTools/ThreadUtils.h b/Code/Tools/CryCommonTools/ThreadUtils.h deleted file mode 100644 index ac60a8420e..0000000000 --- a/Code/Tools/CryCommonTools/ThreadUtils.h +++ /dev/null @@ -1,288 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_THREADUTILS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_THREADUTILS_H -#pragma once - -#include - -#if defined(AZ_PLATFORM_WINDOWS) -#define WIN32_LEAN_AND_MEAN -#include // CRITICAL_SECTION -#endif - -#include -#include - -namespace ThreadUtils -{ -#if defined(AZ_PLATFORM_WINDOWS) - class CriticalSection - { - friend class ConditionVariable; - - public: - CriticalSection() - { - memset(&m_cs, 0, sizeof(m_cs)); - InitializeCriticalSection(&m_cs); - } - - ~CriticalSection() - { - DeleteCriticalSection(&m_cs); - } - - void Lock() - { - EnterCriticalSection(&m_cs); - } - void Unlock() - { - LeaveCriticalSection(&m_cs); - } - bool TryLock() - { - return TryEnterCriticalSection(&m_cs) != FALSE; - } - -#if defined(AZ_DEBUG_BUILD) - bool IsLocked() - { - return m_cs.RecursionCount > 0 && m_cs.OwningThread == GetCurrentThread(); - } -#endif - - private: - // You are not allowed to copy or move a CRITICAL_SECTION - // handle, so make this class non-copyable - CriticalSection(const CriticalSection& cs); - CriticalSection& operator=(const CriticalSection& cs); - - CRITICAL_SECTION m_cs; - }; - - class ConditionVariable - { - public: - ConditionVariable() - { - InitializeConditionVariable(&m_cv); - } - - void Wake() - { - WakeConditionVariable(&m_cv); - } - - void WakeAll() - { - WakeAllConditionVariable(&m_cv); - } - - void Sleep(CriticalSection& cs, DWORD milliseconds = INFINITE) - { - SleepConditionVariableCS(&m_cv, &cs.m_cs, milliseconds); - } - - private: - // You are not allowed to copy or move a CONDITION_VARIABLE - // handle, so make this class non-copyable - ConditionVariable(const ConditionVariable& cs); - ConditionVariable& operator=(const ConditionVariable& cs); - - CONDITION_VARIABLE m_cv; - }; -#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) - class CriticalSection - { - public: - CriticalSection() - : m_locked(false) - { - } - - ~CriticalSection() - { - } - - void Lock() - { - m_cs.lock(); - m_locked = true; - } - void Unlock() - { - m_cs.unlock(); - m_locked = false; - } - bool TryLock() - { - m_locked = m_cs.try_lock(); - return m_locked; - } - -#if defined (AZ_DEBUG_BUILD) - bool IsLocked() - { - return m_locked; - } -#endif - - private: - // You are not allowed to copy or move a CRITICAL_SECTION - // handle, so make this class non-copyable - CriticalSection(const CriticalSection& cs); - CriticalSection& operator=(const CriticalSection& cs); - - bool m_locked; - AZStd::recursive_mutex m_cs; - }; -#endif - - class AutoLock - { - private: - CriticalSection& m_lock; - - AutoLock(); - AutoLock(const AutoLock&); - AutoLock& operator = (const AutoLock&); - - public: - AutoLock(CriticalSection& lock) - : m_lock(lock) - { - m_lock.Lock(); - } - ~AutoLock() - { - m_lock.Unlock(); - } - }; - - typedef void(* JobFunc)(void*); - - struct Job - { - JobFunc m_func; - void* m_data; - int m_debugInitialThread; - - Job() - : m_func(0) - , m_data(0) - , m_debugInitialThread(0) - { - } - - Job(JobFunc func, void* data) - : m_func(func) - , m_data(data) - , m_debugInitialThread(0) - { - } - - void Run() - { - m_func(m_data); - } - }; - typedef std::deque Jobs; - - struct JobTrace - { - Job m_job; - bool m_stolen; - int m_duration; - - JobTrace() - : m_duration(0) - , m_stolen(false) - { - } - }; - typedef std::vector JobTraces; - - class SimpleWorker; - - class SimpleThreadPool - { - public: - SimpleThreadPool(bool trace); - ~SimpleThreadPool(); - - bool GetJob(Job& job, int threadIndex); - - // Submits single independent job - template - void Submit(void(* jobFunc)(T*), T* data) - { - Submit(Job((JobFunc)jobFunc, data)); - } - - void Start(int numThreads); - void WaitAllJobs(); - - private: - void Submit(const Job& job); - - bool m_started; - bool m_trace; - - std::vector m_workers; - - std::vector m_threadTraces; - - int m_numProcessedJobs; - AZStd::mutex m_lockJobs; - std::vector m_jobs; - }; - -#if defined(AZ_PLATFORM_WINDOWS) -#pragma pack(push, 8) - struct ThreadNameInfo - { - DWORD dwType; // Must be 0x1000. - LPCSTR szName; // Pointer to name (in user addr space). - DWORD dwThreadID; // Thread ID (-1=caller thread). - DWORD dwFlags; // Reserved for future use, must be zero. - }; -#pragma pack(pop) - - // Usage: SetThreadName (-1, "MainThread"); - // From http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx - inline void SetThreadName([[maybe_unused]] DWORD dwThreadID, [[maybe_unused]] const char* threadName) - { -#ifdef _DEBUG - ThreadNameInfo info; - info.dwType = 0x1000; - info.szName = threadName; - info.dwThreadID = dwThreadID; - info.dwFlags = 0; - - __try - { - const DWORD exceptionCode = 0x406D1388; - RaiseException(exceptionCode, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - } -#endif - } -#endif -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_THREADUTILS_H diff --git a/Code/Tools/CryCommonTools/UI/log_icons.bmp b/Code/Tools/CryCommonTools/UI/log_icons.bmp deleted file mode 100644 index 4080bb98ea..0000000000 --- a/Code/Tools/CryCommonTools/UI/log_icons.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1fb280a5c873225c5f2b0518964c9b7947e81c6fdb4ec19374e02043a12dd295 -size 2358 diff --git a/Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp b/Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp deleted file mode 100644 index 0c44aabb86..0000000000 --- a/Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp +++ /dev/null @@ -1,807 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or 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 "PathHelpers.h" -#include -#include -#include - -namespace PathHelpersTest -{ - class CryCommonToolsPathHelpersTest - : public UnitTest::AllocatorsTestFixture - { - public: - void SetUp() override - { - UnitTest::AllocatorsTestFixture::SetUp(); - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - } - - void TearDown() - { - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - UnitTest::AllocatorsTestFixture::TearDown(); - } - }; - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_StringPathNoExtension_ReturnsEmptyString) - { - const char* filePath = "ext"; - string result = PathHelpers::FindExtension(filePath); - EXPECT_STREQ("", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_StringPath_ReturnsStringExtension) - { - const char* extension = "ext"; - const char* filePath = "foo.ext"; - string result = PathHelpers::FindExtension(filePath); - EXPECT_STREQ(extension, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_WStringPathNoExtension_ReturnsEmptyString) - { - const wchar_t filePath[] = L"ext"; - const wchar_t expectedResult[] = L""; - const wstring result = PathHelpers::FindExtension(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_WStringPath_ReturnsStringExtension) - { - const wchar_t extension[] = L"ext"; - const wchar_t filePath[] = L"foo.ext"; - const wstring result = PathHelpers::FindExtension(filePath); - EXPECT_TRUE(result == extension); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_EmptyStringPath_ReturnsEmptyString) - { - const char* filePath = ""; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringNoExtension_ReturnsStringNoExtension) - { - const char* filePath = "foo.ext"; - const char* newExtension = ""; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ("foo", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathWithDoubleBackSlash_ReturnsUnalteredString) - { - const char* filePath = "foo.ext\\"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathWithForwardSlash_ReturnsUnalteredString) - { - const char* filePath = "foo.ext/"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathWithColon_ReturnsUnalteredString) - { - const char* filePath = "foo.ext:"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathEndsWithPeriod_ReturnsUnalteredString) - { - const char* filePath = "foo.ext."; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringNewExtension_ReturnsStringWithNewExtension) - { - const char* filePath = "foo.ext"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ("foo.new", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_EmptyWStringPath_ReturnsEmptyWString) - { - const wchar_t filePath[] = L""; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringNoExtension_ReturnsWStringNoExtension) - { - const wchar_t filePath[] = L"foo.ext"; - const wchar_t newExtension[] = L""; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathWithDoubleBackSlash_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext\\"; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathWithForwardSlash_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext/"; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathWithColon_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext:"; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathEndsWithPeriod_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext."; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringNewExtension_ReturnsWStringWithNewExtension) - { - const wchar_t filePath[] = L"foo.ext"; - const wchar_t newExtension[] = L"new"; - const wchar_t expectedResult[] = L"foo.new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_StringPathNoExtension_ReturnsUnalteredString) - { - const char* filePath = "foo"; - string result = PathHelpers::RemoveExtension(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_StringPath_ReturnsStringWithoutExtension) - { - const char* filePath = "foo.bar"; - string result = PathHelpers::RemoveExtension(filePath); - EXPECT_STREQ("foo", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_WStringPathNoExtension_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo"; - wstring result = PathHelpers::RemoveExtension(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_WStringPath_ReturnsWStringWithoutExtension) - { - const wchar_t filePath[] = L"foo.bar"; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::RemoveExtension(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathWithColon_RemovesCharactersAfterColon) - { - const char* filePath = "foo:bar"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ("foo:", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathWithColonAsCharacterBeforeLastSeparator_RemovesCharactersAfterLastSeparator) - { - const char* filePath = "foo:/bar"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ("foo:/", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathWithLastSeparatorAsFirstCharacter_ReturnsStringColon) - { - const char* filePath = ":foo"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ(":", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathStartsWithForwardSlash_ReturnsFullString) - { - const char* filePath = "//foo"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathStartsWithDoubleBackSlash_ReturnsFullString) - { - const char* filePath = "\\\\foo"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ(filePath, result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPath_ReturnsOnlyStringPath) - { - const char* filePath = "foobar/"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ("foobar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathWithColon_RemovesCharactersAfterColon) - { - const wchar_t filePath[] = L"foo:bar"; - const wchar_t expectedResult[] = L"foo:"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathWithColonAsCharacterBeforeLastSeparator_RemovesCharactersAfterLastSeparator) - { - const wchar_t filePath[] = L"foo:/bar"; - const wchar_t expectedResult[] = L"foo:/"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathWithLastSeparatorAsFirstCharacter_ReturnsWStringColon) - { - const wchar_t filePath[] = L":foo"; - const wchar_t expectedResult[] = L":"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathStartsWithForwardSlash_ReturnsFullWString) - { - const wchar_t filePath[] = L"//foo"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathStartsWithDoubleBackSlash_ReturnsFullWString) - { - const wchar_t filePath[] = L"\\\\foo"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == filePath); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPath_ReturnsOnlyWStringPath) - { - const wchar_t filePath[] = L"foobar/"; - const wchar_t expectedResult[] = L"foobar"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_StringPathStartsWithForwardSlash_ReturnsEmptyString) - { - const char* filePath = "/:foobar"; - string result = PathHelpers::GetFilename(filePath); - EXPECT_STREQ("", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_StringPathStartsWithDoubleBackSlash_ReturnsEmptyString) - { - const char* filePath = "\\:foobar"; - string result = PathHelpers::GetFilename(filePath); - EXPECT_STREQ("", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_StringPath_ReturnsStringFilename) - { - const char* filePath = "/foo/foo/foobar"; - string result = PathHelpers::GetFilename(filePath); - EXPECT_STREQ("foobar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_WStringPathStartsWithForwardSlash_ReturnsEmptyWString) - { - const wchar_t filePath[] = L"/:foobar"; - const wchar_t expectedResult[] = L""; - wstring result = PathHelpers::GetFilename(filePath); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_WStringPathStartsWithDoubleBackSlash_ReturnsEmptyWString) - { - const wchar_t filePath[] = L"\\:foobar"; - const wchar_t expectedResult[] = L""; - wstring result = PathHelpers::GetFilename(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_WStringPath_ReturnsWStringFilename) - { - const wchar_t filePath[] = L"/foo/foo/foobar"; - const wchar_t expectedResult[] = L"foobar"; - wstring result = PathHelpers::GetFilename(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_EmptyPath_ReturnsEmptyString) - { - const char* filePath = ""; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPathEndsWithForwardSlash_ReturnsStringPath) - { - const char* filePath = "foo/"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPathEndsWithDoubleBackSlash_ReturnsStringPath) - { - const char* filePath = "foo\\"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPathEndsWithColon_ReturnsStringPath) - { - const char* filePath = "foo:"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPath_ReturnsStringWithDoubleBackSlashAdded) - { - const char* filePath = "foo"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ("foo\\", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_EmptyPath_ReturnsEmptyWString) - { - const wchar_t filePath[] = L""; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPathEndsWithForwardSlash_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo/"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPathEndsWithDoubleBackSlash_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo\\"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPathEndsWithColon_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo:"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPath_ReturnsWStringWithDoubleBackSlashAdded) - { - const wchar_t filePath[] = L"foo"; - const wchar_t expectedResult[] = L"foo\\"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_EmptyStringPath_ReturnsEmptyString) - { - const char* filePath = ""; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_StringPathEndsWithForwardSlash_ReturnsStringWithoutForwardSlash) - { - const char* filePath = "foo/"; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ("foo", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_StringPathEndsWithDoubleBackSlash_ReturnsStringWithoutDoubleBackSlash) - { - const char* filePath = "foo\\"; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ("foo", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_StringPath_ReturnsStringPath) - { - const char* filePath = "foo"; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_EmptyWStringPath_ReturnsEmptyWString) - { - const wchar_t filePath[] = L""; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_WStringPathEndsWithForwardSlash_ReturnsWStringWithoutForwardSlash) - { - const wchar_t filePath[] = L"foo/"; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_WStringPathEndsWithDoubleBackSlash_ReturnsWStringWithoutDoubleBackSlash) - { - const wchar_t filePath[] = L"foo\\"; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_WStringPath_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo"; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_StringPathLengthEqualOne_ReturnsStringPath) - { - const char* filePath = "f"; - string result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_StringPathWithDuplicateBackSlashes_ReturnsStringWithoutDoubleBackSlashes) - { - const char* filePath = "foo\\\\bar"; - string result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_StringPathWithDuplicateForwardSlashes_ReturnsStringWithoutForwardSlashes) - { - const char* filePath = "foo//bar"; - string result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_STREQ("foo/bar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_WStringPathLengthEqualOne_ReturnsWStringPath) - { - const wchar_t filePath[] = L"f"; - wstring result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_WStringPathWithDuplicateBackSlashes_ReturnsWStringWithoutDoubleBackSlashes) - { - const wchar_t filePath[] = L"foo\\\\bar"; - const wchar_t expectedResult[] = L"foo\\bar"; - wstring result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_WStringPathWithDuplicateForwardSlashes_ReturnsWStringWithoutForwardSlashes) - { - const wchar_t filePath[] = L"foo//bar"; - const wchar_t expectedResult[] = L"foo/bar"; - wstring result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptySecondStringPath_ReturnsFirstString) - { - const char* filePath1 = "foo"; - const char* filePath2 = ""; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ(filePath1, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptyFirstStringPath_ReturnsSecondString) - { - const char* filePath1 = ""; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ(filePath2, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_StringPath_ReturnsStringAppendedWithDoubleBackSlashDivider) - { - const char* filePath1 = "foo"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstStringPathEndsWithForwardSlash_ReturnsAppendedString) - { - const char* filePath1 = "foo/"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo/bar", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstStringPathEndsWithDoubleBackSlash_ReturnsAppendedString) - { - const char* filePath1 = "foo\\"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstStringPathEndsWithColon_ReturnsAppendedString) - { - const char* filePath1 = "foo:"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo:bar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptySecondWStringPath_ReturnsFirstWString) - { - const wchar_t filePath1[] = L"foo"; - const wchar_t filePath2[] = L""; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == filePath1); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptyFirstWStringPath_ReturnsSecondWString) - { - const wchar_t filePath1[] = L""; - const wchar_t filePath2[] = L"bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == filePath2); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_WStringPath_ReturnsWStringAppendedWithDoubleBackSlashDivider) - { - const wchar_t filePath1[] = L"foo"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo\\bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstWStringPathEndsWithForwardSlash_ReturnsAppendedWString) - { - const wchar_t filePath1[] = L"foo/"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo/bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstWStringPathEndsWithDoubleBackSlash_ReturnsAppendedWString) - { - const wchar_t filePath1[] = L"foo\\"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo\\bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstWStringPathEndsWithColon_ReturnsAppendedWString) - { - const wchar_t filePath1[] = L"foo:"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo:bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_EmptyStringPath_ReturnsTrue) - { - const char* filePath = ""; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPath_ReturnsTrue) - { - const char* filePath = "foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPathBeginsWithForwardSlash_ReturnsFalse) - { - const char* filePath = "/foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPathBeginsWithDoubleBackSlash_ReturnsFalse) - { - const char* filePath = "\\foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE (result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPathBeginsWithColon_ReturnsFalse) - { - const char* filePath = ":foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_EmptyWStringPath_ReturnsTrue) - { - const wchar_t filePath[] = L""; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPath_ReturnsTrue) - { - const wchar_t filePath[] = L"foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPathBeginsWithForwardSlash_ReturnsFalse) - { - const wchar_t filePath[] = L"/foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPathBeginsWithDoubleBackSlash_ReturnsFalse) - { - const wchar_t filePath[] = L"\\foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPathBeginsWithColon_ReturnsFalse) - { - const wchar_t filePath[] = L":foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToUnixPath_StringPath_ReturnsStringWithForwardSlashes) - { - const char* filePath = "foo\\foo\\foo"; - string result = PathHelpers::ToUnixPath(filePath); - EXPECT_STREQ("foo/foo/foo", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToUnixPath_WStringPath_ReturnsWStringWithForwardSlashes) - { - const wchar_t filePath[] = L"foo\\foo\\foo"; - const wchar_t expectedResult[] = L"foo/foo/foo"; - wstring result = PathHelpers::ToUnixPath(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToDosPath_StringPath_ReturnsStringWithDoubleBackSlashes) - { - const char* filePath = "foo/foo/foo"; - string result = PathHelpers::ToDosPath(filePath); - EXPECT_STREQ("foo\\foo\\foo", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToDosPath_WStringPath_ReturnsStringWithDoubleBackSlashes) - { - const wchar_t filePath[] = L"foo/foo/foo"; - const wchar_t expectedResult[] = L"foo\\foo\\foo"; - wstring result = PathHelpers::ToDosPath(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetAsciiPath_EmptyStringPath_ReturnsEmpty) - { - const char* filePath = ""; - string result = PathHelpers::GetAsciiPath(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetAsciiPath_StringPath_ReturnsStringWithoutForwardSlash) - { - const char* filePath = "foo/bar/"; - string result = PathHelpers::GetAsciiPath(filePath); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetAsciiPath_EmptyWStringPath_ReturnsEmpty) - { - const wchar_t filePath[] = L""; - string expectedResult = ""; - string result = PathHelpers::GetAsciiPath(filePath); - EXPECT_STREQ(expectedResult, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, CanonicalizePath_StringPathLengthLessThanThree_ReturnsStringWithoutForwardSlash) - { - const char* filePath = "./"; - string result = PathHelpers::CanonicalizePath(filePath); - EXPECT_STREQ(".", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, CanonicalizePath_StringPathStartsWithPeriodForwardSlash_ReturnsStringWithoutPeriodAndForwardSlash) - { - const char* filePath = "./foo"; - string result = PathHelpers::CanonicalizePath(filePath); - EXPECT_STREQ("foo", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, CanonicalizePath_StringPathStartsWithPeriodDoubleBackSlash_ReturnsStringWithoutPeriodAndDoubleBackSlash) - { - const char* filePath = ".\\foo"; - string result = PathHelpers::CanonicalizePath(filePath); - EXPECT_STREQ("foo", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS -} - -AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp b/Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp deleted file mode 100644 index 013f077528..0000000000 --- a/Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp +++ /dev/null @@ -1,1056 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or 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 "StringHelpers.h" -#include -#include -#include - -namespace StringHelpersTest -{ - class CryCommonToolsStringHelpersTest - : public UnitTest::AllocatorsTestFixture - { - public: - void SetUp() override - { - UnitTest::AllocatorsTestFixture::SetUp(); - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - } - - void TearDown() - { - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - UnitTest::AllocatorsTestFixture::TearDown(); - } - }; - - TEST_F(CryCommonToolsStringHelpersTest, Compare_TwoMatchingStrings_ReturnsZero) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondStringLonger_ReturnsGreaterThanZero) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstStringLonger_ReturnsLessThanZero) - { - const char* string1 = "foobar"; - const char* string2 = "foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstStringCapitalized_ReturnsGreaterThanZero) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondStringCapitalized_ReturnsLessThanZero) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_TwoMatchingWStrings_ReturnsZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondWStringLonger_ReturnsGreaterThanZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstWStringLonger_ReturnsLessThanZero) - { - const wchar_t string1[] = L"foobar"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstWStringCapitalized_ReturnsGreaterThanZero) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondWStringCapitalized_ReturnsLessThanZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_TwoMatchingStrings_ReturnsZero) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstStringCapitalized_ReturnsZero) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondStringCapitalized_ReturnsZero) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondStringLonger_ReturnsGreaterThanZero) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstStringLonger_ReturnsLessThanZero) - { - const char* string1 = "foobar"; - const char* string2 = "foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_TwoMatchingWStrings_ReturnsZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstWStringCapitalized_ReturnsZero) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondWStringCapitalized_ReturnsZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondWStringLonger_ReturnsGreaterThanZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstWStringLonger_ReturnsLessThanZero) - { - const wchar_t string1[] = L"foobar"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SameTwoStrings_ReturnsTrue) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SecondStringUpperCase_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_FirstStringUpperCase_ReturnsFalse) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_DifferentStrings_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SameTwoWStrings_ReturnsTrue) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SecondWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_FirstWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_DifferentWStrings_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SameTwoStrings_ReturnsTrue) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SecondStringUpperCase_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_FirstStringUpperCase_ReturnsFalse) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_DifferentStrings_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SameTwoWStrings_ReturnsTrue) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SecondWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_FirstWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_DifferentWStrings_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathsWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBAR"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobar"; - const char* pattern = "FOO"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathsWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_PatternWstringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"FOO"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathsWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBAR"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobar"; - const char* pattern = "FOO"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathsWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_PatternWStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"FOO"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBAR"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobar"; - const char* pattern = "BAR"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_PatternWStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathCapitalized_ReturnsTrue) - { - const char* string = "FOOBAR"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_PatternStringCapitalized_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "BAR"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_PatternWStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "barbar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobarfoo"; - const char* pattern = "bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobarfoo"; - const char* pattern = "BAR"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBARFOO"; - const char* pattern = "bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathNoMatchingPattern_ReturnsFalse) - { - const char* string = "foofoofoo"; - const char* pattern = "bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"barbar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_PatternWStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBARFOO"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foofoofoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "barbar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobarfoo"; - const char* pattern = "bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_PatternStringCapitalized_ReturnsTrue) - { - const char* string = "foobarfoo"; - const char* pattern = "BAR"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathCapitalized_ReturnsTrue) - { - const char* string = "FOOBARFOO"; - const char* pattern = "bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathNoMatchingPattern_ReturnsFalse) - { - const char* string = "foofoofoo"; - const char* pattern = "bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"barbar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathAndPattern2_ReturnsTrue) - { - const wchar_t string[] = L"foobfobaro"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_PatternWStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"FOOBARFOO"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foofoofoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringMatchingPattern_ReturnsTrue) - { - const char* string = "foo"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foo"; - const char* wildcard = "F*O"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringCapitalized_ReturnsFalse) - { - const char* string = "FOO"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const char* string = "foo"; - const char* wildcard = "f*r"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringNoMatchingPattern_ReturnsFalse) - { - const char* string = "foobar"; - const char* wildcard = "foo"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringMatchingPattern_ReturnsTrue) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WPatternStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"F*O"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOO"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*r"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t wildcard[] = L"foo"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringMatchingPattern_ReturnsTrue) - { - const char* string = "foo"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_PatternStringCapitalized_ReturnsTrue) - { - const char* string = "foo"; - const char* wildcard = "F*O"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringCapitalized_ReturnsTrue) - { - const char* string = "FOO"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const char* string = "foo"; - const char* wildcard = "f*r"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringNoMatchingPattern_ReturnsFalse) - { - const char* string = "foobar"; - const char* wildcard = "foo"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringMatchingPattern_ReturnsTrue) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_PatternWStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"F*O"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"FOO"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*r"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t wildcard[] = L"foo"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, TrimLeft_StringWithoutReturnOrTab_ReturnsString) - { - const char* stringInput = "foo"; - string result = StringHelpers::TrimLeft(stringInput); - EXPECT_STREQ(stringInput, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, TrimRight_StringWithoutReturnOrTab_ReturnsString) - { - const char* stringInput = "foo"; - string result = StringHelpers::TrimRight(stringInput); - EXPECT_STREQ(stringInput, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeLowerCase_UpperCaseString_ReturnsLowerCaseString) - { - const char* stringInput = "FOO"; - string result = StringHelpers::MakeLowerCase(stringInput); - EXPECT_STREQ("foo", result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeLowerCase_UpperCaseWString_ReturnsLowerCaseString) - { - const wchar_t stringInput[] = L"FOO"; - const wchar_t expectedString[] = L"foo"; - wstring result = StringHelpers::MakeLowerCase(stringInput); - EXPECT_TRUE(result == expectedString); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeUpperCase_LowerCaseString_ReturnsUpperCaseString) - { - const char* stringInput = "foo"; - string result = StringHelpers::MakeUpperCase(stringInput); - EXPECT_STREQ("FOO", result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeUpperCase_LowerCaseWString_ReturnsUpperCaseString) - { - const wchar_t stringInput[] = L"foo"; - const wchar_t expectedString[] = L"FOO"; - wstring result = StringHelpers::MakeUpperCase(stringInput); - EXPECT_TRUE(result == expectedString); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplace_ReturnsStringWithReplacedCharacters) - { - const char* stringInput = "foo"; - char oldChar = 'o'; - char newChar = 'i'; - string result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_STREQ("fii", result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplace_ReturnsWStringWithReplacedCharacters) - { - const wchar_t stringInput[] = L"foo"; - wchar_t oldChar = 'o'; - wchar_t newChar = 'i'; - const wchar_t expectedString[] = L"fii"; - wstring result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_TRUE(result == expectedString); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplaceNotInString_ReturnsOriginalString) - { - const char* stringInput = "foo"; - char oldChar = 'a'; - char newChar = 'i'; - string result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_STREQ(stringInput, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplaceNotInWString_ReturnsOriginalWString) - { - const wchar_t stringInput[] = L"foo"; - wchar_t oldChar = 'a'; - wchar_t newChar = 'i'; - wstring result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_TRUE(result == stringInput); - } -} diff --git a/Code/Tools/CryCommonTools/WeightFilterSet.cpp b/Code/Tools/CryCommonTools/WeightFilterSet.cpp deleted file mode 100644 index dfc5ff24d0..0000000000 --- a/Code/Tools/CryCommonTools/WeightFilterSet.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include // assert() -#include "WeightFilterSet.h" // CWeightFilterSet - - - -void CWeightFilterSet::FreeData() -{ - m_FilterKernelBlock.FreeData(); -} - - -bool CWeightFilterSet::Create(const unsigned long indwSideLength, const CSummedAreaFilterKernel& inFilter, const float infR) -{ - assert(indwSideLength >= 1); - - FreeData(); - - // 32 Baustelle - inFilter.CreateWeightFilterBlock(m_FilterKernelBlock, 1, infR * indwSideLength); - return(true); -} - diff --git a/Code/Tools/CryCommonTools/WeightFilterSet.h b/Code/Tools/CryCommonTools/WeightFilterSet.h deleted file mode 100644 index 16c8c79acd..0000000000 --- a/Code/Tools/CryCommonTools/WeightFilterSet.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_WEIGHTFILTERSET_H -#define CRYINCLUDE_CRYCOMMONTOOLS_WEIGHTFILTERSET_H - - -#include "SimpleBitmap.h" // SimpleBitmap<> -#include // STL vector<> -#include "SummedAreaFilterKernel.h" // CSummedAreaFilterKernel - -class CWeightFilterSet -{ -public: - - //! /param indwSideLength [1,..[ e.g. 3 for 3x3 block - bool Create(const unsigned long indwSideLength, const CSummedAreaFilterKernel& inFilter, const float infR); - - //! - void FreeData(); - - //! optimizable - //! weight is 1.0 - //! /param iniX x position in inoutDest - //! /param iniY y position in inoutDest - //! /param TInputImage typically CSimpleBitmap - //! /return weight - template - float GetBlockWithFilter(const TInputImage& inSrc, const int iniX, const int iniY, TElement& outResult) - { - float fWeightSum = 0.0f; - CSimpleBitmap& rBitmap = m_FilterKernelBlock; - - int W = (int)rBitmap.GetWidth(); - int H = (int)rBitmap.GetHeight(); - - int iSrcW = (int)inSrc.GetWidth(); - int iSrcH = (int)inSrc.GetHeight(); - - float* pfWeights = rBitmap.GetPointer(0, 0); - - for (int y = 0; y < H; y++) - { - int iDestY = y + iniY - H / 2; - - // optimizable (don't use the bottom border) - // if(iDestY==iSrcH){ pfWeights+=H;continue; } - - for (int x = 0; x < W; x++, pfWeights++) - { - int iDestX = x + iniX - W / 2; - - // optimizable (don't use the right border) - // if(iDestX==iSrcW) - // continue; - - TElement Value; - - // if(inSrc.Get(iDestX,iDestY,Value)) - if (inSrc.Get((iDestX + iSrcW * 2) % iSrcW, (iDestY + iSrcH * 2) % iSrcH, Value)) // tiled - { - float fWeight = *pfWeights; - - outResult += Value * fWeight; - fWeightSum += fWeight; - } - } - } - - return fWeightSum; - } - - int GetBorderSize() - { - int W = (int)m_FilterKernelBlock.GetWidth(); - - return (W - 1) / 2; - } - -private: // ------------------------------------------------------------- - - CSimpleBitmap m_FilterKernelBlock; //!< weight = 1 -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_WEIGHTFILTERSET_H diff --git a/Code/Tools/CryCommonTools/XMLPakFileSink.cpp b/Code/Tools/CryCommonTools/XMLPakFileSink.cpp deleted file mode 100644 index 9a9590687f..0000000000 --- a/Code/Tools/CryCommonTools/XMLPakFileSink.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include "XMLPakFileSink.h" -#include "StringHelpers.h" - -XMLPakFileSink::XMLPakFileSink(IPakSystem* pakSystem, const string& archivePath, const string& filePath) - : pakSystem(pakSystem) - , filePath(filePath) -{ - archive = pakSystem->OpenArchive(archivePath.c_str()); -} - -XMLPakFileSink::~XMLPakFileSink() -{ - if (archive && pakSystem) - { - SYSTEMTIME st; - GetSystemTime(&st); - - FILETIME ft; - ZeroStruct(ft); - const BOOL ok = SystemTimeToFileTime(&st, &ft); - - LARGE_INTEGER lt; - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - - const __int64 modTime = lt.QuadPart; - ; - - pakSystem->AddToArchive(archive, filePath.c_str(), &data[0], int(data.size()), modTime); - pakSystem->CloseArchive(archive); - } -} - -void XMLPakFileSink::Write(const char* text) -{ - string asciiText = text; - int len = int(asciiText.size()); - int start = int(data.size()); - data.resize(data.size() + len); - memcpy(&data[start], asciiText.c_str(), len); -} diff --git a/Code/Tools/CryCommonTools/XMLPakFileSink.h b/Code/Tools/CryCommonTools/XMLPakFileSink.h deleted file mode 100644 index 973f9a05ca..0000000000 --- a/Code/Tools/CryCommonTools/XMLPakFileSink.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_XMLPAKFILESINK_H -#define CRYINCLUDE_CRYCOMMONTOOLS_XMLPAKFILESINK_H -#pragma once - - -#include "XMLWriter.h" -#include "IPakSystem.h" - -class XMLPakFileSink - : public IXMLSink -{ -public: - XMLPakFileSink(IPakSystem* pakSystem, const string& archivePath, const string& filePath); - ~XMLPakFileSink(); - - // IXMLSink - virtual void Write(const char* text); - -private: - IPakSystem* pakSystem; - PakSystemArchive* archive; - string filePath; - std::vector data; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_XMLPAKFILESINK_H diff --git a/Code/Tools/CryCommonTools/XMLWriter.cpp b/Code/Tools/CryCommonTools/XMLWriter.cpp deleted file mode 100644 index bfaf9df429..0000000000 --- a/Code/Tools/CryCommonTools/XMLWriter.cpp +++ /dev/null @@ -1,261 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include "XMLWriter.h" -#include "StringHelpers.h" -#include - -XMLWriter::XMLWriter(IXMLSink* sink) -{ - m_indentationSize = -1; - m_sink = sink; - - WriteText("\n"); -} - -void XMLWriter::BeginElement(const string& name) -{ - // Write the indentation. - if (m_newLine) - { - for (int i = 0; i < m_indentationSize; ++i) - { - WriteText(" "); - } - } - - WriteText("<%s", name.c_str()); - m_newLine = false; -} - -void XMLWriter::EndElement(const string& name) -{ - // Write the indentation. - if (m_newLine) - { - for (int i = 0; i < m_indentationSize; ++i) - { - WriteText(" "); - } - } - - WriteText("\n", name.c_str()); - m_newLine = true; -} - -void XMLWriter::CloseElement(const string& name, bool newLine) -{ - if (newLine) - { - WriteText(">\n"); - } - else - { - WriteText(">"); - } - m_newLine = newLine; -} - -void XMLWriter::CloseLeafElement(const string& name) -{ - WriteText(" />\n"); - m_newLine = true; -} - -void XMLWriter::IncreaseIndentation() -{ - ++m_indentationSize; -} - -void XMLWriter::DecreaseIndentation() -{ - --m_indentationSize; -} - -void XMLWriter::WriteAttribute(const string& name, const string& value) -{ - WriteText(" %s=\"%s\"", name.c_str(), value.c_str()); -} - -void XMLWriter::SerializeAttribute(char* buffer, size_t bufferSize, const string& value) -{ - // TODO: Escape string. - strcpy_s(buffer, bufferSize, value.c_str()); -} - -void XMLWriter::SerializeAttribute(char* buffer, size_t bufferSize, float value) -{ - sprintf_s(buffer, bufferSize, "%.10e", value); -} - -void XMLWriter::SerializeAttribute(char* buffer, size_t bufferSize, int value) -{ - sprintf_s(buffer, bufferSize, "%d", value); -} - -void XMLWriter::SerializeArrayElement(char* buffer, size_t bufferSize, float value) -{ - sprintf_s(buffer, bufferSize, "%.10e", value); -} - -void XMLWriter::SerializeArrayElement(char* buffer, size_t bufferSize, const string& value) -{ - strcpy(buffer, value.c_str()); -} - -void XMLWriter::SerializeArrayElement(char* buffer, size_t bufferSize, int value) -{ - sprintf_s(buffer, bufferSize, "%d", value); -} - -void XMLWriter::WriteContent(const string& text) -{ - WriteText("%s", text.c_str()); -} - -void XMLWriter::WriteContentLine(const string& text) -{ - // Write the indentation. - if (m_newLine) - { - for (int i = 0; i < m_indentationSize; ++i) - { - WriteText(" "); - } - } - - WriteText("%s\n", text.c_str()); - m_newLine = true; -} - -void XMLWriter::WriteText(const char* format, ...) -{ - va_list args; - va_start(args, format); - char buffer[40000]; - azvsnprintf(buffer, sizeof(buffer), format, args); - m_sink->Write(buffer); - va_end(args); -} - -XMLWriter::Element::Element(XMLWriter& writer, const string& name, bool output) - : m_writer(writer) - , m_name(name) - , m_output(output) - , isParent(false) -{ - if (!m_writer.m_elements.empty()) - { - Element* parent = m_writer.m_elements.back(); - if (!parent->isParent) - { - parent->isParent = true; - if (parent->m_output) - { - m_writer.CloseElement(m_name, true); - } - } - } - m_writer.m_elements.push_back(this); - if (m_output) - { - m_writer.IncreaseIndentation(); - } - if (m_output) - { - m_writer.BeginElement(m_name); - } -} - -XMLWriter::Element::~Element() -{ - if (m_output) - { - if (isParent) - { - m_writer.EndElement(m_name); - } - else - { - m_writer.CloseLeafElement(m_name); - } - } - m_writer.m_elements.pop_back(); - if (m_output) - { - m_writer.DecreaseIndentation(); - } -} - -void XMLWriter::Element::Child(const string& name, const string& value) -{ - Element child(m_writer, name); - child.Content(value); -} - -void XMLWriter::Element::Content(const string& text) -{ - if (m_output) - { - assert(!isParent); - if (!isParent) - { - isParent = true; - m_writer.CloseElement(m_name, false); - } - m_writer.WriteContent(text); - } -} - -void XMLWriter::Element::ContentLine(const string& text) -{ - if (!isParent) - { - isParent = true; - if (m_output) - { - m_writer.CloseElement(m_name, true); - } - } - if (m_output) - { - m_writer.WriteContentLine(text); - } -} - -XMLFileSink::XMLFileSink(const string& filename) -{ - m_file = std::fopen(filename.c_str(), "w"); - if (!m_file) - { - throw OpenFailedError("Unable to open file."); - } -} - -XMLFileSink::~XMLFileSink() -{ - if (m_file) - { - fclose(m_file); - } -} - -void XMLFileSink::Write(const char* text) -{ - if (m_file) - { - string asciiText = StringHelpers::ConvertString(text); - fwrite(asciiText.c_str(), 1, asciiText.size(), m_file); - } -} diff --git a/Code/Tools/CryCommonTools/XMLWriter.h b/Code/Tools/CryCommonTools/XMLWriter.h deleted file mode 100644 index d98b9f3d56..0000000000 --- a/Code/Tools/CryCommonTools/XMLWriter.h +++ /dev/null @@ -1,185 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_XMLWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_XMLWRITER_H -#pragma once - - -#include "Exceptions.h" - -#include -#include -#include - -class IXMLSink -{ -public: - // Define an exception type to throw when file opening fails. - struct OpenFailedErrorTag {}; - typedef Exception OpenFailedError; - - virtual void Write(const char* text) = 0; -}; - -class XMLFileSink - : public IXMLSink -{ -public: - XMLFileSink(const string& name); - ~XMLFileSink(); - - virtual void Write(const char* text); - -private: - FILE* m_file; -}; - -class XMLWriter -{ -public: - XMLWriter(IXMLSink* sink); - - class Element - { - public: - Element(XMLWriter& writer, const string& name, bool output = true); - ~Element(); - - template - void Attribute(const string& name, const T& value); - void Child(const string& name, const string& value); - void Content(const string& text); - void ContentLine(const string& text); - template - void ContentArrayElement(const T& value); - void ContentArrayFloat24(const float floatBuffer[24], const int entryCount); - - void WriteDirectText(const char* text) - { - if (!isParent) - { - isParent = true; - if (m_output) - { - m_writer.CloseElement(m_name, false); - } - } - m_writer.WriteDirectText(text); - } - - private: - XMLWriter& m_writer; - string m_name; - bool isParent; - bool m_output; - }; - - void WriteDirectText(const char* text) - { - m_sink->Write(text); - } - -private: - void IncreaseIndentation(); - void DecreaseIndentation(); - - void BeginElement(const string& name); - void EndElement(const string& name); - void CloseElement(const string& name, bool newLine); - void CloseLeafElement(const string& name); - - void WriteAttribute(const string& name, const string& value); - static void SerializeAttribute(char* buffer, size_t bufferSize, const string& value); - static void SerializeAttribute(char* buffer, size_t bufferSize, float value); - static void SerializeAttribute(char* buffer, size_t bufferSize, int value); - static void SerializeArrayElement(char* buffer, size_t bufferSize, float value); - static void SerializeArrayElement(char* buffer, size_t bufferSize, const string& value); - static void SerializeArrayElement(char* buffer, size_t bufferSize, int value); - void WriteContent(const string& text); - void WriteContentLine(const string& text); - - void WriteText(const char* format, ...); - - IXMLSink* m_sink; - int m_indentationSize; - - std::vector m_elements; - bool m_newLine; -}; - -template -void XMLWriter::Element::Attribute(const string& name, const T& value) -{ - assert(!isParent); - char buffer[1024]; - XMLWriter::SerializeAttribute(buffer, sizeof(buffer), value); - if (m_output) - { - m_writer.WriteAttribute(name, buffer); - } -} - -template -void XMLWriter::Element::ContentArrayElement(const T& value) -{ - if (!m_output) - { - return; - } - - if (!isParent) - { - isParent = true; - m_writer.CloseElement(m_name, false); - } - - char buffer[1024] = {' ', 0}; - XMLWriter::SerializeArrayElement(buffer + 1, sizeof(buffer) - 1, value); - - m_writer.WriteDirectText(buffer); -} - -inline void XMLWriter::Element::ContentArrayFloat24(const float floatBuffer[24], const int entryCount) -{ - if (!m_output) - { - return; - } - if (!isParent) - { - isParent = true; - m_writer.CloseElement(m_name, false); - } - - char buffer[2048]; - if (entryCount == 24) - { - sprintf_s(buffer, " %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e", - floatBuffer[0], floatBuffer[1], floatBuffer[2], floatBuffer[3], floatBuffer[4], floatBuffer[5], floatBuffer[6], floatBuffer[7], - floatBuffer[8], floatBuffer[9], floatBuffer[10], floatBuffer[11], floatBuffer[12], floatBuffer[13], floatBuffer[14], floatBuffer[15], - floatBuffer[16], floatBuffer[17], floatBuffer[18], floatBuffer[19], floatBuffer[20], floatBuffer[21], floatBuffer[22], floatBuffer[23]); - m_writer.WriteDirectText(buffer); - } - else - { - for (int i = 0; i < entryCount; i++) - { - char buffer[1024]; - sprintf_s(buffer, " %.10e", floatBuffer[i]); - m_writer.WriteDirectText(buffer); - } - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_XMLWRITER_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDir.h b/Code/Tools/CryCommonTools/ZipDir/ZipDir.h deleted file mode 100644 index c9954ce5dc..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDir.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIR_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIR_H -#pragma once - -#include "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "smartptr.h" -#include "ZipDirTree.h" -#include "ZipDirList.h" -#include "ZipDirCache.h" -#include "ZipDirCacheRW.h" -#include "ZipDirCacheFactory.h" -#include "ZipDirFind.h" -#include "ZipDirFindRW.h" - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIR_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp deleted file mode 100644 index 1f5d4a9286..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp +++ /dev/null @@ -1,298 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include "FileUtil.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirCache.h" -#include "ZipDirFind.h" -#include "ZipDirCacheFactory.h" -#include -#include -#include "PathHelpers.h" -#include - -using namespace ZipFile; - -// initializes the instance structure -void ZipDir::Cache::Construct(FILE* fNew, size_t nDataSizeIn, const EncryptionKey& key) -{ - m_nRefCount = 0; - m_pFile = fNew; - m_nDataSize = nDataSizeIn; - m_nZipPathOffset = nDataSizeIn; - m_bEncryptHeaders = false; - m_encryptionKey = key; -} - -// self-destruct when ref count drops to 0 -void ZipDir::Cache::Delete() -{ - if (m_pFile) - { - fclose (m_pFile); - } - free(this); -} - -// looks for the given file record in the Central Directory. If there's none, returns NULL. -// if there is some, returns the pointer to it. -// the Path must be the relative path to the file inside the Zip -// if the file handle is passed, it will be used to find the file data offset, if one hasn't been initialized yet -ZipDir::FileEntry* ZipDir::Cache::FindFile (const char* szPath, [[maybe_unused]] bool bRefresh) -{ - ZipDir::FindFile fd (this); - if (!fd.FindExact(szPath)) - { - assert (!fd.GetFileEntry()); - return NULL; - } - assert (fd.GetFileEntry()); - return fd.GetFileEntry(); -} - -// loads the given file into the pCompressed buffer (the actual compressed data) -// if the pUncompressed buffer is supplied, uncompresses the data there -// buffers must have enough memory allocated, according to the info in the FileEntry -// NOTE: there's no need to decompress if the method is 0 (store) -// returns 0 if successful or error code if couldn't do something -ZipDir::ErrorEnum ZipDir::Cache::ReadFile (FileEntry* pFileEntry, void* pCompressed, void* pUncompressed) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->desc.lSizeUncompressed == 0) - { - assert (pFileEntry->desc.lSizeCompressed == 0); - return ZD_ERROR_SUCCESS; - } - - assert (pFileEntry->desc.lSizeCompressed > 0); - - ErrorEnum nError = Refresh(pFileEntry); - if (nError != ZD_ERROR_SUCCESS) - { - return nError; - } - - if (AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(m_pFile, pFileEntry->nFileDataOffset, SEEK_SET)) - { - return ZD_ERROR_IO_FAILED; - } - - SmartPtr pBufferDestroyer; - - void* pBuffer = pCompressed; // the buffer where the compressed data will go - - if (pFileEntry->nMethod == 0 && pUncompressed) - { - // we can directly read into the uncompress buffer - pBuffer = pUncompressed; - } - - if (!pBuffer) - { - if (!pUncompressed) - { - // what's the sense of it - no buffers at all? - return ZD_ERROR_INVALID_CALL; - } - - pBuffer = malloc(pFileEntry->desc.lSizeCompressed); - pBufferDestroyer.Attach(pBuffer); // we want it auto-freed once we return - } - - - if (fread (pBuffer, pFileEntry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return ZD_ERROR_IO_FAILED; - } - - if (pFileEntry->nMethod == METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pBuffer, pFileEntry->desc.lSizeCompressed, m_encryptionKey); - } - - // if there's a buffer for uncompressed data, uncompress it to that buffer - if (pUncompressed) - { - if (pFileEntry->nMethod == 0) - { - assert (pBuffer == pUncompressed); - //assert (pFileEntry->desc.lSizeCompressed == pFileEntry->nSizeUncompressed); - //memcpy (pUncompressed, pBuffer, pFileEntry->desc.lSizeCompressed); - } - else - { - unsigned long nSizeUncompressed = pFileEntry->desc.lSizeUncompressed; - if (Z_OK != ZipRawUncompress(pUncompressed, &nSizeUncompressed, pBuffer, pFileEntry->desc.lSizeCompressed)) - { - return ZD_ERROR_CORRUPTED_DATA; - } - } - } - - return ZD_ERROR_SUCCESS; -} - -// loads and unpacks the file into a newly created buffer (that must be subsequently freed with -// Free()) Returns NULL if failed -void* ZipDir::Cache::AllocAndReadFile (FileEntry* pFileEntry) -{ - if (!pFileEntry) - { - return NULL; - } - - void* pData = malloc(pFileEntry->desc.lSizeUncompressed); - if (pData) - { - if (ZD_ERROR_SUCCESS != ReadFile (pFileEntry, NULL, pData)) - { - free(pData); - pData = NULL; - } - } - return pData; -} - -// frees the memory block that was previously allocated by AllocAndReadFile -void ZipDir::Cache::Free (void* pData) -{ - free(pData); -} - -// refreshes information about the given file entry into this file entry -ZipDir::ErrorEnum ZipDir::Cache::Refresh (FileEntry* pFileEntry) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) - { - return ZD_ERROR_SUCCESS; // the data offset has been successfully read.. - } - - return ZipDir::Refresh(m_pFile, pFileEntry, m_bEncryptHeaders); -} - -////////////////////////////////////////////////////////////////////////// -uint32 ZipDir::Cache::GetFileDataOffset(FileEntry* pFileEntry) -{ - if (pFileEntry->nFileDataOffset == pFileEntry->INVALID_DATA_OFFSET) - { - ZipDir::Refresh (m_pFile, pFileEntry, m_bEncryptHeaders); - } - return pFileEntry->nFileDataOffset; -} - -// returns the size of memory occupied by the instance referred to by this cache -// must be exact, because it's used by CacheRW to reallocate this cache -size_t ZipDir::Cache::GetSize() const -{ - return m_nDataSize + sizeof(Cache) + strlen(GetFilePath()); -} - - -// QUICK check to determine whether the file entry belongs to this object -bool ZipDir::Cache::IsOwnerOf (const FileEntry* pFileEntry) const -{ - // just check whether the pointer is within the memory block of this cache instance - return ((ULONG_PTR)pFileEntry >= (ULONG_PTR)(GetRoot() + 1) - && (ULONG_PTR)pFileEntry <= ((ULONG_PTR)GetRoot()) + m_nDataSize - sizeof(FileEntry)); -} - -bool ZipDir::Cache::UnpakToDisk(const string& destFolder) -{ - return UnpakToDiskInternal(GetRoot(), destFolder); -} - -bool ZipDir::Cache::UnpakToDiskInternal(ZipDir::DirHeader* folder, const string& destFolder) -{ - if (!folder) - { - return false; - } - - if (!FileUtil::EnsureDirectoryExists(destFolder.c_str())) - { - return false; - } - - bool result = true; - for (ZipFile::ushort fileNum = 0; fileNum < folder->numFiles; ++fileNum) - { - ZipDir::FileEntry* fileEntry = folder->GetFileEntry(fileNum); - if (!fileEntry) - { - result = false; - continue; - } - - string filePath = PathHelpers::Join(destFolder, fileEntry->GetName(folder->GetNamePool())); - AZ::IO::SystemFile file; - if (!file.Open(filePath.c_str(), AZ::IO::SystemFile::SF_OPEN_READ_WRITE | AZ::IO::SystemFile::SF_OPEN_CREATE)) - { - result = false; - continue; - } - - if (!fileEntry->desc.lSizeUncompressed) - { - // Nothing to write. Just close the file. - file.Close(); - continue; - } - - AZStd::vector buffer(fileEntry->desc.lSizeUncompressed); - if (ReadFile(fileEntry, nullptr, buffer.data()) == ZD_ERROR_SUCCESS) - { - file.Write(buffer.data(), buffer.size()); - file.Close(); - } - else - { - file.Close(); - AZ::IO::SystemFile::Delete(filePath.c_str()); - result = false; - continue; - } - } - - for (ZipFile::ushort dirNum = 0; dirNum < folder->numDirs; ++dirNum) - { - ZipDir::DirEntry* entry = folder->GetSubdirEntry(dirNum); - if (!entry) - { - result = false; - continue; - } - - string newPath = PathHelpers::Join(destFolder, entry->GetName(folder->GetNamePool())); - if (!UnpakToDiskInternal(entry->GetDirectory(), newPath)) - { - result = false; - continue; - } - } - - return result; -} - diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h deleted file mode 100644 index 958c77efc3..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h +++ /dev/null @@ -1,140 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Declarations of the class used to parse and cache Zipped directory. -// This class is actually an auto-pointer to the instance of the cache, so it can -// be easily passed by value. -// The cache instance contains the optimized for memory usage and fast search tree -// of the files/directories inside the zip; each file has a descriptor with the -// info about where its compressed data lies within the file - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHE_H -#pragma once - - - -///////////////////////////////////////////////////////////// -// THe Zip Dir uses a special memory layout for keeping the structure of zip file. -// This layout is optimized for small memory footprint (for big zip files) -// and quick binary-search access to the individual files. -// -// The serialized layout consists of a number of directory records. -// Each directory record starts with the DirHeader structure, then -// it has an array of DirEntry structures (sorted by name), -// array of FileEntry structures (sorted by name) and then -// the pool of names, followed by pad bytes to align the whole directory -// record on 4-byte boundray. - -namespace ZipDir -{ - // this is the header of the instance data allocated dynamically - // it contains the FILE* : it owns it and closes upon destruction - struct Cache - { - void AddRef() { ++m_nRefCount; } - void Release() - { - if (--m_nRefCount <= 0) - { - Delete(); - } - } - int NumRefs() const { return m_nRefCount; } - - // looks for the given file record in the Central Directory. If there's none, returns NULL. - // if there is some, returns the pointer to it. - // the Path must be the relative path to the file inside the Zip - // if the file handle is passed, it will be used to find the file data offset, if one hasn't been initialized yet - // if bFull is true, then the full information about the file is returned (the offset to the data may be unknown at this point)- - // if needed, the file is accessed and the information is loaded - FileEntry* FindFile (const char* szPath, bool bFullInfo = false); - - // loads the given file into the pCompressed buffer (the actual compressed data) - // if the pUncompressed buffer is supplied, uncompresses the data there - // buffers must have enough memory allocated, according to the info in the FileEntry - // NOTE: there's no need to decompress if the method is 0 (store) - // returns 0 if successful or error code if couldn't do something - ErrorEnum ReadFile (FileEntry* pFileEntry, void* pCompressed, void* pUncompressed); - - // loads and unpacks the file into a newly created buffer (that must be subsequently freed with - // Free()) Returns NULL if failed - void* AllocAndReadFile (FileEntry* pFileEntry); - - // frees the memory block that was previously allocated by AllocAndReadFile - void Free (void*); - - // refreshes information about the given file entry into this file entry - ErrorEnum Refresh (FileEntry* pFileEntry); - - // Return FileEntity data offset inside zip file. - uint32 GetFileDataOffset(FileEntry* pFileEntry); - - - // returns the root directory record; - // through this directory record, user can traverse the whole tree - DirHeader* GetRoot() const - { - return (DirHeader*)(this + 1); - } - - // returns the size of memory occupied by the instance referred to by this cache - // must be exact, because it's used by CacheRW to reallocate this cache - size_t GetSize() const; - - // QUICK check to determine whether the file entry belongs to this object - bool IsOwnerOf (const FileEntry* pFileEntry) const; - - // returns the string - path to the zip file from which this object was constructed. - // this will be "" if the object was constructed with a factory that wasn't created with FLAGS_MEMORIZE_ZIP_PATH - const char* GetFilePath() const - { - return ((const char*)(this + 1)) + m_nZipPathOffset; - } - - // Unpak the file into a destination folder - bool UnpakToDisk(const string& destFolder); - - friend class CacheFactory; // the factory class creates instances of this class - friend class CacheRW; // the Read-Write 2-way cache can modify this cache directly during write operations - protected: - volatile signed int m_nRefCount; // the reference count - FILE* m_pFile; // the opened file - - // the size of the serialized data following this instance (not including the extra fields after the serialized tree data) - size_t m_nDataSize; - // the offset to the path/name of the zip file relative to (char*)(this+1) pointer in bytes - size_t m_nZipPathOffset; - - // tells if encryption used for zip-file - EncryptionKey m_encryptionKey; - bool m_bEncryptHeaders; - public: - // initializes the instance structure - void Construct(FILE* fNew, size_t nDataSize, const EncryptionKey& key); - void Delete(); - private: - bool ReadCompressedData(char* data, size_t size); - bool UnpakToDiskInternal(ZipDir::DirHeader* dirHeader, const string& destFolder); - - // the constructor/destructor cannot be called at all - everything will go through the factory class - Cache() { m_nRefCount = 0; } - ~Cache(){} - }; - - TYPEDEF_AUTOPTR(Cache); - - typedef Cache_AutoPtr CachePtr; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHE_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp deleted file mode 100644 index 9d64f60b63..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirCache.h" -#include "ZipDirCacheRW.h" -#include "ZipDirCacheFactory.h" -#include "ZipDirList.h" -#include - -static uint32 g_defaultEncryptionKey[4] = { 0xc968fb67, 0x8f9b4267, 0x85399e84, 0xf9b99dc4 }; - -ZipDir::CacheFactory::CacheFactory (InitMethodEnum nInitMethod, unsigned nFlags) -{ - m_nCDREndPos = 0; - m_f = NULL; - m_bBuildFileEntryMap = false; // we only need it for validation/debugging - m_bBuildFileEntryTree = true; // we need it to actually build the optimized structure of directories - m_bEncryptedHeaders = false; - - m_nInitMethod = nInitMethod; - m_nFlags = nFlags; -} - -ZipDir::CacheFactory::~CacheFactory() -{ - Clear(); -} - -ZipDir::CachePtr ZipDir::CacheFactory::New (const char* szFile, const uint32 key[4]) -{ - m_encryptionKey = EncryptionKey(g_defaultEncryptionKey); - if (key) - { - m_encryptionKey = EncryptionKey(key); - } - - Clear(); - m_f = nullptr; - azfopen(&m_f, szFile, "rb"); - if (m_f) - { - return MakeCache (szFile); - } - Clear(); - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot open file in binary mode for reading, probably missing file"); - return 0; - /* - if (!m_f) - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED,"Cannot open file in binary mode for reading, probably missing file"); - try - { - return MakeCache (szFile); - } - catch(Error) - { - Clear(); - throw; - } - */ -} - - -ZipDir::CacheRWPtr ZipDir::CacheFactory::NewRW(const char* szFileName, size_t fileAlignment, bool encrypted, const uint32* key) -{ - m_encryptionKey = EncryptionKey(g_defaultEncryptionKey); - if (key) - { - m_encryptionKey = EncryptionKey(key); - } - - CacheRWPtr pCache = new CacheRW(encrypted, m_encryptionKey); - - // opens the given zip file and connects to it. Creates a new file if no such file exists - // if successful, returns true. - if (!(m_nFlags & FLAGS_DONT_MEMORIZE_ZIP_PATH)) - { - pCache->m_strFilePath = szFileName; - } - - if (m_nFlags & FLAGS_DONT_COMPACT) - { - pCache->m_nFlags |= CacheRW::FLAGS_DONT_COMPACT; - } - - // first, try to open the file for reading or reading/writing - if (m_nFlags & FLAGS_READ_ONLY) - { - m_f = nullptr; - azfopen(&m_f, szFileName, "rb"); - pCache->m_nFlags |= CacheRW::FLAGS_CDR_DIRTY | CacheRW::FLAGS_READ_ONLY; - - if (!m_f) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for reading"); - return 0; - } - } - else - { - m_f = NULL; - if (!(m_nFlags & FLAGS_CREATE_NEW)) - { - m_f = nullptr; - azfopen(&m_f, szFileName, "r+b"); - } - - bool bOpenForWriting = true; - - if (m_f) - { - // get file size - fseek(m_f, 0, SEEK_END); - size_t nFileSize = AZ_TRAIT_CRYCOMMONTOOLS_FTELL(m_f); - fseek(m_f, 0, SEEK_SET); - - if (nFileSize) - { - if (!ReadCacheRW(*pCache)) - { - fclose(m_f); - m_f = NULL; - - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not read archive"); - return 0; - } - bOpenForWriting = false; - } - else - { - // if file has 0 bytes (e.g. crash during saving) we don't want to open it - assert(0); // you can ignore, the system shold handle this gracefully - } - } - - if (bOpenForWriting) - { - m_f = nullptr; - azfopen(&m_f, szFileName, "w+b"); - if (m_f) - { - // there's no such file, but we'll create one. We'll need to write out the CDR here - pCache->m_lCDROffset = 0; - pCache->m_nFlags |= CacheRW::FLAGS_CDR_DIRTY; - } - pCache->m_fileAlignment = fileAlignment; - } - - if (!m_f) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for appending (read/write)"); - return 0; - } - } - - - // give the cache the file handle: - pCache->m_pFile = m_f; - // the factory doesn't own it after that - m_f = NULL; - - return pCache; -} - -bool ZipDir::CacheFactory::ReadCacheRW (CacheRW& rwCache) -{ - m_bBuildFileEntryTree = true; - if (!Prepare()) - { - return false; - } - - // since it's open for R/W, we need to know exactly how much space - // we have for each file to use the gaps efficiently - FileEntryList Adjuster (&m_treeFileEntries, m_CDREnd.lCDROffset); - Adjuster.RefreshEOFOffsets(); - - m_treeFileEntries.Swap(rwCache.m_treeDir); - m_CDR_buffer.swap(rwCache.m_CDR_buffer); // CDR Buffer contain actually the string pool for the tree directory. - m_unifiedNameBuffer.swap(rwCache.m_unifiedNameBuffer); // string pool for unified names - - // very important: we need this offset to be able to add to the zip file - rwCache.m_lCDROffset = m_CDREnd.lCDROffset; - - if (m_bEncryptedHeaders != rwCache.m_bEncryptedHeaders) - { - // force to relink and update all headers on close - rwCache.m_nFlags |= ZipDir::CacheRW::FLAGS_UNCOMPACTED; - rwCache.m_bHeadersEncryptedOnClose = rwCache.m_bEncryptedHeaders; - rwCache.m_bEncryptedHeaders = m_bEncryptedHeaders; - } - return true; -} - -// reads everything and prepares the maps -bool ZipDir::CacheFactory::Prepare () -{ - if (!FindCDREnd()) - { - return false; - } - - m_bEncryptedHeaders = (m_CDREnd.nDisk & (1 << 15)) != 0; - m_CDREnd.nDisk = m_CDREnd.nDisk & 0x7fff; - - // we don't support multivolume archives - if (m_CDREnd.nDisk != 0 - || m_CDREnd.nCDRStartDisk != 0 - || m_CDREnd.numEntriesOnDisk != m_CDREnd.numEntriesTotal) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_UNSUPPORTED, "Multivolume archive detected. Current version of ZipDir does not support multivolume archives"); - return false; - } - - // if the central directory offset or size are out of range, - // the CDREnd record is probably corrupt - if (m_CDREnd.lCDROffset > m_nCDREndPos - || m_CDREnd.lCDRSize > m_nCDREndPos - || m_CDREnd.lCDROffset + m_CDREnd.lCDRSize > m_nCDREndPos) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_DATA_IS_CORRUPT, "The central directory offset or size are out of range, the pak is probably corrupt, try to repair or delete the file"); - return false; - } - - if (!BuildFileEntryMap()) - { - return false; - } - - // the number of parsed files MUST be the declared number of entries - // in the central directory - if (m_bBuildFileEntryMap && m_CDREnd.numEntriesTotal != m_mapFileEntries.size()) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "The number of parsed files does not match the declared number of entries in the central directory, the pak is probably corrupt, try to repair or delete the file"); - } - - const size_t numFilesFound = m_treeFileEntries.NumFilesTotal(); - if (m_bBuildFileEntryTree && m_CDREnd.numEntriesTotal != numFilesFound) - { - const size_t numDirsFound = m_treeFileEntries.NumDirsTotal(); - - // Other zip tools create entries for directories. - // These entires don't have representation in our tree. - // FIXME: Proper calculation of entry count should be implemented. - if (m_CDREnd.numEntriesTotal != numFilesFound + numDirsFound) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "The number of parsed files does not match the declared number of entries in the central directory. The pak does not appear to be corrupt, but perhaps there are some duplicated or missing file entries, try to repair the file"); - } - } - - return true; -} - -ZipDir::CachePtr ZipDir::CacheFactory::MakeCache (const char* szFile) -{ - if (!Prepare()) - { - return CachePtr(); - } - - // initializes this object from the given tree, which is a convenient representation of the file tree - size_t nSizeRequired = m_treeFileEntries.GetSizeSerialized(); - size_t nSizeZipPath = 1; // we need to remember the terminating 0 - if (!(m_nFlags & FLAGS_DONT_MEMORIZE_ZIP_PATH)) - { - nSizeZipPath += strlen(szFile); - } - // allocate and initialize the memory that'll be the root now - size_t nCacheInstanceSize = sizeof(Cache) + nSizeRequired + nSizeZipPath; - - Cache* pCacheInstance = (Cache*)malloc(nCacheInstanceSize); // Do not use pools for this allocation - pCacheInstance->Construct(m_f, nSizeRequired, m_encryptionKey); - CachePtr cache = pCacheInstance; - m_f = NULL; // we don't own the file anymore - it's in possession of the cache instance - - // try to serialize into the memory -#if !defined(NDEBUG) - size_t nSizeSerialized = -#endif - m_treeFileEntries.Serialize (cache->GetRoot()); - - assert (nSizeSerialized == nSizeRequired); - - char* pZipPath = ((char*)(pCacheInstance + 1)) + nSizeRequired; - - if (!(m_nFlags & FLAGS_DONT_MEMORIZE_ZIP_PATH)) - { - memcpy (pZipPath, szFile, nSizeZipPath); - } - else - { - pZipPath[0] = '\0'; - } - - Clear(); - - return cache; -} - -void ZipDir::CacheFactory::Clear() -{ - if (m_f) - { - fclose (m_f); - } - m_nCDREndPos = 0; - memset (&m_CDREnd, 0, sizeof(m_CDREnd)); - m_mapFileEntries.clear(); - m_treeFileEntries.Clear(); - m_bEncryptedHeaders = false; -} - - -////////////////////////////////////////////////////////////////////////// -// searches for CDREnd record in the given file -bool ZipDir::CacheFactory::FindCDREnd() -{ - // this buffer will be used to find the CDR End record - // the additional bytes are required to store the potential tail of the CDREnd structure - // when moving the window to the next position in the file - char pReservedBuffer[g_nCDRSearchWindowSize + sizeof(ZipFile::CDREnd) - 1]; - - Seek (0, SEEK_END); - unsigned long nFileSize = Tell(); - - if (nFileSize < sizeof(ZipFile::CDREnd)) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_CDR, "The file is too small, it doesn't even contain the CDREnd structure. Please check and delete the file. Truncated files are not deleted automatically"); - return false; - } - - // this will point to the place where the buffer was loaded - unsigned int nOldBufPos = nFileSize; - // start scanning well before the end of the file to avoid reading beyond the end - - unsigned int nScanPos = nFileSize - sizeof(ZipFile::CDREnd); - - m_CDREnd.lSignature = 0; // invalid signature as the flag of not-found CDR End structure - while (true) - { - unsigned int nNewBufPos; // the new buf pos - char* pWindow = pReservedBuffer; // the window pointer into which data will be read (takes into account the possible tail-of-CDREnd) - if (nOldBufPos <= g_nCDRSearchWindowSize) - { - // the old buffer position doesn't let us read the full search window size - // therefore the new buffer pos will be 0 (instead of negative beyond the start of the file) - // and the window pointer will be closer tot he end of the buffer because the end of the buffer - // contains the data from the previous iteration (possibly) - nNewBufPos = 0; - pWindow = pReservedBuffer + g_nCDRSearchWindowSize - (nOldBufPos - nNewBufPos); - } - else - { - nNewBufPos = nOldBufPos - g_nCDRSearchWindowSize; - assert (nNewBufPos > 0); - } - - // since dealing with 32bit unsigned, check that filesize is bigger than - // CDREnd plus comment before the following check occurs. - if (nFileSize > (sizeof(ZipFile::CDREnd) + 0xFFFF)) - { - // if the new buffer pos is beyond 64k limit for the comment size - if (nNewBufPos < (unsigned int)(nFileSize - sizeof(ZipFile::CDREnd) - 0xFFFF)) - { - nNewBufPos = nFileSize - sizeof(ZipFile::CDREnd) - 0xFFFF; - } - } - - // if there's nothing to search - if (nNewBufPos >= nOldBufPos) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_CDR, "Cannot find Central Directory Record in pak. This is either not a pak file, or a pak file without Central Directory. It does not mean that the data is permanently lost, but it may be severely damaged. Please repair the file with external tools, there may be enough information left to recover the file completely"); // we didn't find anything - return false; - } - - // seek to the start of the new window and read it - Seek (nNewBufPos); - Read (pWindow, nOldBufPos - nNewBufPos); - - while (nScanPos >= nNewBufPos) - { - ZipFile::CDREnd* pEnd = (ZipFile::CDREnd*)(pWindow + nScanPos - nNewBufPos); - if (pEnd->lSignature == pEnd->SIGNATURE) - { - if (pEnd->nCommentLength == nFileSize - nScanPos - sizeof(ZipFile::CDREnd)) - { - // the comment length is exactly what we expected - m_CDREnd = *pEnd; - m_nCDREndPos = nScanPos; - break; - } - else - { - THROW_ZIPDIR_ERROR (ZD_ERROR_DATA_IS_CORRUPT, "Central Directory Record is followed by a comment of inconsistent length. This might be a minor misconsistency, please try to repair the file. However, it is dangerous to open the file because I will have to guess some structure offsets, which can lead to permanent unrecoverable damage of the archive content"); - return false; - } - } - if (nScanPos == 0) - { - break; - } - --nScanPos; - } - - if (m_CDREnd.lSignature == m_CDREnd.SIGNATURE) - { - return true; // we've found it - } - - nOldBufPos = nNewBufPos; - memmove (pReservedBuffer + g_nCDRSearchWindowSize, pWindow, sizeof(ZipFile::CDREnd) - 1); - } - THROW_ZIPDIR_ERROR (ZD_ERROR_UNEXPECTED, "The program flow may not have possibly lead here. This error is unexplainable"); // we shouldn't be here - return false; -} - - -////////////////////////////////////////////////////////////////////////// -// uses the found CDREnd to scan the CDR and probably the Zip file itself -// builds up the m_mapFileEntries -bool ZipDir::CacheFactory::BuildFileEntryMap() -{ - Seek (m_CDREnd.lCDROffset); - - if (m_CDREnd.lCDRSize == 0) - { - return true; - } - - DynArray& pBuffer = m_CDR_buffer; // Use persistent buffer. - - pBuffer.resize(m_CDREnd.lCDRSize + 1); // Allocate one more because we use this memory as a strings pool. - - if (pBuffer.empty()) // couldn't allocate enough memory for temporary copy of CDR - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_MEMORY, "Not enough memory to cache Central Directory record for fast initialization. This error may not happen on non-console systems"); - return false; - } - - // Calculate buffer size for unified filenames - const size_t headersSize = sizeof(ZipFile::CDRFileHeader) * m_CDREnd.numEntriesTotal; - const size_t terminatingZeros = m_CDREnd.numEntriesTotal; - if (headersSize > m_CDREnd.lCDRSize + terminatingZeros) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CORRUPTED_DATA, "Number of entries in Central Directory seems to be wrong"); - return false; - } - const size_t nameBufferSize = m_CDREnd.lCDRSize + terminatingZeros - headersSize; // numEntriesTotal for terminating zeroes - - // Allocate buffer for unified filenames - m_unifiedNameBuffer.resize(nameBufferSize); - if (m_unifiedNameBuffer.empty() && nameBufferSize != 0) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_MEMORY, "Not enough memory to allocate unified names buffer"); - return false; - } - char* pUnifiedName = m_unifiedNameBuffer.empty() ? 0 : &m_unifiedNameBuffer[0]; - const char* const pUnifiedNameEnd = pUnifiedName + m_unifiedNameBuffer.size(); - - ReadHeaderData(&pBuffer[0], m_CDREnd.lCDRSize); - - // now we've read the complete CDR - parse it. - ZipFile::CDRFileHeader* pFile = (ZipFile::CDRFileHeader*)(&pBuffer[0]); - const char* const pEndOfData = &pBuffer[0] + m_CDREnd.lCDRSize; - const char* const pEndOfBuffer = &pBuffer[0] + pBuffer.size(); - char* pFileName; - - // check signature of first entry - if ((const char*)(pFile + 1) <= pEndOfData) - { - if (pFile->lSignature != pFile->SIGNATURE) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, m_bEncryptedHeaders - ? "Signature of CDR entry is corrupt. Wrong decryption key was used or archive is corrupt." - : "Signature of CDR entry is corrupt. Archive is corrupt."); - return false; - } - } - - while ((pFileName = (char*)(pFile + 1)) <= pEndOfData) - { - // Hacky way to use CDR memory block as a string pool. - pFile->lSignature = 0; // Force signature to always be 0 (First byte of signature maybe a zero termination of the previous file filename). - - if (pFile->nVersionNeeded > 20) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_UNSUPPORTED, "Reading file header with unsupported version (nVersionNeeded > 20)."); - return false; - } - //if (pFile->lSignature != pFile->SIGNATURE) // Timur, Dont compare signatures as signatue in memory can be overwritten by the code below - //break; - // the end of this file record - const char* pEndOfRecord = (pFileName + pFile->nFileNameLength + pFile->nExtraFieldLength + pFile->nFileCommentLength); - // if the record overlaps with the End Of CDR structure, something is wrong - if (pEndOfRecord > pEndOfData) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "Central Directory record is either corrupt, or truncated, or missing. Cannot read the archive directory"); - return false; - } - - ////////////////////////////////////////////////////////////////////////// - // Analyze advanced section. - ////////////////////////////////////////////////////////////////////////// - SExtraZipFileData extra; - const char* pExtraField = (pFileName + pFile->nFileNameLength); - const char* pExtraEnd = pExtraField + pFile->nExtraFieldLength; - while (pExtraField < pExtraEnd) - { - const char* pAttrData = pExtraField + sizeof(ZipFile::ExtraFieldHeader); - ZipFile::ExtraFieldHeader& hdr = *(ZipFile::ExtraFieldHeader*)pExtraField; - switch (hdr.headerID) - { - case ZipFile::EXTRA_NTFS: - { - extra.nLastModifyTime = *(uint64*)(pAttrData + sizeof(ZipFile::ExtraNTFSHeader)); - //uint64 accTime = *(uint64*)(pAttrData + sizeof(ZipFile::ExtraNTFSHeader) + 8); - //uint64 crtTime = *(uint64*)(pAttrData + sizeof(ZipFile::ExtraNTFSHeader) + 16); - } - break; - } - pExtraField += sizeof(ZipFile::ExtraFieldHeader) + hdr.dataSize; - } - - bool bDirectory = false; - if (pFile->nFileNameLength > 0 && (pFileName[pFile->nFileNameLength - 1] == '/' || pFileName[pFile->nFileNameLength - 1] == '\\')) - { - bDirectory = true; - } - - if (!bDirectory) - { - const size_t fileNameLen = pFile->nFileNameLength; - pFileName[fileNameLen] = 0; // Not standard!, may overwrite signature of the next memory record data in zip. - - // generate unified name - if (pFileName + fileNameLen + 1 > pEndOfBuffer || - pUnifiedName + fileNameLen + 1 > pUnifiedNameEnd) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CORRUPTED_DATA, "Filename length exceeds estimated size. Try to repair the archive."); - return false; - } - - for (int i = 0; i < fileNameLen + 1; i++) - { - pUnifiedName[i] = ::tolower(pFileName[i]); - } - - // put this entry into the map - AddFileEntry (pFileName, pUnifiedName, pFile, extra); - - pUnifiedName += fileNameLen + 1; - } - - // move to the next file - pFile = (ZipFile::CDRFileHeader*)pEndOfRecord; - } - - // finished reading CDR - return true; -} - - -////////////////////////////////////////////////////////////////////////// -// give the CDR File Header entry, reads the local file header to validate -// and determine where the actual file lies -void ZipDir::CacheFactory::AddFileEntry (char* strFilePath, char* strUnifiedPath, const ZipFile::CDRFileHeader* pFileHeader, const SExtraZipFileData& extra) -{ - if (pFileHeader->lLocalHeaderOffset > m_CDREnd.lCDROffset) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "Central Directory contains file descriptors pointing outside the archive file boundaries. The archive file is either truncated or damaged. Please try to repair the file"); // the file offset is beyond the CDR: impossible - return; - } - - if (pFileHeader->nMethod == ZipFile::METHOD_STORE && pFileHeader->desc.lSizeUncompressed != pFileHeader->desc.lSizeCompressed) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_VALIDATION_FAILED, "File with STORE compression method declares its compressed size not matching its uncompressed size. File descriptor is inconsistent, archive content may be damaged, please try to repair the archive"); - return; - } - - FileEntry fileEntry (*pFileHeader, extra); - - if ((m_bEncryptedHeaders || m_nInitMethod >= ZD_INIT_FULL) && pFileHeader->desc.lSizeCompressed) - { - InitDataOffset(fileEntry, pFileHeader); - } - - if (m_bBuildFileEntryMap) - { - m_mapFileEntries.insert (FileEntryMap::value_type(strFilePath, fileEntry)); - } - - if (m_bBuildFileEntryTree) - { - m_treeFileEntries.Add(strFilePath, strUnifiedPath, fileEntry); - } -} - - -////////////////////////////////////////////////////////////////////////// -// initializes the actual data offset in the file in the fileEntry structure -// searches to the local file header, reads it and calculates the actual offset in the file -void ZipDir::CacheFactory::InitDataOffset (FileEntry& fileEntry, const ZipFile::CDRFileHeader* pFileHeader) -{ - // make sure it's the same file and the fileEntry structure is properly initialized - assert (fileEntry.nFileHeaderOffset == pFileHeader->lLocalHeaderOffset); - - /* - // without validation, it would be like this: - ErrorEnum nError = Refresh(&fileEntry); - if (nError != ZD_ERROR_SUCCESS) - THROW_ZIPDIR_ERROR(nError,"Cannot refresh file entry. Probably corrupted file header inside zip file"); - */ - - - if (m_bEncryptedHeaders) - { - // ignore local header - fileEntry.nFileDataOffset = pFileHeader->lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + pFileHeader->nFileNameLength + pFileHeader->nExtraFieldLength; - } - else - { - Seek(pFileHeader->lLocalHeaderOffset); - // read the local file header and the name (for validation) into the buffer - DynArraypBuffer; - unsigned nBufferLength = sizeof(ZipFile::LocalFileHeader) + pFileHeader->nFileNameLength; - pBuffer.resize(nBufferLength); - Read (&pBuffer[0], nBufferLength); - - // validate the local file header (compare with the CDR file header - they should contain basically the same information) - const ZipFile::LocalFileHeader* pLocalFileHeader = (const ZipFile::LocalFileHeader*)&pBuffer[0]; - if (pFileHeader->desc != pLocalFileHeader->desc - || pFileHeader->nMethod != pLocalFileHeader->nMethod - || pFileHeader->nFileNameLength != pLocalFileHeader->nFileNameLength - // for a tough validation, we can compare the timestamps of the local and central directory entries - // but we won't do that for backward compatibility with ZipDir - //|| pFileHeader->nLastModDate != pLocalFileHeader->nLastModDate - //|| pFileHeader->nLastModTime != pLocalFileHeader->nLastModTime - ) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_VALIDATION_FAILED, "The local file header descriptor doesn't match the basic parameters declared in the global file header in the file. The archive content is misconsistent and may be damaged. Please try to repair the archive"); - return; - } - - // now compare the local file name with the one recorded in CDR: they must match. - if (azmemicmp((const char*)&pBuffer[sizeof(ZipFile::LocalFileHeader)], (const char*)pFileHeader + 1, pFileHeader->nFileNameLength)) - { - // either file name, or the extra field do not match - THROW_ZIPDIR_ERROR(ZD_ERROR_VALIDATION_FAILED, "The local file header contains file name which does not match the file name of the global file header. The archive content is misconsistent with its directory. Please repair the archive"); - return; - } - - fileEntry.nFileDataOffset = pFileHeader->lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + pLocalFileHeader->nFileNameLength + pLocalFileHeader->nExtraFieldLength; - } - - if (fileEntry.nFileDataOffset >= m_nCDREndPos) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_VALIDATION_FAILED, "The global file header declares the file which crosses the boundaries of the archive. The archive is either corrupted or truncated, please try to repair it"); - return; - } - - if (m_nInitMethod >= ZD_INIT_VALIDATE) - { - Validate (fileEntry); - } -} - -////////////////////////////////////////////////////////////////////////// -// reads the file pointed by the given header and entry (they must be coherent) -// and decompresses it; then calculates and validates its CRC32 -void ZipDir::CacheFactory::Validate(const FileEntry& fileEntry) -{ - DynArray pBuffer; - // validate the file contents - // allocate memory for both the compressed data and uncompressed data - pBuffer.resize(fileEntry.desc.lSizeCompressed + fileEntry.desc.lSizeUncompressed); - char* pUncompressed = &pBuffer[fileEntry.desc.lSizeCompressed]; - char* pCompressed = &pBuffer[0]; - - assert (fileEntry.nFileDataOffset != FileEntry::INVALID_DATA_OFFSET); - Seek(fileEntry.nFileDataOffset); - - Read(pCompressed, fileEntry.desc.lSizeCompressed); - - if (fileEntry.nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt(pCompressed, fileEntry.desc.lSizeCompressed, m_encryptionKey); - } - - unsigned long nDestSize = fileEntry.desc.lSizeUncompressed; - int nError = Z_OK; - if (fileEntry.nMethod) - { - nError = ZipRawUncompress (pUncompressed, &nDestSize, pCompressed, fileEntry.desc.lSizeCompressed); - } - else - { - assert (fileEntry.desc.lSizeCompressed == fileEntry.desc.lSizeUncompressed); - memcpy (pUncompressed, pCompressed, fileEntry.desc.lSizeUncompressed); - } - switch (nError) - { - case Z_OK: - break; - case Z_MEM_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_NO_MEMORY, "ZLib reported out-of-memory error"); - return; - case Z_BUF_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_CORRUPTED_DATA, "ZLib reported compressed stream buffer error"); - return; - case Z_DATA_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_CORRUPTED_DATA, "ZLib reported compressed stream data error"); - return; - default: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_FAILED, "ZLib reported an unexpected unknown error"); - return; - } - - if (nDestSize != fileEntry.desc.lSizeUncompressed) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_CORRUPTED_DATA, "Uncompressed stream doesn't match the size of uncompressed file stored in the archive file headers"); - return; - } - - uLong uCRC32 = crc32(0L, Z_NULL, 0); - uCRC32 = crc32(uCRC32, (Bytef*)pUncompressed, nDestSize); - if (uCRC32 != fileEntry.desc.lCRC32) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_CRC32_CHECK, "Uncompressed stream CRC32 check failed"); - return; - } -} - - -////////////////////////////////////////////////////////////////////////// -// extracts the file path from the file header with subsequent information -// may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) -// it's the responsibility of the caller to ensure that the file name is in readable valid memory -char* ZipDir::CacheFactory::GetFilePath (const char* pFileName, ZipFile::ushort nFileNameLength) -{ - static char strResult[_MAX_PATH]; - assert(nFileNameLength < _MAX_PATH); - memcpy(strResult, pFileName, nFileNameLength); - strResult[nFileNameLength] = 0; - for (int i = 0; i < nFileNameLength; i++) - { - strResult[i] = ::tolower(strResult[i]); - } - - return strResult; -} - -// seeks in the file relative to the starting position -void ZipDir::CacheFactory::Seek (ZipFile::ulong nPos, int nOrigin) // throw -{ - if (AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(m_f, nPos, nOrigin)) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot fseek() to the new position in the file. This is unexpected error and should not happen under any circumstances. Perhaps some network or disk failure error has caused this"); - return; - } -} - -unsigned long ZipDir::CacheFactory::Tell () // throw -{ - AZ::s64 nPos = AZ_TRAIT_CRYCOMMONTOOLS_FTELL(m_f); - if (nPos == -1) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot ftell() position in the archive. This is unexpected error and should not happen under any circumstances. Perhaps some network or disk failure error has caused this"); - return 0; - } - return (unsigned long)nPos; -} - -void ZipDir::CacheFactory::Read (void* pDest, unsigned nSize) // throw -{ - if (fread (pDest, nSize, 1, m_f) != 1) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot fread() a portion of data from archive"); - } -} - -void ZipDir::CacheFactory::ReadHeaderData (void* pDest, unsigned nSize) // throw -{ - Read(pDest, nSize); - - if (m_bEncryptedHeaders) - { - ZipDir::Decrypt((char*)pDest, nSize, m_encryptionKey); - } -} - diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h deleted file mode 100644 index caf947e1af..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// This is the class that can read the directory from Zip file, -// and store it into the directory cache - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHEFACTORY_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHEFACTORY_H -#pragma once - - -namespace ZipDir -{ - class CacheRW; - TYPEDEF_AUTOPTR(CacheRW); - typedef CacheRW_AutoPtr CacheRWPtr; - - // an instance of this class is temporarily created on stack to initialize the CZipFile instance - class CacheFactory - { - public: - enum - { - // open RW cache in read-only mode - FLAGS_READ_ONLY = 1, - // do not compact RW-cached zip upon destruction - FLAGS_DONT_COMPACT = 1 << 1, - // if this is set, then the zip paths won't be memorized in the cache objects - FLAGS_DONT_MEMORIZE_ZIP_PATH = 1 << 2, - // if this is set, the archive will be created anew (the existing file will be overwritten) - FLAGS_CREATE_NEW = 1 << 3 - }; - - // initializes the internal structures - // nFlags can have FLAGS_READ_ONLY flag, in this case the object will be opened only for reading - CacheFactory (InitMethodEnum nInitMethod, unsigned nFlags = 0); - ~CacheFactory(); - - // the new function creates a new cache - CachePtr New(const char* szFileName, const uint32 decryptionKey[4]);// throw (ErrorEnum); - - CacheRWPtr NewRW(const char* szFileName, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]); - - protected: - // reads the zip file into the file entry tree. - bool ReadCacheRW (CacheRW& rwCache); - - // creates from the m_f file - // reserves the given number of bytes for future expansion of the object - // upon return, pReserve contains the actual number of bytes that were allocated (more might have been allocated) - CachePtr MakeCache (const char* szFile); - - // this sets the window size of the blocks of data read from the end of the file to find the Central Directory Record - // since normally there are no - enum - { - g_nCDRSearchWindowSize = 0x100 - }; - - void Clear(); - - // reads everything and prepares the maps - bool Prepare(); - - // searches for CDREnd record in the given file - bool FindCDREnd();// throw(ErrorEnum); - - // uses the found CDREnd to scan the CDR and probably the Zip file itself - // builds up the m_mapFileEntries - bool BuildFileEntryMap();// throw (ErrorEnum); - - // give the CDR File Header entry, reads the local file header to validate and determine where - // the actual file lies - // This function can actually modify strFilePath and strUnifiedPath variables, make sure you use copies of real paths. - void AddFileEntry (char* strFilePath, char* strUnifiedPath, const ZipFile::CDRFileHeader* pFileHeader, const SExtraZipFileData& extra);// throw (ErrorEnum); - - // extracts the file path from the file header with subsequent information - // may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) - // it's the responsibility of the caller to ensure that the file name is in readable valid memory - char* GetFilePath (const ZipFile::CDRFileHeader* pFileHeader) - { - return GetFilePath((const char*)(pFileHeader + 1), pFileHeader->nFileNameLength); - } - // extracts the file path from the file header with subsequent information - // may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) - // it's the responsibility of the caller to ensure that the file name is in readable valid memory - char* GetFilePath (const ZipFile::LocalFileHeader* pFileHeader) - { - return GetFilePath((const char*)(pFileHeader + 1), pFileHeader->nFileNameLength); - } - // extracts the file path from the file header with subsequent information - // may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) - // it's the responsibility of the caller to ensure that the file name is in readable valid memory - char* GetFilePath (const char* pFileName, ZipFile::ushort nFileNameLength); - - // validates (if the init method has the corresponding value) the given file/header - void Validate(const FileEntry& fileEntry); - - // initializes the actual data offset in the file in the fileEntry structure - // searches to the local file header, reads it and calculates the actual offset in the file - void InitDataOffset (FileEntry& fileEntry, const ZipFile::CDRFileHeader* pFileHeader); - - // seeks in the file relative to the starting position - void Seek (ZipFile::ulong nPos, int nOrigin = SEEK_SET); // throw - unsigned long Tell (); // throw - void Read (void* pDest, unsigned nSize); // throw - void ReadHeaderData (void* pDest, unsigned nSize);// throw - protected: - - FILE* m_f; - InitMethodEnum m_nInitMethod; - unsigned m_nFlags; - ZipFile::CDREnd m_CDREnd; - - unsigned m_nCDREndPos; // position of the CDR End in the file - - // Map: Relative file path => file entry info - typedef std::map FileEntryMap; - FileEntryMap m_mapFileEntries; - - FileEntryTree m_treeFileEntries; - - DynArray m_CDR_buffer; - DynArray m_unifiedNameBuffer; - - EncryptionKey m_encryptionKey; - bool m_bEncryptedHeaders; - bool m_bBuildFileEntryMap; - bool m_bBuildFileEntryTree; - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHEFACTORY_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp deleted file mode 100644 index 6e47aec5d4..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp +++ /dev/null @@ -1,2100 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include "Util.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirList.h" -#include "ZipDirCache.h" -#include "ZipDirCacheRW.h" -#include "ZipDirCacheFactory.h" -#include "ZipDirFindRW.h" - -#include "ThreadUtils.h" - -#include // declaration of Z_OK for ZipRawDecompress -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum PackFileStatus -{ - PACKFILE_COMPRESSED, - - PACKFILE_ADDED, - PACKFILE_UPTODATE, - PACKFILE_SKIPPED, - PACKFILE_MISSING, - PACKFILE_FAILED -}; - -enum PackFileCompressionPolicy -{ - PACKFILE_USE_REQUESTED_COMPRESSOR, - PACKFILE_USE_FASTEST_DECOMPRESSING_CODEC -}; - -class PackFilePool; -struct PackFileBatch -{ - PackFilePool* pool; - - int zipMaxSize; - int sourceMinSize; - int sourceMaxSize; - int compressionMethod; - int compressionLevel; - - PackFileBatch() - : pool(0) - , sourceMinSize(0) - , sourceMaxSize(0) - , zipMaxSize(0) - , compressionMethod(0) - , compressionLevel(0) - { - } -}; - -class PackFilePool; -struct PackFileJob -{ - int index; - int key; - PackFileBatch* batch; - const char* relativePathSrc; - const char* realFilename; - - unsigned int existingCRC; - - void* compressedData; - unsigned long compressedSize; - unsigned long compressedSizePreviously; - - void* uncompressedData; - unsigned long uncompressedSize; - unsigned long uncompressedSizePreviously; - - int64 modTime; - ZipDir::ErrorEnum zdError; - PackFileStatus status; - PackFileCompressionPolicy compressionPolicy; - - PackFileJob() - : index(0) - , key(0) - , batch(0) - , realFilename(0) - , relativePathSrc(0) - , existingCRC(0) - , compressedData(0) - , compressedSize(0) - , compressedSizePreviously(0) - , uncompressedData(0) - , uncompressedSize(0) - , uncompressedSizePreviously(0) - , modTime(0) - , zdError(ZipDir::ZD_ERROR_NOT_IMPLEMENTED) - , status(PACKFILE_FAILED) - , compressionPolicy(PACKFILE_USE_REQUESTED_COMPRESSOR) - { - } - - void DetachUncompressedData() - { - if (uncompressedData && uncompressedData == compressedData) - { - compressedData = 0; - compressedSize = 0; - } - - uncompressedData = 0; - uncompressedSize = 0; - } - - ~PackFileJob() - { - if (compressedData && compressedData != uncompressedData) - { - azfree(compressedData); - compressedData = 0; - } - - if (uncompressedData) - { - azfree(uncompressedData); - uncompressedData = 0; - } - } -}; - - -// --------------------------------------------------------------------------- -static void PackFileFromDisc(PackFileJob* job); -class PackFilePool -{ -public: - PackFilePool(int numFiles, size_t memoryLimit) - : m_pool(false) - , m_skip(false) - , m_awaitedFile(0) - , m_memoryLimit(memoryLimit) - , m_allocatedMemory(0) - { - m_files.reserve(numFiles); - } - - ~PackFilePool() - { - } - - void Submit(int key, const PackFileJob& job) - { - PackFileJob* newJob = new PackFileJob(job); - - // index in queue, and custom key for identification - newJob->index = int(m_files.size()); - newJob->key = key; - - m_files.push_back(newJob); - } - - PackFileJob* WaitForFile(int index) - { - while (true) - { - { - AZStd::lock_guard lock(m_filesLock); - m_awaitedFile = index; - if (size_t(index) >= m_files.size()) - { - return 0; - } - if (m_files[index]) - { - return m_files[index]; - } - } - Sleep(0); - } - - assert(0); - return 0; - } - - void Start(unsigned numExtraThreads) - { - if (numExtraThreads == 0) - { - for (PackFileJob* job : m_files) - { - PackFileFromDisc(job); - } - } - else - { - for (size_t i = 0; i < m_files.size(); ++i) - { - PackFileJob* job = m_files[i]; - m_files[i] = 0; - m_pool.Submit(&ProcessFile, job); - } - - m_pool.Start(numExtraThreads); - } - } - - size_t GetJobCount() const - { - return m_files.size(); - } - - void SkipPendingFiles() - { - m_skip = true; - } - - void ReleaseFile(int index) - { - assert(m_files[index] != 0); - if (m_files[index]) - { - if (m_memoryLimit != 0) - { - AZStd::lock_guard lock(m_filesLock); - - m_allocatedMemory -= m_files[index]->uncompressedSize; - m_allocatedMemory -= m_files[index]->compressedSize; - } - - delete m_files[index]; - m_files[index] = 0; - } - } - -private: - - // called from non-main thread - static void ProcessFile(PackFileJob* job) - { - PackFilePool* self = job->batch->pool; - - if (!self->m_skip) - { - if (self->m_memoryLimit != 0) - { - while (true) - { - size_t allocatedMemory = 0; - int awaitedFile = 0; - { - AZStd::lock_guard lock(self->m_filesLock); - allocatedMemory = self->m_allocatedMemory; - awaitedFile = self->m_awaitedFile; - } - - if (allocatedMemory > self->m_memoryLimit && job->index > awaitedFile + 1) - { - Sleep(10); // give time to main thread to write data to file - } - else - { - break; - } - } - } - - PackFileFromDisc(job); - } - - self->FileCompleted(job); - } - - // called from non-main thread - void FileCompleted(PackFileJob* job) - { - AZStd::lock_guard lock(m_filesLock); - - assert(job); - assert(job->index < m_files.size()); - assert(m_files[job->index] == 0); - m_files[job->index] = job; - - if (m_memoryLimit != 0) - { - m_allocatedMemory += job->uncompressedSize; - m_allocatedMemory += job->compressedSize; - } - } - - size_t m_memoryLimit; - - AZStd::mutex m_filesLock; - std::vector m_files; - int m_awaitedFile; - size_t m_allocatedMemory; - bool m_skip; - - ThreadUtils::SimpleThreadPool m_pool; -}; - -////////////////////////////////////////////////////////////////////////// -static size_t AlignTo(size_t offset, size_t alignment) -{ - const size_t remainder = offset % alignment; - return remainder ? offset + alignment - remainder : offset; -} -////////////////////////////////////////////////////////////////////////// -// Calculates new offset of the header to make sure that following data are -// aligned properly -static size_t CalculateAlignedHeaderOffset(const char* fileName, size_t currentOffset, size_t alignment) -{ - // Since file should start from header - if (currentOffset == 0) - { - return 0; - } - - // Local header is followed by filename - const size_t totalHeaderSize = sizeof(ZipFile::LocalFileHeader) + strlen(fileName); - - // Align end of the header - const size_t dataOffset = AlignTo(currentOffset + totalHeaderSize, alignment); - - return dataOffset - totalHeaderSize; -} - -////////////////////////////////////////////////////////////////////////// -ZipDir::CacheRW::CacheRW(bool encryptHeaders, const EncryptionKey& encryptionKey) - : m_pFile (NULL) - , m_nFlags (0) - , m_lCDROffset (0) - , m_fileAlignment (1) - , m_bEncryptedHeaders(encryptHeaders) - , m_bHeadersEncryptedOnClose(encryptHeaders) - , m_encryptionKey(encryptionKey) -{ - m_nRefCount = 0; -} -////////////////////////////////////////////////////////////////////////// -ZipDir::CacheRW::~CacheRW() -{ - Close(); -} -////////////////////////////////////////////////////////////////////////// -void ZipDir::CacheRW::AddRef() -{ - ++m_nRefCount; -} - -////////////////////////////////////////////////////////////////////////// -void ZipDir::CacheRW::Release() -{ - if (--m_nRefCount <= 0) - { - delete this; - } -} - -void ZipDir::CacheRW::Close() -{ - if (m_pFile) - { - if (!(m_nFlags & FLAGS_READ_ONLY)) - { - if ((m_nFlags & FLAGS_UNCOMPACTED) && !(m_nFlags & FLAGS_DONT_COMPACT)) - { - if (!RelinkZip()) - { - WriteCDR(); - } - } - else - if (m_nFlags & FLAGS_CDR_DIRTY) - { - WriteCDR(); - } - } - - if (m_pFile) // RelinkZip() might have closed the file - { - fclose (m_pFile); - } - - m_pFile = NULL; - } - m_treeDir.Clear(); -} - -////////////////////////////////////////////////////////////////////////// -char* ZipDir::CacheRW::UnifyPath(char* const str, const char* pPath) -{ - assert(str); - const char* src = pPath; - char* trg = str; - while (*src) - { - if (*src != '/') - { - *trg++ = ::tolower(*src++); - } - else - { - *trg++ = '\\'; - src++; - } - } - *trg = 0; - return str; -} - -////////////////////////////////////////////////////////////////////////// -char* ZipDir::CacheRW::ToUnixPath(char* const str, const char* pPath) -{ - assert(str); - const char* src = pPath; - char* trg = str; - while (*src) - { - if (*src != '/') - { - *trg++ = *src++; - } - else - { - *trg++ = '\\'; - src++; - } - } - *trg = 0; - return str; -} - -////////////////////////////////////////////////////////////////////////// -char* ZipDir::CacheRW::AllocPath(const char* pPath) -{ - char str[_MAX_PATH]; - char* temp = ToUnixPath(str, pPath); - temp = m_tempStringPool.Append(temp, strlen(temp)); - return temp; -} - -static bool UseZlibForFileType(const char* filename) -{ - AZStd::string f(filename); - - //some files types are forced to use zlib - bool found = AzFramework::StringFunc::Path::IsExtension(filename, ".dds") || f.find("cover.ctc") != string::npos || AzFramework::StringFunc::Path::IsExtension(filename, ".uicanvas"); - - return found; -} - -#ifdef AZ_DEBUG_BUILD -static const char* CodecAsString(CompressionCodec::Codec codec) -{ - switch (codec) - { - case CompressionCodec::Codec::ZLIB: - return "ZLIB"; - case CompressionCodec::Codec::ZSTD: - return "ZSTD"; - case CompressionCodec::Codec::LZ4: - return "LZ4"; - } - return "ERROR"; -} -#endif - -static bool CompressData(PackFileJob *job) -{ - bool bUseZlib = UseZlibForFileType(job->relativePathSrc) || (job->compressionPolicy == PACKFILE_USE_REQUESTED_COMPRESSOR); - - bool compressionSuccessful = true; - - if (bUseZlib) - { - job->compressedSize = ZipDir::GetCompressedSizeEstimate(job->uncompressedSize,CompressionCodec::Codec::ZLIB); - job->compressedData = azmalloc(job->compressedSize); - int error = ZipDir::ZipRawCompress(job->uncompressedData, &job->compressedSize, job->compressedData, job->uncompressedSize, job->batch->compressionLevel); - if (error == Z_OK) - { - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - } - else - { - compressionSuccessful = false; - } - } - else - { - unsigned long compressedSize[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - void* compressedData[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - std::chrono::milliseconds decompressionTime[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - bool compressionCodecWasSuccessful[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - - std::chrono::time_point start; - - //do compression - for (CompressionCodec::Codec codec : CompressionCodec::s_AllCodecs) - { - unsigned int index = static_cast(codec); - compressedSize[index] = ZipDir::GetCompressedSizeEstimate(job->uncompressedSize, codec); - compressedData[index] = azmalloc(compressedSize[index]); - AZStd::unique_ptr tempBuffer; - unsigned long tempSize = 0; - - //some files decompress so fast they are beyond our ability to measure so we need to do it a few times to get a reading - int numTimesToDecompress = 1 + ZipDir::TARGET_MIN_TEST_COMPRESS_BYTES / job->uncompressedSize; - - auto testDecompressionTime = [&tempSize, job, &tempBuffer, &start, &compressionCodecWasSuccessful, index, numTimesToDecompress, &compressedData, &compressedSize, &decompressionTime]() { - tempSize = job->uncompressedSize; - tempBuffer = AZStd::make_unique(tempSize); - start = std::chrono::high_resolution_clock::now(); - - //start by assuming the decompression test is never going to result in an error - compressionCodecWasSuccessful[index] = true; - - for (int i = 0; i < numTimesToDecompress; i++) - { - int zerror = ZipDir::ZipRawUncompress(tempBuffer.get(), &tempSize, compressedData[index], compressedSize[index]); - if (zerror != Z_OK) - { - compressionCodecWasSuccessful[index] = false; - break; - } - } - decompressionTime[index] = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - start); - }; - - switch (codec) - { - case CompressionCodec::Codec::ZLIB: - if (ZipDir::ZipRawCompress(job->uncompressedData, &compressedSize[index], compressedData[index], job->uncompressedSize, job->batch->compressionLevel) == Z_OK) - { - testDecompressionTime(); - } - else - { - compressionCodecWasSuccessful[index] = false; - } - break; - - case CompressionCodec::Codec::ZSTD: - if (ZipDir::ZipRawCompressZSTD(job->uncompressedData, &compressedSize[index], compressedData[index], job->uncompressedSize, 1) == Z_OK) - { - testDecompressionTime(); - } - else - { - compressionCodecWasSuccessful[index] = false; - } - break; - - case CompressionCodec::Codec::LZ4: - if (ZipDir::ZipRawCompressLZ4(job->uncompressedData, &compressedSize[index], compressedData[index], job->uncompressedSize, job->batch->compressionLevel) == Z_OK) - { - testDecompressionTime(); - } - else - { - compressionCodecWasSuccessful[index] = false; - } - - break; - - default: - break; - } - } - - //check decompression speed - int bestTimeIndex = -1; - int numberOfSuccessfulCodecs = 0; - for (CompressionCodec::Codec codec : CompressionCodec::s_AllCodecs) - { - int index = static_cast(codec); - if (compressionCodecWasSuccessful[index]) - { - numberOfSuccessfulCodecs++; - if (bestTimeIndex == -1) - { - bestTimeIndex = index; - continue; - } - if ((decompressionTime[index] < decompressionTime[bestTimeIndex])) - { - bestTimeIndex = index; - } - } - } - - if (!numberOfSuccessfulCodecs) - { - AZ_Error("ZipDirCacheRW", false, "None of the available codecs were able to compress the file: %s", job->relativePathSrc); - compressionSuccessful = false; - } - else - { -#ifdef AZ_DEBUG_BUILD - AZ_Printf("ZipDirCacheRW", "Winner for %s is %s with: %d ms ", job->realFilename, CodecAsString(static_cast(bestTimeIndex)), decompressionTime[bestTimeIndex]); -#endif - } - - //get rid of losing data - for (CompressionCodec::Codec codec : CompressionCodec::s_AllCodecs) - { - int index = static_cast(codec); - if (index != bestTimeIndex) - { - azfree(compressedData[index]); - compressedData[index] = nullptr; - } - } - - if (compressionSuccessful) - { - job->compressedSize = compressedSize[bestTimeIndex]; - job->compressedData = compressedData[bestTimeIndex]; - } - } - - //if there was a problem with the compression so just store the file - if (!compressionSuccessful) - { - azfree(job->compressedData); - job->compressedData = job->uncompressedData; - job->compressedSize = job->uncompressedSize; - } - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - return true; -} - -static void PackFileFromMemory(PackFileJob* job) -{ - if (job->existingCRC != 0) - { - unsigned int crcCode = (unsigned int)crc32(0, (unsigned char*)job->uncompressedData, job->uncompressedSize); - if (crcCode == job->existingCRC) - { - job->compressedData = 0; - job->compressedSize = 0; - job->status = PACKFILE_UPTODATE; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - // This file with same data already in pak, skip it. - return; - } - } - - switch (job->batch->compressionMethod) - { - case ZipFile::METHOD_DEFLATE_AND_ENCRYPT: - case ZipFile::METHOD_DEFLATE: - { - // allocate memory for compression. Min is nSize * 1.001 + 12 - if (job->uncompressedSize > 0) - { - CompressData(job); - } - else - { - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - - job->compressedSize = 0; - job->compressedData = 0; - } - break; - } - case ZipFile::METHOD_STORE: - job->compressedData = job->uncompressedData; - job->compressedSize = job->uncompressedSize; - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - break; - - default: - job->status = PACKFILE_FAILED; - job->zdError = ZipDir::ZD_ERROR_UNSUPPORTED; - break; - } -} - -bool ZipDir::CacheRW::WriteCompressedData(const char* data, size_t size, bool encrypt, FILE* file) -{ - if (size <= 0) - { - return true; - } - - std::vector buffer; - if (encrypt) - { - buffer.resize(size); - memcpy(&buffer[0], data, size); - ZipDir::Encrypt(&buffer[0], size, m_encryptionKey); - data = &buffer[0]; - } - - // Danny - writing a single large chunk (more than 6MB?) causes - // Windows fwrite to (silently?!) fail. So we're writing data - // in small chunks. - while (size > 0) - { - const size_t sizeToWrite = Util::getMin(size, size_t(1024 * 1024)); - if (fwrite(data, sizeToWrite, 1, file) != 1) - { - return false; - } - data += sizeToWrite; - size -= sizeToWrite; - } - - return true; -} - -static bool WriteRandomData(FILE* file, size_t size) -{ - if (size <= 0) - { - return true; - } - - const size_t bufferSize = Util::getMin(size, size_t(1024 * 1024)); - std::vector buffer(bufferSize); - - while (size > 0) - { - const size_t sizeToWrite = Util::getMin(size, bufferSize); - - for (size_t i = 0; i < sizeToWrite; ++i) - { - buffer[i] = rand() & 0xff; - } - - if (fwrite(&buffer[0], sizeToWrite, 1, file) != 1) - { - return false; - } - - size -= sizeToWrite; - } - - return true; -} - -bool ZipDir::CacheRW::WriteNullData(size_t size) -{ - if (size <= 0) - { - return true; - } - - const size_t bufferSize = Util::getMin(size, size_t(1024 * 1024)); - std::vector buffer(bufferSize, 0); - - while (size > 0) - { - const size_t sizeToWrite = Util::getMin(size, bufferSize); - - if (fwrite(&buffer[0], sizeToWrite, 1, m_pFile) != 1) - { - return false; - } - - size -= sizeToWrite; - } - - return true; -} - -void ZipDir::CacheRW::StorePackedFile(PackFileJob* job) -{ - if (job->batch->zipMaxSize > 0 && GetTotalFileSize() > job->batch->zipMaxSize) - { - job->status = PACKFILE_SKIPPED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - return; - } - - job->status = PACKFILE_FAILED; - - char str[_MAX_PATH]; - char* relativePath = UnifyPath(str, job->relativePathSrc); - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(job->relativePathSrc), AllocPath(relativePath)); - - if (!pFileEntry) - { - job->zdError = ZipDir::ZD_ERROR_INVALID_PATH; - return; - } - - pFileEntry->OnNewFileData(job->uncompressedData, job->uncompressedSize, - job->compressedSize, job->batch->compressionMethod, false); - pFileEntry->SetFromFileTimeNTFS(job->modTime); - - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - // the new CDR position, if the operation completes successfully - unsigned lNewCDROffset = m_lCDROffset; - - if (pFileEntry->IsInitialized()) - { - // this file entry is already allocated in CDR - - // check if the new compressed data fits into the old place - unsigned nFreeSpace = pFileEntry->nEOFOffset - pFileEntry->nFileHeaderOffset - (unsigned)sizeof(ZipFile::LocalFileHeader) - (unsigned)strlen(relativePath); - - if (nFreeSpace != job->compressedSize) - { - m_nFlags |= FLAGS_UNCOMPACTED; - } - - if (nFreeSpace >= job->compressedSize) - { - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); - if (e != ZipDir::ZD_ERROR_SUCCESS) - { - job->zdError = e; - return; - } - } - else - { - // we need to write the file anew - in place of current CDR - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(job->relativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); - lNewCDROffset = pFileEntry->nEOFOffset; - if (e != ZipDir::ZD_ERROR_SUCCESS) - { - job->zdError = e; - return; - } - } - } - else - { - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(job->relativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); - if (e != ZipDir::ZD_ERROR_SUCCESS) - { - job->zdError = e; - return; - } - - lNewCDROffset = pFileEntry->nFileDataOffset + job->compressedSize; - - m_nFlags |= FLAGS_CDR_DIRTY; - } - - // now we have the fresh local header and data offset - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - job->zdError = ZD_ERROR_IO_FAILED; - return; - } - - const bool encrypt = pFileEntry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - - if (!WriteCompressedData((char*)job->compressedData, job->compressedSize, encrypt, m_pFile)) - { - job->zdError = ZD_ERROR_IO_FAILED; - return; - } - - // since we wrote the file successfully, update the new CDR position - m_lCDROffset = lNewCDROffset; - pFileEntry.Commit(); - - job->status = PACKFILE_ADDED; - job->zdError = ZD_ERROR_SUCCESS; -} - -// Adds a new file to the zip or update an existing one -// adds a directory (creates several nested directories if needed) -ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFile (const char* szRelativePathSrc, void* pUncompressed, unsigned nSize, - unsigned nCompressionMethod, int nCompressionLevel, int64 modTime) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - - PackFileBatch batch; - batch.compressionMethod = nCompressionMethod; - batch.compressionLevel = nCompressionLevel; - - PackFileJob job; - job.relativePathSrc = szRelativePathSrc; - job.modTime = modTime; - job.uncompressedData = pUncompressed; - job.uncompressedSize = nSize; - job.batch = &batch; - - // crc will be used to check if this file need to be updated at all - ZipDir::FileEntry* entry = FindFile(szRelativePath); - if (entry) - { - job.existingCRC = entry->desc.lCRC32; - } - - PackFileFromMemory(&job); - - switch (job.status) - { - case PACKFILE_SKIPPED: - case PACKFILE_MISSING: - case PACKFILE_FAILED: - return ZD_ERROR_IO_FAILED; - } - - StorePackedFile(&job); - job.DetachUncompressedData(); - return job.zdError; -} - -static FILETIME GetFileWriteTimeAndSize(uint64* fileSize, const char* filename) -{ - // Warning: FindFirstFile on NTFS may report file size that - // is not up-to-date with the actual file content. - // http://blogs.msdn.com/b/oldnewthing/archive/2011/12/26/10251026.aspx - - FILETIME fileTime; - -#if defined(AZ_PLATFORM_WINDOWS) - WIN32_FIND_DATAA FindFileData; - HANDLE hFind = FindFirstFileA(filename, &FindFileData); - - if (hFind == INVALID_HANDLE_VALUE) - { - fileTime.dwLowDateTime = 0; - fileTime.dwHighDateTime = 0; - if (fileSize) - { - *fileSize = 0; - } - } - else - { - fileTime.dwLowDateTime = FindFileData.ftLastWriteTime.dwLowDateTime; - fileTime.dwHighDateTime = FindFileData.ftLastWriteTime.dwHighDateTime; - if (fileSize) - { - *fileSize = (uint64(FindFileData.nFileSizeHigh) << 32) + FindFileData.nFileSizeLow; - } - FindClose(hFind); - } -#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) - //We cant use this implmentation for the windows version because ModificationTime - //returns the time filename was changed(ChangeTime) not last written into(LastWriteTime). - //If LocalFileIO ever adds support for LastWriteTime we can have a common implementation. - AZ::IO::LocalFileIO localFileIO; - AZ::u64 modTime = 0; - modTime = localFileIO.ModificationTime(filename); - if(modTime != 0) - { - fileTime.dwHighDateTime = modTime >> 32; - fileTime.dwLowDateTime = modTime & 0xFFFFFFFF; - if (fileSize) - { - localFileIO.Size(filename, *fileSize); - } - } -#else -#error Needs implmentation! -#endif - return fileTime; -} -static void PackFileFromDisc(PackFileJob* job) -{ - const FILETIME ft = GetFileWriteTimeAndSize(0, job->realFilename); - LARGE_INTEGER lt; - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - job->modTime = lt.QuadPart; - - FILE* f = nullptr; - azfopen(&f, job->realFilename, "rb"); - if (!f) - { - job->status = PACKFILE_FAILED; - job->zdError = ZipDir::ZD_ERROR_FILE_NOT_FOUND; - return; - } - - fseek(f, 0, SEEK_END); - size_t fileSize = (size_t)ftell(f); - - if ((fileSize < job->batch->sourceMinSize) || (job->batch->sourceMaxSize > 0 && fileSize > job->batch->sourceMaxSize)) - { - fclose(f); - - job->status = PACKFILE_SKIPPED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - return; - } - - if (!fileSize) - { - //Allow 0-Bytes long files. - job->uncompressedData = nullptr; - } - else - { - job->uncompressedData = azmalloc(fileSize); - - fseek(f, 0, SEEK_SET); - if (fread(job->uncompressedData, 1, fileSize, f) != fileSize) - { - azfree(job->uncompressedData); - job->uncompressedData = 0; - fclose(f); - - job->status = PACKFILE_FAILED; - job->zdError = ZipDir::ZD_ERROR_IO_FAILED; - return; - } - } - fclose(f); - job->uncompressedSize = fileSize; - - PackFileFromMemory(job); -} - -bool ZipDir::CacheRW::UpdateMultipleFiles(const char** realFilenames, const char** filenamesInZip, size_t fileCount, - int compressionLevel, bool encryptContent, size_t zipMaxSize, int sourceMinSize, int sourceMaxSize, - unsigned numExtraThreads, ZipDir::IReporter* reporter, ZipDir::ISplitter* splitter, bool useFastestDecompressionCodec) -{ - int compressionMethod = ZipFile::METHOD_DEFLATE; - if (encryptContent) - { - compressionMethod = ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - } - else if (compressionLevel == 0) - { - compressionMethod = ZipFile::METHOD_STORE; - } - - uint64 totalSize = 0; - - clock_t startTime = clock(); - - PackFileBatch batch; - batch.compressionLevel = compressionLevel; - batch.compressionMethod = compressionMethod; - batch.sourceMinSize = sourceMinSize; - batch.sourceMaxSize = sourceMaxSize; - batch.zipMaxSize = zipMaxSize; - - const size_t memoryLimit = 1024 * 1024 * 1024; // prevents threads from generating more than 1GB of data - PackFilePool pool(fileCount, memoryLimit); - batch.pool = &pool; - - for (int i = 0; i < fileCount; ++i) - { - const char* realFilename = realFilenames[i]; - const char* filenameInZip = filenamesInZip[i]; - - PackFileJob job; - - job.relativePathSrc = filenameInZip; - job.realFilename = realFilename; - job.batch = &batch; - job.compressionPolicy = useFastestDecompressionCodec ? PACKFILE_USE_FASTEST_DECOMPRESSING_CODEC : PACKFILE_USE_REQUESTED_COMPRESSOR; - - { - // crc will be used to check if this file need to be updated at all - ZipDir::FileEntry* entry = FindFile(filenameInZip); - if (entry) - { - uint64 fileSize = 0; - - const FILETIME ft = GetFileWriteTimeAndSize(&fileSize, realFilename); - LARGE_INTEGER lt; - - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - job.modTime = lt.QuadPart; - job.existingCRC = entry->desc.lCRC32; - job.compressedSizePreviously = entry->desc.lSizeCompressed; - job.uncompressedSizePreviously = entry->desc.lSizeUncompressed; - - // Check if file with the same name, timestamp and size already exists in pak. - if (entry->CompareFileTimeNTFS(job.modTime) && fileSize == entry->desc.lSizeUncompressed) - { - if (reporter) - { - reporter->ReportUpToDate(filenameInZip); - } - continue; - } - } - } - - pool.Submit(i, job); - } - - // Get the number of submitted jobs, which is at most - // as large as the largest successfully submitted file-index. - // Any number of files can be skipped for submission. - const int jobCount = pool.GetJobCount(); - if (jobCount == 0) - { - return true; - } - - pool.Start(numExtraThreads); - - for (int i = 0; i < jobCount; ++i) - { - PackFileJob* job = pool.WaitForFile(i); - if (!job) - { - assert(job); - continue; - } - - if (job->status == PACKFILE_COMPRESSED) - { - if (splitter) - { - size_t dsk = GetTotalFileSizeOnDiskSoFar(); - size_t bse = 0; - size_t add = 0; - size_t sub = 0; - - bse += sizeof(ZipFile::CDRFileHeader) + strlen(job->relativePathSrc); - bse += sizeof(ZipFile::LocalFileHeader) + strlen(job->relativePathSrc); - - if (job->compressedSize) - { - add += bse + job->compressedSize; - } - if (job->compressedSizePreviously) - { - sub += bse + job->compressedSizePreviously; - } - - if (splitter->CheckWriteLimit(dsk, add, sub)) - { - splitter->SetLastFile(dsk, add, sub, job->key - 1); - - // deplete the pool before leaving the loop - pool.SkipPendingFiles(); - for (; i < jobCount; ++i) - { - pool.WaitForFile(i); - pool.ReleaseFile(i); - } - - break; - } - } - - StorePackedFile(job); - } - - switch (job->status) - { - case PACKFILE_ADDED: - if (reporter) - { - reporter->ReportAdded(job->relativePathSrc); - } - - totalSize += job->uncompressedSize; - break; - case PACKFILE_MISSING: - if (reporter) - { - reporter->ReportMissing(job->realFilename); - } - break; - case PACKFILE_UPTODATE: - if (reporter) - { - reporter->ReportUpToDate(job->realFilename); - } - break; - case PACKFILE_SKIPPED: - if (reporter) - { - reporter->ReportSkipped(job->realFilename); - } - break; - default: - if (reporter) - { - reporter->ReportFailed(job->realFilename, ""); // TODO reason - } - break; - } - - pool.ReleaseFile(i); - } - - clock_t endTime = clock(); - double timeSeconds = double(endTime - startTime) / CLOCKS_PER_SEC; - double speed = (endTime - startTime) == 0 ? 0.0 : double(totalSize) / timeSeconds; - - if (reporter) - { - reporter->ReportSpeed(speed); - } - - return true; -} - - -// Adds a new file to the zip or update an existing one if it is not compressed - just stored - start a big file -ZipDir::ErrorEnum ZipDir::CacheRW::StartContinuousFileUpdate(const char* szRelativePathSrc, unsigned nSize) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - SmartPtr pBufferDestroyer; - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); - - if (!pFileEntry) - { - return ZD_ERROR_INVALID_PATH; - } - - pFileEntry->OnNewFileData (NULL, nSize, nSize, ZipFile::METHOD_STORE, false); - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - // the new CDR position, if the operation completes successfully - unsigned lNewCDROffset = m_lCDROffset; - if (pFileEntry->IsInitialized()) - { - // check if the new compressed data fits into the old place - unsigned nFreeSpace = pFileEntry->nEOFOffset - pFileEntry->nFileHeaderOffset - (unsigned)sizeof(ZipFile::LocalFileHeader) - (unsigned)strlen(szRelativePath); - - if (nFreeSpace != nSize) - { - m_nFlags |= FLAGS_UNCOMPACTED; - } - - if (nFreeSpace >= nSize) - { - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - } - else - { - // we need to write the file anew - in place of current CDR - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(szRelativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); - lNewCDROffset = pFileEntry->nEOFOffset; - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - } - } - else - { - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(szRelativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - - lNewCDROffset = pFileEntry->nFileDataOffset + nSize; - - m_nFlags |= FLAGS_CDR_DIRTY; - } - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - if (!WriteNullData(nSize)) - { - return ZD_ERROR_IO_FAILED; - } - - pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset; - - // since we wrote the file successfully, update the new CDR position - m_lCDROffset = lNewCDROffset; - pFileEntry.Commit(); - - return ZD_ERROR_SUCCESS; -} - -// Adds a new file to the zip or update an existing's segment if it is not compressed - just stored -// adds a directory (creates several nested directories if needed) -ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFileContinuousSegment (const char* szRelativePathSrc, [[maybe_unused]] unsigned nSize, void* pUncompressed, unsigned nSegmentSize, unsigned nOverwriteSeekPos) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - SmartPtr pBufferDestroyer; - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); - - if (!pFileEntry) - { - return ZD_ERROR_INVALID_PATH; - } - - pFileEntry->OnNewFileData (pUncompressed, nSegmentSize, nSegmentSize, ZipFile::METHOD_STORE, true); - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - // this file entry is already allocated in CDR - unsigned lSegmentOffset = pFileEntry->nEOFOffset; - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePath, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - - if (nOverwriteSeekPos != 0xffffffff) - { - lSegmentOffset = pFileEntry->nFileDataOffset + nOverwriteSeekPos; - } - - // now we have the fresh local header and data offset -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)lSegmentOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, lSegmentOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - const bool encrypt = false; // encryption is not supported for continous updates - if (!WriteCompressedData((char*)pUncompressed, nSegmentSize, encrypt, m_pFile)) - { - return ZD_ERROR_IO_FAILED; - } - - if (nOverwriteSeekPos == 0xffffffff) - { - pFileEntry->nEOFOffset = lSegmentOffset + nSegmentSize; - } - - // since we wrote the file successfully, update CDR - pFileEntry.Commit(); - return ZD_ERROR_SUCCESS; -} - - -ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFileCRC (const char* szRelativePathSrc, unsigned dwCRC32) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - SmartPtr pBufferDestroyer; - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); - - if (!pFileEntry) - { - return ZD_ERROR_INVALID_PATH; - } - - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - pFileEntry->desc.lCRC32 = dwCRC32; - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePath, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - - // since we wrote the file successfully, update - pFileEntry.Commit(); - return ZD_ERROR_SUCCESS; -} - - -// deletes the file from the archive -ZipDir::ErrorEnum ZipDir::CacheRW::RemoveFile (const char* szRelativePathSrc) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - // find the last slash in the path - const char* pSlash = (std::max)(strrchr(szRelativePath, '/'), strrchr(szRelativePath, '\\')); - - const char* pFileName; // the name of the file to delete - - FileEntryTree* pDir; // the dir from which the subdir will be deleted - - if (pSlash) - { - FindDirRW fd (GetRoot()); - // the directory to remove - pDir = fd.FindExact(string (szRelativePath, pSlash - szRelativePath).c_str()); - if (!pDir) - { - return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory - } - pFileName = pSlash + 1; - } - else - { - pDir = GetRoot(); - pFileName = szRelativePath; - } - - ErrorEnum e = pDir->RemoveFile (pFileName); - if (e == ZD_ERROR_SUCCESS) - { - m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; - } - return e; -} - - -// deletes the directory, with all its descendants (files and subdirs) -ZipDir::ErrorEnum ZipDir::CacheRW::RemoveDir (const char* szRelativePathSrc) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - // find the last slash in the path - const char* pSlash = (std::max)(strrchr(szRelativePath, '/'), strrchr(szRelativePath, '\\')); - - const char* pDirName; // the name of the dir to delete - - FileEntryTree* pDir; // the dir from which the subdir will be deleted - - if (pSlash) - { - FindDirRW fd (GetRoot()); - // the directory to remove - pDir = fd.FindExact(string (szRelativePath, pSlash - szRelativePath).c_str()); - if (!pDir) - { - return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory - } - pDirName = pSlash + 1; - } - else - { - pDir = GetRoot(); - pDirName = szRelativePath; - } - - ErrorEnum e = pDir->RemoveDir (pDirName); - if (e == ZD_ERROR_SUCCESS) - { - m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; - } - return e; -} - -// deletes all files and directories in this archive -ZipDir::ErrorEnum ZipDir::CacheRW::RemoveAll() -{ - ErrorEnum e = m_treeDir.RemoveAll(); - if (e == ZD_ERROR_SUCCESS) - { - m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; - } - return e; -} - -ZipDir::ErrorEnum ZipDir::CacheRW::ReadFile (FileEntry* pFileEntry, void* pCompressed, void* pUncompressed) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->desc.lSizeUncompressed == 0) - { - assert (pFileEntry->desc.lSizeCompressed == 0); - return ZD_ERROR_SUCCESS; - } - - assert (pFileEntry->desc.lSizeCompressed > 0); - - ErrorEnum nError = Refresh(pFileEntry); - if (nError != ZD_ERROR_SUCCESS) - { - return nError; - } - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET)) -#else - if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET)) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - SmartPtr pBufferDestroyer; - - void* pBuffer = pCompressed; // the buffer where the compressed data will go - - if (pFileEntry->nMethod == 0 && pUncompressed) - { - // we can directly read into the uncompress buffer - pBuffer = pUncompressed; - } - - if (!pBuffer) - { - if (!pUncompressed) - { - // what's the sense of it - no buffers at all? - return ZD_ERROR_INVALID_CALL; - } - - pBuffer = azmalloc(pFileEntry->desc.lSizeCompressed); - pBufferDestroyer.Attach(pBuffer); // we want it auto-freed once we return - } - - if (fread((char*)pBuffer, pFileEntry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return ZD_ERROR_IO_FAILED; - } - - if (pFileEntry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pBuffer, pFileEntry->desc.lSizeCompressed, m_encryptionKey); - } - - // if there's a buffer for uncompressed data, uncompress it to that buffer - if (pUncompressed) - { - if (pFileEntry->nMethod == 0) - { - assert (pBuffer == pUncompressed); - //assert (pFileEntry->nSizeCompressed == pFileEntry->nSizeUncompressed); - //memcpy (pUncompressed, pBuffer, pFileEntry->nSizeCompressed); - } - else - { - unsigned long nSizeUncompressed = pFileEntry->desc.lSizeUncompressed; - if (nSizeUncompressed > 0) - { - if (Z_OK != ZipRawUncompress(pUncompressed, &nSizeUncompressed, pBuffer, pFileEntry->desc.lSizeCompressed)) - { - return ZD_ERROR_CORRUPTED_DATA; - } - } - } - } - - return ZD_ERROR_SUCCESS; -} - - -////////////////////////////////////////////////////////////////////////// -// finds the file by exact path -ZipDir::FileEntry* ZipDir::CacheRW::FindFile (const char* szPathSrc, [[maybe_unused]] bool bFullInfo) -{ - char str[_MAX_PATH]; - char* szPath = UnifyPath(str, szPathSrc); - - ZipDir::FindFileRW fd (GetRoot()); - if (!fd.FindExact(szPath)) - { - assert (!fd.GetFileEntry()); - return NULL; - } - assert (fd.GetFileEntry()); - return fd.GetFileEntry(); -} - -// returns the size of memory occupied by the instance referred to by this cache -size_t ZipDir::CacheRW::GetSize() const -{ - return sizeof(*this) + m_strFilePath.capacity() + m_treeDir.GetSize() - sizeof(m_treeDir); -} - -// returns the compressed size of all the entries -size_t ZipDir::CacheRW::GetCompressedSize() const -{ - return m_treeDir.GetCompressedFileSize(); -} - -// returns the total size of memory occupied by the instance of this cache and all the compressed files -size_t ZipDir::CacheRW::GetTotalFileSize() const -{ - return GetSize() + GetCompressedSize(); -} - -// returns the total size of space occupied on disk by the instance of this cache and all the compressed files -size_t ZipDir::CacheRW::GetTotalFileSizeOnDiskSoFar() -{ - FileRecordList arrFiles(GetRoot()); - FileRecordList::ZipStats statFiles = arrFiles.GetStats(); - - return m_lCDROffset + statFiles.nSizeCDR; -} - -// refreshes information about the given file entry into this file entry -ZipDir::ErrorEnum ZipDir::CacheRW::Refresh (FileEntry* pFileEntry) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) - { - return ZD_ERROR_SUCCESS; // the data offset has been successfully read.. - } - - return ZipDir::Refresh(m_pFile, pFileEntry, m_bEncryptedHeaders); -} - - -// writes the CDR to the disk -bool ZipDir::CacheRW::WriteCDR(FILE* fTarget, bool encryptCDR) -{ - if (!fTarget) - { - return false; - } - -#ifdef WIN32 - if (_fseeki64(fTarget, (__int64)m_lCDROffset, SEEK_SET)) -#else - if (fseek(fTarget, m_lCDROffset, SEEK_SET)) -#endif - { - return false; - } - - FileRecordList arrFiles(GetRoot()); - //arrFiles.SortByFileOffset(); - size_t nSizeCDR = arrFiles.GetStats().nSizeCDR; - void* pCDR = malloc(nSizeCDR); -#if !defined(NDEBUG) - size_t nSizeCDRSerialized = -#endif - arrFiles.MakeZipCDR(m_lCDROffset, pCDR, encryptCDR); - assert (nSizeCDRSerialized == nSizeCDR); - - if (encryptCDR) - { - // We do not encrypt CDREnd, so we could find it by signature - ZipDir::Encrypt((char*)pCDR, nSizeCDR - sizeof(ZipFile::CDREnd), m_encryptionKey); - } - - size_t nWriteRes = fwrite (pCDR, nSizeCDR, 1, fTarget); - free(pCDR); - return nWriteRes == 1; -} - -// generates random file name -string ZipDir::CacheRW::GetRandomName(int nAttempt) -{ - if (nAttempt) - { - char szBuf[8]; - int i; - for (i = 0; i < sizeof(szBuf) - 1; ++i) - { - int r = rand() % (10 + 'z' - 'a' + 1); - szBuf[i] = r > 9 ? (r - 10) + 'a' : '0' + r; - } - szBuf[i] = '\0'; - return szBuf; - } - else - { - return string(); - } -} - -bool ZipDir::CacheRW::RelinkZip() -{ - AZ::IO::LocalFileIO localFileIO; - for (int nAttempt = 0; nAttempt < 32; ++nAttempt) - { - string strNewFilePath = m_strFilePath + "$" + GetRandomName(nAttempt); - - FILE* f = nullptr; - azfopen(&f, strNewFilePath.c_str(), "wb"); - if (f) - { - bool bOk = RelinkZip(f); - fclose (f); // we don't need the temporary file handle anyway - - if (!bOk) - { - // we don't need the temporary file - localFileIO.Remove(strNewFilePath.c_str()); - return false; - } - - // we successfully relinked, now copy the temporary file to the original file - fclose (m_pFile); - m_pFile = NULL; - - localFileIO.Remove(m_strFilePath.c_str()); - if (localFileIO.Rename(strNewFilePath.c_str(), m_strFilePath.c_str()) == 0) - { - // successfully renamed - reopen - m_pFile = nullptr; - azfopen(&m_pFile, m_strFilePath.c_str(), "r+b"); - return m_pFile == NULL; - } - else - { - // could not rename - - //m_pFile = fopen (strNewFilePath.c_str(), "r+b"); - return false; - } - } - } - - // couldn't open temp file - return false; -} - -bool ZipDir::CacheRW::RelinkZip(FILE* fTmp) -{ - FileRecordList arrFiles(GetRoot()); - arrFiles.SortByFileOffset(); - FileRecordList::ZipStats Stats = arrFiles.GetStats(); - - // we back up our file entries, because we'll need to restore them - // in case the operation fails - std::vector arrFileEntryBackup; - arrFiles.Backup (arrFileEntryBackup); - - // this is the set of files that are to be written out - compressed data and the file record iterator - std::vector queFiles; - queFiles.reserve (g_nMaxItemsRelinkBuffer); - - // the total size of data in the queue - unsigned nQueueSize = 0; - - for (FileRecordList::iterator it = arrFiles.begin(); it != arrFiles.end(); ++it) - { - FileEntry* entry = it->pFileEntry; - // find the file data offset - if (ZD_ERROR_SUCCESS != Refresh(entry)) - { - return false; - } - - // go to the file data -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return false; - } - - // allocate memory for the file compressed data - FileDataRecordPtr pFile = FileDataRecord::New (*it); - - if (!pFile) - { - return false; - } - - // read the compressed data - if (entry->desc.lSizeCompressed && fread (pFile->GetData(), entry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return false; - } - - if (entry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pFile->GetData(), entry->desc.lSizeCompressed, m_encryptionKey); - } - - // put the file into the queue for copying (writing) - queFiles.push_back(pFile); - nQueueSize += entry->desc.lSizeCompressed; - - // if the queue is big enough, write it out - if (nQueueSize > g_nSizeRelinkBuffer || queFiles.size() >= g_nMaxItemsRelinkBuffer) - { - nQueueSize = 0; - if (!WriteZipFiles(queFiles, fTmp)) - { - return false; - } - } - } - - if (!WriteZipFiles(queFiles, fTmp)) - { - return false; - } - - ZipFile::ulong lOldCDROffset = m_lCDROffset; - // the file data has now been written out. Now write the CDR -#ifdef WIN32 - m_lCDROffset = (ZipFile::ulong)_ftelli64(fTmp); -#else - m_lCDROffset = ftell(fTmp); -#endif - if (m_lCDROffset >= 0 && WriteCDR(fTmp, m_bHeadersEncryptedOnClose) && 0 == fflush (fTmp)) - { - // the new file positions are already there - just discard the backup and return - return true; - } - // recover from backup - arrFiles.Restore (arrFileEntryBackup); - m_lCDROffset = lOldCDROffset; - m_bEncryptedHeaders = m_bHeadersEncryptedOnClose; - return false; -} - -// writes out the file data in the queue into the given file. Empties the queue -bool ZipDir::CacheRW::WriteZipFiles(std::vector& queFiles, FILE* fTmp) -{ - for (std::vector::iterator it = queFiles.begin(); it != queFiles.end(); ++it) - { - // set the new header offset to the file entry - we won't need it -#ifdef WIN32 - const unsigned long currentPos = (unsigned long)_ftelli64 (fTmp); -#else - const unsigned long currentPos = ftell (fTmp); -#endif - (*it)->pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset((*it)->strPath.c_str(), currentPos, m_fileAlignment); - - // while writing the local header, the data offset will also be calculated - if (ZD_ERROR_SUCCESS != WriteLocalHeader(fTmp, (*it)->pFileEntry, (*it)->strPath.c_str(), m_bHeadersEncryptedOnClose)) - { - return false; - } - ; - - // write the compressed file data - const bool encrypt = (*it)->pFileEntry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - if (!WriteCompressedData((char*)(*it)->GetData(), (*it)->pFileEntry->desc.lSizeCompressed, encrypt, fTmp)) - { - return false; - } - -#ifdef WIN32 - assert ((*it)->pFileEntry->nEOFOffset == (unsigned long)_ftelli64 (fTmp)); -#else - assert ((*it)->pFileEntry->nEOFOffset == ftell (fTmp)); -#endif - } - queFiles.clear(); - queFiles.reserve (g_nMaxItemsRelinkBuffer); - return true; -} - -void TruncateFile(FILE* file, size_t newLength) -{ -#if defined(AZ_PLATFORM_WINDOWS) - int filedes = _fileno(file); - _chsize_s(filedes, newLength); -#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) - ftruncate(fileno(file), newLength); -#else -#error Not implemented! -#endif -} - -bool ZipDir::CacheRW::EncryptArchive(EncryptionChange change, IEncryptPredicate* encryptContentPredicate, int* numChanged, int* numSkipped) -{ - FileRecordList arrFiles(GetRoot()); - arrFiles.SortByFileOffset(); - - size_t unusedSpace = 0; - size_t lastDataEnd = 0; - - for (FileRecordList::iterator it = arrFiles.begin(); it != arrFiles.end(); ++it) - { - FileEntry* entry = it->pFileEntry; - - if (entry->nFileHeaderOffset > lastDataEnd) - { - fseek(m_pFile, lastDataEnd, SEEK_SET); - size_t gapLength = entry->nFileHeaderOffset - lastDataEnd; - unusedSpace += gapLength; - if (change == ENCRYPT) - { - if (!WriteRandomData(m_pFile, gapLength)) - { - return false; - } - } - else - { - if (!WriteNullData(gapLength)) - { - return false; - } - } - } - lastDataEnd = entry->nEOFOffset; - - if (numSkipped) - { - ++(*numSkipped); - } - - // find the file data offset - if (ZD_ERROR_SUCCESS != Refresh (entry)) - { - return false; - } - - ZipFile::ushort oldMethod = entry->nMethod; - ZipFile::ushort newMethod = oldMethod; - if (change == ENCRYPT) - { - if (entry->nMethod == ZipFile::METHOD_DEFLATE) - { - newMethod = ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - } - } - else - { - if (entry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - newMethod = ZipFile::METHOD_DEFLATE; - } - } - - // allow encryption only for matching files - if (newMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT && - (!encryptContentPredicate || !encryptContentPredicate->Match(it->strPath.c_str()))) - { - newMethod = ZipFile::METHOD_DEFLATE; - } - - entry->nMethod = newMethod; - - const bool encryptHeaders = change == ENCRYPT; - // encryption is toggled or compression method changed... - if (newMethod != oldMethod || encryptHeaders != m_bEncryptedHeaders) - { - // ... update header - if (ZipDir::WriteLocalHeader(m_pFile, entry, it->strPath.c_str(), encryptHeaders) != ZD_ERROR_SUCCESS) - { - return false; - } - } - - if (newMethod == oldMethod) - { - // no need to update file content - continue; - } - - // go to the file data -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return false; - } - - // allocate memory for the file compressed data - FileDataRecordPtr pFile = FileDataRecord::New(*it); - if (!pFile) - { - return false; - } - - // read the compressed data - if (entry->desc.lSizeCompressed && fread (pFile->GetData(), entry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return false; - } - - if (oldMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pFile->GetData(), entry->desc.lSizeCompressed, m_encryptionKey); - } - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return false; - } - - const bool encryptContent = newMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - if (!WriteCompressedData((const char*)pFile->GetData(), entry->desc.lSizeCompressed, encryptContent, m_pFile)) - { - return false; - } - - if (numSkipped) - { - --(*numSkipped); - } - if (numChanged) - { - ++(*numChanged); - } - } - - m_bEncryptedHeaders = change == ENCRYPT; - m_bHeadersEncryptedOnClose = m_bEncryptedHeaders; - - if (!WriteCDR(m_pFile, m_bEncryptedHeaders)) - { - return false; - } - - if (fflush (m_pFile) != 0) - { - return false; - } - - size_t endOfCDR = (size_t)ftell(m_pFile); - - fseek(m_pFile, 0, SEEK_END); - size_t fileSize = (size_t)ftell(m_pFile); - - if (fileSize != endOfCDR) - { - TruncateFile(m_pFile, endOfCDR); - } - - fclose(m_pFile); - m_pFile = 0; - m_treeDir.Clear(); - return true; -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h deleted file mode 100644 index 6c02d34bf3..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h +++ /dev/null @@ -1,283 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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. - -////////////////////////////////////////////////////////////////////////// -// Declaration of the class that will keep the ZipDir Cache object -// and will provide all its services to access Zip file, plus it will -// provide services to write to the zip file efficiently -// Time to time, the contained Cache object will be recreated during -// an archive add operation - -#pragma once - -#include "SimpleStringPool.h" -#include "StringUtils.h" - -struct PackFileJob; -namespace ZipDir -{ - struct FileDataRecord; - TYPEDEF_AUTOPTR(FileDataRecord); - typedef FileDataRecord_AutoPtr FileDataRecordPtr; - - static constexpr int TARGET_MIN_TEST_COMPRESS_BYTES = 128 * 1024; - - struct IReporter - { - virtual void ReportAdded(const char* filename) = 0; - virtual void ReportMissing(const char* filename) = 0; - virtual void ReportUpToDate(const char* filename) = 0; - virtual void ReportSkipped(const char* filename) = 0; - virtual void ReportFailed(const char* filename, const char* error) = 0; - virtual void ReportSpeed(double bytesPerSecond) = 0; - }; - - struct ISplitter - { - // Arguments: - // total - the current size of the pak - // add - the size of the file to add - // sub - the size of the old version of the file which will be removed from the pak - // Return: - // true if adding the current file to the current pak is still permitted. - virtual bool CheckWriteLimit(size_t total, size_t add, size_t sub) const = 0; - - // Arguments: - // total - the current size of the pak - // add - the size of the file to add - // sub - the size of the old version of the file which will be removed from the pak - // offset - the position of the first file which has not been added to the pak - // in the array passed to "UpdateMultipleFiles()" - virtual void SetLastFile(size_t total, size_t add, size_t sub, int offset) = 0; - }; - - struct IEncryptPredicate - { - virtual ~IEncryptPredicate() = default; - virtual bool Match(const char* filename) = 0; - }; - - class CacheRW - { - public: - enum EncryptionChange - { - ENCRYPT, - DECRYPT - }; - // the size of the buffer that's using during re-linking the zip file - enum - { - g_nSizeRelinkBuffer = 128 * 1024 * 1024, // 128 Mbytes - g_nMaxItemsRelinkBuffer = 1024 // max number of files to read before (without) writing - }; - - void AddRef(); - void Release(); - - - CacheRW(bool encryptHeaders, const EncryptionKey& encryptionKey); - ~CacheRW(); - - bool IsValid () const - { - return m_pFile != NULL; - } - - static char* UnifyPath(char* const str, const char* pPath); - static char* ToUnixPath(char* const str, const char* pPath); - char* AllocPath(const char* pPath); - - // opens the given zip file and connects to it. Creates a new file if no such file exists - // if successful, returns true. - //ErrorEnum Open (CMTSafeHeap* pHeap, InitMethodEnum nInitMethod, unsigned nFlags, const char* szFile); - - // Adds a new file to the zip or update an existing one - // adds a directory (creates several nested directories if needed) - ErrorEnum UpdateFile(const char* szRelativePath, void* pUncompressed, unsigned nSize, unsigned nCompressionMethod, int nCompressionLevel, int64 modTime); - - // Sets if Archive should be encrypted or decrypted on close. - bool EncryptArchive(EncryptionChange change, IEncryptPredicate* encryptContentPredicate, int* numChanged, int* numSkipped); - - // Adds or updates a bunch of files. Creates directories if needed. Multithreaded when numExtraThreads > 0 - bool UpdateMultipleFiles(const char** realFilenames, const char** filenamesInZip, size_t fileCount, - int compressionLevel, bool encryptContent, size_t zipMaxSize, int sourceMinSize, int sourceMaxSize, - unsigned numExtraThreads, ZipDir::IReporter* reporter, ZipDir::ISplitter* splitter = nullptr, bool useFastestDecompressionCodec = false); - - // Adds a new file to the zip or update an existing one if it is not compressed - just stored - start a big file - ErrorEnum StartContinuousFileUpdate(const char* szRelativePath, unsigned nSize); - - // Adds a new file to the zip or update an existing's segment if it is not compressed - just stored - // adds a directory (creates several nested directories if needed) - // Arguments: - // nOverwriteSeekPos - 0xffffffff means the seek pos should not be overwritten - ErrorEnum UpdateFileContinuousSegment (const char* szRelativePath, unsigned nSize, void* pUncompressed, unsigned nSegmentSize, unsigned nOverwriteSeekPos); - - ErrorEnum UpdateFileCRC(const char* szRelativePath, unsigned dwCRC32); - - // deletes the file from the archive - ErrorEnum RemoveFile(const char* szRelativePath); - - // deletes the directory, with all its descendants (files and subdirs) - ErrorEnum RemoveDir(const char* szRelativePath); - - // deletes all files and directories in this archive - ErrorEnum RemoveAll(); - - // closes the current zip file - void Close(); - - FileEntry* FindFile(const char* szPath, bool bFullInfo = false); - - ErrorEnum ReadFile(FileEntry* pFileEntry, void* pCompressed, void* pUncompressed); - - void* AllocAndReadFile (FileEntry* pFileEntry); - - void Free (void* p) - { - free(p); - } - - // refreshes information about the given file entry into this file entry - ErrorEnum Refresh (FileEntry* pFileEntry); - - // returns the size of memory occupied by the instance of this cache - size_t GetSize() const; - - // returns the compressed size of all the entries - size_t GetCompressedSize() const; - - // returns the total size of memory occupied by the instance of this cache and all the compressed files - size_t GetTotalFileSize() const; - - // returns the total size of space occupied on disk by the instance of this cache and all the compressed files - size_t GetTotalFileSizeOnDiskSoFar(); - - // QUICK check to determine whether the file entry belongs to this object - bool IsOwnerOf (const FileEntry* pFileEntry) const - { - return m_treeDir.IsOwnerOf(pFileEntry); - } - - // returns the string - path to the zip file from which this object was constructed. - // this will be "" if the object was constructed with a factory that wasn't created with FLAGS_MEMORIZE_ZIP_PATH - const char* GetFilePath() const - { - return m_strFilePath.c_str(); - } - - FileEntryTree* GetRoot() - { - return &m_treeDir; - } - - const FileEntryTree* GetRoot() const - { - return &m_treeDir; - } - - // writes the CDR to the disk - bool WriteCDR() {return WriteCDR(m_pFile, m_bEncryptedHeaders); } - bool WriteCDR(FILE* fTarget, bool encryptHeaders); - - bool RelinkZip(); - protected: - bool RelinkZip(FILE* fTmp); - // writes out the file data in the queue into the given file. Empties the queue - bool WriteZipFiles(std::vector& queFiles, FILE* fTmp); - // generates random file name - string GetRandomName(int nAttempt); - - bool ReadCompressedData(char* data, size_t size); - bool WriteCompressedData(const char* data, size_t size, bool encrypt, FILE* file); - bool WriteNullData(size_t size); - - void StorePackedFile(PackFileJob* job); - protected: - - friend class CacheFactory; - volatile signed int m_nRefCount; // the reference count - FileEntryTree m_treeDir; - FILE* m_pFile; - string m_strFilePath; - - // offset to the start of CDR in the file,even if there's no CDR there currently - // when a new file is added, it can start from here, but this value will need to be updated then - ZipFile::ulong m_lCDROffset; - - CSimpleStringPool m_tempStringPool; - - enum - { - // if this is set, the file needs to be compacted before it can be used by - // all standard zip tools, because gaps between file datas can be present - FLAGS_UNCOMPACTED = 1 << 0, - // if this is set, the CDR needs to be written to the file - FLAGS_CDR_DIRTY = 1 << 1, - // if this is set, the file is opened in read-only mode. no write operations are to be performed - FLAGS_READ_ONLY = 1 << 2, - // when this is set, compact operation is not performed - FLAGS_DONT_COMPACT = 1 << 3 - }; - unsigned m_nFlags; - size_t m_fileAlignment; - - // CDR buffer. - DynArray m_CDR_buffer; - // unified names buffer - DynArray m_unifiedNameBuffer; - - EncryptionKey m_encryptionKey; - bool m_bEncryptedHeaders; - bool m_bHeadersEncryptedOnClose; - }; - - TYPEDEF_AUTOPTR(CacheRW); - typedef CacheRW_AutoPtr CacheRWPtr; - - // creates and if needed automatically destroys the file entry - class FileEntryTransactionAdd - { - class CacheRW* m_pCache; - char m_szPath[_MAX_PATH]; - FileEntry* m_pFileEntry; - bool m_bComitted; - public: - operator FileEntry* () { - return m_pFileEntry; - } - operator bool() const{ - return m_pFileEntry != NULL; - } - FileEntry* operator -> () {return m_pFileEntry; } - FileEntryTransactionAdd(class CacheRW* pCache, char* szPath, char* szUnifiedPath) - : m_pCache(pCache) - , m_bComitted (false) - { - // we need to copy path, because original one will be destroyed by FileEntryTree::Add call - cry_strcpy(m_szPath, szUnifiedPath); - m_pFileEntry = m_pCache->GetRoot()->Add(szPath, szUnifiedPath); - } - ~FileEntryTransactionAdd() - { - if (m_pFileEntry && !m_bComitted) - { - m_pCache->RemoveFile(m_szPath); - } - } - void Commit() - { - m_bComitted = true; - } - }; -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp deleted file mode 100644 index c62428f0b1..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirCache.h" -#include "ZipDirFind.h" -#include "StringHelpers.h" - -bool ZipDir::FindFile::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_nFileEntry = 0; - return SkipNonMatchingFiles(); -} - -bool ZipDir::FindDir::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_nDirEntry = 0; - return SkipNonMatchingDirs(); -} - -// matches the file wilcard in the m_szWildcard to the given file/dir name -// this takes into account the fact that xxx. is the alias name for xxx -bool ZipDir::FindData::MatchWildcard(const char* szName) -{ - if (StringHelpers::MatchesWildcards(szName, m_szWildcard)) - { - return true; - } - - // check if the file object name contains extension sign (.) - const char* p; - for (p = szName; *p && *p != '.'; ++p) - { - continue; - } - - if (*p) - { - // there's an extension sign in the object, but it wasn't matched.. - assert (*p == '.'); - return false; - } - - // no extension sign - add it - char szAlias[_MAX_PATH + 2]; - size_t nLength = p - szName; - if (nLength > _MAX_PATH) - { - nLength = _MAX_PATH; - } - memcpy (szAlias, szName, nLength); - szAlias[nLength] = '.'; // add the alias - szAlias[nLength + 1] = '\0'; // terminate the string - return StringHelpers::MatchesWildcards(szAlias, m_szWildcard); -} - - -ZipDir::FileEntry* ZipDir::FindFile::FindExact (const char* szPath) -{ - if (!PreFind (szPath)) - { - return NULL; - } - - FileEntry* pFileEntry = m_pDirHeader->FindFileEntry(m_szWildcard); - if (pFileEntry) - { - m_nFileEntry = (unsigned)(pFileEntry - m_pDirHeader->GetFileEntry(0)); - } - else - { - m_pDirHeader = NULL; // we didn't find it, fail the search - } - return pFileEntry; -} - -////////////////////////////////////////////////////////////////////////// -// after this call returns successfully (with true returned), the m_szWildcard -// contains the file name/wildcard and m_pDirHeader contains the directory where -// the file (s) are to be found -bool ZipDir::FindData::PreFind (const char* szWildcard) -{ - if (!m_pRoot) - { - return false; - } - - // start the search from the root - m_pDirHeader = m_pRoot; - - // for each path dir name, copy it into the buffer and try to find the subdirectory - const char* pPath = szWildcard; - for (;; ) - { - char* pName = m_szWildcard; - - // at first we'll use the wildcard memory to save the directory names - for (; *pPath && *pPath != '/' && *pPath != '\\' && pName < m_szWildcard + sizeof(m_szWildcard) - 1; ++pPath, ++pName) - { - *pName = ::tolower(*pPath); - } - *pName = '\0'; - - if (*pPath) - { - if (*pPath != '/' && *pPath != '\\') - { - return false;//ZD_ERROR_NAME_TOO_LONG; - } - // this is the name of the directory - DirEntry* pDirEntry = m_pDirHeader->FindSubdirEntry(m_szWildcard); - if (!pDirEntry) - { - m_pDirHeader = NULL; // finish the search - return false; - } - m_pDirHeader = pDirEntry->GetDirectory(); - ++pPath; - assert(m_pDirHeader); - } - else - { - // finally, this is the name of the file (or directory) - return true; - } - } -} - -// goes on to the next entry -bool ZipDir::FindFile::FindNext () -{ - if (m_pDirHeader && m_nFileEntry < m_pDirHeader->numFiles) - { - ++m_nFileEntry; - return SkipNonMatchingFiles(); - } - else - { - return false; - } -} - -// goes on to the next entry -bool ZipDir::FindDir::FindNext () -{ - if (m_pDirHeader && m_nDirEntry < m_pDirHeader->numDirs) - { - ++m_nDirEntry; - return SkipNonMatchingDirs(); - } - else - { - return false; - } -} - -bool ZipDir::FindFile::SkipNonMatchingFiles() -{ - assert(m_pDirHeader && m_nFileEntry <= m_pDirHeader->numFiles); - - for (; m_nFileEntry < m_pDirHeader->numFiles; ++m_nFileEntry) - { - if (MatchWildcard(GetFileName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - -bool ZipDir::FindDir::SkipNonMatchingDirs() -{ - assert(m_pDirHeader && m_nDirEntry <= m_pDirHeader->numDirs); - - for (; m_nDirEntry < m_pDirHeader->numDirs; ++m_nDirEntry) - { - if (MatchWildcard(GetDirName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - - -ZipDir::FileEntry* ZipDir::FindFile::GetFileEntry() -{ - return m_pDirHeader && m_nFileEntry < m_pDirHeader->numFiles ? m_pDirHeader->GetFileEntry(m_nFileEntry) : NULL; -} -ZipDir::DirEntry* ZipDir::FindDir::GetDirEntry() -{ - return m_pDirHeader && m_nDirEntry < m_pDirHeader->numDirs ? m_pDirHeader->GetSubdirEntry(m_nDirEntry) : NULL; -} - -const char* ZipDir::FindFile::GetFileName () -{ - if (m_pDirHeader && m_nFileEntry < m_pDirHeader->numFiles) - { - const char* pNamePool = m_pDirHeader->GetNamePool(); - return m_pDirHeader->GetFileEntry(m_nFileEntry)->GetName(pNamePool); - } - else - { - return ""; // default name - } -} - -const char* ZipDir::FindDir::GetDirName () -{ - if (m_pDirHeader && m_nDirEntry < m_pDirHeader->numDirs) - { - const char* pNamePool = m_pDirHeader->GetNamePool(); - return m_pDirHeader->GetSubdirEntry(m_nDirEntry)->GetName(pNamePool); - } - else - { - return ""; // default name - } -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h deleted file mode 100644 index 99e95607c1..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFIND_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFIND_H -#pragma once - - -namespace ZipDir -{ - // create this structure and loop: - // FindData fd (pZip); - // for (fd.FindFirst("*.cgf"); fd.GetFileEntry(); fd.FindNext()) - // {} // inside the loop, use GetFileEntry() and GetFileName() to get the file entry and name records - class FindData - { - public: - - FindData (DirHeader* pRoot) - : m_pRoot (pRoot) - , m_pDirHeader (NULL) - { - } - - protected: - // initializes everything until the point where the file must be searched for - // after this call returns successfully (with true returned), the m_szWildcard - // contains the file name/wildcard and m_pDirHeader contains the directory where - // the file (s) are to be found - bool PreFind (const char* szWildcard); - - // matches the file wilcard in the m_szWildcard to the given file/dir name - // this takes into account the fact that xxx. is the alias name for xxx - bool MatchWildcard(const char* szName); - - DirHeader* m_pRoot; // the zip file inwhich the search is performed - DirHeader* m_pDirHeader; // the header of the directory in which the files reside - //unsigned m_nDirEntry; // the current directory entry inside the parent directory - - // the actual wildcard being used in the current scan - the file name wildcard only! - char m_szWildcard[_MAX_PATH]; - }; - - class FindFile - : public FindData - { - public: - FindFile (Cache* pCache) - : FindData(pCache->GetRoot()) - { - } - FindFile (DirHeader* pRoot) - : FindData(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - FileEntry* FindExact (const char* szPath); - - // goes on to the next file entry - bool FindNext (); - - FileEntry* GetFileEntry(); - const char* GetFileName (); - - protected: - bool SkipNonMatchingFiles(); - unsigned m_nFileEntry; // the current file index inside the parent directory - }; - - class FindDir - : public FindData - { - public: - FindDir (Cache* pCache) - : FindData(pCache->GetRoot()) - { - } - FindDir (DirHeader* pRoot) - : FindData(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - // goes on to the next file entry - bool FindNext (); - - DirEntry* GetDirEntry(); - const char* GetDirName (); - - protected: - bool SkipNonMatchingDirs(); - unsigned m_nDirEntry; // the current dir index inside the parent directory - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFIND_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp deleted file mode 100644 index a44f8dd45e..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp +++ /dev/null @@ -1,253 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirCacheRW.h" -#include "ZipDirFindRW.h" -#include "StringHelpers.h" - -bool ZipDir::FindFileRW::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_itFile = m_pDirHeader->GetFileBegin(); - return SkipNonMatchingFiles(); -} - -bool ZipDir::FindDirRW::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_itDir = m_pDirHeader->GetDirBegin(); - return SkipNonMatchingDirs(); -} - -// matches the file wilcard in the m_szWildcard to the given file/dir name -// this takes into account the fact that xxx. is the alias name for xxx -bool ZipDir::FindDataRW::MatchWildcard(const char* szName) -{ - if (StringHelpers::MatchesWildcards(szName, m_szWildcard)) - { - return true; - } - - // check if the file object name contains extension sign (.) - const char* p; - for (p = szName; *p && *p != '.'; ++p) - { - continue; - } - - if (*p) - { - // there's an extension sign in the object, but it wasn't matched.. - assert (*p == '.'); - return false; - } - - // no extension sign - add it - char szAlias[_MAX_PATH + 2]; - size_t nLength = p - szName; - if (nLength > _MAX_PATH) - { - nLength = _MAX_PATH; - } - memcpy (szAlias, szName, nLength); - szAlias[nLength] = '.'; // add the alias - szAlias[nLength + 1] = '\0'; // terminate the string - return StringHelpers::MatchesWildcards(szAlias, m_szWildcard); -} - - -ZipDir::FileEntry* ZipDir::FindFileRW::FindExact (const char* szPath) -{ - if (!PreFind (szPath)) - { - return NULL; - } - - FileEntryTree::FileMap::iterator itFile = m_pDirHeader->FindFile(m_szWildcard); - if (itFile != m_pDirHeader->GetFileEnd()) - { - m_itFile = itFile; - } - else - { - m_pDirHeader = NULL; // we didn't find it, fail the search - } - return m_pDirHeader ? m_pDirHeader->GetFileEntry(itFile) : NULL; -} - -ZipDir::FileEntryTree* ZipDir::FindDirRW::FindExact (const char* szPath) -{ - if (!PreFind(szPath)) - { - return NULL; - } - - // the wildcard will contain the target directory name - return m_pDirHeader->FindDir(m_szWildcard); -} - -////////////////////////////////////////////////////////////////////////// -// initializes everything until the point where the file must be searched for -// after this call returns successfully (with true returned), the m_szWildcard -// contains the file name/wildcard and m_pDirHeader contains the directory where -// the file (s) are to be found -bool ZipDir::FindDataRW::PreFind (const char* szWildcard) -{ - if (!m_pRoot) - { - return false; - } - - // start the search from the root - m_pDirHeader = m_pRoot; - - // for each path dir name, copy it into the buffer and try to find the subdirectory - const char* pPath = szWildcard; - for (;; ) - { - char* pName = m_szWildcard; - - // at first we'll use the wildcard memory to save the directory names - for (; *pPath && *pPath != '/' && *pPath != '\\' && pName < m_szWildcard + sizeof(m_szWildcard) - 1; ++pPath, ++pName) - { - *pName = ::tolower(*pPath); - } - *pName = '\0'; - - if (*pPath) - { - // this is the name of the directory - FileEntryTree* pDirEntry = m_pDirHeader->FindDir(m_szWildcard); - if (!pDirEntry) - { - m_pDirHeader = NULL; // finish the search - return false; - } - m_pDirHeader = pDirEntry->GetDirectory(); - ++pPath; - assert(m_pDirHeader); - } - else - { - // finally, this is the name of the file (or directory) - return true; - } - } -} - -// goes on to the next entry -bool ZipDir::FindFileRW::FindNext () -{ - if (m_pDirHeader && m_itFile != m_pDirHeader->GetFileEnd()) - { - ++m_itFile; - return SkipNonMatchingFiles(); - } - else - { - return false; - } -} - -// goes on to the next entry -bool ZipDir::FindDirRW::FindNext () -{ - if (m_pDirHeader && m_itDir != m_pDirHeader->GetDirEnd()) - { - ++m_itDir; - return SkipNonMatchingDirs(); - } - else - { - return false; - } -} - -bool ZipDir::FindFileRW::SkipNonMatchingFiles() -{ - assert(m_pDirHeader); - - for (; m_itFile != m_pDirHeader->GetFileEnd(); ++m_itFile) - { - if (MatchWildcard(GetFileName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - -bool ZipDir::FindDirRW::SkipNonMatchingDirs() -{ - assert(m_pDirHeader); - - for (; m_itDir != m_pDirHeader->GetDirEnd(); ++m_itDir) - { - if (MatchWildcard(GetDirName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - - -ZipDir::FileEntry* ZipDir::FindFileRW::GetFileEntry() -{ - return m_pDirHeader && m_itFile != m_pDirHeader->GetFileEnd() ? m_pDirHeader->GetFileEntry(m_itFile) : NULL; -} -ZipDir::FileEntryTree* ZipDir::FindDirRW::GetDirEntry() -{ - return m_pDirHeader && m_itDir != m_pDirHeader->GetDirEnd() ? m_pDirHeader->GetDirEntry(m_itDir) : NULL; -} - -const char* ZipDir::FindFileRW::GetFileName () -{ - if (m_pDirHeader && m_itFile != m_pDirHeader->GetFileEnd()) - { - return m_pDirHeader->GetFileName(m_itFile); - } - else - { - return ""; // default name - } -} - -const char* ZipDir::FindDirRW::GetDirName () -{ - if (m_pDirHeader && m_itDir != m_pDirHeader->GetDirEnd()) - { - return m_pDirHeader->GetDirName(m_itDir); - } - else - { - return ""; // default name - } -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h deleted file mode 100644 index 3085b5f8ba..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Declaration of the class that can be used to search for the entries -// in a zip dir cache - - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFINDRW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFINDRW_H -#pragma once - - -namespace ZipDir -{ - // create this structure and loop: - // FindData fd (pZip); - // for (fd.FindFirst("*.cgf"); fd.GetFileEntry(); fd.FindNext()) - // {} // inside the loop, use GetFileEntry() and GetFileName() to get the file entry and name records - class FindDataRW - { - public: - FindDataRW (FileEntryTree* pRoot) - : m_pRoot (pRoot) - , m_pDirHeader (NULL) - { - } - - // returns the directory to which the current object belongs - FileEntryTree* GetParentDir() {return m_pDirHeader; } - protected: - // initializes everything until the point where the file must be searched for - // after this call returns successfully (with true returned), the m_szWildcard - // contains the file name/wildcard and m_pDirHeader contains the directory where - // the file (s) are to be found - bool PreFind (const char* szWildcard); - - // matches the file wilcard in the m_szWildcard to the given file/dir name - // this takes into account the fact that xxx. is the alias name for xxx - bool MatchWildcard(const char* szName); - - // the directory inside which the current object (file or directory) is being searched - FileEntryTree* m_pDirHeader; - - FileEntryTree* m_pRoot; // the root of the zip file in which to search - - // the actual wildcard being used in the current scan - the file name wildcard only! - char m_szWildcard[_MAX_PATH]; - }; - - - class FindFileRW - : public FindDataRW - { - public: - FindFileRW (FileEntryTree* pRoot) - : FindDataRW(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - FileEntry* FindExact (const char* szPath); - - // goes on to the next file entry - bool FindNext (); - - FileEntry* GetFileEntry(); - const char* GetFileName (); - - protected: - bool SkipNonMatchingFiles(); - FileEntryTree::FileMap::iterator m_itFile; // the current file iterator inside the parent directory - }; - - class FindDirRW - : public FindDataRW - { - public: - FindDirRW (FileEntryTree* pRoot) - : FindDataRW(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - FileEntryTree* FindExact (const char* szPath); - - // goes on to the next file entry - bool FindNext (); - - FileEntryTree* GetDirEntry(); - const char* GetDirName (); - - protected: - bool SkipNonMatchingDirs(); - FileEntryTree::SubdirMap::iterator m_itDir; // the current dir index inside the parent directory - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFINDRW_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp deleted file mode 100644 index 36b0dd6ba8..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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. - - -#undef max -#include -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirList.h" -#include "ZipDirTree.h" - -ZipDir::FileRecordList::FileRecordList(FileEntryTree* pTree) -{ - clear(); - reserve(pTree->NumFilesTotal()); - AddAllFiles(pTree); -} - -//recursively adds the files from this directory and subdirectories -// the strRoot contains the trailing slash -void ZipDir::FileRecordList::AddAllFiles(FileEntryTree* pTree, string strRoot) -{ - for (FileEntryTree::SubdirMap::iterator it = pTree->GetDirBegin(); it != pTree->GetDirEnd(); ++it) - { - AddAllFiles (it->second, strRoot + it->second->GetOriginalName() + "/"); - } - - for (FileEntryTree::FileMap::iterator it = pTree->GetFileBegin(); it != pTree->GetFileEnd(); ++it) - { - FileRecord rec; - rec.pFileEntry = pTree->GetFileEntry(it); - const char* filename = rec.pFileEntry->szOriginalFileName ? rec.pFileEntry->szOriginalFileName : it->first; - rec.strPath = strRoot + filename; - push_back(rec); - } -} - - -// sorts the files by the physical offset in the zip file -void ZipDir::FileRecordList::SortByFileOffset() -{ - std::sort (begin(), end(), FileRecordFileOffsetOrder()); -} - -// returns the size of CDR in the zip file -ZipDir::FileRecordList::ZipStats ZipDir::FileRecordList::GetStats() const -{ - ZipStats Stats; - Stats.nSizeCDR = sizeof(ZipFile::CDREnd); - Stats.nSizeCompactData = 0; - // for each file, we'll need to store only its CDR header and the name - for (const_iterator it = begin(); it != end(); ++it) - { - Stats.nSizeCDR += sizeof(ZipFile::CDRFileHeader) + it->strPath.length(); - Stats.nSizeCompactData += sizeof(ZipFile::LocalFileHeader) + it->strPath.length() + it->pFileEntry->desc.lSizeCompressed; - } - - return Stats; -} - -// puts the CDR into the given block of mem -size_t ZipDir::FileRecordList::MakeZipCDR(ZipFile::ulong lCDROffset, void* pBuffer, bool encryptedFlag) const -{ - const ZipFile::ushort nBaseVersion = std::max(encryptedFlag ? ZipFile::VERSION_ENCRYPTION_PKWARE : ZipFile::VERSION_DEFAULT, ZipFile::VERSION_COMPRESSION_DEFLATE); - - char* pCur = (char*)pBuffer; - for (const_iterator it = begin(); it != end(); ++it) - { - ZipFile::CDRFileHeader& h = *(ZipFile::CDRFileHeader*)pCur; - pCur = (char*)(&h + 1); - h.lSignature = h.SIGNATURE; - h.nVersionMadeBy = nBaseVersion + (ZipFile::CREATOR_MSDOS << 8); - h.nVersionNeeded = nBaseVersion; - h.nFlags = 0; - h.nMethod = it->pFileEntry->nMethod; - h.nLastModTime = it->pFileEntry->nLastModTime; - h.nLastModDate = it->pFileEntry->nLastModDate; - h.desc = it->pFileEntry->desc; - h.nFileNameLength = (ZipFile::ushort)it->strPath.length(); - h.nExtraFieldLength = 0; - h.nFileCommentLength = 0; - h.nDiskNumberStart = 0; - h.nAttrInternal = 0; - h.lAttrExternal = 0; - h.lLocalHeaderOffset = it->pFileEntry->nFileHeaderOffset; - - memcpy (pCur, it->strPath.c_str(), it->strPath.length()); - pCur += it->strPath.length(); - } - - ZipFile::CDREnd& e = *(ZipFile::CDREnd*)pCur; - e.lSignature = e.SIGNATURE; - e.nDisk = encryptedFlag ? (1 << 15) : 0; - e.nCDRStartDisk = 0; - e.numEntriesOnDisk = (ZipFile::ushort)this->size(); - e.numEntriesTotal = (ZipFile::ushort)this->size(); - e.lCDRSize = (ZipFile::ulong)(pCur - (char*)pBuffer); - e.lCDROffset = lCDROffset; - e.nCommentLength = 0; - - pCur = (char*)(&e + 1); - - return pCur - (char*)pBuffer; -} - - -ZipDir::FileEntryList::FileEntryList (FileEntryTree* pTree, unsigned lCDROffset) - : m_lCDROffset (lCDROffset) -{ - Add (pTree); -} - -void ZipDir::FileEntryList::Add(FileEntryTree* pTree) -{ - for (FileEntryTree::SubdirMap::iterator itDir = pTree->GetDirBegin(); itDir != pTree->GetDirEnd(); ++itDir) - { - Add(pTree->GetDirEntry(itDir)); - } - for (FileEntryTree::FileMap::iterator itFile = pTree->GetFileBegin(); itFile != pTree->GetFileEnd(); ++itFile) - { - insert(pTree->GetFileEntry(itFile)); - } -} - -// updates each file entry's info about the next file entry -void ZipDir::FileEntryList::RefreshEOFOffsets() -{ - iterator it, itNext = begin(); - - if (itNext != end()) - { - while ((it = itNext, ++itNext) != end()) - { - // start scan - (*it)->nEOFOffset = (*itNext)->nFileHeaderOffset; - } - // it is the last one.. - (*it)->nEOFOffset = m_lCDROffset; - } -} - - -void ZipDir::FileRecordList::Backup(std::vector& arrFiles) const -{ - arrFiles.resize (size()); - std::vector::iterator itTgt = arrFiles.begin(); - - for (const_iterator it = begin(); it != end(); ++it, ++itTgt) - { - *itTgt = *it->pFileEntry; - } -} - -void ZipDir::FileRecordList::Restore(const std::vector& arrFiles) -{ - if (arrFiles.size() == size()) - { - std::vector::const_iterator itTgt = arrFiles.begin(); - for (iterator it = begin(); it != end(); ++it, ++itTgt) - { - *it->pFileEntry = *itTgt; - } - } -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirList.h deleted file mode 100644 index 58ce7312ae..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRLIST_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRLIST_H -#pragma once - -#include - -namespace ZipDir -{ - // this is the array of file entries that's convenient to use to construct CDR - struct FileRecord - { - string strPath; // relative path to the file inside zip - FileEntry* pFileEntry; // the file entry itself - - void ConstructFileRecord() - { - new (&strPath)string(); - } - }; - - struct FileDataRecord - : public FileRecord - { - FileDataRecord() { m_nRefCount = 0; } - void AddRef() { ++m_nRefCount; } - void Release() - { - if (--m_nRefCount <= 0) - { - Delete(); - } - } - - void Delete() - { - free (this); - } - - static FileDataRecord* New(const FileRecord& rThat) - { - FileDataRecord* pThis = (FileDataRecord*)malloc(sizeof(FileDataRecord) + rThat.pFileEntry->desc.lSizeCompressed); - - if (pThis) - { - pThis->m_nRefCount = 0; - pThis->ConstructFileRecord(); - *static_cast(pThis) = rThat; - } - return pThis; - } - - void* GetData() {return this + 1; } - - volatile signed int m_nRefCount; // the reference count - }; - - TYPEDEF_AUTOPTR(FileDataRecord); - typedef FileDataRecord_AutoPtr FileDataRecordPtr; - - struct FileRecordFileOffsetOrder - { - bool operator () (const FileRecord& left, const FileRecord& right) - { - return left.pFileEntry->nFileHeaderOffset < right.pFileEntry->nFileHeaderOffset; - } - }; - - // this is used for construction of CDR - class FileRecordList - : public std::vector - { - public: - FileRecordList(class FileEntryTree* pTree); - - struct ZipStats - { - // the size of the CDR in the file - size_t nSizeCDR; - // the size of the file data part (local file descriptors and file datas) - // if it's compacted - size_t nSizeCompactData; - }; - - // sorts the files by the physical offset in the zip file - void SortByFileOffset (); - - // returns the size of CDR in the zip file - ZipStats GetStats() const; - - // puts the CDR into the given block of mem - size_t MakeZipCDR(ZipFile::ulong lCDROffset, void* p, bool encryptedFlag) const; - - void Backup(std::vector& arrFiles) const; - void Restore(const std::vector& arrFiles); - - protected: - // recursively adds the files from this directory and subdirectories - // the strRoot contains the trailing slash - void AddAllFiles(class FileEntryTree* pTree, string strRoot = string()); - }; - - - struct FileEntryFileOffsetOrder - { - bool operator () (FileEntry* pLeft, FileEntry* pRight) const - { - return pLeft->nFileHeaderOffset < pRight->nFileHeaderOffset; - } - }; - - // this is used for refreshing EOFOffsets - class FileEntryList - : public std::set - { - public: - FileEntryList (class FileEntryTree* pTree, unsigned lCDROffset); - // updates each file entry's info about the next file entry - void RefreshEOFOffsets(); - protected: - void Add (class FileEntryTree* pTree); - unsigned m_lCDROffset; - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRLIST_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp deleted file mode 100644 index 3d404ad62b..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp +++ /dev/null @@ -1,670 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "smartptr.h" -#include -#include -#include -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include -#include -#include -#include - -using namespace ZipFile; - -ZipDir::FileEntry::FileEntry(const CDRFileHeader& header, const SExtraZipFileData& extra) -{ - this->desc = header.desc; - this->nFileHeaderOffset = header.lLocalHeaderOffset; - this->nFileDataOffset = INVALID_DATA_OFFSET; // we don't know yet - this->nMethod = header.nMethod; - this->nNameOffset = 0; // we don't know yet -#if defined(AZ_PLATFORM_WINDOWS) - this->nLastModTime = header.nLastModTime; - this->nLastModDate = header.nLastModDate; -#endif - this->nNTFS_LastModifyTime = extra.nLastModifyTime; - this->szOriginalFileName = 0; - - // make an estimation (at least this offset should be there), but we don't actually know yet - this->nEOFOffset = header.lLocalHeaderOffset + sizeof (ZipFile::LocalFileHeader) + header.nFileNameLength + header.desc.lSizeCompressed; -} - - - -// Uncompresses raw (without wrapping) data that is compressed with method 8 (deflated) in the Zip file -// returns one of the Z_* errors (Z_OK upon success) -// This function just mimics the standard uncompress (with modification taken from unzReadCurrentFile) -// with 2 differences: there are no 16-bit checks, and -// it initializes the inflation to start without waiting for compression method byte, as this is the -// way it's stored into zip file -int ZipDir::ZipRawUncompress (void* pUncompressed, unsigned long* pDestSize, const void* pCompressed, unsigned long nSrcSize) -{ - int nReturnCode = Z_OK; - - //check first 4 bytes to see what compression codec was used - if (CompressionCodec::TestForZSTDMagic(pCompressed)) - { - - size_t result = ZSTD_decompress(pUncompressed, *pDestSize, pCompressed, nSrcSize); - - if (ZSTD_isError(result)) - { - AZ_Error("ZipDirStructures", false, "Error decompressing using zstd: %s", ZSTD_getErrorName(result)); - nReturnCode = Z_BUF_ERROR; - } - else - { - *pDestSize = result; - } - return nReturnCode; - } - else if (CompressionCodec::TestForLZ4Magic(pCompressed)) - { - size_t result; - LZ4F_decompressionContext_t dctx; - result = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION); - if (LZ4F_isError(result)) - { - AZ_Error("ZipDirStructures", false, "Error creating lz4 decompression context: %s", LZ4F_getErrorName(result)); - return Z_BUF_ERROR; - } - - size_t dstSize = (size_t)*pDestSize; - size_t srcSize = (size_t)nSrcSize; - result = LZ4F_decompress(dctx, pUncompressed, &dstSize, pCompressed, &srcSize, nullptr); - if (LZ4F_isError(result)) - { - AZ_Error("ZipDirStructures", false, "Error decompressing using lz4: %s", LZ4F_getErrorName(result)); - nReturnCode = Z_BUF_ERROR; - } - else - { - *pDestSize = (long)dstSize; - } - - size_t freeCode = LZ4F_freeDecompressionContext(dctx); - if (LZ4F_isError(freeCode)) - { - //We are not changing the return code in this case, but it is good to record that releasing the - //decompression context failed. - AZ_Error("ZipDirStructures", false, "Error releasing lz4 decompression context: %s", LZ4F_getErrorName(freeCode)); - } - - return nReturnCode; - } - - - //Default to Zlib - z_stream stream; - stream.next_in = (Bytef*)pCompressed; - stream.avail_in = (uInt)nSrcSize; - - int err; - - stream.next_out = (Bytef*)pUncompressed; - stream.avail_out = (uInt) * pDestSize; - - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - stream.opaque = Z_NULL; - - err = inflateInit2(&stream, -MAX_WBITS); - if (err != Z_OK) - { - return err; - } - - // for some strange reason, passing Z_FINISH doesn't work - - // it seems the stream isn't finished for some files and - // inflate returns an error due to stream-end-not-reached (though expected) problem - err = inflate(&stream, Z_SYNC_FLUSH); - if (err != Z_STREAM_END && err != Z_OK) - { - inflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - - *pDestSize = stream.total_out; - - err = inflateEnd(&stream); - return err; - -} - -// compresses the raw data into raw data. The buffer for compressed data itself with the heap passed. Uses method 8 (deflate) -// returns one of the Z_* errors (Z_OK upon success) -int ZipDir::ZipRawCompress(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel) -{ - z_stream stream; - int err; - - stream.next_out = reinterpret_cast(pCompressed); - - stream.next_in = const_cast(static_cast(pUncompressed)); - stream.avail_in = static_cast(nSrcSize); - - stream.avail_out = static_cast(*pDestSize); - - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - stream.opaque = Z_NULL; - - err = deflateInit2 (&stream, nLevel, Z_DEFLATED, -MAX_WBITS, 9, Z_DEFAULT_STRATEGY); - if (err != Z_OK) - { - return err; - } - - err = deflate (&stream, Z_FINISH); - if (err != Z_STREAM_END) - { - deflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - *pDestSize = stream.total_out; - - err = deflateEnd(&stream); - return err; -} - -int ZipDir::ZipRawCompressZSTD(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel) -{ - size_t result = ZSTD_compress(pCompressed, *pDestSize, pUncompressed, nSrcSize, nLevel); - - int err = Z_OK; - - if (ZSTD_isError(result)) - { - err = Z_BUF_ERROR; - } - else - { - *pDestSize = static_cast(result); - } - return err; -} - -int ZipDir::ZipRawCompressLZ4(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, [[maybe_unused]] int nLevel) -{ - int returnCode = Z_OK; - const size_t compressedBufferMaxSize = aznumeric_caster(*pDestSize); - size_t lz4_code = LZ4F_compressFrame(pCompressed, compressedBufferMaxSize, pUncompressed, aznumeric_caster(nSrcSize), nullptr); - - if (LZ4F_isError(lz4_code)) - { - returnCode = Z_BUF_ERROR; - } - else - { - *pDestSize = aznumeric_caster(lz4_code); - } - - return returnCode; -} - -int ZipDir::GetCompressedSizeEstimate(unsigned long uncompressedSize, CompressionCodec::Codec codec) -{ - switch (codec) - { - case CompressionCodec::Codec::ZLIB: - return (uncompressedSize + (uncompressedSize >> 3) + 32); - case CompressionCodec::Codec::ZSTD: - return ZSTD_compressBound(uncompressedSize); - case CompressionCodec::Codec::LZ4: - return LZ4F_compressFrameBound(uncompressedSize, nullptr); - default: - break; - } - return 0; -} - -ZipDir::ValidationResult ZipDir::ValidateZSTDCompressedDataWithOriginalData(const void* pUncompressed, unsigned long uncompressedSize, const void* pCompressed, unsigned long compressedSize) -{ - auto decompressedSize = ZSTD_getDecompressedSize(pCompressed, compressedSize); - ZipDir::ValidationResult testResult = ValidationResult::OK; - - if (decompressedSize != uncompressedSize) - { - testResult = ValidationResult::SIZE_MISMATCH; - } - else - { - void* decompressionBuffer = azmalloc(decompressedSize); - - size_t result = ZSTD_decompress(decompressionBuffer, decompressedSize, pCompressed, compressedSize); - - if (ZSTD_isError(result)) - { - AZ_Warning("Debug", false, "Error decompressing data with zstd: %s", ZSTD_getErrorName(result)); - testResult = ValidationResult::DATA_CORRUPTED; - } - else - { - if (memcmp(decompressionBuffer, pUncompressed, decompressedSize) != 0) - { - testResult = ValidationResult::DATA_NO_MATCH; - } - } - azfree(decompressionBuffer); - } - return testResult; -} - -// finds the subdirectory entry by the name, using the names from the name pool -// assumes: all directories are sorted in alphabetical order. -// case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) -ZipDir::DirEntry* ZipDir::DirHeader::FindSubdirEntry(const char* szName) -{ - if (this->numDirs) - { - const char* pNamePool = GetNamePool(); - DirEntrySortPred pred(pNamePool); - DirEntry* pBegin = GetSubdirEntry(0); - DirEntry* pEnd = pBegin + this->numDirs; - DirEntry* pEntry = std::lower_bound(pBegin, pEnd, szName, pred); -#if defined(LINUX) - if (pEntry != pEnd && !strcasecmp(szName, pEntry->GetName(pNamePool))) -#else - if (pEntry != pEnd && !strcmp(szName, pEntry->GetName(pNamePool))) -#endif - { - return pEntry; - } - } - return NULL; -} - -// finds the file entry by the name, using the names from the name pool -// assumes: all directories are sorted in alphabetical order. -// case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) -ZipDir::FileEntry* ZipDir::DirHeader::FindFileEntry(const char* szName) -{ - if (this->numFiles) - { - const char* pNamePool = GetNamePool(); - DirEntrySortPred pred(pNamePool); - FileEntry* pBegin = GetFileEntry(0); - FileEntry* pEnd = pBegin + this->numFiles; - FileEntry* pEntry = std::lower_bound(pBegin, pEnd, szName, pred); -#if defined(LINUX) - if (pEntry != pEnd && !strcasecmp(szName, pEntry->GetName(pNamePool))) -#else - if (pEntry != pEnd && !strcmp(szName, pEntry->GetName(pNamePool))) -#endif - { - return pEntry; - } - } - return NULL; -} - - -// tries to refresh the file entry from the given file (reads fromthere if needed) -// returns the error code if the operation was impossible to complete -ZipDir::ErrorEnum ZipDir::Refresh(FILE* f, FileEntry* pFileEntry, bool encryptedHeaders) -{ - if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) - { - return ZD_ERROR_SUCCESS; - } - - if (pFileEntry->desc.lSizeCompressed == 0) - { - return ZD_ERROR_SUCCESS; - } - -#ifdef WIN32 - if (_fseeki64(f, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET)) -#else - if (fseek(f, pFileEntry->nFileHeaderOffset, SEEK_SET)) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - if (encryptedHeaders) - { - // with encrypted headers FileEntries should always be initialized from CDR. - return ZD_ERROR_IO_FAILED; - } - - // read the local file header and the name (for validation) into the buffer - LocalFileHeader fileHeader; - if (1 != fread (&fileHeader, sizeof(fileHeader), 1, f)) - { - return ZD_ERROR_IO_FAILED; - } - - if (fileHeader.desc != pFileEntry->desc - || fileHeader.nMethod != pFileEntry->nMethod) - { - return ZD_ERROR_IO_FAILED; - } - - pFileEntry->nFileDataOffset = pFileEntry->nFileHeaderOffset + sizeof(LocalFileHeader) + fileHeader.nFileNameLength + fileHeader.nExtraFieldLength; - pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset + pFileEntry->desc.lSizeCompressed; - return ZD_ERROR_SUCCESS; -} - -// writes into the file local header - without Extra data -// puts the new offset to the file data to the file entry -// in case of error can put INVALID_DATA_OFFSET into the data offset field of file entry -ZipDir::ErrorEnum ZipDir::WriteLocalHeader (FILE* f, FileEntry* pFileEntry, const char* szRelativePath, bool encrypt) -{ - size_t nFileNameLength = strlen(szRelativePath); - size_t nHeaderSize = sizeof(LocalFileHeader) + nFileNameLength; - - pFileEntry->nFileDataOffset = pFileEntry->nFileHeaderOffset + nHeaderSize; - pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset + pFileEntry->desc.lSizeCompressed; - -#ifdef WIN32 - if (_fseeki64 (f, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET)) -#else - if (fseek (f, pFileEntry->nFileHeaderOffset, SEEK_SET)) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - if (encrypt) - { - std::vector garbage; - garbage.resize(nHeaderSize); - for (size_t i = 0; i < nHeaderSize; ++i) - { - garbage[i] = rand() & 0xff; - } - - if (fwrite(&garbage[0], nHeaderSize, 1, f) != 1) - { - return ZD_ERROR_IO_FAILED; - } - } - else - { - LocalFileHeader h; - memset(&h, 0, sizeof(h)); - - h.lSignature = h.SIGNATURE; - h.nVersionNeeded = 10; - h.nFlags = 0; - h.nMethod = pFileEntry->nMethod; -#if defined(AZ_PLATFORM_WINDOWS) - h.nLastModDate = pFileEntry->nLastModDate; - h.nLastModTime = pFileEntry->nLastModTime; -#endif - h.desc = pFileEntry->desc; - h.nFileNameLength = (unsigned short)nFileNameLength; - h.nExtraFieldLength = 0; - - if (1 != fwrite(&h, sizeof(h), 1, f)) - { - return ZD_ERROR_IO_FAILED; - } - - if (nFileNameLength > 0) - { - if (1 != fwrite (szRelativePath, nFileNameLength, 1, f)) - { - return ZD_ERROR_IO_FAILED; - } - } - } - - return ZD_ERROR_SUCCESS; -} - - -// conversion routines for the date/time fields used in Zip -ZipFile::ushort ZipDir::DOSDate(tm* t) -{ - return - ((t->tm_year - 80) << 9) - | (t->tm_mon << 5) - | t->tm_mday; -} - -ZipFile::ushort ZipDir::DOSTime(tm* t) -{ - return - ((t->tm_hour) << 11) - | ((t->tm_min) << 5) - | ((t->tm_sec) >> 1); -} - - - -// sets the current time to modification time -// calculates CRC32 for the new data -void ZipDir::FileEntry::OnNewFileData(void* pUncompressed, unsigned nSize, unsigned nCompressedSize, unsigned nCompressionMethod, bool bContinuous) -{ - time_t nTime; - time(&nTime); -#if defined(AZ_PLATFORM_WINDOWS) - tm t; - localtime_s(&t, &nTime); - this->nLastModTime = DOSTime(&t); - this->nLastModDate = DOSDate(&t); -#else - -#endif - this->nNTFS_LastModifyTime = AZStd::GetTimeUTCMilliSecond(); - - if (!bContinuous) - { - this->desc.lCRC32 = crc32(0L, Z_NULL, 0); - this->desc.lSizeCompressed = nCompressedSize; - this->desc.lSizeUncompressed = nSize; - } - - // we'll need CRC32 of the file to pack it - this->desc.lCRC32 = crc32(this->desc.lCRC32, (Bytef*)pUncompressed, nSize); - - this->nMethod = nCompressionMethod; -} - - -const char* ZipDir::DOSTimeCStr(ZipFile::ushort nTime) -{ - static char szBuf[16]; - azsprintf(szBuf, "%02d:%02d.%02d", (nTime >> 11), ((nTime & ((1 << 11) - 1)) >> 5), ((nTime & ((1 << 5) - 1)) << 1)); - return szBuf; -} - -const char* ZipDir::DOSDateCStr(ZipFile::ushort nTime) -{ - static char szBuf[32]; - azsprintf(szBuf, "%02d.%02d.%04d", (nTime & 0x1F), (nTime >> 5) & 0xF, (nTime >> 9) + 1980); - return szBuf; -} - -uint64 ZipDir::FileEntry::GetModificationTime() -{ - if (nNTFS_LastModifyTime != 0) - { - return nNTFS_LastModifyTime; - } - -#if defined(AZ_PLATFORM_WINDOWS) - // TODO/TIME: check and test - SYSTEMTIME st; - st.wYear = (nLastModDate >> 9) + 1980; - st.wMonth = ((nLastModDate >> 5) & 0xF); - st.wDay = (nLastModDate & 0x1F); - st.wHour = (nLastModTime >> 11); - st.wMinute = (nLastModTime >> 5) & 0x3F; - st.wSecond = (nLastModTime << 1) & 0x3F; - st.wMilliseconds = 0; - FILETIME ft; - SystemTimeToFileTime(&st, &ft); - LARGE_INTEGER lt; - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - return lt.QuadPart; -#else - return 0; -#endif -} - - -void ZipDir::FileEntry::SetFromFileTimeNTFS(int64 timestamp) -{ -#if defined(AZ_PLATFORM_WINDOWS) - FILETIME ft; - ft.dwHighDateTime = timestamp >> 32; - ft.dwLowDateTime = timestamp & 0xFFFFFFFF; - - WORD dosTime, dosDate; - FileTimeToDosDateTime(&ft, &dosDate, &dosTime); - - nLastModDate = dosDate; - nLastModTime = dosTime; -#endif - nNTFS_LastModifyTime = timestamp; -} - -bool ZipDir::FileEntry::CompareFileTimeNTFS(int64 timestamp) -{ -#if defined(AZ_PLATFORM_WINDOWS) - FILETIME ft; - ft.dwHighDateTime = timestamp >> 32; - ft.dwLowDateTime = timestamp & 0xFFFFFFFF; - - WORD dosTime, dosDate; - FileTimeToDosDateTime(&ft, &dosDate, &dosTime); - - return (nLastModTime == dosTime && nLastModDate == dosDate); -#else - return (nNTFS_LastModifyTime == timestamp); -#endif -} - -const char* ZipDir::Error::getError() -{ - switch (this->nError) - { -#define DECLARE_ERROR(x) case ZD_ERROR_##x: \ - return #x; - DECLARE_ERROR(SUCCESS); - DECLARE_ERROR(IO_FAILED); - DECLARE_ERROR(UNEXPECTED); - DECLARE_ERROR(UNSUPPORTED); - DECLARE_ERROR(INVALID_SIGNATURE); - DECLARE_ERROR(ZIP_FILE_IS_CORRUPT); - DECLARE_ERROR(DATA_IS_CORRUPT); - DECLARE_ERROR(NO_CDR); - DECLARE_ERROR(CDR_IS_CORRUPT); - DECLARE_ERROR(NO_MEMORY); - DECLARE_ERROR(VALIDATION_FAILED); - DECLARE_ERROR(CRC32_CHECK); - DECLARE_ERROR(ZLIB_FAILED); - DECLARE_ERROR(ZLIB_CORRUPTED_DATA); - DECLARE_ERROR(ZLIB_NO_MEMORY); - DECLARE_ERROR(CORRUPTED_DATA); - DECLARE_ERROR(INVALID_CALL); - DECLARE_ERROR(NOT_IMPLEMENTED); - DECLARE_ERROR(FILE_NOT_FOUND); - DECLARE_ERROR(DIR_NOT_FOUND); - DECLARE_ERROR(NAME_TOO_LONG); - DECLARE_ERROR(INVALID_PATH); - DECLARE_ERROR(FILE_ALREADY_EXISTS); -#undef DECLARE_ERROR - default: - return "Unknown ZD_ERROR code"; - } -} - - -inline void btea(uint32* v, int n, uint32 const k[4]) -{ -#define TEA_DELTA 0x9e3779b9 -#define TEA_MX (((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4)) ^ ((sum ^ y) + (k[(p & 3) ^ e] ^ z))) - uint32 y, z, sum; - unsigned p, rounds, e; - if (n > 1) /* Coding Part */ - { - rounds = 6 + 52 / n; - sum = 0; - z = v[n - 1]; - do - { - sum += TEA_DELTA; - e = (sum >> 2) & 3; - for (p = 0; p < n - 1; p++) - { - y = v[p + 1]; - z = v[p] += TEA_MX; - } - y = v[0]; - z = v[n - 1] += TEA_MX; - } while (--rounds); - } - else if (n < -1) /* Decoding Part */ - { - n = -n; - rounds = 6 + 52 / n; - sum = rounds * TEA_DELTA; - y = v[0]; - do - { - e = (sum >> 2) & 3; - for (p = n - 1; p > 0; p--) - { - z = v[p - 1]; - y = v[p] -= TEA_MX; - } - z = v[n - 1]; - y = v[0] -= TEA_MX; - } while ((sum -= TEA_DELTA) != 0); - } -#undef TEA_DELTA -#undef TEA_MX -} - -static inline void SwapByteOrder(uint32* values, size_t count) -{ - for (uint32* w = values, * e = values + count; w != e; ++w) - { - *w = (*w >> 24) + ((*w >> 8) & 0xff00) + ((*w & 0xff00) << 8) + (*w << 24); - } -} - -////////////////////////////////////////////////////////////////////////// -void ZipDir::Encrypt(char* buffer, size_t size, const EncryptionKey& key) -{ - uint32* intBuffer = (uint32*)buffer; - const int encryptedLen = size >> 2; - - SwapByteOrder(intBuffer, encryptedLen); - - btea(intBuffer, encryptedLen, key.key); - - SwapByteOrder(intBuffer, encryptedLen); -} - -////////////////////////////////////////////////////////////////////////// -void ZipDir::Decrypt(char* buffer, size_t size, const EncryptionKey& key) -{ - uint32* intBuffer = (uint32*)buffer; - const int encryptedLen = size >> 2; - - SwapByteOrder(intBuffer, encryptedLen); - - btea(intBuffer, -encryptedLen, key.key); - - SwapByteOrder(intBuffer, encryptedLen); -} - diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp deleted file mode 100644 index b35ae48b2a..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp +++ /dev/null @@ -1,356 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" - - -// Adds or finds the file. Returns non-initialized structure if it was added, -// or an IsInitialized() structure if it was found -ZipDir::FileEntry* ZipDir::FileEntryTree::Add(char* szPath, char* szUnifiedPath) -{ - // find the slash; if we found it, it's a subdirectory - add a subdirectory and - // add the file to it. - // if we didn't find it, it's a file - add the file to this dir - - char* pSlash; - for (pSlash = szPath; *pSlash && *pSlash != '/' && *pSlash != '\\'; ++pSlash) - { - continue; // find the next slash - } - char* pUnifiedSlash = szUnifiedPath + (pSlash - szPath); - assert(*pUnifiedSlash == '\0' || *pUnifiedSlash == '\\' || *pUnifiedSlash == '/'); - - if (*pUnifiedSlash) - { - FileEntryTree* pSubdir; - // we have a subdirectory here - create the file in it - { - char* unifiedDir = szUnifiedPath; - *pUnifiedSlash = '\0'; - - char* dir = szPath; - *pSlash = '\0'; - - SubdirMap::iterator it = m_mapDirs.find (unifiedDir); - if (it == m_mapDirs.end()) - { - pSubdir = new FileEntryTree(dir); - m_mapDirs.insert (SubdirMap::value_type(unifiedDir, pSubdir)); - } - else - { - pSubdir = it->second; - } - } - - return pSubdir->Add(pSlash + 1, pUnifiedSlash + 1); - } - else - { - ZipDir::FileEntry* result = &m_mapFiles[szUnifiedPath]; - result->szOriginalFileName = szPath; - return result; - } -} - -// adds a file to this directory -ZipDir::ErrorEnum ZipDir::FileEntryTree::Add (char* szPath, char* szUnifiedPath, const FileEntry& file) -{ - FileEntry* pFile = Add (szPath, szUnifiedPath); - if (!pFile) - { - return ZD_ERROR_INVALID_PATH; - } - if (pFile->IsInitialized()) - { - return ZD_ERROR_FILE_ALREADY_EXISTS; - } - // preserve original filename - const char* szOriginalFileName = pFile->szOriginalFileName; - *pFile = file; - pFile->szOriginalFileName = szOriginalFileName; - return ZD_ERROR_SUCCESS; -} - -// returns the number of files in this tree, including this and sublevels -unsigned ZipDir::FileEntryTree::NumFilesTotal() const -{ - unsigned numFiles = (unsigned)m_mapFiles.size(); - for (SubdirMap::const_iterator it = m_mapDirs.begin(); it != m_mapDirs.end(); ++it) - { - numFiles += it->second->NumFilesTotal(); - } - return numFiles; -} - -#ifdef _TEST_ -size_t g_nSF = 0, g_nSS = 0, g_nSN = 0, g_nSNa = 0, g_nSH; -size_t g_nGF = 0, g_nGS = 0, g_nGN = 0, g_nGNa = 0, g_nGH; -#endif - -// returns the size required to serialize the tree -size_t ZipDir::FileEntryTree::GetSizeSerialized() const -{ - // the total size of name pool gets aligned on 4-byte boundary - size_t nSizeOfNamePool = 0; - size_t nSizeOfFileEntries = 0, nSizeOfDirEntries = 0; - size_t nSizeOfSubdirs = 0; - - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSizeOfDirEntries += sizeof(DirEntry); - const char* dirname = itDir->first; - nSizeOfNamePool += strlen(dirname) + 1; - nSizeOfSubdirs += itDir->second->GetSizeSerialized(); - } - - // for each file, we need to have an entry in the name pool and in the file list - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSizeOfFileEntries += sizeof(FileEntry); - const char* fname = itFile->first; - nSizeOfNamePool += strlen(fname) + 1; - } - - if (nSizeOfNamePool > 0xFFFF) - { - // we don't support so long names/directories - THROW_ZIPDIR_ERROR(ZD_ERROR_UNSUPPORTED, "Name pool larger then 65536 bytes"); - } - -#ifdef _TEST_ - g_nGF += nSizeOfFileEntries; - g_nGS += nSizeOfDirEntries; - g_nGN += nSizeOfNamePool; - g_nGNa += ((nSizeOfNamePool + 3) & ~3); - g_nGH += sizeof(DirHeader); -#endif - - return sizeof(DirHeader) + ((nSizeOfNamePool + 3) & ~3) + nSizeOfDirEntries + nSizeOfFileEntries + nSizeOfSubdirs; -} - -// serializes into the memory -size_t ZipDir::FileEntryTree::Serialize (DirHeader* pDirHeader) const -{ - pDirHeader->numDirs = (ZipFile::ushort)m_mapDirs.size(); - pDirHeader->numFiles = (ZipFile::ushort)m_mapFiles.size(); - DirEntry* pDirEntries = (DirEntry*)(pDirHeader + 1); - FileEntry* pFileEntries = (FileEntry*)(pDirEntries + pDirHeader->numDirs); - char* pNamePool = (char*)(pFileEntries + pDirHeader->numFiles); - - char* pName = pNamePool; - DirEntry* pDirEntry = pDirEntries; - FileEntry* pFileEntry = pFileEntries; - - SubdirMap::const_iterator itDir; - for (itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - pDirEntry->nNameOffset = (ZipFile::ulong)(pName - pNamePool); - size_t nNameLen = strlen(itDir->first); - memcpy (pName, itDir->first, nNameLen + 1); - pName += nNameLen + 1; - ++pDirEntry; - } - - assert ((FileEntry*)pDirEntry == pFileEntry); - - // for each file, we need to have an entry in the name pool and in the file list - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - *pFileEntry = itFile->second; - const char* filename = itFile->first; - pFileEntry->nNameOffset = (ZipFile::ushort)(pName - pNamePool); - size_t nNameLen = strlen(filename); - memcpy (pName, filename, nNameLen + 1); - pName += nNameLen + 1; - ++pFileEntry; - } - assert ((const char*)pFileEntry == pNamePool); - - // now the name pool is full. Go on and fill the other directories - const char* pSubdirHeader = (const char*)(((UINT_PTR)(pName + 3)) & ~3); - -#ifdef _TEST_ - g_nSF += pDirHeader->numFiles * sizeof(FileEntry); - g_nSS += pDirHeader->numDirs * sizeof(DirEntry); - g_nSN += pName - pNamePool; - g_nSNa += pSubdirHeader - pNamePool; - g_nSH += sizeof(DirHeader); -#endif - - pDirEntry = pDirEntries; - for (itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - pDirEntry->nDirHeaderOffset = (ZipFile::ulong)(pSubdirHeader - (const char*)pDirEntry); - pSubdirHeader += itDir->second->Serialize ((DirHeader*)pSubdirHeader); - ++pDirEntry; - } - - - return pSubdirHeader - (const char*)pDirHeader; -} - - - -void ZipDir::FileEntryTree::Clear() -{ - for (SubdirMap::iterator it = m_mapDirs.begin(); it != m_mapDirs.end(); ++it) - { - delete it->second; - } - m_mapDirs.clear(); - m_mapFiles.clear(); -} - - -size_t ZipDir::FileEntryTree::GetSize() const -{ - size_t nSize = sizeof(*this); - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSize += strlen(itDir->first) + sizeof(*itDir) + itDir->second->GetSize(); - } - - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSize += strlen(itFile->first) + sizeof(*itFile); - } - return nSize; -} - -size_t ZipDir::FileEntryTree::GetCompressedFileSize() const -{ - size_t nSize = 0; - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSize += itDir->second->GetCompressedFileSize(); - } - - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSize += itFile->second.desc.lSizeCompressed; - } - return nSize; -} - -size_t ZipDir::FileEntryTree::GetUncompressedFileSize() const -{ - size_t nSize = 0; - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSize += itDir->second->GetUncompressedFileSize(); - } - - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSize += itFile->second.desc.lSizeUncompressed; - } - return nSize; -} - -bool ZipDir::FileEntryTree::IsOwnerOf (const FileEntry* pFileEntry) const -{ - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - if (pFileEntry == &itFile->second) - { - return true; - } - } - - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - if (itDir->second->IsOwnerOf (pFileEntry)) - { - return true; - } - } - - return false; -} - -ZipDir::FileEntryTree* ZipDir::FileEntryTree::FindDir(const char* szDirName) -{ - SubdirMap::iterator it = m_mapDirs.find (szDirName); - if (it == m_mapDirs.end()) - { - return NULL; - } - else - { - return it->second; - } -} - -ZipDir::FileEntryTree::FileMap::iterator ZipDir::FileEntryTree::FindFile (const char* szFileName) -{ - return m_mapFiles.find (szFileName); -} - -ZipDir::FileEntry* ZipDir::FileEntryTree::GetFileEntry(FileMap::iterator it) -{ - return it == GetFileEnd() ? NULL : &it->second; -} - -ZipDir::FileEntryTree* ZipDir::FileEntryTree::GetDirEntry(SubdirMap::iterator it) -{ - return it == GetDirEnd() ? NULL : it->second; -} - -const ZipDir::FileEntry* ZipDir::FileEntryTree::GetFileEntry(FileMap::const_iterator it) const -{ - return it == GetFileEnd() ? NULL : &it->second; -} - -const ZipDir::FileEntryTree* ZipDir::FileEntryTree::GetDirEntry(SubdirMap::const_iterator it) const -{ - return it == GetDirEnd() ? NULL : it->second; -} - -ZipDir::ErrorEnum ZipDir::FileEntryTree::RemoveDir (const char* szDirName) -{ - SubdirMap::iterator itRemove = m_mapDirs.find (szDirName); - if (itRemove == m_mapDirs.end()) - { - return ZD_ERROR_FILE_NOT_FOUND; - } - - delete itRemove->second; - m_mapDirs.erase (itRemove); - return ZD_ERROR_SUCCESS; -} - -ZipDir::ErrorEnum ZipDir::FileEntryTree::RemoveFile (const char* szFileName) -{ - FileMap::iterator itRemove = m_mapFiles.find (szFileName); - if (itRemove == m_mapFiles.end()) - { - return ZD_ERROR_FILE_NOT_FOUND; - } - - m_mapFiles.erase (itRemove); - return ZD_ERROR_SUCCESS; -} - -size_t ZipDir::FileEntryTree::NumDirsTotal() const -{ - size_t result = m_mapDirs.size(); - SubdirMap::const_iterator it; - for (it = m_mapDirs.begin(); it != m_mapDirs.end(); ++it) - { - result += it->second->NumDirsTotal(); - } - return result; -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h deleted file mode 100644 index 0e8af76142..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRTREE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRTREE_H -#pragma once - - -namespace ZipDir -{ - class FileEntryTree - { - public: - FileEntryTree() - : m_originalName(0) {} - FileEntryTree(const char* originalName) - : m_originalName(originalName) {} - ~FileEntryTree () {Clear(); } - - // adds a file to this directory - // Function can modify szPath input - ErrorEnum Add (char* szPath, char* szUnifiedPath, const FileEntry& file); - - // Adds or finds the file. Returns non-initialized structure if it was added, - // or an IsInitialized() structure if it was found - // Function can modify szPath input - FileEntry* Add (char* szPath, char* szUnifiedPath); - - // returns the number of files in this tree, including this and sublevels - unsigned NumFilesTotal() const; - - // returns the size required to serialize the tree - size_t GetSizeSerialized() const; - - // serializes into the memory - size_t Serialize (DirHeader* pDir) const; - - void Clear(); - - void Swap (FileEntryTree& rThat) - { - m_mapDirs.swap (rThat.m_mapDirs); - m_mapFiles.swap (rThat.m_mapFiles); - } - - size_t GetSize() const; - - size_t GetCompressedFileSize() const; - size_t GetUncompressedFileSize() const; - - bool IsOwnerOf (const FileEntry* pFileEntry) const; - - // subdirectories - typedef std::map > SubdirMap; - // file entries - typedef std::map > FileMap; - - FileEntryTree* FindDir(const char* szDirName); - ErrorEnum RemoveDir (const char* szDirName); - ErrorEnum RemoveAll (){Clear(); return ZD_ERROR_SUCCESS; } - FileEntry* FindFileEntry (const char* szFileName); - FileMap::iterator FindFile (const char* szFileName); - ErrorEnum RemoveFile (const char* szFileName); - FileEntryTree* GetDirectory(){return this; } // the FileENtryTree is simultaneously an entry in the dir list AND the directory header - - FileMap::iterator GetFileBegin() {return m_mapFiles.begin(); } - FileMap::iterator GetFileEnd() {return m_mapFiles.end(); } - FileMap::const_iterator GetFileBegin() const {return m_mapFiles.begin(); } - FileMap::const_iterator GetFileEnd() const {return m_mapFiles.end(); } - unsigned NumFiles() const {return (unsigned)m_mapFiles.size(); } - - SubdirMap::iterator GetDirBegin() {return m_mapDirs.begin(); } - SubdirMap::iterator GetDirEnd() {return m_mapDirs.end(); } - SubdirMap::const_iterator GetDirBegin() const {return m_mapDirs.begin(); } - SubdirMap::const_iterator GetDirEnd() const {return m_mapDirs.end(); } - size_t NumDirsTotal() const; - - const char* GetFileName(FileMap::iterator it) {return it->first; } - const char* GetDirName(SubdirMap::iterator it) {return it->first; } - const char* GetOriginalName() const{ return m_originalName; } - - FileEntry* GetFileEntry(FileMap::iterator it); - FileEntryTree* GetDirEntry(SubdirMap::iterator it); - const FileEntry* GetFileEntry(FileMap::const_iterator it) const; - const FileEntryTree* GetDirEntry(SubdirMap::const_iterator it) const; - - protected: - SubdirMap m_mapDirs; - FileMap m_mapFiles; - const char* m_originalName; - }; -} -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRTREE_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipFile.h b/Code/Tools/CryCommonTools/ZipDir/ZipFile.h deleted file mode 100644 index 5e1f78050c..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipFile.h +++ /dev/null @@ -1,19 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILE_H -#pragma once - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILE_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h b/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h deleted file mode 100644 index 3f2083de0f..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h +++ /dev/null @@ -1,388 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_H -#pragma once - -#include -#include - -#if AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 -#pragma pack(push) -#pragma pack(1) -#define PACK_GCC -#else -#define PACK_GCC __PACKED -#endif - -namespace ZipFile -{ - typedef unsigned int ulong; - typedef unsigned short ushort; - - // General-purpose bit field flags - enum - { - GPF_ENCRYPTED = 1 << 0, // If set, indicates that the file is encrypted. - GPF_DATA_DESCRIPTOR = 1 << 3, // if set, the CRC32 and sizes aren't set in the file header, but only in the data descriptor following compressed data - GPF_RESERVED_8_ENHANCED_DEFLATING = 1 << 4, // Reserved for use with method 8, for enhanced deflating. - GPF_COMPRESSED_PATCHED = 1 << 5, // the file is compressed patched data - }; - - // compression methods - enum - { - METHOD_STORE = 0, // The file is stored (no compression) - METHOD_SHRINK = 1, // The file is Shrunk - METHOD_REDUCE_1 = 2, // The file is Reduced with compression factor 1 - METHOD_REDUCE_2 = 3, // The file is Reduced with compression factor 2 - METHOD_REDUCE_3 = 4, // The file is Reduced with compression factor 3 - METHOD_REDUCE_4 = 5, // The file is Reduced with compression factor 4 - METHOD_IMPLODE = 6, // The file is Imploded - METHOD_TOKENIZE = 7, // Reserved for Tokenizing compression algorithm - METHOD_DEFLATE = 8, // The file is Deflated - METHOD_DEFLATE64 = 9, // Enhanced Deflating using Deflate64(tm) - METHOD_IMPLODE_PKWARE = 10, // PKWARE Date Compression Library Imploding - METHOD_DEFLATE_AND_ENCRYPT = 11 // Deflate + Custom encryption - }; - - // version numbers - enum - { - VERSION_DEFAULT = 10, // Default value - - VERSION_TYPE_VOLUMELABEL = 11, // File is a volume label - VERSION_TYPE_FOLDER = 20, // File is a folder (directory) - VERSION_TYPE_PATCHDATASET = 27, // File is a patch data set - VERSION_TYPE_ZIP64 = 45, // File uses ZIP64 format extensions - - VERSION_COMPRESSION_DEFLATE = 20, // File is compressed using Deflate compression - VERSION_COMPRESSION_DEFLATE64 = 21, // File is compressed using Deflate64(tm) - VERSION_COMPRESSION_DCLIMPLODE = 25, // File is compressed using PKWARE DCL Implode - VERSION_COMPRESSION_BZIP2 = 46, // File is compressed using BZIP2 compression* - VERSION_COMPRESSION_LZMA = 63, // File is compressed using LZMA - VERSION_COMPRESSION_PPMD = 63, // File is compressed using PPMd+ - - VERSION_ENCRYPTION_PKWARE = 20, // File is encrypted using traditional PKWARE encryption - VERSION_ENCRYPTION_DES = 50, // File is encrypted using DES - VERSION_ENCRYPTION_3DES = 50, // File is encrypted using 3DES - VERSION_ENCRYPTION_RC2 = 50, // File is encrypted using original RC2 encryption - VERSION_ENCRYPTION_RC4 = 50, // File is encrypted using RC4 encryption - VERSION_ENCRYPTION_AES = 51, // File is encrypted using AES encryption - VERSION_ENCRYPTION_RC2C = 51, // File is encrypted using corrected RC2 encryption** - VERSION_ENCRYPTION_RC4C = 52, // File is encrypted using corrected RC2-64 encryption** - VERSION_ENCRYPTION_NOOAEP = 61, // File is encrypted using non-OAEP key wrapping*** - VERSION_ENCRYPTION_CDR = 62, // Central directory encryption - VERSION_ENCRYPTION_BLOWFISH = 63, // File is encrypted using Blowfish - VERSION_ENCRYPTION_TWOFISH = 63, // File is encrypted using Twofish - }; - - // creator numbers - enum - { - CREATOR_MSDOS = 0, // MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems) - CREATOR_AMIGA = 1, // Amiga - CREATOR_OpenVMS = 2, // OpenVMS - CREATOR_UNIX = 3, // UNIX - CREATOR_VM = 4, // VM/CMS - CREATOR_ATARI = 5, // Atari ST - CREATOR_OS2 = 6, // OS/2 H.P.F.S. - CREATOR_MACINTOSH = 7, // Macintosh - CREATOR_ZSYSTEM = 8, // Z-System - CREATOR_CPM = 9, // CP/M - CREATOR_WINDOWS = 10, // Windows NTFS - CREATOR_MVS = 11, // MVS (OS/390 - Z/OS) - CREATOR_VSE = 12, // VSE - CREATOR_ACORN = 13, // Acorn Risc - CREATOR_VFAT = 14, // VFAT - CREATOR_AMVS = 15, // alternate MVS - CREATOR_BEOS = 16, // BeOS - CREATOR_TANDEM = 17, // Tandem - CREATOR_OS400 = 18, // OS/400 - CREATOR_OSX = 19, // OS X (Darwin) - - CREATOR_UNUSED = 20, // 20 thru 255 - unused - }; - - enum - { - ZIP64_SEE_EXTENSION = -1 // If an archive is in ZIP64 format - // and a value in a field is 0xFFFFFFFF (or 0xFFFF), the size will be - // in the corresponding 8 byte (or 4 byte) ZIP64 extended information. - }; - - // end of Central Directory Record - // followed by the .zip file comment (variable size, can be empty, obtained from nCommentLength) - struct CDREnd - { - enum - { - SIGNATURE = 0x06054b50 - }; - ulong lSignature; // end of central dir signature 4 bytes (0x06054b50) - ushort nDisk; // number of this disk 2 bytes - ushort nCDRStartDisk; // number of the disk with the start of the central directory 2 bytes - ushort numEntriesOnDisk; // total number of entries in the central directory on this disk 2 bytes - ushort numEntriesTotal; // total number of entries in the central directory 2 bytes - ulong lCDRSize; // size of the central directory 4 bytes - ulong lCDROffset; // offset of start of central directory with respect to the starting disk number 4 bytes - ushort nCommentLength; // .ZIP file comment length 2 bytes - - AUTO_STRUCT_INFO - - // .ZIP file comment (variable size, can be empty) follows - } PACK_GCC; - - // end of Central Directory Record - // followed by the zip64 extensible data sector (variable size, can be empty, obtained from nExtDataLength) - struct CDREnd_ZIP64 - { - enum - { - SIGNATURE = 0x06064b50 - }; - ulong lSignature; // end of central dir signature 4 bytes (0x06064b50) - uint64 nExtDataLength; // The value stored into the "size of zip64 end of central directory record" should be the size of the remaining record and should not include the leading 12 bytes. 8 bytes - ushort nVersionMadeBy; // version made by 2 bytes - ushort nVersionNeeded; // version needed to extract 2 bytes - ulong nDisk; // number of this disk 4 bytes - ulong nCDRStartDisk; // number of the disk with the start of the central directory 4 bytes - uint64 numEntriesOnDisk; // total number of entries in the central directory on this disk 8 bytes - uint64 numEntriesTotal; // total number of entries in the central directory 8 bytes - uint64 lCDRSize; // size of the central directory 8 bytes - uint64 lCDROffset; // offset of start of central directory with respect to the starting disk number 8 bytes - - AUTO_STRUCT_INFO - - // zip64 extensible data sector (variable size, can be empty) follows - } PACK_GCC; - - // end of Central Directory Locator - struct CDRLocator_ZIP64 - { - enum - { - SIGNATURE = 0x07064b50 - }; - ulong lSignature; // end of central loc signature 4 bytes (0x07064b50) - ulong nCDR64StartDisk; // number of the disk with the start of the zip64 end of central directory 4 bytes - uint64 lCDR64EndOffset; // relative offset of the zip64 end of central directory record 8 bytes - ulong nDisks; // number of disks 4 bytes - - AUTO_STRUCT_INFO - } PACK_GCC; - - // This descriptor exists only if bit 3 of the general - // purpose bit flag is set (see below). It is byte aligned - // and immediately follows the last byte of compressed data. - // This descriptor is used only when it was not possible to - // seek in the output .ZIP file, e.g., when the output .ZIP file - // was standard output or a non seekable device. For Zip64 format - // archives, the compressed and uncompressed sizes are 8 bytes each. - struct DataDescriptor - { - ulong lCRC32; // crc-32 4 bytes - ulong lSizeCompressed; // compressed size 4 bytes - ulong lSizeUncompressed; // uncompressed size 4 bytes - - bool operator == (const DataDescriptor& d) const - { - return lCRC32 == d.lCRC32 && lSizeCompressed == d.lSizeCompressed && lSizeUncompressed == d.lSizeUncompressed; - } - bool operator != (const DataDescriptor& d) const - { - return lCRC32 != d.lCRC32 || lSizeCompressed != d.lSizeCompressed || lSizeUncompressed != d.lSizeUncompressed; - } - - bool IsZIP64([[maybe_unused]] const DataDescriptor& d) const - { - return lSizeCompressed == (ulong)ZIP64_SEE_EXTENSION || lSizeUncompressed == (ulong)ZIP64_SEE_EXTENSION; - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - // When compressing files, compressed and uncompressed sizes - // should be stored in ZIP64 format (as 8 byte values) when a - // file's size exceeds 0xFFFFFFFF. However ZIP64 format may be - // used regardless of the size of a file. When extracting, if - // the zip64 extended information extra field is present for - // the file the compressed and uncompressed sizes will be 8 - // byte values. - struct DataDescriptor_ZIP64 - { - ulong lCRC32; // crc-32 4 bytes - uint64 lSizeCompressed; // compressed size 8 bytes - uint64 lSizeUncompressed; // uncompressed size 8 bytes - - bool operator == (const DataDescriptor& d) const - { - return lCRC32 == d.lCRC32 && lSizeCompressed == d.lSizeCompressed && lSizeUncompressed == d.lSizeUncompressed; - } - bool operator != (const DataDescriptor& d) const - { - return lCRC32 != d.lCRC32 || lSizeCompressed != d.lSizeCompressed || lSizeUncompressed != d.lSizeUncompressed; - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - // the File Header as it appears in the CDR - // followed by: - // file name (variable size) - // extra field (variable size) - // file comment (variable size) - struct CDRFileHeader - { - enum - { - SIGNATURE = 0x02014b50 - }; - ulong lSignature; // central file header signature 4 bytes (0x02014b50) - ushort nVersionMadeBy; // version made by 2 bytes - ushort nVersionNeeded; // version needed to extract 2 bytes - ushort nFlags; // general purpose bit flag 2 bytes - ushort nMethod; // compression method 2 bytes - ushort nLastModTime; // last mod file time 2 bytes - ushort nLastModDate; // last mod file date 2 bytes - DataDescriptor desc; - ushort nFileNameLength; // file name length 2 bytes - ushort nExtraFieldLength; // extra field length 2 bytes - ushort nFileCommentLength; // file comment length 2 bytes - ushort nDiskNumberStart; // disk number start 2 bytes - ushort nAttrInternal; // internal file attributes 2 bytes - ulong lAttrExternal; // external file attributes 4 bytes - - // This is the offset from the start of the first disk on - // which this file appears, to where the local header should - // be found. If an archive is in zip64 format and the value - // in this field is 0xFFFFFFFF, the size will be in the - // corresponding 8 byte zip64 extended information extra field. - enum - { - ZIP64_LOCAL_HEADER_OFFSET = 0xFFFFFFFF - }; - ulong lLocalHeaderOffset; // relative offset of local header 4 bytes - - bool IsZIP64([[maybe_unused]] const CDRFileHeader& d) const - { - return desc.IsZIP64(desc) || nDiskNumberStart == (ushort)ZIP64_SEE_EXTENSION || lLocalHeaderOffset == (ulong)ZIP64_SEE_EXTENSION; - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - - // this is the local file header that appears before the compressed data - // followed by: - // file name (variable size) - // extra field (variable size) - struct LocalFileHeader - { - enum - { - SIGNATURE = 0x04034b50 - }; - ulong lSignature; // local file header signature 4 bytes (0x04034b50) - ushort nVersionNeeded; // version needed to extract 2 bytes - ushort nFlags; // general purpose bit flag 2 bytes - ushort nMethod; // compression method 2 bytes - ushort nLastModTime; // last mod file time 2 bytes - ushort nLastModDate; // last mod file date 2 bytes - DataDescriptor desc; - ushort nFileNameLength; // file name length 2 bytes - ushort nExtraFieldLength; // extra field length 2 bytes - - bool IsZIP64([[maybe_unused]] const LocalFileHeader& d) const - { - return desc.IsZIP64(desc); - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - // compression methods - enum EExtraHeaderID - { - EXTRA_ZIP64 = 0x0001, // ZIP64 extended information extra field - EXTRA_NTFS = 0x000a, // NTFS - EXTRA_UNIX = 0x000d, // UNIX - EXTRA_PATCH = 0x000f, // Patch Descriptor - }; - - ////////////////////////////////////////////////////////////////////////// - // header1+data1 + header2+data2 . . . - // Each header should consist of: - // Header ID - 2 bytes - // Data Size - 2 bytes - struct ExtraFieldHeader - { - ushort headerID; - ushort dataSize; - - AUTO_STRUCT_INFO - } PACK_GCC; - - struct ExtraNTFSHeader - { - ulong reserved; // 4 bytes. - ushort attrTag; // 2 bytes. - ushort attrSize; // 2 bytes. - - AUTO_STRUCT_INFO - } PACK_GCC; - - ////////////////////////////////////////////////////////////////////////// - // The following is the layout of the zip64 extended - // information "extra" block. If one of the size or - // offset fields in the Local or Central directory - // record is too small to hold the required data, - // a Zip64 extended information record is created. - // The order of the fields in the zip64 extended - // information record is fixed, but the fields MUST - // only appear if the corresponding Local or Central - // directory record field is set to 0xFFFF or 0xFFFFFFFF. - // - // The extended information in the Local header MUST include - // BOTH original and compressed file size fields. - - struct ExtraZIP64LocalFileHeader - { - // LocalFileHeader overrides - uint64 lSizeUncompressed; // uncompressed size 4->8 bytes - uint64 lSizeCompressed; // compressed size 4->8 bytes - - AUTO_STRUCT_INFO - } PACK_GCC; - - struct ExtraZIP64CDRFileHeader - { - // CDRFileHeader overrides - uint64 lSizeUncompressed; // uncompressed size 4->8 bytes - uint64 lSizeCompressed; // compressed size 4->8 bytes - - uint64 lLocalHeaderOffset; // relative offset of local header 4->8 bytes - ulong nDiskNumberStart; // Number of the disk on which this file starts 2->4 bytes - - AUTO_STRUCT_INFO - } PACK_GCC; -} - -#undef PACK_GCC - -#if AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 -#pragma pack(pop) -#endif - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h b/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h deleted file mode 100644 index 9f91eec49b..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_INFO_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_INFO_H -#pragma once - -#include "ZipFileFormat.h" - -STRUCT_INFO_BEGIN(ZipFile::CDREnd) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nDisk, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nCDRStartDisk, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(numEntriesOnDisk, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(numEntriesTotal, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(lCDRSize, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lCDROffset, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nCommentLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::CDREnd) - -STRUCT_INFO_BEGIN(ZipFile::CDREnd_ZIP64) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nExtDataLength, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(nVersionMadeBy, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nVersionNeeded, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nDisk, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nCDRStartDisk, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(numEntriesOnDisk, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(numEntriesTotal, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lCDRSize, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lCDROffset, TYPE_INFO(ZipFile::uint64)) -STRUCT_INFO_END(ZipFile::CDREnd_ZIP64) - -STRUCT_INFO_BEGIN(ZipFile::CDRLocator_ZIP64) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nCDR64StartDisk, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lCDR64EndOffset, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(nDisks, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::CDRLocator_ZIP64) - -STRUCT_INFO_BEGIN(ZipFile::DataDescriptor) -STRUCT_VAR_INFO(lCRC32, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lSizeCompressed, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lSizeUncompressed, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::DataDescriptor) - -STRUCT_INFO_BEGIN(ZipFile::DataDescriptor_ZIP64) -STRUCT_VAR_INFO(lCRC32, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lSizeCompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lSizeUncompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_INFO_END(ZipFile::DataDescriptor_ZIP64) - -STRUCT_INFO_BEGIN(ZipFile::CDRFileHeader) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nVersionMadeBy, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nVersionNeeded, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nMethod, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModTime, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModDate, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(desc, TYPE_INFO(ZipFile::DataDescriptor)) -STRUCT_VAR_INFO(nFileNameLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nExtraFieldLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nFileCommentLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nDiskNumberStart, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nAttrInternal, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(lAttrExternal, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lLocalHeaderOffset, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::CDRFileHeader) - -STRUCT_INFO_BEGIN(ZipFile::LocalFileHeader) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nVersionNeeded, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nMethod, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModTime, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModDate, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(desc, TYPE_INFO(ZipFile::DataDescriptor)) -STRUCT_VAR_INFO(nFileNameLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nExtraFieldLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::LocalFileHeader) - -STRUCT_INFO_BEGIN(ZipFile::ExtraFieldHeader) -STRUCT_VAR_INFO(headerID, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(dataSize, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::ExtraFieldHeader) - -STRUCT_INFO_BEGIN(ZipFile::ExtraNTFSHeader) -STRUCT_VAR_INFO(reserved, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(attrTag, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(attrSize, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::ExtraNTFSHeader) - -STRUCT_INFO_BEGIN(ZipFile::ExtraZIP64Data) -STRUCT_VAR_INFO(lSizeUncompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lSizeCompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lLocalHeaderOffset, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(nDiskNumberStart, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::ExtraZIP64Data) - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_INFO_H diff --git a/Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h b/Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h deleted file mode 100644 index dac298c90c..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h +++ /dev/null @@ -1,426 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// This file contains only the support definitions for CZipDir class -// implementation. This it to unload the ZipDir.h from secondary stuff. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRSTRUCTURES_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRSTRUCTURES_H -#pragma once - -#include - -namespace ZipDir -{ - // possible errors occuring during the method execution - // to avoid clushing with the global Windows defines, we prefix these with ZD_ - enum ErrorEnum - { - ZD_ERROR_SUCCESS = 0, - ZD_ERROR_IO_FAILED, - ZD_ERROR_UNEXPECTED, - ZD_ERROR_UNSUPPORTED, - ZD_ERROR_INVALID_SIGNATURE, - ZD_ERROR_ZIP_FILE_IS_CORRUPT, - ZD_ERROR_DATA_IS_CORRUPT, - ZD_ERROR_NO_CDR, - ZD_ERROR_CDR_IS_CORRUPT, - ZD_ERROR_NO_MEMORY, - ZD_ERROR_VALIDATION_FAILED, - ZD_ERROR_CRC32_CHECK, - ZD_ERROR_ZLIB_FAILED, - ZD_ERROR_ZLIB_CORRUPTED_DATA, - ZD_ERROR_ZLIB_NO_MEMORY, - ZD_ERROR_CORRUPTED_DATA, - ZD_ERROR_INVALID_CALL, - ZD_ERROR_NOT_IMPLEMENTED, - ZD_ERROR_FILE_NOT_FOUND, - ZD_ERROR_DIR_NOT_FOUND, - ZD_ERROR_NAME_TOO_LONG, - ZD_ERROR_INVALID_PATH, - ZD_ERROR_FILE_ALREADY_EXISTS - }; - - // the error describes the reason of the error, as well as the error code, line of code where it happened etc. - struct Error - { - Error(ErrorEnum _nError, const char* _szDescription, const char* _szFunction, const char* _szFile, unsigned _nLine) - : nError(_nError) - , m_szDescription(_szDescription) - , szFunction(_szFunction) - , szFile(_szFile) - , nLine(_nLine) - { - } - - ErrorEnum nError; - const char* getError(); - - const char* getDescription() {return m_szDescription; } - const char* szFunction, * szFile; - unsigned nLine; - protected: - // the description of the error; if needed, will be made as a dynamic string - const char* m_szDescription; - }; - - //#define THROW_ZIPDIR_ERROR(ZD_ERR,DESC) throw Error (ZD_ERR, DESC, __FUNCTION__, __FILE__, __LINE__) - //#define THROW_ZIPDIR_ERROR(ZD_ERR,DESC) CryWarning( VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING,DESC ) - -#define THROW_ZIPDIR_ERROR(ZD_ERR, DESC) - - struct EncryptionKey - { - uint32 key[4]; - - explicit EncryptionKey(const uint32 data[4]) - { - memcpy(key, data, sizeof(key)); - } - - EncryptionKey() - { - memset(key, 0, sizeof(key)); - } - }; - - // possible initialization methods - enum InitMethodEnum - { - // initialize as fast as possible, with minimal validation - ZD_INIT_FAST, - // after initialization, scan through all file headers, precache the actual file data offset values and validate the headers - ZD_INIT_FULL, - // scan all file headers and try to decompress the data, searching for corrupted files - ZD_INIT_VALIDATE, - // maximum level of validation, checks for integrity of the archive - ZD_INIT_VALIDATE_MAX = ZD_INIT_VALIDATE - }; - - typedef void* (* FnAlloc) (void* pUserData, unsigned nItems, unsigned nSize); - typedef void (* FnFree) (void* pUserData, void* pAddress); - - ////////////////////////////////////////////////////////////////////////// - // This structure contains the pointers to functions for memory management - // by default, it's initialized to default malloc/free -#if 0 - struct Allocator - { - FnAlloc fnAlloc; - FnFree fnFree; - void* pOpaque; - - static void* DefaultAlloc (void*, unsigned nItems, unsigned nSize) - { - return malloc (nItems * nSize); - } - - static void DefaultFree (void*, void* pAddress) - { - free (pAddress); - } - - void* Alloc (unsigned nItems, unsigned nSize) - { - return this->fnAlloc(this->pOpaque, nItems, nSize); - } - - void Free (void* pAddress) - { - this->fnFree (this->pOpaque, pAddress); - } - - // constructs the allocator object; by default, the stdlib functions are used - Allocator (FnAlloc fnAllocIn = DefaultAlloc, FnFree fnFreeIn = DefaultFree, void* pOpaqueIn = NULL) - : fnAlloc(fnAllocIn) - , fnFree (fnFreeIn) - , pOpaque(pOpaqueIn) - { - } - }; -#endif - // instance of this class just releases the memory when it's destructed - struct SmartHeapPtr - { - SmartHeapPtr() - : m_pAddress(NULL) - { - } - ~SmartHeapPtr() - { - Release(); - } - - void Attach (void* p) - { - Release(); - m_pAddress = p; - } - - void* Detach() - { - void* p = m_pAddress; - m_pAddress = NULL; - return p; - } - - void Release() - { - if (m_pAddress) - { - free(m_pAddress); - m_pAddress = NULL; - } - } - protected: - // the pointer to free - void* m_pAddress; - }; - - typedef SmartHeapPtr SmartPtr; - - // Uncompresses raw (without wrapping) data that is compressed with method 8 (deflated) in the Zip file - // returns one of the Z_* errors (Z_OK upon success) - extern int ZipRawUncompress (void* pUncompressed, unsigned long* pDestSize, const void* pCompressed, unsigned long nSrcSize); - - // compresses the raw data into raw data. The buffer for compressed data itself with the heap passed. Uses method 8 (deflate) - // returns one of the Z_* errors (Z_OK upon success), and the size in *pDestSize. the pCompressed buffer must be at least nSrcSize*1.001+12 size - - extern int ZipRawCompress (const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel); - extern int ZipRawCompressZSTD(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel); - extern int ZipRawCompressLZ4(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel); - - //returns an estimate of the size of the data when compressed - extern int GetCompressedSizeEstimate(unsigned long uncompressedSize, CompressionCodec::Codec codec = CompressionCodec::Codec::ZLIB); - - enum class ValidationResult - { - OK = 0, - SIZE_MISMATCH, - DATA_CORRUPTED, - DATA_NO_MATCH - }; - //decompresses a zstd blob and compares with the original - returns true if original and uncompressed data match - ValidationResult ValidateZSTDCompressedDataWithOriginalData(const void* pUncompressed, unsigned long uncompressedSize, const void* pCompressed, unsigned long compressedSize); - - ////////////////////////////////////////////////////////////////////////// - struct SExtraZipFileData - { - SExtraZipFileData() - : nLastModifyTime(0) {} - - uint64 nLastModifyTime; - }; - - // this is the record about the file in the Zip file. - struct FileEntry - { - enum - { - INVALID_DATA_OFFSET = 0xFFFFFFFF - }; - - ZipFile::DataDescriptor desc; - ZipFile::ulong nFileHeaderOffset; // offset of the local file header - ZipFile::ulong nFileDataOffset; // offset of the packed info inside the file; NOTE: this can be INVALID_DATA_OFFSET, if not calculated yet! - ZipFile::ushort nMethod; // the method of compression (0 if no compression/store) - ZipFile::ushort nNameOffset; // offset of the file name in the name pool for the directory - - // the file modification times - ZipFile::ushort nLastModTime; - ZipFile::ushort nLastModDate; - - uint64 nNTFS_LastModifyTime; - - // the offset to the start of the next file's header - this - // can be used to calculate the available space in zip file - ZipFile::ulong nEOFOffset; - const char* szOriginalFileName; // original filename (for CacheRW) - - FileEntry() - : nFileHeaderOffset(INVALID_DATA_OFFSET) - , szOriginalFileName(0){} - FileEntry(const ZipFile::CDRFileHeader& header, const SExtraZipFileData& extra); - - bool IsInitialized () - { - // structure marked as non-initialized should have nFileHeaderOffset == INVALID_DATA_OFFSET - return nFileHeaderOffset != INVALID_DATA_OFFSET; - } - // returns the name of this file, given the pointer to the name pool - const char* GetName(const char* pNamePool) const - { - return pNamePool + nNameOffset; - } - - // sets the current time to modification time - // calculates CRC32 for the new data - void OnNewFileData(void* pUncompressed, unsigned nSize, unsigned nCompressedSize, unsigned nCompressionMethod, bool bContinuous); - - uint64 GetModificationTime(); - void SetFromFileTimeNTFS(int64 timestamp); - bool CompareFileTimeNTFS(int64 timestamp); - }; - - // tries to refresh the file entry from the given file (reads fromthere if needed) - // returns the error code if the operation was impossible to complete - extern ErrorEnum Refresh (FILE* f, FileEntry* pFileEntry, bool encrpytedHeaders); - - // writes into the file local header - without Extra data - // puts the new offset to the file data to the file entry - // in case of error can put INVALID_DATA_OFFSET into the data offset field of file entry - extern ErrorEnum WriteLocalHeader (FILE* f, FileEntry* pFileEntry, const char* szRelativePath, bool encrypt); - - // conversion routines for the date/time fields used in Zip - extern ZipFile::ushort DOSDate(tm*); - extern ZipFile::ushort DOSTime(tm*); - - extern const char* DOSTimeCStr(ZipFile::ushort nTime); - extern const char* DOSDateCStr(ZipFile::ushort nTime); - - struct DirHeader; - // this structure represents a subdirectory descriptor in the directory record. - // it points to the actual directory info (list of its subdirs and files), as well - // as on its name - struct DirEntry - { - ZipFile::ulong nDirHeaderOffset;// offset, in bytes, relative to this object, of the actual directory record header - ZipFile::ulong nNameOffset; // offset of the dir name in the name pool of the parent directory - // returns the name of this directory, given the pointer to the name pool of hte parent directory - const char* GetName(const char* pNamePool) const - { - return pNamePool + nNameOffset; - } - - // returns the pointer to the actual directory record. - // call this function only for the actual structure instance contained in a directory record and - // followed by the other directory records - const DirHeader* GetDirectory () const - { - return (const DirHeader*)(((const char*)this) + nDirHeaderOffset); - } - DirHeader* GetDirectory () - { - return (DirHeader*)(((char*)this) + nDirHeaderOffset); - } - }; - - // this is the head of the directory record - // the name pool follows straight the directory and file entries. - struct DirHeader - { - ZipFile::ushort numDirs; // number of directory entries - DirEntry structures - ZipFile::ushort numFiles; // number of file entries - FileEntry structures - - // returns the pointer to the name pool that follows this object - // you can only call this method for the structure instance actually followed by the dir record - const char* GetNamePool() const - { - return ((char*)(this + 1)) + (size_t)this->numDirs * sizeof(DirEntry) + (size_t)this->numFiles * sizeof(FileEntry); - } - char* GetNamePool() - { - return ((char*)(this + 1)) + (size_t)this->numDirs * sizeof(DirEntry) + (size_t)this->numFiles * sizeof(FileEntry); - } - - // returns the pointer to the i-th directory - // call this only for the actual instance of the structure at the head of dir record - const DirEntry* GetSubdirEntry(unsigned i) const - { - assert (i < numDirs); - return ((const DirEntry*)(this + 1)) + i; - } - DirEntry* GetSubdirEntry(unsigned i) - { - assert (i < numDirs); - return ((DirEntry*)(this + 1)) + i; - } - - // returns the pointer to the i-th file - // call this only for the actual instance of the structure at the head of dir record - const FileEntry* GetFileEntry (unsigned i) const - { - assert (i < numFiles); - return (const FileEntry*)(((const DirEntry*)(this + 1)) + numDirs) + i; - } - FileEntry* GetFileEntry (unsigned i) - { - assert (i < numFiles); - return (FileEntry*)(((DirEntry*)(this + 1)) + numDirs) + i; - } - - // finds the subdirectory entry by the name, using the names from the name pool - // assumes: all directories are sorted in alphabetical order. - // case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) - DirEntry* FindSubdirEntry(const char* szName); - - // finds the file entry by the name, using the names from the name pool - // assumes: all directories are sorted in alphabetical order. - // case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) - FileEntry* FindFileEntry(const char* szName); - }; - - // this is the sorting predicate for directory entries - struct DirEntrySortPred - { - DirEntrySortPred (const char* pNamePool) - : m_pNamePool (pNamePool) - { - } - - bool operator () (const FileEntry& left, const FileEntry& right) const - { - return strcmp(left.GetName(m_pNamePool), right.GetName(m_pNamePool)) < 0; - } - - bool operator () (const FileEntry& left, const char* szRight) const - { - return strcmp(left.GetName(m_pNamePool), szRight) < 0; - } - - bool operator () (const char* szLeft, const FileEntry& right) const - { - return strcmp(szLeft, right.GetName(m_pNamePool)) < 0; - } - - bool operator () (const DirEntry& left, const DirEntry& right) const - { - return strcmp(left.GetName(m_pNamePool), right.GetName(m_pNamePool)) < 0; - } - - bool operator () (const DirEntry& left, const char* szName) const - { - return strcmp(left.GetName(m_pNamePool), szName) < 0; - } - - bool operator () (const char* szLeft, const DirEntry& right) const - { - return strcmp(szLeft, right.GetName(m_pNamePool)) < 0; - } - - const char* m_pNamePool; - }; - - inline void tolower (string& str) - { - for (size_t i = 0; i < str.length(); ++i) - { - const_cast(str[i]) = ::tolower(str[i]); - } - } - - void Encrypt(char* buffer, size_t size, const EncryptionKey& key); - void Decrypt(char* buffer, size_t size, const EncryptionKey& key); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRSTRUCTURES_H diff --git a/Code/Tools/CryCommonTools/crycommontools_files.cmake b/Code/Tools/CryCommonTools/crycommontools_files.cmake index d68c49836a..204a65f907 100644 --- a/Code/Tools/CryCommonTools/crycommontools_files.cmake +++ b/Code/Tools/CryCommonTools/crycommontools_files.cmake @@ -10,45 +10,6 @@ # set(FILES - PakSystem.cpp - TempFilePakExtraction.cpp - IPakSystem.h - PakSystem.h - PakXmlFileBufferSource.h - TempFilePakExtraction.h - FileUtil.cpp - PathHelpers.cpp StringHelpers.cpp - FileUtil.h - MathHelpers.h - PathHelpers.h - PropertyHelpers.h - PropertyHelpers.cpp - SimpleStringPool.h - StealingThreadPool.cpp - StealingThreadPool.h StringHelpers.h - ThreadUtils.cpp - ZipDir/ZipDirCache.cpp - ZipDir/ZipDirCacheFactory.cpp - ZipDir/ZipDirCacheRW.cpp - ZipDir/ZipDirFind.cpp - ZipDir/ZipDirFindRW.cpp - ZipDir/ZipDirList.cpp - ZipDir/ZipDirStructures.cpp - ZipDir/ZipDirTree.cpp - ThreadUtils.h - ZipDir/ZipDir.h - ZipDir/ZipDirCache.h - ZipDir/ZipDirCacheFactory.h - ZipDir/ZipDirCacheRW.h - ZipDir/ZipDirFind.h - ZipDir/ZipDirFindRW.h - ZipDir/ZipDirList.h - ZipDir/zipdirstructures.h - ZipDir/ZipDirTree.h - ZipDir/ZipFile.h - ZipDir/ZipFileFormat.h - ZipDir/ZipFileFormat_info.h - SuffixUtil.h ) diff --git a/Code/Tools/CryCommonTools/crycommontools_tests_files.cmake b/Code/Tools/CryCommonTools/crycommontools_tests_files.cmake deleted file mode 100644 index 13f6d90d3c..0000000000 --- a/Code/Tools/CryCommonTools/crycommontools_tests_files.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - UnitTests/PathHelpersUnitTests.cpp - UnitTests/StringHelpersUnitTests.cpp -) diff --git a/Code/Tools/CryCommonTools/zlibstatd64.lib b/Code/Tools/CryCommonTools/zlibstatd64.lib deleted file mode 100644 index 779712e946..0000000000 --- a/Code/Tools/CryCommonTools/zlibstatd64.lib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9d9f51c3e75a4e80f45ba176511a84257146d6bc7c61f0cd582343544fd30e7c -size 277480 diff --git a/Code/Tools/CryXML/CMakeLists.txt b/Code/Tools/CryXML/CMakeLists.txt deleted file mode 100644 index a154fb6bd5..0000000000 --- a/Code/Tools/CryXML/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -if (NOT PAL_TRAIT_BUILD_HOST_TOOLS) - return() -endif() -ly_add_target( - NAME CryXML MODULE - NAMESPACE Legacy - FILES_CMAKE - cryxml_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - COMPILE_DEFINITIONS - PRIVATE - CRYTOOLS - RESOURCE_COMPILER - BUILD_DEPENDENCIES - PRIVATE - 3rdParty::expat - Legacy::CryCommon - Legacy::CryCommonTools -) diff --git a/Code/Tools/CryXML/CryXML.cpp b/Code/Tools/CryXML/CryXML.cpp deleted file mode 100644 index 597c751b0d..0000000000 --- a/Code/Tools/CryXML/CryXML.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Defines the entry point for the DLL application. - - -#include "CryXML_precompiled.h" -#include "CryAssert_impl.h" -#include "ICryXML.h" -#include "XMLSerializer.h" -#include -#include - -class CryXML - : public ICryXML -{ -public: - CryXML(); - virtual void AddRef(); - virtual void Release(); - virtual IXMLSerializer* GetXMLSerializer(); - -private: - int nRefCount; - XMLSerializer serializer; -}; - -static CryXML* s_pCryXML = nullptr; - -#if defined(AZ_PLATFORM_WINDOWS) && !defined(AZ_MONOLITHIC_BUILD) -BOOL APIENTRY DllMain([[maybe_unused]] HANDLE hModule, [[maybe_unused]] DWORD ul_reason_for_call, [[maybe_unused]] LPVOID lpReserved) -{ - return TRUE; -} -#endif - -extern "C" DLL_EXPORT ICryXML * __stdcall GetICryXML() -{ - PREVENT_MODULE_AND_ENVIRONMENT_SYMBOL_STRIPPING - - if (!s_pCryXML) - { - s_pCryXML = new CryXML; - } - return s_pCryXML; -} - -CryXML::CryXML() - : nRefCount(0) -{ -} - -void CryXML::AddRef() -{ - ++this->nRefCount; -} - -void CryXML::Release() -{ - --this->nRefCount; - if (this->nRefCount == 0) - { - if (this == s_pCryXML) - { - s_pCryXML = nullptr; - } - delete this; - } -} - -IXMLSerializer* CryXML::GetXMLSerializer() -{ - return &this->serializer; -} - - -// STLPort requires folowing functions defined: - -// when using STL Port _STLP_DEBUG and _STLP_DEBUG_TERMINATE - avoid actually -// crashing (default terminator seems to kill the thread, which isn't nice). -#ifdef _STLP_DEBUG_TERMINATE -void __stl_debug_terminate(void) -{ - assert(0 && "STL Debug Error"); -} -#endif -#ifdef _STLP_DEBUG_MESSAGE -void __stl_debug_message(const char* format_str, ...) -{ - va_list __args; - va_start(__args, format_str); - vprintf(format_str, __args); - va_end(__args); -} -#endif //_STLP_DEBUG_MESSAGE diff --git a/Code/Tools/CryXML/CryXML.def b/Code/Tools/CryXML/CryXML.def deleted file mode 100644 index 6275474eab..0000000000 --- a/Code/Tools/CryXML/CryXML.def +++ /dev/null @@ -1,3 +0,0 @@ -LIBRARY CryXML -EXPORTS - GetICryXML @1 diff --git a/Code/Tools/CryXML/CryXML_precompiled.cpp b/Code/Tools/CryXML/CryXML_precompiled.cpp deleted file mode 100644 index 8bb231ffd1..0000000000 --- a/Code/Tools/CryXML/CryXML_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 "CryXML_precompiled.h" diff --git a/Code/Tools/CryXML/CryXML_precompiled.h b/Code/Tools/CryXML/CryXML_precompiled.h deleted file mode 100644 index b7f48067b1..0000000000 --- a/Code/Tools/CryXML/CryXML_precompiled.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// -#pragma once - -#include - -#define CRY_ASSERT(condition) assert(condition) -#define CRY_ASSERT_TRACE(condition, message) assert(condition) -#define CRY_ASSERT_MESSAGE(condition, message) assert(condition) - -// Define this to prevent including CryAssert (there is no proper hook for turning this off, like the above). -#define CRYINCLUDE_CRYCOMMON_CRYASSERT_H - -#define CRY_STRING -#include - -#include "Cry_Math.h" diff --git a/Code/Tools/CryXML/ICryXML.h b/Code/Tools/CryXML/ICryXML.h deleted file mode 100644 index fddc95e60e..0000000000 --- a/Code/Tools/CryXML/ICryXML.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYXML_ICRYXML_H -#define CRYINCLUDE_CRYXML_ICRYXML_H -#pragma once - - -class IXMLSerializer; - -class ICryXML -{ -public: - virtual ~ICryXML() = default; - virtual void AddRef() = 0; - virtual void Release() = 0; - virtual IXMLSerializer* GetXMLSerializer() = 0; -}; - -// Prototype for the function that is exported by the DLL - use this function to -// get a pointer to an ICryXML object. The function is exported by name as GetICryXML(). -typedef ICryXML* (* FnGetICryXML)(); - -#endif // CRYINCLUDE_CRYXML_ICRYXML_H diff --git a/Code/Tools/CryXML/IXMLSerializer.h b/Code/Tools/CryXML/IXMLSerializer.h deleted file mode 100644 index 44347beb5b..0000000000 --- a/Code/Tools/CryXML/IXMLSerializer.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYXML_IXMLSERIALIZER_H -#define CRYINCLUDE_CRYXML_IXMLSERIALIZER_H -#pragma once - - -#include "IXml.h" -#include -class IXMLDataSink; -class IXMLDataSource; - -struct IXmlBufferSource -{ - virtual int Read(void* buffer, int size) const = 0; -}; - -class FileXmlBufferSource - : public IXmlBufferSource -{ -public: - FileXmlBufferSource(const char* path) - { - file = nullptr; - azfopen(&file, path, "r"); - } - ~FileXmlBufferSource() - { - if (file) - { - std::fclose(file); - } - } - - virtual int Read(void* buffer, int size) const - { - if (!file) - { - return 0; - } - return check_cast(std::fread(buffer, 1, size, file)); - } - -private: - mutable std::FILE* file; -}; - -class IXMLSerializer -{ -public: - virtual XmlNodeRef CreateNode(const char* tag) = 0; - virtual bool Write(XmlNodeRef root, const char* szFileName) = 0; - - virtual XmlNodeRef Read(const IXmlBufferSource& source, bool bRemoveNonessentialSpacesFromContent, int nErrorBufferSize, char* szErrorBuffer) = 0; -}; - -#endif // CRYINCLUDE_CRYXML_IXMLSERIALIZER_H diff --git a/Code/Tools/CryXML/XML/xml.cpp b/Code/Tools/CryXML/XML/xml.cpp deleted file mode 100644 index 4c117b54c7..0000000000 --- a/Code/Tools/CryXML/XML/xml.cpp +++ /dev/null @@ -1,1400 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "CryXML_precompiled.h" - -//#define _CRT_SECURE_NO_DEPRECATE 1 -//#define _CRT_NONSTDC_NO_DEPRECATE -#include - -#define XML_STATIC -#include -#include "xml.h" -#include "../IXMLSerializer.h" -#include "Util.h" -#include -#include -#include - -#include -#include -#include -#include - -///////////////////////////////////////////////////////////////////// -// String pool implementation (from expat). -///////////////////////////////////////////////////////////////////// -class CSimpleStringPool -{ -public: - enum - { - STD_BLOCK_SIZE = 4096 - }; - struct BLOCK - { - BLOCK* next; - int size; - char s[1]; - }; - unsigned int m_blockSize; - BLOCK* m_blocks; - const char* m_end; - char* m_ptr; - char* m_start; - int nUsedSpace; - int nUsedBlocks; - - CSimpleStringPool() - { - m_blockSize = STD_BLOCK_SIZE; - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - nUsedBlocks = 0; - } - ~CSimpleStringPool() - { - BLOCK* p = m_blocks; - while (p) - { - BLOCK* temp = p->next; - //nFree++; - CryModuleFree(p); - p = temp; - } - m_blocks = 0; - m_ptr = 0; - m_start = 0; - m_end = 0; - } - void SetBlockSize(unsigned int nBlockSize) - { - if (nBlockSize > 1024 * 1024) - { - nBlockSize = 1024 * 1024; - } - unsigned int size = 512; - while (size < nBlockSize) - { - size *= 2; - } - - m_blockSize = size; - } - char* Append(const char* ptr, int nStrLen) - { - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = Util::getMax(nStrLen + 1, (int)m_blockSize); - AllocBlock(nNewBlockSize); - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } - char* ReplaceString(const char* str1, const char* str2) - { - int nStrLen1 = strlen(str1); - int nStrLen2 = strlen(str2); - - // undo ptr1 add. - if (m_ptr != m_start) - { - m_ptr = m_ptr - nStrLen1 - 1; - } - - assert(m_ptr == str1); - - int nStrLen = nStrLen1 + nStrLen2; - - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = Util::getMax(nStrLen + 1, (int)m_blockSize); - if (m_ptr == m_start) - { - ReallocBlock(nNewBlockSize * 2); // Reallocate current block. - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - else - { - AllocBlock(nNewBlockSize); - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } -private: - void AllocBlock(int blockSize) - { - //nMallocs++; - BLOCK* pBlock = (BLOCK*)CryModuleMalloc(offsetof(BLOCK, s) + blockSize * sizeof(char)); - if (!pBlock) - { - // no memory. - //CryError( "Out of memory" ); - m_ptr = 0; - m_start = 0; - m_end = 0; - return; - } - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - nUsedBlocks++; - } - void ReallocBlock(int blockSize) - { - BLOCK* pThisBlock = m_blocks; - BLOCK* pPrevBlock = m_blocks->next; - m_blocks = pPrevBlock; - //nMallocs++; - BLOCK* pBlock = (BLOCK*)CryModuleRealloc(pThisBlock, offsetof(BLOCK, s) + blockSize * sizeof(char)); - if (!pBlock) - { - // no memory. - //CryError( "Out of memory" ); - m_ptr = 0; - m_start = 0; - m_end = 0; - return; - } - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - } -}; - -////////////////////////////////////////////////////////////////////////// -static int __cdecl ascii_stricmp(const char* dst, const char* src) -{ - int f, l; - do - { - if (((f = (unsigned char)(*(dst++))) >= 'A') && (f <= 'Z')) - { - f -= 'A' - 'a'; - } - if (((l = (unsigned char)(*(src++))) >= 'A') && (l <= 'Z')) - { - l -= 'A' - 'a'; - } - } - while (f && (f == l)); - return(f - l); -} - -////////////////////////////////////////////////////////////////////////// -XmlStrCmpFunc g_pXmlStrCmp = &ascii_stricmp; - -////////////////////////////////////////////////////////////////////////// -class CXmlStringData - : public IXmlStringData -{ -public: - int m_nRefCount; - XmlString m_string; - - CXmlStringData() { m_nRefCount = 0; } - virtual void AddRef() { ++m_nRefCount; } - virtual void Release() - { - if (--m_nRefCount <= 0) - { - delete this; - } - } - - virtual const char* GetString() { return m_string.c_str(); }; - virtual size_t GetStringLength() { return m_string.size(); }; -}; - -class CXmlStringPool - : public IXmlStringPool -{ -public: - char* AddString(const char* str) { return m_stringPool.Append(str, (int)strlen(str)); } -private: - CSimpleStringPool m_stringPool; -}; - -/** -****************************************************************************** -* CXmlNode implementation. -****************************************************************************** -*/ - -void CXmlNode::DeleteThis() -{ - delete this; -} - -CXmlNode::~CXmlNode() -{ - // Clear parent pointer from childs. - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - IXmlNode* node = *it; - ((CXmlNode*)node)->m_parent = 0; - } - m_pStringPool->Release(); -} - -CXmlNode::CXmlNode() -{ - m_tag = ""; - m_content = ""; - m_parent = 0; - m_nRefCount = 0; - m_pStringPool = 0; // must be changed later. -} - -CXmlNode::CXmlNode(const char* tag) -{ - m_content = ""; - m_parent = 0; - m_nRefCount = 0; - m_pStringPool = new CXmlStringPool; - m_pStringPool->AddRef(); - m_tag = m_pStringPool->AddString(tag); -} - -////////////////////////////////////////////////////////////////////////// -XmlNodeRef CXmlNode::createNode(const char* tag) -{ - CXmlNode* pNewNode = new CXmlNode; - pNewNode->m_pStringPool = m_pStringPool; - m_pStringPool->AddRef(); - pNewNode->m_tag = m_pStringPool->AddString(tag); - return XmlNodeRef(pNewNode); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setTag(const char* tag) -{ - m_tag = m_pStringPool->AddString(tag); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setContent(const char* str) -{ - m_content = str; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::isTag(const char* tag) const -{ - return g_pXmlStrCmp(tag, m_tag) == 0; -} - -const char* CXmlNode::getAttr(const char* key) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - return svalue; - } - return ""; -} - -bool CXmlNode::getAttr(const char* key, const char** value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - *value = svalue; - return true; - } - else - { - *value = ""; - return false; - } -} - -bool CXmlNode::haveAttr(const char* key) const -{ - XmlAttrConstIter it = GetAttrConstIterator(key); - if (it != m_attributes.end()) - { - return true; - } - return false; -} - -void CXmlNode::delAttr(const char* key) -{ - XmlAttrIter it = GetAttrIterator(key); - if (it != m_attributes.end()) - { - m_attributes.erase(it); - } -} - -void CXmlNode::removeAllAttributes() -{ - m_attributes.clear(); -} - -void CXmlNode::setAttr(const char* key, const char* value) -{ - XmlAttrIter it = GetAttrIterator(key); - if (it == m_attributes.end()) - { - XmlAttribute tempAttr; - tempAttr.key = m_pStringPool->AddString(key); - tempAttr.value = m_pStringPool->AddString(value); - m_attributes.push_back(tempAttr); - // Sort attributes. - //std::sort( m_attributes.begin(),m_attributes.end() ); - } - else - { - // If already exist, override this member. - it->value = m_pStringPool->AddString(value); - } -} - -void CXmlNode::setAttr(const char* key, int value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%d", value); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, unsigned int value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%d", value); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, float value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g", value); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, double value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%.17g", value); - setAttr(key, str); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setAttr(const char* key, int64 value) -{ - char str[32]; - azsnprintf(str, sizeof(str), "%" PRId64, value); - setAttr(key, str); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setAttr(const char* key, uint64 value, bool useHexFormat) -{ - char str[32]; - if (useHexFormat) - { - azsnprintf(str, sizeof(str), "%" PRIX64, value); - } - else - { - azsnprintf(str, sizeof(str), "%" PRIu64, value); - } - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Ang3& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g", value.x, value.y, value.z); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec2& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g", value.x, value.y); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec2d& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%.17g,%.17g", value.x, value.y); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec3& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g", value.x, value.y, value.z); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec3d& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%.17g,%.17g,%.17g", value.x, value.y, value.z); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec4& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g,%g", value.x, value.y, value.z, value.w); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Quat& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g,%g", value.w, value.v.x, value.v.y, value.v.z); - setAttr(key, str); -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, int& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = atoi(svalue); - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, unsigned int& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = strtoul(svalue, NULL, 10); - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, int64& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - azsscanf(svalue, "%" PRId64, &value); - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, uint64& value, bool useHexFormat) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - if (useHexFormat) - { - azsscanf(svalue, "%" PRIX64, &value); - } - else - { - azsscanf(svalue, "%" PRIu64, &value); - } - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, bool& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = atoi(svalue) != 0; - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, float& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = (float)atof(svalue); - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, double& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = atof(svalue); - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Ang3& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y, z; - if (azsscanf(svalue, "%f,%f,%f", &x, &y, &z) == 3) - { - value(x, y, z); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec2& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y; - if (azsscanf(svalue, "%f,%f", &x, &y) == 2) - { - value = Vec2(x, y); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec2d& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - double x, y; - if (azsscanf(svalue, "%lf,%lf", &x, &y) == 2) - { - value = Vec2d(x, y); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec3& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y, z; - if (azsscanf(svalue, "%f,%f,%f", &x, &y, &z) == 3) - { - value(x, y, z); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec4& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y, z, w; - if (azsscanf(svalue, "%f,%f,%f,%f", &x, &y, &z, &w) == 3) - { - value(x, y, z, w); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec3d& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - double x, y, z; - if (azsscanf(svalue, "%lf,%lf,%lf", &x, &y, &z) == 3) - { - value = Vec3d(x, y, z); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Quat& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float w, x, y, z; - if (azsscanf(svalue, "%f,%f,%f,%f", &w, &x, &y, &z) == 4) - { - if (fabs(w) > VEC_EPSILON || fabs(x) > VEC_EPSILON || fabs(y) > VEC_EPSILON || fabs(z) > VEC_EPSILON) - { - //[AlexMcC|02.03.10] directly assign to members to avoid triggering the assert in Quat() with data from bad assets - value.w = w; - value.v = Vec3(x, y, z); - return value.IsValid(); - } - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, ColorB& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - unsigned int r, g, b, a = 255; - int numFound = azsscanf(svalue, "%u,%u,%u,%u", &r, &g, &b, &a); - if (numFound == 3 || numFound == 4) - { - // If we only found 3 values, a should be unchanged, and still be 255 - if (r < 256 && g < 256 && b < 256 && a < 256) - { - value = ColorB(r, g, b, a); - return true; - } - } - } - return false; -} - - -XmlNodeRef CXmlNode::findChild(const char* tag) const -{ - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - if ((*it)->isTag(tag)) - { - return *it; - } - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::deleteChild(const char* tag) -{ - for (XmlNodes::iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - if ((*it)->isTag(tag)) - { - m_childs.erase(it); - return; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::deleteChildAt(int nIndex) -{ - if (nIndex >= 0 && nIndex < (int)m_childs.size()) - { - m_childs.erase(m_childs.begin() + nIndex); - } -} - -//! Adds new child node. -void CXmlNode::addChild(const XmlNodeRef& node) -{ - assert(node != 0); - m_childs.push_back(node); - IXmlNode* n = node; - ((CXmlNode*)n)->m_parent = this; -}; - -void CXmlNode::setParent(const XmlNodeRef& inNewParent) -{ - // note, parent ptrs are not ref counted - IXmlNode* n = inNewParent; - m_parent = (CXmlNode*)n; -} - -void CXmlNode::insertChild(int inIndex, const XmlNodeRef& inNewChild) -{ - assert(inIndex >= 0 && inIndex <= getChildCount()); - assert(inNewChild != 0); - if (inIndex >= 0 && inIndex <= getChildCount() && inNewChild) - { - if (getChildCount() == 0) - { - addChild(inNewChild); - } - else - { - IXmlNode* pNode = ((IXmlNode*)inNewChild); - pNode->AddRef(); - m_childs.insert(m_childs.begin() + inIndex, pNode); - pNode->setParent(this); - } - } -} - -void CXmlNode::replaceChild(int inIndex, const XmlNodeRef& inNewChild) -{ - assert(inIndex >= 0 && inIndex < getChildCount()); - assert(inNewChild != 0); - if (inIndex >= 0 && inIndex < getChildCount() && inNewChild) - { - IXmlNode* wasChild = m_childs[inIndex]; - - if (wasChild->getParent() == this) - { - wasChild->setParent(XmlNodeRef()); // child is orphaned, will be freed by Release() below if this parent is last holding a reference to it - } - wasChild->Release(); - inNewChild->AddRef(); - m_childs[inIndex] = inNewChild; - inNewChild->setParent(this); - } -} - -XmlNodeRef CXmlNode::newChild(const char* tagName) -{ - XmlNodeRef node = createNode(tagName); - addChild(node); - return node; -} - -void CXmlNode::removeChild(const XmlNodeRef& node) -{ - XmlNodes::iterator it = std::find(m_childs.begin(), m_childs.end(), (IXmlNode*)node); - if (it != m_childs.end()) - { - m_childs.erase(it); - } -} - -void CXmlNode::removeAllChilds() -{ - m_childs.clear(); -} - -//! Get XML Node child nodes. -XmlNodeRef CXmlNode::getChild(int i) const -{ - assert(i >= 0 && i < (int)m_childs.size()); - return m_childs[i]; -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::copyAttributes(XmlNodeRef fromNode) -{ - IXmlNode* inode = fromNode; - CXmlNode* n = (CXmlNode*)inode; - if (n->m_pStringPool == m_pStringPool) - { - m_attributes = n->m_attributes; - } - else - { - m_attributes.resize(n->m_attributes.size()); - for (int i = 0; i < (int)n->m_attributes.size(); i++) - { - m_attributes[i].key = m_pStringPool->AddString(n->m_attributes[i].key); - m_attributes[i].value = m_pStringPool->AddString(n->m_attributes[i].value); - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttributeByIndex(int index, const char** key, const char** value) -{ - XmlAttributes::iterator it = m_attributes.begin(); - if (it != m_attributes.end()) - { - std::advance(it, index); - if (it != m_attributes.end()) - { - *key = it->key; - *value = it->value; - return true; - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -XmlNodeRef CXmlNode::clone() -{ - CXmlNode* node = new CXmlNode; - node->m_pStringPool = m_pStringPool; - m_pStringPool->AddRef(); - node->m_tag = m_tag; - node->m_content = m_content; - // Clone attributes. - CXmlNode* n = (CXmlNode*)(IXmlNode*)node; - n->copyAttributes(this); - // Clone sub nodes. - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - XmlNodeRef child = (*it)->clone(); - node->addChild(child); - } - - return node; -} - -////////////////////////////////////////////////////////////////////////// -static void AddTabsToString(XmlString& xml, int level) -{ - static const char* tabs[] = { - "", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - }; - // Add tabs. - if (level < sizeof(tabs) / sizeof(tabs[0])) - { - xml += tabs[level]; - } - else - { - for (int i = 0; i < level; i++) - { - xml += " "; - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::IsValidXmlString(const char* str) const -{ - if (strcspn(str, "\"\'&><") == strlen(str)) - { - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -XmlString CXmlNode::MakeValidXmlString(const XmlString& instr) const -{ - XmlString str = instr; - - // check if str contains any invalid characters - str.replace("&", "&"); - str.replace("\"", """); - str.replace("\'", "'"); - str.replace("<", "<"); - str.replace(">", ">"); - - return str; -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::AddToXmlString(XmlString& xml, int level) const -{ - AddTabsToString(xml, level); - - // Begin Tag - if (m_attributes.empty()) - { - xml += "<"; - xml += m_tag; - if (*m_content == 0 && m_childs.empty()) - { - // Compact tag form. - xml += " />\n"; - return; - } - xml += ">"; - } - else - { - xml += "<"; - xml += m_tag; - xml += " "; - - // Put attributes. - for (XmlAttributes::const_iterator it = m_attributes.begin(); it != m_attributes.end(); ) - { - xml += it->key; - xml += "=\""; - if (IsValidXmlString(it->value)) - { - xml += it->value; - } - else - { - xml += MakeValidXmlString(it->value); - } - it++; - if (it != m_attributes.end()) - { - xml += "\" "; - } - else - { - xml += "\""; - } - } - if (*m_content == 0 && m_childs.empty()) - { - // Compact tag form. - xml += "/>\n"; - return; - } - xml += ">"; - } - - // Put node content. - if (IsValidXmlString(m_content)) - { - xml += m_content; - } - else - { - xml += MakeValidXmlString(m_content); - } - - if (m_childs.empty()) - { - xml += "\n"; - return; - } - - xml += "\n"; - - // Add sub nodes. - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - IXmlNode* node = *it; - ((CXmlNode*)node)->AddToXmlString(xml, level + 1); - } - - // Add tabs. - AddTabsToString(xml, level); - xml += "\n"; -} - -IXmlStringData* CXmlNode::getXMLData(int nReserveMem) const -{ - CXmlStringData* pStrData = new CXmlStringData; - pStrData->m_string.reserve(nReserveMem); - AddToXmlString(pStrData->m_string, 0); - return pStrData; -} - -XmlString CXmlNode::getXML(int level) const -{ - static XmlString xml; - xml = ""; - xml.reserve(6000000); - - AddToXmlString(xml, level); - return xml; -} - -bool CXmlNode::saveToFile(const char* fileName) -{ - XmlString xml = getXML(); - FILE* file = nullptr; - azfopen(&file, fileName, "wt"); - if (file) - { - const char* sxml = (const char*)xml; - fprintf(file, "%s", sxml); - fclose(file); - return true; - } - return false; -} - -/** -****************************************************************************** -* XmlParserImp class. -****************************************************************************** -*/ -class XmlParserImp - : public IXmlStringPool -{ -public: - explicit XmlParserImp(bool bRemoveNonessentialSpacesFromContent); - ~XmlParserImp(); - void beginParse(); - bool parse(const char* buffer, int bufLen); - XmlNodeRef endParse(XmlString& errorString); - - // Add new string to pool. - char* AddString(const char* str) { return m_stringPool.Append(str, (int)strlen(str)); } - //char* AddString( const char *str ) { return (char*)str; } - -protected: - void onStartElement(const char* tagName, const char** atts); - void onEndElement(const char* tagName); - void onRawData(const char* data); - - static void startElement(void* userData, const char* name, const char** atts) - { - ((XmlParserImp*)userData)->onStartElement(name, atts); - } - static void endElement(void* userData, const char* name) - { - ((XmlParserImp*)userData)->onEndElement(name); - } - static void characterData(void* userData, const char* s, int len) - { - char str[500000]; - if (len > sizeof(str) - 1) - { - assert(0); - len = sizeof(str) - 1; - } - memcpy(str, s, len); - str[len] = 0; - ((XmlParserImp*)userData)->onRawData(str); - } - - // First node will become root node. - std::vector nodeStack; - XmlNodeRef m_root; - - XML_Parser m_parser; - CSimpleStringPool m_stringPool; - bool m_bRemoveNonessentialSpacesFromContent; -}; - -/** -****************************************************************************** -* XmlParserImp -****************************************************************************** -*/ -void XmlParserImp::onStartElement(const char* tagName, const char** atts) -{ - XmlNodeRef parent; - CXmlNode* pCNode = new CXmlNode; - pCNode->m_pStringPool = this; - pCNode->m_pStringPool->AddRef(); - pCNode->m_tag = AddString(tagName); - - XmlNodeRef node = pCNode; - - if (!nodeStack.empty()) - { - parent = nodeStack.back(); - } - else - { - m_root = node; - } - nodeStack.push_back(node); - - if (parent) - { - parent->addChild(node); - } - - uint64 line = XML_GetCurrentLineNumber((XML_Parser)m_parser); - node->setLine(line > INT_MAX ? INT_MAX : (int)line); - - // Call start element callback. - int i = 0; - int numAttrs = 0; - while (atts[i] != 0) - { - numAttrs++; - i += 2; - } - if (numAttrs > 0) - { - i = 0; - pCNode->m_attributes.resize(numAttrs); - int nAttr = 0; - while (atts[i] != 0) - { - pCNode->m_attributes[nAttr].key = AddString(atts[i]); - pCNode->m_attributes[nAttr].value = AddString(atts[i + 1]); - nAttr++; - i += 2; - } - // Sort attributes. - //std::sort( pCNode->m_attributes.begin(),pCNode->m_attributes.end() ); - } -} - -void XmlParserImp::onEndElement([[maybe_unused]] const char* tagName) -{ - assert(!nodeStack.empty()); - if (!nodeStack.empty()) - { - nodeStack.pop_back(); - } -} - -void XmlParserImp::onRawData(const char* const data) -{ - if (data && data[0]) - { - CXmlNode* const node = (CXmlNode*)(IXmlNode*)nodeStack.back(); - - if (!m_bRemoveNonessentialSpacesFromContent) - { - // Implementation note: Skipping spaces in beginning (even although - // m_bRemoveNonessentialSpacesFromContent is false) allows us - // to avoid having lot of "space only" content nodes - if (node->m_content.empty()) - { - const size_t len = strlen(data); - const size_t spaceCount = strspn(data, "\r\n\t "); - - if (spaceCount < len) - { - node->m_content += &data[spaceCount]; - } - } - else - { - node->m_content += data; - } - } - else - { - const size_t len = strlen(data); - const size_t spaceCount = strspn(data, "\r\n\t "); - - if ((spaceCount > 0) && (!node->m_content.empty())) - { - node->m_content += " "; - } - - if (spaceCount < len) - { - node->m_content += &data[spaceCount]; - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -static void* custom_xml_malloc(size_t nSize) -{ - return CryModuleMalloc(nSize); -} -static void* custom_xml_realloc(void* p, size_t nSize) -{ - return CryModuleRealloc(p, nSize); -} -static void custom_xml_free(void* p) -{ - CryModuleFree(p); -} - -namespace CryXML_Internal -{ - XML_Memory_Handling_Suite memHandler; - XML_Memory_Handling_Suite* GetMemoryHandler() - { - memHandler.malloc_fcn = custom_xml_malloc; // CryModuleMalloc; - memHandler.realloc_fcn = custom_xml_realloc; // CryModuleRealloc; - memHandler.free_fcn = custom_xml_free; // CryModuleFree; - return &memHandler; - } -} - -XmlParserImp::XmlParserImp(bool bRemoveNonessentialSpacesFromContent) -{ - m_bRemoveNonessentialSpacesFromContent = bRemoveNonessentialSpacesFromContent; - - m_root = 0; - nodeStack.reserve(100); - - m_parser = XML_ParserCreate_MM(NULL, CryXML_Internal::GetMemoryHandler(), NULL); - - XML_SetUserData(m_parser, this); - XML_SetElementHandler(m_parser, startElement, endElement); - XML_SetCharacterDataHandler(m_parser, characterData); - XML_SetEncoding(m_parser, "utf-8"); -} - -XmlParserImp::~XmlParserImp() -{ - XML_ParserFree(m_parser); -} - -void XmlParserImp::beginParse() -{ - m_root = 0; - - m_stringPool.SetBlockSize(1 << 20); -} - -bool XmlParserImp::parse(const char* buffer, int bufLen) -{ - if (!XML_Parse(m_parser, buffer, (int)bufLen, 0)) - { - m_root = 0; - return false; - } - return true; -} - -XmlNodeRef XmlParserImp::endParse(XmlString& errorString) -{ - errorString = ""; - - if (!XML_Parse(m_parser, "", 0, 1)) - { - m_root = 0; - } - - if (!m_root) - { - const char* const errorText = XML_ErrorString(XML_GetErrorCode(m_parser)); - if (errorText) - { - errorString += "XML Error: "; - errorString += errorText; - // The following code is disabled by 'if (false)' because XML_GetCurrentLineNumber() - // XML_GetCurrentColumnNumber() return incorrect numbers. - // The issue (wrong numbers) might be fixed if/when we upgrade to a newer version - // of the Expat XML library (on 2014/02/26 CryEngine still uses expat version 1.95.2 - // from 2001/07/27, although the latest expat version is 2.1.0 from 2012/03/24). - if (false) - { - char s[64]; - azsprintf(s, " at line %d, column %d", (int)XML_GetCurrentLineNumber(m_parser), (int)XML_GetCurrentColumnNumber(m_parser)); - errorString += s; - } - } - } - - XmlNodeRef root = m_root; - m_root = 0; - return root; -} - -XmlParser::XmlParser(bool bRemoveNonessentialSpacesFromContent) -{ - m_pImpl = new XmlParserImp(bRemoveNonessentialSpacesFromContent); - m_pImpl->AddRef(); -} - -XmlParser::~XmlParser() -{ - m_pImpl->Release(); -} - -//! Parse xml file. -XmlNodeRef XmlParser::parse(const char* fileName) -{ - m_errorString = ""; - - std::vector buf; - auto pPak = GetISystem()->GetIPak(); - AZ::IO::HandleType file = pPak->FOpen(fileName, "rb"); - if (file) - { - pPak->FSeek(file, 0, SEEK_END); - int fileSize = pPak->FTell(file); - pPak->FSeek(file, 0, SEEK_SET); - buf.resize(fileSize); - pPak->FRead(&(buf[0]), fileSize, file); - pPak->FClose(file); - m_pImpl->parse(&buf[0], buf.size()); - return m_pImpl->endParse(m_errorString); - } - else - { - return XmlNodeRef(); - } -} - -//! Parse xml from memory buffer. -XmlNodeRef XmlParser::parseBuffer(const char* buffer) -{ - m_errorString = ""; - m_pImpl->beginParse(); - m_pImpl->parse(buffer, strlen(buffer)); - return m_pImpl->endParse(m_errorString); -} - -XmlNodeRef XmlParser::parseSource(const IXmlBufferSource* source) -{ - m_errorString = ""; - char buffer[40000]; - enum - { - bufferSize = sizeof(buffer) / sizeof(buffer[0]) - }; - m_pImpl->beginParse(); - int bytesRead = source->Read(buffer, bufferSize); - while (bytesRead) - { - if (!m_pImpl->parse(buffer, bytesRead)) - { - break; - } - bytesRead = source->Read(buffer, bufferSize); - } - return m_pImpl->endParse(m_errorString); -} diff --git a/Code/Tools/CryXML/XML/xml.h b/Code/Tools/CryXML/XML/xml.h deleted file mode 100644 index 8e9072acbf..0000000000 --- a/Code/Tools/CryXML/XML/xml.h +++ /dev/null @@ -1,471 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYXML_XML_XML_H -#define CRYINCLUDE_CRYXML_XML_XML_H -#pragma once - - -#include -#include -#include - -#include "IXml.h" - -struct IXmlBufferSource; - -struct IXmlStringPool -{ -public: - IXmlStringPool() { m_refCount = 0; } - virtual ~IXmlStringPool() {}; - void AddRef() { m_refCount++; }; - void Release() - { - if (--m_refCount <= 0) - { - delete this; - } - }; - virtual char* AddString(const char* str) = 0; -private: - int m_refCount; -}; - -/************************************************************************/ -/* XmlParser class, Parse xml and return root xml node if success. */ -/************************************************************************/ -class XmlParser -{ -public: - explicit XmlParser(bool bRemoveNonessentialSpacesFromContent); - ~XmlParser(); - - //! Parse xml file. - XmlNodeRef parse(const char* fileName); - - //! Parse xml from memory buffer. - XmlNodeRef parseBuffer(const char* buffer); - - XmlNodeRef parseSource(const IXmlBufferSource* source); - - const char* getErrorString() const { return m_errorString; } - -private: - XmlString m_errorString; - class XmlParserImp* m_pImpl; -}; - -// Compare function for string comparasion, can be strcmp or _stricmp -typedef int (__cdecl * XmlStrCmpFunc)(const char* str1, const char* str2); -extern XmlStrCmpFunc g_pXmlStrCmp; - -////////////////////////////////////////////////////////////////////////// -// XmlAttribute class -////////////////////////////////////////////////////////////////////////// -struct XmlAttribute -{ - const char* key; - const char* value; - - bool operator<(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) < 0; } - bool operator>(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) > 0; } - bool operator==(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) == 0; } - bool operator!=(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) != 0; } -}; - -//! Xml node attributes class. -typedef std::vector XmlAttributes; -typedef XmlAttributes::iterator XmlAttrIter; -typedef XmlAttributes::const_iterator XmlAttrConstIter; - -/** -****************************************************************************** -* CXmlNode class -* Never use CXmlNode directly instead use reference counted XmlNodeRef. -****************************************************************************** -*/ - -class CXmlNode - : public IXmlNode -{ -public: - //! Constructor. - CXmlNode(); - CXmlNode(const char* tag); - //! Destructor. - ~CXmlNode(); - - virtual void DeleteThis(); - - //! Create new XML node. - XmlNodeRef createNode(const char* tag); - - //! Get XML node tag. - const char* getTag() const { return m_tag; }; - void setTag(const char* tag); - - //! Return true if given tag equal to node tag. - bool isTag(const char* tag) const; - - //! Get XML Node attributes. - virtual int getNumAttributes() const { return (int)m_attributes.size(); }; - //! Return attribute key and value by attribute index. - virtual bool getAttributeByIndex(int index, const char** key, const char** value); - - virtual void copyAttributes(XmlNodeRef fromNode); - - //! Get XML Node attribute for specified key. - const char* getAttr(const char* key) const; - - //! Get XML Node attribute for specified key. - // Returns true if the attribute existes, alse otherwise. - bool getAttr(const char* key, const char** value) const; - - //! Check if attributes with specified key exist. - bool haveAttr(const char* key) const; - - //! Creates new xml node and add it to childs list. - XmlNodeRef newChild(const char* tagName); - - //! Adds new child node. - void addChild(const XmlNodeRef& node); - //! Remove child node. - void removeChild(const XmlNodeRef& node); - - void insertChild(int nIndex, const XmlNodeRef& node); - void replaceChild(int nIndex, const XmlNodeRef& node); - - //! Remove all child nodes. - void removeAllChilds(); - - //! Get number of child XML nodes. - int getChildCount() const { return (int)m_childs.size(); }; - - //! Get XML Node child nodes. - XmlNodeRef getChild(int i) const; - - //! Find node with specified tag. - XmlNodeRef findChild(const char* tag) const; - void deleteChild(const char* tag); - void deleteChildAt(int nIndex); - - //! Get parent XML node. - XmlNodeRef getParent() const { return m_parent; } - void setParent(const XmlNodeRef& inRef); - - //! Returns content of this node. - const char* getContent() const { return m_content.c_str(); }; - void setContent(const char* str); - - XmlNodeRef clone(); - - //! Returns line number for XML tag. - int getLine() const { return m_line; }; - //! Set line number in xml. - void setLine(int line) { m_line = line; }; - - //! Returns XML of this node and sub nodes. - virtual IXmlStringData* getXMLData(int nReserveMem = 0) const; - XmlString getXML(int level = 0) const; - bool saveToFile(const char* fileName) override; - - //! Set new XML Node attribute (or override attribute with same key). - void setAttr(const char* key, const char* value); - void setAttr(const char* key, int value); - void setAttr(const char* key, unsigned int value); - void setAttr(const char* key, int64 value); - void setAttr(const char* key, uint64 value, bool useHexFormat = true); - void setAttr(const char* key, float value); - void setAttr(const char* key, double value); - void setAttr(const char* key, const Vec2& value); - void setAttr(const char* key, const Vec2d& value); - void setAttr(const char* key, const Ang3& value); - void setAttr(const char* key, const Vec3& value); - void setAttr(const char* key, const Vec4& value); - void setAttr(const char* key, const Vec3d& value); - void setAttr(const char* key, const Quat& value); - - //! Delete attrbute. - void delAttr(const char* key); - //! Remove all node attributes. - void removeAllAttributes(); - - //! Get attribute value of node. - bool getAttr(const char* key, int& value) const; - bool getAttr(const char* key, unsigned int& value) const; - bool getAttr(const char* key, int64& value) const; - bool getAttr(const char* key, uint64& value, bool useHexFormat = true /*ignored*/) const; - bool getAttr(const char* key, float& value) const; - bool getAttr(const char* key, double& value) const; - bool getAttr(const char* key, bool& value) const; - bool getAttr(const char* key, XmlString& value) const - { - XmlString v; - if (v = getAttr(key)) - { - value = v; - return true; - } - else - { - return false; - } - } - bool getAttr(const char* key, Vec2& value) const; - bool getAttr(const char* key, Vec2d& value) const; - bool getAttr(const char* key, Ang3& value) const; - bool getAttr(const char* key, Vec3& value) const; - bool getAttr(const char* key, Vec3d& value) const; - bool getAttr(const char* key, Vec4& value) const; - bool getAttr(const char* key, Quat& value) const; - bool getAttr(const char* key, ColorB& value) const; - // bool getAttr( const char *key,string &value ) const { XmlString v; if (getAttr(key,v)) { value = (const char*)v; return true; } else return false; } - -#if !defined(RESOURCE_COMPILER) - // - // Summary: - // Collect all allocated memory - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { assert(0); }; - - // Summary: - // Copies children to this node from a given node. - // Children are reference copied (shallow copy) and the children's parent is NOT set to this - // node, but left with its original parent (which is still the parent) - void shareChildren([[maybe_unused]] const XmlNodeRef& fromNode) { assert(0); }; - - // Summary: - // Returns XML of this node and sub nodes into tmpBuffer without XML checks (much faster) - XmlString getXMLUnsafe(int level, [[maybe_unused]] char* tmpBuffer, [[maybe_unused]] uint32 sizeOfTmpBuffer) const { return getXML(level); } - - // Notes: - // Save in small memory chunks. - bool saveToFile([[maybe_unused]] const char* fileName, [[maybe_unused]] size_t chunkSizeBytes, [[maybe_unused]] AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle) override { assert(0); return false; }; - // -#endif - -private: - void AddToXmlString(XmlString& xml, int level) const; - XmlString MakeValidXmlString(const XmlString& xml) const; - bool IsValidXmlString(const char* str) const; - XmlAttrConstIter GetAttrConstIterator(const char* key) const - { - XmlAttribute tempAttr; - tempAttr.key = key; - - XmlAttributes::const_iterator it = std::find(m_attributes.begin(), m_attributes.end(), tempAttr); - return it; - - /* - XmlAttributes::const_iterator it = std::lower_bound( m_attributes.begin(),m_attributes.end(),tempAttr ); - if (it != m_attributes.end() && _stricmp(it->key,key) == 0) - return it; - return m_attributes.end(); - */ - } - XmlAttrIter GetAttrIterator(const char* key) - { - XmlAttribute tempAttr; - tempAttr.key = key; - - XmlAttributes::iterator it = std::find(m_attributes.begin(), m_attributes.end(), tempAttr); - return it; - - // XmlAttributes::iterator it = std::lower_bound( m_attributes.begin(),m_attributes.end(),tempAttr ); - //if (it != m_attributes.end() && _stricmp(it->key,key) == 0) - //return it; - //return m_attributes.end(); - } - const char* GetValue(const char* key) const - { - XmlAttrConstIter it = GetAttrConstIterator(key); - if (it != m_attributes.end()) - { - return it->value; - } - return 0; - } - -private: - //! Line in XML file where this node firstly appeared (usefull for debugging). - int m_line; - - //! Tag of XML node. - const char* m_tag; - //! Content of XML node. - XmlString m_content; - //! Parent XML node. - CXmlNode* m_parent; - - // String pool used by this node. - IXmlStringPool* m_pStringPool; - - typedef std::vector XmlNodes; - XmlNodes m_childs; - //! Xml node attributes. - XmlAttributes m_attributes; - - friend class XmlParserImp; -}; - -#endif // __XML_HEADER__ - - -/* -#ifndef __XML_HEADER__ -#define __XML_HEADER__ - - - -class CXmlNode : public IXmlNode -{ -public: - //! Constructor. - CXmlNode( const char *tag ); - //! Destructor. - ~CXmlNode(); - - ////////////////////////////////////////////////////////////////////////// - //! Reference counting. - void AddRef() { m_refCount++; }; - //! When ref count reach zero XML node dies. - void Release(); - - //! Create new XML node. - XmlNodeRef createNode( const char *tag ); - - //! Get XML node tag. - const char *getTag() const { return m_tag; }; - void setTag( const char *tag ) { m_tag = tag; } - - //! Return true if givven tag equal to node tag. - bool isTag( const char *tag ) const; - - //! Get XML Node attributes. - virtual int getNumAttributes() const { return (int)m_attributes.size(); }; - //! Return attribute key and value by attribute index. - virtual bool getAttributeByIndex( int index,const char **key,const char **value ); - - virtual void* getFirstAttribute(); - virtual bool getNextAttribute( void** pIterator,const char **key,const char **value ); - - virtual void copyAttributes( XmlNodeRef fromNode ); - - //! Get XML Node attribute for specified key. - const char* getAttr( const char *key ) const; - //! Check if attributes with specified key exist. - bool haveAttr( const char *key ) const; - - //! Adds new child node. - void addChild( const XmlNodeRef &node ); - - //! Creates new xml node and add it to childs list. - XmlNodeRef newChild( const char *tagName ); - - //! Remove child node. - void removeChild( const XmlNodeRef &node ); - - //! Remove all child nodes. - void removeAllChilds(); - - //! Get number of child XML nodes. - int getChildCount() const { return (int)m_childs.size(); }; - - //! Get XML Node child nodes. - XmlNodeRef getChild( int i ) const; - - //! Find node with specified tag. - XmlNodeRef findChild( const char *tag ) const; - - //! Get parent XML node. - XmlNodeRef getParent() const { return m_parent; } - - //! Returns content of this node. - const char* getContent() const { return m_content; }; - void setContent( const char *str ) { m_content = str; }; - void addContent( const char *str ) { m_content += str; }; - - XmlNodeRef clone(); - - //! Returns line number for XML tag. - int getLine() const { return m_line; }; - //! Set line number in xml. - void setLine( int line ) { m_line = line; }; - - //! Returns XML of this node and sub nodes. - XmlString getXML( int level=0 ) const; - XmlString getBinaryXML() const; - bool saveToFile( const char *fileName, bool bBinary = false ); - bool saveToSink(IXMLDataSink* pSink, bool bBinary = false); - - //! Set new XML Node attribute (or override attribute with same key). - void setAttr( const char* key,const char* value ); - void setAttr( const char* key,int value ); - void setAttr( const char* key,unsigned int value ); - void setAttr( const char* key,uint64 value ); - void setAttr( const char* key,float value ); - void setAttr( const char* key,const Ang3& value ); - void setAttr( const char* key,const Vec3& value ); - void setAttr( const char* key,const Quat &value ); - - //! Delete attribute. - void delAttr( const char* key ); - //! Remove all node attributes. - void removeAllAttributes(); - - //! Get attribute value of node. - bool getAttr( const char *key,int &value ) const; - bool getAttr( const char *key,unsigned int &value ) const; - bool getAttr( const char *key,uint64 &value ) const; - bool getAttr( const char *key,float &value ) const; - bool getAttr( const char *key,Ang3& value ) const; - bool getAttr( const char *key,Vec3& value ) const; - bool getAttr( const char *key,Quat &value ) const; - bool getAttr( const char *key,bool &value ) const; - bool getAttr( const char *key,XmlString &value ) const { XmlString v; if (v=getAttr(key)) { value = v; return true; } else return false; } -// bool getAttr( const char *key,string &value ) const { XmlString v; if (getAttr(key,v)) { value = (const char*)v; return true; } else return false; } - - // Add an attribute structure directly. - void addAttr(XmlAttribute& attribute); - - void SetBuffer(StringBuffer* pStringBuffer); - -private: - void AddToXmlString( XmlString &xml,int level ) const; - -private: - StringBuffer* m_pStringBuffer; - - //! Ref count itself, its zeroed on node creation. - int m_refCount; - - //! Line in XML file where this node firstly appeared (usefull for debuggin). - int m_line; - //! Tag of XML node. - XmlString m_tag; - - //! Content of XML node. - XmlString m_content; - //! Parent XML node. - CXmlNode *m_parent; - //! Next XML node in same hierarchy level. - - typedef std::vector XmlNodes; - XmlNodes m_childs; - //! Xml node attributes. - XmlAttributes m_attributes; - static XmlAttribute tempAttr; -}; - -#endif // CRYINCLUDE_CRYXML_XML_XML_H -*/ diff --git a/Code/Tools/CryXML/XMLSerializer.cpp b/Code/Tools/CryXML/XMLSerializer.cpp deleted file mode 100644 index e1152f93a3..0000000000 --- a/Code/Tools/CryXML/XMLSerializer.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CryXML_precompiled.h" -#include "XMLSerializer.h" -#include "XML/xml.h" -#include "IXMLSerializer.h" -#include "StringUtils.h" - -XmlNodeRef XMLSerializer::CreateNode(const char* tag) -{ - return new CXmlNode(tag); -} - -bool XMLSerializer::Write(XmlNodeRef root, const char* szFileName) -{ - return root->saveToFile(szFileName); -} - -XmlNodeRef XMLSerializer::Read(const IXmlBufferSource& source, bool bRemoveNonessentialSpacesFromContent, int nErrorBufferSize, char* szErrorBuffer) -{ - XmlParser parser(bRemoveNonessentialSpacesFromContent); - XmlNodeRef root = parser.parseSource(&source); - if (nErrorBufferSize > 0 && szErrorBuffer) - { - const char* const err = parser.getErrorString(); - cry_strcpy(szErrorBuffer, nErrorBufferSize, err ? err : ""); - } - return root; -} diff --git a/Code/Tools/CryXML/XMLSerializer.h b/Code/Tools/CryXML/XMLSerializer.h deleted file mode 100644 index 7730b19963..0000000000 --- a/Code/Tools/CryXML/XMLSerializer.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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_CRYXML_XMLSERIALIZER_H -#define CRYINCLUDE_CRYXML_XMLSERIALIZER_H -#pragma once - - -#include "IXMLSerializer.h" - -class XMLSerializer - : public IXMLSerializer -{ -public: - virtual XmlNodeRef CreateNode(const char* tag); - virtual bool Write(XmlNodeRef root, const char* szFileName); - - virtual XmlNodeRef Read(const IXmlBufferSource& source, bool bRemoveNonessentialSpacesFromContent, int nErrorBufferSize, char* szErrorBuffer); -}; - -#endif // CRYINCLUDE_CRYXML_XMLSERIALIZER_H diff --git a/Code/Tools/CryXML/cryxml_files.cmake b/Code/Tools/CryXML/cryxml_files.cmake deleted file mode 100644 index d81ace11b7..0000000000 --- a/Code/Tools/CryXML/cryxml_files.cmake +++ /dev/null @@ -1,22 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - CryXML.cpp - XMLSerializer.cpp - ICryXML.h - IXMLSerializer.h - XMLSerializer.h - XML/xml.cpp - XML/xml.h - CryXML_precompiled.h - CryXML_precompiled.cpp -) diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings deleted file mode 100644 index e7bbaccd46..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /bumptype=1 /mipmirror=1 /preset=Bump2Normalmap_highQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings deleted file mode 100644 index 5f78477ca8..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_highQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings deleted file mode 100644 index 5f78477ca8..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_highQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings deleted file mode 100644 index 6466dc9099..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /mipalphacoverage=0 /mipmirror=1 /preset=Diffuse_highQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings deleted file mode 100644 index acfbe2a750..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=0 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings deleted file mode 100644 index 00ecf3a56e..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings deleted file mode 100644 index 00ecf3a56e..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings deleted file mode 100644 index cab995b31e..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Bump2Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings deleted file mode 100644 index c5a53f8bd5..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings deleted file mode 100644 index 1048249b71..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Diffuse_lowQ diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings deleted file mode 100644 index db0b877f24..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=ReferenceImage diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings deleted file mode 100644 index 1048249b71..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Diffuse_lowQ diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings deleted file mode 100644 index 84c0416421..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /ms=0 /preset=Diffuse_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings deleted file mode 100644 index c5a53f8bd5..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings deleted file mode 100644 index cb9f25b5d9..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings deleted file mode 100644 index c5a53f8bd5..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings deleted file mode 100644 index 47b9f504fd..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=ColorChart diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings deleted file mode 100644 index 3e5edcd652..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumptype=1 /preset=Bump2Normalmap_lowQ /reduce=0 diff --git a/Gems/Blast/Assets/.p4ignore b/Gems/Blast/Assets/.p4ignore deleted file mode 100644 index 7015097e56..0000000000 --- a/Gems/Blast/Assets/.p4ignore +++ /dev/null @@ -1 +0,0 @@ -*.physx diff --git a/Tools/AnimationTest/assetImportTest.bat b/Tools/AnimationTest/assetImportTest.bat deleted file mode 100644 index 205c17280b..0000000000 --- a/Tools/AnimationTest/assetImportTest.bat +++ /dev/null @@ -1,31 +0,0 @@ -REM -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 - -TITLE asset import test - -SETLOCAL EnableExtensions -set EXE=AssetProcessor_tmp.exe -FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF %%x == %EXE% goto FOUND -echo Make sure asset processor is running before run this script. -goto FIN -:FOUND - -SET F="..\..\Cache\SamplesProject\pc\samplesproject\objects" - -IF EXIST %F% ( - RMDIR /S /Q %F% - ECHO Detected folder at %F% - ECHO Make sure there's no fail / crash in asset processor after all job finished. -) ELSE (ECHO folder %F% NOT FOUND) - -:FIN -PAUSE \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/7z.exe b/Tools/DeepBandwidthToExcel/7z.exe deleted file mode 100644 index 85fa5e2917..0000000000 --- a/Tools/DeepBandwidthToExcel/7z.exe +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2ca56c2a96859b5171e7d24c81ed4d281da0ea26a7eaff7eac975d337eb4a2e1 -size 266752 diff --git a/Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe b/Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe deleted file mode 100644 index b89cb8c457..0000000000 --- a/Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6b8dc17c53df32173fd82d8bfc844bc3752bf6cbaf1bf2fd334dd6949f44b04b -size 1050344 diff --git a/Tools/DeepBandwidthToExcel/Template/[Content_Types].xml b/Tools/DeepBandwidthToExcel/Template/[Content_Types].xml deleted file mode 100644 index 3c4fc1468a..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/[Content_Types].xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/_rels/.rels b/Tools/DeepBandwidthToExcel/Template/_rels/.rels deleted file mode 100644 index 74bfd8d955..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/_rels/.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/docProps/app.xml b/Tools/DeepBandwidthToExcel/Template/docProps/app.xml deleted file mode 100644 index 6430cd86f5..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/docProps/app.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Microsoft Excel0falseWorksheets9Group TotalsMessage TotalsPolicy CountPolicy ImpactSerialisation ImpactBandwidth Over TimeSocket Packets Over TimeSocket Bits Over TimeWarningsCrytek UKfalsefalsefalse12.0000 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/docProps/core.xml b/Tools/DeepBandwidthToExcel/Template/docProps/core.xml deleted file mode 100644 index f1efda39ff..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/docProps/core.xml +++ /dev/null @@ -1,2 +0,0 @@ - -leelee2012-03-06T13:44:11Z2012-03-23T08:28:17Z \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels deleted file mode 100644 index e9dc190f2c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml b/Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml deleted file mode 100644 index 2fb95911c6..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml deleted file mode 100644 index 3e3737423c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Schedule Group'Group Totals'!###---SHEET1_COL0---###peterpaul'Group Totals'!###---SHEET1_COL1---###General55 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml deleted file mode 100644 index 54d3f0da26..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Message'Message Totals'!###---SHEET2_COL0---###peterpaul'Message Totals'!###---SHEET2_COL1---###General55 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml deleted file mode 100644 index f405df758f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Policy Count'Policy Count'!###---SHEET3_COL0---###ui2eid'Policy Count'!###---SHEET3_COL1---###General20801811398975 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml deleted file mode 100644 index 6d461a7cd5..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Policy Impact (Bits Per Policy)'Policy Impact'!###---SHEET4_COL0---###wrlddMov'Policy Impact'!###---SHEET4_COL1---###General5354582913312905 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml deleted file mode 100644 index 5276503965..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - - - - - - - - - - - Overall By Serialisation Impact (Bits - - - - Per Serialise) - - - - - - - - - - - - - - - - - - - - 'Serialisation Impact'!###---SHEET5_COL0---### - - - - wrld - - - dMov - - - - - - - 'Serialisation Impact'!###---SHEET5_COL1---### - - General - - - 53545829 - - - 13312905 - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml deleted file mode 100644 index 3dbcb710ee..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - - - Bandwidth Over Time - - - - - - - - - - ###---SHEET6_CHART---### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml deleted file mode 100644 index 324a3d0296..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - - - - Socket - - - - Packets Per Second - - - - - - - - - - - ###---SHEET7_CHART---### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml deleted file mode 100644 index 9aed1eaa0b..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - Socket - - - - Bits Per Second - - - - - - - - - - ###---SHEET8_CHART---### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels deleted file mode 100644 index 91223aab09..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels deleted file mode 100644 index 63233beb83..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels deleted file mode 100644 index c53f6617a5..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels deleted file mode 100644 index 7fe138bac4..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels deleted file mode 100644 index 22864411ec..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels deleted file mode 100644 index 424914396d..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels deleted file mode 100644 index b1404c3db9..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels deleted file mode 100644 index a9e371607f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml deleted file mode 100644 index 70ea7ed3be..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml +++ /dev/null @@ -1,2 +0,0 @@ - -43809902857429952440114299 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml deleted file mode 100644 index f8a60ce08a..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml +++ /dev/null @@ -1,2 +0,0 @@ - -338100076199285810254057150 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml deleted file mode 100644 index 75e5d9ed25..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml +++ /dev/null @@ -1,2 +0,0 @@ - -2276225095250283714754019050 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml deleted file mode 100644 index de297dbb14..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml +++ /dev/null @@ -1,2 +0,0 @@ - -3001333492851435040123824 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml deleted file mode 100644 index b7c2cf9c02..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml +++ /dev/null @@ -1,2 +0,0 @@ - -25524500104775284572004095250 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml deleted file mode 100644 index c610b4c052..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml +++ /dev/null @@ -1,2 +0,0 @@ - -338099914287528257174409525 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml deleted file mode 100644 index 14d255a242..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml +++ /dev/null @@ -1,2 +0,0 @@ - -247624310477526533399389525 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml deleted file mode 100644 index 1b94acd279..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml +++ /dev/null @@ -1,2 +0,0 @@ - -23809931047752744767539114301 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml b/Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml deleted file mode 100644 index 2fbc1ad0b7..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---STRINGSTABLE---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/styles.xml b/Tools/DeepBandwidthToExcel/Template/xl/styles.xml deleted file mode 100644 index 8238b50fd0..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/styles.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml b/Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml deleted file mode 100644 index 9944f3ecab..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/workbook.xml b/Tools/DeepBandwidthToExcel/Template/xl/workbook.xml deleted file mode 100644 index 19c26d83b6..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/workbook.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels deleted file mode 100644 index 205832e91b..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels deleted file mode 100644 index b48a928346..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels deleted file mode 100644 index c0c5ded4a6..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels deleted file mode 100644 index f34eab954f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels deleted file mode 100644 index 67118d3a1e..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels deleted file mode 100644 index 656a337f58..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels deleted file mode 100644 index efc518bb3f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels deleted file mode 100644 index 586d2d3c76..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml deleted file mode 100644 index 1fbfb22964..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---SHEET1_DATA---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml deleted file mode 100644 index 0d72f8c9da..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---SHEET2_DATA---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml deleted file mode 100644 index 18717c6987..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---SHEET3_DATA---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml deleted file mode 100644 index 9442249676..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - -###---SHEET4_DATA---### - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml deleted file mode 100644 index 14f48b192c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - -###---SHEET5_DATA---### - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml deleted file mode 100644 index fa7a8d800b..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - -###---SHEET6_DATA---### - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml deleted file mode 100644 index 708d01d20c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - -###---SHEET7_DATA---### - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml deleted file mode 100644 index 164cdcdde2..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - -###---SHEET8_DATA---### - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml deleted file mode 100644 index a3a3b40230..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - -###---SHEET9_DATA---### - - diff --git a/scripts/build/package/Platform/Windows/package_filelists/atom.json b/scripts/build/package/Platform/Windows/package_filelists/atom.json index f084173cb2..5f3d3b78cb 100644 --- a/scripts/build/package/Platform/Windows/package_filelists/atom.json +++ b/scripts/build/package/Platform/Windows/package_filelists/atom.json @@ -38,24 +38,13 @@ "AzTestRunner/**": "#include", "CrashHandler/**": "#include", "CryCommonTools/**": "#include", - "CrySCompileServer/**": "#include", - "CryXML/**": "#include", "DeltaCataloger/**": "#include", - "GemRegistry/**": "#include", "GridHub/**": "#include", - "HLSLCrossCompiler/**": "#include", - "HLSLCrossCompilerMETAL/**": "#include", - "LyIdentity/**": "#include", - "LyMetrics/**": "#include", "News/**": "#include", "PythonBindingsExample/**": "#include", - "RC/**": "#include", "RemoteConsole/**": "#include", "SceneAPI/**": "#include", "SerializeContextTools/**": "#include", - "ShaderCacheGen/**": "#include", - "SharedQMLResource/**": "#include", - "Woodpecker/**": "#include", "CMakeLists.txt": "#include" }, "CMakeLists.txt": "#include" From 795aa114e69f6846133442da9d74cae56416ca39 Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Thu, 13 May 2021 16:19:53 +0100 Subject: [PATCH 090/231] Improve selection in the viewport (#720) * improve selection in the viewport * remove debug code * updates following review feedback - update API comments from /// to //! from - add [[nodiscard]] attribute to member function - move constructor implementations to .cpp files * use lambda instead of ternary operator * fix unit test failure caused by typo --- .../AzFramework/Viewport/CameraInput.cpp | 95 ++++++----- .../AzFramework/Viewport/CameraInput.h | 29 ++-- .../AzFramework/Viewport/ClickDetector.cpp | 68 ++++++++ .../AzFramework/Viewport/ClickDetector.h | 75 +++++++++ .../AzFramework/Viewport/CursorState.h | 56 +++++++ .../AzFramework/azframework_files.cmake | 3 + .../EditorTransformComponentSelection.cpp | 36 +++- .../EditorTransformComponentSelection.h | 156 +++++++++--------- Code/Framework/Tests/ClickDetectorTests.cpp | 142 ++++++++++++++++ Code/Framework/Tests/CursorStateTests.cpp | 54 ++++++ .../Tests/frameworktests_files.cmake | 2 + 11 files changed, 573 insertions(+), 143 deletions(-) create mode 100644 Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp create mode 100644 Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h create mode 100644 Code/Framework/AzFramework/AzFramework/Viewport/CursorState.h create mode 100644 Code/Framework/Tests/ClickDetectorTests.cpp create mode 100644 Code/Framework/Tests/CursorStateTests.cpp diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 8669b58911..daf2c63921 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -156,35 +157,25 @@ namespace AzFramework camera.m_lookAt = transform.GetTranslation() + (camera.Rotation().GetBasisY() * -camera.m_lookDist); } - static ScreenVector CursorDelta(const AZStd::optional& currentPosition, const AZStd::optional& lastPosition) - { - return currentPosition.has_value() && lastPosition.has_value() ? currentPosition.value() - lastPosition.value() - : ScreenVector(0, 0); - } - bool CameraSystem::HandleEvents(const InputEvent& event) { if (const auto& cursor = AZStd::get_if(&event)) { - m_currentCursorPosition = cursor->m_position; + m_cursorState.SetCurrentPosition(cursor->m_position); } else if (const auto& scroll = AZStd::get_if(&event)) { m_scrollDelta = scroll->m_delta; } - return m_cameras.HandleEvents(event, CursorDelta(m_currentCursorPosition, m_lastCursorPosition), m_scrollDelta); + return m_cameras.HandleEvents(event, m_cursorState.CursorDelta(), m_scrollDelta); } Camera CameraSystem::StepCamera(const Camera& targetCamera, const float deltaTime) { - const auto cursorDelta = CursorDelta(m_currentCursorPosition, m_lastCursorPosition); - if (m_currentCursorPosition.has_value()) - { - m_lastCursorPosition = m_currentCursorPosition; - } + const auto nextCamera = m_cameras.StepCamera(targetCamera, m_cursorState.CursorDelta(), m_scrollDelta, deltaTime); - const auto nextCamera = m_cameras.StepCamera(targetCamera, cursorDelta, m_scrollDelta, deltaTime); + m_cursorState.Update(); m_scrollDelta = 0.0f; @@ -236,12 +227,12 @@ namespace AzFramework } } - // accumulate - Camera nextCamera = targetCamera; - for (auto& cameraInput : m_activeCameraInputs) - { - nextCamera = cameraInput->StepCamera(nextCamera, cursorDelta, scrollDelta, deltaTime); - } + const Camera nextCamera = AZStd::accumulate( + AZStd::begin(m_activeCameraInputs), AZStd::end(m_activeCameraInputs), targetCamera, + [cursorDelta, scrollDelta, deltaTime](Camera acc, auto& camera) { + acc = camera->StepCamera(acc, cursorDelta, scrollDelta, deltaTime); + return acc; + }); for (int i = 0; i < m_activeCameraInputs.size();) { @@ -275,34 +266,42 @@ namespace AzFramework } } + RotateCameraInput::RotateCameraInput(const InputChannelId rotateChannelId) + : m_rotateChannelId(rotateChannelId) + { + } + void RotateCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { - if (const auto& input = AZStd::get_if(&event)) - { - if (input->m_channelId == m_rotateChannelId) + const ClickDetector::ClickEvent clickEvent = [&event, this] { + if (const auto& input = AZStd::get_if(&event)) { - if (input->m_state == InputChannel::State::Began) + if (input->m_channelId == m_rotateChannelId) { - m_tryingToBegin = true; - m_moveAccumulator = 0.0f; - } - else if (input->m_state == InputChannel::State::Ended) - { - m_tryingToBegin = false; - EndActivation(); + if (input->m_state == InputChannel::State::Began) + { + return ClickDetector::ClickEvent::Down; + } + else if (input->m_state == InputChannel::State::Ended) + { + return ClickDetector::ClickEvent::Up; + } } } - } + return ClickDetector::ClickEvent::Nil; + }(); - if (m_tryingToBegin) + switch (const auto outcome = m_clickDetector.DetectClick(clickEvent, cursorDelta); outcome) { - // only allow the action to begin if the mouse has been moved a small amount - m_moveAccumulator += ScreenVectorLength(cursorDelta); - if (m_moveAccumulator > ed_cameraSystemLookDeadzone) - { - BeginActivation(); - m_tryingToBegin = false; - } + case ClickDetector::ClickOutcome::Move: + BeginActivation(); + break; + case ClickDetector::ClickOutcome::Release: + EndActivation(); + break; + default: + // noop + break; } } @@ -324,6 +323,12 @@ namespace AzFramework return nextCamera; } + PanCameraInput::PanCameraInput(const InputChannelId panChannelId, PanAxesFn panAxesFn) + : m_panAxesFn(AZStd::move(panAxesFn)) + , m_panChannelId(panChannelId) + { + } + void PanCameraInput::HandleEvents( const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { @@ -400,6 +405,11 @@ namespace AzFramework return TranslationType::Nil; } + TranslateCameraInput::TranslateCameraInput(TranslationAxesFn translationAxesFn) + : m_translationAxesFn(AZStd::move(translationAxesFn)) + { + } + void TranslateCameraInput::HandleEvents( const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { @@ -574,6 +584,11 @@ namespace AzFramework return nextCamera; } + OrbitDollyCursorMoveCameraInput::OrbitDollyCursorMoveCameraInput(const InputChannelId dollyChannelId) + : m_dollyChannelId(dollyChannelId) + { + } + void OrbitDollyCursorMoveCameraInput::HandleEvents( const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index 6475753017..41d7f11385 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -17,6 +17,8 @@ #include #include #include +#include +#include #include #include @@ -188,26 +190,21 @@ namespace AzFramework Cameras m_cameras; private: + CursorState m_cursorState; float m_scrollDelta = 0.0f; - AZStd::optional m_lastCursorPosition; - AZStd::optional m_currentCursorPosition; }; class RotateCameraInput : public CameraInput { public: - explicit RotateCameraInput(const InputChannelId rotateChannelId) - : m_rotateChannelId(rotateChannelId) - { - } + explicit RotateCameraInput(InputChannelId rotateChannelId); void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; private: InputChannelId m_rotateChannelId; - float m_moveAccumulator = 0.0f; - bool m_tryingToBegin = false; + ClickDetector m_clickDetector; }; struct PanAxes @@ -240,11 +237,8 @@ namespace AzFramework class PanCameraInput : public CameraInput { public: - PanCameraInput(const InputChannelId panChannelId, PanAxesFn panAxesFn) - : m_panAxesFn(AZStd::move(panAxesFn)) - , m_panChannelId(panChannelId) - { - } + PanCameraInput(InputChannelId panChannelId, PanAxesFn panAxesFn); + void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; @@ -283,10 +277,8 @@ namespace AzFramework class TranslateCameraInput : public CameraInput { public: - explicit TranslateCameraInput(TranslationAxesFn translationAxesFn) - : m_translationAxesFn(AZStd::move(translationAxesFn)) - { - } + explicit TranslateCameraInput(TranslationAxesFn translationAxesFn); + void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; void ResetImpl() override; @@ -363,8 +355,7 @@ namespace AzFramework class OrbitDollyCursorMoveCameraInput : public CameraInput { public: - explicit OrbitDollyCursorMoveCameraInput(const InputChannelId dollyChannelId) - : m_dollyChannelId(dollyChannelId) {} + explicit OrbitDollyCursorMoveCameraInput(InputChannelId dollyChannelId); void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp new file mode 100644 index 0000000000..5af44a81bc --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp @@ -0,0 +1,68 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or 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 AzFramework +{ + ClickDetector::ClickOutcome ClickDetector::DetectClick(const ClickEvent clickEvent, const ScreenVector& cursorDelta) + { + if (clickEvent == ClickEvent::Down) + { + const auto now = std::chrono::steady_clock::now(); + if (m_tryBeginTime) + { + const std::chrono::duration diff = now - m_tryBeginTime.value(); + if (diff.count() < m_doubleClickInterval) + { + return ClickOutcome::Nil; + } + } + + m_detectionState = DetectionState::WaitingForMove; + m_moveAccumulator = 0.0f; + + m_tryBeginTime = now; + } + else if (clickEvent == ClickEvent::Up) + { + const auto clickOutcome = [detectionState = m_detectionState] { + if (detectionState == DetectionState::WaitingForMove) + { + return ClickOutcome::Click; + } + if (detectionState == DetectionState::Moved) + { + return ClickOutcome::Release; + } + return ClickOutcome::Nil; + }(); + + m_detectionState = DetectionState::Nil; + return clickOutcome; + } + + if (m_detectionState == DetectionState::WaitingForMove) + { + // only allow the action to begin if the mouse has been moved a small amount + m_moveAccumulator += ScreenVectorLength(cursorDelta); + if (m_moveAccumulator > m_deadZone) + { + m_detectionState = DetectionState::Moved; + return ClickOutcome::Move; + } + } + + return ClickOutcome::Nil; + } +} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h new file mode 100644 index 0000000000..997ccd07d9 --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.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 + +#include + +namespace AzFramework +{ + struct ScreenVector; + + //! Utility class to help detect different types of mouse click (mouse down and up with + //! no movement), mouse move (down and initial move after some threshold) and mouse release + //! (mouse down with movement and then mouse up). + class ClickDetector + { + //! Alias for recording time of mouse down events + using Time = std::chrono::time_point; + + public: + //! Internal representation of click event (map from external event for this when + //! calling DetectClick). + enum class ClickEvent + { + Nil, + Down, + Up + }; + + //! The type of mouse click. + enum class ClickOutcome + { + Nil, //!< Not recognized. + Move, //!< Initial move after mouse down. + Click, //!< Mouse down and up with no intermediate movement. + Release //!< Mouse down with movement and then mouse up. + }; + + //! Called from any type of 'handle event' function. + ClickOutcome DetectClick(ClickEvent clickEvent, const ScreenVector& cursorDelta); + + void SetDoubleClickInterval(float doubleClickInterval); + + private: + //! Internal state of ClickDetector based on incoming events. + enum class DetectionState + { + Nil, //!< Initial state + WaitingForMove, //! Mouse down has happened but mouse hasn't yet moved. + Moved //! Mouse has moved, no longer will be counted as a click. + }; + + float m_moveAccumulator = 0.0f; //!< How far the mouse has moved after mouse down. + float m_deadZone = 2.0f; //!< How far to move before a click is cancelled (when Move will fire). + float m_doubleClickInterval = 0.4f; //!< Default double click interval, can be overridden. + DetectionState m_detectionState; //!< Internal state of ClickDetector. + AZStd::optional