diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py index 1fe60e3707..45e633a979 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py @@ -27,19 +27,19 @@ class TestPythonAssetProcessing(object): unexpected_lines = [] expected_lines = [ 'Mock asset exists', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_positive.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_negative.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_positive.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_negative.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_positive.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_negative.azmodel) found', - 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel) found' + 'AssetId found for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_positive_1.azmodel) found', + 'AssetId found for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_negative_1.azmodel) found', + 'AssetId found for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_positive_1.azmodel) found', + 'AssetId found for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_negative_1.azmodel) found', + 'AssetId found for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_positive_1.azmodel) found', + 'AssetId found for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_negative_1.azmodel) found', + 'AssetId found for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center_1.azmodel) found' ] timeout = 180 halt_on_unexpected = False test_directory = os.path.join(os.path.dirname(__file__)) testFile = os.path.join(test_directory, 'AssetBuilder_test_case.py') - editor.args.extend(['-NullRenderer', "--skipWelcomeScreenDialog", "--autotest_mode", "--runpythontest", testFile]) + editor.args.extend(['-NullRenderer', '-rhi=Null', "--skipWelcomeScreenDialog", "--autotest_mode", "--runpythontest", testFile]) with editor.start(): editorlog_file = os.path.join(editor.workspace.paths.project_log(), 'Editor.log') diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py index c1519a6fdb..8d418222ce 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py @@ -29,21 +29,21 @@ if (assetIdString.endswith(':528cca58') is False): print ('Mock asset exists') # These tests detect if the geom_group.fbx file turns into a number of azmodel product assets -def test_azmodel_product(generatedModelAssetPath, expectedSubId): +def test_azmodel_product(generatedModelAssetPath): azModelAssetType = azlmbr.math.Uuid_CreateString('{2C7477B6-69C5-45BE-8163-BCD6A275B6D8}', 0) assetId = azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, 'GetAssetIdByPath', generatedModelAssetPath, azModelAssetType, False) assetIdString = assetId.to_string() - if (assetIdString.endswith(':' + expectedSubId) is False): - raise_and_stop(f'Asset at path {generatedModelAssetPath} has unexpected asset ID ({assetIdString}) for ({generatedModelAssetPath}), expected {expectedSubId}!') + if (assetId.is_valid()): + print(f'AssetId found for asset ({generatedModelAssetPath}) found') else: - print(f'Expected subId for asset ({generatedModelAssetPath}) found') + raise_and_stop(f'Asset at path {generatedModelAssetPath} has unexpected asset ID ({assetIdString})!') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_positive.azmodel', '1024be55') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_negative.azmodel', '1052c94e') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_positive.azmodel', '10130556') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_negative.azmodel', '1065724d') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_positive.azmodel', '10d16e68') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_negative.azmodel', '10a71973') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel', '10412075') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_positive_1.azmodel') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_negative_1.azmodel') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_positive_1.azmodel') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_negative_1.azmodel') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_positive_1.azmodel') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_negative_1.azmodel') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center_1.azmodel') azlmbr.editor.EditorToolsApplicationRequestBus(azlmbr.bus.Broadcast, 'ExitNoPrompt') diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py index 1d72885504..ef0a592df0 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py @@ -47,28 +47,28 @@ def open_material(file_path): """ :return: uuid of material document opened """ - return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "OpenDocument", file_path) + return azlmbr.atomtools.AtomToolsDocumentSystemRequestBus(bus.Broadcast, "OpenDocument", file_path) def is_open(document_id): """ :return: bool """ - return materialeditor.MaterialDocumentRequestBus(bus.Event, "IsOpen", document_id) + return azlmbr.atomtools.AtomToolsDocumentRequestBus(bus.Event, "IsOpen", document_id) def save_document(document_id): """ :return: bool success """ - return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "SaveDocument", document_id) + return azlmbr.atomtools.AtomToolsDocumentSystemRequestBus(bus.Broadcast, "SaveDocument", document_id) def save_document_as_copy(document_id, target_path): """ :return: bool success """ - return materialeditor.MaterialDocumentSystemRequestBus( + return azlmbr.atomtools.AtomToolsDocumentSystemRequestBus( bus.Broadcast, "SaveDocumentAsCopy", document_id, target_path ) @@ -77,7 +77,7 @@ def save_document_as_child(document_id, target_path): """ :return: bool success """ - return materialeditor.MaterialDocumentSystemRequestBus( + return azlmbr.atomtools.AtomToolsDocumentSystemRequestBus( bus.Broadcast, "SaveDocumentAsChild", document_id, target_path ) @@ -86,39 +86,39 @@ def save_all(): """ :return: bool success """ - return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "SaveAllDocuments") + return azlmbr.atomtools.AtomToolsDocumentSystemRequestBus(bus.Broadcast, "SaveAllDocuments") def close_document(document_id): """ :return: bool success """ - return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseDocument", document_id) + return azlmbr.atomtools.AtomToolsDocumentSystemRequestBus(bus.Broadcast, "CloseDocument", document_id) def close_all_documents(): """ :return: bool success """ - return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseAllDocuments") + return azlmbr.atomtools.AtomToolsDocumentSystemRequestBus(bus.Broadcast, "CloseAllDocuments") def close_all_except_selected(document_id): """ :return: bool success """ - return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseAllDocumentsExcept", document_id) + return azlmbr.atomtools.AtomToolsDocumentSystemRequestBus(bus.Broadcast, "CloseAllDocumentsExcept", document_id) def get_property(document_id, property_name): """ :return: property value or invalid value if the document is not open or the property_name can't be found """ - return materialeditor.MaterialDocumentRequestBus(bus.Event, "GetPropertyValue", document_id, property_name) + return azlmbr.atomtools.AtomToolsDocumentRequestBus(bus.Event, "GetPropertyValue", document_id, property_name) def set_property(document_id, property_name, value): - materialeditor.MaterialDocumentRequestBus(bus.Event, "SetPropertyValue", document_id, property_name, value) + azlmbr.atomtools.AtomToolsDocumentRequestBus(bus.Event, "SetPropertyValue", document_id, property_name, value) def is_pane_visible(pane_name): @@ -175,7 +175,7 @@ def wait_for_condition(function, timeout_in_seconds=1.0): with Timeout(timeout_in_seconds) as t: while True: try: - atomtools.general.idle_wait_frames(1) + azlmbr.atomtools.general.idle_wait_frames(1) except Exception: print("WARNING: Couldn't wait for frame") @@ -269,6 +269,6 @@ class ScreenshotHelper: def capture_screenshot(file_path): - return ScreenshotHelper(atomtools.general.idle_wait_frames).capture_screenshot_blocking( + return ScreenshotHelper(azlmbr.atomtools.general.idle_wait_frames).capture_screenshot_blocking( os.path.join(file_path) ) diff --git a/Code/Editor/CMakeLists.txt b/Code/Editor/CMakeLists.txt index fca16a2093..9baa83179b 100644 --- a/Code/Editor/CMakeLists.txt +++ b/Code/Editor/CMakeLists.txt @@ -238,9 +238,13 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) 3rdParty::Qt::Core 3rdParty::Qt::Gui 3rdParty::Qt::Widgets + 3rdParty::Qt::Test Legacy::CryCommon AZ::AzToolsFramework + AZ::AzToolsFramework.Tests + AZ::AzToolsFrameworkTestCommon Legacy::EditorLib + Gem::AtomToolsFramework.Static RUNTIME_DEPENDENCIES Gem::LmbrCentral ) diff --git a/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp b/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp new file mode 100644 index 0000000000..a2a7617083 --- /dev/null +++ b/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp @@ -0,0 +1,152 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include +#include + +namespace UnitTest +{ + using AzToolsFramework::ViewportInteraction::MouseInteractionEvent; + + class EditorInteractionViewportSelectionFake : public AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Handler + { + public: + void Connect(); + void Disconnect(); + + // EditorInteractionSystemViewportSelectionRequestBus overrides ... + void SetHandler(const AzToolsFramework::ViewportSelectionRequestsBuilderFn& interactionRequestsBuilder); + void SetDefaultHandler(); + bool InternalHandleMouseViewportInteraction(const MouseInteractionEvent& mouseInteraction); + bool InternalHandleMouseManipulatorInteraction(const MouseInteractionEvent& mouseInteraction); + + AZStd::function m_internalHandleMouseViewportInteraction; + AZStd::function m_internalHandleMouseManipulatorInteraction; + }; + + void EditorInteractionViewportSelectionFake::Connect() + { + AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Handler::BusConnect(AzToolsFramework::GetEntityContextId()); + } + + void EditorInteractionViewportSelectionFake::Disconnect() + { + AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Handler::BusDisconnect(); + } + + void EditorInteractionViewportSelectionFake::SetHandler( + [[maybe_unused]] const AzToolsFramework::ViewportSelectionRequestsBuilderFn& interactionRequestsBuilder) + { + // noop + } + + void EditorInteractionViewportSelectionFake::SetDefaultHandler() + { + // noop + } + + bool EditorInteractionViewportSelectionFake::InternalHandleMouseViewportInteraction(const MouseInteractionEvent& mouseInteraction) + { + if (m_internalHandleMouseViewportInteraction) + { + return m_internalHandleMouseViewportInteraction(mouseInteraction); + } + + return false; + } + + bool EditorInteractionViewportSelectionFake::InternalHandleMouseManipulatorInteraction(const MouseInteractionEvent& mouseInteraction) + { + if (m_internalHandleMouseManipulatorInteraction) + { + return m_internalHandleMouseManipulatorInteraction(mouseInteraction); + } + + return false; + } + + class ViewportManipulatorControllerFixture : public AllocatorsTestFixture + { + public: + static const AzFramework::ViewportId TestViewportId = AzFramework::ViewportId(0); + + void SetUp() override + { + AllocatorsTestFixture::SetUp(); + + m_rootWidget = AZStd::make_unique(); + m_rootWidget->setFixedSize(QSize(100, 100)); + + m_controllerList = AZStd::make_shared(); + m_controllerList->RegisterViewportContext(TestViewportId); + + m_inputChannelMapper = AZStd::make_unique(m_rootWidget.get(), TestViewportId); + } + + void TearDown() + { + m_inputChannelMapper.reset(); + + m_controllerList->UnregisterViewportContext(TestViewportId); + m_controllerList.reset(); + m_rootWidget.reset(); + + AllocatorsTestFixture::TearDown(); + } + + AZStd::unique_ptr m_rootWidget; + AzFramework::ViewportControllerListPtr m_controllerList; + AZStd::unique_ptr m_inputChannelMapper; + }; + + TEST_F(ViewportManipulatorControllerFixture, An_event_is_not_propagated_to_the_viewport_when_a_manipulator_handles_it_first) + { + // forward input events to our controller list + QObject::connect( + m_inputChannelMapper.get(), &AzToolsFramework::QtEventToAzInputMapper::InputChannelUpdated, m_rootWidget.get(), + [this](const AzFramework::InputChannel* inputChannel, [[maybe_unused]] QEvent* event) + { + m_controllerList->HandleInputChannelEvent( + AzFramework::ViewportControllerInputEvent{ TestViewportId, nullptr, *inputChannel }); + }); + + EditorInteractionViewportSelectionFake editorInteractionViewportFake; + editorInteractionViewportFake.m_internalHandleMouseManipulatorInteraction = [](const MouseInteractionEvent&) + { + // report the event was handled (manipulator was interacted with) + return true; + }; + + bool viewportInteractionCalled = false; + editorInteractionViewportFake.m_internalHandleMouseViewportInteraction = [&viewportInteractionCalled](const MouseInteractionEvent&) + { + // we should not call this as the manipulator will have consumed this event + viewportInteractionCalled = true; + return true; + }; + + editorInteractionViewportFake.Connect(); + + m_controllerList->Add(AZStd::make_shared()); + + // simulate a press and move + MousePressAndMove(m_rootWidget.get(), QPoint(10, 10), QPoint(10, 10), Qt::MouseButton::LeftButton); + MouseMove(m_rootWidget.get(), QPoint(20, 20), QPoint(10, 10), Qt::MouseButton::LeftButton); + MouseMove(m_rootWidget.get(), QPoint(30, 30), QPoint(0, 0), Qt::MouseButton::LeftButton); + QTest::mouseRelease(m_rootWidget.get(), Qt::MouseButton::LeftButton, Qt::KeyboardModifier::NoModifier, QPoint(30, 30)); + + // ensure the viewport did not receive the event when it was intercepted first by the manipulator + EXPECT_FALSE(viewportInteractionCalled); + + editorInteractionViewportFake.Disconnect(); + } +} // namespace UnitTest diff --git a/Code/Editor/Plugins/EditorAssetImporter/SceneSerializationHandler.cpp b/Code/Editor/Plugins/EditorAssetImporter/SceneSerializationHandler.cpp index 441fb362d6..c087a27ba4 100644 --- a/Code/Editor/Plugins/EditorAssetImporter/SceneSerializationHandler.cpp +++ b/Code/Editor/Plugins/EditorAssetImporter/SceneSerializationHandler.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -96,7 +97,7 @@ namespace AZ } AZStd::shared_ptr scene = - AssetImportRequest::LoadSceneFromVerifiedPath(cleanPath, sceneSourceGuid, AssetImportRequest::RequestingApplication::Editor); + AssetImportRequest::LoadSceneFromVerifiedPath(cleanPath, sceneSourceGuid, AssetImportRequest::RequestingApplication::Editor, SceneAPI::SceneCore::LoadingComponent::TYPEINFO_Uuid()); if (!scene) { AZ_TracePrintf(Utilities::ErrorWindow, "Failed to load the requested scene."); diff --git a/Code/Editor/ViewportManipulatorController.cpp b/Code/Editor/ViewportManipulatorController.cpp index 0b519f0787..5282af009f 100644 --- a/Code/Editor/ViewportManipulatorController.cpp +++ b/Code/Editor/ViewportManipulatorController.cpp @@ -28,6 +28,8 @@ namespace SandboxEditor { } + ViewportManipulatorControllerInstance::~ViewportManipulatorControllerInstance() = default; + AzToolsFramework::ViewportInteraction::MouseButton ViewportManipulatorControllerInstance::GetMouseButton( const AzFramework::InputChannel& inputChannel) { @@ -103,14 +105,21 @@ namespace SandboxEditor // Cache the ray trace results when doing manipulator interaction checks, no need to recalculate after if (event.m_priority == ManipulatorPriority) { - AzFramework::ScreenPoint screenPosition = AzFramework::ScreenPoint(0, 0); - ViewportMouseCursorRequestBus::EventResult( - screenPosition, GetViewportId(), &ViewportMouseCursorRequestBus::Events::ViewportCursorScreenPosition); + const auto* position = event.m_inputChannel.GetCustomData(); + AZ_Assert(position, "Expected PositionData2D but found nullptr"); - m_mouseInteraction.m_mousePick.m_screenCoordinates = screenPosition; + AzFramework::WindowSize windowSize; + AzFramework::WindowRequestBus::EventResult( + windowSize, event.m_windowHandle, &AzFramework::WindowRequestBus::Events::GetClientAreaSize); + + auto screenPoint = AzFramework::ScreenPoint( + position->m_normalizedPosition.GetX() * windowSize.m_width, + position->m_normalizedPosition.GetY() * windowSize.m_height); + + m_mouseInteraction.m_mousePick.m_screenCoordinates = screenPoint; AZStd::optional ray; ViewportInteractionRequestBus::EventResult( - ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPosition); + ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPoint); if (ray.has_value()) { @@ -118,6 +127,7 @@ namespace SandboxEditor m_mouseInteraction.m_mousePick.m_rayDirection = ray.value().direction; } } + eventType = MouseEvent::Move; } else if (auto mouseButton = GetMouseButton(event.m_inputChannel); mouseButton != MouseButton::None) @@ -217,8 +227,7 @@ namespace SandboxEditor interactionHandled, AzToolsFramework::GetEntityContextId(), targetInteractionEvent, mouseInteractionEvent); } - // Only filter button/key press events, not release events - return interactionHandled && event.m_inputChannel.IsActive(); + return interactionHandled; } void ViewportManipulatorControllerInstance::ResetInputChannels() diff --git a/Code/Editor/ViewportManipulatorController.h b/Code/Editor/ViewportManipulatorController.h index 968b6745c1..d551eb3647 100644 --- a/Code/Editor/ViewportManipulatorController.h +++ b/Code/Editor/ViewportManipulatorController.h @@ -8,25 +8,29 @@ #pragma once -#include -#include #include +#include +#include #include +#include + namespace SandboxEditor { class ViewportManipulatorControllerInstance; - using ViewportManipulatorController = AzFramework::MultiViewportController; + using ViewportManipulatorController = AzFramework:: + MultiViewportController; class ViewportManipulatorControllerInstance final : public AzFramework::MultiViewportControllerInstanceInterface { public: - explicit ViewportManipulatorControllerInstance(AzFramework::ViewportId viewport, ViewportManipulatorController* controller); + SANDBOX_API ViewportManipulatorControllerInstance(AzFramework::ViewportId viewport, ViewportManipulatorController* controller); + SANDBOX_API ~ViewportManipulatorControllerInstance(); - bool HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) override; - void ResetInputChannels() override; - void UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) override; + SANDBOX_API bool HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) override; + SANDBOX_API void ResetInputChannels() override; + SANDBOX_API void UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) override; private: bool IsDoubleClick(AzToolsFramework::ViewportInteraction::MouseButton) const; @@ -39,4 +43,4 @@ namespace SandboxEditor AZStd::unordered_map m_pendingDoubleClicks; AZ::ScriptTimePoint m_curTime; }; -} //namespace SandboxEditor +} // namespace SandboxEditor diff --git a/Code/Editor/editor_lib_test_files.cmake b/Code/Editor/editor_lib_test_files.cmake index c67e70ddbd..49f707b1f6 100644 --- a/Code/Editor/editor_lib_test_files.cmake +++ b/Code/Editor/editor_lib_test_files.cmake @@ -20,6 +20,7 @@ set(FILES Lib/Tests/test_ViewPanePythonBindings.cpp Lib/Tests/test_ViewportTitleDlgPythonBindings.cpp Lib/Tests/test_DisplaySettingsPythonBindings.cpp + Lib/Tests/test_ViewportManipulatorController.cpp DisplaySettingsPythonFuncs.cpp DisplaySettingsPythonFuncs.h ) diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp index 2c1d97dcf6..8312f9fa63 100644 --- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp +++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp @@ -207,7 +207,10 @@ namespace AzFramework // Handles Win32 Window Event callbacks LRESULT CALLBACK NativeWindowImpl_Win32::WindowCallback(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - NativeWindowImpl_Win32* nativeWindowImpl = reinterpret_cast(GetWindowLongPtr(hWnd, GWLP_USERDATA)); + NativeWindowImpl_Win32* nativeWindowImpl = reinterpret_cast(GetWindowLongPtr(hWnd, GWLP_USERDATA)); + + // If set to true, call DefWindowProc to ensure the default Windows behavior occurs + bool shouldBubbleEventUp = false; switch (message) { @@ -276,14 +279,19 @@ namespace AzFramework uint32_t refreshRate = DisplayConfig.dmDisplayFrequency; WindowNotificationBus::Event( nativeWindowImpl->GetWindowHandle(), &WindowNotificationBus::Events::OnRefreshRateChanged, refreshRate); + shouldBubbleEventUp = true; break; } default: - return DefWindowProc(hWnd, message, wParam, lParam); + shouldBubbleEventUp = true; break; } - return 0; + if (!shouldBubbleEventUp) + { + return 0; + } + return DefWindowProc(hWnd, message, wParam, lParam); } void NativeWindowImpl_Win32::WindowSizeChanged(const uint32_t width, const uint32_t height) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index b5cf5fb878..7df1e1b5c1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -219,42 +219,10 @@ namespace AzToolsFramework bool PrefabEditorEntityOwnershipService::SaveToStream(AZ::IO::GenericStream& stream, AZStd::string_view filename) { AZ::IO::Path relativePath = m_loaderInterface->GenerateRelativePath(filename); - AzToolsFramework::Prefab::TemplateId templateId = m_prefabSystemComponent->GetTemplateIdFromFilePath(relativePath); m_rootInstance->SetTemplateSourcePath(relativePath); - - if (templateId == AzToolsFramework::Prefab::InvalidTemplateId) - { - m_rootInstance->m_containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent()); - HandleEntitiesAdded({ m_rootInstance->m_containerEntity.get() }); - - AzToolsFramework::Prefab::PrefabDom dom; - bool success = AzToolsFramework::Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(*m_rootInstance, dom); - if (!success) - { - AZ_Error("Prefab", false, "Failed to convert current root instance into a DOM when saving file '%.*s'", AZ_STRING_ARG(filename)); - return false; - } - templateId = m_prefabSystemComponent->AddTemplate(relativePath, AZStd::move(dom)); - - if (templateId == AzToolsFramework::Prefab::InvalidTemplateId) - { - AZ_Error("Prefab", false, "Couldn't add new template id '%i' when saving file '%.*s'", templateId, AZ_STRING_ARG(filename)); - return false; - } - } - - Prefab::TemplateId prevTemplateId = m_rootInstance->GetTemplateId(); - m_rootInstance->SetTemplateId(templateId); - - if (prevTemplateId != Prefab::InvalidTemplateId && templateId != prevTemplateId) - { - // Make sure we only have one level template loaded at a time - m_prefabSystemComponent->RemoveTemplate(prevTemplateId); - } - + AZStd::string out; - if (!m_loaderInterface->SaveTemplateToString(m_rootInstance->GetTemplateId(), out)) { return false; @@ -266,7 +234,7 @@ namespace AzToolsFramework { return false; } - m_prefabSystemComponent->SetTemplateDirtyFlag(templateId, false); + m_prefabSystemComponent->SetTemplateDirtyFlag(m_rootInstance->GetTemplateId(), false); return true; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.cpp index 4f238ac336..b7776238ba 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.cpp @@ -162,7 +162,6 @@ namespace AzToolsFramework : QObject(sourceWidget) , m_sourceWidget(sourceWidget) , m_keyboardModifiers(AZStd::make_shared()) - , m_cursorPosition(AZStd::make_shared()) { InitializeKeyMappings(); InitializeMouseButtonMappings(); @@ -230,24 +229,17 @@ namespace AzToolsFramework return false; } - // Because there's no "end" to mouse movement and wheel events, we reset mouse movement channels that have been opened - // during the next processed non-mouse event. - if (m_mouseChannelsNeedUpdate && event->type() != QEvent::Type::MouseMove && event->type() != QEvent::Type::Wheel) - { - m_cursorPosition->m_normalizedPositionDelta = AZ::Vector2::CreateZero(); - ProcessPendingMouseEvents(); - m_mouseChannelsNeedUpdate = false; - } + const auto eventType = event->type(); // Only accept mouse & key release events that originate from an object that is not our target widget, // as we don't want to erroneously intercept user input meant for another component. - if (object != m_sourceWidget && event->type() != QEvent::Type::KeyRelease && event->type() != QEvent::Type::MouseButtonRelease) + if (object != m_sourceWidget && eventType != QEvent::Type::KeyRelease && eventType != QEvent::Type::MouseButtonRelease) { return false; } // If our focus changes, go ahead and reset all input devices. - if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut) + if (eventType == QEvent::FocusIn || eventType == QEvent::FocusOut) { HandleFocusChange(event); } @@ -255,27 +247,28 @@ namespace AzToolsFramework // ShortcutOverride is used in lieu of KeyPress for high priority input channels like Alt // that need to be accepted and stopped before they bubble up and cause unintended behavior. else if ( - event->type() == QEvent::Type::KeyPress || event->type() == QEvent::Type::KeyRelease || - event->type() == QEvent::Type::ShortcutOverride) + eventType == QEvent::Type::KeyPress || eventType == QEvent::Type::KeyRelease || eventType == QEvent::Type::ShortcutOverride) { QKeyEvent* keyEvent = static_cast(event); HandleKeyEvent(keyEvent); } // Map mouse events to input channels. - else if (event->type() == QEvent::Type::MouseButtonPress || event->type() == QEvent::Type::MouseButtonRelease || event->type() == QEvent::Type::MouseButtonDblClick) + else if ( + eventType == QEvent::Type::MouseButtonPress || eventType == QEvent::Type::MouseButtonRelease || + eventType == QEvent::Type::MouseButtonDblClick) { QMouseEvent* mouseEvent = static_cast(event); HandleMouseButtonEvent(mouseEvent); } // Map mouse movement to the movement input channels. // This includes SystemCursorPosition alongside Movement::X and Movement::Y. - else if (event->type() == QEvent::Type::MouseMove) + else if (eventType == QEvent::Type::MouseMove) { QMouseEvent* mouseEvent = static_cast(event); HandleMouseMoveEvent(mouseEvent); } // Map wheel events to the mouse Z movement channel. - else if (event->type() == QEvent::Type::Wheel) + else if (eventType == QEvent::Type::Wheel) { QWheelEvent* wheelEvent = static_cast(event); HandleWheelEvent(wheelEvent); @@ -303,14 +296,16 @@ namespace AzToolsFramework auto mouseWheelChannel = GetInputChannel(AzFramework::InputDeviceMouse::Movement::Z); - systemCursorChannel->ProcessRawInputEvent(m_cursorPosition->m_normalizedPositionDelta.GetLength()); + systemCursorChannel->ProcessRawInputEvent(m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta.GetLength()); // Generate movement events based on the pixel delta divided by the DPI scaling factor, to calculate a rough approximation // of cursor movement velocity. movementXChannel->ProcessRawInputEvent( - m_cursorPosition->m_normalizedPositionDelta.GetX() * aznumeric_cast(m_sourceWidget->width()) / static_cast(m_sourceWidget->devicePixelRatioF())); + m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta.GetX() * aznumeric_cast(m_sourceWidget->width()) / + m_sourceWidget->devicePixelRatioF()); movementYChannel->ProcessRawInputEvent( - m_cursorPosition->m_normalizedPositionDelta.GetY() * aznumeric_cast(m_sourceWidget->height()) / static_cast(m_sourceWidget->devicePixelRatioF())); - mouseWheelChannel->ProcessRawInputEvent(0.f); + m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta.GetY() * aznumeric_cast(m_sourceWidget->height()) / + m_sourceWidget->devicePixelRatioF()); + mouseWheelChannel->ProcessRawInputEvent(0.0f); NotifyUpdateChannelIfNotIdle(systemCursorChannel, nullptr); NotifyUpdateChannelIfNotIdle(movementXChannel, nullptr); @@ -358,14 +353,13 @@ namespace AzToolsFramework void QtEventToAzInputMapper::HandleMouseMoveEvent(QMouseEvent* mouseEvent) { - AZ::Vector2 lastCursorPosition = m_cursorPosition->m_normalizedPosition; + AZ::Vector2 lastCursorPosition = m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition; const QPoint mousePos = mouseEvent->pos(); const AZ::Vector2 normalizedPosition = WidgetPositionToNormalizedPosition(mousePos); - m_cursorPosition->m_normalizedPositionDelta = normalizedPosition - m_cursorPosition->m_normalizedPosition; - m_cursorPosition->m_normalizedPosition = normalizedPosition; + m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta = normalizedPosition - m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition; + m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition = normalizedPosition; ProcessPendingMouseEvents(); - m_mouseChannelsNeedUpdate = true; if (m_capturingCursor) { @@ -376,7 +370,7 @@ namespace AzToolsFramework // Even though we just set the cursor position, there are edge cases such as remote desktop that will leave // the cursor position unchanged. For safety, we re-cache our last cursor position for delta generation. QPoint actualWidgetPosition = m_sourceWidget->mapFromGlobal(QCursor::pos()); - m_cursorPosition->m_normalizedPosition = WidgetPositionToNormalizedPosition(actualWidgetPosition); + m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition = WidgetPositionToNormalizedPosition(actualWidgetPosition); } } @@ -427,21 +421,18 @@ namespace AzToolsFramework } cursorZChannel->ProcessRawInputEvent(aznumeric_cast(wheelAngle)); NotifyUpdateChannelIfNotIdle(cursorZChannel, wheelEvent); - m_mouseChannelsNeedUpdate = true; } void QtEventToAzInputMapper::HandleFocusChange(QEvent* event) { for (auto& channelData : m_channels) { - // If resetting the input device changed the channel state, submit it to the mapped channel list - // for processing. + // If resetting the input device changed the channel state, submit it to the mapped channel list for processing. if (channelData.second->IsActive()) { channelData.second->UpdateState(false); NotifyUpdateChannelIfNotIdle(channelData.second, event); } } - m_mouseChannelsNeedUpdate = false; } } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.h index 919d8fcc2a..0187cb2e5b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.h @@ -138,8 +138,6 @@ namespace AzToolsFramework // The current keyboard modifier state used by our synthetic key input channels. AZStd::shared_ptr m_keyboardModifiers; - // The current normalized cursor position used by our synthetic system cursor event. - AZStd::shared_ptr m_cursorPosition; // A lookup table for Qt key -> AZ input channel. AZStd::unordered_map m_keyMappings; // A lookup table for Qt mouse button -> AZ input channel. @@ -152,8 +150,6 @@ namespace AzToolsFramework AZStd::unordered_map m_channels; // The source widget to map events from, used to calculate the relative mouse position within the widget bounds. QWidget* m_sourceWidget; - // Flags when mouse movement channels have been opened and may need to be closed (as there are no movement ended events). - bool m_mouseChannelsNeedUpdate = false; // Flags whether or not Qt events should currently be processed. bool m_enabled = true; // Flags whether or not the cursor is being constrained to the source widget (for invisible mouse movement). diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Logger/TraceLogger.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Logger/TraceLogger.cpp index 5f1546bf83..e81aaed6c9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Logger/TraceLogger.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Logger/TraceLogger.cpp @@ -5,11 +5,9 @@ * */ -#include - #include #include - +#include namespace AzToolsFramework { @@ -25,6 +23,22 @@ namespace AzToolsFramework bool TraceLogger::OnOutput(const char* window, const char* message) { + for (const auto& filter : m_windowFilters) + { + if (AZ::StringFunc::Contains(window, filter)) + { + return true; + } + } + + for (const auto& filter : m_messageFilters) + { + if (AZ::StringFunc::Contains(message, filter)) + { + return true; + } + } + if (m_logFile) { m_logFile->AppendLog(AzFramework::LogFile::SEV_NORMAL, window, message); @@ -36,10 +50,10 @@ namespace AzToolsFramework return false; } - void TraceLogger::WriteStartupLog(const AZStd::string& logFileName) - { + void TraceLogger::PrepareLogFile(const AZStd::string& logFileName) + { using namespace AzFramework; - + AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); AZ_Assert(fileIO != nullptr, "FileIO should be running at this point"); @@ -71,4 +85,34 @@ namespace AzToolsFramework m_logFile->FlushLog(); } } + + void TraceLogger::AddWindowFilter(const AZStd::string& filter) + { + m_windowFilters.insert(filter); + } + + void TraceLogger::RemoveWindowFilter(const AZStd::string& filter) + { + m_windowFilters.erase(filter); + } + + void TraceLogger::ClearWindowFilter() + { + m_windowFilters.clear(); + } + + void TraceLogger::AddMessageFilter(const AZStd::string& filter) + { + m_messageFilters.insert(filter); + } + + void TraceLogger::RemoveMessageFilter(const AZStd::string& filter) + { + m_messageFilters.erase(filter); + } + + void TraceLogger::ClearMessageFilter() + { + m_messageFilters.clear(); + } } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Logger/TraceLogger.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Logger/TraceLogger.h index a10f4fc2df..10708e3239 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Logger/TraceLogger.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Logger/TraceLogger.h @@ -22,8 +22,26 @@ namespace AzToolsFramework TraceLogger(); ~TraceLogger(); - //! Intalize logging for O3DEToolsApplications - void WriteStartupLog(const AZStd::string& logFileName); + //! Open log file and dump log sink into it + void PrepareLogFile(const AZStd::string& logFileName); + + //! Add filter to ignore messages for windows with matching names + void AddWindowFilter(const AZStd::string& filter); + + //! Remove window filter + void RemoveWindowFilter(const AZStd::string& filter); + + //! Clear window filters + void ClearWindowFilter(); + + //! Add filter to ignore messages with matching names + void AddMessageFilter(const AZStd::string& filter); + + //! Remove message filter + void RemoveMessageFilter(const AZStd::string& filter); + + //! Clear message filters + void ClearMessageFilter(); protected: ////////////////////////////////////////////////////////////////////////// @@ -38,6 +56,8 @@ namespace AzToolsFramework AZStd::string message; }; AZStd::vector m_startupLogSink; + AZStd::unordered_set m_windowFilters; + AZStd::unordered_set m_messageFilters; AZStd::unique_ptr m_logFile; }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.cpp index 1bec929223..6608e87784 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.cpp @@ -27,6 +27,35 @@ using namespace AzToolsFramework; namespace UnitTest { + void MousePressAndMove( + QWidget* widget, const QPoint& initialPositionWidget, const QPoint& mouseDelta, const Qt::MouseButton mouseButton) + { + QPoint position = widget->mapToGlobal(initialPositionWidget); + QTest::mousePress(widget, mouseButton, Qt::NoModifier, position); + + MouseMove(widget, initialPositionWidget, mouseDelta, mouseButton); + } + + // Note: There are a series of bugs in Qt that appear to be preventing mouseMove events + // firing when sent through the QTest framework. This is a work around for our version + // of Qt. In future this can hopefully be simplified. See ^1 for workaround. + // More info: Issues with mouse move in Qt + // - https://bugreports.qt.io/browse/QTBUG-5232 + // - https://bugreports.qt.io/browse/QTBUG-69414 + // - https://lists.qt-project.org/pipermail/development/2019-July/036873.html + void MouseMove(QWidget* widget, const QPoint& initialPositionWidget, const QPoint& mouseDelta, const Qt::MouseButton mouseButton) + { + QPoint nextPosition = widget->mapToGlobal(initialPositionWidget + mouseDelta); + + // ^1 To ensure a mouse move event is fired we must call the test mouse move function + // and also send a mouse move event that matches. Each on their own do not appear to + // work - please see the links above for more context. + QTest::mouseMove(widget, nextPosition); + QMouseEvent mouseMoveEvent( + QEvent::MouseMove, QPointF(nextPosition), QPointF(nextPosition), Qt::NoButton, mouseButton, Qt::NoModifier); + QApplication::sendEvent(widget, &mouseMoveEvent); + } + bool TestWidget::eventFilter(QObject* watched, QEvent* event) { AZ_UNUSED(watched); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h index 3c413fd21e..b3a660d0f2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h @@ -59,6 +59,21 @@ namespace UnitTest { constexpr AZStd::string_view prefabSystemSetting = "/Amazon/Preferences/EnablePrefabSystem"; + /// Performs a mouse press and move event on the provided widget. + /// @param widget The widget to perform the mouse press and move on. + /// @param initialPositionWidget The position of the mouse relative to the widget (will be remapped to a global position internally). + /// @param mouseDelta How far to move the mouse. + /// @param mouseButton The button to be used during the press and move. + void MousePressAndMove( + QWidget* widget, const QPoint& initialPositionWidget, const QPoint& mouseDelta, Qt::MouseButton mouseButton = Qt::LeftButton); + + /// Performs a mouse move event on the provided widget. + /// @param widget The widget to perform the mouse move on. + /// @param initialPositionWidget The position of the mouse relative to the widget (will be remapped to a global position internally). + /// @param mouseDelta How far to move the mouse (note: mouseDelta may be zero and the mouse will only be moved to initialPosition). + /// @param mouseButton The button to be held during the move. + void MouseMove(QWidget* widget, const QPoint& initialPosition, const QPoint& mouseDelta, Qt::MouseButton mouseButton = Qt::NoButton); + /// Test widget to store QActions generated by EditorTransformComponentSelection. class TestWidget : public QWidget { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h index ef1dfb0414..543d5fb3a5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h @@ -313,7 +313,7 @@ namespace AzToolsFramework //! Utility function to return EntityContextId. inline AzFramework::EntityContextId GetEntityContextId() { - AzFramework::EntityContextId entityContextId; + auto entityContextId = AzFramework::EntityContextId::CreateNull(); EditorEntityContextRequestBus::BroadcastResult(entityContextId, &EditorEntityContextRequests::GetEditorEntityContextId); return entityContextId; diff --git a/Code/Framework/AzToolsFramework/CMakeLists.txt b/Code/Framework/AzToolsFramework/CMakeLists.txt index 2754dd19eb..e444ce5efb 100644 --- a/Code/Framework/AzToolsFramework/CMakeLists.txt +++ b/Code/Framework/AzToolsFramework/CMakeLists.txt @@ -59,6 +59,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PUBLIC AZ::AzTestShared PRIVATE + 3rdParty::Qt::Test 3rdParty::googletest::GMock 3rdParty::GoogleBenchmark AZ::AzToolsFramework @@ -75,8 +76,9 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE Tests BUILD_DEPENDENCIES - PRIVATE + PUBLIC AZ::AzTestShared + PRIVATE 3rdParty::Qt::Test AZ::AzFrameworkTestShared AZ::AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/Tests/SpinBoxTests.cpp b/Code/Framework/AzToolsFramework/Tests/SpinBoxTests.cpp index a88cb68638..2d524cbcf4 100644 --- a/Code/Framework/AzToolsFramework/Tests/SpinBoxTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/SpinBoxTests.cpp @@ -107,31 +107,6 @@ namespace UnitTest EXPECT_THAT(m_doubleSpinBoxWithLineEdit, Ne(nullptr)); } - // Note: There are a series of bugs in Qt that appear to be preventing mouseMove events - // firing when sent through the QTest framework. This is a work around for our version - // of Qt. In future this can hopefully be simplified. See ^1 for workaround. - // More info: Issues with mouse move in Qt - // - https://bugreports.qt.io/browse/QTBUG-5232 - // - https://bugreports.qt.io/browse/QTBUG-69414 - // - https://lists.qt-project.org/pipermail/development/2019-July/036873.html - void MousePressAndMove( - QWidget* widget, const QPoint& widgetScreenPosition, const QPoint& mouseDelta) - { - QPoint position = widget->mapToGlobal(widgetScreenPosition); - QPoint nextPosition = widget->mapToGlobal(widgetScreenPosition + mouseDelta); - - QTest::mousePress(widget, Qt::LeftButton, Qt::NoModifier, position); - - // ^1 To ensure a mouse move event is fired we must call the test mouse move function - // and also send a mouse move event that matches. Each on their own do not appear to - // work - please see the links above for more context. - QTest::mouseMove(widget, nextPosition); - QMouseEvent mouseMoveEvent( - QEvent::MouseMove, QPointF(nextPosition), QPointF(nextPosition), - Qt::NoButton, Qt::LeftButton, Qt::NoModifier); - QApplication::sendEvent(widget, &mouseMoveEvent); - } - TEST_F(SpinBoxFixture, SpinBoxMousePressAndMoveRightScrollsValue) { m_doubleSpinBox->setValue(10.0); diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp index 32d5e995ab..be2816c890 100644 --- a/Code/Legacy/CrySystem/Log.cpp +++ b/Code/Legacy/CrySystem/Log.cpp @@ -851,7 +851,8 @@ bool CLog::LogToMainThread(const char* szString, ELogType logType, bool bAdd, SL { // When logging from other thread then main, push all log strings to queue. SLogMsg msg; - azstrcpy(msg.msg, AZ_ARRAY_SIZE(msg.msg), szString); + constexpr size_t maxArraySize = AZ_ARRAY_SIZE(msg.msg); + azstrncpy(msg.msg, maxArraySize, szString, maxArraySize - 1); msg.bAdd = bAdd; msg.destination = destination; msg.logType = logType; diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp index 8ea25a2ff0..68b00eb811 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp @@ -21,11 +21,16 @@ namespace AZ { AssImpMaterialWrapper::AssImpMaterialWrapper(aiMaterial* aiMaterial) - :SDKMaterial::MaterialWrapper(aiMaterial) + :m_assImpMaterial(aiMaterial) { AZ_Assert(aiMaterial, "Asset Importer Material cannot be null"); } + aiMaterial* AssImpMaterialWrapper::GetAssImpMaterial() const + { + return m_assImpMaterial; + } + AZStd::string AssImpMaterialWrapper::GetName() const { return m_assImpMaterial->GetName().C_Str(); diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.h b/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.h index 8d7138db16..776e73ebfb 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.h +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.h @@ -20,6 +20,7 @@ namespace AZ AZ_RTTI(AssImpMaterialWrapper, "{66992628-CFCE-441B-8849-9344A49AFAC9}", SDKMaterial::MaterialWrapper); AssImpMaterialWrapper(aiMaterial* aiMaterial); ~AssImpMaterialWrapper() override = default; + aiMaterial* GetAssImpMaterial() const; AZStd::string GetName() const override; AZ::u64 GetUniqueId() const override; AZ::Vector3 GetDiffuseColor() const override; @@ -38,6 +39,9 @@ namespace AZ AZStd::optional GetUseEmissiveMap() const; AZStd::optional GetEmissiveIntensity() const; AZStd::optional GetUseAOMap() const; + + protected: + aiMaterial* m_assImpMaterial = nullptr; }; } // namespace AssImpSDKWrapper }// namespace AZ diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpNodeWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/AssImpNodeWrapper.cpp index 9bd9b191ec..87583a961b 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpNodeWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpNodeWrapper.cpp @@ -17,14 +17,16 @@ namespace AZ namespace AssImpSDKWrapper { AssImpNodeWrapper::AssImpNodeWrapper(aiNode* sourceNode) - :SDKNode::NodeWrapper(sourceNode) + : m_assImpNode(sourceNode) { AZ_Assert(m_assImpNode, "Asset Importer Node cannot be null"); } - AssImpNodeWrapper::~AssImpNodeWrapper() + aiNode* AssImpNodeWrapper::GetAssImpNode() const { + return m_assImpNode; } + const char* AssImpNodeWrapper::GetName() const { return m_assImpNode->mName.C_Str(); diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpNodeWrapper.h b/Code/Tools/SceneAPI/SDKWrapper/AssImpNodeWrapper.h index bcf9eb9234..266653ca51 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpNodeWrapper.h +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpNodeWrapper.h @@ -20,7 +20,8 @@ namespace AZ public: AZ_RTTI(AssImpNodeWrapper, "{1043260B-9076-49B7-AD38-EF62E85F7C1D}", SDKNode::NodeWrapper); AssImpNodeWrapper(aiNode* sourceNode); - ~AssImpNodeWrapper() override; + ~AssImpNodeWrapper() override = default; + aiNode* GetAssImpNode() const; const char* GetName() const override; AZ::u64 GetUniqueId() const override; int GetChildCount() const override; @@ -28,6 +29,9 @@ namespace AZ const bool ContainsMesh(); bool ContainsBones(const aiScene& scene) const; int GetMaterialCount() const override; + + protected: + aiNode* m_assImpNode = nullptr; }; } // namespace AssImpSDKWrapper }// namespace AZ diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp index 12aefca00c..14f9bc0fe3 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp @@ -25,15 +25,10 @@ namespace AZ namespace AssImpSDKWrapper { AssImpSceneWrapper::AssImpSceneWrapper() - : SDKScene::SceneWrapperBase() { } AssImpSceneWrapper::AssImpSceneWrapper(aiScene* aiScene) - : SDKScene::SceneWrapperBase(aiScene) - { - } - - AssImpSceneWrapper::~AssImpSceneWrapper() + : m_assImpScene(aiScene) { } @@ -114,6 +109,11 @@ namespace AZ m_importer.FreeScene(); } + const aiScene* AssImpSceneWrapper::GetAssImpScene() const + { + return m_assImpScene; + } + AZStd::pair AssImpSceneWrapper::GetUpVectorAndSign() const { AZStd::pair result(AxisVector::Z, 1); diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.h b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.h index 5747f7025d..57f82cc4b1 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.h +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.h @@ -21,13 +21,14 @@ namespace AZ AZ_RTTI(AssImpSceneWrapper, "{43A61F62-DCD4-4132-B80B-F2FBC80740BC}", SDKScene::SceneWrapperBase); AssImpSceneWrapper(); AssImpSceneWrapper(aiScene* aiScene); - ~AssImpSceneWrapper(); + ~AssImpSceneWrapper() override = default; bool LoadSceneFromFile(const char* fileName) override; bool LoadSceneFromFile(const AZStd::string& fileName) override; const std::shared_ptr GetRootNode() const override; std::shared_ptr GetRootNode() override; + virtual const aiScene* GetAssImpScene() const; void Clear() override; enum class AxisVector @@ -43,7 +44,7 @@ namespace AZ AZStd::string GetSceneFileName() const { return m_sceneFileName; } protected: - + const aiScene* m_assImpScene = nullptr; Assimp::Importer m_importer; // FBX SDK automatically resolved relative paths to textures based on the current file location. diff --git a/Code/Tools/SceneAPI/SDKWrapper/MaterialWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/MaterialWrapper.cpp index 8209bd4bd0..9e7225ac9d 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/MaterialWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/MaterialWrapper.cpp @@ -12,21 +12,6 @@ namespace AZ { namespace SDKMaterial { - MaterialWrapper::MaterialWrapper(aiMaterial* assImpMaterial) - : m_assImpMaterial(assImpMaterial) - { - } - - MaterialWrapper::~MaterialWrapper() - { - m_assImpMaterial = nullptr; - } - - aiMaterial* MaterialWrapper::GetAssImpMaterial() - { - return m_assImpMaterial; - } - AZStd::string MaterialWrapper::GetName() const { return AZStd::string(); diff --git a/Code/Tools/SceneAPI/SDKWrapper/MaterialWrapper.h b/Code/Tools/SceneAPI/SDKWrapper/MaterialWrapper.h index db351f208c..53778ea783 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/MaterialWrapper.h +++ b/Code/Tools/SceneAPI/SDKWrapper/MaterialWrapper.h @@ -34,10 +34,7 @@ namespace AZ BaseColor }; - MaterialWrapper(aiMaterial* assImpmaterial); - virtual ~MaterialWrapper(); - - aiMaterial* GetAssImpMaterial(); + virtual ~MaterialWrapper() = default; virtual AZStd::string GetName() const; virtual AZ::u64 GetUniqueId() const; @@ -47,9 +44,6 @@ namespace AZ virtual AZ::Vector3 GetEmissiveColor() const; virtual float GetOpacity() const; virtual float GetShininess() const; - - protected: - aiMaterial* m_assImpMaterial = nullptr; }; } // namespace SDKMaterial } // namespace AZ diff --git a/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.cpp index 21a4de7c44..6b1c4ba99a 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.cpp @@ -12,21 +12,6 @@ namespace AZ { namespace SDKNode { - NodeWrapper::NodeWrapper(aiNode* aiNode) - : m_assImpNode(aiNode) - { - } - - NodeWrapper::~NodeWrapper() - { - m_assImpNode = nullptr; - } - - aiNode* NodeWrapper::GetAssImpNode() - { - return m_assImpNode; - } - const char* NodeWrapper::GetName() const { return ""; diff --git a/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h b/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h index bef3cf0db4..dfd216912a 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h +++ b/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h @@ -20,9 +20,7 @@ namespace AZ public: AZ_RTTI(NodeWrapper, "{5EB0897B-9728-44B7-B056-BA34AAF14715}"); - NodeWrapper() = default; - NodeWrapper(aiNode* aiNode); - virtual ~NodeWrapper(); + virtual ~NodeWrapper() = default; enum CurveNodeComponent { @@ -31,16 +29,12 @@ namespace AZ Component_Z }; - aiNode* GetAssImpNode(); - virtual const char* GetName() const; virtual AZ::u64 GetUniqueId() const; virtual int GetMaterialCount() const; virtual int GetChildCount()const; virtual const std::shared_ptr GetChild(int childIndex) const; - - aiNode* m_assImpNode = nullptr; }; } //namespace Node } //namespace AZ diff --git a/Code/Tools/SceneAPI/SDKWrapper/SceneWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/SceneWrapper.cpp index 37e92a1eac..42f07618e5 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/SceneWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/SceneWrapper.cpp @@ -13,12 +13,6 @@ namespace AZ { const char* SceneWrapperBase::s_defaultSceneName = "myScene"; - SceneWrapperBase::SceneWrapperBase(aiScene* aiScene) - : m_assImpScene(aiScene) - { - } - - bool SceneWrapperBase::LoadSceneFromFile([[maybe_unused]] const char* fileName) { return false; @@ -40,12 +34,5 @@ namespace AZ void SceneWrapperBase::Clear() { } - - const aiScene* SceneWrapperBase::GetAssImpScene() const - { - return m_assImpScene; - } - - } //namespace Scene }// namespace AZ diff --git a/Code/Tools/SceneAPI/SDKWrapper/SceneWrapper.h b/Code/Tools/SceneAPI/SDKWrapper/SceneWrapper.h index d4776174d9..67128134d1 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/SceneWrapper.h +++ b/Code/Tools/SceneAPI/SDKWrapper/SceneWrapper.h @@ -20,9 +20,7 @@ namespace AZ { public: AZ_RTTI(SceneWrapperBase, "{703CD344-2C75-4F30-8CE2-6BDEF2511AFD}"); - SceneWrapperBase() = default; virtual ~SceneWrapperBase() = default; - SceneWrapperBase(aiScene* aiScene); virtual bool LoadSceneFromFile(const char* fileName); virtual bool LoadSceneFromFile(const AZStd::string& fileName); @@ -31,10 +29,6 @@ namespace AZ virtual std::shared_ptr GetRootNode(); virtual void Clear(); - - virtual const aiScene* GetAssImpScene() const; - - const aiScene* m_assImpScene = nullptr; static const char* s_defaultSceneName; }; diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp index 8983c76bac..aa53f8be9b 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp @@ -56,9 +56,9 @@ namespace AZ Events::ProcessingResultCombiner combinedMaterialImportResults; AZStd::unordered_map> materialMap; - for (unsigned int idx = 0; idx < context.m_sourceNode.m_assImpNode->mNumMeshes; ++idx) + for (unsigned int idx = 0; idx < context.m_sourceNode.GetAssImpNode()->mNumMeshes; ++idx) { - int meshIndex = context.m_sourceNode.m_assImpNode->mMeshes[idx]; + int meshIndex = context.m_sourceNode.GetAssImpNode()->mMeshes[idx]; const aiMesh* assImpMesh = context.m_sourceScene.GetAssImpScene()->mMeshes[meshIndex]; AZ_Assert(assImpMesh, "Asset Importer Mesh should not be null."); int materialIndex = assImpMesh->mMaterialIndex; diff --git a/Code/Tools/SceneAPI/SceneBuilder/SceneImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/SceneImporter.cpp index 3f2ec6c1eb..c0c0fe1330 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/SceneImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/SceneImporter.cpp @@ -222,7 +222,12 @@ namespace AZ int childCount = node.m_node->GetChildCount(); for (int i = 0; i < childCount; ++i) { - std::shared_ptr child = std::make_shared(node.m_node->GetChild(i)->GetAssImpNode()); + const std::shared_ptr nodeWrapper = node.m_node->GetChild(i); + auto assImpNodeWrapper = azrtti_cast(nodeWrapper.get()); + + AZ_Assert(assImpNodeWrapper, "Child node is not the expected AssImpNodeWrapper type"); + + std::shared_ptr child = std::make_shared(assImpNodeWrapper->GetAssImpNode()); if (child) { nodes.emplace(AZStd::move(child), newNode); diff --git a/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.cpp b/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.cpp index 7950eff130..a182e4f02d 100644 --- a/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.cpp +++ b/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.cpp @@ -104,7 +104,7 @@ namespace AZ } AZStd::shared_ptr AssetImportRequest::LoadSceneFromVerifiedPath(const AZStd::string& assetFilePath, const Uuid& sourceGuid, - RequestingApplication requester) + RequestingApplication requester, const Uuid& loadingComponentUuid) { AZStd::string sceneName; AzFramework::StringFunc::Path::GetFileName(assetFilePath.c_str(), sceneName); @@ -113,7 +113,7 @@ namespace AZ // Unique pointer, will deactivate and clean up once going out of scope. SceneCore::EntityConstructor::EntityPointer loaders = - SceneCore::EntityConstructor::BuildEntity("Scene Loading", SceneCore::LoadingComponent::TYPEINFO_Uuid()); + SceneCore::EntityConstructor::BuildEntity("Scene Loading", loadingComponentUuid); ProcessingResultCombiner areAllPrepared; AssetImportRequestBus::BroadcastResult(areAllPrepared, &AssetImportRequestBus::Events::PrepareForAssetLoading, *scene, requester); diff --git a/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.h b/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.h index 2a071a4001..8b6e119f99 100644 --- a/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.h +++ b/Code/Tools/SceneAPI/SceneCore/Events/AssetImportRequest.h @@ -102,8 +102,9 @@ namespace AZ //! @param sourceGuid The guid assigned to the source file (not the manifest). //! @param requester The application making the request to load the file. This can be used to optimize the type and amount of data //! to load. + //! @param loadingComponentUuid The UUID assigned to the loading component. static AZStd::shared_ptr LoadSceneFromVerifiedPath(const AZStd::string& assetFilePath, - const Uuid&sourceGuid, RequestingApplication requester); + const Uuid& sourceGuid, RequestingApplication requester, const Uuid& loadingComponentUuid); //! Utility function to determine if a given file path points to a scene manifest file (.assetinfo). //! @param filePath A relative or absolute path to the file to check. diff --git a/Code/Tools/SceneAPI/SceneCore/Tests/Events/AssetImporterRequestTests.cpp b/Code/Tools/SceneAPI/SceneCore/Tests/Events/AssetImporterRequestTests.cpp index a610cee5a4..42ddc0139c 100644 --- a/Code/Tools/SceneAPI/SceneCore/Tests/Events/AssetImporterRequestTests.cpp +++ b/Code/Tools/SceneAPI/SceneCore/Tests/Events/AssetImporterRequestTests.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace AZ @@ -184,7 +185,7 @@ namespace AZ EXPECT_CALL(handler, UpdateManifest(_, _, _)).Times(0); AZStd::shared_ptr result = - AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic); + AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic, SceneCore::LoadingComponent::TYPEINFO_Uuid()); EXPECT_EQ(nullptr, result); } @@ -207,7 +208,7 @@ namespace AZ EXPECT_CALL(handler, UpdateManifest(_, _, _)).Times(0); AZStd::shared_ptr result = - AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic); + AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic, SceneCore::LoadingComponent::TYPEINFO_Uuid()); EXPECT_EQ(nullptr, result); } @@ -230,7 +231,7 @@ namespace AZ EXPECT_CALL(handler, UpdateManifest(_, _, _)).Times(0); AZStd::shared_ptr result = - AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic); + AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic, SceneCore::LoadingComponent::TYPEINFO_Uuid()); EXPECT_EQ(nullptr, result); } @@ -253,7 +254,7 @@ namespace AZ EXPECT_CALL(handler, UpdateManifest(_, _, _)).Times(0); AZStd::shared_ptr result = - AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic); + AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic, SceneCore::LoadingComponent::TYPEINFO_Uuid()); EXPECT_EQ(nullptr, result); } @@ -285,7 +286,7 @@ namespace AZ EXPECT_CALL(manifestHandler, UpdateManifest(_, _, _)).Times(1); AZStd::shared_ptr result = - AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic); + AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic, SceneCore::LoadingComponent::TYPEINFO_Uuid()); EXPECT_EQ(nullptr, result); } @@ -313,7 +314,7 @@ namespace AZ EXPECT_CALL(manifestHandler, UpdateManifest(_, _, _)).Times(1); AZStd::shared_ptr result = - AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic); + AssetImportRequest::LoadSceneFromVerifiedPath("test.asset", m_testId, Events::AssetImportRequest::RequestingApplication::Generic, SceneCore::LoadingComponent::TYPEINFO_Uuid()); EXPECT_NE(nullptr, result); } diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslShaderBuilderSystemComponent.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslShaderBuilderSystemComponent.cpp index 29e6fb7a6f..16cebef6ac 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslShaderBuilderSystemComponent.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslShaderBuilderSystemComponent.cpp @@ -81,7 +81,7 @@ namespace AZ // Register Shader Asset Builder AssetBuilderSDK::AssetBuilderDesc shaderAssetBuilderDescriptor; shaderAssetBuilderDescriptor.m_name = "Shader Asset Builder"; - shaderAssetBuilderDescriptor.m_version = 102; // ATOM-15472 + shaderAssetBuilderDescriptor.m_version = 103; // ATOM-15058 // .shader file changes trigger rebuilds shaderAssetBuilderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern( AZStd::string::format("*.%s", RPI::ShaderSourceData::Extension), AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); shaderAssetBuilderDescriptor.m_busId = azrtti_typeid(); diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.cpp index 945f9734ca..9c77ae6b35 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.cpp @@ -8,11 +8,6 @@ #include -#define MCPP_DLL_IMPORT 1 -#define MCPP_DONT_USE_SHORT_NAMES 1 -#include -#undef MCPP_DLL_IMPORT - #include #include @@ -31,8 +26,6 @@ #include -#include - namespace AZ { namespace ShaderBuilder @@ -83,124 +76,125 @@ namespace AZ } } - //! Binder helper to Matsui C-Pre-Processor library - class McppBinder + /////////////////////////////////////////////////////////////////////// + // McppBinder starts + bool McppBinder::StartPreprocessWithCommandLine(int argc, const char* argv[]) { - public: - McppBinder(PreprocessorData& out, bool plugERR) - : m_outputData(out), - m_plugERR(plugERR) + int errorCode = mcpp_lib_main(argc, argv); + // convert from std::ostringstring to AZStd::string + m_outputData.code = m_outStream.str().c_str(); + m_outputData.diagnostics = m_errStream.str().c_str(); + return errorCode == 0; + } + + int McppBinder::Putc_StaticHinge(int c, MCPP_OUTDEST od) + { + char asString[2] = { aznumeric_cast(c), 0 }; + return Fputs_StaticHinge(asString, od); + } + + int McppBinder::Fputs_StaticHinge(const char* s, MCPP_OUTDEST od) + { + if (!OkToLog(od)) { - // single live instance - s_mcppExclusiveProtection.lock(); - s_currentInstance = this; - SetupMcppCallbacks(); + return 0; } - ~McppBinder() + // chose the proper stream + auto& selectedStream = od == MCPP_OUT ? s_currentInstance->m_outStream : s_currentInstance->m_errStream; + auto tellBefore = selectedStream.tellp(); + // append that message to it + selectedStream << s; + return aznumeric_cast(selectedStream.tellp() - tellBefore); + } + + int McppBinder::Fprintf_StaticHinge(MCPP_OUTDEST od, const char* format, ...) + { + if (!OkToLog(od)) { - s_currentInstance = nullptr; - s_mcppExclusiveProtection.unlock(); + return 0; } + // run the formatting on stack memory first, in case it's enough + char localBuffer[DefaultFprintfBufferSize]; - bool StartPreprocessWithCommandLine(int argc, const char* argv[]) + va_list args; + + va_start(args, format); + int count = azvsnprintf(localBuffer, DefaultFprintfBufferSize, format, args); + va_end(args); + + char* result = localBuffer; + + // @result will be bound to @biggerData in case @localBuffer is not big enough. + std::unique_ptr biggerData; + // ">=" is the right comparison because in case count == bufferSize + // We will need an extra byte to accomodate the '\0' ending character. + if (count >= DefaultFprintfBufferSize) { - int errorCode = mcpp_lib_main(argc, argv); - // convert from std::ostringstring to AZStd::string - m_outputData.code = m_outStream.str().c_str(); - m_outputData.diagnostics = m_errStream.str().c_str(); - return errorCode == 0; - } - - private: - - // ====== C-API compatible "Static Hinges" (plain free functions) ====== - // : capturing-lambdas, function-objects, bind-expression; can't be decayed to function pointers, - // because they hold runtime-dynamic type-erased states. So we need intermediates - - // entry point from mcpp. hijacking its output - static int Putc_StaticHinge(int c, MCPP_OUTDEST od) - { - char asString[2] = { aznumeric_cast(c), 0 }; - return Fputs_StaticHinge(asString, od); - } - - // entry point from mcpp. hijacking its output - static int Fputs_StaticHinge(const char* s, MCPP_OUTDEST od) - { - if (!OkToLog(od)) - { - return 0; - } - // chose the proper stream - auto& selectedStream = od == MCPP_OUT ? s_currentInstance->m_outStream : s_currentInstance->m_errStream; - auto tellBefore = selectedStream.tellp(); - // append that message to it - selectedStream << s; - return aznumeric_cast(selectedStream.tellp() - tellBefore); - } - - // entry point from mcpp. hijacking its output - static int Fprintf_StaticHinge(MCPP_OUTDEST od, const char* format, ...) - { - if (!OkToLog(od)) - { - return 0; - } - // run the formatting on stack memory first, in case it's enough - constexpr int bufferSize = 256; - char localBuffer[bufferSize]; - va_list args; + // There wasn't enough space in the local store. + count++; // vsnprintf returns a size that doesn't include the null character. + biggerData.reset(new char[count]); + result = &biggerData[0]; + + // Remark: for MacOS & Linux it is important to call va_start again before + // each call to azvsnprintf. Not required for Windows. va_start(args, format); - int count = azvsnprintf(localBuffer, 256, format, args); - AZStd::unique_ptr biggerData; // will be bound to a bigger array if necessary. - char* result = localBuffer; - if (count > bufferSize) - { // there wasn't enough space in the local store. - biggerData.reset(new char[count]); - result = &biggerData[0]; // change `result`'s pointee - count = azvsnprintf(result, count, format, args); - } - AZ_Error("Preprocessor", count >= 0, "String formatting of pre-precessor output failed"); + count = azvsnprintf(result, count, format, args); va_end(args); - return Fputs_StaticHinge(result, od); } - - static void IncludeReport_StaticHinge(FILE*, const char*, const char*, const char* path) + else if (count == -1) { - s_currentInstance->m_outputData.includedPaths.insert(path); + // In Windows azvsnprintf will always return -1 if @localBuffer is not big enough, + // But it will write in @localBuffer what it could. + // See: + // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/vsnprintf-vsnprintf-vsnprintf-l-vsnwprintf-vsnwprintf-l?view=msvc-160 + // In particular: "If the number of characters to write is greater than count, + // these functions return -1 indicating that output has been truncated." + + // There wasn't enough space in the local store. + // Remark: for MacOS & Linux it is important to call va_start again before + // each call to azvsnprintf. Not required for Windows. + va_start(args, format); + count = azvscprintf(format, args) + 1; // vscprintf returns a size that doesn't include the null character. + va_end(args); + + biggerData.reset(new char[count]); + result = &biggerData[0]; + + va_start(args, format); + count = azvsnprintf(result, count, format, args); + va_end(args); } - // ====== utility methods ===== + AZ_Error("Preprocessor", count >= 0, "String formatting of pre-precessor output failed"); + return Fputs_StaticHinge(result, od); + } - static bool OkToLog(MCPP_OUTDEST od) - { - bool isErrButOk = od == MCPP_ERR && s_currentInstance->m_plugERR; - return od == MCPP_OUT || isErrButOk; - } + void McppBinder::IncludeReport_StaticHinge(FILE*, const char*, const char*, const char* path) + { + s_currentInstance->m_outputData.includedPaths.insert(path); + } - static void SetupMcppCallbacks() - { - // callback for header included notification - mcpp_set_report_include_callback(IncludeReport_StaticHinge); - // callback for output redirection - mcpp_set_out_func(Putc_StaticHinge, Fputs_StaticHinge, Fprintf_StaticHinge); - } + bool McppBinder::OkToLog(MCPP_OUTDEST od) + { + bool isErrButOk = od == MCPP_ERR && s_currentInstance->m_plugERR; + return od == MCPP_OUT || isErrButOk; + } - // ====== instance data ====== - PreprocessorData& m_outputData; - std::ostringstream m_outStream, m_errStream; - bool m_plugERR; - - // ====== shared data ====== - // MCPP is a library with tons of non TLS global states, it can only be accessed by one client at a time. - static AZStd::mutex s_mcppExclusiveProtection; - static McppBinder* s_currentInstance; - }; + void McppBinder::SetupMcppCallbacks() + { + // callback for header included notification + mcpp_set_report_include_callback(IncludeReport_StaticHinge); + // callback for output redirection + mcpp_set_out_func(Putc_StaticHinge, Fputs_StaticHinge, Fprintf_StaticHinge); + } // definitions for the linker AZStd::mutex McppBinder::s_mcppExclusiveProtection; McppBinder* McppBinder::s_currentInstance = nullptr; + // McppBinder ends + /////////////////////////////////////////////////////////////////////// + bool PreprocessFile(const AZStd::string& fullPath, PreprocessorData& outputData, const PreprocessorOptions& options , bool collectDiagnostics, bool preprocessIncludedFiles) { diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.h b/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.h index bb4388999f..9f3c770e78 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.h +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/Preprocessor.h @@ -14,6 +14,18 @@ #include #include +#define MCPP_DLL_IMPORT 1 +#define MCPP_DONT_USE_SHORT_NAMES 1 +#include +#undef MCPP_DLL_IMPORT + +#include + +namespace UnitTest +{ + class McppBinderTests; +} + namespace AZ { namespace ShaderBuilder @@ -93,5 +105,64 @@ namespace AZ AZStd::string& sourceCode, AZStd::string newFileOrigin); + //! Binder helper to Matsui C-Pre-Processor library + class McppBinder + { + public: + McppBinder(PreprocessorData& out, bool plugERR) + : m_outputData(out) + , m_plugERR(plugERR) + { + // single live instance + s_mcppExclusiveProtection.lock(); + s_currentInstance = this; + SetupMcppCallbacks(); + } + ~McppBinder() + { + s_currentInstance = nullptr; + s_mcppExclusiveProtection.unlock(); + } + + // This constant is in the header so McppBinderTests can see it. + static constexpr int DefaultFprintfBufferSize = 256; + + bool StartPreprocessWithCommandLine(int argc, const char* argv[]); + + private: + friend class ::UnitTest::McppBinderTests; + + // ====== C-API compatible "Static Hinges" (plain free functions) ====== + // : capturing-lambdas, function-objects, bind-expression; can't be decayed to function pointers, + // because they hold runtime-dynamic type-erased states. So we need intermediates + + // entry point from mcpp. hijacking its output + static int Putc_StaticHinge(int c, MCPP_OUTDEST od); + + // entry point from mcpp. hijacking its output + static int Fputs_StaticHinge(const char* s, MCPP_OUTDEST od); + + // entry point from mcpp. hijacking its output + static int Fprintf_StaticHinge(MCPP_OUTDEST od, const char* format, ...); + + static void IncludeReport_StaticHinge(FILE*, const char*, const char*, const char* path); + + // ====== utility methods ===== + + static bool OkToLog(MCPP_OUTDEST od); + + static void SetupMcppCallbacks(); + + // ====== instance data ====== + PreprocessorData& m_outputData; + std::ostringstream m_outStream, m_errStream; + bool m_plugERR; + + // ====== shared data ====== + // MCPP is a library with tons of non TLS global states, it can only be accessed by one client at a time. + static AZStd::mutex s_mcppExclusiveProtection; + static McppBinder* s_currentInstance; + }; + } // ShaderBuilder } // AZ diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp index 606502fb22..2332f4522b 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp @@ -226,11 +226,9 @@ namespace AZ if (!hasRasterProgram && !hasComputeProgram && !hasRayTracingProgram) { - AZStd::string entryPointNames = ShaderBuilderUtility::GetAcceptableDefaultEntryPointNames(azslData); return AZ::Failure( - AZStd::string::format( "Shader asset descriptor has a program variant that does not define any entry points. Either declare entry " - "points in the .shader file, or use one of the available default names (not case-sensitive): [%s]", - entryPointNames.c_str())); + AZStd::string( "Shader asset descriptor has a program variant that does not define any entry points." + " Please declare entry points in the .shader file.")); } return AZ::Success(attributeMaps); @@ -478,21 +476,18 @@ namespace AZ } } - // Discover entry points & type of programs. - MapOfStringToStageType shaderEntryPoints; if (shaderSourceData.m_programSettings.m_entryPoints.empty()) { - AZ_TracePrintf( - ShaderAssetBuilderName, - "ProgramSettings do not specify entry points, will use GetDefaultEntryPointsFromShader()\n"); - ShaderBuilderUtility::GetDefaultEntryPointsFromFunctionDataList(azslData.m_functions, shaderEntryPoints); + AZ_Error( ShaderAssetBuilderName, false, "ProgramSettings must specify entry points."); + response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed; + return; } - else + + // Discover entry points & type of programs. + MapOfStringToStageType shaderEntryPoints; + for (const auto& entryPoint : shaderSourceData.m_programSettings.m_entryPoints) { - for (const auto& entryPoint : shaderSourceData.m_programSettings.m_entryPoints) - { - shaderEntryPoints[entryPoint.m_name] = entryPoint.m_type; - } + shaderEntryPoints[entryPoint.m_name] = entryPoint.m_type; } bool hasRasterProgram = false; diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp index d7c3de48c0..0018f2ead8 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp @@ -809,91 +809,6 @@ namespace AZ return success; } - - //! Returns a list of acceptable default entry point names - static void GetAcceptableDefaultEntryPoints( - const AZStd::vector& azslFunctionDataList, - AZStd::unordered_map& defaultEntryPoints) - { - for (const auto& func : azslFunctionDataList) - { - if (!func.m_hasShaderStageVaryings) - { - // Not declaring any semantics for a shader entry is valid, but unusual. - // A shader entry with no semantics must be explicitly listed and won't be selected by default. - continue; - } - - if (func.m_name.starts_with("VS") || func.m_name.ends_with("VS")) - { - defaultEntryPoints[func.m_name] = RPI::ShaderStageType::Vertex; - AZ_TracePrintf( - ShaderBuilderUtilityName, "Assuming \"%s\" is a valid Vertex shader entry point.\n", func.m_name.c_str()); - } - else if (func.m_name.starts_with("PS") || func.m_name.ends_with("PS")) - { - defaultEntryPoints[func.m_name] = RPI::ShaderStageType::Fragment; - AZ_TracePrintf( - ShaderBuilderUtilityName, "Assuming \"%s\" is a valid Fragment shader entry point.\n", - func.m_name.c_str()); - } - else if (func.m_name.starts_with("CS") || func.m_name.ends_with("CS")) - { - defaultEntryPoints[func.m_name] = RPI::ShaderStageType::Compute; - AZ_TracePrintf( - ShaderBuilderUtilityName, "Assuming \"%s\" is a valid Compute shader entry point.\n", func.m_name.c_str()); - } - } - } - - - // DEPRECATED [ATOM-15472 - //! Returns a list of acceptable default entry point names - //! This function - static void GetAcceptableDefaultEntryPoints( - const AzslData& azslData, AZStd::unordered_map& defaultEntryPoints) - { - return GetAcceptableDefaultEntryPoints(azslData.m_functions, defaultEntryPoints); - } - - - void GetDefaultEntryPointsFromFunctionDataList( - const AZStd::vector azslFunctionDataList, - AZStd::unordered_map& shaderEntryPoints) - { - AZStd::unordered_map defaultEntryPoints; - GetAcceptableDefaultEntryPoints(azslFunctionDataList, defaultEntryPoints); - - for (const auto& functionData : azslFunctionDataList) - { - for (const auto& defaultEntryPoint : defaultEntryPoints) - { - // Equal defaults to case insensitive compares... - if (AzFramework::StringFunc::Equal(defaultEntryPoint.first.c_str(), functionData.m_name.c_str())) - { - shaderEntryPoints[defaultEntryPoint.first] = defaultEntryPoint.second; - break; // stop looping default entry points and go to the next shader function - } - } - } - } - - AZStd::string GetAcceptableDefaultEntryPointNames(const AzslData& azslData) - { - AZStd::unordered_map defaultEntryPointList; - GetAcceptableDefaultEntryPoints(azslData, defaultEntryPointList); - - AZStd::vector defaultEntryPointNamesList; - for (const auto& shaderEntryPoint : defaultEntryPointList) - { - defaultEntryPointNamesList.push_back(shaderEntryPoint.first); - } - AZStd::string shaderEntryPoints; - AzFramework::StringFunc::Join( - shaderEntryPoints, defaultEntryPointNamesList.begin(), defaultEntryPointNamesList.end(), ", "); - return AZStd::move(shaderEntryPoints); - } - } // namespace ShaderBuilderUtility } // namespace ShaderBuilder } // AZ diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.h b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.h index 9310bf2e2f..c000ba9df6 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.h +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.h @@ -94,10 +94,6 @@ namespace AZ RPI::ShaderOutputContract& shaderOutputContract, size_t& colorAttachmentCount); - //! Returns a list of acceptable default entry point names as a single string for debug messages. - AZStd::string GetAcceptableDefaultEntryPointNames(const AzslData& shaderData); - - //! Create a file from a string's content. //! That file will be named filename.api.azslin //! This is meant to be used at this stage: @@ -138,10 +134,6 @@ namespace AZ AZStd::vector GetSupervariantListFromShaderSourceData( const RPI::ShaderSourceData& shaderSourceData); - void GetDefaultEntryPointsFromFunctionDataList( - const AZStd::vector azslFunctionDataList, - AZStd::unordered_map& shaderEntryPoints); - void LogProfilingData(const char* builderName, AZStd::string_view shaderPath); //! Returns the asset path of a product artifact produced by ShaderAssetBuilder. diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp index 1da4623774..59660440e4 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp @@ -843,17 +843,14 @@ namespace AZ MapOfStringToStageType shaderEntryPoints; if (shaderSourceDescriptor.m_programSettings.m_entryPoints.empty()) { - AZ_TracePrintf( - ShaderVariantAssetBuilderName, - "ProgramSettings do not specify entry points, will use GetDefaultEntryPointsFromShader()\n"); - ShaderBuilderUtility::GetDefaultEntryPointsFromFunctionDataList(azslFunctions, shaderEntryPoints); + AZ_Error(ShaderVariantAssetBuilderName, false, "ProgramSettings must specify entry points."); + response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed; + return; } - else + + for (const auto& entryPoint : shaderSourceDescriptor.m_programSettings.m_entryPoints) { - for (const auto& entryPoint : shaderSourceDescriptor.m_programSettings.m_entryPoints) - { - shaderEntryPoints[entryPoint.m_name] = entryPoint.m_type; - } + shaderEntryPoints[entryPoint.m_name] = entryPoint.m_type; } // 3- hlslCode diff --git a/Gems/Atom/Asset/Shader/Code/Tests/McppBinderTests.cpp b/Gems/Atom/Asset/Shader/Code/Tests/McppBinderTests.cpp new file mode 100644 index 0000000000..926f9b0a76 --- /dev/null +++ b/Gems/Atom/Asset/Shader/Code/Tests/McppBinderTests.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +#include "Common/ShaderBuilderTestFixture.h" + +#include + +namespace UnitTest +{ + using namespace AZ; + + // The main purpose of this class is to test ShaderBuilder::McppBinder::Fprintf_StaticHinge() + // Which has three common scenarios to validate. + // 1- The formatted string is expected to yield less bytes than McppBinder::DefaultFprintfBufferSize. + // 2- The formatted string is expected to yield exactly McppBinder::DefaultFprintfBufferSize number of bytes. + // 3- The formatted string is expectedc to yield more bytes than McppBinder::DefaultFprintfBufferSize. + class McppBinderTests : public ShaderBuilderTestFixture + { + public: + + // Fills @buffer with 'a' to 'z' for up to @bufferSize number of bytes. + // This function will null('\0') char terminate @buffer. + void FillBufferWithAlphabet(char* buffer, int bufferSize) + { + for (int bufferPos = 0, rollback = 0; bufferPos < (bufferSize - 1); ++bufferPos) + { + const char value = 'a' + rollback++; + buffer[bufferPos] = value; + if (value == 'z') + { + rollback = 0; + } + } + buffer[bufferSize - 1] = '\0'; + } + + // Pushes the null terminated string, @inputString, into McppBinder capture stream + // using McppBinder::Fprintf_StaticHinge(). + // Returns the content of the McppBinder capture stream as a string. + AZStd::string PrintStringThroughStaticHinge(const char* inputString) + { + ShaderBuilder::PreprocessorData preprocessorData; + ShaderBuilder::McppBinder mcppBinder(preprocessorData, false); + ShaderBuilder::McppBinder::Fprintf_StaticHinge(MCPP_OUTDEST::MCPP_OUT, "%s", inputString); + // convert from std::ostringstring to AZStd::string + return AZStd::string(mcppBinder.m_outStream.str().c_str()); + } + }; // class McppBinderTests + + + TEST_F(McppBinderTests, ShouldPrintLessBytesThanDefaultSize) + { + constexpr int bufferSize = (ShaderBuilder::McppBinder::DefaultFprintfBufferSize / 2) + 1; + EXPECT_TRUE(bufferSize > 0); + char buffer[bufferSize] = ""; + FillBufferWithAlphabet(buffer, bufferSize); + auto printedString = PrintStringThroughStaticHinge(buffer); + EXPECT_EQ(AZStd::string(buffer), printedString); + } + + TEST_F(McppBinderTests, ShouldPrintSameBytesAsDefaultSize) + { + constexpr int bufferSize = ShaderBuilder::McppBinder::DefaultFprintfBufferSize + 1; + EXPECT_TRUE(bufferSize > 0); + char buffer[bufferSize] = ""; + FillBufferWithAlphabet(buffer, bufferSize); + auto printedString = PrintStringThroughStaticHinge(buffer); + EXPECT_EQ(AZStd::string(buffer), printedString); + } + + TEST_F(McppBinderTests, ShouldPrintMoreBytesThanDefaultSize) + { + constexpr int bufferSize = (ShaderBuilder::McppBinder::DefaultFprintfBufferSize * 2) + 1; + EXPECT_TRUE(bufferSize > 0); + char buffer[bufferSize] = ""; + FillBufferWithAlphabet(buffer, bufferSize); + auto printedString = PrintStringThroughStaticHinge(buffer); + EXPECT_EQ(AZStd::string(buffer), printedString); + } + +} //namespace UnitTest + +//AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); + diff --git a/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake b/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake index bfddb5ce8e..033b399478 100644 --- a/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake +++ b/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake @@ -10,4 +10,5 @@ set(FILES Tests/Common/ShaderBuilderTestFixture.h Tests/Common/ShaderBuilderTestFixture.cpp Tests/SupervariantCmdArgumentTests.cpp + Tests/McppBinderTests.cpp ) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Special/ShadowCatcher.shader b/Gems/Atom/Feature/Common/Assets/Materials/Special/ShadowCatcher.shader index f4784440b1..7df4169498 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Special/ShadowCatcher.shader +++ b/Gems/Atom/Feature/Common/Assets/Materials/Special/ShadowCatcher.shader @@ -18,5 +18,20 @@ "BlendOp": "Add" }, + "ProgramSettings" : + { + "EntryPoints": + [ + { + "name": "ShadowCatcherVS", + "type" : "Vertex" + }, + { + "name": "ShadowCatcherPS", + "type" : "Fragment" + } + ] + }, + "DrawList": "transparent" } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPass.shader b/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPass.shader index fe76eb06cb..463db025e7 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPass.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPass.shader @@ -9,5 +9,16 @@ "DisableOptimizations" : false }, + "ProgramSettings" : + { + "EntryPoints": + [ + { + "name": "DepthPassVS", + "type" : "Vertex" + } + ] + }, + "DrawList" : "depth" } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPassTransparentMax.shader b/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPassTransparentMax.shader index a56959e357..5bfdc8bcc1 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPassTransparentMax.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPassTransparentMax.shader @@ -13,5 +13,16 @@ "CompilerHints" : { }, + "ProgramSettings" : + { + "EntryPoints": + [ + { + "name": "DepthPassVS", + "type" : "Vertex" + } + ] + }, + "DrawList" : "depthTransparentMax" } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPassTransparentMin.shader b/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPassTransparentMin.shader index 709e467479..5cd8ea7c33 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPassTransparentMin.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Depth/DepthPassTransparentMin.shader @@ -11,5 +11,16 @@ "DisableOptimizations" : false }, + "ProgramSettings" : + { + "EntryPoints": + [ + { + "name": "DepthPassVS", + "type" : "Vertex" + } + ] + }, + "DrawList" : "depthTransparentMin" } diff --git a/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp index add6d0e098..7c6dfcf744 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp @@ -9,6 +9,7 @@ #include "ProfilingCaptureSystemComponent.h" #include +#include #include #include #include @@ -141,36 +142,6 @@ namespace AZ AZStd::vector m_pipelineStatisticsEntries; }; - // Intermediate class to serialize Cpu TimedRegion data. - class CpuProfilingStatisticsSerializer - { - public: - class CpuProfilingStatisticsSerializerEntry - { - public: - AZ_TYPE_INFO(CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry, "{26B78F65-EB96-46E2-BE7E-A1233880B225}"); - static void Reflect(AZ::ReflectContext* context); - - CpuProfilingStatisticsSerializerEntry() = default; - CpuProfilingStatisticsSerializerEntry(const RHI::CachedTimeRegion& cachedTimeRegion); - - private: - Name m_groupName; - Name m_regionName; - uint16_t m_stackDepth; - AZStd::sys_time_t m_startTick; - AZStd::sys_time_t m_endTick; - }; - - AZ_TYPE_INFO(CpuProfilingStatisticsSerializer, "{D5B02946-0D27-474F-9A44-364C2706DD41}"); - static void Reflect(AZ::ReflectContext* context); - - CpuProfilingStatisticsSerializer() = default; - CpuProfilingStatisticsSerializer(const AZStd::ring_buffer& continuousData); - - AZStd::vector m_cpuProfilingStatisticsSerializerEntries; - }; - // Intermediate class to serialize benchmark metadata. class BenchmarkMetadataSerializer { @@ -327,65 +298,6 @@ namespace AZ } } - // --- CpuProfilingStatisticsSerializer --- - - CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializer(const AZStd::ring_buffer& continuousData) - { - // Create serializable entries - for (const auto& timeRegionMap : continuousData) - { - for (const auto& threadEntry : timeRegionMap) - { - for (const auto& cachedRegionEntry : threadEntry.second) - { - m_cpuProfilingStatisticsSerializerEntries.insert( - m_cpuProfilingStatisticsSerializerEntries.end(), - cachedRegionEntry.second.begin(), - cachedRegionEntry.second.end()); - } - } - } - } - - void CpuProfilingStatisticsSerializer::Reflect(AZ::ReflectContext* context) - { - if (auto* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("cpuProfilingStatisticsSerializerEntry", &CpuProfilingStatisticsSerializer::m_cpuProfilingStatisticsSerializerEntries) - ; - } - - CpuProfilingStatisticsSerializerEntry::Reflect(context); - } - - // --- CpuProfilingStatisticsSerializerEntry --- - - CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::CpuProfilingStatisticsSerializerEntry(const RHI::CachedTimeRegion& cachedTimeRegion) - { - m_groupName = cachedTimeRegion.m_groupRegionName->m_groupName; - m_regionName = cachedTimeRegion.m_groupRegionName->m_regionName; - m_stackDepth = cachedTimeRegion.m_stackDepth; - m_startTick = cachedTimeRegion.m_startTick; - m_endTick = cachedTimeRegion.m_endTick; - } - - void CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::Reflect(AZ::ReflectContext* context) - { - if (auto* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("groupName", &CpuProfilingStatisticsSerializerEntry::m_groupName) - ->Field("regionName", &CpuProfilingStatisticsSerializerEntry::m_regionName) - ->Field("stackDepth", &CpuProfilingStatisticsSerializerEntry::m_stackDepth) - ->Field("startTick", &CpuProfilingStatisticsSerializerEntry::m_startTick) - ->Field("endTick", &CpuProfilingStatisticsSerializerEntry::m_endTick) - ; - } - } - // --- BenchmarkMetadataSerializer --- BenchmarkMetadataSerializer::BenchmarkMetadataSerializer(const AZStd::string& benchmarkName, const RHI::PhysicalDeviceDescriptor& gpuDescriptor) @@ -458,7 +370,7 @@ namespace AZ TimestampSerializer::Reflect(context); CpuFrameTimeSerializer::Reflect(context); PipelineStatisticsSerializer::Reflect(context); - CpuProfilingStatisticsSerializer::Reflect(context); + RHI::CpuProfilingStatisticsSerializer::Reflect(context); BenchmarkMetadataSerializer::Reflect(context); } @@ -651,10 +563,10 @@ namespace AZ JsonSerializerSettings serializationSettings; serializationSettings.m_keepDefaults = true; - CpuProfilingStatisticsSerializer serializer(data); + RHI::CpuProfilingStatisticsSerializer serializer(data); const auto saveResult = JsonSerializationUtils::SaveObjectToFile(&serializer, - outputFilePath, (CpuProfilingStatisticsSerializer*)nullptr, &serializationSettings); + outputFilePath, (RHI::CpuProfilingStatisticsSerializer*)nullptr, &serializationSettings); AZStd::string captureInfo = outputFilePath; if (!saveResult.IsSuccess()) @@ -694,7 +606,7 @@ namespace AZ const bool captureStarted = m_cpuProfilingStatisticsCapture.StartCapture([this, outputFilePath, wasEnabled]() { // Blocking call for a single frame of data, avoid thread overhead - AZStd::ring_buffer singleFrameData; + AZStd::ring_buffer singleFrameData(1); singleFrameData.push_back(RHI::CpuProfiler::Get()->GetTimeRegionMap()); SerializeCpuProfilingData(singleFrameData, outputFilePath, wasEnabled); }); diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h index 2e4ca67db8..9372977d8e 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -161,5 +162,33 @@ namespace AZ AZStd::ring_buffer m_continuousCaptureData; }; - }; // namespace RPI + // Intermediate class to serialize Cpu TimedRegion data. + class CpuProfilingStatisticsSerializer + { + public: + class CpuProfilingStatisticsSerializerEntry + { + public: + AZ_TYPE_INFO(CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry, "{26B78F65-EB96-46E2-BE7E-A1233880B225}"); + static void Reflect(AZ::ReflectContext* context); + + CpuProfilingStatisticsSerializerEntry() = default; + CpuProfilingStatisticsSerializerEntry(const RHI::CachedTimeRegion& cachedTimeRegion); + + Name m_groupName; + Name m_regionName; + uint16_t m_stackDepth; + AZStd::sys_time_t m_startTick; + AZStd::sys_time_t m_endTick; + }; + + AZ_TYPE_INFO(CpuProfilingStatisticsSerializer, "{D5B02946-0D27-474F-9A44-364C2706DD41}"); + static void Reflect(AZ::ReflectContext* context); + + CpuProfilingStatisticsSerializer() = default; + CpuProfilingStatisticsSerializer(const AZStd::ring_buffer& continuousData); + + AZStd::vector m_cpuProfilingStatisticsSerializerEntries; + }; + }; // namespace RHI }; // namespace AZ diff --git a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp index 8d6be17ad3..6cfd68d3c6 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp @@ -409,5 +409,64 @@ namespace AZ m_cachedTimeRegionMutex.unlock(); } } - } -} + + // --- CpuProfilingStatisticsSerializer --- + + CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializer(const AZStd::ring_buffer& continuousData) + { + // Create serializable entries + for (const auto& timeRegionMap : continuousData) + { + for (const auto& threadEntry : timeRegionMap) + { + for (const auto& cachedRegionEntry : threadEntry.second) + { + m_cpuProfilingStatisticsSerializerEntries.insert( + m_cpuProfilingStatisticsSerializerEntries.end(), + cachedRegionEntry.second.begin(), + cachedRegionEntry.second.end()); + } + } + } + } + + void CpuProfilingStatisticsSerializer::Reflect(AZ::ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("cpuProfilingStatisticsSerializerEntries", &CpuProfilingStatisticsSerializer::m_cpuProfilingStatisticsSerializerEntries) + ; + } + + CpuProfilingStatisticsSerializerEntry::Reflect(context); + } + + // --- CpuProfilingStatisticsSerializerEntry --- + + CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::CpuProfilingStatisticsSerializerEntry(const RHI::CachedTimeRegion& cachedTimeRegion) + { + m_groupName = cachedTimeRegion.m_groupRegionName->m_groupName; + m_regionName = cachedTimeRegion.m_groupRegionName->m_regionName; + m_stackDepth = cachedTimeRegion.m_stackDepth; + m_startTick = cachedTimeRegion.m_startTick; + m_endTick = cachedTimeRegion.m_endTick; + } + + void CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::Reflect(AZ::ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("groupName", &CpuProfilingStatisticsSerializerEntry::m_groupName) + ->Field("regionName", &CpuProfilingStatisticsSerializerEntry::m_regionName) + ->Field("stackDepth", &CpuProfilingStatisticsSerializerEntry::m_stackDepth) + ->Field("startTick", &CpuProfilingStatisticsSerializerEntry::m_startTick) + ->Field("endTick", &CpuProfilingStatisticsSerializerEntry::m_endTick) + ; + } + } + } // namespace RHI +} // namespace AZ diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h index 3e3fbec8fe..549f787ac9 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h @@ -10,7 +10,9 @@ #include #include + #include + #include #include @@ -118,7 +120,6 @@ namespace AZ AZ_Error("AZ::RPI::JsonUtils", false, "Failed to load object from json string: %s", loadResult.GetError().c_str()); return false; } - } // namespace JsonUtils } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp index db0eff5fc1..13e5714b52 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp @@ -1235,7 +1235,8 @@ namespace AZ // ProductMesh. That large buffer gets set on the LOD directly // rather than a Mesh in the LOD. ProductMeshContentAllocInfo lodBufferInfo; - + + bool isFirstMesh = true; for (const ProductMeshContent& mesh : lodMeshList) { if (lodBufferInfo.m_uvSetFloatCounts.size() < mesh.m_uvSets.size()) @@ -1347,6 +1348,14 @@ namespace AZ if (!mesh.m_skinJointIndices.empty() && !mesh.m_skinWeights.empty()) { + if (!isFirstMesh && lodBufferInfo.m_skinInfluencesCount == 0) + { + AZ_Error( + s_builderName, false, + "Attempting to merge a mix of static and skinned meshes, this will fail on buffer generation later. Mesh with " + "name %s is skinned, but previous meshes were not skinned.", + mesh.m_name.GetCStr()); + } AZ_Assert(mesh.m_skinJointIndices.size() == mesh.m_skinWeights.size(), "Number of skin influence joint indices (%d) should match the number of weights (%d).", mesh.m_skinJointIndices.size(), mesh.m_skinWeights.size()); @@ -1363,6 +1372,11 @@ namespace AZ lodBufferInfo.m_skinInfluencesCount += numNewSkinInfluences; } + else if (lodBufferInfo.m_skinInfluencesCount > 0) + { + AZ_Error(s_builderName, false, "Attempting to merge a mix of static and skinned meshes, this will fail on buffer generation later. Mesh with name %s is not skinned, but previous meshes were skinned.", + mesh.m_name.GetCStr()); + } if (!mesh.m_morphTargetVertexData.empty()) { @@ -1375,6 +1389,7 @@ namespace AZ } meshViews.emplace_back(AZStd::move(meshView)); + isFirstMesh = false; } // Now that we have the views settled, we can just merge the mesh diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocument.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocument.h new file mode 100644 index 0000000000..565c9f00a3 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocument.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include + +namespace AtomToolsFramework +{ + /** + * AtomToolsDocument provides an API for modifying and saving documents. + */ + class AtomToolsDocument + : public AtomToolsDocumentRequestBus::Handler + { + public: + AZ_RTTI(AtomToolsDocument, "{8992DF74-88EC-438C-B280-6E71D4C0880B}"); + AZ_CLASS_ALLOCATOR(AtomToolsDocument, AZ::SystemAllocator, 0); + AZ_DISABLE_COPY(AtomToolsDocument); + + AtomToolsDocument(); + virtual ~AtomToolsDocument(); + + const AZ::Uuid& GetId() const; + + //////////////////////////////////////////////////////////////////////// + // AtomToolsDocumentRequestBus::Handler implementation + AZStd::string_view GetAbsolutePath() const override; + AZStd::string_view GetRelativePath() const override; + const AZStd::any& GetPropertyValue(const AZ::Name& propertyFullName) const override; + const AtomToolsFramework::DynamicProperty& GetProperty(const AZ::Name& propertyFullName) const override; + bool IsPropertyGroupVisible(const AZ::Name& propertyGroupFullName) const override; + void SetPropertyValue(const AZ::Name& propertyFullName, const AZStd::any& value) override; + bool Open(AZStd::string_view loadPath) override; + bool Reopen() override; + bool Save() override; + bool SaveAsCopy(AZStd::string_view savePath) override; + bool SaveAsChild(AZStd::string_view savePath) override; + bool Close() override; + bool IsOpen() const override; + bool IsModified() const override; + bool IsSavable() const override; + bool CanUndo() const override; + bool CanRedo() const override; + bool Undo() override; + bool Redo() override; + bool BeginEdit() override; + bool EndEdit() override; + //////////////////////////////////////////////////////////////////////// + + protected: + + // Unique id of this document + AZ::Uuid m_id = AZ::Uuid::CreateRandom(); + + // Relative path to the material source file + AZStd::string m_relativePath; + + // Absolute path to the material source file + AZStd::string m_absolutePath; + + AZStd::any m_invalidValue; + + AtomToolsFramework::DynamicProperty m_invalidProperty; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentNotificationBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentNotificationBus.h similarity index 54% rename from Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentNotificationBus.h rename to Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentNotificationBus.h index aafd0a0a57..9c3a536333 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentNotificationBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentNotificationBus.h @@ -7,80 +7,77 @@ */ #pragma once -#include -#include - #include #include #include #include -namespace MaterialEditor +namespace AtomToolsFramework { - class MaterialDocumentNotifications + class AtomToolsDocumentNotifications : public AZ::EBusTraits { public: static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - //! Signal that a material document was created - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a document was created + //! @param documentId unique id of document for which the notification is sent virtual void OnDocumentCreated([[maybe_unused]] const AZ::Uuid& documentId) {} - //! Signal that a material document was destroyed - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a document was destroyed + //! @param documentId unique id of document for which the notification is sent virtual void OnDocumentDestroyed([[maybe_unused]] const AZ::Uuid& documentId) {} - //! Signal that a material document was opened - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a document was opened + //! @param documentId unique id of document for which the notification is sent virtual void OnDocumentOpened([[maybe_unused]] const AZ::Uuid& documentId) {} - //! Signal that a material document was closed - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a document was closed + //! @param documentId unique id of document for which the notification is sent virtual void OnDocumentClosed([[maybe_unused]] const AZ::Uuid& documentId) {} - //! Signal that a material document was saved - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a document was saved + //! @param documentId unique id of document for which the notification is sent virtual void OnDocumentSaved([[maybe_unused]] const AZ::Uuid& documentId) {} - //! Signal that a material document was selected - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a document was selected + //! @param documentId unique id of document for which the notification is sent virtual void OnDocumentSelected([[maybe_unused]] const AZ::Uuid& documentId) {} - //! Signal that a material document was modified - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a document was modified + //! @param documentId unique id of document for which the notification is sent virtual void OnDocumentModified([[maybe_unused]] const AZ::Uuid& documentId) {} - //! Signal that a material document dependency was modified - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a document dependency was modified + //! @param documentId unique id of document for which the notification is sent virtual void OnDocumentDependencyModified([[maybe_unused]] const AZ::Uuid& documentId) {} - //! Signal that a material document was modified externally - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a document was modified externally + //! @param documentId unique id of document for which the notification is sent virtual void OnDocumentExternallyModified([[maybe_unused]] const AZ::Uuid& documentId) {} - //! Signal that a material document undo state was updated - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a document undo state was updated + //! @param documentId unique id of document for which the notification is sent virtual void OnDocumentUndoStateChanged([[maybe_unused]] const AZ::Uuid& documentId) {} - //! Signal that a material property changed - //! @param documentId unique id of material document for which the notification is sent + //! Signal that a property changed + //! @param documentId unique id of document for which the notification is sent //! @param property object containing the property value and configuration that was modified virtual void OnDocumentPropertyValueModified([[maybe_unused]] const AZ::Uuid& documentId, [[maybe_unused]] const AtomToolsFramework::DynamicProperty& property) {} //! Signal that the property configuration has been changed. - //! @param documentId unique id of material document for which the notification is sent + //! @param documentId unique id of document for which the notification is sent //! @param property object containing the property value and configuration that was modified virtual void OnDocumentPropertyConfigModified([[maybe_unused]] const AZ::Uuid& documentId, [[maybe_unused]] const AtomToolsFramework::DynamicProperty& property) {} //! Signal that the property group visibility has been changed. - //! @param documentId unique id of material document for which the notification is sent + //! @param documentId unique id of document for which the notification is sent //! @param groupId id of the group that changed //! @param visible whether the property group is visible virtual void OnDocumentPropertyGroupVisibilityChanged([[maybe_unused]] const AZ::Uuid& documentId, [[maybe_unused]] const AZ::Name& groupId, [[maybe_unused]] bool visible) {} }; - using MaterialDocumentNotificationBus = AZ::EBus; -} // namespace MaterialEditor + using AtomToolsDocumentNotificationBus = AZ::EBus; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentRequestBus.h new file mode 100644 index 0000000000..a8ef7852ea --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentRequestBus.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include +#include + +namespace AtomToolsFramework +{ + class AtomToolsDocumentRequests + : public AZ::EBusTraits + { + public: + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; + typedef AZ::Uuid BusIdType; + + //! Get absolute path of document + virtual AZStd::string_view GetAbsolutePath() const = 0; + + //! Get relative path of document + virtual AZStd::string_view GetRelativePath() const = 0; + + //! Return property value + //! If the document is not open or the id can't be found, an invalid value is returned instead. + virtual const AZStd::any& GetPropertyValue(const AZ::Name& propertyFullName) const = 0; + + //! Returns a property object + //! If the document is not open or the id can't be found, an invalid property is returned. + virtual const AtomToolsFramework::DynamicProperty& GetProperty(const AZ::Name& propertyFullName) const = 0; + + //! Returns whether a property group is visible + //! If the document is not open or the id can't be found, returns false. + virtual bool IsPropertyGroupVisible(const AZ::Name& propertyGroupFullName) const = 0; + + //! Modify document property value + virtual void SetPropertyValue(const AZ::Name& propertyFullName, const AZStd::any& value) = 0; + + //! Load document and related data + //! @param loadPath absolute path of document to load + virtual bool Open(AZStd::string_view loadPath) = 0; + + //! Reopen document preserving edits + virtual bool Reopen() = 0; + + //! Save document to file + virtual bool Save() = 0; + + //! Save document copy + //! @param savePath absolute path where document is saved + virtual bool SaveAsCopy(AZStd::string_view savePath) = 0; + + //! Save document to a new source file derived from of the open document + //! @param savePath absolute path where document is saved + virtual bool SaveAsChild(AZStd::string_view savePath) = 0; + + //! Close document and reset its data + virtual bool Close() = 0; + + //! Document is loaded + virtual bool IsOpen() const = 0; + + //! Document has changes pending + virtual bool IsModified() const = 0; + + //! Can the document be saved + virtual bool IsSavable() const = 0; + + //! Returns true if there are reversible modifications to the document + virtual bool CanUndo() const = 0; + + //! Returns true if there are changes that were reversed and can be re-applied to the document + virtual bool CanRedo() const = 0; + + //! Restores the previous state of the document + virtual bool Undo() = 0; + + //! Restores the next state of the document + virtual bool Redo() = 0; + + //! Signal that editing is about to begin, like beginning to drag a slider control + virtual bool BeginEdit() = 0; + + //! Signal that editing has completed, like after releasing the mouse button after continuously dragging a slider control + virtual bool EndEdit() = 0; + }; + + using AtomToolsDocumentRequestBus = AZ::EBus; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystemRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystemRequestBus.h new file mode 100644 index 0000000000..f751915a9a --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystemRequestBus.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace AtomToolsFramework +{ + class AtomToolsDocument; + + //! AtomToolsDocumentSystemRequestBus provides high level requests for menus, scripts, etc. + class AtomToolsDocumentSystemRequests + : public AZ::EBusTraits + { + public: + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + + //! Register a document factory function used to create specific document types + virtual void RegisterDocumentType(AZStd::function documentCreator) = 0; + + //! Create a document object + //! @return Uuid of new document, or null Uuid if failed + virtual AZ::Uuid CreateDocument() = 0; + + //! Destroy a document object with the specified id + //! @return true if Uuid was found and removed, otherwise false + virtual bool DestroyDocument(const AZ::Uuid& documentId) = 0; + + //! Open a document for editing + //! @param sourcePath document to open. + //! @return unique id of new document if successful, otherwise null Uuid + virtual AZ::Uuid OpenDocument(AZStd::string_view sourcePath) = 0; + + //! Create a new document by specifying a source and prompting the user for destination path. + //! @param sourcePath document to open. + //! @param targetPath location where document is saved. + //! @return unique id of new document if successful, otherwise null Uuid + virtual AZ::Uuid CreateDocumentFromFile(AZStd::string_view sourcePath, AZStd::string_view targetPath) = 0; + + //! Close the specified document + //! @param documentId unique id of document to close + virtual bool CloseDocument(const AZ::Uuid& documentId) = 0; + + //! Close all documents + virtual bool CloseAllDocuments() = 0; + + //! Close all documents except for documentId + //! @param documentId unique id of document to not close + virtual bool CloseAllDocumentsExcept(const AZ::Uuid& documentId) = 0; + + //! Save the specified document + //! @param documentId unique id of document to save + virtual bool SaveDocument(const AZ::Uuid& documentId) = 0; + + //! Save the specified document to a different file + //! @param documentId unique id of document to save + //! @param targetPath location where document is saved. + virtual bool SaveDocumentAsCopy(const AZ::Uuid& documentId, AZStd::string_view targetPath) = 0; + + //! Save the specified document to a different file, referencing the original document as its parent + //! @param documentId unique id of document to save + //! @param targetPath location where document is saved. + virtual bool SaveDocumentAsChild(const AZ::Uuid& documentId, AZStd::string_view targetPath) = 0; + + //! Save all documents + virtual bool SaveAllDocuments() = 0; + }; + + using AtomToolsDocumentSystemRequestBus = AZ::EBus; + +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystemSettings.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystemSettings.h new file mode 100644 index 0000000000..9b4c1d77fe --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystemSettings.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#include +#include +#include +#endif + +namespace AtomToolsFramework +{ + struct AtomToolsDocumentSystemSettings + : public AZ::UserSettings + { + AZ_RTTI(AtomToolsDocumentSystemSettings, "{9E576D4F-A74A-4326-9135-C07284D0A3B9}", AZ::UserSettings); + AZ_CLASS_ALLOCATOR(AtomToolsDocumentSystemSettings, AZ::SystemAllocator, 0); + + static void Reflect(AZ::ReflectContext* context); + + bool m_showReloadDocumentPrompt = true; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp index aedad7706b..efd3fec0e8 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp @@ -7,15 +7,15 @@ #include #include - -#include #include +#include #include #include #include -#include #include +#include + #include #include #include @@ -66,6 +66,9 @@ namespace AtomToolsFramework this->PumpSystemEventLoopUntilEmpty(); this->Tick(); }); + + // Suppress spam from the Source Control system + m_traceLogger.AddWindowFilter(AzToolsFramework::SCC_WINDOW); } AtomToolsApplication ::~AtomToolsApplication() @@ -396,7 +399,7 @@ namespace AtomToolsFramework AZStd::string fileName = GetBuildTargetName() + ".log"; - m_traceLogger.WriteStartupLog(fileName.c_str()); + m_traceLogger.PrepareLogFile(fileName.c_str()); if (!LaunchDiscoveryService()) { diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp index b601596032..21a185b290 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp @@ -8,6 +8,7 @@ #include #include +#include #include namespace AtomToolsFramework @@ -16,6 +17,7 @@ namespace AtomToolsFramework { m_descriptors.insert(m_descriptors.end(), { AtomToolsFrameworkSystemComponent::CreateDescriptor(), + AtomToolsDocumentSystemComponent::CreateDescriptor(), AtomToolsMainWindowSystemComponent::CreateDescriptor(), }); } @@ -24,6 +26,7 @@ namespace AtomToolsFramework { return AZ::ComponentTypeList{ azrtti_typeid(), + azrtti_typeid(), azrtti_typeid(), }; } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp new file mode 100644 index 0000000000..48212fe154 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp @@ -0,0 +1,149 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +namespace AtomToolsFramework +{ + AtomToolsDocument::AtomToolsDocument() + { + AtomToolsDocumentRequestBus::Handler::BusConnect(m_id); + AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsDocumentNotificationBus::Events::OnDocumentCreated, m_id); + } + + AtomToolsDocument::~AtomToolsDocument() + { + AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsDocumentNotificationBus::Events::OnDocumentDestroyed, m_id); + AtomToolsDocumentRequestBus::Handler::BusDisconnect(); + } + + const AZ::Uuid& AtomToolsDocument::GetId() const + { + return m_id; + } + + AZStd::string_view AtomToolsDocument::GetAbsolutePath() const + { + return m_absolutePath; + } + + AZStd::string_view AtomToolsDocument::GetRelativePath() const + { + return m_relativePath; + } + + const AZStd::any& AtomToolsDocument::GetPropertyValue(const AZ::Name& propertyFullName) const + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return m_invalidValue; + } + + const AtomToolsFramework::DynamicProperty& AtomToolsDocument::GetProperty(const AZ::Name& propertyFullName) const + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return m_invalidProperty; + } + + bool AtomToolsDocument::IsPropertyGroupVisible(const AZ::Name& propertyGroupFullName) const + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } + + void AtomToolsDocument::SetPropertyValue(const AZ::Name& propertyFullName, const AZStd::any& value) + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + } + + bool AtomToolsDocument::Open(AZStd::string_view loadPath) + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } + + bool AtomToolsDocument::Reopen() + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } + + bool AtomToolsDocument::Save() + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } + + bool AtomToolsDocument::SaveAsCopy(AZStd::string_view savePath) + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } + + + bool AtomToolsDocument::SaveAsChild(AZStd::string_view savePath) + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } + + bool AtomToolsDocument::Close() + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } + + bool AtomToolsDocument::IsOpen() const + { + return false; + } + + bool AtomToolsDocument::IsModified() const + { + return false; + } + + bool AtomToolsDocument::IsSavable() const + { + return false; + } + + bool AtomToolsDocument::CanUndo() const + { + return false; + } + + bool AtomToolsDocument::CanRedo() const + { + return false; + } + + bool AtomToolsDocument::Undo() + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } + + bool AtomToolsDocument::Redo() + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } + + bool AtomToolsDocument::BeginEdit() + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } + + bool AtomToolsDocument::EndEdit() + { + AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); + return false; + } +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.cpp new file mode 100644 index 0000000000..5652e9fe23 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.cpp @@ -0,0 +1,511 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT +#include +#include +#include +AZ_POP_DISABLE_WARNING + +namespace AtomToolsFramework +{ + AtomToolsDocumentSystemComponent::AtomToolsDocumentSystemComponent() + { + } + + void AtomToolsDocumentSystemComponent::Reflect(AZ::ReflectContext* context) + { + AtomToolsDocumentSystemSettings::Reflect(context); + + if (AZ::SerializeContext* serialize = azrtti_cast(context)) + { + serialize->Class() + ->Version(0); + + if (AZ::EditContext* ec = serialize->GetEditContext()) + { + ec->Class("AtomToolsDocumentSystemComponent", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("System")) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ; + } + } + + if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) + { + behaviorContext->EBus("AtomToolsDocumentSystemRequestBus") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "Editor") + ->Attribute(AZ::Script::Attributes::Module, "atomtools") + ->Event("CreateDocument", &AtomToolsDocumentSystemRequestBus::Events::CreateDocument) + ->Event("DestroyDocument", &AtomToolsDocumentSystemRequestBus::Events::DestroyDocument) + ->Event("OpenDocument", &AtomToolsDocumentSystemRequestBus::Events::OpenDocument) + ->Event("CreateDocumentFromFile", &AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile) + ->Event("CloseDocument", &AtomToolsDocumentSystemRequestBus::Events::CloseDocument) + ->Event("CloseAllDocuments", &AtomToolsDocumentSystemRequestBus::Events::CloseAllDocuments) + ->Event("CloseAllDocumentsExcept", &AtomToolsDocumentSystemRequestBus::Events::CloseAllDocumentsExcept) + ->Event("SaveDocument", &AtomToolsDocumentSystemRequestBus::Events::SaveDocument) + ->Event("SaveDocumentAsCopy", &AtomToolsDocumentSystemRequestBus::Events::SaveDocumentAsCopy) + ->Event("SaveDocumentAsChild", &AtomToolsDocumentSystemRequestBus::Events::SaveDocumentAsChild) + ->Event("SaveAllDocuments", &AtomToolsDocumentSystemRequestBus::Events::SaveAllDocuments) + ; + + behaviorContext->EBus("AtomToolsDocumentRequestBus") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "Editor") + ->Attribute(AZ::Script::Attributes::Module, "atomtools") + ->Event("GetAbsolutePath", &AtomToolsDocumentRequestBus::Events::GetAbsolutePath) + ->Event("GetRelativePath", &AtomToolsDocumentRequestBus::Events::GetRelativePath) + ->Event("GetPropertyValue", &AtomToolsDocumentRequestBus::Events::GetPropertyValue) + ->Event("SetPropertyValue", &AtomToolsDocumentRequestBus::Events::SetPropertyValue) + ->Event("Open", &AtomToolsDocumentRequestBus::Events::Open) + ->Event("Reopen", &AtomToolsDocumentRequestBus::Events::Reopen) + ->Event("Close", &AtomToolsDocumentRequestBus::Events::Close) + ->Event("Save", &AtomToolsDocumentRequestBus::Events::Save) + ->Event("SaveAsChild", &AtomToolsDocumentRequestBus::Events::SaveAsChild) + ->Event("SaveAsCopy", &AtomToolsDocumentRequestBus::Events::SaveAsCopy) + ->Event("IsOpen", &AtomToolsDocumentRequestBus::Events::IsOpen) + ->Event("IsModified", &AtomToolsDocumentRequestBus::Events::IsModified) + ->Event("IsSavable", &AtomToolsDocumentRequestBus::Events::IsSavable) + ->Event("CanUndo", &AtomToolsDocumentRequestBus::Events::CanUndo) + ->Event("CanRedo", &AtomToolsDocumentRequestBus::Events::CanRedo) + ->Event("Undo", &AtomToolsDocumentRequestBus::Events::Undo) + ->Event("Redo", &AtomToolsDocumentRequestBus::Events::Redo) + ->Event("BeginEdit", &AtomToolsDocumentRequestBus::Events::BeginEdit) + ->Event("EndEdit", &AtomToolsDocumentRequestBus::Events::EndEdit) + ; + } + } + + void AtomToolsDocumentSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC_CE("AtomToolsDocumentSystemService")); + } + + void AtomToolsDocumentSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("AtomToolsDocumentSystemService")); + } + + void AtomToolsDocumentSystemComponent::Init() + { + } + + void AtomToolsDocumentSystemComponent::Activate() + { + m_documentMap.clear(); + m_settings = AZ::UserSettings::CreateFind(AZ_CRC_CE("AtomToolsDocumentSystemSettings"), AZ::UserSettings::CT_GLOBAL); + AtomToolsDocumentSystemRequestBus::Handler::BusConnect(); + AtomToolsDocumentNotificationBus::Handler::BusConnect(); + } + + void AtomToolsDocumentSystemComponent::Deactivate() + { + AZ::TickBus::Handler::BusDisconnect(); + AtomToolsDocumentNotificationBus::Handler::BusDisconnect(); + AtomToolsDocumentSystemRequestBus::Handler::BusDisconnect(); + m_documentMap.clear(); + } + + void AtomToolsDocumentSystemComponent::RegisterDocumentType(AZStd::function documentCreator) + { + m_documentCreator = documentCreator; + } + + AZ::Uuid AtomToolsDocumentSystemComponent::CreateDocument() + { + if (!m_documentCreator) + { + AZ_Error("AtomToolsDocument", false, "Failed to create new document"); + return AZ::Uuid::CreateNull(); + } + + AZStd::unique_ptr document(m_documentCreator()); + if (!document) + { + AZ_Error("AtomToolsDocument", false, "Failed to create new document"); + return AZ::Uuid::CreateNull(); + } + + AZ::Uuid documentId = document->GetId(); + m_documentMap.emplace(documentId, document.release()); + return documentId; + } + + bool AtomToolsDocumentSystemComponent::DestroyDocument(const AZ::Uuid& documentId) + { + return m_documentMap.erase(documentId) != 0; + } + + void AtomToolsDocumentSystemComponent::OnDocumentExternallyModified(const AZ::Uuid& documentId) + { + m_documentIdsToReopen.insert(documentId); + if (!AZ::TickBus::Handler::BusIsConnected()) + { + AZ::TickBus::Handler::BusConnect(); + } + } + + void AtomToolsDocumentSystemComponent::OnDocumentDependencyModified(const AZ::Uuid& documentId) + { + m_documentIdsToReopen.insert(documentId); + if (!AZ::TickBus::Handler::BusIsConnected()) + { + AZ::TickBus::Handler::BusConnect(); + } + } + + void AtomToolsDocumentSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) + { + for (const AZ::Uuid& documentId : m_documentIdsToReopen) + { + AZStd::string documentPath; + AtomToolsDocumentRequestBus::EventResult(documentPath, documentId, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); + + if (m_settings->m_showReloadDocumentPrompt && + (QMessageBox::question(QApplication::activeWindow(), + QString("Document was externally modified"), + QString("Would you like to reopen the document:\n%1?").arg(documentPath.c_str()), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)) + { + continue; + } + + AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + bool openResult = false; + AtomToolsDocumentRequestBus::EventResult(openResult, documentId, &AtomToolsDocumentRequestBus::Events::Open, documentPath); + if (!openResult) + { + QMessageBox::critical( + QApplication::activeWindow(), QString("Document could not be opened"), + QString("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); + } + } + + for (const AZ::Uuid& documentId : m_documentIdsToReopen) + { + AZStd::string documentPath; + AtomToolsDocumentRequestBus::EventResult(documentPath, documentId, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); + + if (m_settings->m_showReloadDocumentPrompt && + (QMessageBox::question(QApplication::activeWindow(), + QString("Document dependencies have changed"), + QString("Would you like to update the document with these changes:\n%1?").arg(documentPath.c_str()), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)) + { + continue; + } + + AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + bool openResult = false; + AtomToolsDocumentRequestBus::EventResult(openResult, documentId, &AtomToolsDocumentRequestBus::Events::Reopen); + if (!openResult) + { + QMessageBox::critical( + QApplication::activeWindow(), QString("Document could not be opened"), + QString("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); + } + } + + m_documentIdsToReopen.clear(); + m_documentIdsToReopen.clear(); + AZ::TickBus::Handler::BusDisconnect(); + } + + AZ::Uuid AtomToolsDocumentSystemComponent::OpenDocument(AZStd::string_view sourcePath) + { + return OpenDocumentImpl(sourcePath, true); + } + + AZ::Uuid AtomToolsDocumentSystemComponent::CreateDocumentFromFile(AZStd::string_view sourcePath, AZStd::string_view targetPath) + { + const AZ::Uuid documentId = OpenDocumentImpl(sourcePath, false); + if (documentId.IsNull()) + { + return AZ::Uuid::CreateNull(); + } + + if (!SaveDocumentAsChild(documentId, targetPath)) + { + CloseDocument(documentId); + return AZ::Uuid::CreateNull(); + } + + // Send document open notification after creating new one + AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); + return documentId; + } + + bool AtomToolsDocumentSystemComponent::CloseDocument(const AZ::Uuid& documentId) + { + bool isOpen = false; + AtomToolsDocumentRequestBus::EventResult(isOpen, documentId, &AtomToolsDocumentRequestBus::Events::IsOpen); + if (!isOpen) + { + // immediately destroy unopened documents + AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::DestroyDocument, documentId); + return true; + } + + AZStd::string documentPath; + AtomToolsDocumentRequestBus::EventResult(documentPath, documentId, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); + + bool isModified = false; + AtomToolsDocumentRequestBus::EventResult(isModified, documentId, &AtomToolsDocumentRequestBus::Events::IsModified); + if (isModified) + { + auto selection = QMessageBox::question(QApplication::activeWindow(), + QString("Document has unsaved changes"), + QString("Do you want to save changes to\n%1?").arg(documentPath.c_str()), + QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); + if (selection == QMessageBox::Cancel) + { + AZ_TracePrintf("AtomToolsDocument", "Close document canceled: %s", documentPath.c_str()); + return false; + } + if (selection == QMessageBox::Yes) + { + if (!SaveDocument(documentId)) + { + AZ_Error("AtomToolsDocument", false, "Close document failed because document was not saved: %s", documentPath.c_str()); + return false; + } + } + } + + AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + bool closeResult = true; + AtomToolsDocumentRequestBus::EventResult(closeResult, documentId, &AtomToolsDocumentRequestBus::Events::Close); + if (!closeResult) + { + QMessageBox::critical( + QApplication::activeWindow(), QString("Document could not be closed"), + QString("Failed to close: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + return false; + } + + AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::DestroyDocument, documentId); + return true; + } + + bool AtomToolsDocumentSystemComponent::CloseAllDocuments() + { + bool result = true; + auto documentMap = m_documentMap; + for (const auto& documentPair : documentMap) + { + if (!CloseDocument(documentPair.first)) + { + result = false; + } + } + + return result; + } + + bool AtomToolsDocumentSystemComponent::CloseAllDocumentsExcept(const AZ::Uuid& documentId) + { + bool result = true; + auto documentMap = m_documentMap; + for (const auto& documentPair : documentMap) + { + if (documentPair.first != documentId) + { + if (!CloseDocument(documentPair.first)) + { + result = false; + } + } + } + + return result; + } + + bool AtomToolsDocumentSystemComponent::SaveDocument(const AZ::Uuid& documentId) + { + AZStd::string saveDocumentPath; + AtomToolsDocumentRequestBus::EventResult(saveDocumentPath, documentId, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); + + if (saveDocumentPath.empty() || !AzFramework::StringFunc::Path::Normalize(saveDocumentPath)) + { + return false; + } + + const QFileInfo saveInfo(saveDocumentPath.c_str()); + if (saveInfo.exists() && !saveInfo.isWritable()) + { + QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Document could not be overwritten:\n%1").arg(saveDocumentPath.c_str())); + return false; + } + + AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + bool result = false; + AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsDocumentRequestBus::Events::Save); + if (!result) + { + QMessageBox::critical( + QApplication::activeWindow(), QString("Document could not be saved"), + QString("Failed to save: \n%1\n\n%2").arg(saveDocumentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + return false; + } + + return true; + } + + bool AtomToolsDocumentSystemComponent::SaveDocumentAsCopy(const AZ::Uuid& documentId, AZStd::string_view targetPath) + { + AZStd::string saveDocumentPath = targetPath; + if (saveDocumentPath.empty() || !AzFramework::StringFunc::Path::Normalize(saveDocumentPath)) + { + return false; + } + + const QFileInfo saveInfo(saveDocumentPath.c_str()); + if (saveInfo.exists() && !saveInfo.isWritable()) + { + QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Document could not be overwritten:\n%1").arg(saveDocumentPath.c_str())); + return false; + } + + AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + bool result = false; + AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsDocumentRequestBus::Events::SaveAsCopy, saveDocumentPath); + if (!result) + { + QMessageBox::critical( + QApplication::activeWindow(), QString("Document could not be saved"), + QString("Failed to save: \n%1\n\n%2").arg(saveDocumentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + return false; + } + + return true; + } + + bool AtomToolsDocumentSystemComponent::SaveDocumentAsChild(const AZ::Uuid& documentId, AZStd::string_view targetPath) + { + AZStd::string saveDocumentPath = targetPath; + if (saveDocumentPath.empty() || !AzFramework::StringFunc::Path::Normalize(saveDocumentPath)) + { + return false; + } + + const QFileInfo saveInfo(saveDocumentPath.c_str()); + if (saveInfo.exists() && !saveInfo.isWritable()) + { + QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Document could not be overwritten:\n%1").arg(saveDocumentPath.c_str())); + return false; + } + + AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + bool result = false; + AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsDocumentRequestBus::Events::SaveAsChild, saveDocumentPath); + if (!result) + { + QMessageBox::critical( + QApplication::activeWindow(), QString("Document could not be saved"), + QString("Failed to save: \n%1\n\n%2").arg(saveDocumentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + return false; + } + + return true; + } + + bool AtomToolsDocumentSystemComponent::SaveAllDocuments() + { + bool result = true; + for (const auto& documentPair : m_documentMap) + { + if (!SaveDocument(documentPair.first)) + { + result = false; + } + } + + return result; + } + + AZ::Uuid AtomToolsDocumentSystemComponent::OpenDocumentImpl(AZStd::string_view sourcePath, bool checkIfAlreadyOpen) + { + AZStd::string requestedPath = sourcePath; + if (requestedPath.empty()) + { + return AZ::Uuid::CreateNull(); + } + + if (!AzFramework::StringFunc::Path::Normalize(requestedPath)) + { + QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Document path is invalid:\n%1").arg(requestedPath.c_str())); + return AZ::Uuid::CreateNull(); + } + + // Determine if the file is already open and select it + if (checkIfAlreadyOpen) + { + for (const auto& documentPair : m_documentMap) + { + AZStd::string openDocumentPath; + AtomToolsDocumentRequestBus::EventResult(openDocumentPath, documentPair.first, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); + if (openDocumentPath == requestedPath) + { + AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentPair.first); + return documentPair.first; + } + } + } + + AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + AZ::Uuid documentId = AZ::Uuid::CreateNull(); + AtomToolsDocumentSystemRequestBus::BroadcastResult(documentId, &AtomToolsDocumentSystemRequestBus::Events::CreateDocument); + if (documentId.IsNull()) + { + QMessageBox::critical( + QApplication::activeWindow(), QString("Document could not be created"), + QString("Failed to create: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); + return AZ::Uuid::CreateNull(); + } + + traceRecorder.GetDump().clear(); + + bool openResult = false; + AtomToolsDocumentRequestBus::EventResult(openResult, documentId, &AtomToolsDocumentRequestBus::Events::Open, requestedPath); + if (!openResult) + { + QMessageBox::critical( + QApplication::activeWindow(), QString("Document could not be opened"), + QString("Failed to open: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); + AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::DestroyDocument, documentId); + return AZ::Uuid::CreateNull(); + } + + return documentId; + } +} diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.h new file mode 100644 index 0000000000..9c556a07e7 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT +#include +#include +AZ_POP_DISABLE_WARNING + +namespace AtomToolsFramework +{ + //! AtomToolsDocumentSystemComponent is the central component of the Material Editor Core gem + class AtomToolsDocumentSystemComponent + : public AZ::Component + , private AZ::TickBus::Handler + , private AtomToolsDocumentNotificationBus::Handler + , private AtomToolsDocumentSystemRequestBus::Handler + { + public: + AZ_COMPONENT(AtomToolsDocumentSystemComponent, "{343A3383-6A59-4343-851B-BF84FC6CB18E}"); + + AtomToolsDocumentSystemComponent(); + ~AtomToolsDocumentSystemComponent() = default; + AtomToolsDocumentSystemComponent(const AtomToolsDocumentSystemComponent&) = delete; + AtomToolsDocumentSystemComponent& operator=(const AtomToolsDocumentSystemComponent&) = delete; + + static void Reflect(AZ::ReflectContext* context); + + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + + private: + //////////////////////////////////////////////////////////////////////// + // AZ::Component interface implementation + void Init() override; + void Activate() override; + void Deactivate() override; + //////////////////////////////////////////////////////////////////////// + + ////////////////////////////////////////////////////////////////////////// + // AtomToolsDocumentNotificationBus::Handler overrides... + void OnDocumentDependencyModified(const AZ::Uuid& documentId) override; + void OnDocumentExternallyModified(const AZ::Uuid& documentId) override; + ////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////// + // AZ::TickBus::Handler overrides... + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + //////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////// + // AtomToolsDocumentSystemRequestBus::Handler overrides... + void RegisterDocumentType(AZStd::function documentCreator) override; + AZ::Uuid CreateDocument() override; + bool DestroyDocument(const AZ::Uuid& documentId) override; + AZ::Uuid OpenDocument(AZStd::string_view sourcePath) override; + AZ::Uuid CreateDocumentFromFile(AZStd::string_view sourcePath, AZStd::string_view targetPath) override; + bool CloseDocument(const AZ::Uuid& documentId) override; + bool CloseAllDocuments() override; + bool CloseAllDocumentsExcept(const AZ::Uuid& documentId) override; + bool SaveDocument(const AZ::Uuid& documentId) override; + bool SaveDocumentAsCopy(const AZ::Uuid& documentId, AZStd::string_view targetPath) override; + bool SaveDocumentAsChild(const AZ::Uuid& documentId, AZStd::string_view targetPath) override; + bool SaveAllDocuments() override; + //////////////////////////////////////////////////////////////////////// + + AZ::Uuid OpenDocumentImpl(AZStd::string_view sourcePath, bool checkIfAlreadyOpen); + + AZStd::intrusive_ptr m_settings; + AZStd::function m_documentCreator; + AZStd::unordered_map> m_documentMap; + AZStd::unordered_set m_documentIdsToRebuild; + AZStd::unordered_set m_documentIdsToReopen; + const size_t m_maxMessageBoxLineCount = 15; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemSettings.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemSettings.cpp new file mode 100644 index 0000000000..94af43e524 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemSettings.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include + +namespace AtomToolsFramework +{ + void AtomToolsDocumentSystemSettings::Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("showReloadDocumentPrompt", &AtomToolsDocumentSystemSettings::m_showReloadDocumentPrompt) + ; + + if (auto editContext = serializeContext->GetEditContext()) + { + editContext->Class( + "AtomToolsDocumentSystemSettings", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Default, &AtomToolsDocumentSystemSettings::m_showReloadDocumentPrompt, "Show Reload Document Prompt", "") + ; + } + } + + if (auto behaviorContext = azrtti_cast(context)) + { + behaviorContext->Class("AtomToolsDocumentSystemSettings") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "Editor") + ->Attribute(AZ::Script::Attributes::Module, "atomtools") + ->Constructor() + ->Constructor() + ->Property("showReloadDocumentPrompt", BehaviorValueProperty(&AtomToolsDocumentSystemSettings::m_showReloadDocumentPrompt)) + ; + } + } +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake index 8eb82778e3..cd056f5fcf 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake @@ -11,6 +11,11 @@ set(FILES Include/AtomToolsFramework/Communication/LocalServer.h Include/AtomToolsFramework/Communication/LocalSocket.h Include/AtomToolsFramework/Debug/TraceRecorder.h + Include/AtomToolsFramework/Document/AtomToolsDocument.h + Include/AtomToolsFramework/Document/AtomToolsDocumentSystemSettings.h + Include/AtomToolsFramework/Document/AtomToolsDocumentSystemRequestBus.h + Include/AtomToolsFramework/Document/AtomToolsDocumentNotificationBus.h + Include/AtomToolsFramework/Document/AtomToolsDocumentRequestBus.h Include/AtomToolsFramework/DynamicProperty/DynamicProperty.h Include/AtomToolsFramework/DynamicProperty/DynamicPropertyGroup.h Include/AtomToolsFramework/Inspector/InspectorWidget.h @@ -32,6 +37,10 @@ set(FILES Source/Communication/LocalServer.cpp Source/Communication/LocalSocket.cpp Source/Debug/TraceRecorder.cpp + Source/Document/AtomToolsDocument.cpp + Source/Document/AtomToolsDocumentSystemSettings.cpp + Source/Document/AtomToolsDocumentSystemComponent.cpp + Source/Document/AtomToolsDocumentSystemComponent.h Source/DynamicProperty/DynamicProperty.cpp Source/DynamicProperty/DynamicPropertyGroup.cpp Source/Inspector/InspectorWidget.cpp diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Core/MaterialDocumentFactoryRequestBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Core/MaterialDocumentFactoryRequestBus.h deleted file mode 100644 index e936d5159b..0000000000 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Core/MaterialDocumentFactoryRequestBus.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include -#include -#include - -namespace MaterialEditor -{ - //! MaterialDocumentFactoryRequestBus provides a factory interface for creating and destroying material documents (in memory) - class MaterialDocumentFactoryRequests - : public AZ::EBusTraits - { - public: - // Only a single handler is allowed - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - - //! Create a material document object - //! @return Uuid of new material document, or null Uuid if failed - virtual AZ::Uuid CreateDocument() = 0; - - //! Destroy a material document object with the specified id - //! @return true if Uuid was found and removed, otherwise false - virtual bool DestroyDocument(const AZ::Uuid& documentId) = 0; - }; - - using MaterialDocumentFactoryRequestBus = AZ::EBus; - -} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentRequestBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentRequestBus.h index f81476a3a9..c95aa4f215 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentRequestBus.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentRequestBus.h @@ -7,15 +7,10 @@ */ #pragma once +#include #include #include -#include - #include -#include - -#include -#include namespace AZ { @@ -39,12 +34,6 @@ namespace MaterialEditor static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; typedef AZ::Uuid BusIdType; - //! Get absolute path of material source file - virtual AZStd::string_view GetAbsolutePath() const = 0; - - //! Get relative path of material source file - virtual AZStd::string_view GetRelativePath() const = 0; - //! Get material asset created by MaterialDocument virtual AZ::Data::Asset GetAsset() const = 0; @@ -56,69 +45,6 @@ namespace MaterialEditor //! Get the internal material type source data virtual const AZ::RPI::MaterialTypeSourceData* GetMaterialTypeSourceData() const = 0; - - //! Return property value - //! If the document is not open or the id can't be found, an invalid value is returned instead. - virtual const AZStd::any& GetPropertyValue(const AZ::Name& propertyFullName) const = 0; - - //! Returns a property object - //! If the document is not open or the id can't be found, an invalid property is returned. - virtual const AtomToolsFramework::DynamicProperty& GetProperty(const AZ::Name& propertyFullName) const = 0; - - //! Returns whether a property group is visible - //! If the document is not open or the id can't be found, returns false. - virtual bool IsPropertyGroupVisible(const AZ::Name& propertyGroupFullName) const = 0; - - //! Modify material property value - virtual void SetPropertyValue(const AZ::Name& propertyFullName, const AZStd::any& value) = 0; - - //! Load source material and related data - //! @param loadPath Absolute path of material to load - virtual bool Open(AZStd::string_view loadPath) = 0; - - //! Reload document preserving edits - virtual bool Rebuild() = 0; - - //! Save material to source file - virtual bool Save() = 0; - - //! Save material to a new source file - //! @param savePath Absolute path where material is saved - virtual bool SaveAsCopy(AZStd::string_view savePath) = 0; - - //! Save material to a new source file as a child of the open material - //! @param savePath Absolute path where material is saved - virtual bool SaveAsChild(AZStd::string_view savePath) = 0; - - //! Close material document and reset its data - virtual bool Close() = 0; - - //! Material is loaded - virtual bool IsOpen() const = 0; - - //! Material has changes pending - virtual bool IsModified() const = 0; - - //! Can the document be saved - virtual bool IsSavable() const = 0; - - //! Returns true if there are reversible modifications to the material document - virtual bool CanUndo() const = 0; - - //! Returns true if there are changes that were reversed and can be re-applied to the material document - virtual bool CanRedo() const = 0; - - //! Restores the previous state of the material document - virtual bool Undo() = 0; - - //! Restores the next state of the material document - virtual bool Redo() = 0; - - //! Signal that property editing is about to begin, like beginning to drag a slider control - virtual bool BeginEdit() = 0; - - //! Signal that property editing has completed, like after releasing the mouse button after continuously dragging a slider control - virtual bool EndEdit() = 0; }; using MaterialDocumentRequestBus = AZ::EBus; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h index d9c835b14b..5f39c50717 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h @@ -20,12 +20,11 @@ namespace MaterialEditor struct MaterialDocumentSettings : public AZ::UserSettings { - AZ_RTTI(MaterialDocumentSettings, "{FA4F4BF3-BF39-4753-AAF7-AF383B868881}", AZ::UserSettings); + AZ_RTTI(MaterialDocumentSettings, "{12E8461F-65AD-4AD2-8A1D-82C3B1183522}", AZ::UserSettings); AZ_CLASS_ALLOCATOR(MaterialDocumentSettings, AZ::SystemAllocator, 0); static void Reflect(AZ::ReflectContext* context); - bool m_showReloadDocumentPrompt = true; AZStd::string m_defaultMaterialTypeName = "StandardPBR"; }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSystemRequestBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSystemRequestBus.h deleted file mode 100644 index 18534b3d2d..0000000000 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSystemRequestBus.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include - -namespace MaterialEditor -{ - static const char* MaterialExtension = "material"; - static const char* MaterialTypeExtension = "materialtype"; - - //! MaterialDocumentSystemRequestBus provides high level file requests for menus, scripts, etc. - class MaterialDocumentSystemRequests - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - //! Create a material document object - //! @return Uuid of new material document, or null Uuid if failed - virtual AZ::Uuid CreateDocument() = 0; - - //! Destroy a material document object with the specified id - //! @return true if Uuid was found and removed, otherwise false - virtual bool DestroyDocument(const AZ::Uuid& documentId) = 0; - - //! Open a material document for editing - //! @param sourcePath material document to open. - //! @return unique id of new material document if successful, otherwise null Uuid - virtual AZ::Uuid OpenDocument(AZStd::string_view sourcePath) = 0; - - //! Create a new document by specifying a source and prompting the user for destination path. - //! If the source file is a material type then this results in creating a new material based on that type. - //! If the source file is a material this results in creating a child material with the source file as its parent. - //! @param sourcePath material document to open. - //! @param targetPath location where document is saved. - //! @return unique id of new material document if successful, otherwise null Uuid - virtual AZ::Uuid CreateDocumentFromFile(AZStd::string_view sourcePath, AZStd::string_view targetPath) = 0; - - //! Close the specified material document - //! @param documentId unique id of material document to close - virtual bool CloseDocument(const AZ::Uuid& documentId) = 0; - - //! Close all material documents - virtual bool CloseAllDocuments() = 0; - - //! Close all material documents except for documentId - //! @param documentId unique id of material document to not close - virtual bool CloseAllDocumentsExcept(const AZ::Uuid& documentId) = 0; - - //! Save the specified material document - //! @param documentId unique id of material document to save - virtual bool SaveDocument(const AZ::Uuid& documentId) = 0; - - //! Save the specified material document to a different file - //! @param documentId unique id of material document to save - //! @param targetPath location where document is saved. - virtual bool SaveDocumentAsCopy(const AZ::Uuid& documentId, AZStd::string_view targetPath) = 0; - - //! Save the specified material document to a different file, referencing the original material as its parent - //! @param documentId unique id of material document to save - //! @param targetPath location where document is saved. - virtual bool SaveDocumentAsChild(const AZ::Uuid& documentId, AZStd::string_view targetPath) = 0; - - //! Save all material documents - virtual bool SaveAllDocuments() = 0; - }; - - using MaterialDocumentSystemRequestBus = AZ::EBus; - -} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index f2e012e158..11834beb73 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -6,53 +6,39 @@ * */ -#include -#include -#include #include #include +#include #include #include -#include #include #include +#include +#include +#include #include -#include -#include +#include #include #include #include +#include namespace MaterialEditor { MaterialDocument::MaterialDocument() + : AtomToolsFramework::AtomToolsDocument() { MaterialDocumentRequestBus::Handler::BusConnect(m_id); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentCreated, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentCreated, m_id); } MaterialDocument::~MaterialDocument() { - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentDestroyed, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentDestroyed, m_id); MaterialDocumentRequestBus::Handler::BusDisconnect(); Clear(); } - const AZ::Uuid& MaterialDocument::GetId() const - { - return m_id; - } - - AZStd::string_view MaterialDocument::GetAbsolutePath() const - { - return m_absolutePath; - } - - AZStd::string_view MaterialDocument::GetRelativePath() const - { - return m_relativePath; - } - AZ::Data::Asset MaterialDocument::GetAsset() const { return m_materialAsset; @@ -170,17 +156,17 @@ namespace MaterialEditor EditorMaterialFunctorResult result = RunEditorMaterialFunctors(dirtyFlags); for (const Name& changedPropertyGroupName : result.m_updatedPropertyGroups) { - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentPropertyGroupVisibilityChanged, m_id, changedPropertyGroupName, IsPropertyGroupVisible(changedPropertyGroupName)); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentPropertyGroupVisibilityChanged, m_id, changedPropertyGroupName, IsPropertyGroupVisible(changedPropertyGroupName)); } for (const Name& changedPropertyName : result.m_updatedProperties) { - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentPropertyConfigModified, m_id, GetProperty(changedPropertyName)); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentPropertyConfigModified, m_id, GetProperty(changedPropertyName)); } } } - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentPropertyValueModified, m_id, property); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentModified, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentPropertyValueModified, m_id, property); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentModified, m_id); } bool MaterialDocument::Open(AZStd::string_view loadPath) @@ -192,11 +178,11 @@ namespace MaterialEditor return false; } - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentOpened, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, m_id); return true; } - bool MaterialDocument::Rebuild() + bool MaterialDocument::Reopen() { // Store history and property changes that should be reapplied after reload auto undoHistoryToRestore = m_undoHistory; @@ -222,7 +208,7 @@ namespace MaterialEditor RestorePropertyValues(propertyValuesToRestore); AZStd::swap(undoHistoryToRestore, m_undoHistory); AZStd::swap(undoHistoryIndexToRestore, m_undoHistoryIndex); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentOpened, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, m_id); return true; } @@ -285,7 +271,7 @@ namespace MaterialEditor AZ_TracePrintf("MaterialDocument", "Material document saved: '%s'.\n", m_absolutePath.data()); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentSaved, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentSaved, m_id); m_saveTriggeredInternally = true; return true; @@ -348,7 +334,7 @@ namespace MaterialEditor AZ_TracePrintf("MaterialDocument", "Material document saved: '%s'.\n", normalizedSavePath.c_str()); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentSaved, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentSaved, m_id); // If the document is saved to a new file we need to reopen the new document to update assets, paths, property deltas. if (!Open(normalizedSavePath)) @@ -424,7 +410,7 @@ namespace MaterialEditor AZ_TracePrintf("MaterialDocument", "Material document saved: '%s'.\n", normalizedSavePath.c_str()); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentSaved, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentSaved, m_id); // If the document is saved to a new file we need to reopen the new document to update assets, paths, property deltas. if (!Open(normalizedSavePath)) @@ -450,7 +436,7 @@ namespace MaterialEditor AZ_TracePrintf("MaterialDocument", "Material document closed: '%s'.\n", m_absolutePath.c_str()); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentClosed, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentClosed, m_id); // Clearing after notification so paths are still available Clear(); @@ -496,7 +482,7 @@ namespace MaterialEditor // The history index is one beyond the last executed command. Decrement the index then execute undo. m_undoHistory[--m_undoHistoryIndex].first(); AZ_TracePrintf("MaterialDocument", "Material document undo: '%s'.\n", m_absolutePath.c_str()); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); return true; } return false; @@ -509,7 +495,7 @@ namespace MaterialEditor // Execute the current redo command then move the history index to the next position. m_undoHistory[m_undoHistoryIndex++].second(); AZ_TracePrintf("MaterialDocument", "Material document redo: '%s'.\n", m_absolutePath.c_str()); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); return true; } return false; @@ -557,7 +543,7 @@ namespace MaterialEditor // Assign the index to the end of history m_undoHistoryIndex = aznumeric_cast(m_undoHistory.size()); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); } m_propertyValuesBeforeEdit.clear(); @@ -584,7 +570,7 @@ namespace MaterialEditor if (!m_saveTriggeredInternally) { AZ_TracePrintf("MaterialDocument", "Material document changed externally: '%s'.\n", m_absolutePath.c_str()); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentExternallyModified, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentExternallyModified, m_id); } m_saveTriggeredInternally = false; } @@ -595,7 +581,7 @@ namespace MaterialEditor if (m_dependentAssetIds.find(asset->GetId()) != m_dependentAssetIds.end()) { AZ_TracePrintf("MaterialDocument", "Material document dependency changed: '%s'.\n", m_absolutePath.c_str()); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentDependencyModified, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentDependencyModified, m_id); } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h index 63d98259ad..d732680b7b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h @@ -18,8 +18,7 @@ #include #include #include - -#include +#include namespace MaterialEditor { @@ -27,7 +26,8 @@ namespace MaterialEditor * MaterialDocument provides an API for modifying and saving material document properties. */ class MaterialDocument - : public MaterialDocumentRequestBus::Handler + : public AtomToolsFramework::AtomToolsDocument + , public MaterialDocumentRequestBus::Handler , private AZ::TickBus::Handler , private AZ::Data::AssetBus::MultiHandler , private AzToolsFramework::AssetSystemBus::Handler @@ -40,22 +40,15 @@ namespace MaterialEditor MaterialDocument(); virtual ~MaterialDocument(); - const AZ::Uuid& GetId() const; - //////////////////////////////////////////////////////////////////////// - // MaterialDocumentRequestBus::Handler implementation - AZStd::string_view GetAbsolutePath() const override; - AZStd::string_view GetRelativePath() const override; - AZ::Data::Asset GetAsset() const override; - AZ::Data::Instance GetInstance() const override; - const AZ::RPI::MaterialSourceData* GetMaterialSourceData() const override; - const AZ::RPI::MaterialTypeSourceData* GetMaterialTypeSourceData() const override; + // AtomToolsFramework::AtomToolsDocument + //////////////////////////////////////////////////////////////////////// const AZStd::any& GetPropertyValue(const AZ::Name& propertyFullName) const override; const AtomToolsFramework::DynamicProperty& GetProperty(const AZ::Name& propertyFullName) const override; bool IsPropertyGroupVisible(const AZ::Name& propertyGroupFullName) const override; void SetPropertyValue(const AZ::Name& propertyFullName, const AZStd::any& value) override; bool Open(AZStd::string_view loadPath) override; - bool Rebuild() override; + bool Reopen() override; bool Save() override; bool SaveAsCopy(AZStd::string_view savePath) override; bool SaveAsChild(AZStd::string_view savePath) override; @@ -71,6 +64,14 @@ namespace MaterialEditor bool EndEdit() override; //////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////// + // MaterialDocumentRequestBus::Handler implementation + AZ::Data::Asset GetAsset() const override; + AZ::Data::Instance GetInstance() const override; + const AZ::RPI::MaterialSourceData* GetMaterialSourceData() const override; + const AZ::RPI::MaterialTypeSourceData* GetMaterialTypeSourceData() const override; + //////////////////////////////////////////////////////////////////////// + private: // Predicate for evaluating properties @@ -130,21 +131,12 @@ namespace MaterialEditor // @return names for the set of properties and groups that have been changed or need update. EditorMaterialFunctorResult RunEditorMaterialFunctors(AZ::RPI::MaterialPropertyFlags dirtyFlags); - // Unique id of this material document - AZ::Uuid m_id = AZ::Uuid::CreateRandom(); - // Underlying material asset AZ::Data::Asset m_materialAsset; // Material instance being edited AZ::Data::Instance m_materialInstance; - // Relative path to the material source file - AZStd::string m_relativePath; - - // Absolute path to the material source file - AZStd::string m_absolutePath; - // Asset used to open document AZ::Data::AssetId m_sourceAssetId; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentModule.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentModule.cpp index 5780cd45c0..c721798cfd 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentModule.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentModule.cpp @@ -7,10 +7,8 @@ */ #include -#include - -#include #include +#include namespace MaterialEditor { diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp index b0d6e35d7f..4823b8c67c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp @@ -18,7 +18,6 @@ namespace MaterialEditor { serializeContext->Class() ->Version(1) - ->Field("showReloadDocumentPrompt", &MaterialDocumentSettings::m_showReloadDocumentPrompt) ->Field("defaultMaterialTypeName", &MaterialDocumentSettings::m_defaultMaterialTypeName) ; @@ -28,7 +27,6 @@ namespace MaterialEditor "MaterialDocumentSettings", "") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialDocumentSettings::m_showReloadDocumentPrompt, "Show Reload Document Prompt", "") ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialDocumentSettings::m_defaultMaterialTypeName, "Default Material Type Name", "") ; } @@ -39,10 +37,9 @@ namespace MaterialEditor behaviorContext->Class("MaterialDocumentSettings") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, "render") + ->Attribute(AZ::Script::Attributes::Module, "materialeditor") ->Constructor() ->Constructor() - ->Property("showReloadDocumentPrompt", BehaviorValueProperty(&MaterialDocumentSettings::m_showReloadDocumentPrompt)) ->Property("defaultMaterialTypeName", BehaviorValueProperty(&MaterialDocumentSettings::m_defaultMaterialTypeName)) ; } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp index e4a3b8235d..9302b5ac5c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp @@ -6,40 +6,17 @@ * */ -#include - -#include #include #include -#include -#include -#include -#include -#include +#include #include #include #include -#include -#include -#include -#include -#include -#include - -AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -#include -#include -#include -#include -AZ_POP_DISABLE_WARNING +#include +#include namespace MaterialEditor { - MaterialDocumentSystemComponent::MaterialDocumentSystemComponent() - { - } - void MaterialDocumentSystemComponent::Reflect(AZ::ReflectContext* context) { MaterialDocumentSettings::Reflect(context); @@ -53,7 +30,7 @@ namespace MaterialEditor { ec->Class("MaterialDocumentSystemComponent", "Tool for editing Atom material files") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("System")) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ; } @@ -61,66 +38,31 @@ namespace MaterialEditor if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->EBus("MaterialDocumentSystemRequestBus") - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) - ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, "materialeditor") - ->Event("CreateDocument", &MaterialDocumentSystemRequestBus::Events::CreateDocument) - ->Event("DestroyDocument", &MaterialDocumentSystemRequestBus::Events::DestroyDocument) - ->Event("OpenDocument", &MaterialDocumentSystemRequestBus::Events::OpenDocument) - ->Event("CreateDocumentFromFile", &MaterialDocumentSystemRequestBus::Events::CreateDocumentFromFile) - ->Event("CloseDocument", &MaterialDocumentSystemRequestBus::Events::CloseDocument) - ->Event("CloseAllDocuments", &MaterialDocumentSystemRequestBus::Events::CloseAllDocuments) - ->Event("CloseAllDocumentsExcept", &MaterialDocumentSystemRequestBus::Events::CloseAllDocumentsExcept) - ->Event("SaveDocument", &MaterialDocumentSystemRequestBus::Events::SaveDocument) - ->Event("SaveDocumentAsCopy", &MaterialDocumentSystemRequestBus::Events::SaveDocumentAsCopy) - ->Event("SaveDocumentAsChild", &MaterialDocumentSystemRequestBus::Events::SaveDocumentAsChild) - ->Event("SaveAllDocuments", &MaterialDocumentSystemRequestBus::Events::SaveAllDocuments) - ; - behaviorContext->EBus("MaterialDocumentRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") ->Attribute(AZ::Script::Attributes::Module, "materialeditor") - ->Event("GetAbsolutePath", &MaterialDocumentRequestBus::Events::GetAbsolutePath) - ->Event("GetRelativePath", &MaterialDocumentRequestBus::Events::GetRelativePath) - ->Event("GetPropertyValue", &MaterialDocumentRequestBus::Events::GetPropertyValue) - ->Event("SetPropertyValue", &MaterialDocumentRequestBus::Events::SetPropertyValue) - ->Event("Open", &MaterialDocumentRequestBus::Events::Open) - ->Event("Rebuild", &MaterialDocumentRequestBus::Events::Rebuild) - ->Event("Close", &MaterialDocumentRequestBus::Events::Close) - ->Event("Save", &MaterialDocumentRequestBus::Events::Save) - ->Event("SaveAsChild", &MaterialDocumentRequestBus::Events::SaveAsChild) - ->Event("SaveAsCopy", &MaterialDocumentRequestBus::Events::SaveAsCopy) - ->Event("IsOpen", &MaterialDocumentRequestBus::Events::IsOpen) - ->Event("IsModified", &MaterialDocumentRequestBus::Events::IsModified) - ->Event("IsSavable", &MaterialDocumentRequestBus::Events::IsSavable) - ->Event("CanUndo", &MaterialDocumentRequestBus::Events::CanUndo) - ->Event("CanRedo", &MaterialDocumentRequestBus::Events::CanRedo) - ->Event("Undo", &MaterialDocumentRequestBus::Events::Undo) - ->Event("Redo", &MaterialDocumentRequestBus::Events::Redo) - ->Event("BeginEdit", &MaterialDocumentRequestBus::Events::BeginEdit) - ->Event("EndEdit", &MaterialDocumentRequestBus::Events::EndEdit) ; } } void MaterialDocumentSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { - required.push_back(AZ_CRC("AssetProcessorToolsConnection", 0x734669bc)); - required.push_back(AZ_CRC("AssetDatabaseService", 0x3abf5601)); - required.push_back(AZ_CRC("PropertyManagerService", 0x63a3d7ad)); - required.push_back(AZ_CRC("RPISystem", 0xf2add773)); + required.push_back(AZ_CRC_CE("AtomToolsDocumentSystemService")); + required.push_back(AZ_CRC_CE("AssetProcessorToolsConnection")); + required.push_back(AZ_CRC_CE("AssetDatabaseService")); + required.push_back(AZ_CRC_CE("PropertyManagerService")); + required.push_back(AZ_CRC_CE("RPISystem")); } void MaterialDocumentSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { - provided.push_back(AZ_CRC("MaterialDocumentSystemService")); + provided.push_back(AZ_CRC_CE("MaterialDocumentSystemService")); } void MaterialDocumentSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { - incompatible.push_back(AZ_CRC("MaterialDocumentSystemService")); + incompatible.push_back(AZ_CRC_CE("MaterialDocumentSystemService")); } void MaterialDocumentSystemComponent::Init() @@ -129,388 +71,15 @@ namespace MaterialEditor void MaterialDocumentSystemComponent::Activate() { - m_documentMap.clear(); - m_settings = AZ::UserSettings::CreateFind(AZ::Crc32("MaterialDocumentSettings"), AZ::UserSettings::CT_GLOBAL); - MaterialDocumentSystemRequestBus::Handler::BusConnect(); - MaterialDocumentNotificationBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( + &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Handler::RegisterDocumentType, + []() + { + return aznew MaterialDocument(); + }); } void MaterialDocumentSystemComponent::Deactivate() { - AZ::TickBus::Handler::BusDisconnect(); - MaterialDocumentNotificationBus::Handler::BusDisconnect(); - MaterialDocumentSystemRequestBus::Handler::BusDisconnect(); - m_documentMap.clear(); - } - - AZ::Uuid MaterialDocumentSystemComponent::CreateDocument() - { - auto document = AZStd::make_unique(); - if (!document) - { - AZ_Error("MaterialDocument", false, "Failed to create new document"); - return AZ::Uuid::CreateNull(); - } - - AZ::Uuid documentId = document->GetId(); - m_documentMap.emplace(documentId, document.release()); - return documentId; - } - - bool MaterialDocumentSystemComponent::DestroyDocument(const AZ::Uuid& documentId) - { - return m_documentMap.erase(documentId) != 0; - } - - void MaterialDocumentSystemComponent::OnDocumentExternallyModified(const AZ::Uuid& documentId) - { - m_documentIdsToReopen.insert(documentId); - if (!AZ::TickBus::Handler::BusIsConnected()) - { - AZ::TickBus::Handler::BusConnect(); - } - } - - void MaterialDocumentSystemComponent::OnDocumentDependencyModified(const AZ::Uuid& documentId) - { - m_documentIdsToRebuild.insert(documentId); - if (!AZ::TickBus::Handler::BusIsConnected()) - { - AZ::TickBus::Handler::BusConnect(); - } - } - - void MaterialDocumentSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) - { - for (const AZ::Uuid& documentId : m_documentIdsToReopen) - { - AZStd::string documentPath; - MaterialDocumentRequestBus::EventResult(documentPath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); - - if (m_settings->m_showReloadDocumentPrompt && - (QMessageBox::question(QApplication::activeWindow(), - QString("Material document was externally modified"), - QString("Would you like to reopen the document:\n%1?").arg(documentPath.c_str()), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)) - { - continue; - } - - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); - - bool openResult = false; - MaterialDocumentRequestBus::EventResult(openResult, documentId, &MaterialDocumentRequestBus::Events::Open, documentPath); - if (!openResult) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Material document could not be opened"), - QString("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseDocument, documentId); - } - } - - for (const AZ::Uuid& documentId : m_documentIdsToRebuild) - { - AZStd::string documentPath; - MaterialDocumentRequestBus::EventResult(documentPath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); - - if (m_settings->m_showReloadDocumentPrompt && - (QMessageBox::question(QApplication::activeWindow(), - QString("Material document dependencies have changed"), - QString("Would you like to update the document with these changes:\n%1?").arg(documentPath.c_str()), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)) - { - continue; - } - - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); - - bool openResult = false; - MaterialDocumentRequestBus::EventResult(openResult, documentId, &MaterialDocumentRequestBus::Events::Rebuild); - if (!openResult) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Material document could not be opened"), - QString("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseDocument, documentId); - } - } - - m_documentIdsToRebuild.clear(); - m_documentIdsToReopen.clear(); - AZ::TickBus::Handler::BusDisconnect(); - } - - AZ::Uuid MaterialDocumentSystemComponent::OpenDocument(AZStd::string_view sourcePath) - { - return OpenDocumentImpl(sourcePath, true); - } - - AZ::Uuid MaterialDocumentSystemComponent::CreateDocumentFromFile(AZStd::string_view sourcePath, AZStd::string_view targetPath) - { - const AZ::Uuid documentId = OpenDocumentImpl(sourcePath, false); - if (documentId.IsNull()) - { - return AZ::Uuid::CreateNull(); - } - - if (!SaveDocumentAsChild(documentId, targetPath)) - { - CloseDocument(documentId); - return AZ::Uuid::CreateNull(); - } - - // Send document open notification after creating new material - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentOpened, documentId); - return documentId; - } - - bool MaterialDocumentSystemComponent::CloseDocument(const AZ::Uuid& documentId) - { - bool isOpen = false; - MaterialDocumentRequestBus::EventResult(isOpen, documentId, &MaterialDocumentRequestBus::Events::IsOpen); - if (!isOpen) - { - // immediately destroy unopened documents - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::DestroyDocument, documentId); - return true; - } - - AZStd::string documentPath; - MaterialDocumentRequestBus::EventResult(documentPath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); - - bool isModified = false; - MaterialDocumentRequestBus::EventResult(isModified, documentId, &MaterialDocumentRequestBus::Events::IsModified); - if (isModified) - { - auto selection = QMessageBox::question(QApplication::activeWindow(), - QString("Material document has unsaved changes"), - QString("Do you want to save changes to\n%1?").arg(documentPath.c_str()), - QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); - if (selection == QMessageBox::Cancel) - { - AZ_TracePrintf("MaterialDocument", "Close document canceled: %s", documentPath.c_str()); - return false; - } - if (selection == QMessageBox::Yes) - { - if (!SaveDocument(documentId)) - { - AZ_Error("MaterialDocument", false, "Close document failed because document was not saved: %s", documentPath.c_str()); - return false; - } - } - } - - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); - - bool closeResult = true; - MaterialDocumentRequestBus::EventResult(closeResult, documentId, &MaterialDocumentRequestBus::Events::Close); - if (!closeResult) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Material document could not be closed"), - QString("Failed to close: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); - return false; - } - - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::DestroyDocument, documentId); - return true; - } - - bool MaterialDocumentSystemComponent::CloseAllDocuments() - { - bool result = true; - auto documentMap = m_documentMap; - for (const auto& documentPair : documentMap) - { - if (!CloseDocument(documentPair.first)) - { - result = false; - } - } - - return result; - } - - bool MaterialDocumentSystemComponent::CloseAllDocumentsExcept(const AZ::Uuid& documentId) - { - bool result = true; - auto documentMap = m_documentMap; - for (const auto& documentPair : documentMap) - { - if (documentPair.first != documentId) - { - if (!CloseDocument(documentPair.first)) - { - result = false; - } - } - } - - return result; - } - - bool MaterialDocumentSystemComponent::SaveDocument(const AZ::Uuid& documentId) - { - AZStd::string saveMaterialPath; - MaterialDocumentRequestBus::EventResult(saveMaterialPath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); - - if (saveMaterialPath.empty() || !AzFramework::StringFunc::Path::Normalize(saveMaterialPath)) - { - return false; - } - - const QFileInfo saveInfo(saveMaterialPath.c_str()); - if (saveInfo.exists() && !saveInfo.isWritable()) - { - QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Material document could not be overwritten:\n%1").arg(saveMaterialPath.c_str())); - return false; - } - - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); - - bool result = false; - MaterialDocumentRequestBus::EventResult(result, documentId, &MaterialDocumentRequestBus::Events::Save); - if (!result) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Material document could not be saved"), - QString("Failed to save: \n%1\n\n%2").arg(saveMaterialPath.c_str()).arg(traceRecorder.GetDump().c_str())); - return false; - } - - return true; - } - - bool MaterialDocumentSystemComponent::SaveDocumentAsCopy(const AZ::Uuid& documentId, AZStd::string_view targetPath) - { - AZStd::string saveMaterialPath = targetPath; - if (saveMaterialPath.empty() || !AzFramework::StringFunc::Path::Normalize(saveMaterialPath)) - { - return false; - } - - const QFileInfo saveInfo(saveMaterialPath.c_str()); - if (saveInfo.exists() && !saveInfo.isWritable()) - { - QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Material document could not be overwritten:\n%1").arg(saveMaterialPath.c_str())); - return false; - } - - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); - - bool result = false; - MaterialDocumentRequestBus::EventResult(result, documentId, &MaterialDocumentRequestBus::Events::SaveAsCopy, saveMaterialPath); - if (!result) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Material document could not be saved"), - QString("Failed to save: \n%1\n\n%2").arg(saveMaterialPath.c_str()).arg(traceRecorder.GetDump().c_str())); - return false; - } - - return true; - } - - bool MaterialDocumentSystemComponent::SaveDocumentAsChild(const AZ::Uuid& documentId, AZStd::string_view targetPath) - { - AZStd::string saveMaterialPath = targetPath; - if (saveMaterialPath.empty() || !AzFramework::StringFunc::Path::Normalize(saveMaterialPath)) - { - return false; - } - - const QFileInfo saveInfo(saveMaterialPath.c_str()); - if (saveInfo.exists() && !saveInfo.isWritable()) - { - QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Material document could not be overwritten:\n%1").arg(saveMaterialPath.c_str())); - return false; - } - - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); - - bool result = false; - MaterialDocumentRequestBus::EventResult(result, documentId, &MaterialDocumentRequestBus::Events::SaveAsChild, saveMaterialPath); - if (!result) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Material document could not be saved"), - QString("Failed to save: \n%1\n\n%2").arg(saveMaterialPath.c_str()).arg(traceRecorder.GetDump().c_str())); - return false; - } - - return true; - } - - bool MaterialDocumentSystemComponent::SaveAllDocuments() - { - bool result = true; - for (const auto& documentPair : m_documentMap) - { - if (!SaveDocument(documentPair.first)) - { - result = false; - } - } - - return result; - } - - AZ::Uuid MaterialDocumentSystemComponent::OpenDocumentImpl(AZStd::string_view sourcePath, bool checkIfAlreadyOpen) - { - AZStd::string requestedPath = sourcePath; - if (requestedPath.empty()) - { - return AZ::Uuid::CreateNull(); - } - - if (!AzFramework::StringFunc::Path::Normalize(requestedPath)) - { - QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Material document path is invalid:\n%1").arg(requestedPath.c_str())); - return AZ::Uuid::CreateNull(); - } - - // Determine if the file is already open and select it - if (checkIfAlreadyOpen) - { - for (const auto& documentPair : m_documentMap) - { - AZStd::string openMaterialPath; - MaterialDocumentRequestBus::EventResult(openMaterialPath, documentPair.first, &MaterialDocumentRequestBus::Events::GetAbsolutePath); - if (openMaterialPath == requestedPath) - { - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentOpened, documentPair.first); - return documentPair.first; - } - } - } - - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); - - AZ::Uuid documentId = AZ::Uuid::CreateNull(); - MaterialDocumentSystemRequestBus::BroadcastResult(documentId, &MaterialDocumentSystemRequestBus::Events::CreateDocument); - if (documentId.IsNull()) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Material document could not be created"), - QString("Failed to create: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); - return AZ::Uuid::CreateNull(); - } - - traceRecorder.GetDump().clear(); - - bool openResult = false; - MaterialDocumentRequestBus::EventResult(openResult, documentId, &MaterialDocumentRequestBus::Events::Open, requestedPath); - if (!openResult) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Material document could not be opened"), - QString("Failed to open: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::DestroyDocument, documentId); - return AZ::Uuid::CreateNull(); - } - - return documentId; } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h index 3b20f40b4f..af19956088 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h @@ -9,34 +9,17 @@ #pragma once #include -#include -#include -#include - -#include -#include -#include -#include -#include - -AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -#include -AZ_POP_DISABLE_WARNING namespace MaterialEditor { - //! MaterialDocumentSystemComponent is the central component of the Material Editor Core gem + //! MaterialDocumentSystemComponent class MaterialDocumentSystemComponent : public AZ::Component - , private AZ::TickBus::Handler - , private MaterialDocumentNotificationBus::Handler - , private MaterialDocumentSystemRequestBus::Handler { public: - AZ_COMPONENT(MaterialDocumentSystemComponent, "{58ABE0AE-2710-41E2-ADFD-E2D67407427D}"); + AZ_COMPONENT(MaterialDocumentSystemComponent, "{E011DA51-855D-45FA-87A3-1C1CD6379091}"); - MaterialDocumentSystemComponent(); + MaterialDocumentSystemComponent() = default; ~MaterialDocumentSystemComponent() = default; MaterialDocumentSystemComponent(const MaterialDocumentSystemComponent&) = delete; MaterialDocumentSystemComponent& operator=(const MaterialDocumentSystemComponent&) = delete; @@ -54,39 +37,5 @@ namespace MaterialEditor void Activate() override; void Deactivate() override; //////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // MaterialDocumentNotificationBus::Handler overrides... - void OnDocumentDependencyModified(const AZ::Uuid& documentId) override; - void OnDocumentExternallyModified(const AZ::Uuid& documentId) override; - ////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // AZ::TickBus::Handler overrides... - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // MaterialDocumentSystemRequestBus::Handler overrides... - AZ::Uuid CreateDocument() override; - bool DestroyDocument(const AZ::Uuid& documentId) override; - AZ::Uuid OpenDocument(AZStd::string_view sourcePath) override; - AZ::Uuid CreateDocumentFromFile(AZStd::string_view sourcePath, AZStd::string_view targetPath) override; - bool CloseDocument(const AZ::Uuid& documentId) override; - bool CloseAllDocuments() override; - bool CloseAllDocumentsExcept(const AZ::Uuid& documentId) override; - bool SaveDocument(const AZ::Uuid& documentId) override; - bool SaveDocumentAsCopy(const AZ::Uuid& documentId, AZStd::string_view targetPath) override; - bool SaveDocumentAsChild(const AZ::Uuid& documentId, AZStd::string_view targetPath) override; - bool SaveAllDocuments() override; - //////////////////////////////////////////////////////////////////////// - - AZ::Uuid OpenDocumentImpl(AZStd::string_view sourcePath, bool checkIfAlreadyOpen); - - AZStd::intrusive_ptr m_settings; - AZStd::unordered_map> m_documentMap; - AZStd::unordered_set m_documentIdsToRebuild; - AZStd::unordered_set m_documentIdsToReopen; - const size_t m_maxMessageBoxLineCount = 15; }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index bdd9e6fbaf..cec882cabb 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -7,9 +7,9 @@ */ #include -#include #include #include +#include #include #include #include @@ -68,7 +68,7 @@ namespace MaterialEditor const AZStd::string openDocumentPath = commandLine.GetMiscValue(openDocumentIndex); AZ_Printf(GetBuildTargetName().c_str(), "Opening document: %s", openDocumentPath.c_str()); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); } Base::ProcessCommandLine(commandLine); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h index da691feff7..e91bce48f0 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h @@ -8,8 +8,8 @@ #pragma once -#include #include +#include namespace MaterialEditor { diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp index 23e37b2f7c..f98cdce91b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp @@ -243,7 +243,7 @@ namespace MaterialEditor OnFieldOfViewChanged(viewportSettings->m_fieldOfView); OnDisplayMapperOperationTypeChanged(viewportSettings->m_displayMapperOperationType); - MaterialDocumentNotificationBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(); MaterialViewportNotificationBus::Handler::BusConnect(); AZ::TickBus::Handler::BusConnect(); AZ::TransformNotificationBus::MultiHandler::BusConnect(m_cameraEntity->GetId()); @@ -255,7 +255,7 @@ namespace MaterialEditor AzFramework::WindowSystemRequestBus::Handler::BusDisconnect(); AZ::TransformNotificationBus::MultiHandler::BusDisconnect(); AZ::TickBus::Handler::BusDisconnect(); - MaterialDocumentNotificationBus::Handler::BusDisconnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusDisconnect(); MaterialViewportNotificationBus::Handler::BusDisconnect(); AZ::Data::AssetBus::Handler::BusDisconnect(); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.h index 4efaf51d01..240d66fd43 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.h @@ -8,16 +8,14 @@ #pragma once -#include -#include -#include - -#include -#include #include #include +#include #include - +#include +#include +#include +#include #include #include @@ -45,7 +43,7 @@ namespace MaterialEditor class MaterialViewportRenderer : public AZ::Data::AssetBus::Handler , public AZ::TickBus::Handler - , public MaterialDocumentNotificationBus::Handler + , public AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler , public MaterialViewportNotificationBus::Handler , public AZ::TransformNotificationBus::MultiHandler , public AzFramework::WindowSystemRequestBus::Handler @@ -60,7 +58,7 @@ namespace MaterialEditor private: - // MaterialDocumentNotificationBus::Handler interface overrides... + // AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler interface overrides... void OnDocumentOpened(const AZ::Uuid& documentId) override; // MaterialViewportNotificationBus::Handler interface overrides... diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportSettings.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportSettings.cpp index 52f277d984..c2c35119c2 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportSettings.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportSettings.cpp @@ -54,7 +54,7 @@ namespace MaterialEditor behaviorContext->Class("MaterialViewportSettings") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, "render") + ->Attribute(AZ::Script::Attributes::Module, "materialeditor") ->Constructor() ->Constructor() ->Property("enableGrid", BehaviorValueProperty(&MaterialViewportSettings::m_enableGrid)) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialBrowserWidget.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialBrowserWidget.cpp index 20098f461b..4df76b4dac 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialBrowserWidget.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialBrowserWidget.cpp @@ -7,9 +7,12 @@ */ #include -#include +#include +#include #include #include +#include +#include #include #include #include @@ -18,9 +21,8 @@ #include #include #include - -#include -#include +#include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include @@ -91,14 +93,14 @@ namespace MaterialEditor } }); - MaterialDocumentNotificationBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(); } MaterialBrowserWidget::~MaterialBrowserWidget() { // Maintains the tree expansion state between runs m_ui->m_assetBrowserTreeViewWidget->SaveState(); - MaterialDocumentNotificationBus::Handler::BusDisconnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusDisconnect(); AZ::TickBus::Handler::BusDisconnect(); } @@ -144,13 +146,13 @@ namespace MaterialEditor { if (entry) { - if (AzFramework::StringFunc::Path::IsExtension(entry->GetFullPath().c_str(), MaterialExtension)) + if (AzFramework::StringFunc::Path::IsExtension(entry->GetFullPath().c_str(), AZ::RPI::MaterialSourceData::Extension)) { - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::OpenDocument, entry->GetFullPath()); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, entry->GetFullPath()); } - else if (AzFramework::StringFunc::Path::IsExtension(entry->GetFullPath().c_str(), MaterialTypeExtension)) + else if (AzFramework::StringFunc::Path::IsExtension(entry->GetFullPath().c_str(), AZ::RPI::MaterialTypeSourceData::Extension)) { - //ignore MaterialTypeExtension + //ignore AZ::RPI::MaterialTypeSourceData::Extension } else { @@ -163,7 +165,7 @@ namespace MaterialEditor void MaterialBrowserWidget::OnDocumentOpened(const AZ::Uuid& documentId) { AZStd::string absolutePath; - MaterialDocumentRequestBus::EventResult(absolutePath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(absolutePath, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetAbsolutePath); if (!absolutePath.empty()) { // Selecting a new asset in the browser is not guaranteed to happen immediately. @@ -230,4 +232,4 @@ namespace MaterialEditor } // namespace MaterialEditor -#include +#include diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialBrowserWidget.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialBrowserWidget.h index 2ded270af0..24a244bc3c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialBrowserWidget.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialBrowserWidget.h @@ -9,15 +9,15 @@ #pragma once #if !defined(Q_MOC_RUN) -#include +#include #include #include #include #include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include #include +#include AZ_POP_DISABLE_WARNING #endif @@ -45,7 +45,7 @@ namespace MaterialEditor class MaterialBrowserWidget : public QWidget , protected AZ::TickBus::Handler - , protected MaterialDocumentNotificationBus::Handler + , protected AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler { Q_OBJECT public: @@ -56,7 +56,7 @@ namespace MaterialEditor AzToolsFramework::AssetBrowser::FilterConstType CreateFilter() const; void OpenSelectedEntries(); - // MaterialDocumentNotificationBus::Handler implementation + // AtomToolsDocumentNotificationBus::Handler implementation void OnDocumentOpened(const AZ::Uuid& documentId) override; // AZ::TickBus::Handler diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorBrowserInteractions.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorBrowserInteractions.cpp index b957c550e6..3440d9c316 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorBrowserInteractions.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorBrowserInteractions.cpp @@ -6,32 +6,28 @@ * */ -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - #include -#include - -#include -#include - -#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include namespace MaterialEditor { @@ -66,11 +62,11 @@ namespace MaterialEditor if (entry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Source) { const auto source = azalias_cast(entry); - if (AzFramework::StringFunc::Path::IsExtension(entry->GetFullPath().c_str(), MaterialExtension)) + if (AzFramework::StringFunc::Path::IsExtension(entry->GetFullPath().c_str(), AZ::RPI::MaterialSourceData::Extension)) { AddContextMenuActionsForMaterialSource(caller, menu, source); } - else if (AzFramework::StringFunc::Path::IsExtension(entry->GetFullPath().c_str(), MaterialTypeExtension)) + else if (AzFramework::StringFunc::Path::IsExtension(entry->GetFullPath().c_str(), AZ::RPI::MaterialTypeSourceData::Extension)) { AddContextMenuActionsForMaterialTypeSource(caller, menu, source); } @@ -115,7 +111,7 @@ namespace MaterialEditor AZ_CORRECT_FILESYSTEM_SEPARATOR + "untitled." + AZ::RPI::MaterialSourceData::Extension).absoluteFilePath(); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CreateDocumentFromFile, + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile, entry->GetFullPath(), AtomToolsFramework::GetSaveFileInfo(defaultPath).absoluteFilePath().toUtf8().constData()); }); @@ -157,7 +153,7 @@ namespace MaterialEditor { menu->addAction("Open", [entry]() { - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::OpenDocument, entry->GetFullPath()); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, entry->GetFullPath()); }); menu->addAction("Duplicate...", [entry, caller]() @@ -191,7 +187,7 @@ namespace MaterialEditor AZ_CORRECT_FILESYSTEM_SEPARATOR + "untitled." + AZ::RPI::MaterialSourceData::Extension).absoluteFilePath(); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CreateDocumentFromFile, + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile, entry->GetFullPath(), AtomToolsFramework::GetSaveFileInfo(defaultPath).absoluteFilePath().toUtf8().constData()); }); @@ -258,7 +254,7 @@ namespace MaterialEditor !createDialog.m_materialFileInfo.absoluteFilePath().isEmpty() && !createDialog.m_materialTypeFileInfo.absoluteFilePath().isEmpty()) { - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CreateDocumentFromFile, + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile, createDialog.m_materialTypeFileInfo.absoluteFilePath().toUtf8().constData(), createDialog.m_materialFileInfo.absoluteFilePath().toUtf8().constData()); } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 1bd6067116..48f2dc3441 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -6,7 +6,11 @@ * */ +#include #include +#include +#include +#include #include #include #include @@ -15,11 +19,6 @@ #include #include #include - -#include -#include -#include - #include #include #include @@ -106,13 +105,13 @@ namespace MaterialEditor m_advancedDockManager->restoreState(windowState); } - MaterialDocumentNotificationBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(); OnDocumentOpened(AZ::Uuid::CreateNull()); } MaterialEditorWindow::~MaterialEditorWindow() { - MaterialDocumentNotificationBus::Handler::BusDisconnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusDisconnect(); } @@ -150,7 +149,7 @@ namespace MaterialEditor void MaterialEditorWindow::closeEvent(QCloseEvent* closeEvent) { bool didClose = true; - MaterialDocumentSystemRequestBus::BroadcastResult(didClose, &MaterialDocumentSystemRequestBus::Events::CloseAllDocuments); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(didClose, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseAllDocuments); if (!didClose) { closeEvent->ignore(); @@ -171,17 +170,17 @@ namespace MaterialEditor void MaterialEditorWindow::OnDocumentOpened(const AZ::Uuid& documentId) { bool isOpen = false; - MaterialDocumentRequestBus::EventResult(isOpen, documentId, &MaterialDocumentRequestBus::Events::IsOpen); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isOpen, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsOpen); bool isSavable = false; - MaterialDocumentRequestBus::EventResult(isSavable, documentId, &MaterialDocumentRequestBus::Events::IsSavable); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isSavable, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsSavable); bool isModified = false; - MaterialDocumentRequestBus::EventResult(isModified, documentId, &MaterialDocumentRequestBus::Events::IsModified); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isModified, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsModified); bool canUndo = false; - MaterialDocumentRequestBus::EventResult(canUndo, documentId, &MaterialDocumentRequestBus::Events::CanUndo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(canUndo, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::CanUndo); bool canRedo = false; - MaterialDocumentRequestBus::EventResult(canRedo, documentId, &MaterialDocumentRequestBus::Events::CanRedo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(canRedo, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::CanRedo); AZStd::string absolutePath; - MaterialDocumentRequestBus::EventResult(absolutePath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(absolutePath, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetAbsolutePath); AZStd::string filename; AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); @@ -238,7 +237,7 @@ namespace MaterialEditor const QString documentPath = GetDocumentPath(documentId); if (!documentPath.isEmpty()) { - const QString status = QString("Document closed: %1").arg(documentPath); + const QString status = QString("Document opened: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } } @@ -255,9 +254,9 @@ namespace MaterialEditor void MaterialEditorWindow::OnDocumentModified(const AZ::Uuid& documentId) { bool isModified = false; - MaterialDocumentRequestBus::EventResult(isModified, documentId, &MaterialDocumentRequestBus::Events::IsModified); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isModified, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsModified); AZStd::string absolutePath; - MaterialDocumentRequestBus::EventResult(absolutePath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(absolutePath, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetAbsolutePath); AZStd::string filename; AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); @@ -268,9 +267,9 @@ namespace MaterialEditor if (documentId == GetDocumentIdFromTab(m_tabWidget->currentIndex())) { bool canUndo = false; - MaterialDocumentRequestBus::EventResult(canUndo, documentId, &MaterialDocumentRequestBus::Events::CanUndo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(canUndo, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::CanUndo); bool canRedo = false; - MaterialDocumentRequestBus::EventResult(canRedo, documentId, &MaterialDocumentRequestBus::Events::CanRedo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(canRedo, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::CanRedo); m_actionUndo->setEnabled(canUndo); m_actionRedo->setEnabled(canRedo); } @@ -279,15 +278,15 @@ namespace MaterialEditor void MaterialEditorWindow::OnDocumentSaved(const AZ::Uuid& documentId) { bool isModified = false; - MaterialDocumentRequestBus::EventResult(isModified, documentId, &MaterialDocumentRequestBus::Events::IsModified); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isModified, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsModified); AZStd::string absolutePath; - MaterialDocumentRequestBus::EventResult(absolutePath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(absolutePath, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetAbsolutePath); AZStd::string filename; AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document closed: %1").arg(documentPath); + const QString status = QString("Document saved: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } @@ -306,7 +305,7 @@ namespace MaterialEditor !createDialog.m_materialFileInfo.absoluteFilePath().isEmpty() && !createDialog.m_materialTypeFileInfo.absoluteFilePath().isEmpty()) { - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CreateDocumentFromFile, + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile, createDialog.m_materialTypeFileInfo.absoluteFilePath().toUtf8().constData(), createDialog.m_materialFileInfo.absoluteFilePath().toUtf8().constData()); } @@ -317,7 +316,7 @@ namespace MaterialEditor const AZStd::string filePath = AtomToolsFramework::GetOpenFileInfo(assetTypes).absoluteFilePath().toUtf8().constData(); if (!filePath.empty()) { - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::OpenDocument, filePath); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, filePath); } }, QKeySequence::Open); @@ -328,11 +327,11 @@ namespace MaterialEditor m_actionSave = m_menuFile->addAction("&Save", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); bool result = false; - MaterialDocumentSystemRequestBus::BroadcastResult(result, &MaterialDocumentSystemRequestBus::Events::SaveDocument, documentId); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveDocument, documentId); if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to save document: %1").arg(documentPath); + const QString status = QString("Document save failed: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Save); @@ -342,11 +341,11 @@ namespace MaterialEditor const QString documentPath = GetDocumentPath(documentId); bool result = false; - MaterialDocumentSystemRequestBus::BroadcastResult(result, &MaterialDocumentSystemRequestBus::Events::SaveDocumentAsCopy, + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveDocumentAsCopy, documentId, AtomToolsFramework::GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { - const QString status = QString("Failed to save document: %1").arg(documentPath); + const QString status = QString("Document save failed: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::SaveAs); @@ -356,21 +355,21 @@ namespace MaterialEditor const QString documentPath = GetDocumentPath(documentId); bool result = false; - MaterialDocumentSystemRequestBus::BroadcastResult(result, &MaterialDocumentSystemRequestBus::Events::SaveDocumentAsChild, + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveDocumentAsChild, documentId, AtomToolsFramework::GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { - const QString status = QString("Failed to save document: %1").arg(documentPath); + const QString status = QString("Document save failed: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }); m_actionSaveAll = m_menuFile->addAction("Save A&ll", [this]() { bool result = false; - MaterialDocumentSystemRequestBus::BroadcastResult(result, &MaterialDocumentSystemRequestBus::Events::SaveAllDocuments); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveAllDocuments); if (!result) { - const QString status = QString("Failed to save documents."); + const QString status = QString("Document save all failed."); m_statusMessage->setText(QString("%1").arg(status)); } }); @@ -379,16 +378,16 @@ namespace MaterialEditor m_actionClose = m_menuFile->addAction("&Close", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseDocument, documentId); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); }, QKeySequence::Close); m_actionCloseAll = m_menuFile->addAction("Close All", [this]() { - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseAllDocuments); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseAllDocuments); }); m_actionCloseOthers = m_menuFile->addAction("Close Others", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseAllDocumentsExcept, documentId); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseAllDocumentsExcept, documentId); }); m_menuFile->addSeparator(); @@ -412,11 +411,11 @@ namespace MaterialEditor m_actionUndo = m_menuEdit->addAction("&Undo", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); bool result = false; - MaterialDocumentRequestBus::EventResult(result, documentId, &MaterialDocumentRequestBus::Events::Undo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::Undo); if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to perform undo on document: %1").arg(documentPath); + const QString status = QString("Document undo failed: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Undo); @@ -424,11 +423,11 @@ namespace MaterialEditor m_actionRedo = m_menuEdit->addAction("&Redo", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); bool result = false; - MaterialDocumentRequestBus::EventResult(result, documentId, &MaterialDocumentRequestBus::Events::Redo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::Redo); if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to perform redo on document: %1").arg(documentPath); + const QString status = QString("Document redo failed: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Redo); @@ -501,19 +500,19 @@ namespace MaterialEditor // This should automatically clear the active document connect(m_tabWidget, &QTabWidget::currentChanged, this, [this](int tabIndex) { const AZ::Uuid documentId = GetDocumentIdFromTab(tabIndex); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentOpened, documentId); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); }); connect(m_tabWidget, &QTabWidget::tabCloseRequested, this, [this](int tabIndex) { const AZ::Uuid documentId = GetDocumentIdFromTab(tabIndex); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseDocument, documentId); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); }); } QString MaterialEditorWindow::GetDocumentPath(const AZ::Uuid& documentId) const { AZStd::string absolutePath; - MaterialDocumentRequestBus::EventResult(absolutePath, documentId, &MaterialDocumentRequestBus::Handler::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(absolutePath, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Handler::GetAbsolutePath); return absolutePath.c_str(); } @@ -529,15 +528,15 @@ namespace MaterialEditor const QString selectActionName = (currentTabIndex == clickedTabIndex) ? "Select in Browser" : "Select"; tabMenu.addAction(selectActionName, [this, clickedTabIndex]() { const AZ::Uuid documentId = GetDocumentIdFromTab(clickedTabIndex); - MaterialDocumentNotificationBus::Broadcast(&MaterialDocumentNotificationBus::Events::OnDocumentOpened, documentId); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); }); tabMenu.addAction("Close", [this, clickedTabIndex]() { const AZ::Uuid documentId = GetDocumentIdFromTab(clickedTabIndex); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseDocument, documentId); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); }); auto closeOthersAction = tabMenu.addAction("Close Others", [this, clickedTabIndex]() { const AZ::Uuid documentId = GetDocumentIdFromTab(clickedTabIndex); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseAllDocumentsExcept, documentId); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseAllDocumentsExcept, documentId); }); closeOthersAction->setEnabled(tabBar->count() > 1); tabMenu.exec(QCursor::pos()); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index 43151b9c03..b7d0cbf8da 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -9,7 +9,7 @@ #pragma once #if !defined(Q_MOC_RUN) -#include +#include #include #include @@ -30,7 +30,7 @@ namespace MaterialEditor */ class MaterialEditorWindow : public AtomToolsFramework::AtomToolsMainWindow - , private MaterialDocumentNotificationBus::Handler + , private AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler { Q_OBJECT public: @@ -46,7 +46,7 @@ namespace MaterialEditor void LockViewportRenderTargetSize(uint32_t width, uint32_t height) override; void UnlockViewportRenderTargetSize() override; - // MaterialDocumentNotificationBus::Handler overrides... + // AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler overrides... void OnDocumentOpened(const AZ::Uuid& documentId) override; void OnDocumentClosed(const AZ::Uuid& documentId) override; void OnDocumentModified(const AZ::Uuid& documentId) override; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp index 62a1b207de..71c71e8b75 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp @@ -37,7 +37,7 @@ namespace MaterialEditor behaviorContext->Class("MaterialEditorWindowSettings") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, "render") + ->Attribute(AZ::Script::Attributes::Module, "materialeditor") ->Constructor() ->Constructor() ; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp index ccf07c2136..28d7d3d3f5 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp @@ -6,17 +6,15 @@ * */ +#include #include #include #include #include - -#include - +#include #include #include #include - #include namespace MaterialEditor @@ -27,12 +25,12 @@ namespace MaterialEditor m_windowSettings = AZ::UserSettings::CreateFind( AZ::Crc32("MaterialEditorWindowSettings"), AZ::UserSettings::CT_GLOBAL); - MaterialDocumentNotificationBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(); } MaterialInspector::~MaterialInspector() { - MaterialDocumentNotificationBus::Handler::BusDisconnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusDisconnect(); AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); } @@ -69,9 +67,9 @@ namespace MaterialEditor m_documentId = documentId; bool isOpen = false; - MaterialDocumentRequestBus::EventResult(isOpen, m_documentId, &MaterialDocumentRequestBus::Events::IsOpen); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isOpen, m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsOpen); - MaterialDocumentRequestBus::EventResult(m_documentPath, m_documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(m_documentPath, m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetAbsolutePath); if (!m_documentId.IsNull() && isOpen) { @@ -113,13 +111,13 @@ namespace MaterialEditor auto& group = m_groups[groupNameId]; AtomToolsFramework::DynamicProperty property; - MaterialDocumentRequestBus::EventResult( - property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::Name("overview.materialType")); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult( + property, m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetProperty, AZ::Name("overview.materialType")); group.m_properties.push_back(property); property = {}; - MaterialDocumentRequestBus::EventResult( - property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::Name("overview.parentMaterial")); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult( + property, m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetProperty, AZ::Name("overview.parentMaterial")); group.m_properties.push_back(property); // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties @@ -145,8 +143,8 @@ namespace MaterialEditor for (const auto& uvNamePair : uvNameMap) { AtomToolsFramework::DynamicProperty property; - MaterialDocumentRequestBus::EventResult( - property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult( + property, m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetProperty, AZ::RPI::MaterialPropertyId(groupNameId, uvNamePair.m_shaderInput.ToString()).GetFullName()); group.m_properties.push_back(property); @@ -182,8 +180,8 @@ namespace MaterialEditor for (const auto& propertyDefinition : propertyListItr->second) { AtomToolsFramework::DynamicProperty property; - MaterialDocumentRequestBus::EventResult( - property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult( + property, m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetProperty, AZ::RPI::MaterialPropertyId(groupNameId, propertyDefinition.m_nameId).GetFullName()); group.m_properties.push_back(property); } @@ -196,8 +194,8 @@ namespace MaterialEditor AddGroup(groupNameId, groupDisplayName, groupDescription, propertyGroupWidget); bool isGroupVisible = false; - MaterialDocumentRequestBus::EventResult( - isGroupVisible, m_documentId, &MaterialDocumentRequestBus::Events::IsPropertyGroupVisible, AZ::Name{groupNameId}); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult( + isGroupVisible, m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsPropertyGroupVisible, AZ::Name{groupNameId}); SetGroupVisible(groupNameId, isGroupVisible); } } @@ -264,7 +262,7 @@ namespace MaterialEditor if (m_activeProperty != property) { m_activeProperty = property; - MaterialDocumentRequestBus::Event(m_documentId, &MaterialDocumentRequestBus::Events::BeginEdit); + AtomToolsFramework::AtomToolsDocumentRequestBus::Event(m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::BeginEdit); } } } @@ -276,8 +274,8 @@ namespace MaterialEditor { if (m_activeProperty == property) { - MaterialDocumentRequestBus::Event( - m_documentId, &MaterialDocumentRequestBus::Events::SetPropertyValue, property->GetId(), property->GetValue()); + AtomToolsFramework::AtomToolsDocumentRequestBus::Event( + m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::SetPropertyValue, property->GetId(), property->GetValue()); } } } @@ -292,10 +290,10 @@ namespace MaterialEditor { if (m_activeProperty == property) { - MaterialDocumentRequestBus::Event( - m_documentId, &MaterialDocumentRequestBus::Events::SetPropertyValue, property->GetId(), property->GetValue()); + AtomToolsFramework::AtomToolsDocumentRequestBus::Event( + m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::SetPropertyValue, property->GetId(), property->GetValue()); - MaterialDocumentRequestBus::Event(m_documentId, &MaterialDocumentRequestBus::Events::EndEdit); + AtomToolsFramework::AtomToolsDocumentRequestBus::Event(m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::EndEdit); m_activeProperty = nullptr; } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h index ccef72ea3f..845a8cb0f7 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h @@ -9,14 +9,12 @@ #pragma once #if !defined(Q_MOC_RUN) -#include -#include - +#include +#include #include #include - -#include -#include +#include +#include #endif namespace MaterialEditor @@ -25,7 +23,7 @@ namespace MaterialEditor //! The settings can be divided into cards, with each one showing a subset of properties. class MaterialInspector : public AtomToolsFramework::InspectorWidget - , public MaterialDocumentNotificationBus::Handler + , public AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler , public AzToolsFramework::IPropertyEditorNotify { Q_OBJECT @@ -52,7 +50,7 @@ namespace MaterialEditor void AddUvNamesGroup(); void AddPropertiesGroup(); - // MaterialDocumentNotificationBus::Handler implementation + // AtomToolsDocumentNotificationBus::Handler implementation void OnDocumentOpened(const AZ::Uuid& documentId) override; void OnDocumentPropertyValueModified(const AZ::Uuid& documentId, const AtomToolsFramework::DynamicProperty& property) override; void OnDocumentPropertyConfigModified(const AZ::Uuid& documentId, const AtomToolsFramework::DynamicProperty& property) override; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.cpp index 22a85d84a7..c7d4b195a3 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.cpp @@ -15,7 +15,9 @@ namespace MaterialEditor : AtomToolsFramework::InspectorWidget(parent) { m_documentSettings = - AZ::UserSettings::CreateFind(AZ::Crc32("MaterialDocumentSettings"), AZ::UserSettings::CT_GLOBAL); + AZ::UserSettings::CreateFind(AZ_CRC_CE("MaterialDocumentSettings"), AZ::UserSettings::CT_GLOBAL); + m_documentSystemSettings = AZ::UserSettings::CreateFind( + AZ_CRC_CE("AtomToolsDocumentSystemSettings"), AZ::UserSettings::CT_GLOBAL); } SettingsWidget::~SettingsWidget() @@ -26,23 +28,37 @@ namespace MaterialEditor void SettingsWidget::Populate() { AddGroupsBegin(); - AddDocumentGroup(); + AddDocumentSystemSettingsGroup(); + AddDocumentSettingsGroup(); AddGroupsEnd(); } - void SettingsWidget::AddDocumentGroup() + void SettingsWidget::AddDocumentSettingsGroup() { const AZStd::string groupNameId = "documentSettings"; const AZStd::string groupDisplayName = "Document Settings"; const AZStd::string groupDescription = "Document Settings"; - const AZ::Crc32 saveStateKey(AZStd::string::format("SettingsWidget::DocumentGroup")); + const AZ::Crc32 saveStateKey(AZStd::string::format("SettingsWidget::DocumentSettingsGroup")); AddGroup( groupNameId, groupDisplayName, groupDescription, new AtomToolsFramework::InspectorPropertyGroupWidget( m_documentSettings.get(), nullptr, m_documentSettings->TYPEINFO_Uuid(), this, this, saveStateKey)); } + void SettingsWidget::AddDocumentSystemSettingsGroup() + { + const AZStd::string groupNameId = "documentSystemSettings"; + const AZStd::string groupDisplayName = "Document System Settings"; + const AZStd::string groupDescription = "Document System Settings"; + + const AZ::Crc32 saveStateKey(AZStd::string::format("SettingsWidget::DocumentSystemSettingsGroup")); + AddGroup( + groupNameId, groupDisplayName, groupDescription, + new AtomToolsFramework::InspectorPropertyGroupWidget( + m_documentSystemSettings.get(), nullptr, m_documentSystemSettings->TYPEINFO_Uuid(), this, this, saveStateKey)); + } + void SettingsWidget::Reset() { AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.h index 56fc7fbebb..fea98eeda1 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.h @@ -10,6 +10,7 @@ #if !defined(Q_MOC_RUN) #include +#include #include #include #endif @@ -31,7 +32,8 @@ namespace MaterialEditor void Populate(); private: - void AddDocumentGroup(); + void AddDocumentSettingsGroup(); + void AddDocumentSystemSettingsGroup(); // AtomToolsFramework::InspectorRequestBus::Handler overrides... void Reset() override; @@ -46,5 +48,6 @@ namespace MaterialEditor void PropertySelectionChanged(AzToolsFramework::InstanceDataNode*, bool) override {} AZStd::intrusive_ptr m_documentSettings; + AZStd::intrusive_ptr m_documentSystemSettings; }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/materialeditordocument_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditordocument_files.cmake index 0c657361f1..d86dd03749 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditordocument_files.cmake +++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditordocument_files.cmake @@ -8,8 +8,6 @@ set(FILES Include/Atom/Document/MaterialDocumentModule.h - Include/Atom/Document/MaterialDocumentSystemRequestBus.h - Include/Atom/Document/MaterialDocumentNotificationBus.h Include/Atom/Document/MaterialDocumentRequestBus.h Include/Atom/Document/MaterialDocumentSettings.h Source/Document/MaterialDocumentModule.cpp diff --git a/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py b/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py index 2116a3de6c..6708553e20 100755 --- a/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py +++ b/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py @@ -93,11 +93,11 @@ def ToRadians(degrees): return 3.14159 * degrees / 180.0; def OpenMaterial(filename): - documentId = azlmbr.materialeditor.MaterialDocumentSystemRequestBus(azlmbr.bus.Broadcast, 'OpenDocument', os.path.join(g_materialTestFolder, filename)) + documentId = azlmbr.atomtools.AtomToolsDocumentSystemRequestBus(azlmbr.bus.Broadcast, 'OpenDocument', os.path.join(g_materialTestFolder, filename)) return documentId def CloseMaterial(documentId): - azlmbr.materialeditor.MaterialDocumentSystemRequestBus(azlmbr.bus.Broadcast, 'CloseDocument', documentId) + azlmbr.atomtools.AtomToolsDocumentSystemRequestBus(azlmbr.bus.Broadcast, 'CloseDocument', documentId) def SelectLightingPreset(presetName): azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, 'SelectLightingPresetByName', presetName) diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Document/ShaderManagementConsoleDocumentNotificationBus.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Document/ShaderManagementConsoleDocumentNotificationBus.h deleted file mode 100644 index e497b2bc2f..0000000000 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Document/ShaderManagementConsoleDocumentNotificationBus.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include -#include - -namespace ShaderManagementConsole -{ - class ShaderManagementConsoleDocumentNotifications - : public AZ::EBusTraits - { - public: - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - - //! Signal that a document was created - //! @param documentId unique id of document for which the notification is sent - virtual void OnDocumentCreated([[maybe_unused]] const AZ::Uuid& documentId) {} - - //! Signal that a document was destroyed - //! @param documentId unique id of document for which the notification is sent - virtual void OnDocumentDestroyed([[maybe_unused]] const AZ::Uuid& documentId) {} - - //! Signal that a document was opened - //! @param documentId unique id of document for which the notification is sent - virtual void OnDocumentOpened([[maybe_unused]] const AZ::Uuid& documentId) {} - - //! Signal that a document was closed - //! @param documentId unique id of document for which the notification is sent - virtual void OnDocumentClosed([[maybe_unused]] const AZ::Uuid& documentId) {} - - //! Signal that a document was saved - //! @param documentId unique id of document for which the notification is sent - virtual void OnDocumentSaved([[maybe_unused]] const AZ::Uuid& documentId) {} - - //! Signal that a document was selected - //! @param documentId unique id of document for which the notification is sent - virtual void OnDocumentSelected([[maybe_unused]] const AZ::Uuid& documentId) {} - - //! Signal that a document was modified - //! @param documentId unique id of document for which the notification is sent - virtual void OnDocumentModified([[maybe_unused]] const AZ::Uuid& documentId) {} - - //! Signal that a document undo state was updated - //! @param documentId unique id of document for which the notification is sent - virtual void OnDocumentUndoStateChanged([[maybe_unused]] const AZ::Uuid& documentId) {} - }; - - using ShaderManagementConsoleDocumentNotificationBus = AZ::EBus; -} // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Document/ShaderManagementConsoleDocumentRequestBus.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Document/ShaderManagementConsoleDocumentRequestBus.h index 25e157d1f3..d0e6aea5b9 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Document/ShaderManagementConsoleDocumentRequestBus.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Document/ShaderManagementConsoleDocumentRequestBus.h @@ -7,18 +7,13 @@ */ #pragma once -#include -#include -#include -#include - -#include #include #include +#include +#include namespace ShaderManagementConsole { - using ShaderManagementConsoleDocumentResult = AZ::Outcome; class ShaderManagementConsoleDocumentRequests : public AZ::EBusTraits @@ -28,12 +23,6 @@ namespace ShaderManagementConsole static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; typedef AZ::Uuid BusIdType; - //! Get absolute path of document - virtual AZStd::string_view GetAbsolutePath() const = 0; - - //! Get relative path of document - virtual AZStd::string_view GetRelativePath() const = 0; - //! Get the number of options virtual size_t GetShaderOptionCount() const = 0; @@ -45,47 +34,6 @@ namespace ShaderManagementConsole //! Get the information for the shader variant at the specified index virtual const AZ::RPI::ShaderVariantListSourceData::VariantInfo& GetShaderVariantInfo(size_t index) const = 0; - - //! Load document and related data - //! @param loadPath Absolute path of document to load - virtual ShaderManagementConsoleDocumentResult Open(AZStd::string_view loadPath) = 0; - - //! Save document to file - virtual ShaderManagementConsoleDocumentResult Save() = 0; - - //! Save document copy - //! @param savePath Absolute path where document is saved - virtual ShaderManagementConsoleDocumentResult SaveAsCopy(AZStd::string_view savePath) = 0; - - //! Close document and reset its data - virtual ShaderManagementConsoleDocumentResult Close() = 0; - - //! document is loaded - virtual bool IsOpen() const = 0; - - //! document has changes pending - virtual bool IsModified() const = 0; - - //! Can the document be saved - virtual bool IsSavable() const = 0; - - //! Returns true if there are reversible modifications to the document - virtual bool CanUndo() const = 0; - - //! Returns true if there are changes that were reversed and can be re-applied to the document - virtual bool CanRedo() const = 0; - - //! Restores the previous state of the document - virtual bool Undo() = 0; - - //! Restores the next state of the document - virtual bool Redo() = 0; - - //! Signal that editing is about to begin, like beginning to drag a slider control - virtual bool BeginEdit() = 0; - - //! Signal that editing has completed, like after releasing the mouse button after continuously dragging a slider control - virtual bool EndEdit() = 0; }; using ShaderManagementConsoleDocumentRequestBus = AZ::EBus; diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Document/ShaderManagementConsoleDocumentSystemRequestBus.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Document/ShaderManagementConsoleDocumentSystemRequestBus.h deleted file mode 100644 index b21686ebaf..0000000000 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Document/ShaderManagementConsoleDocumentSystemRequestBus.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include - -namespace ShaderManagementConsole -{ - //! ShaderManagementConsoleDocumentSystemRequestBus provides high level file requests for menus, scripts, etc. - class ShaderManagementConsoleDocumentSystemRequests - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - //! Create a document object - //! @return Uuid of new document, or null Uuid if failed - virtual AZ::Uuid CreateDocument() = 0; - - //! Destroy a document object with the specified id - //! @return true if Uuid was found and removed, otherwise false - virtual bool DestroyDocument(const AZ::Uuid& documentId) = 0; - - //! Open a document for editing - //! @param path document to edit. - //! @return unique id of new document if successful, otherwise null Uuid - virtual AZ::Uuid OpenDocument(AZStd::string_view path) = 0; - - //! Close the specified document - //! @param documentId unique id of document to close - virtual bool CloseDocument(const AZ::Uuid& documentId) = 0; - - //! Close all documents - virtual bool CloseAllDocuments() = 0; - - //! Save the specified document - //! @param documentId unique id of document to save - virtual bool SaveDocument(const AZ::Uuid& documentId) = 0; - - //! Save the specified document to a different file - //! @param documentId unique id of document to save - virtual bool SaveDocumentAsCopy(const AZ::Uuid& documentId) = 0; - - //! Save all documents - virtual bool SaveAllDocuments() = 0; - }; - - using ShaderManagementConsoleDocumentSystemRequestBus = AZ::EBus; - -} // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.cpp index 67990d4b71..2b7767635e 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.cpp @@ -8,48 +8,32 @@ #include #include - -#include -#include - +#include #include #include #include +#include namespace ShaderManagementConsole { ShaderManagementConsoleDocument::ShaderManagementConsoleDocument() + : AtomToolsFramework::AtomToolsDocument() { ShaderManagementConsoleDocumentRequestBus::Handler::BusConnect(m_id); - ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentCreated, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentCreated, m_id); } ShaderManagementConsoleDocument::~ShaderManagementConsoleDocument() { - ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentDestroyed, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentDestroyed, m_id); ShaderManagementConsoleDocumentRequestBus::Handler::BusDisconnect(); - } - - const AZ::Uuid& ShaderManagementConsoleDocument::GetId() const - { - return m_id; - } - - AZStd::string_view ShaderManagementConsoleDocument::GetAbsolutePath() const - { - return m_absolutePath; - } - - AZStd::string_view ShaderManagementConsoleDocument::GetRelativePath() const - { - return m_relativePath; + Clear(); } size_t ShaderManagementConsoleDocument::GetShaderOptionCount() const { auto layout = m_shaderAsset->GetShaderOptionGroupLayout(); auto& shaderOptionDescriptors = layout->GetShaderOptions(); - return shaderOptionDescriptors.size(); } @@ -57,7 +41,6 @@ namespace ShaderManagementConsole { auto layout = m_shaderAsset->GetShaderOptionGroupLayout(); auto& shaderOptionDescriptors = layout->GetShaderOptions(); - return shaderOptionDescriptors[index]; } @@ -71,19 +54,21 @@ namespace ShaderManagementConsole return m_shaderVariantListSourceData.m_shaderVariants[index]; } - ShaderManagementConsoleDocumentResult ShaderManagementConsoleDocument::Open(AZStd::string_view loadPath) + bool ShaderManagementConsoleDocument::Open(AZStd::string_view loadPath) { Clear(); m_absolutePath = loadPath; if (!AzFramework::StringFunc::Path::Normalize(m_absolutePath)) { - return AZ::Failure(AZStd::string::format("Document path could not be normalized: '%s'.", m_absolutePath.c_str())); + AZ_Error("ShaderManagementConsoleDocument", false, "Document path could not be normalized: '%s'.", m_absolutePath.c_str()); + return false; } if (AzFramework::StringFunc::Path::IsRelative(m_absolutePath.c_str())) { - return AZ::Failure(AZStd::string::format("Document path must be absolute: '%s'.", m_absolutePath.c_str())); + AZ_Error("ShaderManagementConsoleDocument", false, "Document path must be absolute: '%s'.", m_absolutePath.c_str()); + return false; } if (AzFramework::StringFunc::Path::IsExtension(m_absolutePath.c_str(), AZ::RPI::ShaderVariantListSourceData::Extension)) @@ -91,7 +76,8 @@ namespace ShaderManagementConsole // Load the shader config data and create a shader config asset from it if (!AZ::RPI::JsonUtils::LoadObjectFromFile(m_absolutePath, m_shaderVariantListSourceData)) { - return AZ::Failure(AZStd::string::format("Failed loading shader variant list data: '%s.'", m_absolutePath.c_str())); + AZ_Error("ShaderManagementConsoleDocument", false, "Failed loading shader variant list data: '%s.'", m_absolutePath.c_str()); + return false; } } @@ -103,13 +89,15 @@ namespace ShaderManagementConsole watchFolder); if (!result) { - return AZ::Failure(AZStd::string::format("Could not find source data: '%s'.", m_absolutePath.c_str())); + AZ_Error("ShaderManagementConsoleDocument", false, "Could not find source data: '%s'.", m_absolutePath.c_str()); + return false; } m_relativePath = m_shaderVariantListSourceData.m_shaderFilePath; if (!AzFramework::StringFunc::Path::Normalize(m_relativePath)) { - return AZ::Failure(AZStd::string::format("Shader path could not be normalized: '%s'.", m_relativePath.c_str())); + AZ_Error("ShaderManagementConsoleDocument", false, "Shader path could not be normalized: '%s'.", m_relativePath.c_str()); + return false; } AZStd::string shaderPath = m_relativePath; @@ -118,78 +106,28 @@ namespace ShaderManagementConsole m_shaderAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath(shaderPath.c_str()); if (!m_shaderAsset) { - return AZ::Failure(AZStd::string::format("Could not load shader asset: %s.", shaderPath.c_str())); + AZ_Error("ShaderManagementConsoleDocument", false, "Could not load shader asset: %s.", shaderPath.c_str()); + return false; } - ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentOpened, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, m_id); - return AZ::Success(AZStd::string::format("Document loaded: '%s'", m_absolutePath.c_str())); + AZ_TracePrintf("ShaderManagementConsoleDocument", "Document opened: '%s'\n", m_absolutePath.c_str()); + return true; } - ShaderManagementConsoleDocumentResult ShaderManagementConsoleDocument::Save() + bool ShaderManagementConsoleDocument::Close() { if (!IsOpen()) { - return AZ::Failure(AZStd::string::format("Document is not open to be saved: '%s'.", m_absolutePath.c_str())); - } - - if (!IsSavable()) - { - return AZ::Failure(AZStd::string::format("Document can not be saved: '%s'.", m_absolutePath.c_str())); - } - - return AZ::Failure(AZStd::string::format("%s is not implemented!", __FUNCTION__)); - - // Auto add or checkout saved file - //AzToolsFramework::SourceControlCommandBus::Broadcast(&AzToolsFramework::SourceControlCommandBus::Events::RequestEdit, - // m_absolutePath.c_str(), true, - // [](bool, const AzToolsFramework::SourceControlFileInfo&) {}); - - //ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentSaved, m_id); - - //return AZ::Success(AZStd::string::format("Document saved: %s", m_absolutePath.data())); - } - - ShaderManagementConsoleDocumentResult ShaderManagementConsoleDocument::SaveAsCopy(AZStd::string_view savePath) - { - if (!IsOpen()) - { - return AZ::Failure(AZStd::string::format("Document is not open to be saved: '%s'.", m_absolutePath.c_str())); - } - - if (!IsSavable()) - { - return AZ::Failure(AZStd::string::format("Document can not be saved: '%s'.", m_absolutePath.c_str())); - } - - AZStd::string normalizedSavePath = savePath; - if (!AzFramework::StringFunc::Path::Normalize(normalizedSavePath)) - { - return AZ::Failure(AZStd::string::format("Document save path could not be normalized: '%s'.", normalizedSavePath.c_str())); - } - - return AZ::Failure(AZStd::string::format("%s is not implemented!", __FUNCTION__)); - - // Auto add or checkout saved file - //AzToolsFramework::SourceControlCommandBus::Broadcast(&AzToolsFramework::SourceControlCommandBus::Events::RequestEdit, - // normalizedSavePath.c_str(), true, - // [](bool, const AzToolsFramework::SourceControlFileInfo&) {}); - - //ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentSaved, m_id); - - //return AZ::Success(AZStd::string::format("Document saved: %s", normalizedSavePath.c_str())); - } - - ShaderManagementConsoleDocumentResult ShaderManagementConsoleDocument::Close() - { - if (!IsOpen()) - { - return AZ::Failure(AZStd::string("Document is not open")); + AZ_Error("ShaderManagementConsoleDocument", false, "Document is not open"); + return false; } Clear(); - ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentClosed, m_id); - return AZ::Success(AZStd::string("Document was closed")); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentClosed, m_id); + AZ_TracePrintf("ShaderManagementConsoleDocument", "Document closed\n"); + return true; } bool ShaderManagementConsoleDocument::IsOpen() const @@ -197,77 +135,11 @@ namespace ShaderManagementConsole return !m_absolutePath.empty() && !m_relativePath.empty(); } - bool ShaderManagementConsoleDocument::IsModified() const - { - return false; - } - - bool ShaderManagementConsoleDocument::IsSavable() const - { - return true; - } - - bool ShaderManagementConsoleDocument::CanUndo() const - { - // Undo will only be allowed if something has been recorded and we're not at the beginning of history - return IsOpen() && !m_undoHistory.empty() && m_undoHistoryIndex > 0; - } - - bool ShaderManagementConsoleDocument::CanRedo() const - { - // Redo will only be allowed if something has been recorded and we're not at the end of history - return IsOpen() && !m_undoHistory.empty() && m_undoHistoryIndex < m_undoHistory.size(); - } - - bool ShaderManagementConsoleDocument::Undo() - { - if (CanUndo()) - { - // The history index is one beyond the last executed command. Decrement the index then execute undo. - m_undoHistory[--m_undoHistoryIndex].first(); - ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); - return true; - } - return false; - } - - bool ShaderManagementConsoleDocument::Redo() - { - if (CanRedo()) - { - // Execute the current redo command then move the history index to the next position. - m_undoHistory[m_undoHistoryIndex++].second(); - ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); - return true; - } - return false; - } - - bool ShaderManagementConsoleDocument::BeginEdit() - { - return true; - } - - bool ShaderManagementConsoleDocument::EndEdit() - { - // Wipe any state beyond the current history index - m_undoHistory.erase(m_undoHistory.begin() + m_undoHistoryIndex, m_undoHistory.end()); - - // Add undo and redo operations using lambdas that will capture property state and restore it when executed - m_undoHistory.emplace_back( - [this]() { /**/ }, - [this]() { /**/ }); - - // Assign the index to the end of history - m_undoHistoryIndex = aznumeric_cast(m_undoHistory.size()); - ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); - - return true; - } - void ShaderManagementConsoleDocument::Clear() { m_absolutePath.clear(); m_relativePath.clear(); + m_shaderVariantListSourceData = {}; + m_shaderAsset = {}; } } // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.h index 6c9580c086..eb7d6b87a0 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.h @@ -7,13 +7,12 @@ */ #pragma once -#include -#include - -#include -#include - #include +#include +#include +#include +#include +#include namespace ShaderManagementConsole { @@ -21,7 +20,8 @@ namespace ShaderManagementConsole * ShaderManagementConsoleDocument provides an API for modifying and saving document properties. */ class ShaderManagementConsoleDocument - : public ShaderManagementConsoleDocumentRequestBus::Handler + : public AtomToolsFramework::AtomToolsDocument + , public ShaderManagementConsoleDocumentRequestBus::Handler { public: AZ_RTTI(ShaderManagementConsoleDocument, "{DBA269AE-892B-415C-8FA1-166B94B0E045}"); @@ -31,29 +31,20 @@ namespace ShaderManagementConsole ShaderManagementConsoleDocument(); virtual ~ShaderManagementConsoleDocument(); - const AZ::Uuid& GetId() const; + //////////////////////////////////////////////////////////////////////// + // AtomToolsFramework::AtomToolsDocument + //////////////////////////////////////////////////////////////////////// + bool Open(AZStd::string_view loadPath) override; + bool Close() override; + bool IsOpen() const override; + //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // ShaderManagementConsoleDocumentRequestBus::Handler implementation - AZStd::string_view GetAbsolutePath() const override; - AZStd::string_view GetRelativePath() const override; size_t GetShaderOptionCount() const override; const AZ::RPI::ShaderOptionDescriptor& GetShaderOptionDescriptor(size_t index) const override; size_t GetShaderVariantCount() const override; const AZ::RPI::ShaderVariantListSourceData::VariantInfo& GetShaderVariantInfo(size_t index) const override; - ShaderManagementConsoleDocumentResult Open(AZStd::string_view loadPath) override; - ShaderManagementConsoleDocumentResult Save() override; - ShaderManagementConsoleDocumentResult SaveAsCopy(AZStd::string_view savePath) override; - ShaderManagementConsoleDocumentResult Close() override; - bool IsOpen() const override; - bool IsModified() const override; - bool IsSavable() const override; - bool CanUndo() const override; - bool CanRedo() const override; - bool Undo() override; - bool Redo() override; - bool BeginEdit() override; - bool EndEdit() override; //////////////////////////////////////////////////////////////////////// private: @@ -67,28 +58,11 @@ namespace ShaderManagementConsole using UndoRedoHistory = AZStd::vector; void Clear(); - - // Unique id of this document - AZ::Uuid m_id = AZ::Uuid::CreateRandom(); - - // Relative path to the document - AZStd::string m_relativePath; - - // Absolute path to the document - AZStd::string m_absolutePath; // Source data for shader variant list AZ::RPI::ShaderVariantListSourceData m_shaderVariantListSourceData; // Shader asset for the corresponding shader variant list AZ::Data::Asset m_shaderAsset; - - // Variables needed for tracking the undo and redo state of this document - - // Container of undo commands - UndoRedoHistory m_undoHistory; - - // The current position in the undo redo history - int m_undoHistoryIndex = 0; }; } // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentModule.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentModule.cpp index 4987b0528f..a9415fd85b 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentModule.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentModule.cpp @@ -7,10 +7,8 @@ */ #include -#include - -#include #include +#include namespace ShaderManagementConsole { diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.cpp index fae9ec75ef..55b800067a 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.cpp @@ -6,39 +6,16 @@ * */ -#include - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include #include -#include - -AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -#include -#include -#include -AZ_POP_DISABLE_WARNING +#include +#include +#include +#include +#include +#include namespace ShaderManagementConsole { - ShaderManagementConsoleDocumentSystemComponent::ShaderManagementConsoleDocumentSystemComponent() - { - } - void ShaderManagementConsoleDocumentSystemComponent::Reflect(AZ::ReflectContext* context) { if (AZ::SerializeContext* serialize = azrtti_cast(context)) @@ -50,7 +27,7 @@ namespace ShaderManagementConsole { ec->Class("ShaderManagementConsoleDocumentSystemComponent", "Manages documents") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("System")) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ; } @@ -58,63 +35,35 @@ namespace ShaderManagementConsole if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->EBus("ShaderManagementConsoleDocumentSystemRequestBus") - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) - ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, "shadermanagementconsole") - ->Event("CreateDocument", &ShaderManagementConsoleDocumentSystemRequestBus::Events::CreateDocument) - ->Event("DestroyDocument", &ShaderManagementConsoleDocumentSystemRequestBus::Events::DestroyDocument) - ->Event("OpenDocument", &ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument) - ->Event("CloseDocument", &ShaderManagementConsoleDocumentSystemRequestBus::Events::CloseDocument) - ->Event("CloseAllDocuments", &ShaderManagementConsoleDocumentSystemRequestBus::Events::CloseAllDocuments) - ->Event("SaveDocument", &ShaderManagementConsoleDocumentSystemRequestBus::Events::SaveDocument) - ->Event("SaveDocumentAsCopy", &ShaderManagementConsoleDocumentSystemRequestBus::Events::SaveDocumentAsCopy) - ->Event("SaveAllDocuments", &ShaderManagementConsoleDocumentSystemRequestBus::Events::SaveAllDocuments) - ; - behaviorContext->EBus("ShaderManagementConsoleDocumentRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") ->Attribute(AZ::Script::Attributes::Module, "shadermanagementconsole") - ->Event("GetAbsolutePath", &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath) - ->Event("GetRelativePath", &ShaderManagementConsoleDocumentRequestBus::Events::GetRelativePath) ->Event("GetShaderOptionCount", &ShaderManagementConsoleDocumentRequestBus::Events::GetShaderOptionCount) ->Event("GetShaderOptionDescriptor", &ShaderManagementConsoleDocumentRequestBus::Events::GetShaderOptionDescriptor) ->Event("GetShaderVariantCount", &ShaderManagementConsoleDocumentRequestBus::Events::GetShaderVariantCount) ->Event("GetShaderVariantInfo", &ShaderManagementConsoleDocumentRequestBus::Events::GetShaderVariantInfo) - ->Event("Open", &ShaderManagementConsoleDocumentRequestBus::Events::Open) - ->Event("Close", &ShaderManagementConsoleDocumentRequestBus::Events::Close) - ->Event("Save", &ShaderManagementConsoleDocumentRequestBus::Events::Save) - ->Event("SaveAsCopy", &ShaderManagementConsoleDocumentRequestBus::Events::SaveAsCopy) - ->Event("IsOpen", &ShaderManagementConsoleDocumentRequestBus::Events::IsOpen) - ->Event("IsModified", &ShaderManagementConsoleDocumentRequestBus::Events::IsModified) - ->Event("IsSavable", &ShaderManagementConsoleDocumentRequestBus::Events::IsSavable) - ->Event("CanUndo", &ShaderManagementConsoleDocumentRequestBus::Events::CanUndo) - ->Event("CanRedo", &ShaderManagementConsoleDocumentRequestBus::Events::CanRedo) - ->Event("Undo", &ShaderManagementConsoleDocumentRequestBus::Events::Undo) - ->Event("Redo", &ShaderManagementConsoleDocumentRequestBus::Events::Redo) - ->Event("BeginEdit", &ShaderManagementConsoleDocumentRequestBus::Events::BeginEdit) - ->Event("EndEdit", &ShaderManagementConsoleDocumentRequestBus::Events::EndEdit) ; } } void ShaderManagementConsoleDocumentSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { - required.push_back(AZ_CRC("AssetProcessorToolsConnection", 0x734669bc)); - required.push_back(AZ_CRC("AssetDatabaseService", 0x3abf5601)); - required.push_back(AZ_CRC("PropertyManagerService", 0x63a3d7ad)); - required.push_back(AZ_CRC("RPISystem", 0xf2add773)); + required.push_back(AZ_CRC_CE("AtomToolsDocumentSystemService")); + required.push_back(AZ_CRC_CE("AssetProcessorToolsConnection")); + required.push_back(AZ_CRC_CE("AssetDatabaseService")); + required.push_back(AZ_CRC_CE("PropertyManagerService")); + required.push_back(AZ_CRC_CE("RPISystem")); } void ShaderManagementConsoleDocumentSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { - provided.push_back(AZ_CRC("ShaderManagementConsoleDocumentSystemService")); + provided.push_back(AZ_CRC_CE("ShaderManagementConsoleDocumentSystemService")); } void ShaderManagementConsoleDocumentSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { - incompatible.push_back(AZ_CRC("ShaderManagementConsoleDocumentSystemService")); + incompatible.push_back(AZ_CRC_CE("ShaderManagementConsoleDocumentSystemService")); } void ShaderManagementConsoleDocumentSystemComponent::Init() @@ -123,203 +72,15 @@ namespace ShaderManagementConsole void ShaderManagementConsoleDocumentSystemComponent::Activate() { - m_documentMap.clear(); - ShaderManagementConsoleDocumentSystemRequestBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( + &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Handler::RegisterDocumentType, + []() + { + return aznew ShaderManagementConsoleDocument(); + }); } void ShaderManagementConsoleDocumentSystemComponent::Deactivate() { - ShaderManagementConsoleDocumentSystemRequestBus::Handler::BusDisconnect(); - m_documentMap.clear(); - } - - AZ::Uuid ShaderManagementConsoleDocumentSystemComponent::CreateDocument() - { - auto document = AZStd::make_unique(); - if (!document) - { - AZ_Error("ShaderManagementConsoleDocument", false, "Failed to create new document"); - return AZ::Uuid::CreateNull(); - } - - AZ::Uuid documentId = document->GetId(); - m_documentMap.emplace(documentId, document.release()); - return documentId; - } - - bool ShaderManagementConsoleDocumentSystemComponent::DestroyDocument(const AZ::Uuid& documentId) - { - return m_documentMap.erase(documentId) != 0; - } - - AZ::Uuid ShaderManagementConsoleDocumentSystemComponent::OpenDocument(AZStd::string_view path) - { - return OpenDocumentImpl(path, true); - } - - bool ShaderManagementConsoleDocumentSystemComponent::CloseDocument(const AZ::Uuid& documentId) - { - bool isOpen = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(isOpen, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsOpen); - if (!isOpen) - { - return true; - } - - bool isModified = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(isModified, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsModified); - if (isModified) - { - if (QMessageBox::question(QApplication::activeWindow(), "document has unsaved changes", "Would you like to close anyway?", - QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) - { - return false; - } - } - - ShaderManagementConsoleDocumentResult closeResult = AZ::Success(AZStd::string("There is no active document")); - ShaderManagementConsoleDocumentRequestBus::EventResult(closeResult, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::Close); - if (!closeResult) - { - QMessageBox::critical(QApplication::activeWindow(), "Failed to close document", - QString::fromUtf8(closeResult.GetError().data(), (int)closeResult.GetError().size())); - return false; - } - - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::DestroyDocument, documentId); - return true; - } - - bool ShaderManagementConsoleDocumentSystemComponent::CloseAllDocuments() - { - bool result = true; - auto documentMap = m_documentMap; - for (const auto& documentPair : documentMap) - { - if (!CloseDocument(documentPair.first)) - { - result = false; - } - } - - return result; - } - - bool ShaderManagementConsoleDocumentSystemComponent::SaveDocument(const AZ::Uuid& documentId) - { - AZStd::string documentPath; - ShaderManagementConsoleDocumentRequestBus::EventResult(documentPath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); - - const QFileInfo saveInfo(documentPath.c_str()); - if (saveInfo.absoluteFilePath().isEmpty()) - { - return false; - } - - if (saveInfo.exists() && !saveInfo.isWritable()) - { - QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Unable to save document. File can not be overwritten.")); - return false; - } - - ShaderManagementConsoleDocumentResult result = AZ::Failure(AZStd::string("There is no active document")); - ShaderManagementConsoleDocumentRequestBus::EventResult(result, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::Save); - if (!result) - { - QMessageBox::critical(QApplication::activeWindow(), "document not saved", - QString::fromUtf8(result.GetError().data(), (int)result.GetError().size())); - return false; - } - - AZ_TracePrintf("ShaderManagementConsole", "%s\n", result.GetValue().c_str()); - return true; - } - - bool ShaderManagementConsoleDocumentSystemComponent::SaveDocumentAsCopy(const AZ::Uuid& documentId) - { - AZStd::string documentPath; - ShaderManagementConsoleDocumentRequestBus::EventResult(documentPath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); - - const QFileInfo& saveInfo = AtomToolsFramework::GetSaveFileInfo(documentPath.c_str()); - if (saveInfo.absoluteFilePath().isEmpty()) - { - return false; - } - - AZStd::string saveDocumentPath = saveInfo.absoluteFilePath().toUtf8().constData(); - AzFramework::StringFunc::Path::Normalize(saveDocumentPath); - - ShaderManagementConsoleDocumentResult result = AZ::Failure(AZStd::string("There is no active document")); - ShaderManagementConsoleDocumentRequestBus::EventResult(result, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::SaveAsCopy, saveDocumentPath); - if (!result) - { - QMessageBox::critical(QApplication::activeWindow(), "document copy not saved", - QString::fromUtf8(result.GetError().data(), (int)result.GetError().size())); - return false; - } - - AZ_TracePrintf("ShaderManagementConsole", "%s\n", result.GetValue().c_str()); - return true; - } - - bool ShaderManagementConsoleDocumentSystemComponent::SaveAllDocuments() - { - bool result = true; - for (const auto& documentPair : m_documentMap) - { - if (!SaveDocument(documentPair.first)) - { - result = false; - } - } - - return result; - } - - AZ::Uuid ShaderManagementConsoleDocumentSystemComponent::OpenDocumentImpl(AZStd::string_view path, bool checkIfAlreadyOpen) - { - AZStd::string requestedPath = path; - if (requestedPath.empty() || !AzFramework::StringFunc::Path::Normalize(requestedPath)) - { - QMessageBox::critical(QApplication::activeWindow(), "document path is invalid", - QString::fromUtf8(requestedPath.data(), (int)requestedPath.size())); - return AZ::Uuid::CreateNull(); - } - - // Determine if the file is already open and select it - if (checkIfAlreadyOpen) - { - for (const auto& documentPair : m_documentMap) - { - AZStd::string openDocumentPath; - ShaderManagementConsoleDocumentRequestBus::EventResult(openDocumentPath, documentPair.first, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); - if (openDocumentPath == requestedPath) - { - ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentOpened, documentPair.first); - return documentPair.first; - } - } - } - - AZ::Uuid documentId = AZ::Uuid::CreateNull(); - ShaderManagementConsoleDocumentSystemRequestBus::BroadcastResult(documentId, &ShaderManagementConsoleDocumentSystemRequestBus::Events::CreateDocument); - if (documentId.IsNull()) - { - QMessageBox::critical(QApplication::activeWindow(), "Failed to create document", - QString::fromUtf8(requestedPath.data(), (int)requestedPath.size())); - return AZ::Uuid::CreateNull(); - } - - ShaderManagementConsoleDocumentResult openResult = AZ::Failure(AZStd::string("Failed to open document")); - ShaderManagementConsoleDocumentRequestBus::EventResult(openResult, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::Open, requestedPath); - if (!openResult) - { - QMessageBox::critical(QApplication::activeWindow(), "Failed to open document", - QString::fromUtf8(openResult.GetError().data(), (int)openResult.GetError().size())); - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::DestroyDocument, documentId); - return AZ::Uuid::CreateNull(); - } - - return documentId; } } diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.h index 245222976e..1ee825f6de 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.h @@ -9,28 +9,17 @@ #pragma once #include -#include - -#include -#include -#include - -AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -#include -AZ_POP_DISABLE_WARNING namespace ShaderManagementConsole { - //! ShaderManagementConsoleDocumentSystemComponent is the central component of the Shader Management Console Core gem + //! ShaderManagementConsoleDocumentSystemComponent class ShaderManagementConsoleDocumentSystemComponent : public AZ::Component - , private ShaderManagementConsoleDocumentSystemRequestBus::Handler { public: - AZ_COMPONENT(ShaderManagementConsoleDocumentSystemComponent, "{58ABE0AE-2710-41E2-ADFD-E2D67407427D}"); + AZ_COMPONENT(ShaderManagementConsoleDocumentSystemComponent, "{1610159D-59DC-48B1-B2D1-FCE7AFD3B012}"); - ShaderManagementConsoleDocumentSystemComponent(); + ShaderManagementConsoleDocumentSystemComponent() = default; ~ShaderManagementConsoleDocumentSystemComponent() = default; ShaderManagementConsoleDocumentSystemComponent(const ShaderManagementConsoleDocumentSystemComponent&) = delete; ShaderManagementConsoleDocumentSystemComponent& operator =(const ShaderManagementConsoleDocumentSystemComponent&) = delete; @@ -48,21 +37,5 @@ namespace ShaderManagementConsole void Activate() override; void Deactivate() override; //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // ShaderManagementConsoleDocumentSystemRequestBus::Handler overrides... - AZ::Uuid CreateDocument() override; - bool DestroyDocument(const AZ::Uuid& documentId) override; - AZ::Uuid OpenDocument(AZStd::string_view path) override; - bool CloseDocument(const AZ::Uuid& documentId) override; - bool CloseAllDocuments() override; - bool SaveDocument(const AZ::Uuid& documentId) override; - bool SaveDocumentAsCopy(const AZ::Uuid& documentId) override; - bool SaveAllDocuments() override; - //////////////////////////////////////////////////////////////////////// - - AZ::Uuid OpenDocumentImpl(AZStd::string_view path, bool checkIfAlreadyOpen); - - AZStd::unordered_map> m_documentMap; }; } diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp index 313522a256..3d07a0de15 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp @@ -7,8 +7,8 @@ */ #include -#include #include +#include #include #include #include @@ -66,8 +66,8 @@ namespace ShaderManagementConsole const AZStd::string openDocumentPath = commandLine.GetMiscValue(openDocumentIndex); AZ_Printf(GetBuildTargetName().c_str(), "Opening document: %s", openDocumentPath.c_str()); - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast( - &ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( + &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); } Base::ProcessCommandLine(commandLine); diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h index 24b2020dad..6596429577 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h @@ -8,8 +8,8 @@ #pragma once -#include #include +#include namespace ShaderManagementConsole { diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserInteractions.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserInteractions.cpp index c0b9f5502c..b82d348df3 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserInteractions.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserInteractions.cpp @@ -6,28 +6,24 @@ * */ -#include -#include -#include -#include -#include -#include - -#include - +#include +#include +#include #include - +#include #include +#include #include #include -#include #include -#include +#include -#include -#include - -#include +#include +#include +#include +#include +#include +#include namespace ShaderManagementConsole { @@ -80,7 +76,7 @@ namespace ShaderManagementConsole { if (AzFramework::StringFunc::Path::IsExtension(entry->GetFullPath().c_str(), AZ::RPI::ShaderVariantListSourceData::Extension)) { - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument, entry->GetFullPath().c_str()); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, entry->GetFullPath().c_str()); } else { diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserWidget.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserWidget.cpp index 588dccca1b..eb863a195a 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserWidget.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserWidget.cpp @@ -6,26 +6,21 @@ * */ -#include - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include #include - -#include - -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include @@ -85,14 +80,14 @@ namespace ShaderManagementConsole }); AssetBrowserModelNotificationBus::Handler::BusConnect(); - ShaderManagementConsoleDocumentNotificationBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(); } ShaderManagementConsoleBrowserWidget::~ShaderManagementConsoleBrowserWidget() { // Maintains the tree expansion state between runs m_ui->m_assetBrowserTreeViewWidget->SaveState(); - ShaderManagementConsoleDocumentNotificationBus::Handler::BusDisconnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusDisconnect(); AssetBrowserModelNotificationBus::Handler::BusDisconnect(); } @@ -150,7 +145,7 @@ namespace ShaderManagementConsole { if (AzFramework::StringFunc::Path::IsExtension(sourceEntry->GetFullPath().c_str(), AZ::RPI::ShaderVariantListSourceData::Extension)) { - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument, sourceEntry->GetFullPath()); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, sourceEntry->GetFullPath()); } else { @@ -192,7 +187,7 @@ namespace ShaderManagementConsole void ShaderManagementConsoleBrowserWidget::OnDocumentOpened(const AZ::Uuid& documentId) { AZStd::string absolutePath; - ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(absolutePath, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetAbsolutePath); if (!absolutePath.empty()) { m_pathToSelect = absolutePath; @@ -203,4 +198,4 @@ namespace ShaderManagementConsole } // namespace ShaderManagementConsole -#include +#include diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserWidget.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserWidget.h index d251ab26f9..73a2a24aa9 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserWidget.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleBrowserWidget.h @@ -9,11 +9,10 @@ #pragma once #if !defined(Q_MOC_RUN) +#include #include -#include #include #include -#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include @@ -44,7 +43,7 @@ namespace ShaderManagementConsole class ShaderManagementConsoleBrowserWidget : public QWidget , public AzToolsFramework::AssetBrowser::AssetBrowserModelNotificationBus::Handler - , public ShaderManagementConsoleDocumentNotificationBus::Handler + , public AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler { Q_OBJECT public: @@ -64,7 +63,7 @@ namespace ShaderManagementConsole // AssetBrowserModelNotificationBus::Handler implementation void EntryAdded(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) override; - // ShaderManagementConsoleDocumentNotificationBus::Handler implementation + // AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler implementation void OnDocumentOpened(const AZ::Uuid& documentId) override; }; } // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index a7c8d79130..0b4802640b 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -13,12 +13,11 @@ #include #include #include - #include #include - #include -#include +#include +#include #include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT @@ -62,19 +61,19 @@ namespace ShaderManagementConsole // Restore geometry and show the window mainWindowWrapper->showFromSettings(); - ShaderManagementConsoleDocumentNotificationBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(); OnDocumentOpened(AZ::Uuid::CreateNull()); } ShaderManagementConsoleWindow::~ShaderManagementConsoleWindow() { - ShaderManagementConsoleDocumentNotificationBus::Handler::BusDisconnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusDisconnect(); } void ShaderManagementConsoleWindow::closeEvent(QCloseEvent* closeEvent) { bool didClose = true; - ShaderManagementConsoleDocumentSystemRequestBus::BroadcastResult(didClose, &ShaderManagementConsoleDocumentSystemRequestBus::Events::CloseAllDocuments); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(didClose, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseAllDocuments); if (!didClose) { closeEvent->ignore(); @@ -88,17 +87,17 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindow::OnDocumentOpened(const AZ::Uuid& documentId) { bool isOpen = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(isOpen, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsOpen); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isOpen, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsOpen); bool isSavable = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(isSavable, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsSavable); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isSavable, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsSavable); bool isModified = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(isModified, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsModified); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isModified, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsModified); bool canUndo = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(canUndo, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::CanUndo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(canUndo, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::CanUndo); bool canRedo = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(canRedo, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::CanRedo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(canRedo, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::CanRedo); AZStd::string absolutePath; - ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(absolutePath, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetAbsolutePath); AZStd::string filename; AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); @@ -150,7 +149,7 @@ namespace ShaderManagementConsole const QString documentPath = GetDocumentPath(documentId); if (!documentPath.isEmpty()) { - const QString status = QString("Document closed: %1").arg(documentPath); + const QString status = QString("Document opened: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } } @@ -167,9 +166,9 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindow::OnDocumentModified(const AZ::Uuid& documentId) { bool isModified = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(isModified, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsModified); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isModified, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsModified); AZStd::string absolutePath; - ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(absolutePath, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetAbsolutePath); AZStd::string filename; AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); @@ -180,9 +179,9 @@ namespace ShaderManagementConsole if (documentId == GetDocumentIdFromTab(m_tabWidget->currentIndex())) { bool canUndo = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(canUndo, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::CanUndo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(canUndo, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::CanUndo); bool canRedo = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(canRedo, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::CanRedo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(canRedo, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::CanRedo); m_actionUndo->setEnabled(canUndo); m_actionRedo->setEnabled(canRedo); } @@ -191,15 +190,15 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindow::OnDocumentSaved(const AZ::Uuid& documentId) { bool isModified = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(isModified, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsModified); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(isModified, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsModified); AZStd::string absolutePath; - ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(absolutePath, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetAbsolutePath); AZStd::string filename; AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document closed: %1").arg(documentPath); + const QString status = QString("Document saved: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } @@ -217,7 +216,7 @@ namespace ShaderManagementConsole const AZStd::string filePath = AtomToolsFramework::GetOpenFileInfo(assetTypes).absoluteFilePath().toUtf8().constData(); if (!filePath.empty()) { - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument, filePath); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, filePath); } }, QKeySequence::Open); @@ -225,32 +224,56 @@ namespace ShaderManagementConsole m_menuFile->addSeparator(); - m_actionClose = m_menuFile->addAction("&Close", [this]() { - CloseDocumentForTab(m_tabWidget->currentIndex()); - }, QKeySequence::Close); - - m_actionCloseAll = m_menuFile->addAction("Close All", [this]() { - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::CloseAllDocuments); - }); - - m_actionCloseOthers = m_menuFile->addAction("Close Others", [this]() { - CloseAllExceptDocumentForTab(m_tabWidget->currentIndex()); - }); - - m_menuFile->addSeparator(); - m_actionSave = m_menuFile->addAction("&Save", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::SaveDocument, documentId); + bool result = false; + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveDocument, documentId); + if (!result) + { + const QString documentPath = GetDocumentPath(documentId); + const QString status = QString("Document save failed: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); + } }, QKeySequence::Save); m_actionSaveAsCopy = m_menuFile->addAction("Save &As...", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::SaveDocumentAsCopy, documentId); + const QString documentPath = GetDocumentPath(documentId); + + bool result = false; + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveDocumentAsCopy, + documentId, AtomToolsFramework::GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); + if (!result) + { + const QString status = QString("Document save failed: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); + } }, QKeySequence::SaveAs); m_actionSaveAll = m_menuFile->addAction("Save A&ll", [this]() { - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::SaveAllDocuments); + bool result = false; + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveAllDocuments); + if (!result) + { + const QString status = QString("Document save all failed."); + m_statusMessage->setText(QString("%1").arg(status)); + } + }); + + m_menuFile->addSeparator(); + + m_actionClose = m_menuFile->addAction("&Close", [this]() { + const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); + }, QKeySequence::Close); + + m_actionCloseAll = m_menuFile->addAction("Close All", [this]() { + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseAllDocuments); + }); + + m_actionCloseOthers = m_menuFile->addAction("Close Others", [this]() { + const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseAllDocumentsExcept, documentId); }); m_menuFile->addSeparator(); @@ -274,11 +297,11 @@ namespace ShaderManagementConsole m_actionUndo = m_menuEdit->addAction("&Undo", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); bool result = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(result, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::Undo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::Undo); if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to perform undo on document: %1").arg(documentPath); + const QString status = QString("Document undo failed: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Undo); @@ -286,30 +309,27 @@ namespace ShaderManagementConsole m_actionRedo = m_menuEdit->addAction("&Redo", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); bool result = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(result, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::Redo); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::Redo); if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to perform redo on document: %1").arg(documentPath); + const QString status = QString("Document redo failed: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Redo); m_menuEdit->addSeparator(); - m_actionSettings = m_menuEdit->addAction("&Preferences...", [this]() { + m_actionSettings = m_menuEdit->addAction("&Settings...", [this]() { }, QKeySequence::Preferences); m_actionSettings->setEnabled(false); m_menuView = m_menuBar->addMenu("&View"); - m_actionAssetBrowser = m_menuView->addAction( - "&Asset Browser", - [this]() - { - const AZStd::string label = "Asset Browser"; - SetDockWidgetVisible(label, !IsDockWidgetVisible(label)); - }); + m_actionAssetBrowser = m_menuView->addAction("&Asset Browser", [this]() { + const AZStd::string label = "Asset Browser"; + SetDockWidgetVisible(label, !IsDockWidgetVisible(label)); + }); m_actionPythonTerminal = m_menuView->addAction("Python &Terminal", [this]() { const AZStd::string label = "Python Terminal"; @@ -344,18 +364,20 @@ namespace ShaderManagementConsole // When the last tab is removed tabIndex will be -1 and the document ID will be null // This should automatically clear the active document connect(m_tabWidget, &QTabWidget::currentChanged, this, [this](int tabIndex) { - SelectDocumentForTab(tabIndex); + const AZ::Uuid documentId = GetDocumentIdFromTab(tabIndex); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); }); connect(m_tabWidget, &QTabWidget::tabCloseRequested, this, [this](int tabIndex) { - CloseDocumentForTab(tabIndex); + const AZ::Uuid documentId = GetDocumentIdFromTab(tabIndex); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); }); } QString ShaderManagementConsoleWindow::GetDocumentPath(const AZ::Uuid& documentId) const { AZStd::string absolutePath; - ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Handler::GetAbsolutePath); + AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(absolutePath, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Handler::GetAbsolutePath); return absolutePath.c_str(); } @@ -370,51 +392,22 @@ namespace ShaderManagementConsole QMenu tabMenu; const QString selectActionName = (currentTabIndex == clickedTabIndex) ? "Select in Browser" : "Select"; tabMenu.addAction(selectActionName, [this, clickedTabIndex]() { - SelectDocumentForTab(clickedTabIndex); + const AZ::Uuid documentId = GetDocumentIdFromTab(clickedTabIndex); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); }); tabMenu.addAction("Close", [this, clickedTabIndex]() { - CloseDocumentForTab(clickedTabIndex); + const AZ::Uuid documentId = GetDocumentIdFromTab(clickedTabIndex); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); }); auto closeOthersAction = tabMenu.addAction("Close Others", [this, clickedTabIndex]() { - CloseAllExceptDocumentForTab(clickedTabIndex); + const AZ::Uuid documentId = GetDocumentIdFromTab(clickedTabIndex); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CloseAllDocumentsExcept, documentId); }); closeOthersAction->setEnabled(tabBar->count() > 1); tabMenu.exec(QCursor::pos()); } } - void ShaderManagementConsoleWindow::SelectDocumentForTab(const int tabIndex) - { - const AZ::Uuid documentId = GetDocumentIdFromTab(tabIndex); - ShaderManagementConsoleDocumentNotificationBus::Broadcast(&ShaderManagementConsoleDocumentNotificationBus::Events::OnDocumentOpened, documentId); - } - - void ShaderManagementConsoleWindow::CloseDocumentForTab(const int tabIndex) - { - const AZ::Uuid documentId = GetDocumentIdFromTab(tabIndex); - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::CloseDocument, documentId); - } - - void ShaderManagementConsoleWindow::CloseAllExceptDocumentForTab(const int tabIndex) - { - AZStd::vector documentIdsToClose; - documentIdsToClose.reserve(m_tabWidget->count()); - const AZ::Uuid documentIdToKeepOpen = GetDocumentIdFromTab(tabIndex); - for (int tabI = 0; tabI < m_tabWidget->count(); ++tabI) - { - const AZ::Uuid documentId = GetDocumentIdFromTab(tabI); - if (documentId != documentIdToKeepOpen) - { - documentIdsToClose.push_back(documentId); - } - } - - for (const AZ::Uuid& documentId : documentIdsToClose) - { - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::CloseDocument, documentId); - } - } - QStandardItemModel* ShaderManagementConsoleWindow::CreateDocumentContent(const AZ::Uuid& documentId) { AZStd::unordered_set optionNames; diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h index 37efcb1b45..2b682f6c09 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h @@ -9,9 +9,9 @@ #pragma once #if !defined(Q_MOC_RUN) -#include #include #include +#include #include #include @@ -31,7 +31,7 @@ namespace ShaderManagementConsole */ class ShaderManagementConsoleWindow : public AtomToolsFramework::AtomToolsMainWindow - , private ShaderManagementConsoleDocumentNotificationBus::Handler + , private AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler { Q_OBJECT public: @@ -43,7 +43,7 @@ namespace ShaderManagementConsole ~ShaderManagementConsoleWindow(); private: - // ShaderManagementConsoleDocumentNotificationBus::Handler overrides... + // AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler overrides... void OnDocumentOpened(const AZ::Uuid& documentId) override; void OnDocumentClosed(const AZ::Uuid& documentId) override; void OnDocumentModified(const AZ::Uuid& documentId) override; @@ -57,10 +57,6 @@ namespace ShaderManagementConsole void OpenTabContextMenu() override; - void SelectDocumentForTab(const int tabIndex); - void CloseDocumentForTab(const int tabIndex); - void CloseAllExceptDocumentForTab(const int tabIndex); - void closeEvent(QCloseEvent* closeEvent) override; QStandardItemModel* CreateDocumentContent(const AZ::Uuid& documentId); diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp index a89cdfddb8..a59712d572 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp @@ -6,25 +6,20 @@ * */ -#include - -#include -#include -#include - #include - -#include -#include +#include +#include +#include +#include +#include #include - +#include +#include #include #include #include - -#include -#include -#include +#include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsole_files.cmake b/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsole_files.cmake index 6442df4832..e832ba2784 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsole_files.cmake +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsole_files.cmake @@ -10,7 +10,5 @@ set(FILES Source/main.cpp Source/ShaderManagementConsoleApplication.cpp Source/ShaderManagementConsoleApplication.h - Include/Atom/Document/ShaderManagementConsoleDocumentModule.h - Source/Document/ShaderManagementConsoleDocumentModule.cpp ../Scripts/GenerateShaderVariantListForMaterials.py ) diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsoledocument_files.cmake b/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsoledocument_files.cmake index e703f5efcc..220d2895ac 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsoledocument_files.cmake +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsoledocument_files.cmake @@ -7,11 +7,11 @@ # set(FILES - Include/Atom/Document/ShaderManagementConsoleDocumentSystemRequestBus.h - Include/Atom/Document/ShaderManagementConsoleDocumentNotificationBus.h + Include/Atom/Document/ShaderManagementConsoleDocumentModule.h Include/Atom/Document/ShaderManagementConsoleDocumentRequestBus.h - Source/Document/ShaderManagementConsoleDocumentSystemComponent.cpp - Source/Document/ShaderManagementConsoleDocumentSystemComponent.h Source/Document/ShaderManagementConsoleDocument.cpp Source/Document/ShaderManagementConsoleDocument.h + Source/Document/ShaderManagementConsoleDocumentModule.cpp + Source/Document/ShaderManagementConsoleDocumentSystemComponent.cpp + Source/Document/ShaderManagementConsoleDocumentSystemComponent.h ) diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Scripts/GenerateShaderVariantListForMaterials.py b/Gems/Atom/Tools/ShaderManagementConsole/Scripts/GenerateShaderVariantListForMaterials.py index 6c5e8df3dd..7bd65568ed 100755 --- a/Gems/Atom/Tools/ShaderManagementConsole/Scripts/GenerateShaderVariantListForMaterials.py +++ b/Gems/Atom/Tools/ShaderManagementConsole/Scripts/GenerateShaderVariantListForMaterials.py @@ -153,7 +153,7 @@ def main(): azlmbr.shader.SaveShaderVariantListSourceData(shaderVariantListFilePath, shaderVariantList) # Open the document in shader management console - result = azlmbr.shadermanagementconsole.ShaderManagementConsoleDocumentSystemRequestBus( + result = azlmbr.atomtools.AtomToolsDocumentSystemRequestBus( azlmbr.bus.Broadcast, 'OpenDocument', shaderVariantListFilePath diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h index 75b7ec9fdd..bdaf38a64a 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include @@ -102,6 +103,12 @@ namespace AZ //! Draws the statistical view of the CPU profiling data. void DrawStatisticsView(); + //! Callback invoked when the "Load File" button is pressed in the file picker. + void LoadFile(); + + //! Draws the file picker window. + void DrawFilePicker(); + //! Draws the CPU profiling visualizer. void DrawVisualizer(); @@ -198,6 +205,14 @@ namespace AZ AZ::RHI::CpuTimingStatistics m_cpuTimingStatisticsWhenPause; AZStd::string m_lastCapturedFilePath; + + bool m_showFilePicker = false; + + // Cached file paths to previous traces on disk, sorted with the most recent trace at the front. + AZStd::vector m_cachedCapturePaths; + + // Index into the file picker, used to determine which file to load when "Load File" is pressed. + int m_currentFileIndex = 0; }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl index 4e28658cc0..a225646761 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl @@ -9,9 +9,14 @@ #include #include #include +#include +#include #include -#include +#include +#include +#include +#include #include #include #include @@ -45,6 +50,74 @@ namespace AZ AZ_Assert(ticksPerSecond >= 1000, "Error in converting ticks to ms, expected ticksPerSecond >= 1000"); return static_cast((ticks * 1000) / (ticksPerSecond / 1000)) / 1000.0f; } + + using DeserializedCpuData = AZStd::vector; + inline Outcome LoadSavedCpuProfilingStatistics(const AZStd::string& capturePath) + { + auto* base = IO::FileIOBase::GetInstance(); + + char resolvedPath[IO::MaxPathLength]; + if (!base->ResolvePath(capturePath.c_str(), resolvedPath, IO::MaxPathLength)) + { + return Failure(AZStd::string::format("Could not resolve the path to file %s, is the path correct?", resolvedPath)); + } + + u64 captureSizeBytes; + const IO::Result fileSizeResult = base->Size(resolvedPath, captureSizeBytes); + if (!fileSizeResult) + { + return Failure(AZStd::string::format("Could not read the size of file %s, is the path correct?", resolvedPath)); + } + + // NOTE: this uses raw file pointers over the abstractions and utility functions provided by AZ::JsonSerializationUtils because + // saved profiling captures can be upwards of 400 MB. This necessitates a buffered approach to avoid allocating huge chunks of memory. + FILE* fp = nullptr; + azfopen(&fp, resolvedPath, "rb"); + if (!fp) + { + return Failure(AZStd::string::format("Could not fopen file %s, is the path correct?\n", resolvedPath)); + } + + constexpr AZStd::size_t MaxBufSize = 65536; + const AZStd::size_t bufSize = AZStd::min(MaxBufSize, aznumeric_cast(captureSizeBytes)); + char* buf = reinterpret_cast(azmalloc(bufSize)); + + rapidjson::Document document; + rapidjson::FileReadStream inputStream(fp, buf, bufSize); + document.ParseStream(inputStream); + + azfree(buf); + fclose(fp); + + if (document.HasParseError()) + { + const auto pe = document.GetParseError(); + return Failure(AZStd::string::format( + "Rapidjson could not parse the document with ParseErrorCode %u. See 3rdParty/rapidjson/error.h for definitions.\n", pe)); + } + + if (!document.IsObject() || !document.HasMember("ClassData")) + { + return Failure(AZStd::string::format( + "Error in loading saved capture: top-level object does not have a ClassData field. Did the serialization format change recently?\n")); + } + + AZ_TracePrintf("JsonUtils", "Successfully loaded JSON into memory.\n"); + + const auto& root = document["ClassData"]; + RHI::CpuProfilingStatisticsSerializer serializer; + const JsonSerializationResult::ResultCode deserializationResult = JsonSerialization::Load(serializer, root); + if (deserializationResult.GetProcessing() == JsonSerializationResult::Processing::Halted + || serializer.m_cpuProfilingStatisticsSerializerEntries.empty()) + { + return Failure(AZStd::string::format("Error in deserializing document: %s\n", deserializationResult.ToString(capturePath.c_str()).c_str())); + } + + AZ_TracePrintf("JsonUtils", "Successfully loaded CPU profiling data with %zu profiling entries.\n", + serializer.m_cpuProfilingStatisticsSerializerEntries.size()); + + return Success(AZStd::move(serializer.m_cpuProfilingStatisticsSerializerEntries)); + } } // namespace CpuProfilerImGuiHelper inline void ImGuiCpuProfiler::Draw(bool& keepDrawing, const AZ::RHI::CpuTimingStatistics& currentCpuTimingStatistics) @@ -80,6 +153,11 @@ namespace AZ { DrawStatisticsView(); } + + if (m_showFilePicker) + { + DrawFilePicker(); + } } ImGui::End(); @@ -110,6 +188,11 @@ namespace AZ inline void ImGuiCpuProfiler::DrawCommonHeader() { + if (!m_lastCapturedFilePath.empty()) + { + ImGui::Text("Saved: %s", m_lastCapturedFilePath.c_str()); + } + if (ImGui::Button(m_enableVisualizer ? "Swap to statistics" : "Swap to visualizer")) { m_enableVisualizer = !m_enableVisualizer; @@ -157,10 +240,31 @@ namespace AZ } } - if (!m_lastCapturedFilePath.empty()) + ImGui::SameLine(); + if (ImGui::Button("Load file")) { - ImGui::SameLine(); - ImGui::Text("Saved: %s", m_lastCapturedFilePath.c_str()); + m_showFilePicker = true; + + // Only update the cached file list when opened so that we aren't making IO calls on every frame. + auto* base = AZ::IO::FileIOBase::GetInstance(); + const AZStd::string defaultSavedCapturePath = "@user@/CpuProfiler"; + + m_cachedCapturePaths.clear(); + base->FindFiles( + defaultSavedCapturePath.c_str(), "*.json", + [&paths = m_cachedCapturePaths](const char* path) -> bool + { + auto foundPath = IO::Path(path); + paths.push_back(foundPath); + return true; + }); + + // Sort by decreasing modification time (most recent at the top) + AZStd::sort(m_cachedCapturePaths.begin(), m_cachedCapturePaths.end(), + [&base](const IO::Path& lhs, const IO::Path& rhs) + { + return base->ModificationTime(lhs.c_str()) > base->ModificationTime(rhs.c_str()); + }); } } @@ -313,6 +417,45 @@ namespace AZ } } + inline void ImGuiCpuProfiler::DrawFilePicker() + { + ImGui::SetNextWindowSize({ 500, 200 }, ImGuiCond_Once); + if (ImGui::Begin("File Picker", &m_showFilePicker)) + { + if (ImGui::Button("Load selected")) + { + LoadFile(); + } + + auto getter = [](void* vectorPointer, int idx, const char** out_text) -> bool + { + const auto& pathVec = *static_cast*>(vectorPointer); + if (idx < 0 || idx >= pathVec.size()) + { + return false; + } + *out_text = pathVec[idx].c_str(); + return true; + }; + + ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth()); + ImGui::ListBox("", &m_currentFileIndex, getter, &m_cachedCapturePaths, aznumeric_cast(m_cachedCapturePaths.size())); + } + ImGui::End(); + } + + inline void ImGuiCpuProfiler::LoadFile() + { + const IO::Path& pathToLoad = m_cachedCapturePaths[m_currentFileIndex]; + auto res = CpuProfilerImGuiHelper::LoadSavedCpuProfilingStatistics(pathToLoad.String()); + if (!res.IsSuccess()) + { + AZ_TracePrintf("ImGuiCpuProfiler", "%s", res.GetError().c_str()); + return; + } + // TODO ATOM-16022 Parse this data and display it in the visualizer widget. + } + // -- CPU Visualizer -- inline void ImGuiCpuProfiler::DrawVisualizer() { diff --git a/Gems/LyShine/Code/Source/UiCanvasFileObject.h b/Gems/LyShine/Code/Source/UiCanvasFileObject.h index 4cfec60bea..167405355b 100644 --- a/Gems/LyShine/Code/Source/UiCanvasFileObject.h +++ b/Gems/LyShine/Code/Source/UiCanvasFileObject.h @@ -24,7 +24,8 @@ public: AZ_CLASS_ALLOCATOR(UiCanvasFileObject, AZ::SystemAllocator, 0); AZ_RTTI(UiCanvasFileObject, "{1F02632F-F113-49B1-85AD-8CD0FA78B8AA}"); - static UiCanvasFileObject* LoadCanvasFromStream(AZ::IO::GenericStream& stream, const AZ::ObjectStream::FilterDescriptor& filterDesc = AZ::ObjectStream::FilterDescriptor(AZ::ObjectStream::AssetFilterAssetTypesOnly)); + // Load canvas from stream with an optional asset filter. No asset references are ignored by default + static UiCanvasFileObject* LoadCanvasFromStream(AZ::IO::GenericStream& stream, const AZ::ObjectStream::FilterDescriptor& filterDesc = AZ::ObjectStream::FilterDescriptor()); static void SaveCanvasToStream(AZ::IO::GenericStream& stream, UiCanvasFileObject* canvasFileObject); static AZ::Entity* LoadCanvasEntitiesFromStream(AZ::IO::GenericStream& stream, AZ::Entity*& rootSliceEntity); diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index d3f1c63974..2445aba9bd 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -88,7 +88,7 @@ namespace PhysX ->EnumAttribute(Physics::ShapeType::Box, "Box") ->EnumAttribute(Physics::ShapeType::Capsule, "Capsule") ->EnumAttribute(Physics::ShapeType::PhysicsAsset, "PhysicsAsset") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorProxyShapeConfig::OnShapeTypeChanged) // note: we do not want the user to be able to change shape types while in ComponentMode (there will // potentially be different ComponentModes for different shape types) ->Attribute(AZ::Edit::Attributes::ReadOnly, &AzToolsFramework::ComponentModeFramework::InComponentMode) @@ -116,6 +116,19 @@ namespace PhysX } } + AZ::u32 EditorProxyShapeConfig::OnShapeTypeChanged() + { + //reset the physics asset if the shape type was Physics Asset + if (m_shapeType != Physics::ShapeType::PhysicsAsset && + m_lastShapeType == Physics::ShapeType::PhysicsAsset) + { + m_physicsAsset.m_pxAsset.Reset(); + m_physicsAsset.m_configuration = Physics::PhysicsAssetShapeConfiguration(); + } + m_lastShapeType = m_shapeType; + return AZ::Edit::PropertyRefreshLevels::EntireTree; + } + AZ::u32 EditorProxyShapeConfig::OnConfigurationChanged() { return AZ::Edit::PropertyRefreshLevels::ValuesOnly; diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.h b/Gems/PhysX/Code/Source/EditorColliderComponent.h index 8a78cc1cb8..50cf9d0c8b 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.h +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.h @@ -58,8 +58,8 @@ namespace PhysX //! Proxy container for only displaying a specific shape configuration depending on the shapeType selected. struct EditorProxyShapeConfig { - AZ_CLASS_ALLOCATOR(EditorProxyShapeConfig, AZ::SystemAllocator, 0); - AZ_RTTI(EditorProxyShapeConfig, "{531FB42A-42A9-4234-89BA-FD349EF83D0C}"); + AZ_CLASS_ALLOCATOR(PhysX::EditorProxyShapeConfig, AZ::SystemAllocator, 0); + AZ_RTTI(PhysX::EditorProxyShapeConfig, "{531FB42A-42A9-4234-89BA-FD349EF83D0C}"); static void Reflect(AZ::ReflectContext* context); EditorProxyShapeConfig() = default; @@ -84,9 +84,12 @@ namespace PhysX AZStd::shared_ptr CloneCurrent() const; + private: bool ShowingSubdivisionLevel() const; - + AZ::u32 OnShapeTypeChanged(); AZ::u32 OnConfigurationChanged(); + + Physics::ShapeType m_lastShapeType = Physics::ShapeType::PhysicsAsset; }; class EditorColliderComponentDescriptor; diff --git a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneSerializationHandler.cpp b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneSerializationHandler.cpp index feab5863e6..0e3f86471c 100644 --- a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneSerializationHandler.cpp +++ b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneSerializationHandler.cpp @@ -19,6 +19,7 @@ #include #include #include +#include namespace SceneBuilder { @@ -79,8 +80,9 @@ namespace SceneBuilder return nullptr; } - AZStd::shared_ptr scene = - AssetImportRequest::LoadSceneFromVerifiedPath(filePath, sceneSourceGuid, AssetImportRequest::RequestingApplication::AssetProcessor); + AZStd::shared_ptr scene = AssetImportRequest::LoadSceneFromVerifiedPath( + filePath, sceneSourceGuid, AssetImportRequest::RequestingApplication::AssetProcessor, + AZ::SceneAPI::SceneCore::LoadingComponent::TYPEINFO_Uuid()); if (!scene) { diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index e4398099d1..1a8e805f91 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -6,7 +6,7 @@ # # -set(LY_UNITY_BUILD OFF CACHE BOOL "UNITY builds") +set(LY_UNITY_BUILD ON CACHE BOOL "UNITY builds") include(CMakeFindDependencyMacro) include(cmake/LyAutoGen.cmake)